@agegr/pi-web 0.2.1

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 (272) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/package.json +1 -0
  3. package/.next/server/app/_global-error/page/app-paths-manifest.json +3 -0
  4. package/.next/server/app/_global-error/page/build-manifest.json +17 -0
  5. package/.next/server/app/_global-error/page/next-font-manifest.json +6 -0
  6. package/.next/server/app/_global-error/page/react-loadable-manifest.json +1 -0
  7. package/.next/server/app/_global-error/page/server-reference-manifest.json +4 -0
  8. package/.next/server/app/_global-error/page.js +10 -0
  9. package/.next/server/app/_global-error/page.js.map +5 -0
  10. package/.next/server/app/_global-error/page.js.nft.json +1 -0
  11. package/.next/server/app/_global-error/page_client-reference-manifest.js +3 -0
  12. package/.next/server/app/_global-error.html +1 -0
  13. package/.next/server/app/_global-error.meta +15 -0
  14. package/.next/server/app/_global-error.rsc +15 -0
  15. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +5 -0
  16. package/.next/server/app/_global-error.segments/_full.segment.rsc +15 -0
  17. package/.next/server/app/_global-error.segments/_head.segment.rsc +6 -0
  18. package/.next/server/app/_global-error.segments/_index.segment.rsc +5 -0
  19. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -0
  20. package/.next/server/app/_not-found/page/app-paths-manifest.json +3 -0
  21. package/.next/server/app/_not-found/page/build-manifest.json +17 -0
  22. package/.next/server/app/_not-found/page/next-font-manifest.json +6 -0
  23. package/.next/server/app/_not-found/page/react-loadable-manifest.json +1 -0
  24. package/.next/server/app/_not-found/page/server-reference-manifest.json +4 -0
  25. package/.next/server/app/_not-found/page.js +13 -0
  26. package/.next/server/app/_not-found/page.js.map +5 -0
  27. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  28. package/.next/server/app/_not-found/page_client-reference-manifest.js +3 -0
  29. package/.next/server/app/_not-found.html +1 -0
  30. package/.next/server/app/_not-found.meta +16 -0
  31. package/.next/server/app/_not-found.rsc +16 -0
  32. package/.next/server/app/_not-found.segments/_full.segment.rsc +16 -0
  33. package/.next/server/app/_not-found.segments/_head.segment.rsc +6 -0
  34. package/.next/server/app/_not-found.segments/_index.segment.rsc +5 -0
  35. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +5 -0
  36. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +5 -0
  37. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -0
  38. package/.next/server/app/api/agent/[id]/events/route/app-paths-manifest.json +3 -0
  39. package/.next/server/app/api/agent/[id]/events/route/build-manifest.json +9 -0
  40. package/.next/server/app/api/agent/[id]/events/route/server-reference-manifest.json +4 -0
  41. package/.next/server/app/api/agent/[id]/events/route.js +6 -0
  42. package/.next/server/app/api/agent/[id]/events/route.js.map +5 -0
  43. package/.next/server/app/api/agent/[id]/events/route.js.nft.json +1 -0
  44. package/.next/server/app/api/agent/[id]/events/route_client-reference-manifest.js +3 -0
  45. package/.next/server/app/api/agent/[id]/route/app-paths-manifest.json +3 -0
  46. package/.next/server/app/api/agent/[id]/route/build-manifest.json +9 -0
  47. package/.next/server/app/api/agent/[id]/route/server-reference-manifest.json +4 -0
  48. package/.next/server/app/api/agent/[id]/route.js +7 -0
  49. package/.next/server/app/api/agent/[id]/route.js.map +5 -0
  50. package/.next/server/app/api/agent/[id]/route.js.nft.json +1 -0
  51. package/.next/server/app/api/agent/[id]/route_client-reference-manifest.js +3 -0
  52. package/.next/server/app/api/agent/new/route/app-paths-manifest.json +3 -0
  53. package/.next/server/app/api/agent/new/route/build-manifest.json +9 -0
  54. package/.next/server/app/api/agent/new/route/server-reference-manifest.json +4 -0
  55. package/.next/server/app/api/agent/new/route.js +7 -0
  56. package/.next/server/app/api/agent/new/route.js.map +5 -0
  57. package/.next/server/app/api/agent/new/route.js.nft.json +1 -0
  58. package/.next/server/app/api/agent/new/route_client-reference-manifest.js +3 -0
  59. package/.next/server/app/api/files/[...path]/route/app-paths-manifest.json +3 -0
  60. package/.next/server/app/api/files/[...path]/route/build-manifest.json +9 -0
  61. package/.next/server/app/api/files/[...path]/route/server-reference-manifest.json +4 -0
  62. package/.next/server/app/api/files/[...path]/route.js +7 -0
  63. package/.next/server/app/api/files/[...path]/route.js.map +5 -0
  64. package/.next/server/app/api/files/[...path]/route.js.nft.json +1 -0
  65. package/.next/server/app/api/files/[...path]/route_client-reference-manifest.js +3 -0
  66. package/.next/server/app/api/models/route/app-paths-manifest.json +3 -0
  67. package/.next/server/app/api/models/route/build-manifest.json +9 -0
  68. package/.next/server/app/api/models/route/server-reference-manifest.json +4 -0
  69. package/.next/server/app/api/models/route.js +6 -0
  70. package/.next/server/app/api/models/route.js.map +5 -0
  71. package/.next/server/app/api/models/route.js.nft.json +1 -0
  72. package/.next/server/app/api/models/route_client-reference-manifest.js +3 -0
  73. package/.next/server/app/api/models-config/route/app-paths-manifest.json +3 -0
  74. package/.next/server/app/api/models-config/route/build-manifest.json +9 -0
  75. package/.next/server/app/api/models-config/route/server-reference-manifest.json +4 -0
  76. package/.next/server/app/api/models-config/route.js +7 -0
  77. package/.next/server/app/api/models-config/route.js.map +5 -0
  78. package/.next/server/app/api/models-config/route.js.nft.json +1 -0
  79. package/.next/server/app/api/models-config/route_client-reference-manifest.js +3 -0
  80. package/.next/server/app/api/sessions/[id]/context/route/app-paths-manifest.json +3 -0
  81. package/.next/server/app/api/sessions/[id]/context/route/build-manifest.json +9 -0
  82. package/.next/server/app/api/sessions/[id]/context/route/server-reference-manifest.json +4 -0
  83. package/.next/server/app/api/sessions/[id]/context/route.js +7 -0
  84. package/.next/server/app/api/sessions/[id]/context/route.js.map +5 -0
  85. package/.next/server/app/api/sessions/[id]/context/route.js.nft.json +1 -0
  86. package/.next/server/app/api/sessions/[id]/context/route_client-reference-manifest.js +3 -0
  87. package/.next/server/app/api/sessions/[id]/route/app-paths-manifest.json +3 -0
  88. package/.next/server/app/api/sessions/[id]/route/build-manifest.json +9 -0
  89. package/.next/server/app/api/sessions/[id]/route/server-reference-manifest.json +4 -0
  90. package/.next/server/app/api/sessions/[id]/route.js +7 -0
  91. package/.next/server/app/api/sessions/[id]/route.js.map +5 -0
  92. package/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -0
  93. package/.next/server/app/api/sessions/[id]/route_client-reference-manifest.js +3 -0
  94. package/.next/server/app/api/sessions/new/route/app-paths-manifest.json +3 -0
  95. package/.next/server/app/api/sessions/new/route/build-manifest.json +9 -0
  96. package/.next/server/app/api/sessions/new/route/server-reference-manifest.json +4 -0
  97. package/.next/server/app/api/sessions/new/route.js +6 -0
  98. package/.next/server/app/api/sessions/new/route.js.map +5 -0
  99. package/.next/server/app/api/sessions/new/route.js.nft.json +1 -0
  100. package/.next/server/app/api/sessions/new/route_client-reference-manifest.js +3 -0
  101. package/.next/server/app/api/sessions/route/app-paths-manifest.json +3 -0
  102. package/.next/server/app/api/sessions/route/build-manifest.json +9 -0
  103. package/.next/server/app/api/sessions/route/server-reference-manifest.json +4 -0
  104. package/.next/server/app/api/sessions/route.js +7 -0
  105. package/.next/server/app/api/sessions/route.js.map +5 -0
  106. package/.next/server/app/api/sessions/route.js.nft.json +1 -0
  107. package/.next/server/app/api/sessions/route_client-reference-manifest.js +3 -0
  108. package/.next/server/app/favicon.ico/route/app-paths-manifest.json +3 -0
  109. package/.next/server/app/favicon.ico/route/build-manifest.json +9 -0
  110. package/.next/server/app/favicon.ico/route.js +8 -0
  111. package/.next/server/app/favicon.ico/route.js.map +5 -0
  112. package/.next/server/app/favicon.ico/route.js.nft.json +1 -0
  113. package/.next/server/app/favicon.ico.body +0 -0
  114. package/.next/server/app/favicon.ico.meta +1 -0
  115. package/.next/server/app/index.html +1 -0
  116. package/.next/server/app/index.meta +14 -0
  117. package/.next/server/app/index.rsc +15 -0
  118. package/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -0
  119. package/.next/server/app/index.segments/_full.segment.rsc +15 -0
  120. package/.next/server/app/index.segments/_head.segment.rsc +6 -0
  121. package/.next/server/app/index.segments/_index.segment.rsc +5 -0
  122. package/.next/server/app/index.segments/_tree.segment.rsc +2 -0
  123. package/.next/server/app/page/app-paths-manifest.json +3 -0
  124. package/.next/server/app/page/build-manifest.json +17 -0
  125. package/.next/server/app/page/next-font-manifest.json +6 -0
  126. package/.next/server/app/page/react-loadable-manifest.json +1 -0
  127. package/.next/server/app/page/server-reference-manifest.json +4 -0
  128. package/.next/server/app/page.js +14 -0
  129. package/.next/server/app/page.js.map +5 -0
  130. package/.next/server/app/page.js.nft.json +1 -0
  131. package/.next/server/app/page_client-reference-manifest.js +3 -0
  132. package/.next/server/app-paths-manifest.json +16 -0
  133. package/.next/server/chunks/[externals]_next_dist_0h.fyd6._.js +3 -0
  134. package/.next/server/chunks/[externals]_next_dist_0h.fyd6._.js.map +1 -0
  135. package/.next/server/chunks/[root-of-the-server]__002d92q._.js +6 -0
  136. package/.next/server/chunks/[root-of-the-server]__002d92q._.js.map +1 -0
  137. package/.next/server/chunks/[root-of-the-server]__00a-~o4._.js +3 -0
  138. package/.next/server/chunks/[root-of-the-server]__00a-~o4._.js.map +1 -0
  139. package/.next/server/chunks/[root-of-the-server]__06qx74m._.js +5 -0
  140. package/.next/server/chunks/[root-of-the-server]__06qx74m._.js.map +1 -0
  141. package/.next/server/chunks/[root-of-the-server]__0_ehal9._.js +5 -0
  142. package/.next/server/chunks/[root-of-the-server]__0_ehal9._.js.map +1 -0
  143. package/.next/server/chunks/[root-of-the-server]__0a-p9wd._.js +3 -0
  144. package/.next/server/chunks/[root-of-the-server]__0a-p9wd._.js.map +1 -0
  145. package/.next/server/chunks/[root-of-the-server]__0b0kii6._.js +8 -0
  146. package/.next/server/chunks/[root-of-the-server]__0b0kii6._.js.map +1 -0
  147. package/.next/server/chunks/[root-of-the-server]__0cw6f~v._.js +5 -0
  148. package/.next/server/chunks/[root-of-the-server]__0cw6f~v._.js.map +1 -0
  149. package/.next/server/chunks/[root-of-the-server]__0llo_uy._.js +5 -0
  150. package/.next/server/chunks/[root-of-the-server]__0llo_uy._.js.map +1 -0
  151. package/.next/server/chunks/[root-of-the-server]__0rr3q~-._.js +5 -0
  152. package/.next/server/chunks/[root-of-the-server]__0rr3q~-._.js.map +1 -0
  153. package/.next/server/chunks/[root-of-the-server]__0y7g-4j._.js +4 -0
  154. package/.next/server/chunks/[root-of-the-server]__0y7g-4j._.js.map +1 -0
  155. package/.next/server/chunks/[root-of-the-server]__11j~5mn._.js +3 -0
  156. package/.next/server/chunks/[root-of-the-server]__11j~5mn._.js.map +1 -0
  157. package/.next/server/chunks/[turbopack]_runtime.js +903 -0
  158. package/.next/server/chunks/[turbopack]_runtime.js.map +11 -0
  159. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_events_route_actions_05o7blz.js +3 -0
  160. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_events_route_actions_05o7blz.js.map +1 -0
  161. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_route_actions_0kr98j0.js +3 -0
  162. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_route_actions_0kr98j0.js.map +1 -0
  163. package/.next/server/chunks/_next-internal_server_app_api_agent_new_route_actions_0w3r5tj.js +3 -0
  164. package/.next/server/chunks/_next-internal_server_app_api_agent_new_route_actions_0w3r5tj.js.map +1 -0
  165. package/.next/server/chunks/_next-internal_server_app_api_files_[___path]_route_actions_0_g4akf.js +3 -0
  166. package/.next/server/chunks/_next-internal_server_app_api_files_[___path]_route_actions_0_g4akf.js.map +1 -0
  167. package/.next/server/chunks/_next-internal_server_app_api_models-config_route_actions_0ipr5cq.js +3 -0
  168. package/.next/server/chunks/_next-internal_server_app_api_models-config_route_actions_0ipr5cq.js.map +1 -0
  169. package/.next/server/chunks/_next-internal_server_app_api_models_route_actions_0vfccm4.js +3 -0
  170. package/.next/server/chunks/_next-internal_server_app_api_models_route_actions_0vfccm4.js.map +1 -0
  171. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_context_route_actions_0d0pnzf.js +3 -0
  172. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_context_route_actions_0d0pnzf.js.map +1 -0
  173. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_route_actions_0eo4u5w.js +3 -0
  174. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_route_actions_0eo4u5w.js.map +1 -0
  175. package/.next/server/chunks/_next-internal_server_app_api_sessions_new_route_actions_093p~n-.js +3 -0
  176. package/.next/server/chunks/_next-internal_server_app_api_sessions_new_route_actions_093p~n-.js.map +1 -0
  177. package/.next/server/chunks/_next-internal_server_app_api_sessions_route_actions_0y1t9w0.js +3 -0
  178. package/.next/server/chunks/_next-internal_server_app_api_sessions_route_actions_0y1t9w0.js.map +1 -0
  179. package/.next/server/chunks/_next-internal_server_app_favicon_ico_route_actions_095lj93.js +3 -0
  180. package/.next/server/chunks/_next-internal_server_app_favicon_ico_route_actions_095lj93.js.map +1 -0
  181. package/.next/server/chunks/lib_session-reader_ts_07kvkqq._.js +5 -0
  182. package/.next/server/chunks/lib_session-reader_ts_07kvkqq._.js.map +1 -0
  183. package/.next/server/chunks/node_modules_next_04~_e52._.js +13 -0
  184. package/.next/server/chunks/node_modules_next_04~_e52._.js.map +1 -0
  185. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0yubv2d.js +3 -0
  186. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0yubv2d.js.map +1 -0
  187. package/.next/server/chunks/ssr/[root-of-the-server]__00d4x5d._.js +3 -0
  188. package/.next/server/chunks/ssr/[root-of-the-server]__00d4x5d._.js.map +1 -0
  189. package/.next/server/chunks/ssr/[root-of-the-server]__02hi65f._.js +3 -0
  190. package/.next/server/chunks/ssr/[root-of-the-server]__02hi65f._.js.map +1 -0
  191. package/.next/server/chunks/ssr/[root-of-the-server]__06-2p1a._.js +33 -0
  192. package/.next/server/chunks/ssr/[root-of-the-server]__06-2p1a._.js.map +1 -0
  193. package/.next/server/chunks/ssr/[root-of-the-server]__09z7o2x._.js +19 -0
  194. package/.next/server/chunks/ssr/[root-of-the-server]__09z7o2x._.js.map +1 -0
  195. package/.next/server/chunks/ssr/[root-of-the-server]__0jag6jd._.js +3 -0
  196. package/.next/server/chunks/ssr/[root-of-the-server]__0jag6jd._.js.map +1 -0
  197. package/.next/server/chunks/ssr/[root-of-the-server]__0pr3cat._.js +33 -0
  198. package/.next/server/chunks/ssr/[root-of-the-server]__0pr3cat._.js.map +1 -0
  199. package/.next/server/chunks/ssr/[root-of-the-server]__0pspq~2._.js +6 -0
  200. package/.next/server/chunks/ssr/[root-of-the-server]__0pspq~2._.js.map +1 -0
  201. package/.next/server/chunks/ssr/[root-of-the-server]__0w~zl.s._.js +3 -0
  202. package/.next/server/chunks/ssr/[root-of-the-server]__0w~zl.s._.js.map +1 -0
  203. package/.next/server/chunks/ssr/[turbopack]_runtime.js +903 -0
  204. package/.next/server/chunks/ssr/[turbopack]_runtime.js.map +11 -0
  205. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0k77kol.js +3 -0
  206. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0k77kol.js.map +1 -0
  207. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0eq97pa.js +3 -0
  208. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0eq97pa.js.map +1 -0
  209. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_09-gtaw.js +3 -0
  210. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_09-gtaw.js.map +1 -0
  211. package/.next/server/chunks/ssr/app_layout_tsx_13yf0ls._.js +3 -0
  212. package/.next/server/chunks/ssr/app_layout_tsx_13yf0ls._.js.map +1 -0
  213. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0r3vloj._.js +3 -0
  214. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0r3vloj._.js.map +1 -0
  215. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0ybdq6k._.js +3 -0
  216. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0ybdq6k._.js.map +1 -0
  217. package/.next/server/chunks/ssr/node_modules_09w7yel._.js +33 -0
  218. package/.next/server/chunks/ssr/node_modules_09w7yel._.js.map +1 -0
  219. package/.next/server/chunks/ssr/node_modules_0vtdjw7._.js +3 -0
  220. package/.next/server/chunks/ssr/node_modules_0vtdjw7._.js.map +1 -0
  221. package/.next/server/chunks/ssr/node_modules_next_dist_09y1ibj._.js +6 -0
  222. package/.next/server/chunks/ssr/node_modules_next_dist_09y1ibj._.js.map +1 -0
  223. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0inhx6q._.js +3 -0
  224. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0inhx6q._.js.map +1 -0
  225. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0ghu-f7.js +3 -0
  226. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0ghu-f7.js.map +1 -0
  227. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0lgvd_..js +3 -0
  228. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0lgvd_..js.map +1 -0
  229. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0cjv-23.js +3 -0
  230. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0cjv-23.js.map +1 -0
  231. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_002l7yi.js +4 -0
  232. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_002l7yi.js.map +1 -0
  233. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_02suzhc.js +4 -0
  234. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_02suzhc.js.map +1 -0
  235. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0nsg22r.js +4 -0
  236. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0nsg22r.js.map +1 -0
  237. package/.next/server/functions-config-manifest.json +4 -0
  238. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  239. package/.next/server/middleware-build-manifest.js +21 -0
  240. package/.next/server/middleware-manifest.json +6 -0
  241. package/.next/server/next-font-manifest.js +1 -0
  242. package/.next/server/next-font-manifest.json +6 -0
  243. package/.next/server/pages/404.html +1 -0
  244. package/.next/server/pages/500.html +1 -0
  245. package/.next/server/pages-manifest.json +4 -0
  246. package/.next/server/prefetch-hints.json +1 -0
  247. package/.next/server/server-reference-manifest.js +1 -0
  248. package/.next/server/server-reference-manifest.json +5 -0
  249. package/.next/static/chunks/0-j.wjqnc6zff.js +1 -0
  250. package/.next/static/chunks/02i7dfk78~t~2.js +4 -0
  251. package/.next/static/chunks/02p06lvcsni3l.js +1 -0
  252. package/.next/static/chunks/03~yq9q893hmn.js +1 -0
  253. package/.next/static/chunks/09dho1gmydle0.js +1 -0
  254. package/.next/static/chunks/0_mdnxjv887c..css +1 -0
  255. package/.next/static/chunks/0cj37tl-sc0gx.js +2 -0
  256. package/.next/static/chunks/0h4bblvd1oiwg.js +1 -0
  257. package/.next/static/chunks/0j-yjan8jn-8-.js +31 -0
  258. package/.next/static/chunks/0lpjxrppxb_hc.js +1 -0
  259. package/.next/static/chunks/turbopack-04u~j1o-remaj.js +1 -0
  260. package/.next/static/h_DPSqE34dYtPmxavamVm/_buildManifest.js +11 -0
  261. package/.next/static/h_DPSqE34dYtPmxavamVm/_clientMiddlewareManifest.js +1 -0
  262. package/.next/static/h_DPSqE34dYtPmxavamVm/_ssgManifest.js +1 -0
  263. package/.next/static/media/favicon.0~uco8ba8mwit.ico +0 -0
  264. package/README.md +62 -0
  265. package/bin/pi-web.js +24 -0
  266. package/next.config.ts +8 -0
  267. package/package.json +43 -0
  268. package/public/file.svg +1 -0
  269. package/public/globe.svg +1 -0
  270. package/public/next.svg +1 -0
  271. package/public/vercel.svg +1 -0
  272. package/public/window.svg +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../node_modules/next/src/server/route-modules/app-page/vendored/ssr/react-dom.ts","../../../../node_modules/next/src/client/components/http-access-fallback/http-access-fallback.ts","../../../../node_modules/next/dist/esm/client/components/is-next-router-error.js","../../../../node_modules/next/dist/esm/client/components/redirect-status-code.js","../../../../node_modules/next/dist/esm/client/components/redirect-error.js","../../../../node_modules/next/src/shared/lib/invariant-error.ts","../../../../node_modules/next/src/shared/lib/promise-with-resolvers.ts","../../../../node_modules/next/src/lib/framework/boundary-constants.tsx","../../../../node_modules/next/dist/esm/client/components/static-generation-bailout.js","../../../../node_modules/next/dist/esm/server/app-render/staged-rendering.js","../../../../node_modules/next/dist/esm/shared/lib/lazy-dynamic/bailout-to-csr.js","../../../../node_modules/next/dist/esm/client/components/hooks-server-context.js","../../../../node_modules/next/dist/esm/server/app-render/dynamic-rendering.js","../../../../node_modules/next/dist/esm/server/app-render/instant-validation/boundary-constants.js","../../../../node_modules/next/dist/esm/server/dynamic-rendering-utils.js","../../../../node_modules/next/dist/esm/lib/scheduler.js","../../../../node_modules/next/dist/esm/server/lib/router-utils/is-postpone.js","../../../../node_modules/next/dist/esm/client/components/unstable-rethrow.server.js","../../../../node_modules/next/dist/esm/shared/lib/utils/warn-once.js","../../../../node_modules/next/dist/esm/client/components/http-access-fallback/error-boundary.js","../../../../node_modules/next/dist/esm/client/components/navigation-untracked.js","../../../../node_modules/next/src/client/components/app-router-headers.ts","../../../../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/route-params.js","../../../../node_modules/next/src/server/route-modules/app-page/vendored/ssr/react-server-dom-turbopack-client.ts","../../../../node_modules/next/src/client/components/use-action-queue.ts","../../../../node_modules/next/src/client/components/segment-cache/navigation-testing-lock.ts","../../../../node_modules/next/dist/esm/shared/lib/deployment-id.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/fetch-server-response.js","../../../../node_modules/next/dist/esm/client/components/error-boundary.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/disable-smooth-scroll.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/router-reducer/create-router-cache-key.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/client/components/handle-isr-error.js","../../../../node_modules/next/dist/esm/client/components/layout-router.js","../../../../node_modules/next/dist/esm/client/navigation-build-id.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/router-reducer-types.js","../../../../node_modules/next/dist/esm/client/components/match-segments.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/bfcache-state-manager.js","../../../../node_modules/next/dist/esm/client/components/redirect.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/is-bot.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/cache-map.js","../../../../node_modules/next/dist/esm/client/components/navigation.react-server.js","../../../../node_modules/next/dist/esm/client/app-call-server.js","../../../../node_modules/next/dist/esm/client/components/navigation.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/lru.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/vary-path.js","../../../../node_modules/next/dist/esm/client/components/nav-failure-handler.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/types.js","../../../../node_modules/next/dist/esm/client/components/unresolved-thenable.js","../../../../node_modules/next/dist/esm/client/components/links.js","../../../../node_modules/next/dist/esm/shared/lib/router/utils/html-bots.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/client/components/unstable-rethrow.js","../../../../node_modules/next/dist/esm/shared/lib/hash.js","../../../../node_modules/next/dist/esm/client/flight-data-helpers.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/scheduler.js","../../../../node_modules/next/dist/esm/shared/lib/segment-cache/vary-params-decoding.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/cache.js","../../../../node_modules/next/dist/esm/client/components/router-reducer/ppr-navigations.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/navigation.js","../../../../node_modules/next/dist/esm/client/components/segment-cache/optimistic-routes.js","../../../../node_modules/next/src/client/components/render-from-template-context.tsx","../../../../node_modules/next/dist/esm/server/create-deduped-by-callsite-server-error-logger.js","../../../../node_modules/next/dist/esm/server/app-render/vary-params.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/dist/compiled/%40edge-runtime/cookies/index.js","../../../../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/router/utils/querystring.js","../../../../node_modules/next/dist/esm/shared/lib/action-revalidation-kind.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/parse-relative-url.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/request/utils.js","../../../../node_modules/next/dist/esm/server/request/search-params.js","../../../../node_modules/next/src/server/request/params.ts","../../../../node_modules/next/src/client/components/client-page.tsx","../../../../node_modules/next/src/client/components/client-segment.tsx","../../../../node_modules/next/src/lib/framework/boundary-components.tsx","../../../../node_modules/next/src/lib/metadata/generate/icon-mark.tsx"],"sourcesContent":["module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactDOM\n","export const HTTPAccessErrorStatus = {\n NOT_FOUND: 404,\n FORBIDDEN: 403,\n UNAUTHORIZED: 401,\n}\n\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))\n\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'\n\nexport type HTTPAccessFallbackError = Error & {\n digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`\n}\n\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 */\nexport function isHTTPAccessFallbackError(\n error: unknown\n): error is HTTPAccessFallbackError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n const [prefix, httpStatus] = error.digest.split(';')\n\n return (\n prefix === HTTP_ERROR_FALLBACK_ERROR_CODE &&\n ALLOWED_CODES.has(Number(httpStatus))\n )\n}\n\nexport function getAccessFallbackHTTPStatus(\n error: HTTPAccessFallbackError\n): number {\n const httpStatus = error.digest.split(';')[1]\n return Number(httpStatus)\n}\n\nexport function getAccessFallbackErrorTypeByStatus(\n status: number\n): 'not-found' | 'forbidden' | 'unauthorized' | undefined {\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","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","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","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","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","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","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","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 RenderStage[RenderStage[\"EarlyStatic\"] = 2] = \"EarlyStatic\";\n RenderStage[RenderStage[\"Static\"] = 3] = \"Static\";\n RenderStage[RenderStage[\"EarlyRuntime\"] = 4] = \"EarlyRuntime\";\n RenderStage[RenderStage[\"Runtime\"] = 5] = \"Runtime\";\n RenderStage[RenderStage[\"Dynamic\"] = 6] = \"Dynamic\";\n RenderStage[RenderStage[\"Abandoned\"] = 7] = \"Abandoned\";\n return RenderStage;\n}({});\nexport class StagedRenderingController {\n constructor(abortSignal, abandonController, shouldTrackSyncIO){\n this.abortSignal = abortSignal;\n this.abandonController = abandonController;\n this.shouldTrackSyncIO = shouldTrackSyncIO;\n this.currentStage = 1;\n this.syncInterruptReason = null;\n this.staticStageEndTime = Infinity;\n this.runtimeStageEndTime = Infinity;\n this.staticStageListeners = [];\n this.earlyRuntimeStageListeners = [];\n this.runtimeStageListeners = [];\n this.dynamicStageListeners = [];\n this.staticStagePromise = createPromiseWithResolvers();\n this.earlyRuntimeStagePromise = createPromiseWithResolvers();\n this.runtimeStagePromise = createPromiseWithResolvers();\n this.dynamicStagePromise = createPromiseWithResolvers();\n if (abortSignal) {\n abortSignal.addEventListener('abort', ()=>{\n // Reject all stage promises that haven't already been resolved.\n // If a promise was already resolved via advanceStage, the reject\n // is a no-op. The ignoreReject handler suppresses unhandled\n // rejection warnings for promises that no one is awaiting.\n const { reason } = abortSignal;\n this.staticStagePromise.promise.catch(ignoreReject);\n this.staticStagePromise.reject(reason);\n this.earlyRuntimeStagePromise.promise.catch(ignoreReject);\n this.earlyRuntimeStagePromise.reject(reason);\n this.runtimeStagePromise.promise.catch(ignoreReject);\n this.runtimeStagePromise.reject(reason);\n this.dynamicStagePromise.promise.catch(ignoreReject);\n this.dynamicStagePromise.reject(reason);\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 onStage(stage, callback) {\n if (this.currentStage >= stage) {\n callback();\n } else if (stage === 3) {\n this.staticStageListeners.push(callback);\n } else if (stage === 4) {\n this.earlyRuntimeStageListeners.push(callback);\n } else if (stage === 5) {\n this.runtimeStageListeners.push(callback);\n } else if (stage === 6) {\n this.dynamicStageListeners.push(callback);\n } else {\n // This should never happen\n throw Object.defineProperty(new InvariantError(`Invalid render stage: ${stage}`), \"__NEXT_ERROR_CODE\", {\n value: \"E881\",\n enumerable: false,\n configurable: true\n });\n }\n }\n shouldTrackSyncInterrupt() {\n if (!this.shouldTrackSyncIO) {\n return false;\n }\n switch(this.currentStage){\n case 1:\n // If we haven't started the render yet, it can't be interrupted.\n return false;\n case 2:\n case 3:\n return true;\n case 4:\n // EarlyRuntime is for runtime-prefetchable segments. Sync IO\n // should error because it would abort a runtime prefetch.\n return true;\n case 5:\n // Runtime is for non-prefetchable segments. Sync IO is fine there\n // because in practice this segment will never be runtime prefetched\n return false;\n case 6:\n case 7:\n return false;\n default:\n return false;\n }\n }\n syncInterruptCurrentStageWithReason(reason) {\n if (this.currentStage === 1) {\n return;\n }\n // If the render has already been abandoned, there's nothing to interrupt.\n if (this.currentStage === 7) {\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 = 7;\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 switch(this.currentStage){\n case 2:\n case 3:\n case 4:\n {\n // EarlyRuntime is for runtime-prefetchable segments. Sync IO here\n // means the prefetch would be aborted too early.\n this.syncInterruptReason = reason;\n this.advanceStage(6);\n return;\n }\n case 5:\n {\n // canSyncInterrupt returns false for Runtime, so we should\n // never get here. Defensive no-op.\n return;\n }\n case 6:\n default:\n }\n }\n getSyncInterruptReason() {\n return this.syncInterruptReason;\n }\n getStaticStageEndTime() {\n return this.staticStageEndTime;\n }\n getRuntimeStageEndTime() {\n return this.runtimeStageEndTime;\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 switch(currentStage){\n case 2:\n {\n this.resolveStaticStage();\n }\n // intentional fallthrough\n case 3:\n {\n this.resolveEarlyRuntimeStage();\n }\n // intentional fallthrough\n case 4:\n {\n this.resolveRuntimeStage();\n }\n // intentional fallthrough\n case 5:\n {\n this.currentStage = 7;\n return;\n }\n case 6:\n case 1:\n case 7:\n break;\n default:\n {\n currentStage;\n }\n }\n }\n advanceStage(stage) {\n // If we're already at the target stage or beyond, do nothing.\n // (this can happen e.g. if sync IO advanced us to the dynamic stage)\n if (stage <= this.currentStage) {\n return;\n }\n let currentStage = this.currentStage;\n this.currentStage = stage;\n if (currentStage < 3 && stage >= 3) {\n this.resolveStaticStage();\n }\n if (currentStage < 4 && stage >= 4) {\n this.resolveEarlyRuntimeStage();\n }\n if (currentStage < 5 && stage >= 5) {\n this.staticStageEndTime = performance.now() + performance.timeOrigin;\n this.resolveRuntimeStage();\n }\n if (currentStage < 6 && stage >= 6) {\n this.runtimeStageEndTime = performance.now() + performance.timeOrigin;\n this.resolveDynamicStage();\n return;\n }\n }\n /** Fire the `onStage` listeners for the static stage and unblock any promises waiting for it. */ resolveStaticStage() {\n const staticListeners = this.staticStageListeners;\n for(let i = 0; i < staticListeners.length; i++){\n staticListeners[i]();\n }\n staticListeners.length = 0;\n this.staticStagePromise.resolve();\n }\n /** Fire the `onStage` listeners for the early runtime stage and unblock any promises waiting for it. */ resolveEarlyRuntimeStage() {\n const earlyRuntimeListeners = this.earlyRuntimeStageListeners;\n for(let i = 0; i < earlyRuntimeListeners.length; i++){\n earlyRuntimeListeners[i]();\n }\n earlyRuntimeListeners.length = 0;\n this.earlyRuntimeStagePromise.resolve();\n }\n /** Fire the `onStage` listeners for the runtime stage and unblock any promises waiting for it. */ resolveRuntimeStage() {\n const runtimeListeners = this.runtimeStageListeners;\n for(let i = 0; i < runtimeListeners.length; i++){\n runtimeListeners[i]();\n }\n runtimeListeners.length = 0;\n this.runtimeStagePromise.resolve();\n }\n /** Fire the `onStage` listeners for the dynamic stage and unblock any promises waiting for it. */ resolveDynamicStage() {\n const dynamicListeners = this.dynamicStageListeners;\n for(let i = 0; i < dynamicListeners.length; i++){\n dynamicListeners[i]();\n }\n dynamicListeners.length = 0;\n this.dynamicStagePromise.resolve();\n }\n getStagePromise(stage) {\n switch(stage){\n case 3:\n {\n return this.staticStagePromise.promise;\n }\n case 4:\n {\n return this.earlyRuntimeStagePromise.promise;\n }\n case 5:\n {\n return this.runtimeStagePromise.promise;\n }\n case 6:\n {\n return this.dynamicStagePromise.promise;\n }\n default:\n {\n stage;\n throw Object.defineProperty(new InvariantError(`Invalid render stage: ${stage}`), \"__NEXT_ERROR_CODE\", {\n value: \"E881\",\n enumerable: false,\n configurable: true\n });\n }\n }\n }\n waitForStage(stage) {\n return this.getStagePromise(stage);\n }\n delayUntilStage(stage, displayName, resolvedValue) {\n const ioTriggerPromise = this.getStagePromise(stage);\n const promise = makeDevtoolsIOPromiseFromIOTrigger(ioTriggerPromise, displayName, resolvedValue);\n // Analogously to `makeHangingPromise`, 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 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}\n\n//# sourceMappingURL=staged-rendering.js.map","// This has to be a shared module which is shared between client component error boundary and dynamic component\nconst BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING';\n/** An error that should be thrown when we want to bail out to client-side rendering. */ export class BailoutToCSRError extends Error {\n constructor(reason){\n super(`Bail out to client-side rendering: ${reason}`), this.reason = reason, this.digest = BAILOUT_TO_CSR;\n }\n}\n/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */ export function isBailoutToCSRError(err) {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false;\n }\n return err.digest === BAILOUT_TO_CSR;\n}\n\n//# sourceMappingURL=bailout-to-csr.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","/**\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 { throwForMissingRequestStore, workUnitAsyncStorage } from './work-unit-async-storage.external';\nimport { workAsyncStorage } from '../app-render/work-async-storage.external';\nimport { makeHangingPromise, getRuntimeStage } 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 { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';\nimport { InvariantError } from '../../shared/lib/invariant-error';\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants';\nconst hasPostpone = typeof React.unstable_postpone === 'function';\nexport function createDynamicTrackingState(isDebugDynamicAccesses) {\n return {\n isDebugDynamicAccesses,\n dynamicAccesses: [],\n syncDynamicErrorWithStack: null\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}\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 'prerender-ppr':\n case 'request':\n case 'generate-static-params':\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 Object.defineProperty(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`), \"__NEXT_ERROR_CODE\", {\n value: \"E553\",\n enumerable: false,\n configurable: true\n });\n }\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender-ppr':\n return postponeWithTracking(store.route, expression, workUnitStore.dynamicTracking);\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 = Object.defineProperty(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`), \"__NEXT_ERROR_CODE\", {\n value: \"E550\",\n enumerable: false,\n configurable: true\n });\n store.dynamicUsageDescription = expression;\n store.dynamicUsageStack = err.stack;\n throw err;\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n workUnitStore.usedDynamic = true;\n }\n break;\n case 'generate-static-params':\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 = Object.defineProperty(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`), \"__NEXT_ERROR_CODE\", {\n value: \"E558\",\n enumerable: false,\n configurable: true\n });\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-ppr':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n break;\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n workUnitStore.usedDynamic = true;\n }\n break;\n default:\n workUnitStore;\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 abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore);\n // It is important that we set this tracking value after aborting. Aborts are executed\n // synchronously except for the case where you abort during render itself. By setting this\n // value late we can use it to determine if any of the aborted tasks are the task that\n // called the sync IO expression in the first place.\n if (dynamicTracking) {\n if (dynamicTracking.syncDynamicErrorWithStack === null) {\n dynamicTracking.syncDynamicErrorWithStack = errorWithStack;\n }\n }\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 // It is important that we set this tracking value after aborting. Aborts are executed\n // synchronously except for the case where you abort during render itself. By setting this\n // value late we can use it to determine if any of the aborted tasks are the task that\n // called the sync IO expression in the first place.\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}\nexport function Postpone({ reason, route }) {\n const prerenderStore = workUnitAsyncStorage.getStore();\n const dynamicTracking = prerenderStore && prerenderStore.type === 'prerender-ppr' ? prerenderStore.dynamicTracking : null;\n postponeWithTracking(route, reason, dynamicTracking);\n}\nexport function postponeWithTracking(route, expression, dynamicTracking) {\n assertPostpone();\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 React.unstable_postpone(createPostponeReason(route, expression));\n}\nfunction createPostponeReason(route, expression) {\n return `Route ${route} needs to bail out of prerendering at this point because it used ${expression}. ` + `React throws this special object to indicate where. It should not be caught by ` + `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`;\n}\nexport function isDynamicPostpone(err) {\n if (typeof err === 'object' && err !== null && typeof err.message === 'string') {\n return isDynamicPostponeReason(err.message);\n }\n return false;\n}\nfunction isDynamicPostponeReason(reason) {\n return reason.includes('needs to bail out of prerendering at this point because it used') && reason.includes('Learn more: https://nextjs.org/docs/messages/ppr-caught-error');\n}\nif (isDynamicPostponeReason(createPostponeReason('%%%', '^^^')) === false) {\n throw Object.defineProperty(new Error('Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js'), \"__NEXT_ERROR_CODE\", {\n value: \"E296\",\n enumerable: false,\n configurable: true\n });\n}\nconst NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED';\nfunction createPrerenderInterruptedError(message) {\n const error = Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E394\",\n enumerable: false,\n configurable: true\n });\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}\nfunction assertPostpone() {\n if (!hasPostpone) {\n throw Object.defineProperty(new Error(`Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`), \"__NEXT_ERROR_CODE\", {\n value: \"E224\",\n enumerable: false,\n configurable: true\n });\n }\n}\n/**\n * This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's\n * abort semantics slightly.\n */ export function createRenderInBrowserAbortSignal() {\n const controller = new AbortController();\n controller.abort(Object.defineProperty(new BailoutToCSRError('Render in Browser'), \"__NEXT_ERROR_CODE\", {\n value: \"E721\",\n enumerable: false,\n configurable: true\n }));\n return controller.signal;\n}\n/**\n * In a prerender, we may end up with hanging Promises as inputs due them\n * stalling on connection() or because they're loading dynamic data. In that\n * case we need to abort the encoding of arguments since they'll never complete.\n */ export 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 runtime stage,\n // at which point all runtime inputs will be resolved.\n // (otherwise, a runtime prerender might consider `cookies()` hanging\n // even though they'd resolve in the next task.)\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 if (// eslint-disable-next-line no-restricted-syntax -- We are discriminating between two different refined types and don't need an addition exhaustive switch here\n workUnitStore.type === 'prerender-runtime' && workUnitStore.stagedRendering) {\n const { stagedRendering } = workUnitStore;\n stagedRendering.waitForStage(getRuntimeStage(stagedRendering)).then(()=>scheduleOnNextTick(()=>controller.abort()));\n } else {\n scheduleOnNextTick(()=>controller.abort());\n }\n }\n return controller.signal;\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return undefined;\n default:\n workUnitStore;\n }\n}\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}\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 case 'prerender':\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(makeHangingPromise(workUnitStore.renderSignal, workStore.route, expression));\n }\n break;\n }\n case 'prerender-ppr':\n {\n const fallbackParams = workUnitStore.fallbackRouteParams;\n if (fallbackParams && fallbackParams.size > 0) {\n return postponeWithTracking(workStore.route, expression, workUnitStore.dynamicTracking);\n }\n break;\n }\n case 'validation-client':\n {\n break;\n }\n case 'prerender-runtime':\n throw Object.defineProperty(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.`), \"__NEXT_ERROR_CODE\", {\n value: \"E771\",\n enumerable: false,\n configurable: true\n });\n case 'cache':\n case 'private-cache':\n throw Object.defineProperty(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.`), \"__NEXT_ERROR_CODE\", {\n value: \"E745\",\n enumerable: false,\n configurable: true\n });\n case 'generate-static-params':\n throw Object.defineProperty(new InvariantError(`\\`${expression}\\` was called in \\`generateStaticParams\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1130\",\n enumerable: false,\n configurable: true\n });\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(makeHangingPromise(workUnitStore.renderSignal, workStore.route, expression));\n break;\n }\n case 'prerender-legacy':\n case 'prerender-ppr':\n {\n if (workStore.forceStatic) {\n return;\n }\n throw Object.defineProperty(new BailoutToCSRError(expression), \"__NEXT_ERROR_CODE\", {\n value: \"E394\",\n enumerable: false,\n configurable: true\n });\n }\n case 'prerender':\n case 'prerender-runtime':\n throw Object.defineProperty(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.`), \"__NEXT_ERROR_CODE\", {\n value: \"E795\",\n enumerable: false,\n configurable: true\n });\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n throw Object.defineProperty(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.`), \"__NEXT_ERROR_CODE\", {\n value: \"E745\",\n enumerable: false,\n configurable: true\n });\n case 'generate-static-params':\n throw Object.defineProperty(new InvariantError(`\\`${expression}\\` was called in \\`generateStaticParams\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1130\",\n enumerable: false,\n configurable: true\n });\n case 'request':\n return;\n default:\n workUnitStore;\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]`);\nexport function trackAllowedDynamicAccess(workStore, componentStack, dynamicValidation, 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 } 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 (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n dynamicValidation.dynamicErrors.push(clientDynamic.syncDynamicErrorWithStack);\n return;\n } else {\n const message = `Route \"${workStore.route}\": Uncached data was accessed outside of ` + '<Suspense>. This delays the entire page from rendering, resulting in a ' + 'slow user experience. Learn more: ' + 'https://nextjs.org/docs/messages/blocking-route';\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1079\",\n enumerable: false,\n configurable: true\n }), componentStack, null);\n dynamicValidation.dynamicErrors.push(error);\n return;\n }\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 dynamic data. */ DynamicHoleKind[DynamicHoleKind[\"Dynamic\"] = 2] = \"Dynamic\";\n return DynamicHoleKind;\n}({});\nexport function createInstantValidationState(createInstantStack) {\n return {\n hasDynamicMetadata: false,\n hasAllowedClientDynamicAboveBoundary: false,\n dynamicMetadata: null,\n hasDynamicViewport: false,\n hasAllowedDynamic: false,\n dynamicErrors: [],\n validationPreventingErrors: [],\n thrownErrorsOutsideBoundary: [],\n createInstantStack\n };\n}\nexport function trackDynamicHoleInNavigation(workStore, componentStack, dynamicValidation, clientDynamic, kind, boundaryState) {\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 if (hasMetadataRegex.test(componentStack)) {\n const usageDescription = kind === 1 ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments.` : `Uncached data or \\`connection()\\` was accessed inside \\`generateMetadata\\`.`;\n const message = `Route \"${workStore.route}\": ${usageDescription} Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1076\",\n enumerable: false,\n configurable: true\n }), componentStack, dynamicValidation.createInstantStack);\n dynamicValidation.dynamicMetadata = error;\n return;\n }\n if (hasViewportRegex.test(componentStack)) {\n const usageDescription = kind === 1 ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateViewport\\`.` : `Uncached data or \\`connection()\\` was accessed inside \\`generateViewport\\`.`;\n const message = `Route \"${workStore.route}\": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1086\",\n enumerable: false,\n configurable: true\n }), componentStack, dynamicValidation.createInstantStack);\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 (boundaryState.expectedIds.size === boundaryState.renderedIds.size) {\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 \\`unstable_instant\\` because a Client Component in a parent segment prevented the page from rendering.`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1082\",\n enumerable: false,\n configurable: true\n }), componentStack, dynamicValidation.createInstantStack);\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 (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n const syncError = clientDynamic.syncDynamicErrorWithStack;\n if (dynamicValidation.createInstantStack !== null && syncError.cause === undefined) {\n syncError.cause = dynamicValidation.createInstantStack();\n }\n dynamicValidation.dynamicErrors.push(syncError);\n return;\n }\n const usageDescription = kind === 1 ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed outside of \\`<Suspense>\\`.` : `Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`.`;\n const message = `Route \"${workStore.route}\": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1078\",\n enumerable: false,\n configurable: true\n }), componentStack, dynamicValidation.createInstantStack);\n dynamicValidation.dynamicErrors.push(error);\n return;\n}\nexport function trackThrownErrorInNavigation(workStore, dynamicValidation, thrownValue, componentStack) {\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 const error = addErrorContext(Object.defineProperty(new Error('An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.', {\n cause: thrownValue\n }), \"__NEXT_ERROR_CODE\", {\n value: \"E1118\",\n enumerable: false,\n configurable: true\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 const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because an error prevented the target segment from rendering.`;\n const error = addErrorContext(Object.defineProperty(new Error(message, {\n cause: thrownValue\n }), \"__NEXT_ERROR_CODE\", {\n value: \"E1112\",\n enumerable: false,\n configurable: true\n }), componentStack, null // TODO(instant-validation-build): conflicting use of cause\n );\n dynamicValidation.validationPreventingErrors.push(error);\n }\n}\nexport function trackDynamicHoleInRuntimeShell(workStore, componentStack, dynamicValidation, 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 } else if (hasMetadataRegex.test(componentStack)) {\n const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed inside \\`generateMetadata\\`. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1080\",\n enumerable: false,\n configurable: true\n }), componentStack, null);\n dynamicValidation.dynamicMetadata = error;\n return;\n } else if (hasViewportRegex.test(componentStack)) {\n // TODO(instant-validation): If the page only has holes caused by runtime data,\n // we won't find out if there's a suspense-above-body and error for dynamic viewport\n // even if there is in fact a suspense-above-body\n const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed inside \\`generateViewport\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1077\",\n enumerable: false,\n configurable: true\n }), 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 (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n dynamicValidation.dynamicErrors.push(clientDynamic.syncDynamicErrorWithStack);\n return;\n }\n const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1084\",\n enumerable: false,\n configurable: true\n }), componentStack, null);\n dynamicValidation.dynamicErrors.push(error);\n return;\n}\nexport function trackDynamicHoleInStaticShell(workStore, componentStack, dynamicValidation, 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 } else if (hasMetadataRegex.test(componentStack)) {\n const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1085\",\n enumerable: false,\n configurable: true\n }), componentStack, null);\n dynamicValidation.dynamicMetadata = error;\n return;\n } else if (hasViewportRegex.test(componentStack)) {\n const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateViewport\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1081\",\n enumerable: false,\n configurable: true\n }), 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 (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n dynamicValidation.dynamicErrors.push(clientDynamic.syncDynamicErrorWithStack);\n return;\n } else {\n const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`;\n const error = addErrorContext(Object.defineProperty(new Error(message), \"__NEXT_ERROR_CODE\", {\n value: \"E1083\",\n enumerable: false,\n configurable: true\n }), componentStack, null);\n dynamicValidation.dynamicErrors.push(error);\n return;\n }\n}\n/**\n * In dev mode, we prefer using the owner stack, otherwise the provided\n * component stack is used.\n *\n * Accepts an already-created Error so the SWC error-code plugin can see the\n * `new Error(...)` call at each call site and auto-assign error codes.\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 if (process.env.NODE_ENV !== 'development') {\n console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:\n - Start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.\n - Rerun the production build with \\`next build --debug-prerender\\` to generate better stack traces.`);\n } else if (!process.env.__NEXT_DEV_SERVER) {\n console.error(`To debug the issue, start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.`);\n }\n}\nexport function throwIfDisallowedDynamic(workStore, prelude, dynamicValidation, serverDynamic) {\n if (serverDynamic.syncDynamicErrorWithStack) {\n logDisallowedDynamicError(workStore, serverDynamic.syncDynamicErrorWithStack);\n throw new StaticGenBailoutError();\n }\n if (prelude !== 0) {\n if (dynamicValidation.hasSuspenseAboveBody) {\n // This route has opted into allowing fully dynamic rendering\n // by including a Suspense boundary above the body. In this case\n // a lack of a shell is not considered disallowed so we simply return\n return;\n }\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(`Route \"${workStore.route}\" has a \\`generateViewport\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) without explicitly allowing fully dynamic rendering. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`);\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 } else {\n if (dynamicValidation.hasAllowedDynamic === false && dynamicValidation.hasDynamicMetadata) {\n console.error(`Route \"${workStore.route}\" has a \\`generateMetadata\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) when the rest of the route does not. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`);\n throw new StaticGenBailoutError();\n }\n }\n}\nexport function getStaticShellDisallowedDynamicReasons(workStore, prelude, dynamicValidation, configAllowsBlocking) {\n if (configAllowsBlocking || dynamicValidation.hasSuspenseAboveBody) {\n // This route has opted into allowing fully dynamic rendering\n // by including a Suspense boundary above the body. In this case\n // a lack of a shell is not considered disallowed so we simply return\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 Object.defineProperty(new InvariantError(`Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason.`), \"__NEXT_ERROR_CODE\", {\n value: \"E936\",\n enumerable: false,\n configurable: true\n })\n ];\n }\n } else {\n // We have a prelude but we might still have dynamic metadata without any other dynamic access\n if (dynamicValidation.hasAllowedDynamic === false && dynamicValidation.dynamicErrors.length === 0 && dynamicValidation.dynamicMetadata) {\n return [\n dynamicValidation.dynamicMetadata\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) {\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 return validationPreventingErrors;\n }\n if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) {\n const { thrownErrorsOutsideBoundary, createInstantStack } = dynamicValidation;\n if (thrownErrorsOutsideBoundary.length === 0) {\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering for an unknown reason.`;\n const error = createInstantStack !== null ? createInstantStack() : new Error();\n error.name = 'Error';\n error.message = message;\n return [\n error\n ];\n } else if (thrownErrorsOutsideBoundary.length === 1) {\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to the following error.`;\n const error = createInstantStack !== null ? createInstantStack() : new Error();\n error.name = 'Error';\n error.message = message;\n return [\n error,\n thrownErrorsOutsideBoundary[0]\n ];\n } else {\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to one of the following errors.`;\n const error = createInstantStack !== null ? createInstantStack() : new Error();\n error.name = 'Error';\n error.message = message;\n return [\n error,\n ...thrownErrorsOutsideBoundary\n ];\n }\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) {\n // If a client component suspended prevented us from rendering a shell\n // but didn't block validation, we don't require a prelude.\n if (dynamicValidation.hasAllowedClientDynamicAboveBoundary) {\n return [];\n }\n // If we ever get this far then we messed up the tracking of invalid dynamic.\n return [\n Object.defineProperty(new InvariantError(`Route \"${workStore.route}\" failed to render during instant validation and Next.js was unable to determine a reason.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1055\",\n enumerable: false,\n configurable: true\n })\n ];\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 // We had a non-empty prelude and there are no dynamic holes\n return [];\n}\n\n//# sourceMappingURL=dynamic-rendering.js.map","export const INSTANT_VALIDATION_BOUNDARY_NAME = '__next_instant_validation_boundary__';\n\n//# sourceMappingURL=boundary-constants.js.map","import { RenderStage } from './app-render/staged-rendering';\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 abortListenersBySignal = new WeakMap();\n/**\n * This function constructs a promise that will never resolve. This is primarily\n * useful for cacheComponents where we use promise resolution timing to determine which\n * parts of a render can be included in a prerender.\n *\n * @internal\n */ export function makeHangingPromise(signal, route, expression) {\n if (signal.aborted) {\n return Promise.reject(new HangingPromiseRejectionError(route, expression));\n } else {\n const hangingPromise = new Promise((_, reject)=>{\n const boundRejection = reject.bind(null, new HangingPromiseRejectionError(route, expression));\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() {}\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 * Returns the appropriate runtime stage for the current point in the render.\n * Runtime-prefetchable segments render in the early stages and should wait\n * for EarlyRuntime. Non-prefetchable segments render in the later stages\n * and should wait for Runtime.\n */ export function getRuntimeStage(stagedRendering) {\n if (stagedRendering.currentStage === RenderStage.EarlyStatic || stagedRendering.currentStage === RenderStage.EarlyRuntime) {\n return RenderStage.EarlyRuntime;\n }\n return RenderStage.Runtime;\n}\n/**\n * Delays until the appropriate runtime stage based on the current stage of\n * the rendering pipeline:\n *\n * - Early stages → wait for EarlyRuntime\n * (for runtime-prefetchable segments)\n * - Later stages → wait for Runtime\n * (for segments not using runtime prefetch)\n *\n * This ensures that cookies()/headers()/etc. resolve at the right time for\n * each segment type.\n */ export function delayUntilRuntimeStage(prerenderStore, result) {\n const { stagedRendering } = prerenderStore;\n if (!stagedRendering) {\n return result;\n }\n return stagedRendering.waitForStage(getRuntimeStage(stagedRendering)).then(()=>result);\n}\n\n//# sourceMappingURL=dynamic-rendering-utils.js.map","/**\n * Schedules a function to be called on the next tick after the other promises\n * have been resolved.\n *\n * @param cb the function to schedule\n */ export const scheduleOnNextTick = (cb)=>{\n // We use Promise.resolve().then() here so that the operation is scheduled at\n // the end of the promise job queue, we then add it to the next process tick\n // to ensure it's evaluated afterwards.\n //\n // This was inspired by the implementation of the DataLoader interface: https://github.com/graphql/dataloader/blob/d336bd15282664e0be4b4a657cb796f09bafbc6b/src/index.js#L213-L255\n //\n Promise.resolve().then(()=>{\n if (process.env.NEXT_RUNTIME === 'edge') {\n setTimeout(cb, 0);\n } else {\n process.nextTick(cb);\n }\n });\n};\n/**\n * Schedules a function to be called using `setImmediate` or `setTimeout` if\n * `setImmediate` is not available (like in the Edge runtime).\n *\n * @param cb the function to schedule\n */ export const scheduleImmediate = (cb)=>{\n if (process.env.NEXT_RUNTIME === 'edge') {\n setTimeout(cb, 0);\n } else {\n setImmediate(cb);\n }\n};\n/**\n * returns a promise than resolves in a future task. There is no guarantee that the task it resolves in\n * will be the next task but if you await it you can at least be sure that the current task is over and\n * most usefully that the entire microtask queue of the current task has been emptied.\n */ export function atLeastOneTask() {\n return new Promise((resolve)=>scheduleImmediate(resolve));\n}\n/**\n * This utility function is extracted to make it easier to find places where we are doing\n * specific timing tricks to try to schedule work after React has rendered. This is especially\n * important at the moment because Next.js uses the edge builds of React which use setTimeout to\n * schedule work when you might expect that something like setImmediate would do the trick.\n *\n * Long term we should switch to the node versions of React rendering when possible and then\n * update this to use setImmediate rather than setTimeout\n */ export function waitAtLeastOneReactRenderTask() {\n if (process.env.NEXT_RUNTIME === 'edge') {\n return new Promise((r)=>setTimeout(r, 0));\n } else {\n return new Promise((r)=>setImmediate(r));\n }\n}\n\n//# sourceMappingURL=scheduler.js.map","const REACT_POSTPONE_TYPE = Symbol.for('react.postpone');\nexport function isPostpone(error) {\n return typeof error === 'object' && error !== null && error.$$typeof === REACT_POSTPONE_TYPE;\n}\n\n//# sourceMappingURL=is-postpone.js.map","import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils';\nimport { isPostpone } from '../../server/lib/router-utils/is-postpone';\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr';\nimport { isNextRouterError } from './is-next-router-error';\nimport { isDynamicPostpone, isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering';\nimport { isDynamicServerError } from './hooks-server-context';\nexport function unstable_rethrow(error) {\n if (isNextRouterError(error) || isBailoutToCSRError(error) || isDynamicServerError(error) || isDynamicPostpone(error) || isPostpone(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.server.js.map","let warnOnce = (_)=>{};\nif (process.env.NODE_ENV !== 'production') {\n const warnings = new Set();\n warnOnce = (msg)=>{\n if (!warnings.has(msg)) {\n console.warn(msg);\n }\n warnings.add(msg);\n };\n}\nexport { warnOnce };\n\n//# sourceMappingURL=warn-once.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 { warnOnce } from '../../../shared/lib/utils/warn-once';\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 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","import { useContext } from 'react';\nimport { PathnameContext } from '../../shared/lib/hooks-client-context.shared-runtime';\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 if (typeof window === 'undefined') {\n // AsyncLocalStorage should not be included in the client bundle.\n const { workUnitAsyncStorage } = require('../../server/app-render/work-unit-async-storage.external');\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (!workUnitStore) return false;\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\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 'generate-static-params':\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","export const RSC_HEADER = 'rsc' as const\nexport const ACTION_HEADER = 'next-action' as const\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' as const\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const\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 =\n 'next-router-segment-prefetch' as const\nexport const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh' as const\nexport const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const\nexport const NEXT_URL = 'next-url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\n// Header for the Instant Navigation Testing API. In development and testing\n// builds, static pre-renders normally don't happen. This header tells the\n// server to perform a static pre-render anyway, allowing tests to assert on\n// the prefetched UI. Not exposed in production builds by default.\nexport const NEXT_INSTANT_PREFETCH_HEADER =\n 'next-instant-navigation-testing-prefetch' as const\n\n// Cookie for the Instant Navigation Testing API. Used for MPA navigations\n// (page reload, full page load) where we can't set request headers. When set,\n// the server renders only the static shell. Not exposed in production builds\n// by default.\nexport const NEXT_INSTANT_TEST_COOKIE =\n 'next-instant-navigation-testing' as const\n\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] as const\n\nexport const NEXT_RSC_UNION_QUERY = '_rsc' as const\n\nexport const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time' as const\nexport const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed' as const\nexport const NEXT_REWRITTEN_PATH_HEADER = 'x-nextjs-rewritten-path' as const\nexport const NEXT_REWRITTEN_QUERY_HEADER = 'x-nextjs-rewritten-query' as const\nexport const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender' as const\nexport const NEXT_ACTION_NOT_FOUND_HEADER = 'x-nextjs-action-not-found' as const\nexport const NEXT_REQUEST_ID_HEADER = 'x-nextjs-request-id' as const\nexport const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id' as const\n\n// TODO: Should this include nextjs in the name, like the others?\nexport const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated' as const\n","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 addSearchParamsIfPageSegment(segment, searchParams) {\n const isPageSegment = segment.includes(PAGE_SEGMENT_KEY);\n if (isPageSegment) {\n const stringifiedQuery = JSON.stringify(searchParams);\n return stringifiedQuery !== '{}' ? PAGE_SEGMENT_KEY + '?' + stringifiedQuery : PAGE_SEGMENT_KEY;\n }\n return segment;\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.startsWith(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","import { PAGE_SEGMENT_KEY } from '../segment';\nexport const ROOT_SEGMENT_REQUEST_KEY = '';\nexport const HEAD_REQUEST_KEY = '/_head';\nexport function createSegmentRequestKeyPart(segment) {\n if (typeof segment === 'string') {\n if (segment.startsWith(PAGE_SEGMENT_KEY)) {\n // The Flight Router State type sometimes includes the search params in\n // the page segment. However, the Segment Cache tracks this as a separate\n // key. So, we strip the search params here, and then add them back when\n // the cache entry is turned back into a FlightRouterState. This is an\n // unfortunate consequence of the FlightRouteState being used both as a\n // transport type and as a cache key; we'll address this once more of the\n // Segment Cache implementation has settled.\n // TODO: We should hoist the search params out of the FlightRouterState\n // type entirely, This is our plan for dynamic route params, too.\n return PAGE_SEGMENT_KEY;\n }\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","import { addSearchParamsIfPageSegment, 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';\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 rewrittenQuery === '' ? '' : '?' + 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 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 return rewrittenPath ?? urlToUrlWithoutFlightMarker(new URL(response.url)).pathname;\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)=>encodeURIComponent(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 encodeURIComponent(s.slice(prefix));\n }\n return encodeURIComponent(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)=>encodeURIComponent(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 encodeURIComponent(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 encodeURIComponent(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.startsWith(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, renderedSearch) {\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 // TODO: Refactor or remove this helper function to accept a string rather\n // than the whole segment type. Also we can probably just append the\n // search string instead of turning it into JSON.\n const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(paramValue, Object.fromEntries(new URLSearchParams(renderedSearch)));\n return pageSegmentWithSearchParams;\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 const length = pathname.endsWith('/index.txt') ? 10 : 4;\n // Slice off `/index.txt` or `.txt` from the end of the pathname\n urlWithoutFlightParameters.pathname = 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","module.exports = (\n require('../../module.compiled') as typeof import('../../module.compiled')\n).vendored['react-ssr']!.ReactServerDOMTurbopackClient\n","import type { Dispatch } from 'react'\nimport React, { use, useMemo, useOptimistic } from 'react'\nimport { isThenable } from '../../shared/lib/is-thenable'\nimport type { AppRouterActionQueue } from './app-router-instance'\nimport {\n ACTION_REFRESH,\n type AppRouterState,\n type ReducerActions,\n type ReducerState,\n} from './router-reducer/router-reducer-types'\n\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: Dispatch<ReducerActions> | null = null\n\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 */\nexport function refreshOnInstantNavigationUnlock() {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n if (dispatch !== null) {\n dispatch({ type: ACTION_REFRESH, bypassCacheInvalidation: true })\n } else {\n window.location.reload()\n }\n }\n}\n\nexport function dispatchAppRouterAction(action: ReducerActions) {\n if (dispatch === null) {\n throw new Error(\n 'Internal Next.js error: Router action dispatched before initialization.'\n )\n }\n dispatch(action)\n}\n\n// Optimistic state setter for experimental_gesturePush. Only should be used\n// during a gesture transition.\nlet setGestureRouterState: ((state: ReducerState) => void) | null = null\n\nexport function dispatchGestureState(state: ReducerState) {\n if (setGestureRouterState === null) {\n throw new Error(\n 'Internal Next.js error: Router action dispatched before initialization.'\n )\n }\n setGestureRouterState(state)\n}\n\nconst __DEV__ = process.env.NODE_ENV !== 'production'\nconst promisesWithDebugInfo: WeakMap<\n Promise<AppRouterState>,\n Promise<AppRouterState> & { _debugInfo?: Array<unknown> }\n> = __DEV__ ? new WeakMap() : (null as any)\n\nexport function useActionQueue(\n actionQueue: AppRouterActionQueue\n): AppRouterState {\n const [canonicalState, setState] = React.useState<ReducerState>(\n actionQueue.state\n )\n\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\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: Dispatch<ReducerActions>\n\n if (process.env.NODE_ENV !== 'production') {\n const { useAppDevRenderingIndicator } =\n require('../../next-devtools/userspace/use-app-dev-rendering-indicator') as typeof import('../../next-devtools/userspace/use-app-dev-rendering-indicator')\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const appDevRenderingIndicator = useAppDevRenderingIndicator()\n\n nextDispatch = (action: ReducerActions) => {\n appDevRenderingIndicator(() => {\n actionQueue.dispatch(action, setState)\n })\n }\n } else {\n nextDispatch = (action: ReducerActions) =>\n actionQueue.dispatch(action, setState)\n }\n\n if (typeof window !== 'undefined') {\n dispatch = nextDispatch\n }\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\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: Array<unknown> = []\n promiseWithDebugInfo = Promise.resolve(state).then((asyncState) => {\n if (asyncState.debugInfo !== null) {\n debugInfo.push(...asyncState.debugInfo)\n }\n return asyncState\n }) as Promise<AppRouterState> & { _debugInfo?: Array<unknown> }\n promiseWithDebugInfo._debugInfo = debugInfo\n\n promisesWithDebugInfo.set(state, promiseWithDebugInfo)\n }\n\n return promiseWithDebugInfo\n }\n return state\n }, [state])\n\n return isThenable(stateWithDebugInfo)\n ? use(stateWithDebugInfo)\n : stateWithDebugInfo\n}\n","/**\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\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue'\n\ntype InstantNavCookieState = 'pending' | 'mpa' | 'spa'\n\ntype InstantCookie =\n // pending (waiting to capture)\n | [captured: 0, id: string]\n // captured MPA page load\n | [captured: 1, id: string, state: null]\n // captured SPA navigation (from/to route trees)\n | [\n captured: 1,\n id: string,\n state: { from: FlightRouterState; to: FlightRouterState | null },\n ]\n\nfunction parseCookieValue(raw: string): InstantNavCookieState {\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed) && parsed.length >= 3) {\n const rawState = parsed[2]\n return rawState === null ? 'mpa' : 'spa'\n }\n } catch {}\n return 'pending'\n}\n\nfunction writeCookieValue(value: InstantCookie): void {\n if (typeof cookieStore === 'undefined') {\n return\n }\n // Read the existing cookie to preserve its attributes (domain, path),\n // then write back with the new value. This updates the same cookie\n // entry that the external actor created, regardless of how it was\n // scoped.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {\n if (existing) {\n const options: any = {\n name: NEXT_INSTANT_TEST_COOKIE,\n value: JSON.stringify(value),\n path: existing.path ?? '/',\n }\n if (existing.domain) {\n options.domain = existing.domain\n }\n cookieStore.set(options)\n }\n })\n}\n\ntype NavigationLockState = {\n promise: Promise<void>\n resolve: () => void\n}\n\nlet lockState: NavigationLockState | null = null\n\nfunction acquireLock(): void {\n if (lockState !== null) {\n return\n }\n let resolve: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n lockState = { promise, resolve: resolve! }\n}\n\nfunction releaseLock(): void {\n if (lockState !== null) {\n lockState.resolve()\n lockState = null\n }\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 */\nexport function startListeningForInstantNavigationCookie(): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n // If the server served a static 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: any) => {\n if (!cookie) {\n window.location.reload()\n }\n })\n }\n\n writeCookieValue([1, `c${Math.random()}`, null])\n acquireLock()\n }\n\n if (typeof cookieStore === 'undefined') {\n return\n }\n\n cookieStore.addEventListener('change', (event: CookieChangeEvent) => {\n for (const cookie of event.changed) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n const state = parseCookieValue(cookie.value ?? '')\n\n if (state !== 'pending') {\n // Captured value — our own transition. Ignore.\n return\n }\n\n // Pending value — external actor starting a new lock scope.\n if (lockState !== null) {\n releaseLock()\n }\n acquireLock()\n return\n }\n }\n\n for (const cookie of event.deleted) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n releaseLock()\n refreshOnInstantNavigationUnlock()\n return\n }\n }\n })\n }\n}\n\n/**\n * Transitions the cookie from pending to captured-SPA. Called when a\n * client-side navigation is captured by the lock.\n *\n * @param fromTree - The flight router state of the from-route\n * @param toTree - The flight router state of the to-route (null if not yet known)\n */\nexport function transitionToCapturedSPA(\n fromTree: FlightRouterState,\n toTree: FlightRouterState | null\n): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n }\n}\n\n/**\n * Updates the captured-SPA cookie with the resolved route trees.\n * Called after the prefetch resolves and the target route tree is known.\n */\nexport function updateCapturedSPAToTree(\n fromTree: FlightRouterState,\n toTree: FlightRouterState\n): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n }\n}\n\n/**\n * Returns true if the navigation lock is currently active.\n */\nexport function isNavigationLocked(): boolean {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n return lockState !== null\n }\n return false\n}\n\n/**\n * Waits for the navigation lock to be released, if it's currently held.\n * No-op if the lock is not acquired.\n */\nexport async function waitForNavigationLockIfActive(): Promise<void> {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n if (lockState !== null) {\n await lockState.promise\n }\n }\n}\n","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 delete document.documentElement.dataset.dplId;\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_IMMUTABLE_ASSET_TOKEN || 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","'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 { 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 { normalizeFlightData, 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 } 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 // Typically, during a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise.\n // TODO: Remove this check once the old PPR flag is removed\n const isLegacyPPR = process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS;\n const shouldImmediatelyDecode = !isLegacyPPR;\n const res = await createFetch(url, headers, 'auto', shouldImmediatelyDecode);\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 let flightResponsePromise = res.flightResponsePromise;\n if (flightResponsePromise === null) {\n // Typically, `createFetch` would have already started decoding the\n // Flight response. If it hasn't, though, we need to decode it now.\n // TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR\n // without Cache Components). Remove this branch once legacy PPR\n // is deleted.\n flightResponsePromise = createFromNextReadableStream(res.body, headers, {\n allowPartialStream: postponed\n });\n }\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 const normalizedFlightData = normalizeFlightData(flightResponse.f);\n if (typeof normalizedFlightData === 'string') {\n return doMpaNavigation(normalizedFlightData);\n }\n const staticStageData = cacheData !== null ? await resolveStaticStageData(cacheData, flightResponse, headers) : null;\n return {\n flightData: normalizedFlightData,\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 staticStageData,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null\n };\n } catch (err) {\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 Object.defineProperty(new InvariantError('Expected RSC navigation response to have a body'), \"__NEXT_ERROR_CODE\", {\n value: \"E1088\",\n enumerable: false,\n configurable: true\n });\n }\n const { stream, isPartial } = await stripIsPartialByte(response.body);\n let responseStream;\n let cacheData;\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n const [stream1, stream2] = stream.tee();\n responseStream = stream1;\n cacheData = {\n isResponsePartial: isPartial,\n responseBodyClone: stream2\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.\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 */ export async function resolveStaticStageData(cacheData, flightResponse, headers) {\n const { isResponsePartial, responseBodyClone } = cacheData;\n if (responseBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n responseBodyClone.cancel();\n return {\n response: flightResponse,\n isResponsePartial: false\n };\n }\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const response = await decodeStaticStage(responseBodyClone, flightResponse.l, headers);\n return {\n response,\n isResponsePartial: true\n };\n }\n // No caching — cancel the unused clone.\n responseBodyClone.cancel();\n }\n return null;\n}\n/**\n * Truncates a Flight stream clone at the given byte boundary and decodes the\n * static stage prefix. Used by both the navigation path and the initial HTML\n * hydration path.\n */ export async function decodeStaticStage(responseBodyClone, staticStageByteLengthPromise, headers) {\n const staticStageByteLength = await staticStageByteLengthPromise;\n const truncatedStream = truncateStream(responseBodyClone, staticStageByteLength);\n return createFromNextReadableStream(truncatedStream, headers, {\n allowPartialStream: true\n });\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 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 ? createFromNextFetch(fetchPromise, headers) : 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 setCacheBustingSearchParam(fetchUrl, headers);\n processed = fetch(fetchUrl, fetchOptions).then(processFetch);\n fetchPromise = processed.then(({ response })=>response);\n flightResponsePromise = shouldImmediatelyDecode ? createFromNextFetch(fetchPromise, headers) : 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}\nfunction truncateStream(stream, byteLength) {\n const reader = stream.getReader();\n let remaining = byteLength;\n return new ReadableStream({\n async pull (controller) {\n if (remaining <= 0) {\n reader.cancel();\n controller.close();\n return;\n }\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n if (value.byteLength <= remaining) {\n controller.enqueue(value);\n remaining -= value.byteLength;\n } else {\n controller.enqueue(value.subarray(0, remaining));\n remaining = 0;\n reader.cancel();\n controller.close();\n }\n },\n cancel () {\n reader.cancel();\n }\n });\n}\n\n//# sourceMappingURL=fetch-server-response.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.unstable_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(error) {\n if (isNextRouterError(error)) {\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 error;\n }\n return {\n error\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)) {\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 handleISRError({\n error: this.state.error\n });\n return /*#__PURE__*/ _jsxs(_Fragment, {\n children: [\n this.props.errorStyles,\n this.props.errorScripts,\n /*#__PURE__*/ _jsx(this.props.errorComponent, {\n error: this.state.error,\n reset: this.reset,\n unstable_retry: this.unstable_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","import { warnOnce } from '../../utils/warn-once';\n/**\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 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","/**\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","import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment';\nexport function createRouterCacheKey(segment, withoutSearchParameters = false) {\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 // Page segments might have search parameters, ie __PAGE__?foo=bar\n // When `withoutSearchParameters` is true, we only want to return the page segment\n if (withoutSearchParameters && segment.startsWith(PAGE_SEGMENT_KEY)) {\n return PAGE_SEGMENT_KEY;\n }\n return segment;\n}\n\n//# sourceMappingURL=create-router-cache-key.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 } 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';\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 does not return anything.\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 = (url, headers)=>{\n const uniqueCacheKey = computeCacheBustingSearchParam(headers[NEXT_ROUTER_PREFETCH_HEADER], headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER], headers[NEXT_ROUTER_STATE_TREE_HEADER], headers[NEXT_URL]);\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 null, 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","const workAsyncStorage = typeof window === 'undefined' ? require('../../server/app-render/work-async-storage.external').workAsyncStorage : undefined;\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 (workAsyncStorage) {\n const store = workAsyncStorage.getStore();\n if (store?.isStaticGeneration) {\n if (error) {\n console.error(error);\n }\n throw error;\n }\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, { Activity, Fragment, useContext, use, Suspense, useDeferredValue, useLayoutEffect } from 'react';\nimport ReactDOM from 'react-dom';\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 { createRouterCacheKey } from './router-reducer/create-router-cache-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 './router-reducer/ppr-navigations';\nconst enableNewScrollHandler = process.env.__NEXT_APP_NEW_SCROLL_HANDLER;\nconst __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;\n// TODO-APP: Replace with new React API for finding dom nodes without a `ref` when available\n/**\n * Wraps ReactDOM.findDOMNode with additional logic to hide React Strict Mode warning\n */ function findDOMNode(instance) {\n // Tree-shake for server bundle\n if (typeof window === 'undefined') return null;\n // __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE.findDOMNode is null during module init.\n // We need to lazily reference it.\n const internal_reactDOMfindDOMNode = __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE.findDOMNode;\n return internal_reactDOMfindDOMNode(instance);\n}\nconst rectProperties = [\n 'bottom',\n 'height',\n 'left',\n 'right',\n 'top',\n 'width',\n 'x',\n 'y'\n];\n/**\n * Check if a HTMLElement is hidden or fixed/sticky position\n */ function shouldSkipElement(element) {\n // we ignore fixed or sticky positioned elements since they'll likely pass the \"in-viewport\" check\n // and will result in a situation we bail on scroll because of something like a fixed nav,\n // even though the actual page content is offscreen\n if ([\n 'sticky',\n 'fixed'\n ].includes(getComputedStyle(element).position)) {\n return true;\n }\n // Uses `getBoundingClientRect` to check if the element is hidden instead of `offsetParent`\n // because `offsetParent` doesn't consider document/body\n const rect = element.getBoundingClientRect();\n return rectProperties.every((item)=>rect[item] === 0);\n}\n/**\n * Check if the top corner of the HTMLElement is in the viewport.\n */ function topOfElementInViewport(instance, viewportHeight) {\n const rects = instance.getClientRects();\n if (rects.length === 0) {\n // Just to be explicit.\n return false;\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 >= 0 && elementTop <= viewportHeight;\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];\n}\nclass InnerScrollAndFocusHandlerOld extends React.Component {\n componentDidMount() {\n this.handlePotentialScroll();\n }\n componentDidUpdate() {\n this.handlePotentialScroll();\n }\n render() {\n return this.props.children;\n }\n constructor(...args){\n super(...args), this.handlePotentialScroll = ()=>{\n // Handle scroll and focus, it's only applied once.\n const { focusAndScrollRef, cacheNode } = this.props;\n const scrollRef = focusAndScrollRef.forceScroll ? focusAndScrollRef.scrollRef : cacheNode.scrollRef;\n if (scrollRef === null || !scrollRef.current) return;\n let domNode = null;\n const hashFragment = focusAndScrollRef.hashFragment;\n if (hashFragment) {\n domNode = getHashFragmentDomNode(hashFragment);\n }\n // `findDOMNode` is tricky because it returns just the first child if the component is a fragment.\n // This already caused a bug where the first child was a <link/> in head.\n if (!domNode) {\n domNode = findDOMNode(this);\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 (!(domNode instanceof Element)) {\n return;\n }\n // Verify if the element is a HTMLElement and if we want to consider it for scroll behavior.\n // If the element is skipped, try to select the next sibling and try again.\n while(!(domNode instanceof HTMLElement) || shouldSkipElement(domNode)){\n if (process.env.NODE_ENV !== 'production') {\n if (domNode.parentElement?.localName === 'head') {\n // We enter this state when metadata was rendered as part of the page or via Next.js.\n // This is always a bug in Next.js and caused by React hoisting metadata.\n // Fixed with `experimental.appNewScrollHandler`\n }\n }\n // No siblings found that match the criteria are found, so handle scroll higher up in the tree instead.\n if (domNode.nextElementSibling === null) {\n return;\n }\n domNode = domNode.nextElementSibling;\n }\n // Mark as scrolled so no other segment scrolls for this navigation.\n scrollRef.current = false;\n disableSmoothScrollDuringRouteTransition(()=>{\n // In case of hash scroll, we only need to scroll the element into view\n if (hashFragment) {\n domNode.scrollIntoView();\n return;\n }\n // Store the current viewport height because reading `clientHeight` causes a reflow,\n // and it won't change during this function.\n const htmlElement = document.documentElement;\n const viewportHeight = htmlElement.clientHeight;\n // If the element's top edge is already in the viewport, exit early.\n if (topOfElementInViewport(domNode, viewportHeight)) {\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 (!topOfElementInViewport(domNode, viewportHeight)) {\n // Scroll into view doesn't scroll horizontally by default when not needed\n domNode.scrollIntoView();\n }\n }, {\n // We will force layout by querying domNode position\n dontForceLayout: true,\n onlyHashChange: focusAndScrollRef.onlyHashChange\n });\n // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`\n focusAndScrollRef.onlyHashChange = false;\n focusAndScrollRef.hashFragment = null;\n // Set focus on the element\n domNode.focus();\n };\n }\n}\n/**\n * Fork of InnerScrollAndFocusHandlerOld using Fragment refs for scrolling.\n * No longer focuses the first host descendant.\n */ function InnerScrollHandlerNew(props) {\n const childrenRef = React.useRef(null);\n useLayoutEffect(()=>{\n const { focusAndScrollRef, cacheNode } = props;\n const scrollRef = focusAndScrollRef.forceScroll ? focusAndScrollRef.scrollRef : cacheNode.scrollRef;\n if (scrollRef === null || !scrollRef.current) return;\n let instance = null;\n const hashFragment = focusAndScrollRef.hashFragment;\n if (hashFragment) {\n instance = getHashFragmentDomNode(hashFragment);\n }\n if (!instance) {\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 // Mark as scrolled so no other segment scrolls for this navigation.\n scrollRef.current = false;\n const activeElement = document.activeElement;\n if (activeElement !== null && 'blur' in activeElement && typeof activeElement.blur === 'function') {\n // Trying to match hard navigations.\n // Ideally we'd move the internal focus cursor either to the top\n // or at least before the segment. But there's no DOM API to do that,\n // so we just blur.\n // We could workaround this by moving focus to a temporary element in\n // the body. But adding elements might trigger layout or other effects\n // so it should be well motivated.\n activeElement.blur();\n }\n disableSmoothScrollDuringRouteTransition(()=>{\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 // Store the current viewport height because reading `clientHeight` causes a reflow,\n // and it won't change during this function.\n const htmlElement = document.documentElement;\n const viewportHeight = htmlElement.clientHeight;\n // If the element's top edge is already in the viewport, exit early.\n if (topOfElementInViewport(instance, viewportHeight)) {\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 (!topOfElementInViewport(instance, viewportHeight)) {\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: focusAndScrollRef.onlyHashChange\n });\n // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`\n focusAndScrollRef.onlyHashChange = false;\n focusAndScrollRef.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}\nconst InnerScrollAndMaybeFocusHandler = enableNewScrollHandler ? InnerScrollHandlerNew : InnerScrollAndFocusHandlerOld;\nfunction ScrollAndMaybeFocusHandler({ children, cacheNode }) {\n const context = useContext(GlobalLayoutRouterContext);\n if (!context) {\n throw Object.defineProperty(new Error('invariant global layout router not mounted'), \"__NEXT_ERROR_CODE\", {\n value: \"E473\",\n enumerable: false,\n configurable: true\n });\n }\n return /*#__PURE__*/ _jsx(InnerScrollAndMaybeFocusHandler, {\n focusAndScrollRef: context.focusAndScrollRef,\n cacheNode: cacheNode,\n children: children\n });\n}\n/**\n * InnerLayoutRouter handles rendering the provided segment based on the cache.\n */ function InnerLayoutRouter({ tree, segmentPath, debugNameContext, cacheNode: maybeCacheNode, params, url, isActive }) {\n const context = useContext(GlobalLayoutRouterContext);\n const parentNavPromises = useContext(NavigationPromisesContext);\n if (!context) {\n throw Object.defineProperty(new Error('invariant global layout router not mounted'), \"__NEXT_ERROR_CODE\", {\n value: \"E473\",\n enumerable: false,\n configurable: true\n });\n }\n const cacheNode = maybeCacheNode !== null ? maybeCacheNode : //\n // This should only be reachable for inactive/hidden segments, during\n // prerendering The active segment should always be consistent with the\n // CacheNode tree. Regardless, if we don't have a matching CacheNode, we\n // must suspend rather than render nothing, to prevent showing an\n // inconsistent route.\n use(unresolvedThenable);\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 = cacheNode.prefetchRsc !== null ? cacheNode.prefetchRsc : cacheNode.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(cacheNode.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 parentCacheNode: cacheNode,\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 CacheNode.)\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 parentCacheNode: parentContext.parentCacheNode,\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 Object.defineProperty(new Error('invariant expected layout router to be mounted'), \"__NEXT_ERROR_CODE\", {\n value: \"E56\",\n enumerable: false,\n configurable: true\n });\n }\n const { parentTree, parentCacheNode, parentSegmentPath, parentParams, parentLoadingData, url, isActive, debugNameContext } = context;\n // Get the CacheNode 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 — it represents the\n // identity of the UI tree. Whenever the state key changes, the tree is\n // recreated and the state is reset. In the App Router model, search params do\n // not cause state to be lost, so two segments with the same segment path but\n // different search params should have the same state key.\n //\n // The \"cache\" key of a segment, however, *does* include the search params, if\n // it's possible that the segment accessed the search params on the server.\n // (This only applies to page segments; layout segments cannot access search\n // params on the server.)\n const activeTree = parentTree[1][parallelRouterKey];\n const maybeParentSlots = parentCacheNode.slots;\n if (activeTree === undefined || maybeParentSlots === null) {\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 const { InstantValidationBoundaryContext } = require('./instant-validation/boundary');\n maybeValidationBoundaryId = use(InstantValidationBoundaryContext);\n }\n const activeSegment = activeTree[0];\n const activeCacheNode = maybeParentSlots[parallelRouterKey] ?? null;\n const activeStateKey = createRouterCacheKey(activeSegment, true) // no search params\n ;\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, activeCacheNode, activeStateKey);\n let children = [];\n do {\n const tree = bfcacheEntry.tree;\n const cacheNode = bfcacheEntry.cacheNode;\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(ScrollAndMaybeFocusHandler, {\n cacheNode: cacheNode,\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 cacheNode: cacheNode,\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 const { RenderValidationBoundaryAtThisLevel } = require('./instant-validation/boundary');\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 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","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","export const matchSegment = (existingSegment, segment)=>{\n // segment is either Array or string\n if (typeof existingSegment === 'string') {\n if (typeof segment === 'string') {\n // Common case: segment is just a string\n return existingSegment === segment;\n }\n return false;\n }\n if (typeof segment === 'string') {\n return false;\n }\n return existingSegment[0] === segment[0] && existingSegment[1] === segment[1];\n};\n\n//# sourceMappingURL=match-segments.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","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 * Note that we don't store the RSC data for the cache entries in this hook —\n * the data for inactive segments is stored in the parent CacheNode, which\n * *does* have a longer lifetime than the React tree. This hook only determines\n * which of those trees should have their *state* preserved, by <Activity>.\n */ export function useRouterBFCache(activeTree, activeCacheNode, 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 cacheNode: activeCacheNode,\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 cacheNode: activeCacheNode,\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 cacheNode: oldEntry.cacheNode,\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 { RedirectStatusCode } from './redirect-status-code';\nimport { isRedirectError, REDIRECT_ERROR_CODE } from './redirect-error';\nconst actionAsyncStorage = typeof window === 'undefined' ? require('../../server/app-render/action-async-storage.external').actionAsyncStorage : undefined;\nexport function getRedirectError(url, type, statusCode = RedirectStatusCode.TemporaryRedirect) {\n const error = Object.defineProperty(new Error(REDIRECT_ERROR_CODE), \"__NEXT_ERROR_CODE\", {\n value: \"E394\",\n enumerable: false,\n configurable: true\n });\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 or Server Action, it will serve a 307/303 to the caller.\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 or Server Action, it will serve a 308/303 to the caller.\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 Object.defineProperty(new Error('Not a redirect error'), \"__NEXT_ERROR_CODE\", {\n value: \"E260\",\n enumerable: false,\n configurable: true\n });\n }\n return error.digest.split(';', 2)[1];\n}\nexport function getRedirectStatusCodeFromError(error) {\n if (!isRedirectError(error)) {\n throw Object.defineProperty(new Error('Not a redirect error'), \"__NEXT_ERROR_CODE\", {\n value: \"E260\",\n enumerable: false,\n configurable: true\n });\n }\n return Number(error.digest.split(';').at(-2));\n}\n\n//# sourceMappingURL=redirect.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 { hexHash } from '../../hash';\nexport function computeCacheBustingSearchParam(prefetchHeader, segmentPrefetchHeader, stateTreeHeader, nextUrlHeader) {\n if ((prefetchHeader === undefined || prefetchHeader === '0') && segmentPrefetchHeader === undefined && stateTreeHeader === undefined && nextUrlHeader === undefined) {\n return '';\n }\n return hexHash([\n prefetchHeader || '0',\n segmentPrefetchHeader || '0',\n stateTreeHeader || '0',\n nextUrlHeader || '0'\n ].join(','));\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//# sourceMappingURL=cache-key.js.map","import { lruPut, updateLruSize, deleteFromLru } from './lru';\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) {\n const entry = getEntryWithFallbackImpl(now, currentCacheVersion, rootEntry, keys, isRevalidation, 0);\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) {\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 // The matched entry has not expired. Return it.\n return entry;\n}\nfunction getEntryWithFallbackImpl(now, currentCacheVersion, entry, keys, isRevalidation, previousKey) {\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 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 // TODO: When performing a lookup during a navigation, as opposed to a\n // prefetch, we may want to skip entries that are Pending if there's also\n // a Fulfilled fallback entry. Tricky to say, though, since if it's\n // already pending, it's likely to stream in soon. Maybe we could do this\n // just on slow connections and offline mode.\n return lazilyEvictIfNeeded(now, currentCacheVersion, entry);\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);\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);\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","import { ReadonlyURLSearchParams } from './readonly-url-search-params';\nexport function unstable_isUnrecognizedActionError() {\n throw Object.defineProperty(new Error('`unstable_isUnrecognizedActionError` can only be used on the client.'), \"__NEXT_ERROR_CODE\", {\n value: \"E776\",\n enumerable: false,\n configurable: true\n });\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 { 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=app-call-server.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';\nconst useDynamicRouteParams = typeof window === 'undefined' ? require('../../server/app-render/dynamic-rendering').useDynamicRouteParams : undefined;\nconst useDynamicSearchParams = typeof window === 'undefined' ? require('../../server/app-render/dynamic-rendering').useDynamicSearchParams : undefined;\nconst { instrumentParamsForClientValidation, instrumentSearchParamsForClientValidation, expectCompleteParamsInClientValidation } = typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS ? require('../../server/app-render/instant-validation/instant-samples-client') : {};\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 Object.defineProperty(new Error('invariant expected app router to be mounted'), \"__NEXT_ERROR_CODE\", {\n value: \"E238\",\n enumerable: false,\n configurable: true\n });\n }\n return router;\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 { 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 { FetchStrategy } from './types';\nimport { Fallback } from './cache-map';\nimport { HEAD_REQUEST_KEY } from '../../../shared/lib/segment-cache/segment-value-encoding';\nexport function getRouteVaryPath(pathname, search, nextUrl) {\n // requestKey -> searchParams -> nextUrl\n const varyPath = {\n id: null,\n value: pathname,\n parent: {\n id: '?',\n value: search,\n parent: {\n id: null,\n value: nextUrl,\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 parent: {\n id: '?',\n value: search,\n parent: {\n id: null,\n value: couldBeIntercepted ? nextUrl : Fallback,\n parent: null\n }\n }\n };\n return varyPath;\n}\nexport function appendLayoutVaryPath(parentPath, cacheKey, paramName) {\n const varyPathPart = {\n id: paramName,\n value: cacheKey,\n parent: parentPath\n };\n return varyPathPart;\n}\nexport function finalizeLayoutVaryPath(requestKey, varyPath) {\n const layoutVaryPath = {\n id: null,\n value: requestKey,\n parent: varyPath\n };\n return layoutVaryPath;\n}\nexport function getPartialLayoutVaryPath(finalizedVaryPath) {\n // This is the inverse of finalizeLayoutVaryPath.\n return finalizedVaryPath.parent;\n}\nexport function finalizePageVaryPath(requestKey, renderedSearch, varyPath) {\n // Unlike layouts, a page segment's vary path also includes the search string.\n // requestKey -> searchParams -> pathParams\n const pageVaryPath = {\n id: null,\n value: requestKey,\n parent: {\n id: '?',\n value: renderedSearch,\n parent: varyPath\n }\n };\n return pageVaryPath;\n}\nexport function getPartialPageVaryPath(finalizedVaryPath) {\n // This is the inverse of finalizePageVaryPath.\n return finalizedVaryPath.parent.parent;\n}\nexport function finalizeMetadataVaryPath(pageRequestKey, renderedSearch, varyPath) {\n // The metadata \"segment\" is not a real segment because it doesn't exist in\n // the normal structure of the route tree, but in terms of caching, it\n // behaves like a page segment because it varies by all the same params as\n // a page.\n //\n // To keep the protocol for querying the server simple, the request key for\n // the metadata does not include any path information. It's unnecessary from\n // the server's perspective, because unlike page segments, there's only one\n // metadata response per URL, i.e. there's no need to distinguish multiple\n // parallel pages.\n //\n // However, this means the metadata request key is insufficient for\n // caching the the metadata in the client cache, because on the client we\n // use the request key to distinguish the metadata entry from all other\n // page's metadata entries.\n //\n // So instead we create a simulated request key based on the page segment.\n // Conceptually this is equivalent to the request key the server would have\n // assigned the metadata segment if it treated it as part of the actual\n // route structure.\n // If there are multiple parallel pages, we use whichever is the first one.\n // This is fine because the only difference between request keys for\n // different parallel pages are things like route groups and parallel\n // route slots. As long as it's always the same one, it doesn't matter.\n const pageVaryPath = {\n id: null,\n // Append the actual metadata request key to the page request key. Note\n // that we're not using a separate vary path part; it's unnecessary because\n // these are not conceptually separate inputs.\n value: pageRequestKey + HEAD_REQUEST_KEY,\n parent: {\n id: '?',\n value: renderedSearch,\n parent: varyPath\n }\n };\n return pageVaryPath;\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 // Only page segments (and the special \"metadata\" segment, which is treated\n // like a page segment for the purposes of caching) may contain search\n // params. There's no reason to include them in the vary path otherwise.\n if (tree.isPage) {\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. Clone\n // the end of the original vary path to replace the search params\n // with Fallback.\n //\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with Fallback\n const searchParamsVaryPath = originalVaryPath.parent;\n const pathParamsVaryPath = searchParamsVaryPath.parent;\n const patchedVaryPath = {\n id: null,\n value: originalVaryPath.value,\n parent: {\n id: '?',\n value: Fallback,\n parent: pathParamsVaryPath\n }\n };\n return patchedVaryPath;\n }\n }\n // The request does vary on search params. We don't need to modify anything.\n return originalVaryPath;\n}\nexport function clonePageVaryPathWithNewSearchParams(originalVaryPath, newSearch) {\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with newSearch\n const searchParamsVaryPath = originalVaryPath.parent;\n const clonedVaryPath = {\n id: null,\n value: originalVaryPath.value,\n parent: {\n id: '?',\n value: newSearch,\n parent: searchParamsVaryPath.parent\n }\n };\n return clonedVaryPath;\n}\nexport function getRenderedSearchFromVaryPath(varyPath) {\n const searchParams = varyPath.parent.value;\n return typeof searchParams === 'string' ? searchParams : null;\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 parent: original.parent === null ? null : getFulfilledSegmentVaryPath(original.parent, varyParams)\n };\n return clone;\n}\n\n//# sourceMappingURL=vary-path.js.map","import { useEffect } from 'react';\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url';\nexport function handleHardNavError(error) {\n if (error && 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 * 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)\n FetchStrategy[FetchStrategy[\"LoadingBoundary\"] = 0] = \"LoadingBoundary\";\n FetchStrategy[FetchStrategy[\"PPR\"] = 1] = \"PPR\";\n FetchStrategy[FetchStrategy[\"PPRRuntime\"] = 2] = \"PPRRuntime\";\n FetchStrategy[FetchStrategy[\"Full\"] = 3] = \"Full\";\n return FetchStrategy;\n}({});\n\n//# sourceMappingURL=types.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 { 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 } = 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) {\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 };\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 };\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 for (const entry of entries){\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 } = require('./app-router-instance');\n const appRouterState = getCurrentAppRouterState();\n if (appRouterState !== null) {\n const treeAtTimeOfPrefetch = appRouterState.tree;\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, treeAtTimeOfPrefetch, instance.fetchStrategy, priority, null);\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, treeAtTimeOfPrefetch, instance.fetchStrategy, priority);\n }\n }\n }\n}\nexport function pingVisibleLinks(nextUrl, tree) {\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 base 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, tree)) {\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, tree, instance.fetchStrategy, PrefetchPriority.Default, null);\n }\n}\n\n//# sourceMappingURL=links.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","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, 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, rsc, prefetchRsc, head, prefetchHead, dynamicStaleAt) {\n if (typeof window === 'undefined') {\n return;\n }\n const entry = {\n rsc,\n prefetchRsc,\n // TODO: These fields will be removed from both BFCacheEntry and\n // SegmentCacheEntry. The head has its own separate cache entry.\n head,\n prefetchHead,\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 };\n const isRevalidation = false;\n setInCacheMap(bfcacheMap, varyPath, entry, isRevalidation);\n}\nexport function writeHeadToBFCache(now, varyPath, head, prefetchHead, dynamicStaleAt) {\n // Read the special \"segment\" that represents the head data.\n writeToBFCache(now, varyPath, head, prefetchHead, null, null, dynamicStaleAt);\n}\n/**\n * Update the staleAt of an existing BFCache entry. Used after a dynamic\n * response arrives with a per-page stale time from `unstable_dynamicStaleTime`.\n * The per-page value is authoritative — it overrides whatever staleAt was set\n * by the default DYNAMIC_STALETIME_MS.\n */ export function updateBFCacheEntryStaleAt(varyPath, 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);\n if (entry !== null) {\n entry.staleAt = newStaleAt;\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);\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);\n}\n\n//# sourceMappingURL=bfcache.js.map","import { completeHardNavigation, navigate as navigateUsingSegmentCache } from '../../segment-cache/navigation';\nimport { getStaleTimeMs } from '../../segment-cache/cache';\nimport { FreshnessPolicy } from '../ppr-navigations';\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.cache, 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 // This segment has a runtime prefetch enabled (via unstable_instant with\n // prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.\n PrefetchHint[PrefetchHint[\"HasRuntimePrefetch\"] = 1] = \"HasRuntimePrefetch\";\n // This segment or one of its descendants has an instant config defined\n // (any truthy unstable_instant, regardless of prefetch mode). Propagates\n // upward so the root segment reflects the entire subtree.\n PrefetchHint[PrefetchHint[\"SubtreeHasInstant\"] = 2] = \"SubtreeHasInstant\";\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 the root layout of the application.\n PrefetchHint[PrefetchHint[\"IsRootLayout\"] = 16] = \"IsRootLayout\";\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 // at the end of its SegmentPrefetch[] array.\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 return PrefetchHint;\n}({});\n\n//# sourceMappingURL=app-router-types.js.map","/**\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 * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */ export const unstable_rethrow = typeof window === 'undefined' ? require('./unstable-rethrow.server').unstable_rethrow : require('./unstable-rethrow.browser').unstable_rethrow;\n\n//# sourceMappingURL=unstable-rethrow.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","import { PAGE_SEGMENT_KEY } from '../shared/lib/segment';\nimport { getCacheKeyForDynamicParam, parseDynamicParamFromURLPart, doesStaticSegmentAppearInURL, getRenderedPathname, getRenderedSearch } from './route-params';\nimport { createHrefFromUrl } from './components/router-reducer/create-href-from-url';\n// TODO: We should only have to export `normalizeFlightData`, however because the initial flight data\n// that gets passed to `createInitialRouterState` doesn't conform to the `FlightDataPath` type (it's missing the root segment)\n// we're currently exporting it so we can use it directly. This should be fixed as part of the unification of\n// the different ways we express `FlightSegmentPath`.\nexport function getFlightDataPartsFromPath(flightDataPath) {\n // Pick the last 4 items from the `FlightDataPath` to get the [tree, seedData, viewport, isHeadPartial].\n const flightDataPathLength = 4;\n // tree, seedData, and head are *always* the last three items in the `FlightDataPath`.\n const [tree, seedData, head, isHeadPartial] = flightDataPath.slice(-flightDataPathLength);\n // The `FlightSegmentPath` is everything except the last three items. For a root render, it won't be present.\n const segmentPath = flightDataPath.slice(0, -flightDataPathLength);\n return {\n // TODO: Unify these two segment path helpers. We are inconsistently pushing an empty segment (\"\")\n // to the start of the segment path in some places which makes it hard to use solely the segment path.\n // Look for \"// TODO-APP: remove ''\" in the codebase.\n pathToSegment: segmentPath.slice(0, -1),\n segmentPath,\n // if the `FlightDataPath` corresponds with the root, there'll be no segment path,\n // in which case we default to ''.\n segment: segmentPath[segmentPath.length - 1] ?? '',\n tree,\n seedData,\n head,\n isHeadPartial,\n isRootRender: flightDataPath.length === flightDataPathLength\n };\n}\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 Flight data sent by the server with the correct params parsed\n // 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 originalFlightDataPath = fallbackInitialRSCPayload.f[0];\n const originalFlightRouterState = originalFlightDataPath[0];\n const payload = {\n c: canonicalUrl.split('/'),\n q: renderedSearch,\n i: fallbackInitialRSCPayload.i,\n f: [\n [\n fillInFallbackFlightRouterState(originalFlightRouterState, renderedPathname, renderedSearch),\n originalFlightDataPath[1],\n originalFlightDataPath[2],\n originalFlightDataPath[2]\n ]\n ],\n m: fallbackInitialRSCPayload.m,\n G: fallbackInitialRSCPayload.G,\n S: fallbackInitialRSCPayload.S,\n h: fallbackInitialRSCPayload.h\n };\n if (fallbackInitialRSCPayload.b) {\n payload.b = fallbackInitialRSCPayload.b;\n }\n return payload;\n}\nfunction fillInFallbackFlightRouterState(flightRouterState, renderedPathname, renderedSearch) {\n const pathnameParts = renderedPathname.split('/').filter((p)=>p !== '');\n const index = 0;\n return fillInFallbackFlightRouterStateImpl(flightRouterState, renderedSearch, pathnameParts, index);\n}\nfunction fillInFallbackFlightRouterStateImpl(flightRouterState, renderedSearch, pathnameParts, pathnamePartsIndex) {\n const originalSegment = flightRouterState[0];\n let newSegment;\n let doesAppearInURL;\n if (typeof originalSegment === 'string') {\n newSegment = originalSegment;\n doesAppearInURL = doesStaticSegmentAppearInURL(originalSegment);\n } else {\n const paramName = originalSegment[0];\n const paramType = originalSegment[2];\n const staticSiblings = originalSegment[3];\n const paramValue = parseDynamicParamFromURLPart(paramType, pathnameParts, pathnamePartsIndex);\n const cacheKey = getCacheKeyForDynamicParam(paramValue, renderedSearch);\n newSegment = [\n paramName,\n cacheKey,\n paramType,\n staticSiblings\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 = flightRouterState[1];\n const newChildren = {};\n for(let key in children){\n const childFlightRouterState = children[key];\n newChildren[key] = fillInFallbackFlightRouterStateImpl(childFlightRouterState, renderedSearch, pathnameParts, childPathnamePartsIndex);\n }\n const newState = [\n newSegment,\n newChildren,\n null,\n flightRouterState[3],\n flightRouterState[4]\n ];\n return newState;\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}\nexport function normalizeFlightData(flightData) {\n // FlightData can be a string when the server didn't respond with a proper flight response,\n // or when a redirect happens, to signal to the client that it needs to perform an MPA navigation.\n if (typeof flightData === 'string') {\n return flightData;\n }\n return flightData.map((flightDataPath)=>getFlightDataPartsFromPath(flightDataPath));\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 // Everything else is used only by the client and is not needed for requests.\n return result;\n}\n/**\n * Strips client-only data from segments:\n * - Search parameters from __PAGE__ 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 // Strip search params from __PAGE__ segments\n if (segment.startsWith(PAGE_SEGMENT_KEY + '?')) {\n return PAGE_SEGMENT_KEY;\n }\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","import { PrefetchHint } from '../../../shared/lib/app-router-types';\nimport { matchSegment } from '../match-segments';\nimport { readOrCreateRouteCacheEntry, readOrCreateSegmentCacheEntry, fetchRouteOnCacheMiss, fetchSegmentOnCacheMiss, fetchInlinedSegmentsOnCacheMiss, EntryStatus, fetchSegmentPrefetchesUsingDynamicRequest, convertRouteTreeToFlightRouterState, readOrCreateRevalidatingSegmentEntry, upgradeToPendingSegment, overwriteRevalidatingSegmentCacheEntry, canNewFetchStrategyProvideMoreContent, attemptToFulfillDynamicSegmentFromBFCache, attemptToUpgradeSegmentFromBFCache } from './cache';\nimport { createCacheKey } from './cache-key';\nimport { FetchStrategy, PrefetchPriority } from './types';\nimport { getCurrentRouteCacheVersion, getCurrentSegmentCacheVersion } from './cache';\nimport { addSearchParamsIfPageSegment, PAGE_SEGMENT_KEY } from '../../../shared/lib/segment';\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 treeAtTimeOfPrefetch The app's current FlightRouterState\n * @param fetchStrategy Whether to prefetch dynamic data, in addition to\n * static data. This is used by `<Link prefetch={true}>`.\n * @param _onComplete Called when the prefetch task finishes. Testing API only.\n */ export function schedulePrefetchTask(key, treeAtTimeOfPrefetch, fetchStrategy, priority, onInvalidate, _onComplete) {\n // Spawn a new prefetch task\n const task = {\n key,\n treeAtTimeOfPrefetch,\n routeCacheVersion: getCurrentRouteCacheVersion(),\n segmentCacheVersion: getCurrentSegmentCacheVersion(),\n priority,\n phase: 1,\n hasBackgroundWork: false,\n spawnedRuntimePrefetches: null,\n fetchStrategy,\n sortId: sortIdCounter++,\n isCanceled: false,\n onInvalidate,\n _heapIndex: -1\n };\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n task._onComplete = _onComplete;\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 heapDelete(taskHeap, task);\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n // Call completion callback. In practice this shouldn't be reached for\n // test-initiated prefetches since cancellation is only used by the Link\n // component when elements scroll out of viewport.\n const onComplete = task._onComplete;\n task._onComplete = undefined;\n onComplete?.();\n }\n}\nexport function reschedulePrefetchTask(task, treeAtTimeOfPrefetch, 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 //\n // Note: _onComplete is not reset here because it's preserved on the same\n // task object. When the rescheduled task completes, the original callback\n // will still be invoked.\n // Un-cancel the task, in case it was previously canceled.\n task.isCanceled = false;\n task.phase = 1;\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.treeAtTimeOfPrefetch = treeAtTimeOfPrefetch;\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, tree) {\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.treeAtTimeOfPrefetch !== tree || 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 // 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 attempt. Reset them after each\n // iteration of the task queue.\n const hasBackgroundWork = task.hasBackgroundWork;\n task.hasBackgroundWork = 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 === 1) {\n // Finished prefetching the route tree. Proceed to prefetching\n // the segments.\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 if (process.env.__NEXT_EXPOSE_TESTING_API) {\n // Notify the Instant Navigation Testing API that the prefetch has\n // completed, so it can proceed with navigation.\n const onComplete = task._onComplete;\n task._onComplete = undefined;\n onComplete?.();\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 */ 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 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 !== 0) {\n // Do not prefetch segment data until we've entered the segment 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.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.SubtreeHasInstant) {\n // If `instant` is defined anywhere on the target route, ignore the\n // fetch strategy and switch to unified strategy used by Cache\n // 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 `instant` rather than the `cacheComponents`\n // flag is to support incremental adoption. `prefetch={true}` will\n // continue to work until you opt into `instant`.\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 pingStaticHead(now, task, route);\n const exitStatus = pingSharedPartOfCacheComponentsTree(now, task, route, task.treeAtTimeOfPrefetch, tree);\n if (exitStatus === 0) {\n // Child yielded without finishing.\n return 0;\n }\n const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches;\n if (spawnedRuntimePrefetches !== null) {\n // During the first pass, we discovered segments that require a\n // runtime prefetch. Do a second pass to construct a request tree.\n const spawnedEntries = new Map();\n pingRuntimeHead(now, task, route, spawnedEntries, FetchStrategy.PPRRuntime);\n const requestTree = pingRuntimePrefetches(now, task, route, tree, spawnedRuntimePrefetches, spawnedEntries);\n let needsDynamicRequest = spawnedEntries.size > 0;\n if (needsDynamicRequest) {\n // Perform a dynamic prefetch request and populate the cache with\n // the result.\n spawnPrefetchSubtask(fetchSegmentPrefetchesUsingDynamicRequest(task, route, FetchStrategy.PPRRuntime, requestTree, spawnedEntries));\n }\n }\n return 2;\n }\n case FetchStrategy.Full:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.LoadingBoundary:\n {\n // Prefetch multiple segments using a single dynamic 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 pingRuntimeHead(now, task, route, spawnedEntries, fetchStrategy);\n const dynamicRequestTree = diffRouteTreeAgainstCurrent(now, task, route, task.treeAtTimeOfPrefetch, tree, spawnedEntries, fetchStrategy);\n let needsDynamicRequest = spawnedEntries.size > 0;\n if (needsDynamicRequest) {\n spawnPrefetchSubtask(fetchSegmentPrefetchesUsingDynamicRequest(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}\nfunction pingStaticHead(now, task, route) {\n // The Head data for a page (metadata, viewport) is not really a route\n // segment, in the sense that it doesn't appear in the route tree. But we\n // store it in the cache as if it were, using a special key.\n pingStaticSegmentData(now, task, route, readOrCreateSegmentCacheEntry(now, FetchStrategy.PPR, route.metadata), task.key, route.metadata);\n}\nfunction pingRuntimeHead(now, task, route, spawnedEntries, fetchStrategy) {\n pingRouteTreeAndIncludeDynamicData(now, task, route, route.metadata, false, spawnedEntries, // When prefetching the head, there's no difference between Full\n // and LoadingBoundary\n fetchStrategy === FetchStrategy.LoadingBoundary ? FetchStrategy.Full : fetchStrategy);\n}\n// TODO: Rename dynamic -> runtime throughout this module\nfunction pingSharedPartOfCacheComponentsTree(now, task, route, oldTree, newTree) {\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 // start by prefetching each segment individually. Once we reach the \"new\"\n // part of the tree — the part that doesn't exist on the current page — we\n // may choose to switch to a runtime prefetch instead, based on the\n // information sent by the server in the route tree.\n //\n // The traversal starts in the \"shared\" part of the tree. Once we reach the\n // \"new\" part of the tree, we switch to a different traversal,\n // pingNewPartOfCacheComponentsTree.\n // Prefetch this segment's static data.\n const segment = readOrCreateSegmentCacheEntry(now, task.fetchStrategy, newTree);\n pingStaticSegmentData(now, task, route, segment, task.key, newTree);\n // Recursively ping the children.\n const oldTreeChildren = oldTree[1];\n const newTreeChildren = newTree.slots;\n if (newTreeChildren !== null) {\n for(const parallelRouteKey in newTreeChildren){\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return 0;\n }\n const newTreeChild = newTreeChildren[parallelRouteKey];\n const newTreeChildSegment = newTreeChild.segment;\n const oldTreeChild = oldTreeChildren[parallelRouteKey];\n const oldTreeChildSegment = oldTreeChild?.[0];\n let childExitStatus;\n if (oldTreeChildSegment !== undefined && doesCurrentSegmentMatchCachedSegment(route, newTreeChildSegment, oldTreeChildSegment)) {\n // We're still in the \"shared\" part of the tree.\n childExitStatus = pingSharedPartOfCacheComponentsTree(now, task, route, oldTreeChild, newTreeChild);\n } else {\n // We've entered the \"new\" part of the tree. Switch\n // traversal functions.\n childExitStatus = pingNewPartOfCacheComponentsTree(now, task, route, newTreeChild);\n }\n if (childExitStatus === 0) {\n // Child yielded without finishing.\n return 0;\n }\n }\n }\n return 2;\n}\nfunction pingNewPartOfCacheComponentsTree(now, task, route, tree) {\n // We're now prefetching in the \"new\" part of the tree, the part that doesn't\n // exist on the current page. (In other words, we're deeper than the\n // shared layouts.) Segments in here default to being prefetched statically.\n // However, if the server instructs us to, we may switch to a runtime\n // prefetch instead. Traverse the tree and check at each segment.\n if (tree.prefetchHints & PrefetchHint.HasRuntimePrefetch) {\n // This route has a runtime prefetch response. Since we're below the shared\n // layout, everything from this point should be prefetched using a single,\n // combined runtime request, rather than using per-segment static requests.\n // This is true even if some of the child segments are known to be fully\n // static — once we've decided to perform a runtime prefetch, we might as\n // well respond with the static segments in the same roundtrip. (That's how\n // regular navigations work, too.) We'll still skip over segments that are\n // already cached, though.\n //\n // It's the server's responsibility to set a reasonable value of\n // `hasRuntimePrefetch`. Currently it's user-defined, but eventually, the\n // server may send a value of `false` even if the user opts in, if it\n // determines during build that the route is always fully static. There are\n // more optimizations we can do once we implement fallback param\n // tracking, too.\n //\n // Use the task object to collect the segments that need a runtime prefetch.\n // This will signal to the outer task queue that a second traversal is\n // required to construct a request tree.\n if (task.spawnedRuntimePrefetches === null) {\n task.spawnedRuntimePrefetches = new Set([\n tree.requestKey\n ]);\n } else {\n task.spawnedRuntimePrefetches.add(tree.requestKey);\n }\n // Then exit the traversal without prefetching anything further.\n return 2;\n }\n // This segment should not be runtime prefetched. Prefetch its static data.\n const segment = readOrCreateSegmentCacheEntry(now, task.fetchStrategy, tree);\n pingStaticSegmentData(now, task, route, segment, task.key, tree);\n if (tree.slots !== null) {\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return 0;\n }\n // Recursively ping the children.\n for(const parallelRouteKey in tree.slots){\n const childTree = tree.slots[parallelRouteKey];\n const childExitStatus = pingNewPartOfCacheComponentsTree(now, task, route, childTree);\n if (childExitStatus === 0) {\n // Child yielded without finishing.\n return 0;\n }\n }\n }\n // This segment and all its children have finished prefetching.\n return 2;\n}\nfunction diffRouteTreeAgainstCurrent(now, task, route, oldTree, newTree, spawnedEntries, fetchStrategy) {\n // This is a single recursive traversal that does multiple things:\n // - Finds the parts of the target route (newTree) that are not part of\n // of the current page (oldTree) by diffing them, using the same algorithm\n // as a real navigation.\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 oldTreeChildren = oldTree[1];\n const newTreeChildren = newTree.slots;\n let requestTreeChildren = {};\n if (newTreeChildren !== null) {\n for(const parallelRouteKey in newTreeChildren){\n const newTreeChild = newTreeChildren[parallelRouteKey];\n const newTreeChildSegment = newTreeChild.segment;\n const oldTreeChild = oldTreeChildren[parallelRouteKey];\n const oldTreeChildSegment = oldTreeChild?.[0];\n if (oldTreeChildSegment !== undefined && doesCurrentSegmentMatchCachedSegment(route, newTreeChildSegment, oldTreeChildSegment)) {\n // This segment is already part of the current route. Keep traversing.\n const requestTreeChild = diffRouteTreeAgainstCurrent(now, task, route, oldTreeChild, newTreeChild, spawnedEntries, fetchStrategy);\n requestTreeChildren[parallelRouteKey] = requestTreeChild;\n } else {\n // This segment is not part of the current route. We're entering a\n // part of the tree that we need to prefetch (unless everything is\n // 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 dynamic 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 = (newTreeChild.prefetchHints & (PrefetchHint.SegmentHasLoadingBoundary | PrefetchHint.SubtreeHasLoadingBoundary)) !== 0;\n const requestTreeChild = subtreeHasLoadingBoundary ? pingPPRDisabledRouteTreeUpToLoadingBoundary(now, task, route, newTreeChild, null, spawnedEntries) : convertRouteTreeToFlightRouterState(newTreeChild);\n requestTreeChildren[parallelRouteKey] = requestTreeChild;\n break;\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 const requestTreeChild = pingRouteTreeAndIncludeDynamicData(now, task, route, newTreeChild, false, spawnedEntries, fetchStrategy);\n requestTreeChildren[parallelRouteKey] = requestTreeChild;\n break;\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 const requestTreeChild = pingRouteTreeAndIncludeDynamicData(now, task, route, newTreeChild, false, spawnedEntries, fetchStrategy);\n requestTreeChildren[parallelRouteKey] = requestTreeChild;\n break;\n }\n default:\n fetchStrategy;\n }\n }\n }\n }\n const requestTree = [\n newTree.segment,\n requestTreeChildren,\n null,\n null\n ];\n return requestTree;\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.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 spawnedEntries.set(tree.requestKey, 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 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 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 in tree.slots){\n const childTree = tree.slots[parallelRouteKey];\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 return requestTree;\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, // 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, tree);\n if (fulfilled !== null) {\n break;\n }\n }\n spawnedSegment = pingFullSegmentRevalidation(now, 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, tree, fetchStrategy);\n }\n break;\n }\n default:\n segment;\n }\n const requestTreeChildren = {};\n if (tree.slots !== null) {\n for(const parallelRouteKey in tree.slots){\n const childTree = tree.slots[parallelRouteKey];\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 return requestTree;\n}\nfunction pingRuntimePrefetches(now, task, route, tree, spawnedRuntimePrefetches, spawnedEntries) {\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.PPRRuntime);\n }\n let requestTreeChildren = {};\n const slots = tree.slots;\n if (slots !== null) {\n for(const parallelRouteKey in slots){\n const childTree = slots[parallelRouteKey];\n requestTreeChildren[parallelRouteKey] = pingRuntimePrefetches(now, task, route, childTree, spawnedRuntimePrefetches, spawnedEntries);\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 return requestTree;\n}\nfunction pingStaticSegmentData(now, task, route, segment, routeKey, tree) {\n switch(segment.status){\n case EntryStatus.Empty:\n if (process.env.__NEXT_PREFETCH_INLINING) {\n // All segment data for this route is bundled into a single\n // /_inlined response. Walk the full route tree to collect all\n // Empty segments, upgrade them to Pending, and spawn one\n // bundled request. Subsequent calls for other segments in the\n // same tree will see them as Pending and skip.\n const inlinedEntries = collectInlinedEntries(now, route);\n if (inlinedEntries.size > 0) {\n spawnPrefetchSubtask(fetchInlinedSegmentsOnCacheMiss(route, routeKey, route.tree, inlinedEntries));\n }\n break;\n }\n // Upgrade to Pending so we know there's already a request in progress\n spawnPrefetchSubtask(fetchSegmentOnCacheMiss(route, upgradeToPendingSegment(segment, FetchStrategy.PPR), routeKey, tree));\n break;\n case EntryStatus.Pending:\n {\n // There's already a request in progress. Depending on what kind of\n // request it is, we may want to revalidate it.\n switch(segment.fetchStrategy){\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full:\n break;\n case FetchStrategy.LoadingBoundary:\n // There's a pending request, but because it's using the old\n // prefetching strategy, we can't be sure if it will be fulfilled by\n // the response — it might be inside the loading boundary. Perform\n // a revalidation, but because it's speculative, wait to do it at\n // background priority.\n if (background(task)) {\n // TODO: Instead of speculatively revalidating, consider including\n // `hasLoading` in the route tree prefetch response.\n pingPPRSegmentRevalidation(now, route, routeKey, tree);\n }\n break;\n default:\n segment.fetchStrategy;\n }\n break;\n }\n case EntryStatus.Rejected:\n {\n // The existing entry in the cache was rejected. Depending on how it\n // was originally fetched, we may or may not want to revalidate it.\n switch(segment.fetchStrategy){\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full:\n break;\n case FetchStrategy.LoadingBoundary:\n // There's a rejected entry, but it was fetched using the loading\n // boundary strategy. So the reason it wasn't returned by the server\n // might just be because it was inside a loading boundary. Or because\n // there was a dynamic rewrite. Revalidate it using the per-\n // segment strategy.\n //\n // Because a rejected segment will definitely prevent the segment (and\n // all of its children) from rendering, we perform this revalidation\n // immediately instead of deferring it to a background task.\n pingPPRSegmentRevalidation(now, route, routeKey, tree);\n break;\n default:\n segment.fetchStrategy;\n }\n break;\n }\n case EntryStatus.Fulfilled:\n break;\n default:\n segment;\n }\n// Segments do not have dependent tasks, so once the prefetch is initiated,\n// there's nothing else for us to do (except write the server data into the\n// entry, which is handled by `fetchSegmentOnCacheMiss`).\n}\n/**\n * Walks the RouteTree (including the head metadata) and collects any segments\n * that are still Empty into a Map, upgrading them to Pending. These entries\n * will be fulfilled by the inlined prefetch response.\n */ function collectInlinedEntries(now, route) {\n const entries = new Map();\n collectInlinedEntriesImpl(now, route.tree, entries);\n // Also collect the head/metadata entry.\n const headEntry = readOrCreateSegmentCacheEntry(now, FetchStrategy.PPR, route.metadata);\n if (headEntry.status === EntryStatus.Empty) {\n entries.set(route.metadata.requestKey, upgradeToPendingSegment(headEntry, FetchStrategy.PPR));\n }\n return entries;\n}\nfunction collectInlinedEntriesImpl(now, tree, entries) {\n const entry = readOrCreateSegmentCacheEntry(now, FetchStrategy.PPR, tree);\n if (entry.status === EntryStatus.Empty) {\n entries.set(tree.requestKey, upgradeToPendingSegment(entry, FetchStrategy.PPR));\n }\n if (tree.slots !== null) {\n for(const parallelRouteKey in tree.slots){\n collectInlinedEntriesImpl(now, tree.slots[parallelRouteKey], entries);\n }\n }\n}\nfunction pingPPRSegmentRevalidation(now, route, routeKey, tree) {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(now, FetchStrategy.PPR, tree);\n switch(revalidatingSegment.status){\n case EntryStatus.Empty:\n // Spawn a prefetch request. The fetch function handles upserting\n // the entry at the correct fulfilled vary path upon completion.\n spawnPrefetchSubtask(fetchSegmentOnCacheMiss(route, upgradeToPendingSegment(revalidatingSegment, FetchStrategy.PPR), routeKey, tree));\n break;\n case EntryStatus.Pending:\n break;\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n break;\n default:\n revalidatingSegment;\n }\n}\nfunction pingFullSegmentRevalidation(now, tree, fetchStrategy) {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(now, fetchStrategy, tree);\n if (revalidatingSegment.status === EntryStatus.Empty) {\n // During a Full/PPRRuntime prefetch, a single dynamic request is made for all the\n // segments that we need. So we don't initiate a request here directly. By\n // returning a pending entry from this function, it signals to the caller\n // that this segment should be included in the request that's sent to\n // the server.\n const pendingSegment = upgradeToPendingSegment(revalidatingSegment, fetchStrategy);\n // The upsert is handled by fulfillEntrySpawnedByRuntimePrefetch\n // when the dynamic prefetch 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, fetchStrategy, tree);\n const pendingSegment = upgradeToPendingSegment(emptySegment, fetchStrategy);\n // The upsert is handled by fulfillEntrySpawnedByRuntimePrefetch\n // when the dynamic prefetch 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 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}\nfunction doesCurrentSegmentMatchCachedSegment(route, currentSegment, cachedSegment) {\n if (cachedSegment === PAGE_SEGMENT_KEY) {\n // In the FlightRouterState stored by the router, the page segment has the\n // rendered search params appended to the name of the segment. In the\n // prefetch cache, however, this is stored separately. So, when comparing\n // the router's current FlightRouterState to the cached FlightRouterState,\n // we need to make sure we compare both parts of the segment.\n // TODO: This is not modeled clearly. We use the same type,\n // FlightRouterState, for both the CacheNode tree _and_ the prefetch cache\n // _and_ the server response format, when conceptually those are three\n // different things and treated in different ways. We should encode more of\n // this information into the type design so mistakes are less likely.\n return currentSegment === addSearchParamsIfPageSegment(PAGE_SEGMENT_KEY, Object.fromEntries(new URLSearchParams(route.renderedSearch)));\n }\n // Non-page segments are compared using the same function as the server\n return matchSegment(cachedSegment, currentSegment);\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","/**\n * Vary Params Decoding\n *\n * This module is shared between server and client.\n */ /**\n * Synchronously reads vary params from a thenable.\n *\n * By the time this is called (client-side or in collectSegmentData), the\n * thenable should already be fulfilled because the Flight stream has been\n * fully received. We check the status synchronously to avoid unnecessary\n * microtasks.\n *\n * Returns null if the thenable is still pending (which shouldn't happen in\n * normal operation - it indicates the server failed to track vary params).\n */ export function readVaryParams(thenable) {\n // Attach a no-op listener to force Flight to synchronously resolve the\n // thenable. When a thenable arrives from the Flight stream, it may be in an\n // intermediate 'resolved_model' state (data received but not unwrapped).\n // Calling .then() triggers Flight to transition it to 'fulfilled', making\n // the value available synchronously. React uses this same optimization\n // internally to avoid unnecessary microtasks.\n thenable.then(noop);\n // If the thenable is still not 'fulfilled' after calling .then(), the server\n // failed to resolve it before the stream ended. Treat as unknown.\n if (thenable.status !== 'fulfilled') {\n return null;\n }\n return thenable.value;\n}\nconst noop = ()=>{};\n\n//# sourceMappingURL=vary-params-decoding.js.map","import { readVaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding';\nimport { NEXT_DID_POSTPONE_HEADER, NEXT_INSTANT_PREFETCH_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 } from '../router-reducer/fetch-server-response';\nimport { pingPrefetchTask, isPrefetchTaskDirty } from './scheduler';\nimport { getRouteVaryPath, getFulfilledRouteVaryPath, getFulfilledSegmentVaryPath, getSegmentVaryPathForRequest, appendLayoutVaryPath, finalizeLayoutVaryPath, finalizePageVaryPath, clonePageVaryPathWithNewSearchParams, finalizeMetadataVaryPath, getPartialPageVaryPath, getPartialLayoutVaryPath, getRenderedSearchFromVaryPath } from './vary-path';\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url';\nimport { createCacheKey as createPrefetchRequestKey } from './cache-key';\nimport { doesStaticSegmentAppearInURL, getCacheKeyForDynamicParam, getRenderedPathname, getRenderedSearch, parseDynamicParamFromURLPart } from '../../route-params';\nimport { createCacheMap, getFromCacheMap, setInCacheMap, setSizeInCacheMap, deleteFromCacheMap, isValueExpired } from './cache-map';\nimport { appendSegmentRequestKeyPart, convertSegmentPathToStaticExportFilename, createSegmentRequestKeyPart, HEAD_REQUEST_KEY, ROOT_SEGMENT_REQUEST_KEY } from '../../../shared/lib/segment-cache/segment-value-encoding';\nimport { normalizeFlightData, prepareFlightRouterStateForRequest } from '../../flight-data-helpers';\nimport { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer';\nimport { pingVisibleLinks } from '../links';\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment';\nimport { FetchStrategy } from './types';\nimport { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers';\nimport { readFromBFCache, UnknownDynamicStaleTime } from './bfcache';\nimport { discoverKnownRoute, matchKnownRoute } from './optimistic-routes';\nimport { convertServerPatchToFullTree } from './navigation';\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/**\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 */ 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}({});\nconst isOutputExportMode = process.env.NODE_ENV === 'production' && process.env.__NEXT_CONFIG_OUTPUT === 'export';\nconst MetadataOnlyRequestTree = [\n '',\n {},\n null,\n 'metadata-only'\n];\nlet routeCacheMap = createCacheMap();\nlet 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, tree) {\n currentRouteCacheVersion++;\n currentSegmentCacheVersion++;\n pingVisibleLinks(nextUrl, tree);\n pingInvalidationListeners(nextUrl, tree);\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, tree) {\n currentRouteCacheVersion++;\n pingVisibleLinks(nextUrl, tree);\n pingInvalidationListeners(nextUrl, tree);\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, tree) {\n currentSegmentCacheVersion++;\n pingVisibleLinks(nextUrl, tree);\n pingInvalidationListeners(nextUrl, tree);\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, tree) {\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, tree)) {\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);\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(key.pathname, key.search);\n }\n return null;\n}\nexport function readSegmentCacheEntry(now, varyPath) {\n const isRevalidation = false;\n return getFromCacheMap(now, getCurrentSegmentCacheVersion(), segmentCacheMap, varyPath, isRevalidation);\n}\nfunction readRevalidatingSegmentCacheEntry(now, varyPath) {\n const isRevalidation = true;\n return getFromCacheMap(now, getCurrentSegmentCacheVersion(), segmentCacheMap, varyPath, isRevalidation);\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: 0,\n blockedTasks: null,\n tree: null,\n metadata: 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 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 !== 2) {\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 : 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.tree, optimisticRenderedSearch);\n const optimisticMetadataTree = deprecated_createOptimisticRouteTree(routeWithNoSearchParams.metadata, optimisticRenderedSearch);\n // Clone the base route tree, and override the relevant fields with our\n // optimistic values.\n const optimisticEntry = {\n canonicalUrl: optimisticCanonicalUrl,\n status: 2,\n // This isn't cloned because it's instance-specific\n blockedTasks: null,\n tree: optimisticRouteTree,\n metadata: optimisticMetadataTree,\n couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,\n supportsPerSegmentPrefetching: routeWithNoSearchParams.supportsPerSegmentPrefetching,\n hasDynamicRewrite: routeWithNoSearchParams.hasDynamicRewrite,\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 = {};\n for(const parallelRouteKey in originalSlots){\n const childTree = originalSlots[parallelRouteKey];\n clonedSlots[parallelRouteKey] = deprecated_createOptimisticRouteTree(childTree, newRenderedSearch);\n }\n }\n // We only need to clone the vary path if the route is a page.\n if (tree.isPage) {\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n refreshState: tree.refreshState,\n varyPath: clonePageVaryPathWithNewSearchParams(tree.varyPath, newRenderedSearch),\n isPage: true,\n slots: clonedSlots,\n prefetchHints: tree.prefetchHints\n };\n }\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n refreshState: tree.refreshState,\n varyPath: tree.varyPath,\n isPage: false,\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, fetchStrategy, tree) {\n const existingEntry = readSegmentCacheEntry(now, 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 = false;\n setInCacheMap(segmentCacheMap, varyPathForRequest, pendingEntry, isRevalidation);\n return pendingEntry;\n}\nexport function readOrCreateRevalidatingSegmentEntry(now, 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, 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(segmentCacheMap, varyPathForRequest, pendingEntry, isRevalidation);\n return pendingEntry;\n}\nexport function overwriteRevalidatingSegmentCacheEntry(now, 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(segmentCacheMap, varyPathForRequest, pendingEntry, isRevalidation);\n return pendingEntry;\n}\nexport function upsertSegmentEntry(now, varyPath, candidateEntry) {\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 = readSegmentCacheEntry(now, varyPath);\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 (// We fetched the new segment using a different, less specific fetch strategy\n // than the segment we already have in the cache, so it can't 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 // We're going to leave revalidating entry in the cache so that it doesn't\n // get revalidated again unnecessarily. Downgrade the Fulfilled entry to\n // Rejected and null out the data so it can be garbage collected. We leave\n // `staleAt` intact to prevent subsequent revalidation attempts only until\n // the entry expires.\n const rejectedEntry = candidateEntry;\n rejectedEntry.status = 3;\n rejectedEntry.rsc = null;\n return null;\n }\n // Evict the existing entry from the cache.\n deleteFromCacheMap(existingEntry);\n }\n const isRevalidation = false;\n setInCacheMap(segmentCacheMap, varyPath, candidateEntry, isRevalidation);\n return candidateEntry;\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: 0,\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 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 = 1;\n pendingEntry.fetchStrategy = fetchStrategy;\n if (fetchStrategy === FetchStrategy.Full) {\n // We can assume the response will contain the full segment data. Set this\n // to false so we know it's OK to omit this segment from any navigation\n // requests that may happen while the data is still pending.\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);\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, 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);\n const segmentVaryPath = getSegmentVaryPathForRequest(FetchStrategy.Full, tree);\n const upserted = upsertSegmentEntry(now, segmentVaryPath, newEntry);\n if (upserted !== null && upserted.status === 2) {\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}\nexport function createMetadataRouteTree(metadataVaryPath) {\n // The Head is not actually part of the route tree, but other than that, it's\n // fetched and cached like a segment. Some functions expect a RouteTree\n // object, so rather than fork the logic in all those places, we use this\n // \"fake\" one.\n const metadata = {\n requestKey: HEAD_REQUEST_KEY,\n segment: HEAD_REQUEST_KEY,\n refreshState: null,\n varyPath: metadataVaryPath,\n // The metadata isn't really a \"page\" (though it isn't really a \"segment\"\n // either) but for the purposes of how this field is used, it behaves like\n // one. If this logic ever gets more complex we can change this to an enum.\n isPage: true,\n slots: null,\n prefetchHints: 0\n };\n return metadata;\n}\nexport function fulfillRouteCacheEntry(now, entry, tree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching) {\n // Get the rendered search from the vary path\n const renderedSearch = getRenderedSearchFromVaryPath(metadataVaryPath) ?? '';\n const fulfilledEntry = entry;\n fulfilledEntry.status = 2;\n fulfilledEntry.tree = tree;\n fulfilledEntry.metadata = createMetadataRouteTree(metadataVaryPath);\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 fulfilledEntry.staleAt = now + STATIC_STALETIME_MS;\n fulfilledEntry.couldBeIntercepted = couldBeIntercepted;\n fulfilledEntry.canonicalUrl = canonicalUrl;\n fulfilledEntry.renderedSearch = renderedSearch;\n fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching;\n fulfilledEntry.hasDynamicRewrite = false;\n pingBlockedTasks(entry);\n return fulfilledEntry;\n}\nexport function writeRouteIntoCache(now, pathname, nextUrl, tree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching) {\n const pendingEntry = createDetachedRouteCacheEntry();\n const fulfilledEntry = fulfillRouteCacheEntry(now, pendingEntry, tree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);\n const renderedSearch = fulfilledEntry.renderedSearch;\n const varyPath = getFulfilledRouteVaryPath(pathname, renderedSearch, nextUrl, couldBeIntercepted);\n const isRevalidation = false;\n setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation);\n return fulfilledEntry;\n}\n/**\n * Marks a route cache entry as having a dynamic rewrite. Called when we\n * discover that a route pattern has dynamic rewrite behavior - i.e., we used\n * an optimistic route tree for prediction, but the server responded with a\n * different rendered pathname.\n *\n * Once marked, attempts to use this entry as a template for prediction will\n * bail out to server resolution.\n */ export function markRouteEntryAsDynamicRewrite(entry) {\n entry.hasDynamicRewrite = true;\n// Note: The caller is responsible for also calling invalidateRouteCacheEntries\n// to invalidate other entries that may have been derived from this template\n// before we knew it had a dynamic rewrite.\n}\nfunction fulfillSegmentCacheEntry(segmentCacheEntry, rsc, staleAt, isPartial) {\n const fulfilledEntry = segmentCacheEntry;\n fulfilledEntry.status = 2;\n fulfilledEntry.rsc = rsc;\n fulfilledEntry.staleAt = staleAt;\n fulfilledEntry.isPartial = isPartial;\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 return fulfilledEntry;\n}\nfunction rejectRouteCacheEntry(entry, staleAt) {\n const rejectedEntry = entry;\n rejectedEntry.status = 3;\n rejectedEntry.staleAt = staleAt;\n pingBlockedTasks(entry);\n}\nfunction rejectSegmentCacheEntry(entry, staleAt) {\n const rejectedEntry = entry;\n rejectedEntry.status = 3;\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}\nfunction convertRootTreePrefetchToRouteTree(rootTree, renderedPathname, renderedSearch, acc) {\n // Remove trailing and leading slashes\n const pathnameParts = renderedPathname.split('/').filter((p)=>p !== '');\n const index = 0;\n const rootSegment = ROOT_SEGMENT_REQUEST_KEY;\n return convertTreePrefetchToRouteTree(rootTree.tree, rootSegment, null, ROOT_SEGMENT_REQUEST_KEY, pathnameParts, index, renderedSearch, acc);\n}\nfunction convertTreePrefetchToRouteTree(prefetch, segment, partialVaryPath, requestKey, pathnameParts, pathnamePartsIndex, renderedSearch, acc) {\n // Converts the route tree sent by the server into the format used by the\n // cache. The cached version of the tree includes additional fields, such as a\n // cache key for each segment. Since this is frequently accessed, we compute\n // it once instead of on every access. This same cache key is also used to\n // request the segment from the server.\n let slots = null;\n let isPage;\n let varyPath;\n const prefetchSlots = prefetch.slots;\n if (prefetchSlots !== null) {\n isPage = false;\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath);\n slots = {};\n for(let parallelRouteKey in prefetchSlots){\n const childPrefetch = prefetchSlots[parallelRouteKey];\n const childSegmentName = childPrefetch.name;\n const childParam = childPrefetch.param;\n let childDoesAppearInURL;\n let childSegment;\n let childPartialVaryPath;\n if (childParam !== null) {\n // This segment is parameterized. Get the param from the pathname.\n const childParamValue = parseDynamicParamFromURLPart(childParam.type, pathnameParts, pathnamePartsIndex);\n // Assign a cache key to the segment, based on the param value. In the\n // pre-Segment Cache implementation, the server computes this and sends\n // it in the body of the response. In the Segment Cache implementation,\n // the server sends an empty string and we fill it in here.\n // TODO: We're intentionally not adding the search param to page\n // segments here; it's tracked separately and added back during a read.\n // This would clearer if we waited to construct the segment until it's\n // read from the cache, since that's effectively what we're\n // doing anyway.\n const childParamKey = // The server omits this field from the prefetch response when\n // cacheComponents is enabled.\n childParam.key !== null ? childParam.key : getCacheKeyForDynamicParam(childParamValue, '');\n childPartialVaryPath = appendLayoutVaryPath(partialVaryPath, childParamKey, childSegmentName);\n childSegment = [\n childSegmentName,\n childParamKey,\n childParam.type,\n childParam.siblings\n ];\n childDoesAppearInURL = true;\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n childPartialVaryPath = partialVaryPath;\n childSegment = childSegmentName;\n childDoesAppearInURL = doesStaticSegmentAppearInURL(childSegmentName);\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 = childDoesAppearInURL ? pathnamePartsIndex + 1 : pathnamePartsIndex;\n const childRequestKeyPart = createSegmentRequestKeyPart(childSegment);\n const childRequestKey = appendSegmentRequestKeyPart(requestKey, parallelRouteKey, childRequestKeyPart);\n slots[parallelRouteKey] = convertTreePrefetchToRouteTree(childPrefetch, childSegment, childPartialVaryPath, childRequestKey, pathnameParts, childPathnamePartsIndex, renderedSearch, acc);\n }\n } else {\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true;\n varyPath = finalizePageVaryPath(requestKey, renderedSearch, partialVaryPath);\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(requestKey, renderedSearch, partialVaryPath);\n }\n } else {\n // This is a layout segment.\n isPage = false;\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath);\n }\n }\n return {\n requestKey,\n segment,\n refreshState: null,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. The fix would be to\n // create separate constructors and call the appropriate one from each of\n // the branches above. Just seems a bit overkill only for one field so I'll\n // leave it as-is for now. If isPage were wrong it would break the behavior\n // and we'd catch it quickly, anyway.\n varyPath: varyPath,\n isPage: isPage,\n slots,\n prefetchHints: prefetch.prefetchHints\n };\n}\nexport function convertRootFlightRouterStateToRouteTree(flightRouterState, renderedSearch, acc) {\n return convertFlightRouterStateToRouteTree(flightRouterState, ROOT_SEGMENT_REQUEST_KEY, null, renderedSearch, acc);\n}\nexport function convertReusedFlightRouterStateToRouteTree(parentRouteTree, parallelRouteKey, flightRouterState, renderedSearch, acc) {\n // Create a RouteTree for a FlightRouterState that was reused from an older\n // route. This happens during a navigation when a parallel route slot does not\n // match the target route; we reuse whatever slot was already active.\n // Unlike a FlightRouterState, the RouteTree type contains backreferences to\n // the parent segments. Append the vary path to the parent's vary path.\n const parentPartialVaryPath = parentRouteTree.isPage ? getPartialPageVaryPath(parentRouteTree.varyPath) : getPartialLayoutVaryPath(parentRouteTree.varyPath);\n const segment = flightRouterState[0];\n // And the request key.\n const parentRequestKey = parentRouteTree.requestKey;\n const requestKeyPart = createSegmentRequestKeyPart(segment);\n const requestKey = appendSegmentRequestKeyPart(parentRequestKey, parallelRouteKey, requestKeyPart);\n return convertFlightRouterStateToRouteTree(flightRouterState, requestKey, parentPartialVaryPath, renderedSearch, acc);\n}\nfunction convertFlightRouterStateToRouteTree(flightRouterState, requestKey, parentPartialVaryPath, parentRenderedSearch, acc) {\n const originalSegment = flightRouterState[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 const renderedSearch = refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch;\n let segment;\n let partialVaryPath;\n let isPage;\n let varyPath;\n if (Array.isArray(originalSegment)) {\n isPage = false;\n const paramCacheKey = originalSegment[1];\n const paramName = originalSegment[0];\n partialVaryPath = appendLayoutVaryPath(parentPartialVaryPath, paramCacheKey, paramName);\n varyPath = finalizeLayoutVaryPath(requestKey, 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 isPage = true;\n // The navigation implementation expects the search params to be included\n // in the segment. However, in the case of a static response, the search\n // params are omitted. So the client needs to add them back in when reading\n // from the Segment Cache.\n //\n // For consistency, we'll do this for dynamic responses, too.\n //\n // TODO: We should move search params out of FlightRouterState and handle\n // them entirely on the client, similar to our plan for dynamic params.\n segment = PAGE_SEGMENT_KEY;\n varyPath = finalizePageVaryPath(requestKey, renderedSearch, partialVaryPath);\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(requestKey, renderedSearch, partialVaryPath);\n }\n } else {\n // This is a layout segment.\n isPage = false;\n segment = originalSegment;\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath);\n }\n }\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 = {\n [parallelRouteKey]: childTree\n };\n } else {\n slots[parallelRouteKey] = childTree;\n }\n }\n return {\n requestKey,\n segment,\n refreshState,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. The fix would be to\n // create separate constructors and call the appropriate one from each of\n // the branches above. Just seems a bit overkill only for one field so I'll\n // leave it as-is for now. If isPage were wrong it would break the behavior\n // and we'd catch it quickly, anyway.\n varyPath: varyPath,\n isPage: isPage,\n slots,\n prefetchHints: flightRouterState[4] ?? 0\n };\n}\nexport function convertRouteTreeToFlightRouterState(routeTree) {\n const parallelRoutes = {};\n if (routeTree.slots !== null) {\n for(const parallelRouteKey in routeTree.slots){\n parallelRoutes[parallelRouteKey] = convertRouteTreeToFlightRouterState(routeTree.slots[parallelRouteKey]);\n }\n }\n const flightRouterState = [\n routeTree.segment,\n parallelRoutes,\n null,\n null\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 // Tell the server to perform a static pre-render for the Instant Navigation\n // Testing API. Static pre-renders don't normally happen during development.\n addInstantPrefetchHeaderIfLocked(headers);\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() + 10 * 1000);\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 || // 204 is a Cache miss. Though theoretically this shouldn't happen when\n // PPR is enabled, because we always respond to route tree requests, even\n // if it needs to be blockingly generated on demand.\n response.status === 204 || !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() + 10 * 1000);\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 // This checks whether the response was served from the per-segment cache,\n // rather than the old prefetching flow. If it fails, it implies that PPR\n // is disabled on this route.\n const routeIsPPREnabled = 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 if (routeIsPPREnabled) {\n const { stream: prefetchStream, size: responseSize } = await createNonTaskyPrefetchResponseStream(response.body);\n closed.resolve();\n setSizeInCacheMap(entry, responseSize);\n const serverData = await createFromNextReadableStream(prefetchStream, headers, {\n allowPartialStream: true\n });\n if ((response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.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 // TODO: We should cache the fact that this is an MPA navigation.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000);\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.\n const renderedPathname = getRenderedPathname(response);\n const renderedSearch = getRenderedSearch(response);\n // Convert the server-sent data 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 };\n const routeTree = convertRootTreePrefetchToRouteTree(serverData, renderedPathname, renderedSearch, acc);\n const metadataVaryPath = acc.metadataVaryPath;\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000);\n return null;\n }\n discoverKnownRoute(Date.now(), pathname, nextUrl, entry, routeTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, routeIsPPREnabled, false // hasDynamicRewrite\n );\n } else {\n // PPR is not enabled for this route. The server responds with a\n // different format (FlightRouterState) that we need to convert.\n // TODO: We will unify the responses eventually. I'm keeping the types\n // separate for now because FlightRouterState has so many\n // overloaded concerns.\n const { stream: prefetchStream, size: responseSize } = await createNonTaskyPrefetchResponseStream(response.body);\n closed.resolve();\n setSizeInCacheMap(entry, responseSize);\n const serverData = await createFromNextReadableStream(prefetchStream, headers, {\n allowPartialStream: true\n });\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() + 10 * 1000);\n return null;\n }\n // Read head vary params synchronously. Individual segments carry their\n // own thenables in CacheNodeSeedData.\n const headVaryParamsThenable = serverData.h;\n const headVaryParams = headVaryParamsThenable !== null ? readVaryParams(headVaryParamsThenable) : null;\n writeDynamicTreeResponseIntoCache(Date.now(), // The non-PPR response format is what we'd get if we prefetched these segments\n // using the LoadingBoundary fetch strategy, so mark their cache entries accordingly.\n FetchStrategy.LoadingBoundary, response, serverData, entry, couldBeIntercepted, canonicalUrl, routeIsPPREnabled, headVaryParams, pathname, nextUrl);\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, Date.now() + 10 * 1000);\n return null;\n }\n}\nexport async function fetchSegmentOnCacheMiss(route, segmentCacheEntry, routeKey, tree) {\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 // 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 const requestKey = tree.requestKey;\n const normalizedRequestKey = requestKey === ROOT_SEGMENT_REQUEST_KEY ? // 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 '/_index' : requestKey;\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 // Tell the server to perform a static pre-render for the Instant Navigation\n // Testing API. Static pre-renders don't normally happen during development.\n addInstantPrefetchHeaderIfLocked(headers);\n const requestUrl = isOutputExportMode ? addSegmentPathToUrlInOutputExportMode(url, normalizedRequestKey) : url;\n try {\n const response = await fetchPrefetchResponse(requestUrl, headers);\n if (!response || !response.ok || response.status === 204 || // Cache miss\n // This checks whether the response was served from the per-segment cache,\n // rather than the old prefetching flow. If it fails, it implies that PPR\n // is disabled on this route. Theoretically this should never happen\n // because we only issue requests for segments once we've verified that\n // the route supports PPR.\n response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' && // In output: \"export\" mode, we can't rely on response headers. But if\n // we receive a well-formed response, we can assume it's a static\n // response, because all data is static in this mode.\n !isOutputExportMode || !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 rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000);\n return null;\n }\n // See TODO in fetchRouteOnCacheMiss about removing `closed` for\n // buffered prefetch paths.\n const closed = createPromiseWithResolvers();\n const { stream: prefetchStream, size: responseSize } = await createNonTaskyPrefetchResponseStream(response.body);\n closed.resolve();\n setSizeInCacheMap(segmentCacheEntry, responseSize);\n const serverData = await createFromNextReadableStream(prefetchStream, headers, {\n allowPartialStream: true\n });\n if ((response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.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 rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000);\n return null;\n }\n const now = Date.now();\n const staleAt = now + getStaleTimeMs(serverData.staleTime);\n const fulfilledEntry = fulfillSegmentCacheEntry(segmentCacheEntry, serverData.rsc, staleAt, serverData.isPartial);\n // If the server tells us which params the segment varies by, we can re-key\n // the entry to a more generic vary path. This allows the entry to be reused\n // across different param values for params that the segment doesn't\n // actually depend on.\n const varyParams = serverData.varyParams;\n const fulfilledVaryPath = process.env.__NEXT_VARY_PARAMS && varyParams !== null ? getFulfilledSegmentVaryPath(tree.varyPath, varyParams) : getSegmentVaryPathForRequest(segmentCacheEntry.fetchStrategy, tree);\n // Re-key and upsert the entry at the fulfilled vary path. This ensures\n // the entry is stored at the most generic path possible based on which\n // params the segment actually depends on.\n upsertSegmentEntry(now, fulfilledVaryPath, fulfilledEntry);\n return {\n value: fulfilledEntry,\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n closed: closed.promise\n };\n } catch (error) {\n // Either the connection itself failed, or something bad happened while\n // decoding the response.\n rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000);\n return null;\n }\n}\n// TODO: The inlined prefetch flow below is temporary. Eventually, inlining\n// will be the default behavior controlled by a size heuristic rather than a\n// boolean flag. At that point, the per-segment and inlined fetch paths will\n// merge, and these separate functions will be removed.\n//\n// The call site in the scheduler is guarded by\n// process.env.__NEXT_PREFETCH_INLINING, so these functions are\n// dead-code-eliminated from the client bundle when the feature is disabled.\nexport async function fetchInlinedSegmentsOnCacheMiss(route, routeKey, tree, spawnedEntries) {\n // When prefetch inlining is enabled, all segment data for a route is bundled\n // into a single /_inlined response instead of individual per-segment\n // requests. This function fetches that response and walks the tree to fill\n // all segment cache entries at once.\n const url = new URL(route.canonicalUrl, location.origin);\n const nextUrl = routeKey.nextUrl;\n const headers = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/' + PAGE_SEGMENT_KEY\n };\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl;\n }\n addInstantPrefetchHeaderIfLocked(headers);\n try {\n const response = await fetchPrefetchResponse(url, headers);\n if (!response || !response.ok || response.status === 204 || response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' && !isOutputExportMode || !response.body) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000);\n return null;\n }\n // See TODO in fetchRouteOnCacheMiss about removing `closed` for\n // buffered prefetch paths.\n const closed = createPromiseWithResolvers();\n const { stream: prefetchStream } = await createNonTaskyPrefetchResponseStream(response.body);\n closed.resolve();\n const serverData = await createFromNextReadableStream(prefetchStream, headers, {\n allowPartialStream: true\n });\n if ((response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.tree.segment.buildId) !== getNavigationBuildId()) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000);\n return null;\n }\n const now = Date.now();\n // Walk the inlined tree in parallel with the RouteTree and fill\n // segment cache entries.\n fillInlinedSegmentEntries(now, route, tree, serverData.tree, spawnedEntries);\n // Fill the head entry.\n const headStaleAt = now + getStaleTimeMs(serverData.head.staleTime);\n const headKey = route.metadata.requestKey;\n const ownedHeadEntry = spawnedEntries.get(headKey);\n if (ownedHeadEntry !== undefined) {\n fulfillSegmentCacheEntry(ownedHeadEntry, serverData.head.rsc, headStaleAt, serverData.head.isPartial);\n } else {\n // The head was already cached. Try to upsert if the entry is empty.\n const existingEntry = readOrCreateSegmentCacheEntry(now, FetchStrategy.PPR, route.metadata);\n if (existingEntry.status === 0) {\n fulfillSegmentCacheEntry(upgradeToPendingSegment(existingEntry, FetchStrategy.PPR), serverData.head.rsc, headStaleAt, serverData.head.isPartial);\n }\n }\n // Reject any remaining entries that were not fulfilled by the response.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000);\n return {\n value: null,\n closed: closed.promise\n };\n } catch (error) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000);\n return null;\n }\n}\nfunction fillInlinedSegmentEntries(now, route, tree, inlinedNode, spawnedEntries) {\n // Check if the spawned entries map has an entry for this segment's key.\n const segment = inlinedNode.segment;\n const staleAt = now + getStaleTimeMs(segment.staleTime);\n const ownedEntry = spawnedEntries.get(tree.requestKey);\n if (ownedEntry !== undefined) {\n // We own this entry. Fulfill it directly.\n fulfillSegmentCacheEntry(ownedEntry, segment.rsc, staleAt, segment.isPartial);\n } else {\n // Not owned by us — this is extra data from the inlined response for a\n // segment that was already cached. Try to upsert if the entry is empty.\n const existingEntry = readOrCreateSegmentCacheEntry(now, FetchStrategy.PPR, tree);\n if (existingEntry.status === 0) {\n fulfillSegmentCacheEntry(upgradeToPendingSegment(existingEntry, FetchStrategy.PPR), segment.rsc, staleAt, segment.isPartial);\n }\n }\n // Recurse into children.\n if (tree.slots !== null && inlinedNode.slots !== null) {\n for(const parallelRouteKey in tree.slots){\n const childTree = tree.slots[parallelRouteKey];\n const childInlinedNode = inlinedNode.slots[parallelRouteKey];\n if (childInlinedNode !== undefined) {\n fillInlinedSegmentEntries(now, route, childTree, childInlinedNode, spawnedEntries);\n }\n }\n }\n}\nexport async function fetchSegmentPrefetchesUsingDynamicRequest(task, route, fetchStrategy, dynamicRequestTree, spawnedEntries) {\n const key = task.key;\n const url = new URL(route.canonicalUrl, location.origin);\n const nextUrl = key.nextUrl;\n if (spawnedEntries.size === 1 && spawnedEntries.has(route.metadata.requestKey)) {\n // The only thing pending is the head. Instruct the server to\n // skip over everything else.\n dynamicRequestTree = MetadataOnlyRequestTree;\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.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() + 10 * 1000);\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() + 10 * 1000);\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 prefetchStream;\n let bufferedResponseSize = null;\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 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 } else {\n const { stream, size } = await createNonTaskyPrefetchResponseStream(response.body);\n closed.resolve();\n prefetchStream = stream;\n bufferedResponseSize = size;\n }\n const [serverData, cacheData] = await Promise.all([\n createFromNextReadableStream(prefetchStream, headers, {\n allowPartialStream: true\n }),\n response.cacheData\n ]);\n // Read head vary params synchronously. Individual segments carry their\n // own thenables in CacheNodeSeedData.\n const headVaryParamsThenable = serverData.h;\n const headVaryParams = headVaryParamsThenable !== null ? readVaryParams(headVaryParamsThenable) : null;\n const now = Date.now();\n const staleAt = await getStaleAt(now, serverData.s, response);\n // PPRRuntime prefetches are partial when the server marks the response\n // as '~' (Partial). Full/LoadingBoundary prefetches are always complete.\n const isResponsePartial = fetchStrategy === FetchStrategy.PPRRuntime && (cacheData?.isResponsePartial ?? false);\n // Aside from writing the data into the cache, this function also returns\n // the entries that were fulfilled, so we can streamingly update their sizes\n // in the LRU as more data comes in.\n const buildId = response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b;\n const flightDatas = normalizeFlightData(serverData.f);\n if (typeof flightDatas === 'string') {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000);\n return null;\n }\n const navigationSeed = convertServerPatchToFullTree(now, dynamicRequestTree, flightDatas, renderedSearch, // Not needed for prefetch responses; pass unknown to use the default.\n UnknownDynamicStaleTime);\n fulfilledEntries = writeDynamicRenderResponseIntoCache(now, fetchStrategy, flightDatas, buildId, isResponsePartial, headVaryParams, staleAt, navigationSeed, spawnedEntries);\n // For buffered responses, update LRU sizes now that we know which\n // entries were fulfilled.\n if (bufferedResponseSize !== null && fulfilledEntries !== null && fulfilledEntries.length > 0) {\n const averageSize = bufferedResponseSize / fulfilledEntries.length;\n for (const entry of fulfilledEntries){\n setSizeInCacheMap(entry, averageSize);\n }\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 rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000);\n return null;\n }\n}\nfunction writeDynamicTreeResponseIntoCache(now, fetchStrategy, response, serverData, entry, couldBeIntercepted, canonicalUrl, routeIsPPREnabled, headVaryParams, originalPathname, nextUrl) {\n const renderedSearch = getRenderedSearch(response);\n const normalizedFlightDataResult = normalizeFlightData(serverData.f);\n if (// A string result means navigating to this route will result in an\n // MPA navigation.\n typeof normalizedFlightDataResult === 'string' || normalizedFlightDataResult.length !== 1) {\n rejectRouteCacheEntry(entry, now + 10 * 1000);\n return;\n }\n const flightData = normalizedFlightDataResult[0];\n if (!flightData.isRootRender) {\n // Unexpected response format.\n rejectRouteCacheEntry(entry, now + 10 * 1000);\n return;\n }\n const flightRouterState = flightData.tree;\n // If the response was postponed, segments may contain dynamic holes.\n // The head has its own partiality flag (flightDataEntry.isHeadPartial)\n // which is handled separately in writeDynamicRenderResponseIntoCache.\n const isResponsePartial = response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1';\n // Convert the server-sent data 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 };\n const routeTree = convertRootFlightRouterStateToRouteTree(flightRouterState, renderedSearch, acc);\n const metadataVaryPath = acc.metadataVaryPath;\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, now + 10 * 1000);\n return;\n }\n discoverKnownRoute(now, originalPathname, nextUrl, entry, routeTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, routeIsPPREnabled, false // hasDynamicRewrite\n );\n // If the server sent segment data as part of the response, we should write\n // it into the cache to prevent a second, redundant prefetch request.\n // TODO: This is a leftover branch from before Client Segment Cache was\n // enabled everywhere. Tree prefetches should never include segment data. We\n // can delete it. Leaving for a subsequent PR.\n const navigationSeed = convertServerPatchToFullTree(now, flightRouterState, normalizedFlightDataResult, renderedSearch, UnknownDynamicStaleTime);\n const buildId = response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b;\n writeDynamicRenderResponseIntoCache(now, fetchStrategy, normalizedFlightDataResult, buildId, isResponsePartial, headVaryParams, getStaleAtFromHeader(now, response), navigationSeed, null);\n}\nfunction rejectSegmentEntriesIfStillPending(entries, staleAt) {\n const fulfilledEntries = [];\n for (const entry of entries.values()){\n if (entry.status === 1) {\n rejectSegmentCacheEntry(entry, staleAt);\n } else if (entry.status === 2) {\n fulfilledEntries.push(entry);\n }\n }\n return fulfilledEntries;\n}\nexport function writeDynamicRenderResponseIntoCache(now, fetchStrategy, flightDatas, buildId, isResponsePartial, headVaryParams, staleAt, navigationSeed, spawnedEntries) {\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 + 10 * 1000);\n }\n return null;\n }\n const routeTree = navigationSeed.routeTree;\n const metadataTree = navigationSeed.metadataVaryPath !== null ? createMetadataRouteTree(navigationSeed.metadataVaryPath) : null;\n for (const flightDataEntry of flightDatas){\n const seedData = flightDataEntry.seedData;\n if (seedData !== null) {\n // The data sent by the server represents only a subtree of the app. We\n // need to find the part of the task tree that matches the response.\n //\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n const segmentPath = flightDataEntry.segmentPath;\n let tree = routeTree;\n for(let i = 0; i < segmentPath.length; i += 2){\n const parallelRouteKey = segmentPath[i];\n if (tree?.slots?.[parallelRouteKey] !== undefined) {\n tree = tree.slots[parallelRouteKey];\n } else {\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000);\n }\n return null;\n }\n }\n writeSeedDataIntoCache(now, fetchStrategy, tree, staleAt, seedData, isResponsePartial, spawnedEntries);\n }\n const head = flightDataEntry.head;\n if (head !== null && metadataTree !== null) {\n // When Cache Components is enabled, the server conservatively marks\n // the head as partial during static generation (isPossiblyPartialHead\n // in app-render.tsx), even for fully static pages where the head is\n // actually complete. When the response is non-partial, we override\n // this since the server confirmed no dynamic content exists.\n //\n // Without Cache Components, the server always sends the correct\n // isHeadPartial value, so no override is needed.\n const isHeadPartial = !isResponsePartial && process.env.__NEXT_CACHE_COMPONENTS ? false : flightDataEntry.isHeadPartial;\n fulfillEntrySpawnedByRuntimePrefetch(now, fetchStrategy, head, isHeadPartial, staleAt, // For head entries, use the head-specific vary params passed as\n // parameter.\n headVaryParams, metadataTree, spawnedEntries);\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 const fulfilledEntries = rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000);\n return fulfilledEntries;\n }\n return null;\n}\nfunction writeSeedDataIntoCache(now, fetchStrategy, tree, staleAt, seedData, isResponsePartial, entriesOwnedByCurrentTask) {\n // This function is used to write the result of a runtime server request\n // (CacheNodeSeedData) into the prefetch cache.\n const rsc = seedData[0];\n const isPartial = rsc === null || isResponsePartial;\n const varyParamsThenable = seedData[4];\n // Each segment carries its own vary params thenable in the seed data. The\n // thenable resolves to the set of params the segment accessed during render.\n // A null thenable means tracking was not enabled (not a prerender).\n const varyParams = varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null;\n fulfillEntrySpawnedByRuntimePrefetch(now, fetchStrategy, rsc, isPartial, staleAt, varyParams, tree, entriesOwnedByCurrentTask);\n // Recursively write the child data into the cache.\n const slots = tree.slots;\n if (slots !== null) {\n const seedDataChildren = seedData[1];\n for(const parallelRouteKey in slots){\n const childTree = slots[parallelRouteKey];\n const childSeedData = seedDataChildren[parallelRouteKey];\n if (childSeedData !== null && childSeedData !== undefined) {\n writeSeedDataIntoCache(now, fetchStrategy, childTree, staleAt, childSeedData, isResponsePartial, entriesOwnedByCurrentTask);\n }\n }\n }\n}\nfunction fulfillEntrySpawnedByRuntimePrefetch(now, fetchStrategy, rsc, isPartial, staleAt, segmentVaryParams, tree, entriesOwnedByCurrentTask) {\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 const ownedEntry = entriesOwnedByCurrentTask !== null ? entriesOwnedByCurrentTask.get(tree.requestKey) : undefined;\n if (ownedEntry !== undefined) {\n const fulfilledEntry = fulfillSegmentCacheEntry(ownedEntry, rsc, staleAt, isPartial);\n // Re-key the entry based on which params the segment actually depends on.\n if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n const fulfilledVaryPath = getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams);\n const isRevalidation = false;\n setInCacheMap(segmentCacheMap, fulfilledVaryPath, fulfilledEntry, isRevalidation);\n }\n } else {\n // There's no matching entry. Attempt to create a new one.\n const possiblyNewEntry = readOrCreateSegmentCacheEntry(now, fetchStrategy, tree);\n if (possiblyNewEntry.status === 0) {\n // Confirmed this is a new entry. We can fulfill it.\n const newEntry = possiblyNewEntry;\n const fulfilledEntry = fulfillSegmentCacheEntry(upgradeToPendingSegment(newEntry, fetchStrategy), rsc, staleAt, isPartial);\n // Re-key the entry based on which params the segment actually depends on.\n if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n const fulfilledVaryPath = getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams);\n const isRevalidation = false;\n setInCacheMap(segmentCacheMap, fulfilledVaryPath, fulfilledEntry, isRevalidation);\n }\n } else {\n // There was already an entry in the cache. But we may be able to\n // replace it with the new one from the server.\n const newEntry = fulfillSegmentCacheEntry(upgradeToPendingSegment(createDetachedSegmentCacheEntry(now), fetchStrategy), rsc, staleAt, isPartial);\n // Use the fulfilled vary path if available, otherwise fall back to\n // the request vary path.\n const varyPath = process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null ? getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams) : getSegmentVaryPathForRequest(fetchStrategy, tree);\n upsertSegmentEntry(now, varyPath, newEntry);\n }\n }\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 // `createNonTaskyPrefetchResponseStream` 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}\nasync function createNonTaskyPrefetchResponseStream(body) {\n // Buffer the entire response before passing it to the Flight client. This\n // ensures that when Flight processes the stream, all model data is available\n // synchronously. This is important for readVaryParams, which synchronously\n // checks the thenable status — if data arrived in multiple network chunks,\n // the thenables might not yet be fulfilled.\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 //\n // Read the entire response from the network.\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 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 let buffer;\n if (chunks.length === 1) {\n buffer = chunks[0];\n } else if (chunks.length > 1) {\n 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 } else {\n buffer = new Uint8Array(0);\n }\n const stream = new ReadableStream({\n start (controller) {\n controller.enqueue(buffer);\n controller.close();\n }\n });\n return {\n stream,\n size\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 * - `PPR` can provide shells for each segment (even for segments that use 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}\n/**\n * Adds the instant prefetch header if the navigation lock is active.\n * Uses a lazy require to ensure dead code elimination.\n */ function addInstantPrefetchHeaderIfLocked(headers) {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } = require('./navigation-testing-lock');\n if (isNavigationLocked()) {\n headers[NEXT_INSTANT_PREFETCH_HEADER] = '1';\n }\n }\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 the stale time from an async iterable or a response header and\n * returns a staleAt timestamp.\n *\n * TODO: Buffer the response and then read the iterable values\n * synchronously, similar to readVaryParams. This would avoid the need to\n * make this async, and we could also use it in\n * writeDynamicTreeResponseIntoCache. This will also be needed when React\n * starts leaving async iterables hanging when the outer RSC stream is\n * aborted e.g. due to sync I/O (with unstable_allowPartialStream).\n */ export async function getStaleAt(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 * Writes the static stage of a navigation response into the segment cache.\n * When `isResponsePartial` is false, segments are written as non-partial with\n * `FetchStrategy.Full` so no dynamic follow-up is needed. Default segments\n * are skipped (by `writeSeedDataIntoCache`) to avoid caching fallback content\n * that would block refreshes from overwriting with dynamic data.\n */ export function writeStaticStageResponseIntoCache(now, flightData, buildId, headVaryParamsThenable, staleAt, baseTree, renderedSearch, isResponsePartial) {\n const fetchStrategy = isResponsePartial ? FetchStrategy.PPR : FetchStrategy.Full;\n const headVaryParams = headVaryParamsThenable !== null ? readVaryParams(headVaryParamsThenable) : null;\n const flightDatas = normalizeFlightData(flightData);\n if (typeof flightDatas === 'string') {\n return;\n }\n const navigationSeed = convertServerPatchToFullTree(now, baseTree, flightDatas, renderedSearch, UnknownDynamicStaleTime);\n writeDynamicRenderResponseIntoCache(now, fetchStrategy, flightDatas, buildId, isResponsePartial, headVaryParams, staleAt, navigationSeed, null // spawnedEntries — no pre-created entries; will create or upsert\n );\n}\n/**\n * Decodes an embedded runtime prefetch Flight stream, normalizes the flight\n * data, and derives a `NavigationSeed` from the base tree.\n *\n * Returns `null` if the response triggers an MPA navigation.\n */ export async function processRuntimePrefetchStream(now, runtimePrefetchStream, baseTree, renderedSearch) {\n const { stream, isPartial } = await stripIsPartialByte(runtimePrefetchStream);\n const serverData = await createFromNextReadableStream(stream, undefined, {\n allowPartialStream: true\n });\n const headVaryParamsThenable = serverData.h;\n const headVaryParams = headVaryParamsThenable !== null ? readVaryParams(headVaryParamsThenable) : null;\n const staleAt = await getStaleAt(now, serverData.s);\n const flightDatas = normalizeFlightData(serverData.f);\n if (typeof flightDatas === 'string') {\n return null;\n }\n const navigationSeed = convertServerPatchToFullTree(now, baseTree, flightDatas, renderedSearch, UnknownDynamicStaleTime);\n return {\n flightDatas,\n navigationSeed,\n buildId: serverData.b,\n isResponsePartial: isPartial,\n headVaryParams,\n staleAt\n };\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","import { PrefetchHint } from '../../../shared/lib/app-router-types';\nimport { PAGE_SEGMENT_KEY, DEFAULT_SEGMENT_KEY, NOT_FOUND_SEGMENT_KEY } from '../../../shared/lib/segment';\nimport { matchSegment } from '../match-segments';\nimport { createHrefFromUrl } from './create-href-from-url';\nimport { fetchServerResponse } from './fetch-server-response';\nimport { dispatchAppRouterAction } from '../use-action-queue';\nimport { ACTION_SERVER_PATCH } from './router-reducer-types';\nimport { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout';\nimport { getLastCommittedTree } from './reducers/committed-state';\nimport { convertServerPatchToFullTree } from '../segment-cache/navigation';\nimport { convertReusedFlightRouterStateToRouteTree, readSegmentCacheEntry, waitForSegmentCacheEntry, markRouteEntryAsDynamicRewrite, invalidateRouteCacheEntries, getStaleAt, writeStaticStageResponseIntoCache, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache, EntryStatus } from '../segment-cache/cache';\nimport { FetchStrategy } from '../segment-cache/types';\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes';\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants';\nimport { getRenderedSearchFromVaryPath } from '../segment-cache/vary-path';\nimport { readFromBFCache, readFromBFCacheDuringRegularNavigation, writeToBFCache, writeHeadToBFCache, updateBFCacheEntryStaleAt, computeDynamicStaleAt } from '../segment-cache/bfcache';\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 createInitialCacheNodeForHydration(navigatedAt, initialTree, seedData, seedHead, 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 task = createCacheNodeOnNavigation(navigatedAt, initialTree, null, 1, seedData, seedHead, seedDynamicStaleAt, false, accumulation);\n return task;\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 a Task object, which contains both the updated Cache Node and a path\n// to the pending subtrees that need to be resolved by the navigation response.\n//\n// A return value of `null` means there were no changes, and the previous tree\n// can be reused without initiating a server request.\nexport function startPPRNavigation(navigatedAt, oldUrl, oldRenderedSearch, oldCacheNode, oldRouterState, newRouteTree, newMetadataVaryPath, freshness, seedData, seedHead, seedDynamicStaleAt, isSamePageNavigation, accumulation) {\n const didFindRootLayout = false;\n const parentNeedsDynamicRequest = false;\n const parentRefreshState = null;\n const oldRootRefreshState = {\n canonicalUrl: createHrefFromUrl(oldUrl),\n renderedSearch: oldRenderedSearch\n };\n return updateCacheNodeOnNavigation(navigatedAt, oldUrl, oldCacheNode !== null ? oldCacheNode : undefined, oldRouterState, newRouteTree, newMetadataVaryPath, freshness, didFindRootLayout, seedData, seedHead, seedDynamicStaleAt, isSamePageNavigation, parentNeedsDynamicRequest, oldRootRefreshState, parentRefreshState, accumulation);\n}\nfunction updateCacheNodeOnNavigation(navigatedAt, oldUrl, oldCacheNode, oldRouterState, newRouteTree, newMetadataVaryPath, freshness, didFindRootLayout, seedData, seedHead, seedDynamicStaleAt, isSamePageNavigation, parentNeedsDynamicRequest, oldRootRefreshState, parentRefreshState, accumulation) {\n // Check if this segment matches the one in the previous route.\n const oldSegment = oldRouterState[0];\n const newSegment = createSegmentFromRouteTree(newRouteTree);\n if (!matchSegment(newSegment, oldSegment)) {\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 (// Check if the route tree changed before we reached a layout. (The\n // highest-level layout in a route tree is referred to as the \"root\"\n // layout.) This could mean that we're navigating between two different\n // root layouts. When this happens, we perform a full-page (MPA-style)\n // navigation.\n //\n // However, the algorithm for deciding where to start rendering a route\n // (i.e. the one performed in order to reach this function) is stricter\n // than the one used to detect a change in the root layout. So just\n // because we're re-rendering a segment outside of the root layout does\n // not mean we should trigger a full-page navigation.\n //\n // Specifically, we handle dynamic parameters differently: two segments\n // are considered the same even if their parameter values are different.\n //\n // Refer to isNavigatingToNewRootLayout for details.\n //\n // Note that we only have to perform this extra traversal if we didn't\n // already discover a root layout in the part of the tree that is\n // unchanged. We also only need to compare the subtree that is not\n // shared. In the common case, this branch is skipped completely.\n !didFindRootLayout && isNavigatingToNewRootLayout(oldRouterState, 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 createCacheNodeOnNavigation(navigatedAt, newRouteTree, newMetadataVaryPath, freshness, seedData, seedHead, seedDynamicStaleAt, parentNeedsDynamicRequest, accumulation);\n }\n const newSlots = newRouteTree.slots;\n const oldRouterStateChildren = oldRouterState[1];\n const seedDataChildren = seedData !== null ? seedData[1] : null;\n // We're currently traversing the part of the tree that was also part of\n // the previous route. If we discover a root layout, then we don't need to\n // trigger an MPA navigation.\n const childDidFindRootLayout = didFindRootLayout || (newRouteTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0;\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 // TODO: We're not consistent about how we do this check. Some places\n // check if the segment starts with PAGE_SEGMENT_KEY, but most seem to\n // check if there any any children, which is why I'm doing it here. We\n // should probably encode an empty children set as `null` though. Either\n // way, we should update all the checks to be consistent.\n const isLeafSegment = newSlots === null;\n // Get the data for this segment. Since it was part of the previous route,\n // usually we just clone the data from the old CacheNode. However, during a\n // refresh or a revalidation, there won't be any existing CacheNode. So we\n // may need to consult the prefetch cache, like we would for a new segment.\n let newCacheNode;\n let needsDynamicRequest;\n if (oldCacheNode !== undefined && !shouldRefreshDynamicData && // During a same-page navigation, we always refetch the page segments\n !(isLeafSegment && isSamePageNavigation)) {\n // Reuse the existing CacheNode\n const dropPrefetchRsc = false;\n newCacheNode = reuseSharedCacheNode(dropPrefetchRsc, oldCacheNode);\n needsDynamicRequest = false;\n } else {\n // If this is part of a refresh, ignore the existing CacheNode and create a\n // new one.\n const seedRsc = seedData !== null ? seedData[0] : null;\n const result = createCacheNodeForSegment(navigatedAt, newRouteTree, seedRsc, newMetadataVaryPath, seedHead, freshness, seedDynamicStaleAt);\n newCacheNode = result.cacheNode;\n needsDynamicRequest = result.needsDynamicRequest;\n // Carry forward the old node's scrollRef. This preserves scroll\n // intent when a prior navigation's cache node is replaced by a\n // refresh before the scroll handler has had a chance to fire —\n // e.g. when router.push() and router.refresh() are called in the\n // same startTransition batch.\n if (oldCacheNode !== undefined) {\n newCacheNode.scrollRef = oldCacheNode.scrollRef;\n }\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 // 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 let newCacheNodeSlots = null;\n if (newSlots !== null) {\n const oldCacheNodeSlots = oldCacheNode !== undefined ? oldCacheNode.slots : null;\n newCacheNode.slots = newCacheNodeSlots = {};\n taskChildren = new Map();\n for(let parallelRouteKey in newSlots){\n let newRouteTreeChild = newSlots[parallelRouteKey];\n const oldRouterStateChild = oldRouterStateChildren[parallelRouteKey];\n if (oldRouterStateChild === 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 let seedDataChild = seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null;\n const oldSegmentChild = oldRouterStateChild[0];\n let newSegmentChild = createSegmentFromRouteTree(newRouteTreeChild);\n let seedHeadChild = seedHead;\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) {\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(newRouteTree, parallelRouteKey, oldRootRefreshState, oldRouterStateChild);\n newSegmentChild = createSegmentFromRouteTree(newRouteTreeChild);\n // Since we're switching to a different route tree, these are no\n // longer valid, because they correspond to the outer tree.\n seedDataChild = null;\n seedHeadChild = null;\n }\n const oldCacheNodeChild = oldCacheNodeSlots !== null ? oldCacheNodeSlots[parallelRouteKey] : undefined;\n const taskChild = updateCacheNodeOnNavigation(navigatedAt, oldUrl, oldCacheNodeChild, oldRouterStateChild, newRouteTreeChild, newMetadataVaryPath, freshness, childDidFindRootLayout, seedDataChild ?? null, seedHeadChild, seedDynamicStaleAt, isSamePageNavigation, parentNeedsDynamicRequest || needsDynamicRequest, oldRootRefreshState, refreshState, accumulation);\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 newCacheNodeSlots[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 = [\n createSegmentFromRouteTree(newRouteTree),\n patchedRouterStateChildren,\n refreshState !== null ? [\n refreshState.canonicalUrl,\n refreshState.renderedSearch\n ] : null,\n null,\n newRouteTree.prefetchHints\n ];\n return {\n status: needsDynamicRequest ? 0 : 1,\n route: newFlightRouterState,\n node: newCacheNode,\n dynamicRequestTree: createDynamicRequestTree(newFlightRouterState, dynamicRequestTreeChildren, needsDynamicRequest, childNeedsDynamicRequest, parentNeedsDynamicRequest),\n refreshState,\n children: taskChildren\n };\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 * This is only called inside `createCacheNodeOnNavigation`, which only\n * runs when segments diverge from the previous route. So for a refresh\n * where the route structure stays the same, segments match, the update\n * path is taken, and this function is never called — no scroll ref is\n * assigned. A scroll ref is only assigned when the route actually\n * changed (e.g. a redirect, or a dynamic condition on the server that\n * produces a different route).\n *\n * Skipped during hydration (initial render should not scroll) and\n * history traversal (scroll restoration is handled separately).\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 createCacheNodeOnNavigation(navigatedAt, newRouteTree, newMetadataVaryPath, freshness, seedData, seedHead, seedDynamicStaleAt, parentNeedsDynamicRequest, accumulation) {\n // Same traversal as updateCacheNodeNavigation, 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 updateCacheNodeOnNavigation, 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 newSegment = createSegmentFromRouteTree(newRouteTree);\n const newSlots = newRouteTree.slots;\n const seedDataChildren = seedData !== null ? seedData[1] : null;\n const seedRsc = seedData !== null ? seedData[0] : null;\n const result = createCacheNodeForSegment(navigatedAt, newRouteTree, seedRsc, newMetadataVaryPath, seedHead, freshness, seedDynamicStaleAt);\n const newCacheNode = result.cacheNode;\n const needsDynamicRequest = result.needsDynamicRequest;\n const isLeafSegment = newSlots === null;\n if (isLeafSegment) {\n accumulateScrollRef(freshness, newCacheNode, accumulation);\n }\n let patchedRouterStateChildren = {};\n let taskChildren = null;\n let childNeedsDynamicRequest = false;\n let dynamicRequestTreeChildren = {};\n let newCacheNodeSlots = null;\n if (newSlots !== null) {\n newCacheNode.slots = newCacheNodeSlots = {};\n taskChildren = new Map();\n for(let parallelRouteKey in newSlots){\n const newRouteTreeChild = newSlots[parallelRouteKey];\n const seedDataChild = seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null;\n const taskChild = createCacheNodeOnNavigation(navigatedAt, newRouteTreeChild, newMetadataVaryPath, freshness, seedDataChild ?? null, seedHead, seedDynamicStaleAt, parentNeedsDynamicRequest || needsDynamicRequest, accumulation);\n taskChildren.set(parallelRouteKey, taskChild);\n newCacheNodeSlots[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 const newFlightRouterState = [\n newSegment,\n patchedRouterStateChildren,\n null,\n null,\n newRouteTree.prefetchHints\n ];\n return {\n status: needsDynamicRequest ? 0 : 1,\n route: newFlightRouterState,\n node: newCacheNode,\n dynamicRequestTree: createDynamicRequestTree(newFlightRouterState, dynamicRequestTreeChildren, needsDynamicRequest, childNeedsDynamicRequest, parentNeedsDynamicRequest),\n // This route is not part of the current tree, so there's no reason to\n // track the refresh URL.\n refreshState: null,\n children: taskChildren\n };\n}\nfunction createSegmentFromRouteTree(newRouteTree) {\n if (newRouteTree.isPage) {\n // In a dynamic server response, the server embeds the search params into\n // the segment key, but in a static one it's omitted. The client handles\n // this inconsistency by adding the search params back right at the end.\n //\n // TODO: The only thing this is used for is to create a cache key for\n // ChildSegmentMap. But we already track the `renderedSearch` everywhere as\n // part of the varyPath. The plan is get rid of ChildSegmentMap and\n // store the page data in a CacheMap using the varyPath, like we do\n // for prefetches. Then we can remove it from the segment key.\n //\n // As an incremental step, we can grab the search params from the varyPath.\n const renderedSearch = getRenderedSearchFromVaryPath(newRouteTree.varyPath);\n if (renderedSearch === null) {\n return PAGE_SEGMENT_KEY;\n }\n // This is based on equivalent logic in addSearchParamsIfPageSegment, used\n // on the server.\n const stringifiedQuery = JSON.stringify(Object.fromEntries(new URLSearchParams(renderedSearch)));\n return stringifiedQuery !== '{}' ? PAGE_SEGMENT_KEY + '?' + stringifiedQuery : PAGE_SEGMENT_KEY;\n }\n return newRouteTree.segment;\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 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(parentRouteTree, parallelRouteKey, oldRootRefreshState, oldRouterState) {\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 it in the Flight Router State.\n let reusedUrl;\n let reusedRenderedSearch;\n const oldRefreshState = oldRouterState[2];\n if (oldRefreshState !== undefined && oldRefreshState !== null) {\n // This segment was already reused from an even older route. Keep its\n // existing URL and refresh state.\n reusedUrl = oldRefreshState[0];\n reusedRenderedSearch = oldRefreshState[1];\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 acc = {\n metadataVaryPath: null\n };\n const reusedRouteTree = convertReusedFlightRouterStateToRouteTree(parentRouteTree, parallelRouteKey, oldRouterState, reusedRenderedSearch, acc);\n reusedRouteTree.refreshState = {\n canonicalUrl: reusedUrl,\n renderedSearch: reusedRenderedSearch\n };\n return reusedRouteTree;\n}\nfunction reuseSharedCacheNode(dropPrefetchRsc, existingCacheNode) {\n // Clone the CacheNode that was already present in the previous tree.\n // Carry forward the scrollRef so scroll intent from a prior navigation\n // survives tree rebuilds (e.g. push + refresh in the same batch).\n return createCacheNode(existingCacheNode.rsc, dropPrefetchRsc ? null : existingCacheNode.prefetchRsc, existingCacheNode.head, dropPrefetchRsc ? null : existingCacheNode.prefetchHead, existingCacheNode.scrollRef);\n}\nfunction createCacheNodeForSegment(now, tree, seedRsc, metadataVaryPath, seedHead, freshness, dynamicStaleAt) {\n // Construct a new CacheNode 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 isPage = tree.isPage;\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 return {\n cacheNode: createCacheNode(bfcacheEntry.rsc, bfcacheEntry.prefetchRsc, bfcacheEntry.head, bfcacheEntry.prefetchHead),\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 updateCacheNodeOnNavigation.\n const rsc = seedRsc;\n const prefetchRsc = null;\n const head = isPage ? seedHead : null;\n const prefetchHead = null;\n writeToBFCache(now, tree.varyPath, rsc, prefetchRsc, head, prefetchHead, dynamicStaleAt);\n if (isPage && metadataVaryPath !== null) {\n writeHeadToBFCache(now, metadataVaryPath, head, prefetchHead, dynamicStaleAt);\n }\n return {\n cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),\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 return {\n cacheNode: createCacheNode(bfcacheEntry.rsc, dropPrefetchRsc ? null : bfcacheEntry.prefetchRsc, bfcacheEntry.head, dropPrefetchRsc ? null : bfcacheEntry.prefetchHead),\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 const segmentEntry = readSegmentCacheEntry(now, tree.varyPath);\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 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 // 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 // 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 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 } 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 }\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 } else {\n // The data is fully cached.\n prefetchRsc = null;\n rsc = cachedRsc;\n }\n doesSegmentNeedDynamicRequest = isCachedRscPartial;\n }\n // If this is a page segment, we need to do the same for the head. This\n // follows analogous logic to the segment data above.\n // TODO: We don't need to store the head on the page segment's CacheNode; we\n // can lift it to the main state object. Then we can also delete\n // findHeadCache.\n let prefetchHead = null;\n let head = null;\n let doesHeadNeedDynamicRequest = isPage;\n if (isPage) {\n let cachedHead = null;\n let isCachedHeadPartial = true;\n if (metadataVaryPath !== null) {\n const metadataEntry = readSegmentCacheEntry(now, metadataVaryPath);\n if (metadataEntry !== null) {\n switch(metadataEntry.status){\n case EntryStatus.Fulfilled:\n {\n cachedHead = metadataEntry.rsc;\n isCachedHeadPartial = metadataEntry.isPartial;\n break;\n }\n case EntryStatus.Pending:\n {\n cachedHead = waitForSegmentCacheEntry(metadataEntry).then((entry)=>entry !== null ? entry.rsc : null);\n isCachedHeadPartial = metadataEntry.isPartial;\n break;\n }\n case EntryStatus.Empty:\n case EntryStatus.Rejected:\n {\n break;\n }\n default:\n {\n metadataEntry;\n break;\n }\n }\n }\n }\n if (process.env.__NEXT_OPTIMISTIC_ROUTING && isCachedHeadPartial) {\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 cachedHead = '';\n }\n if (seedHead !== null) {\n if (isCachedHeadPartial) {\n prefetchHead = cachedHead;\n head = seedHead;\n } else {\n prefetchHead = null;\n head = cachedHead;\n }\n doesHeadNeedDynamicRequest = false;\n } else {\n if (isCachedHeadPartial) {\n prefetchHead = cachedHead;\n head = createDeferredRsc();\n } else {\n prefetchHead = null;\n head = cachedHead;\n }\n doesHeadNeedDynamicRequest = isCachedHeadPartial;\n }\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 if (freshness !== 5) {\n writeToBFCache(now, tree.varyPath, rsc, prefetchRsc, head, prefetchHead, dynamicStaleAt);\n if (isPage && metadataVaryPath !== null) {\n writeHeadToBFCache(now, metadataVaryPath, head, prefetchHead, dynamicStaleAt);\n }\n }\n return {\n cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),\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 || doesHeadNeedDynamicRequest\n };\n}\nfunction createCacheNode(rsc, prefetchRsc, head, prefetchHead, scrollRef = null) {\n return {\n rsc,\n prefetchRsc,\n head,\n prefetchHead,\n slots: null,\n scrollRef\n };\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// updateCacheNodeOnNavigation. 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(task, 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) {\n const dynamicRequestTree = task.dynamicRequestTree;\n if (dynamicRequestTree === null) {\n // This navigation was fully cached. There are no dynamic requests to spawn.\n previousNavigationDidMismatch = false;\n return;\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(task, dynamicRequestTree, primaryUrl, nextUrl, freshnessPolicy, routeCacheEntry);\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(task, 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));\n }\n }\n }\n // Further async operations are moved into this separate function to\n // discourage sequential network requests.\n const voidPromise = finishNavigationTask(task, 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(task, 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(task, null, null);\n }\n switch(exitStatus){\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.\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, task.route, routeCacheEntry, navigateType);\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, task.route, routeCacheEntry, navigateType);\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 CacheNode 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, baseTree, // 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) {\n // If the navigation used a route prediction, mark it as having a dynamic\n // rewrite since it resulted in a mismatch.\n if (routeCacheEntry !== null) {\n markRouteEntryAsDynamicRewrite(routeCacheEntry);\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 metadataVaryPath = seed.metadataVaryPath;\n if (metadataVaryPath !== null) {\n const now = Date.now();\n discoverKnownRoute(now, retryUrl.pathname, retryNextUrl, null, seed.routeTree, metadataVaryPath, false, createHrefFromUrl(retryUrl), false, true // hasDynamicRewrite\n );\n }\n }\n // Invalidate all route cache entries. Other entries may have been derived\n // from the template before we knew it had a dynamic rewrite. This also\n // triggers re-prefetching of visible links.\n invalidateRouteCacheEntries(retryNextUrl, baseTree);\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 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 };\n dispatchAppRouterAction(retryAction);\n}\nasync function fetchMissingDynamicData(task, dynamicRequestTree, url, nextUrl, freshnessPolicy, routeCacheEntry) {\n try {\n const result = await fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n isHmrRefresh: freshnessPolicy === 4\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 = convertServerPatchToFullTree(now, task.route, result.flightData, result.renderedSearch, 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) {\n await waitForNavigationLock();\n }\n if (routeCacheEntry !== null && result.staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } = result.staticStageData;\n getStaleAt(now, staticStageResponse.s).then((staleAt)=>{\n const buildId = result.responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? staticStageResponse.b;\n writeStaticStageResponseIntoCache(now, staticStageResponse.f, buildId, staticStageResponse.h, staleAt, dynamicRequestTree, result.renderedSearch, isResponsePartial);\n }).catch(()=>{\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n });\n }\n if (routeCacheEntry !== null && result.runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(now, result.runtimePrefetchStream, dynamicRequestTree, result.renderedSearch).then((processed)=>{\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(now, FetchStrategy.PPRRuntime, processed.flightDatas, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.staleAt, processed.navigationSeed, null);\n }\n }).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(task, seed.routeTree, seed.data, seed.head, dynamicStaleAt, result.debugInfo);\n return {\n exitStatus: didReceiveUnknownParallelRoute ? 1 : 0,\n url: new URL(result.canonicalUrl, location.origin),\n seed\n };\n } catch {\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, dynamicData, dynamicHead, dynamicStaleAt, debugInfo) {\n if (task.status === 0 && dynamicData !== null) {\n task.status = 1;\n finishPendingCacheNode(task.node, dynamicData, dynamicHead, debugInfo);\n // Update the BFCache entry's staleAt for this segment with the value\n // from the dynamic response. This applies the per-page\n // unstable_dynamicStaleTime if set, or the default DYNAMIC_STALETIME_MS.\n // We only update segments that received dynamic data — static segments\n // are unaffected.\n updateBFCacheEntryStaleAt(serverRouteTree.varyPath, dynamicStaleAt);\n }\n const taskChildren = task.children;\n const serverChildren = serverRouteTree.slots;\n const dynamicDataChildren = dynamicData !== null ? dynamicData[1] : null;\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 in serverChildren){\n const serverRouteTreeChild = serverChildren[parallelRouteKey];\n const dynamicDataChild = dynamicDataChildren !== null ? dynamicDataChildren[parallelRouteKey] : null;\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 const taskSegment = taskChild.route[0];\n const serverSegment = createSegmentFromRouteTree(serverRouteTreeChild);\n if (matchSegment(serverSegment, taskSegment) && dynamicDataChild !== null && dynamicDataChild !== undefined) {\n // Found a match for this task. Keep traversing down the task tree.\n const childDidReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(taskChild, serverRouteTreeChild, dynamicDataChild, dynamicHead, dynamicStaleAt, debugInfo);\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, dynamicHead, debugInfo) {\n // Writes a dynamic response into an existing Cache Node 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).\n // but it cannot 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 // on the Cache Node.\n const rsc = cacheNode.rsc;\n const dynamicSegmentData = dynamicData[0];\n if (dynamicSegmentData === null) {\n // This is an empty CacheNode; 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 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 } else if (isDeferredRsc(rsc)) {\n // This is a deferred RSC promise. We can fulfill it with the data we just\n // received from the server. If it was already resolved by a different\n // navigation, then this does nothing because we can't overwrite data.\n rsc.resolve(dynamicSegmentData, debugInfo);\n } else {\n // This is not a deferred RSC promise, nor is it empty, so it must have\n // been populated by a different navigation. We must not overwrite it.\n }\n // Check if this is a leaf segment. If so, it will have a `head` property with\n // a pending promise that needs to be resolved with the dynamic head from\n // the server.\n const head = cacheNode.head;\n if (isDeferredRsc(head)) {\n head.resolve(dynamicHead, debugInfo);\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, 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.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 // Check if this is a leaf segment. If so, it will have a `head` property with\n // a pending promise that needs to be resolved. If an error was provided, we\n // will not resolve it with an error, since this is rendered at the root of\n // the app. We want the segment to error, not the entire app.\n const head = cacheNode.head;\n if (isDeferredRsc(head)) {\n head.resolve(null, debugInfo);\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. Waits for the navigation lock\n * to be released before returning. The network request has already completed by\n * the time this is called, so this only delays writing the dynamic data.\n *\n * Not exposed in production builds by default.\n */ async function waitForNavigationLock() {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { waitForNavigationLockIfActive } = require('../segment-cache/navigation-testing-lock');\n await waitForNavigationLockIfActive();\n }\n}\n\n//# sourceMappingURL=ppr-navigations.js.map","import { fetchServerResponse } from '../router-reducer/fetch-server-response';\nimport { startPPRNavigation, spawnDynamicRequests, FreshnessPolicy } from '../router-reducer/ppr-navigations';\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url';\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants';\nimport { EntryStatus, readRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry, convertRootFlightRouterStateToRouteTree, getStaleAt, writeStaticStageResponseIntoCache, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache } from './cache';\nimport { discoverKnownRoute } from './optimistic-routes';\nimport { createCacheKey } from './cache-key';\nimport { schedulePrefetchTask } from './scheduler';\nimport { PrefetchPriority, FetchStrategy } from './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 './bfcache';\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, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType) {\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 // static shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } = require('./navigation-testing-lock');\n if (isNavigationLocked()) {\n return ensurePrefetchThenNavigate(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType);\n }\n }\n return navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType);\n}\nfunction navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType) {\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, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route);\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, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, optimisticRoute);\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, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType).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, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, 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) {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\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 task = startPPRNavigation(now, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, navigationSeed.routeTree, navigationSeed.metadataVaryPath, freshnessPolicy, navigationSeed.data, navigationSeed.head, navigationSeed.dynamicStaleAt, isSamePageNavigation, accumulation);\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(task, url, nextUrl, freshnessPolicy, accumulation, routeCacheEntry, navigateType);\n }\n return completeSoftNavigation(state, url, nextUrl, task.route, task.node, 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, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType, route) {\n const routeTree = route.tree;\n const canonicalUrl = route.canonicalUrl + url.hash;\n const renderedSearch = route.renderedSearch;\n const prefetchSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath,\n data: null,\n head: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime)\n };\n return navigateToKnownRoute(now, state, url, canonicalUrl, prefetchSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, null, route);\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, currentCacheNode, currentFlightRouterState, freshnessPolicy, scrollBehavior, navigateType) {\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 CacheNode\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 { flightData, canonicalUrl, renderedSearch, couldBeIntercepted, supportsPerSegmentPrefetching, dynamicStaleTime, staticStageData, 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 = convertServerPatchToFullTree(now, currentFlightRouterState, flightData, renderedSearch, 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 const metadataVaryPath = navigationSeed.metadataVaryPath;\n if (metadataVaryPath !== null) {\n discoverKnownRoute(now, url.pathname, nextUrl, null, navigationSeed.routeTree, metadataVaryPath, couldBeIntercepted, createHrefFromUrl(canonicalUrl), supportsPerSegmentPrefetching, false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n );\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } = staticStageData;\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n getStaleAt(now, staticStageResponse.s).then((staleAt)=>{\n const buildId = responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? staticStageResponse.b;\n writeStaticStageResponseIntoCache(now, staticStageResponse.f, buildId, staticStageResponse.h, staleAt, currentFlightRouterState, renderedSearch, isResponsePartial);\n }).catch(()=>{\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n });\n }\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(now, runtimePrefetchStream, currentFlightRouterState, renderedSearch).then((processed)=>{\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(now, FetchStrategy.PPRRuntime, processed.flightDatas, processed.buildId, processed.isResponsePartial, processed.headVaryParams, processed.staleAt, processed.navigationSeed, null);\n }\n }).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 }\n return navigateToKnownRoute(now, state, url, createHrefFromUrl(canonicalUrl), navigationSeed, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, freshnessPolicy, nextUrl, scrollBehavior, navigateType, 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);\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 focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\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, tree, cache, 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 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 the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false;\n }\n activeScrollRef = oldState.focusAndScrollRef.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.focusAndScrollRef.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.focusAndScrollRef.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 focusAndScrollRef: {\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 `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== '' ? decodeURIComponent(url.hash.slice(1)) : oldState.focusAndScrollRef.hashFragment\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo\n };\n return newState;\n}\nexport function completeTraverseNavigation(state, url, renderedSearch, cache, tree, 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 focusAndScrollRef: state.focusAndScrollRef,\n cache,\n // Restore provided tree\n tree,\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}\nexport function convertServerPatchToFullTree(now, currentTree, flightData, renderedSearch, dynamicStaleTimeSeconds) {\n // During a client navigation or prefetch, the server sends back only a patch\n // for the parts of the tree that have changed.\n //\n // This applies the patch to the base tree to create a full representation of\n // the resulting tree.\n //\n // The return type includes a full FlightRouterState tree and a full\n // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n // eventually be unified, but there's still lots of existing code that\n // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n //\n // TODO: This similar to what apply-router-state-patch-to-tree does. It\n // will eventually fully replace it. We should get rid of all the remaining\n // places where we iterate over the server patch format. This should also\n // eventually replace normalizeFlightData.\n let baseTree = currentTree;\n let baseData = null;\n let head = null;\n if (flightData !== null) {\n for (const { segmentPath, tree: treePatch, seedData: dataPatch, head: headPatch } of flightData){\n const result = convertServerPatchToFullTreeImpl(baseTree, baseData, treePatch, dataPatch, segmentPath, renderedSearch, 0);\n baseTree = result.tree;\n baseData = result.data;\n // This is the same for all patches per response, so just pick an\n // arbitrary one\n head = headPatch;\n }\n }\n const finalFlightRouterState = baseTree;\n // Convert the final FlightRouterState into a RouteTree type.\n //\n // TODO: Eventually, FlightRouterState will evolve to being a transport format\n // only. The RouteTree type will become the main type used for dealing with\n // routes on the client, and we'll store it in the state directly.\n const acc = {\n metadataVaryPath: null\n };\n const routeTree = convertRootFlightRouterStateToRouteTree(finalFlightRouterState, renderedSearch, acc);\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n data: baseData,\n renderedSearch,\n head,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds)\n };\n}\nfunction convertServerPatchToFullTreeImpl(baseRouterState, baseData, treePatch, dataPatch, segmentPath, renderedSearch, index) {\n if (index === segmentPath.length) {\n // We reached the part of the tree that we need to patch.\n return {\n tree: treePatch,\n data: dataPatch\n };\n }\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // This path tells us which part of the base tree to apply the tree patch.\n //\n // NOTE: We receive the FlightRouterState patch in the same request as the\n // seed data patch. Therefore we don't need to worry about diffing the segment\n // values; we can assume the server sent us a correct result.\n const updatedParallelRouteKey = segmentPath[index];\n // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n const baseTreeChildren = baseRouterState[1];\n const baseSeedDataChildren = baseData !== null ? baseData[1] : null;\n const newTreeChildren = {};\n const newSeedDataChildren = {};\n for(const parallelRouteKey in baseTreeChildren){\n const childBaseRouterState = baseTreeChildren[parallelRouteKey];\n const childBaseSeedData = baseSeedDataChildren !== null ? baseSeedDataChildren[parallelRouteKey] ?? null : null;\n if (parallelRouteKey === updatedParallelRouteKey) {\n const result = convertServerPatchToFullTreeImpl(childBaseRouterState, childBaseSeedData, treePatch, dataPatch, segmentPath, renderedSearch, // Advance the index by two and keep cloning until we reach\n // the end of the segment path.\n index + 2);\n newTreeChildren[parallelRouteKey] = result.tree;\n newSeedDataChildren[parallelRouteKey] = result.data;\n } else {\n // This child is not being patched. Copy it over as-is.\n newTreeChildren[parallelRouteKey] = childBaseRouterState;\n newSeedDataChildren[parallelRouteKey] = childBaseSeedData;\n }\n }\n let clonedTree;\n let clonedSeedData;\n // Clone all the fields except the children.\n // Clone the FlightRouterState tree. Based on equivalent logic in\n // apply-router-state-patch-to-tree, but should confirm whether we need to\n // copy all of these fields. Not sure the server ever sends, e.g. the\n // refetch marker.\n clonedTree = [\n baseRouterState[0],\n newTreeChildren\n ];\n if (2 in baseRouterState) {\n const compressedRefreshState = baseRouterState[2];\n if (compressedRefreshState !== undefined && compressedRefreshState !== null) {\n // Since this part of the tree was patched with new data, any parent\n // refresh states should be updated to reflect the new rendered search\n // value. (The refresh state acts like a \"context provider\".) All pages\n // within the same server response share the same renderedSearch value,\n // but the same RouteTree could be composed from multiple different\n // routes, and multiple responses.\n clonedTree[2] = [\n compressedRefreshState[0],\n renderedSearch\n ];\n }\n }\n if (3 in baseRouterState) {\n clonedTree[3] = baseRouterState[3];\n }\n if (4 in baseRouterState) {\n clonedTree[4] = baseRouterState[4];\n }\n // Clone the CacheNodeSeedData tree.\n const isEmptySeedDataPartial = true;\n clonedSeedData = [\n null,\n newSeedDataChildren,\n null,\n isEmptySeedDataPartial,\n null\n ];\n return {\n tree: clonedTree,\n data: clonedSeedData\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, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType) {\n const link = getLinkForCurrentNavigation();\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR;\n // Transition the cookie to captured-SPA immediately, before waiting\n // for the prefetch. This ensures the devtools panel can update its UI\n // right away, even if the prefetch takes time (e.g. dev compilation).\n // The \"to\" tree starts as null and is filled in after the prefetch\n // resolves and the navigation produces a new router state.\n const { transitionToCapturedSPA, updateCapturedSPAToTree } = require('./navigation-testing-lock');\n transitionToCapturedSPA(currentFlightRouterState, null);\n const cacheKey = createCacheKey(url.href, nextUrl);\n await new Promise((resolve)=>{\n schedulePrefetchTask(cacheKey, currentFlightRouterState, fetchStrategy, PrefetchPriority.Default, null, resolve // _onComplete callback\n );\n });\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(state, url, currentUrl, currentRenderedSearch, currentCacheNode, currentFlightRouterState, nextUrl, freshnessPolicy, scrollBehavior, navigateType);\n // Update the cookie with the resolved \"to\" tree so the devtools\n // panel can display both routes immediately.\n updateCapturedSPAToTree(currentFlightRouterState, result.tree);\n return result;\n}\n\n//# sourceMappingURL=navigation.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 { EntryStatus, writeRouteIntoCache, fulfillRouteCacheEntry, createMetadataRouteTree } from './cache';\nimport { doesStaticSegmentAppearInURL } from '../../route-params';\nimport { appendLayoutVaryPath, finalizeLayoutVaryPath, finalizePageVaryPath, finalizeMetadataVaryPath } from './vary-path';\nfunction createEmptyPart() {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null\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 route entry is marked as having a\n * dynamic rewrite, which prevents it from being used as a template for future\n * predictions. 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, nextUrl, pendingEntry, routeTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching, hasDynamicRewrite) {\n const tree = routeTree;\n const pathnameParts = pathname.split('/').filter((p)=>p !== '');\n const firstPart = pathnameParts.length > 0 ? pathnameParts[0] : null;\n const remainingParts = pathnameParts.length > 0 ? pathnameParts.slice(1) : [];\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(now, pendingEntry, tree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);\n if (hasDynamicRewrite) {\n fulfilledEntry.hasDynamicRewrite = true;\n }\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, firstPart, remainingParts, fulfilledEntry, now, pathname, nextUrl, tree, metadataVaryPath, couldBeIntercepted, canonicalUrl, 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, firstPart, remainingParts, null, now, pathname, nextUrl, tree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching, hasDynamicRewrite);\n}\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart.\n * A node can have at most one dynamic child (you can't have both [slug] and\n * [id] at the same route level), so we either return existing or create new.\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, urlPart, remainingParts, existingEntry, // These are passed through unchanged for entry creation at the leaf\nnow, pathname, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching, hasDynamicRewrite) {\n const segment = routeTree.segment;\n let segmentAppearsInURL;\n let paramName = null;\n let paramType = null;\n let staticSiblings = null;\n if (typeof segment === 'string') {\n segmentAppearsInURL = doesStaticSegmentAppearInURL(segment);\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n paramName = segment[0];\n paramType = segment[2];\n staticSiblings = segment[3];\n segmentAppearsInURL = true;\n }\n let knownRoutePart = parentKnownRoutePart;\n let nextUrlPart = urlPart;\n let nextRemainingParts = remainingParts;\n if (segmentAppearsInURL) {\n // Check for mismatch: if this is a static segment, the URL part must match\n if (paramName === null && urlPart !== segment) {\n // URL doesn't match route structure (likely a rewrite).\n // Don't populate the known route tree, just write the route into the\n // cache and return immediately.\n if (existingEntry !== null) {\n return existingEntry;\n }\n return writeRouteIntoCache(now, pathname, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);\n }\n // URL matches route structure. Build the known route tree.\n if (paramName !== null && paramType !== null) {\n // Dynamic segment\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 } else {\n // Static segment\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 }\n // Advance to next URL part\n nextUrlPart = remainingParts.length > 0 ? remainingParts[0] : null;\n nextRemainingParts = remainingParts.length > 0 ? remainingParts.slice(1) : [];\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\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 parallelRouteKey in slots){\n const childRouteTree = slots[parallelRouteKey];\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, nextUrlPart, nextRemainingParts, existingEntry, now, pathname, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, 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 if (existingEntry !== null) {\n return existingEntry;\n }\n return writeRouteIntoCache(now, pathname, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);\n }\n // Reached a page node. Create/get the route cache entry and store as a\n // pattern. First, check if there's already a pattern for this route.\n if (knownRoutePart.pattern !== null) {\n // If this route has a dynamic rewrite, mark the existing pattern.\n if (hasDynamicRewrite) {\n knownRoutePart.pattern.hasDynamicRewrite = true;\n }\n return knownRoutePart.pattern;\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, nextUrl, fullTree, metadataVaryPath, couldBeIntercepted, canonicalUrl, supportsPerSegmentPrefetching);\n }\n if (hasDynamicRewrite) {\n entry.hasDynamicRewrite = true;\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(pathname, search) {\n const pathnameParts = pathname.split('/').filter((p)=>p !== '');\n const resolvedParams = new Map();\n const match = matchKnownRoutePart(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 // \"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 acc = {\n metadataVaryPath: null\n };\n const reifiedTree = reifyRouteTree(pattern.tree, resolvedParams, search, 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);\n // Create a synthetic (predicted) entry and store it as the new pattern.\n //\n // Why replace the pattern? We intentionally update the pattern with this\n // synthetic entry so that if our prediction was wrong (server returns a\n // different pathname due to dynamic rewrite), the entry gets marked with\n // hasDynamicRewrite. Future predictions for this route will see the flag\n // and bail out to server resolution instead of making the same mistake.\n const syntheticEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n tree: reifiedTree,\n metadata: reifiedMetadata,\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n hasDynamicRewrite: false,\n renderedSearch: search,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version\n };\n matchedPart.pattern = syntheticEntry;\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(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) {\n const pattern = part.pattern;\n if (pattern !== null && !pattern.hasDynamicRewrite) {\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(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\n if (part.dynamicChild !== null) {\n const dynamicPart = part.dynamicChild;\n const paramName = part.dynamicChildParamName;\n const paramType = part.dynamicChildParamType;\n const dynamicPattern = dynamicPart.pattern;\n switch(paramType){\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite && urlPart !== null) {\n resolvedParams.set(paramName, pathnameParts.slice(partIndex));\n return {\n part: dynamicPart,\n pattern: dynamicPattern\n };\n }\n break;\n case 'oc':\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite) {\n if (urlPart !== null) {\n resolvedParams.set(paramName, pathnameParts.slice(partIndex));\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 if (part.pattern === null || part.pattern.hasDynamicRewrite) {\n resolvedParams.set(paramName, []);\n return {\n part: dynamicPart,\n pattern: dynamicPattern\n };\n }\n }\n break;\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, urlPart);\n return matchKnownRoutePart(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) {\n const pattern = part.pattern;\n if (pattern !== null && !pattern.hasDynamicRewrite) {\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 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 const newCacheKey = Array.isArray(newValue) ? newValue.join('/') : newValue;\n newSegment = [\n paramName,\n newCacheKey,\n paramType,\n staticSiblings\n ];\n partialVaryPath = appendLayoutVaryPath(parentPartialVaryPath, newCacheKey, paramName);\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 if (pattern.slots !== null) {\n newSlots = {};\n for(const key in pattern.slots){\n newSlots[key] = reifyRouteTree(pattern.slots[key], resolvedParams, search, partialVaryPath, acc);\n }\n }\n if (pattern.isPage) {\n // Page segment: finalize with search params\n const newVaryPath = finalizePageVaryPath(pattern.requestKey, search, partialVaryPath);\n // Collect metadata vary path (first page wins, same as original algorithm)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(pattern.requestKey, search, partialVaryPath);\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n refreshState: pattern.refreshState,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n isPage: true,\n varyPath: newVaryPath\n };\n } else {\n // Layout segment: finalize without search params\n const newVaryPath = finalizeLayoutVaryPath(pattern.requestKey, partialVaryPath);\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n refreshState: pattern.refreshState,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n isPage: false,\n varyPath: newVaryPath\n };\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","'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","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 { workUnitAsyncStorage } from './work-unit-async-storage.external';\nfunction createSegmentVaryParamsAccumulator() {\n const accumulator = {\n varyParams: new Set(),\n status: 'pending',\n value: new Set(),\n then (onfulfilled) {\n if (onfulfilled) {\n if (accumulator.status === 'pending') {\n accumulator.resolvers.push(onfulfilled);\n } else {\n onfulfilled(accumulator.value);\n }\n }\n },\n resolvers: []\n };\n return accumulator;\n}\n/**\n * A singleton accumulator that's already resolved to an empty Set. 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 resolve later\n * - Resilient: resolves correctly even if other tracking fails\n * - Memory efficient: reuses the same object\n */ const emptySet = new Set();\nexport const emptyVaryParamsAccumulator = {\n varyParams: emptySet,\n status: 'fulfilled',\n value: emptySet,\n then (onfulfilled) {\n if (onfulfilled) {\n onfulfilled(emptySet);\n }\n },\n resolvers: []\n};\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 = createSegmentVaryParamsAccumulator();\n const rootParams = createSegmentVaryParamsAccumulator();\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 a thenable that resolves to the segment's vary params once rendering\n * is complete. The thenable can be passed directly to React Flight for\n * serialization.\n */ export function createVaryParamsAccumulator() {\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-runtime':\n {\n const responseAccumulator = workUnitStore.varyParamsAccumulator;\n if (responseAccumulator !== null) {\n const accumulator = createSegmentVaryParamsAccumulator();\n responseAccumulator.segments.add(accumulator);\n return accumulator;\n }\n return null;\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n break;\n default:\n workUnitStore;\n }\n }\n return null;\n}\nexport function getMetadataVaryParamsAccumulator() {\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-runtime':\n {\n const responseAccumulator = workUnitStore.varyParamsAccumulator;\n if (responseAccumulator !== null) {\n return responseAccumulator.head;\n }\n return null;\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null;\n default:\n workUnitStore;\n }\n }\n return null;\n}\nexport function getVaryParamsThenable(accumulator) {\n return accumulator;\n}\nexport function getMetadataVaryParamsThenable() {\n const accumulator = getMetadataVaryParamsAccumulator();\n if (accumulator !== null) {\n return getVaryParamsThenable(accumulator);\n }\n return 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;\nexport function getRootParamsVaryParamsAccumulator() {\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-runtime':\n {\n const responseAccumulator = workUnitStore.varyParamsAccumulator;\n if (responseAccumulator !== null) {\n return responseAccumulator.rootParams;\n }\n return null;\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null;\n default:\n workUnitStore;\n }\n }\n return null;\n}\n/**\n * Records that a param was accessed. Adds the param name to the accumulator's\n * varyParams set.\n */ export function accumulateVaryParam(accumulator, paramName) {\n accumulator.varyParams.add(paramName);\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 const underlyingSearchParamsWithVarying = {};\n for(const searchParamName in originalSearchParamsObject){\n Object.defineProperty(underlyingSearchParamsWithVarying, searchParamName, {\n get () {\n // TODO: Unlike path params, we don't vary track each search param\n // individually. The entire search string is treated as a single param.\n // This may change in the future.\n accumulateVaryParam(accumulator, '?');\n return originalSearchParamsObject[searchParamName];\n },\n enumerable: true\n });\n }\n return underlyingSearchParamsWithVarying;\n}\n/**\n * Resolves all segment accumulators in a ResponseVaryParamsAccumulator with\n * their final vary params. Call this after rendering is complete.\n *\n * Each segment's thenable is resolved with its vary params merged with the\n * root params. If we can't track vary params (e.g., legacy prerender), simply\n * don't call this function - the client treats unresolved thenables as\n * \"unknown\" vary params.\n */ export async function finishAccumulatingVaryParams(responseAccumulator) {\n const rootVaryParams = responseAccumulator.rootParams.varyParams;\n // Resolve head\n finishSegmentAccumulator(responseAccumulator.head, rootVaryParams);\n // Resolve each segment\n for (const segmentAccumulator of responseAccumulator.segments){\n finishSegmentAccumulator(segmentAccumulator, rootVaryParams);\n }\n // Now that the thenables are resolved, Flight should be able to flush the\n // vary params into the response stream. This work gets scheduled internally\n // by Flight using a microtask as soon as we notify the thenable listeners.\n //\n // We need to ensure that Flight's pending queues are emptied before this\n // function returns; the caller will abort the prerender immediately after.\n // We can't use a macrotask, because that would allow dynamic IO to sneak\n // into the response. So we use microtasks instead.\n //\n // The exact number of awaits here isn't important (indeed, one seems to be\n // sufficient, at the time of writing), as long as we wait enough ticks for\n // Flight to finish writing the response.\n //\n // Anything that remains in Flight's internal queue after these awaits must\n // be actual dynamic IO, not caused by pending vary params tasks. In other\n // words, failing to do this would cause us to treat a fully static prerender\n // as if it were partially dynamic.\n await Promise.resolve();\n await Promise.resolve();\n await Promise.resolve();\n}\nfunction finishSegmentAccumulator(accumulator, rootVaryParams) {\n if (accumulator.status !== 'pending') {\n return;\n }\n const merged = new Set(accumulator.varyParams);\n for (const param of rootVaryParams){\n merged.add(param);\n }\n accumulator.value = merged;\n accumulator.status = 'fulfilled';\n for (const resolver of accumulator.resolvers){\n resolver(merged);\n }\n accumulator.resolvers = [];\n}\n\n//# sourceMappingURL=vary-params.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","\"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","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 function searchParamsToUrlQuery(searchParams) {\n const query = {};\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] = [\n existing,\n value\n ];\n }\n }\n return query;\n}\nfunction stringifyUrlQueryParam(param) {\n if (typeof param === 'string') {\n return param;\n }\n if (typeof param === 'number' && !isNaN(param) || typeof param === 'boolean') {\n return String(param);\n } else {\n return '';\n }\n}\nexport function urlQueryToSearchParams(query) {\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}\nexport function assign(target, ...searchParamsList) {\n for (const searchParams of searchParamsList){\n for (const key of searchParams.keys()){\n target.delete(key);\n }\n for (const [key, value] of searchParams.entries()){\n target.append(key, value);\n }\n }\n return target;\n}\n\n//# sourceMappingURL=querystring.js.map","export const ActionDidNotRevalidate = 0;\nexport const ActionDidRevalidateStaticAndDynamic = 1;\nexport const ActionDidRevalidateDynamicOnly = 2;\n\n//# sourceMappingURL=action-revalidation-kind.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}\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];\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 Object.defineProperty(new Error(`Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`), \"__NEXT_ERROR_CODE\", {\n value: \"E269\",\n enumerable: false,\n configurable: true\n });\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 Object.defineProperty(new Error(`Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`), \"__NEXT_ERROR_CODE\", {\n value: \"E207\",\n enumerable: false,\n configurable: true\n });\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 Object.defineProperty(new Error(`Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`), \"__NEXT_ERROR_CODE\", {\n value: \"E486\",\n enumerable: false,\n configurable: true\n });\n }\n interceptedRoute = splitInterceptingRoute.slice(0, -2).concat(interceptedRoute).join('/');\n break;\n default:\n throw Object.defineProperty(new Error('Invariant: unexpected marker'), \"__NEXT_ERROR_CODE\", {\n value: \"E112\",\n enumerable: false,\n configurable: true\n });\n }\n return {\n interceptingRoute,\n interceptedRoute\n };\n}\n\n//# sourceMappingURL=interception-routes.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 Object.defineProperty(new Error(`invariant: invalid relative URL, router received ${url}`), \"__NEXT_ERROR_CODE\", {\n value: \"E159\",\n enumerable: false,\n configurable: true\n });\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 { 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}\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 */ static seal(headers) {\n return 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 default:\n return ReflectAdapter.get(target, prop, receiver);\n }\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-ppr':\n case 'prerender-client':\n case 'prerender':\n case 'prerender-runtime':\n case 'generate-static-params':\n break;\n default:\n workUnitStore;\n }\n }\n if (!validationSampleTracking) {\n throw Object.defineProperty(new InvariantError('Expected to have a workUnitStore that provides validationSampleTracking'), \"__NEXT_ERROR_CODE\", {\n value: \"E1110\",\n enumerable: false,\n configurable: true\n });\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 Object.defineProperty(new InstantValidationError(`Route \"${route}\" accessed cookie \"${name}\" which is not defined in the \\`samples\\` ` + `of \\`unstable_instant\\`. Add it to the sample's \\`cookies\\` array, ` + `or \\`{ name: \"${name}\", value: null }\\` if it should be absent.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1115\",\n enumerable: false,\n configurable: true\n });\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 Object.defineProperty(new InstantValidationError('Invalid sample: Defining cookies via a \"cookie\" header is not supported. Use `cookies: [{ name: ..., value: ... }]` instead.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1111\",\n enumerable: false,\n configurable: true\n });\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(Object.defineProperty(new InstantValidationError(`Route \"${route}\" accessed header \"${name}\" which is not defined in the \\`samples\\` ` + `of \\`unstable_instant\\`. Add it to the sample's \\`headers\\` array, ` + `or \\`[\"${name}\", null]\\` if it should be absent.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1116\",\n enumerable: false,\n configurable: true\n }));\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 Object.defineProperty(new Error('Draft mode cannot be enabled during build-time instant validation.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1092\",\n enumerable: false,\n configurable: true\n });\n },\n disable () {\n throw Object.defineProperty(new Error('Draft mode cannot be disabled during build-time instant validation.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1094\",\n enumerable: false,\n configurable: true\n });\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(Object.defineProperty(new InstantValidationError(`Route \"${route}\" accessed param \"${prop}\" which is not defined in the \\`samples\\` ` + `of \\`unstable_instant\\`. Add it to the sample's \\`params\\` object.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1095\",\n enumerable: false,\n configurable: true\n }));\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 Object.defineProperty(new InstantValidationError(`Route \"${route}\" accessed searchParam \"${name}\" which is not defined in the \\`samples\\` ` + `of \\`unstable_instant\\`. Add it to the sample's \\`searchParams\\` object, ` + `or \\`{ \"${name}\": null }\\` if it should be absent.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1098\",\n enumerable: false,\n configurable: true\n });\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 Object.defineProperty(new InstantValidationError(`Expected sample param value for segment '${rawSegment}' to be an array of strings, got ${typeof paramValue}`), \"__NEXT_ERROR_CODE\", {\n value: \"E1104\",\n enumerable: false,\n configurable: true\n });\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 Object.defineProperty(new InstantValidationError(`Expected sample param value for segment '${rawSegment}' to be a string, got ${typeof paramValue}`), \"__NEXT_ERROR_CODE\", {\n value: \"E1108\",\n enumerable: false,\n configurable: true\n });\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 Object.defineProperty(new InvariantError('Not implemented: Validation of interception routes'), \"__NEXT_ERROR_CODE\", {\n value: \"E1106\",\n enumerable: false,\n configurable: true\n });\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(Object.defineProperty(new InstantValidationError(`Route \"${route}\" accessed root param \"${paramName}\" which is not defined in the \\`samples\\` ` + `of \\`unstable_instant\\`. Add it to the sample's \\`params\\` object.`), \"__NEXT_ERROR_CODE\", {\n value: \"E1114\",\n enumerable: false,\n configurable: true\n }));\n }\n}\n\n//# sourceMappingURL=instant-samples.js.map","import { StaticGenBailoutError } from '../../client/components/static-generation-bailout';\nimport { afterTaskAsyncStorage } from '../app-render/after-task-async-storage.external';\nexport function throwWithStaticGenerationBailoutErrorWithDynamicError(route, expression) {\n throw Object.defineProperty(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`), \"__NEXT_ERROR_CODE\", {\n value: \"E543\",\n enumerable: false,\n configurable: true\n });\n}\nexport function throwForSearchParamsAccessInUseCache(workStore, constructorOpt) {\n const error = Object.defineProperty(new Error(`Route ${workStore.route} used \\`searchParams\\` inside \"use cache\". Accessing dynamic request data inside a cache scope is not supported. If you need some search params inside a cached function await \\`searchParams\\` outside of the cached function and pass only the required search params as arguments to the cached function. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`), \"__NEXT_ERROR_CODE\", {\n value: \"E842\",\n enumerable: false,\n configurable: true\n });\n Error.captureStackTrace(error, constructorOpt);\n workStore.invalidDynamicUsageError ??= error;\n throw error;\n}\nexport function isRequestAPICallableInsideAfter() {\n const afterTaskStore = afterTaskAsyncStorage.getStore();\n return (afterTaskStore == null ? void 0 : afterTaskStore.rootTaskSpawnPhase) === 'action';\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, postponeWithTracking, annotateDynamicAccess } from '../app-render/dynamic-rendering';\nimport { workUnitAsyncStorage, throwInvariantForMissingStore } from '../app-render/work-unit-async-storage.external';\nimport { InvariantError } from '../../shared/lib/invariant-error';\nimport { makeDevtoolsIOAwarePromise, makeHangingPromise } 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';\nimport { RenderStage } from '../app-render/staged-rendering';\nexport function createSearchParamsFromClient(underlyingSearchParams) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw Object.defineProperty(new InvariantError('Expected workStore to be initialized'), \"__NEXT_ERROR_CODE\", {\n value: \"E1068\",\n enumerable: false,\n configurable: true\n });\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore);\n case 'validation-client':\n {\n return createClientSearchParamsInValidation(underlyingSearchParams, workStore, workUnitStore);\n }\n case 'prerender-runtime':\n throw Object.defineProperty(new InvariantError('createSearchParamsFromClient should not be called in a runtime prerender.'), \"__NEXT_ERROR_CODE\", {\n value: \"E769\",\n enumerable: false,\n configurable: true\n });\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw Object.defineProperty(new InvariantError('createSearchParamsFromClient should not be called in cache contexts.'), \"__NEXT_ERROR_CODE\", {\n value: \"E739\",\n enumerable: false,\n configurable: true\n });\n case 'generate-static-params':\n throw Object.defineProperty(new InvariantError('createSearchParamsFromClient should not be called inside generateStaticParams.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1133\",\n enumerable: false,\n configurable: true\n });\n case 'request':\n // Client searchParams are not runtime prefetchable\n const isRuntimePrefetchable = false;\n return createRenderSearchParams(underlyingSearchParams, workStore, workUnitStore, isRuntimePrefetchable);\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, isRuntimePrefetchable) {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator();\n return createServerSearchParamsForServerPage(underlyingSearchParams, metadataVaryParamsAccumulator, isRuntimePrefetchable);\n}\nexport function createServerSearchParamsForServerPage(underlyingSearchParams, varyParamsAccumulator, isRuntimePrefetchable) {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw Object.defineProperty(new InvariantError('Expected workStore to be initialized'), \"__NEXT_ERROR_CODE\", {\n value: \"E1068\",\n enumerable: false,\n configurable: true\n });\n }\n const workUnitStore = workUnitAsyncStorage.getStore();\n if (workUnitStore) {\n switch(workUnitStore.type){\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore);\n case 'validation-client':\n throw Object.defineProperty(new InvariantError('createServerSearchParamsForServerPage should not be called in a client validation.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1066\",\n enumerable: false,\n configurable: true\n });\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw Object.defineProperty(new InvariantError('createServerSearchParamsForServerPage should not be called in cache contexts.'), \"__NEXT_ERROR_CODE\", {\n value: \"E747\",\n enumerable: false,\n configurable: true\n });\n case 'generate-static-params':\n throw Object.defineProperty(new InvariantError('createServerSearchParamsForServerPage should not be called inside generateStaticParams.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1128\",\n enumerable: false,\n configurable: true\n });\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(underlyingSearchParams, workUnitStore, varyParamsAccumulator, isRuntimePrefetchable);\n case 'request':\n return createRenderSearchParams(underlyingSearchParams, workStore, workUnitStore, isRuntimePrefetchable);\n default:\n workUnitStore;\n }\n }\n throwInvariantForMissingStore();\n}\nexport function createPrerenderSearchParamsForClientPage() {\n const workStore = workAsyncStorage.getStore();\n if (!workStore) {\n throw Object.defineProperty(new InvariantError('Expected workStore to be initialized'), \"__NEXT_ERROR_CODE\", {\n value: \"E1068\",\n enumerable: false,\n configurable: true\n });\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 makeHangingPromise(workUnitStore.renderSignal, workStore.route, '`searchParams`');\n case 'validation-client':\n throw Object.defineProperty(new InvariantError('createPrerenderSearchParamsForClientPage should not be called in a client validation.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1061\",\n enumerable: false,\n configurable: true\n });\n case 'prerender-runtime':\n throw Object.defineProperty(new InvariantError('createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'), \"__NEXT_ERROR_CODE\", {\n value: \"E768\",\n enumerable: false,\n configurable: true\n });\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw Object.defineProperty(new InvariantError('createPrerenderSearchParamsForClientPage should not be called in cache contexts.'), \"__NEXT_ERROR_CODE\", {\n value: \"E746\",\n enumerable: false,\n configurable: true\n });\n case 'generate-static-params':\n throw Object.defineProperty(new InvariantError('createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'), \"__NEXT_ERROR_CODE\", {\n value: \"E1124\",\n enumerable: false,\n configurable: true\n });\n case 'prerender-ppr':\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 // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore);\n case 'prerender-ppr':\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, workUnitStore, varyParamsAccumulator, isRuntimePrefetchable) {\n const underlyingSearchParamsWithVarying = varyParamsAccumulator !== null ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams) : underlyingSearchParams;\n const result = makeUntrackedSearchParams(underlyingSearchParamsWithVarying);\n const { stagedRendering } = workUnitStore;\n if (!stagedRendering) {\n return result;\n }\n const stage = isRuntimePrefetchable ? RenderStage.EarlyRuntime : RenderStage.Runtime;\n return stagedRendering.waitForStage(stage).then(()=>result);\n}\nfunction createRenderSearchParams(underlyingSearchParams, workStore, requestStore, isRuntimePrefetchable) {\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 } else {\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, isRuntimePrefetchable);\n } else if (requestStore.asyncApiPromises) {\n if (requestStore.validationSamples) {\n const { createExhaustiveSearchParamsProxy } = require('../app-render/instant-validation/instant-samples');\n const declaredKeys = new Set(Object.keys(requestStore.validationSamples.searchParams ?? {}));\n underlyingSearchParams = createExhaustiveSearchParamsProxy(underlyingSearchParams, declaredKeys, workStore.route);\n }\n return (isRuntimePrefetchable ? requestStore.asyncApiPromises.earlySharedSearchParamsParent : requestStore.asyncApiPromises.sharedSearchParamsParent).then(()=>underlyingSearchParams);\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams);\n }\n }\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 = makeHangingPromise(prerenderStore.renderSignal, workStore.route, '`searchParams`');\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 switch(prop){\n case 'then':\n {\n const expression = '`await searchParams`, `searchParams.then`, or similar';\n annotateDynamicAccess(expression, prerenderStore);\n return ReflectAdapter.get(target, prop, receiver);\n }\n case 'status':\n {\n const expression = '`use(searchParams)`, `searchParams.status`, or similar';\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 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 if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(workStore.route, expression, prerenderStore.dynamicTracking);\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 Object.defineProperty(new InvariantError('Expected workStore to be initialized'), \"__NEXT_ERROR_CODE\", {\n value: \"E1068\",\n enumerable: false,\n configurable: true\n });\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, isRuntimePrefetchable) {\n if (requestStore.asyncApiPromises) {\n // Do not cache the resulting promise. If we do, we'll only show the first \"awaited at\"\n // across all segments that receive searchParams.\n return makeUntrackedSearchParamsWithDevWarningsImpl(underlyingSearchParams, workStore, requestStore, isRuntimePrefetchable);\n } else {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams);\n if (cachedSearchParams) {\n return cachedSearchParams;\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(underlyingSearchParams, workStore, requestStore, isRuntimePrefetchable);\n CachedSearchParams.set(requestStore, promise);\n return promise;\n }\n}\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(underlyingSearchParams, workStore, requestStore, isRuntimePrefetchable) {\n const promiseInitialized = {\n current: false\n };\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(underlyingSearchParams, workStore, promiseInitialized);\n let promise;\n if (requestStore.asyncApiPromises) {\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 sharedSearchParamsParent = isRuntimePrefetchable ? requestStore.asyncApiPromises.earlySharedSearchParamsParent : requestStore.asyncApiPromises.sharedSearchParamsParent;\n promise = new Promise((resolve, reject)=>{\n sharedSearchParamsParent.then(()=>resolve(proxiedUnderlying), reject);\n });\n // @ts-expect-error\n promise.displayName = 'searchParams';\n } else {\n promise = makeDevtoolsIOAwarePromise(proxiedUnderlying, requestStore, RenderStage.Runtime);\n }\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 runtime 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 Object.defineProperty(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`), \"__NEXT_ERROR_CODE\", {\n value: \"E848\",\n enumerable: false,\n configurable: true\n });\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","import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport { RenderStage } from '../app-render/staged-rendering'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\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-ppr':\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(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'request':\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 const fallbackParams = workUnitStore.fallbackParams\n // Client params are not runtime prefetchable\n const isRuntimePrefetchable = false\n return createRenderParamsInDev(\n underlyingParams,\n fallbackParams,\n workStore,\n workUnitStore,\n isRuntimePrefetchable\n )\n } else if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n isRuntimePrefetchable: boolean\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator,\n isRuntimePrefetchable\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\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-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // Route params are not runtime prefetchable\n const isRuntimePrefetchable = false\n return createRuntimePrerenderParams(\n underlyingParams,\n null,\n workUnitStore,\n varyParamsAccumulator,\n isRuntimePrefetchable\n )\n }\n case 'request':\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 const fallbackParams = workUnitStore.fallbackParams\n // Route params are not runtime prefetchable\n const isRuntimePrefetchable = false\n return createRenderParamsInDev(\n underlyingParams,\n fallbackParams,\n workStore,\n workUnitStore,\n isRuntimePrefetchable\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null,\n isRuntimePrefetchable: boolean\n): Promise<Params> {\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-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workUnitStore,\n varyParamsAccumulator,\n isRuntimePrefetchable\n )\n case 'request':\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 const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n fallbackParams,\n workStore,\n workUnitStore,\n isRuntimePrefetchable\n )\n } else if (\n workUnitStore.asyncApiPromises &&\n workUnitStore.validationSamples\n ) {\n return createServerParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples,\n workUnitStore.asyncApiPromises,\n isRuntimePrefetchable\n )\n } else if (\n workUnitStore.asyncApiPromises &&\n hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)\n ) {\n return (\n isRuntimePrefetchable\n ? workUnitStore.asyncApiPromises.earlySharedParamsParent\n : workUnitStore.asyncApiPromises.sharedParamsParent\n ).then(() => underlyingParams)\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\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 makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`'\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'request':\n break\n default:\n workUnitStore satisfies never\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}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const underlyingParamsWithVarying =\n varyParamsAccumulator !== null\n ? createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n : underlyingParams\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client': {\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(\n underlyingParamsWithVarying,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParamsWithVarying,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n return makeUntrackedParams(underlyingParamsWithVarying)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null,\n isRuntimePrefetchable: boolean\n): Promise<Params> {\n const underlyingParamsWithVarying =\n varyParamsAccumulator !== null\n ? createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n : underlyingParams\n\n const result = makeUntrackedParams(underlyingParamsWithVarying)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n return result\n }\n const stage = isRuntimePrefetchable\n ? RenderStage.EarlyRuntime\n : RenderStage.Runtime\n return stagedRendering.waitForStage(stage).then(() => result)\n}\n\nfunction hasFallbackRouteParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined\n): boolean {\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\nfunction createServerParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n isRuntimePrefetchable: boolean\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return (\n isRuntimePrefetchable\n ? asyncApiPromises.earlySharedParamsParent\n : asyncApiPromises.sharedParamsParent\n ).then(() => proxiedUnderlying)\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(underlyingParams: Params): Promise<Params> {\n return makeUntrackedParams(underlyingParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore,\n isRuntimePrefetchable: boolean\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore,\n isRuntimePrefetchable\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`'\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\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 = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\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 if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore,\n isRuntimePrefetchable: boolean\n): Promise<Params> {\n if (requestStore.asyncApiPromises && hasFallbackParams) {\n // We wrap each instance of params in a `new Promise()`, because deduping\n // them across requests doesn't work anyway and this let 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 sharedParamsParent = isRuntimePrefetchable\n ? requestStore.asyncApiPromises.earlySharedParamsParent\n : requestStore.asyncApiPromises.sharedParamsParent\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n sharedParamsParent.then(() => resolve(underlyingParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'params'\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n }\n\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\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\n ? makeDevtoolsIOAwarePromise(\n underlyingParams,\n requestStore,\n RenderStage.Runtime\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(underlyingParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\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\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\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}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n","'use client'\n\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { Params } from '../../server/request/params'\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'\n\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 */\nexport function ClientPageRoot({\n Component,\n serverProvidedParams,\n}: {\n Component: React.ComponentType<any>\n serverProvidedParams: null | {\n searchParams: ParsedUrlQuery\n params: Params\n promises: Array<Promise<any>> | null\n }\n}) {\n let searchParams: ParsedUrlQuery\n let params: 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 =\n layoutRouterContext !== null ? layoutRouterContext.parentParams : {}\n\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\n if (typeof window === 'undefined') {\n let clientSearchParams: Promise<ParsedUrlQuery>\n let clientParams: Promise<Params>\n\n const { createSearchParamsFromClient } =\n require('../../server/request/search-params') as typeof import('../../server/request/search-params')\n clientSearchParams = createSearchParamsFromClient(searchParams)\n\n const { createParamsFromClient } =\n require('../../server/request/params') as typeof import('../../server/request/params')\n clientParams = createParamsFromClient(params)\n\n return <Component params={clientParams} searchParams={clientSearchParams} />\n } else {\n const { createRenderSearchParamsFromClient } =\n require('../request/search-params.browser') as typeof import('../request/search-params.browser')\n const clientSearchParams = createRenderSearchParamsFromClient(searchParams)\n const { createRenderParamsFromClient } =\n require('../request/params.browser') as typeof import('../request/params.browser')\n const clientParams = createRenderParamsFromClient(params)\n\n return <Component params={clientParams} searchParams={clientSearchParams} />\n }\n}\n","'use client'\n\nimport type { Params } from '../../server/request/params'\nimport { LayoutRouterContext } from '../../shared/lib/app-router-context.shared-runtime'\nimport { use } from 'react'\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 if (typeof window === 'undefined') {\n const { createParamsFromClient } =\n require('../../server/request/params') as typeof import('../../server/request/params')\n const clientParams: Promise<Params> = createParamsFromClient(params)\n\n return <Component {...slots} params={clientParams} />\n } else {\n const { createRenderParamsFromClient } =\n require('../request/params.browser') as typeof import('../request/params.browser')\n const clientParams = createRenderParamsFromClient(params)\n return <Component {...slots} params={clientParams} />\n }\n}\n","'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","'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"],"names":["module","exports","require","vendored","ReactDOM","HTTPAccessErrorStatus","NOT_FOUND","FORBIDDEN","UNAUTHORIZED","ALLOWED_CODES","Set","Object","values","HTTP_ERROR_FALLBACK_ERROR_CODE","isHTTPAccessFallbackError","error","digest","prefix","httpStatus","split","has","Number","getAccessFallbackHTTPStatus","getAccessFallbackErrorTypeByStatus","status","RedirectStatusCode","InvariantError","Error","constructor","message","options","endsWith","name","createPromiseWithResolvers","resolve","reject","promise","Promise","res","rej","METADATA_BOUNDARY_NAME","VIEWPORT_BOUNDARY_NAME","OUTLET_BOUNDARY_NAME","ROOT_LAYOUT_BOUNDARY_NAME","DYNAMIC_ERROR_CODE","DynamicServerError","description","err","isDynamicServerError","REACT_POSTPONE_TYPE","Symbol","for","isPostpone","$$typeof","hasFallbackRouteParams","workUnitAsyncStorage","workUnitStore","getStore","type","fallbackParams","fallbackRouteParams","size","useUntrackedPathname","RSC_HEADER","ACTION_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_HMR_REFRESH_HEADER","NEXT_HMR_REFRESH_HASH_COOKIE","NEXT_URL","RSC_CONTENT_TYPE_HEADER","NEXT_INSTANT_PREFETCH_HEADER","NEXT_INSTANT_TEST_COOKIE","FLIGHT_HEADERS","NEXT_RSC_UNION_QUERY","NEXT_ROUTER_STALE_TIME_HEADER","NEXT_DID_POSTPONE_HEADER","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","NEXT_IS_PRERENDER_HEADER","NEXT_ACTION_NOT_FOUND_HEADER","NEXT_REQUEST_ID_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_ACTION_REVALIDATED_HEADER","getSegmentValue","segment","Array","isArray","isGroupSegment","isParallelRouteSegment","startsWith","computeSelectedLayoutSegment","addSearchParamsIfPageSegment","searchParams","isPageSegment","includes","PAGE_SEGMENT_KEY","stringifiedQuery","JSON","stringify","segments","parallelRouteKey","length","first","rawSegment","DEFAULT_SEGMENT_KEY","getSelectedLayoutSegmentPath","tree","segmentPath","node","children","parallelRoutes","segmentValue","NOT_FOUND_SEGMENT_KEY","push","ReactServerDOMTurbopackClient","React","use","useMemo","useOptimistic","isThenable","ACTION_REFRESH","dispatch","refreshOnInstantNavigationUnlock","process","env","__NEXT_EXPOSE_TESTING_API","bypassCacheInvalidation","window","location","reload","dispatchAppRouterAction","action","setGestureRouterState","dispatchGestureState","state","__DEV__","NODE_ENV","promisesWithDebugInfo","WeakMap","useActionQueue","actionQueue","canonicalState","setState","useState","setGesture","nextDispatch","useAppDevRenderingIndicator","appDevRenderingIndicator","stateWithDebugInfo","promiseWithDebugInfo","get","undefined","debugInfo","then","asyncState","_debugInfo","set","parseCookieValue","raw","parsed","parse","rawState","writeCookieValue","value","cookieStore","existing","path","domain","lockState","acquireLock","r","releaseLock","startListeningForInstantNavigationCookie","self","__next_instant_test","cookie","Math","random","addEventListener","event","changed","deleted","transitionToCapturedSPA","fromTree","toTree","from","to","updateCapturedSPAToTree","isNavigationLocked","waitForNavigationLockIfActive","unresolvedThenable","useContext","TemplateContext","RenderFromTemplateContext","createSegmentVaryParamsAccumulator","accumulator","varyParams","onfulfilled","resolvers","emptySet","emptyVaryParamsAccumulator","createResponseVaryParamsAccumulator","head","rootParams","createVaryParamsAccumulator","responseAccumulator","varyParamsAccumulator","add","getMetadataVaryParamsAccumulator","getVaryParamsThenable","getMetadataVaryParamsThenable","getViewportVaryParamsAccumulator","getRootParamsVaryParamsAccumulator","accumulateVaryParam","paramName","accumulateRootVaryParam","rootParamsAccumulator","createVaryingParams","originalParamsObject","optionalCatchAllParamName","Proxy","target","prop","receiver","prototype","hasOwnProperty","call","Reflect","ownKeys","underlyingParamsWithVarying","defineProperty","enumerable","createVaryingSearchParams","originalSearchParamsObject","underlyingSearchParamsWithVarying","searchParamName","finishAccumulatingVaryParams","rootVaryParams","finishSegmentAccumulator","segmentAccumulator","merged","param","resolver","ReflectAdapter","bind","deleteProperty","__defProp","__getOwnPropDesc","getOwnPropertyDescriptor","__getOwnPropNames","getOwnPropertyNames","__hasOwnProp","__export","all","__copyProps","except","desc","key","__toCommonJS","mod","src_exports","RequestCookies","ResponseCookies","parseCookie","parseSetCookie","stringifyCookie","c","_a","attrs","expires","Date","toUTCString","maxAge","secure","httpOnly","sameSite","partitioned","priority","filter","Boolean","stringified","encodeURIComponent","join","map","Map","pair","splitAt","indexOf","slice","decodeURIComponent","setCookie","attributes","httponly","maxage","samesite","fromEntries","value2","toLowerCase","replace","parseSameSite","parsePriority","compact","t","newT","SAME_SITE","string","PRIORITY","splitCookiesString","cookiesString","cookiesStrings","pos","start","ch","lastComma","nextStart","cookiesSeparatorFound","skipWhitespace","test","charAt","notSpecialChar","substring","requestHeaders","_parsed","_headers","header","iterator","args","getAll","_","n","delete","names","result","clear","keys","toString","v","responseHeaders","_b","_c","getSetCookie","cookieStrings","cookieString","normalizeCookie","bag","headers","serialized","append","now","throwWithStaticGenerationBailoutErrorWithDynamicError","route","expression","configurable","throwForSearchParamsAccessInUseCache","workStore","constructorOpt","captureStackTrace","invalidDynamicUsageError","isRequestAPICallableInsideAfter","afterTaskStore","rootTaskSpawnPhase","workAsyncStorage","throwToInterruptStaticGeneration","postponeWithTracking","throwInvariantForMissingStore","describeStringPropertyAccess","wellKnownProperties","makeDevtoolsIOAwarePromise","makeHangingPromise","createDedupedByCallsiteServerErrorLoggerDev","dynamicAccessAsyncStorage","RenderStage","createParamsFromClient","underlyingParams","createStaticPrerenderParams","createClientParamsInInstantValidation","validationSamples","isRuntimePrefetchable","createRenderParamsInDev","createRenderParamsInProd","createServerParamsForMetadata","metadataVaryParamsAccumulator","createServerParamsForServerSegment","createServerParamsForRoute","createRuntimePrerenderParams","asyncApiPromises","createServerParamsInInstantValidation","earlySharedParamsParent","sharedParamsParent","createPrerenderParamsForClientSegment","renderSignal","prerenderStore","makeHangingParams","makeErroringParams","makeUntrackedParams","stagedRendering","stage","EarlyRuntime","Runtime","waitForStage","createExhaustiveParamsProxy","declaredParams","params","proxiedUnderlying","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","fallbackParamsProxyHandler","originalMethod","store","abortController","abort","apply","cachedParams","augmentedUnderlying","forEach","dynamicTracking","hasFallbackParams","displayName","instrumentParamsPromiseWithDevWarnings","proxiedPromise","proxiedProperties","warnForSyncAccess","createParamsAccessError","LayoutRouterContext","urlSearchParamsToParsedUrlQuery","SearchParamsContext","ClientPageRoot","Component","serverProvidedParams","layoutRouterContext","parentParams","clientSearchParams","clientParams","createSearchParamsFromClient","createRenderSearchParamsFromClient","createRenderParamsFromClient","ClientSegmentRoot","slots","NameSpace","MetadataBoundary","ViewportBoundary","OutletBoundary","RootLayoutBoundary","IconMark","meta"],"mappings":"6CAAAA,EAAOC,OAAO,CACZC,EAAQ,CAAA,CAAA,IAAA,GACRC,QAAQ,CAAC,YAAY,CAAEC,QA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Z,EAAAA,aADV,AADA,SAEUA,CAAuB0P,KAAK,CAAC,GAAoC,CAAA,AAEhEyJ,EAGXF,CAAS,CAAChZ,EAAAA,aAFV,AACA,SACUA,CAAuByP,KAAK,CAAC,GAAoC,CAAA,AAEhE0J,CARiD,CAW5DH,CAAS,CAAC/Y,EAAAA,WAFV,AACA,IAXgF,KAYtEA,CAAqBwP,KAAK,CAAC,GAAkC,CAAA,AAE5D2J,EAGXJ,CAX4D,AAWnD,CACP9Y,EAAAA,eAHF,AACA,EAXgF,QAa9EA,CAA0BuP,KAAK,CAAC,EAP0B,CAQ3D,CAAA,kBAT+E,qBAMpB,oBADoB,mGCvC1D,IAItB,CAAA,EAAO,EAAA,GAAA,EAAC6J,OAAAA,CAAK/Z,KAAK","ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,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]}