mailcast 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1342) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/app-path-routes-manifest.json +63 -0
  3. package/.next/build/chunks/[root-of-the-server]__05i36w1t4lzaf._.js +500 -0
  4. package/.next/build/chunks/[root-of-the-server]__05i36w1t4lzaf._.js.map +11 -0
  5. package/.next/build/chunks/[root-of-the-server]__1kki86fknkq7y._.js +189 -0
  6. package/.next/build/chunks/[root-of-the-server]__1kki86fknkq7y._.js.map +8 -0
  7. package/.next/build/chunks/[turbopack-node]_transforms_postcss_ts_1gfkiq9iz8yb8._.js +13 -0
  8. package/.next/build/chunks/[turbopack-node]_transforms_postcss_ts_1gfkiq9iz8yb8._.js.map +5 -0
  9. package/.next/build/chunks/[turbopack]_runtime.js +1054 -0
  10. package/.next/build/chunks/[turbopack]_runtime.js.map +11 -0
  11. package/.next/build/chunks/node_modules__pnpm_1e0eoiefxqbi6._.js +7265 -0
  12. package/.next/build/chunks/node_modules__pnpm_1e0eoiefxqbi6._.js.map +47 -0
  13. package/.next/build/chunks/pool_entry-[turbopack-node]_transforms_postcss_ts_0tp-k2vy8nj6i._.js +6 -0
  14. package/.next/build/chunks/pool_entry-[turbopack-node]_transforms_postcss_ts_0tp-k2vy8nj6i._.js.map +5 -0
  15. package/.next/build/package.json +1 -0
  16. package/.next/build-manifest.json +223 -0
  17. package/.next/diagnostics/build-diagnostics.json +6 -0
  18. package/.next/diagnostics/framework.json +1 -0
  19. package/.next/diagnostics/route-bundle-stats.json +305 -0
  20. package/.next/export-marker.json +6 -0
  21. package/.next/fallback-build-manifest.json +15 -0
  22. package/.next/images-manifest.json +68 -0
  23. package/.next/next-minimal-server.js.nft.json +1 -0
  24. package/.next/next-server.js.nft.json +1 -0
  25. package/.next/package.json +1 -0
  26. package/.next/prerender-manifest.json +209 -0
  27. package/.next/required-server-files.js +370 -0
  28. package/.next/required-server-files.json +370 -0
  29. package/.next/routes-manifest.json +456 -0
  30. package/.next/server/app/_global-error/page/app-paths-manifest.json +3 -0
  31. package/.next/server/app/_global-error/page/build-manifest.json +22 -0
  32. package/.next/server/app/_global-error/page/next-font-manifest.json +6 -0
  33. package/.next/server/app/_global-error/page/react-loadable-manifest.json +1 -0
  34. package/.next/server/app/_global-error/page/server-reference-manifest.json +4 -0
  35. package/.next/server/app/_global-error/page.js +11 -0
  36. package/.next/server/app/_global-error/page.js.map +5 -0
  37. package/.next/server/app/_global-error/page.js.nft.json +1 -0
  38. package/.next/server/app/_global-error/page_client-reference-manifest.js +3 -0
  39. package/.next/server/app/_global-error.html +1 -0
  40. package/.next/server/app/_global-error.meta +30 -0
  41. package/.next/server/app/_global-error.rsc +18 -0
  42. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +23 -0
  43. package/.next/server/app/_global-error.segments/_full.segment.rsc +18 -0
  44. package/.next/server/app/_global-error.segments/_tree.segment.rsc +2 -0
  45. package/.next/server/app/_not-found/page/app-paths-manifest.json +3 -0
  46. package/.next/server/app/_not-found/page/build-manifest.json +22 -0
  47. package/.next/server/app/_not-found/page/next-font-manifest.json +6 -0
  48. package/.next/server/app/_not-found/page/react-loadable-manifest.json +1 -0
  49. package/.next/server/app/_not-found/page/server-reference-manifest.json +4 -0
  50. package/.next/server/app/_not-found/page.js +13 -0
  51. package/.next/server/app/_not-found/page.js.map +5 -0
  52. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  53. package/.next/server/app/_not-found/page_client-reference-manifest.js +3 -0
  54. package/.next/server/app/_not-found.html +1 -0
  55. package/.next/server/app/_not-found.meta +35 -0
  56. package/.next/server/app/_not-found.rsc +25 -0
  57. package/.next/server/app/_not-found.segments/_full.segment.rsc +25 -0
  58. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +31 -0
  59. package/.next/server/app/_not-found.segments/_tree.segment.rsc +4 -0
  60. package/.next/server/app/api/auth/login/route/app-paths-manifest.json +3 -0
  61. package/.next/server/app/api/auth/login/route/build-manifest.json +12 -0
  62. package/.next/server/app/api/auth/login/route/server-reference-manifest.json +4 -0
  63. package/.next/server/app/api/auth/login/route.js +10 -0
  64. package/.next/server/app/api/auth/login/route.js.map +5 -0
  65. package/.next/server/app/api/auth/login/route.js.nft.json +1 -0
  66. package/.next/server/app/api/auth/login/route_client-reference-manifest.js +3 -0
  67. package/.next/server/app/api/auth/logout/route/app-paths-manifest.json +3 -0
  68. package/.next/server/app/api/auth/logout/route/build-manifest.json +12 -0
  69. package/.next/server/app/api/auth/logout/route/server-reference-manifest.json +4 -0
  70. package/.next/server/app/api/auth/logout/route.js +10 -0
  71. package/.next/server/app/api/auth/logout/route.js.map +5 -0
  72. package/.next/server/app/api/auth/logout/route.js.nft.json +1 -0
  73. package/.next/server/app/api/auth/logout/route_client-reference-manifest.js +3 -0
  74. package/.next/server/app/api/auth/session/route/app-paths-manifest.json +3 -0
  75. package/.next/server/app/api/auth/session/route/build-manifest.json +12 -0
  76. package/.next/server/app/api/auth/session/route/server-reference-manifest.json +4 -0
  77. package/.next/server/app/api/auth/session/route.js +10 -0
  78. package/.next/server/app/api/auth/session/route.js.map +5 -0
  79. package/.next/server/app/api/auth/session/route.js.nft.json +1 -0
  80. package/.next/server/app/api/auth/session/route_client-reference-manifest.js +3 -0
  81. package/.next/server/app/api/auth/setup/route/app-paths-manifest.json +3 -0
  82. package/.next/server/app/api/auth/setup/route/build-manifest.json +12 -0
  83. package/.next/server/app/api/auth/setup/route/server-reference-manifest.json +4 -0
  84. package/.next/server/app/api/auth/setup/route.js +10 -0
  85. package/.next/server/app/api/auth/setup/route.js.map +5 -0
  86. package/.next/server/app/api/auth/setup/route.js.nft.json +1 -0
  87. package/.next/server/app/api/auth/setup/route_client-reference-manifest.js +3 -0
  88. package/.next/server/app/api/campaigns/[id]/publish/route/app-paths-manifest.json +3 -0
  89. package/.next/server/app/api/campaigns/[id]/publish/route/build-manifest.json +12 -0
  90. package/.next/server/app/api/campaigns/[id]/publish/route/server-reference-manifest.json +4 -0
  91. package/.next/server/app/api/campaigns/[id]/publish/route.js +9 -0
  92. package/.next/server/app/api/campaigns/[id]/publish/route.js.map +5 -0
  93. package/.next/server/app/api/campaigns/[id]/publish/route.js.nft.json +1 -0
  94. package/.next/server/app/api/campaigns/[id]/publish/route_client-reference-manifest.js +3 -0
  95. package/.next/server/app/api/campaigns/[id]/route/app-paths-manifest.json +3 -0
  96. package/.next/server/app/api/campaigns/[id]/route/build-manifest.json +12 -0
  97. package/.next/server/app/api/campaigns/[id]/route/server-reference-manifest.json +4 -0
  98. package/.next/server/app/api/campaigns/[id]/route.js +8 -0
  99. package/.next/server/app/api/campaigns/[id]/route.js.map +5 -0
  100. package/.next/server/app/api/campaigns/[id]/route.js.nft.json +1 -0
  101. package/.next/server/app/api/campaigns/[id]/route_client-reference-manifest.js +3 -0
  102. package/.next/server/app/api/campaigns/[id]/send/route/app-paths-manifest.json +3 -0
  103. package/.next/server/app/api/campaigns/[id]/send/route/build-manifest.json +12 -0
  104. package/.next/server/app/api/campaigns/[id]/send/route/server-reference-manifest.json +4 -0
  105. package/.next/server/app/api/campaigns/[id]/send/route.js +13 -0
  106. package/.next/server/app/api/campaigns/[id]/send/route.js.map +5 -0
  107. package/.next/server/app/api/campaigns/[id]/send/route.js.nft.json +1 -0
  108. package/.next/server/app/api/campaigns/[id]/send/route_client-reference-manifest.js +3 -0
  109. package/.next/server/app/api/campaigns/[id]/stats/route/app-paths-manifest.json +3 -0
  110. package/.next/server/app/api/campaigns/[id]/stats/route/build-manifest.json +12 -0
  111. package/.next/server/app/api/campaigns/[id]/stats/route/server-reference-manifest.json +4 -0
  112. package/.next/server/app/api/campaigns/[id]/stats/route.js +8 -0
  113. package/.next/server/app/api/campaigns/[id]/stats/route.js.map +5 -0
  114. package/.next/server/app/api/campaigns/[id]/stats/route.js.nft.json +1 -0
  115. package/.next/server/app/api/campaigns/[id]/stats/route_client-reference-manifest.js +3 -0
  116. package/.next/server/app/api/campaigns/all/route/app-paths-manifest.json +3 -0
  117. package/.next/server/app/api/campaigns/all/route/build-manifest.json +12 -0
  118. package/.next/server/app/api/campaigns/all/route/server-reference-manifest.json +4 -0
  119. package/.next/server/app/api/campaigns/all/route.js +8 -0
  120. package/.next/server/app/api/campaigns/all/route.js.map +5 -0
  121. package/.next/server/app/api/campaigns/all/route.js.nft.json +1 -0
  122. package/.next/server/app/api/campaigns/all/route_client-reference-manifest.js +3 -0
  123. package/.next/server/app/api/campaigns/route/app-paths-manifest.json +3 -0
  124. package/.next/server/app/api/campaigns/route/build-manifest.json +12 -0
  125. package/.next/server/app/api/campaigns/route/server-reference-manifest.json +4 -0
  126. package/.next/server/app/api/campaigns/route.js +9 -0
  127. package/.next/server/app/api/campaigns/route.js.map +5 -0
  128. package/.next/server/app/api/campaigns/route.js.nft.json +1 -0
  129. package/.next/server/app/api/campaigns/route_client-reference-manifest.js +3 -0
  130. package/.next/server/app/api/contacts/[id]/route/app-paths-manifest.json +3 -0
  131. package/.next/server/app/api/contacts/[id]/route/build-manifest.json +12 -0
  132. package/.next/server/app/api/contacts/[id]/route/server-reference-manifest.json +4 -0
  133. package/.next/server/app/api/contacts/[id]/route.js +8 -0
  134. package/.next/server/app/api/contacts/[id]/route.js.map +5 -0
  135. package/.next/server/app/api/contacts/[id]/route.js.nft.json +1 -0
  136. package/.next/server/app/api/contacts/[id]/route_client-reference-manifest.js +3 -0
  137. package/.next/server/app/api/contacts/all/route/app-paths-manifest.json +3 -0
  138. package/.next/server/app/api/contacts/all/route/build-manifest.json +12 -0
  139. package/.next/server/app/api/contacts/all/route/server-reference-manifest.json +4 -0
  140. package/.next/server/app/api/contacts/all/route.js +8 -0
  141. package/.next/server/app/api/contacts/all/route.js.map +5 -0
  142. package/.next/server/app/api/contacts/all/route.js.nft.json +1 -0
  143. package/.next/server/app/api/contacts/all/route_client-reference-manifest.js +3 -0
  144. package/.next/server/app/api/contacts/import/route/app-paths-manifest.json +3 -0
  145. package/.next/server/app/api/contacts/import/route/build-manifest.json +12 -0
  146. package/.next/server/app/api/contacts/import/route/server-reference-manifest.json +4 -0
  147. package/.next/server/app/api/contacts/import/route.js +8 -0
  148. package/.next/server/app/api/contacts/import/route.js.map +5 -0
  149. package/.next/server/app/api/contacts/import/route.js.nft.json +1 -0
  150. package/.next/server/app/api/contacts/import/route_client-reference-manifest.js +3 -0
  151. package/.next/server/app/api/contacts/route/app-paths-manifest.json +3 -0
  152. package/.next/server/app/api/contacts/route/build-manifest.json +12 -0
  153. package/.next/server/app/api/contacts/route/server-reference-manifest.json +4 -0
  154. package/.next/server/app/api/contacts/route.js +8 -0
  155. package/.next/server/app/api/contacts/route.js.map +5 -0
  156. package/.next/server/app/api/contacts/route.js.nft.json +1 -0
  157. package/.next/server/app/api/contacts/route_client-reference-manifest.js +3 -0
  158. package/.next/server/app/api/cron/route/app-paths-manifest.json +3 -0
  159. package/.next/server/app/api/cron/route/build-manifest.json +12 -0
  160. package/.next/server/app/api/cron/route/server-reference-manifest.json +4 -0
  161. package/.next/server/app/api/cron/route.js +15 -0
  162. package/.next/server/app/api/cron/route.js.map +5 -0
  163. package/.next/server/app/api/cron/route.js.nft.json +1 -0
  164. package/.next/server/app/api/cron/route_client-reference-manifest.js +3 -0
  165. package/.next/server/app/api/forms/[id]/route/app-paths-manifest.json +3 -0
  166. package/.next/server/app/api/forms/[id]/route/build-manifest.json +12 -0
  167. package/.next/server/app/api/forms/[id]/route/server-reference-manifest.json +4 -0
  168. package/.next/server/app/api/forms/[id]/route.js +9 -0
  169. package/.next/server/app/api/forms/[id]/route.js.map +5 -0
  170. package/.next/server/app/api/forms/[id]/route.js.nft.json +1 -0
  171. package/.next/server/app/api/forms/[id]/route_client-reference-manifest.js +3 -0
  172. package/.next/server/app/api/forms/[id]/submissions/route/app-paths-manifest.json +3 -0
  173. package/.next/server/app/api/forms/[id]/submissions/route/build-manifest.json +12 -0
  174. package/.next/server/app/api/forms/[id]/submissions/route/server-reference-manifest.json +4 -0
  175. package/.next/server/app/api/forms/[id]/submissions/route.js +8 -0
  176. package/.next/server/app/api/forms/[id]/submissions/route.js.map +5 -0
  177. package/.next/server/app/api/forms/[id]/submissions/route.js.nft.json +1 -0
  178. package/.next/server/app/api/forms/[id]/submissions/route_client-reference-manifest.js +3 -0
  179. package/.next/server/app/api/forms/[id]/submit/route/app-paths-manifest.json +3 -0
  180. package/.next/server/app/api/forms/[id]/submit/route/build-manifest.json +12 -0
  181. package/.next/server/app/api/forms/[id]/submit/route/server-reference-manifest.json +4 -0
  182. package/.next/server/app/api/forms/[id]/submit/route.js +17 -0
  183. package/.next/server/app/api/forms/[id]/submit/route.js.map +5 -0
  184. package/.next/server/app/api/forms/[id]/submit/route.js.nft.json +1 -0
  185. package/.next/server/app/api/forms/[id]/submit/route_client-reference-manifest.js +3 -0
  186. package/.next/server/app/api/forms/route/app-paths-manifest.json +3 -0
  187. package/.next/server/app/api/forms/route/build-manifest.json +12 -0
  188. package/.next/server/app/api/forms/route/server-reference-manifest.json +4 -0
  189. package/.next/server/app/api/forms/route.js +9 -0
  190. package/.next/server/app/api/forms/route.js.map +5 -0
  191. package/.next/server/app/api/forms/route.js.nft.json +1 -0
  192. package/.next/server/app/api/forms/route_client-reference-manifest.js +3 -0
  193. package/.next/server/app/api/forms/templates/[id]/route/app-paths-manifest.json +3 -0
  194. package/.next/server/app/api/forms/templates/[id]/route/build-manifest.json +12 -0
  195. package/.next/server/app/api/forms/templates/[id]/route/server-reference-manifest.json +4 -0
  196. package/.next/server/app/api/forms/templates/[id]/route.js +8 -0
  197. package/.next/server/app/api/forms/templates/[id]/route.js.map +5 -0
  198. package/.next/server/app/api/forms/templates/[id]/route.js.nft.json +1 -0
  199. package/.next/server/app/api/forms/templates/[id]/route_client-reference-manifest.js +3 -0
  200. package/.next/server/app/api/forms/templates/route/app-paths-manifest.json +3 -0
  201. package/.next/server/app/api/forms/templates/route/build-manifest.json +12 -0
  202. package/.next/server/app/api/forms/templates/route/server-reference-manifest.json +4 -0
  203. package/.next/server/app/api/forms/templates/route.js +9 -0
  204. package/.next/server/app/api/forms/templates/route.js.map +5 -0
  205. package/.next/server/app/api/forms/templates/route.js.nft.json +1 -0
  206. package/.next/server/app/api/forms/templates/route_client-reference-manifest.js +3 -0
  207. package/.next/server/app/api/groups/[id]/contacts/route/app-paths-manifest.json +3 -0
  208. package/.next/server/app/api/groups/[id]/contacts/route/build-manifest.json +12 -0
  209. package/.next/server/app/api/groups/[id]/contacts/route/server-reference-manifest.json +4 -0
  210. package/.next/server/app/api/groups/[id]/contacts/route.js +8 -0
  211. package/.next/server/app/api/groups/[id]/contacts/route.js.map +5 -0
  212. package/.next/server/app/api/groups/[id]/contacts/route.js.nft.json +1 -0
  213. package/.next/server/app/api/groups/[id]/contacts/route_client-reference-manifest.js +3 -0
  214. package/.next/server/app/api/groups/[id]/route/app-paths-manifest.json +3 -0
  215. package/.next/server/app/api/groups/[id]/route/build-manifest.json +12 -0
  216. package/.next/server/app/api/groups/[id]/route/server-reference-manifest.json +4 -0
  217. package/.next/server/app/api/groups/[id]/route.js +8 -0
  218. package/.next/server/app/api/groups/[id]/route.js.map +5 -0
  219. package/.next/server/app/api/groups/[id]/route.js.nft.json +1 -0
  220. package/.next/server/app/api/groups/[id]/route_client-reference-manifest.js +3 -0
  221. package/.next/server/app/api/groups/route/app-paths-manifest.json +3 -0
  222. package/.next/server/app/api/groups/route/build-manifest.json +12 -0
  223. package/.next/server/app/api/groups/route/server-reference-manifest.json +4 -0
  224. package/.next/server/app/api/groups/route.js +8 -0
  225. package/.next/server/app/api/groups/route.js.map +5 -0
  226. package/.next/server/app/api/groups/route.js.nft.json +1 -0
  227. package/.next/server/app/api/groups/route_client-reference-manifest.js +3 -0
  228. package/.next/server/app/api/media/[name]/route/app-paths-manifest.json +3 -0
  229. package/.next/server/app/api/media/[name]/route/build-manifest.json +12 -0
  230. package/.next/server/app/api/media/[name]/route/server-reference-manifest.json +4 -0
  231. package/.next/server/app/api/media/[name]/route.js +8 -0
  232. package/.next/server/app/api/media/[name]/route.js.map +5 -0
  233. package/.next/server/app/api/media/[name]/route.js.nft.json +1 -0
  234. package/.next/server/app/api/media/[name]/route_client-reference-manifest.js +3 -0
  235. package/.next/server/app/api/media/route/app-paths-manifest.json +3 -0
  236. package/.next/server/app/api/media/route/build-manifest.json +12 -0
  237. package/.next/server/app/api/media/route/server-reference-manifest.json +4 -0
  238. package/.next/server/app/api/media/route.js +8 -0
  239. package/.next/server/app/api/media/route.js.map +5 -0
  240. package/.next/server/app/api/media/route.js.nft.json +1 -0
  241. package/.next/server/app/api/media/route_client-reference-manifest.js +3 -0
  242. package/.next/server/app/api/public/forms/[id]/route/app-paths-manifest.json +3 -0
  243. package/.next/server/app/api/public/forms/[id]/route/build-manifest.json +12 -0
  244. package/.next/server/app/api/public/forms/[id]/route/server-reference-manifest.json +4 -0
  245. package/.next/server/app/api/public/forms/[id]/route.js +17 -0
  246. package/.next/server/app/api/public/forms/[id]/route.js.map +5 -0
  247. package/.next/server/app/api/public/forms/[id]/route.js.nft.json +1 -0
  248. package/.next/server/app/api/public/forms/[id]/route_client-reference-manifest.js +3 -0
  249. package/.next/server/app/api/public/posts/[slug]/route/app-paths-manifest.json +3 -0
  250. package/.next/server/app/api/public/posts/[slug]/route/build-manifest.json +12 -0
  251. package/.next/server/app/api/public/posts/[slug]/route/server-reference-manifest.json +4 -0
  252. package/.next/server/app/api/public/posts/[slug]/route.js +9 -0
  253. package/.next/server/app/api/public/posts/[slug]/route.js.map +5 -0
  254. package/.next/server/app/api/public/posts/[slug]/route.js.nft.json +1 -0
  255. package/.next/server/app/api/public/posts/[slug]/route_client-reference-manifest.js +3 -0
  256. package/.next/server/app/api/public/posts/route/app-paths-manifest.json +3 -0
  257. package/.next/server/app/api/public/posts/route/build-manifest.json +12 -0
  258. package/.next/server/app/api/public/posts/route/server-reference-manifest.json +4 -0
  259. package/.next/server/app/api/public/posts/route.js +8 -0
  260. package/.next/server/app/api/public/posts/route.js.map +5 -0
  261. package/.next/server/app/api/public/posts/route.js.nft.json +1 -0
  262. package/.next/server/app/api/public/posts/route_client-reference-manifest.js +3 -0
  263. package/.next/server/app/api/public/unsubscribe/route/app-paths-manifest.json +3 -0
  264. package/.next/server/app/api/public/unsubscribe/route/build-manifest.json +12 -0
  265. package/.next/server/app/api/public/unsubscribe/route/server-reference-manifest.json +4 -0
  266. package/.next/server/app/api/public/unsubscribe/route.js +9 -0
  267. package/.next/server/app/api/public/unsubscribe/route.js.map +5 -0
  268. package/.next/server/app/api/public/unsubscribe/route.js.nft.json +1 -0
  269. package/.next/server/app/api/public/unsubscribe/route_client-reference-manifest.js +3 -0
  270. package/.next/server/app/api/route/app-paths-manifest.json +3 -0
  271. package/.next/server/app/api/route/build-manifest.json +12 -0
  272. package/.next/server/app/api/route/server-reference-manifest.json +4 -0
  273. package/.next/server/app/api/route.js +7 -0
  274. package/.next/server/app/api/route.js.map +5 -0
  275. package/.next/server/app/api/route.js.nft.json +1 -0
  276. package/.next/server/app/api/route_client-reference-manifest.js +3 -0
  277. package/.next/server/app/api/senders/[id]/route/app-paths-manifest.json +3 -0
  278. package/.next/server/app/api/senders/[id]/route/build-manifest.json +12 -0
  279. package/.next/server/app/api/senders/[id]/route/server-reference-manifest.json +4 -0
  280. package/.next/server/app/api/senders/[id]/route.js +8 -0
  281. package/.next/server/app/api/senders/[id]/route.js.map +5 -0
  282. package/.next/server/app/api/senders/[id]/route.js.nft.json +1 -0
  283. package/.next/server/app/api/senders/[id]/route_client-reference-manifest.js +3 -0
  284. package/.next/server/app/api/senders/route/app-paths-manifest.json +3 -0
  285. package/.next/server/app/api/senders/route/build-manifest.json +12 -0
  286. package/.next/server/app/api/senders/route/server-reference-manifest.json +4 -0
  287. package/.next/server/app/api/senders/route.js +11 -0
  288. package/.next/server/app/api/senders/route.js.map +5 -0
  289. package/.next/server/app/api/senders/route.js.nft.json +1 -0
  290. package/.next/server/app/api/senders/route_client-reference-manifest.js +3 -0
  291. package/.next/server/app/api/settings/telegram/route/app-paths-manifest.json +3 -0
  292. package/.next/server/app/api/settings/telegram/route/build-manifest.json +12 -0
  293. package/.next/server/app/api/settings/telegram/route/server-reference-manifest.json +4 -0
  294. package/.next/server/app/api/settings/telegram/route.js +9 -0
  295. package/.next/server/app/api/settings/telegram/route.js.map +5 -0
  296. package/.next/server/app/api/settings/telegram/route.js.nft.json +1 -0
  297. package/.next/server/app/api/settings/telegram/route_client-reference-manifest.js +3 -0
  298. package/.next/server/app/api/settings/telegram/stats/route/app-paths-manifest.json +3 -0
  299. package/.next/server/app/api/settings/telegram/stats/route/build-manifest.json +12 -0
  300. package/.next/server/app/api/settings/telegram/stats/route/server-reference-manifest.json +4 -0
  301. package/.next/server/app/api/settings/telegram/stats/route.js +8 -0
  302. package/.next/server/app/api/settings/telegram/stats/route.js.map +5 -0
  303. package/.next/server/app/api/settings/telegram/stats/route.js.nft.json +1 -0
  304. package/.next/server/app/api/settings/telegram/stats/route_client-reference-manifest.js +3 -0
  305. package/.next/server/app/api/stats/route/app-paths-manifest.json +3 -0
  306. package/.next/server/app/api/stats/route/build-manifest.json +12 -0
  307. package/.next/server/app/api/stats/route/server-reference-manifest.json +4 -0
  308. package/.next/server/app/api/stats/route.js +8 -0
  309. package/.next/server/app/api/stats/route.js.map +5 -0
  310. package/.next/server/app/api/stats/route.js.nft.json +1 -0
  311. package/.next/server/app/api/stats/route_client-reference-manifest.js +3 -0
  312. package/.next/server/app/api/t/[token]/route/app-paths-manifest.json +3 -0
  313. package/.next/server/app/api/t/[token]/route/build-manifest.json +12 -0
  314. package/.next/server/app/api/t/[token]/route/server-reference-manifest.json +4 -0
  315. package/.next/server/app/api/t/[token]/route.js +8 -0
  316. package/.next/server/app/api/t/[token]/route.js.map +5 -0
  317. package/.next/server/app/api/t/[token]/route.js.nft.json +1 -0
  318. package/.next/server/app/api/t/[token]/route_client-reference-manifest.js +3 -0
  319. package/.next/server/app/api/templates/[id]/route/app-paths-manifest.json +3 -0
  320. package/.next/server/app/api/templates/[id]/route/build-manifest.json +12 -0
  321. package/.next/server/app/api/templates/[id]/route/server-reference-manifest.json +4 -0
  322. package/.next/server/app/api/templates/[id]/route.js +8 -0
  323. package/.next/server/app/api/templates/[id]/route.js.map +5 -0
  324. package/.next/server/app/api/templates/[id]/route.js.nft.json +1 -0
  325. package/.next/server/app/api/templates/[id]/route_client-reference-manifest.js +3 -0
  326. package/.next/server/app/api/templates/route/app-paths-manifest.json +3 -0
  327. package/.next/server/app/api/templates/route/build-manifest.json +12 -0
  328. package/.next/server/app/api/templates/route/server-reference-manifest.json +4 -0
  329. package/.next/server/app/api/templates/route.js +8 -0
  330. package/.next/server/app/api/templates/route.js.map +5 -0
  331. package/.next/server/app/api/templates/route.js.nft.json +1 -0
  332. package/.next/server/app/api/templates/route_client-reference-manifest.js +3 -0
  333. package/.next/server/app/api/workflows/[id]/enroll/route/app-paths-manifest.json +3 -0
  334. package/.next/server/app/api/workflows/[id]/enroll/route/build-manifest.json +12 -0
  335. package/.next/server/app/api/workflows/[id]/enroll/route/server-reference-manifest.json +4 -0
  336. package/.next/server/app/api/workflows/[id]/enroll/route.js +15 -0
  337. package/.next/server/app/api/workflows/[id]/enroll/route.js.map +5 -0
  338. package/.next/server/app/api/workflows/[id]/enroll/route.js.nft.json +1 -0
  339. package/.next/server/app/api/workflows/[id]/enroll/route_client-reference-manifest.js +3 -0
  340. package/.next/server/app/api/workflows/[id]/route/app-paths-manifest.json +3 -0
  341. package/.next/server/app/api/workflows/[id]/route/build-manifest.json +12 -0
  342. package/.next/server/app/api/workflows/[id]/route/server-reference-manifest.json +4 -0
  343. package/.next/server/app/api/workflows/[id]/route.js +8 -0
  344. package/.next/server/app/api/workflows/[id]/route.js.map +5 -0
  345. package/.next/server/app/api/workflows/[id]/route.js.nft.json +1 -0
  346. package/.next/server/app/api/workflows/[id]/route_client-reference-manifest.js +3 -0
  347. package/.next/server/app/api/workflows/[id]/run/route/app-paths-manifest.json +3 -0
  348. package/.next/server/app/api/workflows/[id]/run/route/build-manifest.json +12 -0
  349. package/.next/server/app/api/workflows/[id]/run/route/server-reference-manifest.json +4 -0
  350. package/.next/server/app/api/workflows/[id]/run/route.js +15 -0
  351. package/.next/server/app/api/workflows/[id]/run/route.js.map +5 -0
  352. package/.next/server/app/api/workflows/[id]/run/route.js.nft.json +1 -0
  353. package/.next/server/app/api/workflows/[id]/run/route_client-reference-manifest.js +3 -0
  354. package/.next/server/app/api/workflows/route/app-paths-manifest.json +3 -0
  355. package/.next/server/app/api/workflows/route/build-manifest.json +12 -0
  356. package/.next/server/app/api/workflows/route/server-reference-manifest.json +4 -0
  357. package/.next/server/app/api/workflows/route.js +8 -0
  358. package/.next/server/app/api/workflows/route.js.map +5 -0
  359. package/.next/server/app/api/workflows/route.js.nft.json +1 -0
  360. package/.next/server/app/api/workflows/route_client-reference-manifest.js +3 -0
  361. package/.next/server/app/blog/[slug]/page/app-paths-manifest.json +3 -0
  362. package/.next/server/app/blog/[slug]/page/build-manifest.json +22 -0
  363. package/.next/server/app/blog/[slug]/page/next-font-manifest.json +6 -0
  364. package/.next/server/app/blog/[slug]/page/react-loadable-manifest.json +1 -0
  365. package/.next/server/app/blog/[slug]/page/server-reference-manifest.json +4 -0
  366. package/.next/server/app/blog/[slug]/page.js +19 -0
  367. package/.next/server/app/blog/[slug]/page.js.map +5 -0
  368. package/.next/server/app/blog/[slug]/page.js.nft.json +1 -0
  369. package/.next/server/app/blog/[slug]/page_client-reference-manifest.js +3 -0
  370. package/.next/server/app/blog/page/app-paths-manifest.json +3 -0
  371. package/.next/server/app/blog/page/build-manifest.json +22 -0
  372. package/.next/server/app/blog/page/next-font-manifest.json +6 -0
  373. package/.next/server/app/blog/page/react-loadable-manifest.json +1 -0
  374. package/.next/server/app/blog/page/server-reference-manifest.json +4 -0
  375. package/.next/server/app/blog/page.js +16 -0
  376. package/.next/server/app/blog/page.js.map +5 -0
  377. package/.next/server/app/blog/page.js.nft.json +1 -0
  378. package/.next/server/app/blog/page_client-reference-manifest.js +3 -0
  379. package/.next/server/app/dashboard/automations/page/app-paths-manifest.json +3 -0
  380. package/.next/server/app/dashboard/automations/page/build-manifest.json +22 -0
  381. package/.next/server/app/dashboard/automations/page/next-font-manifest.json +6 -0
  382. package/.next/server/app/dashboard/automations/page/react-loadable-manifest.json +1 -0
  383. package/.next/server/app/dashboard/automations/page/server-reference-manifest.json +4 -0
  384. package/.next/server/app/dashboard/automations/page.js +18 -0
  385. package/.next/server/app/dashboard/automations/page.js.map +5 -0
  386. package/.next/server/app/dashboard/automations/page.js.nft.json +1 -0
  387. package/.next/server/app/dashboard/automations/page_client-reference-manifest.js +3 -0
  388. package/.next/server/app/dashboard/campaigns/[id]/page/app-paths-manifest.json +3 -0
  389. package/.next/server/app/dashboard/campaigns/[id]/page/build-manifest.json +22 -0
  390. package/.next/server/app/dashboard/campaigns/[id]/page/next-font-manifest.json +6 -0
  391. package/.next/server/app/dashboard/campaigns/[id]/page/react-loadable-manifest.json +10 -0
  392. package/.next/server/app/dashboard/campaigns/[id]/page/server-reference-manifest.json +4 -0
  393. package/.next/server/app/dashboard/campaigns/[id]/page.js +18 -0
  394. package/.next/server/app/dashboard/campaigns/[id]/page.js.map +5 -0
  395. package/.next/server/app/dashboard/campaigns/[id]/page.js.nft.json +1 -0
  396. package/.next/server/app/dashboard/campaigns/[id]/page_client-reference-manifest.js +3 -0
  397. package/.next/server/app/dashboard/campaigns/page/app-paths-manifest.json +3 -0
  398. package/.next/server/app/dashboard/campaigns/page/build-manifest.json +22 -0
  399. package/.next/server/app/dashboard/campaigns/page/next-font-manifest.json +6 -0
  400. package/.next/server/app/dashboard/campaigns/page/react-loadable-manifest.json +1 -0
  401. package/.next/server/app/dashboard/campaigns/page/server-reference-manifest.json +4 -0
  402. package/.next/server/app/dashboard/campaigns/page.js +18 -0
  403. package/.next/server/app/dashboard/campaigns/page.js.map +5 -0
  404. package/.next/server/app/dashboard/campaigns/page.js.nft.json +1 -0
  405. package/.next/server/app/dashboard/campaigns/page_client-reference-manifest.js +3 -0
  406. package/.next/server/app/dashboard/contacts/page/app-paths-manifest.json +3 -0
  407. package/.next/server/app/dashboard/contacts/page/build-manifest.json +22 -0
  408. package/.next/server/app/dashboard/contacts/page/next-font-manifest.json +6 -0
  409. package/.next/server/app/dashboard/contacts/page/react-loadable-manifest.json +1 -0
  410. package/.next/server/app/dashboard/contacts/page/server-reference-manifest.json +4 -0
  411. package/.next/server/app/dashboard/contacts/page.js +18 -0
  412. package/.next/server/app/dashboard/contacts/page.js.map +5 -0
  413. package/.next/server/app/dashboard/contacts/page.js.nft.json +1 -0
  414. package/.next/server/app/dashboard/contacts/page_client-reference-manifest.js +3 -0
  415. package/.next/server/app/dashboard/forms/page/app-paths-manifest.json +3 -0
  416. package/.next/server/app/dashboard/forms/page/build-manifest.json +22 -0
  417. package/.next/server/app/dashboard/forms/page/next-font-manifest.json +6 -0
  418. package/.next/server/app/dashboard/forms/page/react-loadable-manifest.json +1 -0
  419. package/.next/server/app/dashboard/forms/page/server-reference-manifest.json +4 -0
  420. package/.next/server/app/dashboard/forms/page.js +18 -0
  421. package/.next/server/app/dashboard/forms/page.js.map +5 -0
  422. package/.next/server/app/dashboard/forms/page.js.nft.json +1 -0
  423. package/.next/server/app/dashboard/forms/page_client-reference-manifest.js +3 -0
  424. package/.next/server/app/dashboard/media/page/app-paths-manifest.json +3 -0
  425. package/.next/server/app/dashboard/media/page/build-manifest.json +22 -0
  426. package/.next/server/app/dashboard/media/page/next-font-manifest.json +6 -0
  427. package/.next/server/app/dashboard/media/page/react-loadable-manifest.json +1 -0
  428. package/.next/server/app/dashboard/media/page/server-reference-manifest.json +4 -0
  429. package/.next/server/app/dashboard/media/page.js +18 -0
  430. package/.next/server/app/dashboard/media/page.js.map +5 -0
  431. package/.next/server/app/dashboard/media/page.js.nft.json +1 -0
  432. package/.next/server/app/dashboard/media/page_client-reference-manifest.js +3 -0
  433. package/.next/server/app/dashboard/page/app-paths-manifest.json +3 -0
  434. package/.next/server/app/dashboard/page/build-manifest.json +22 -0
  435. package/.next/server/app/dashboard/page/next-font-manifest.json +6 -0
  436. package/.next/server/app/dashboard/page/react-loadable-manifest.json +1 -0
  437. package/.next/server/app/dashboard/page/server-reference-manifest.json +4 -0
  438. package/.next/server/app/dashboard/page.js +18 -0
  439. package/.next/server/app/dashboard/page.js.map +5 -0
  440. package/.next/server/app/dashboard/page.js.nft.json +1 -0
  441. package/.next/server/app/dashboard/page_client-reference-manifest.js +3 -0
  442. package/.next/server/app/dashboard/senders/page/app-paths-manifest.json +3 -0
  443. package/.next/server/app/dashboard/senders/page/build-manifest.json +22 -0
  444. package/.next/server/app/dashboard/senders/page/next-font-manifest.json +6 -0
  445. package/.next/server/app/dashboard/senders/page/react-loadable-manifest.json +1 -0
  446. package/.next/server/app/dashboard/senders/page/server-reference-manifest.json +4 -0
  447. package/.next/server/app/dashboard/senders/page.js +18 -0
  448. package/.next/server/app/dashboard/senders/page.js.map +5 -0
  449. package/.next/server/app/dashboard/senders/page.js.nft.json +1 -0
  450. package/.next/server/app/dashboard/senders/page_client-reference-manifest.js +3 -0
  451. package/.next/server/app/dashboard/settings/page/app-paths-manifest.json +3 -0
  452. package/.next/server/app/dashboard/settings/page/build-manifest.json +22 -0
  453. package/.next/server/app/dashboard/settings/page/next-font-manifest.json +6 -0
  454. package/.next/server/app/dashboard/settings/page/react-loadable-manifest.json +1 -0
  455. package/.next/server/app/dashboard/settings/page/server-reference-manifest.json +4 -0
  456. package/.next/server/app/dashboard/settings/page.js +18 -0
  457. package/.next/server/app/dashboard/settings/page.js.map +5 -0
  458. package/.next/server/app/dashboard/settings/page.js.nft.json +1 -0
  459. package/.next/server/app/dashboard/settings/page_client-reference-manifest.js +3 -0
  460. package/.next/server/app/doc/page/app-paths-manifest.json +3 -0
  461. package/.next/server/app/doc/page/build-manifest.json +22 -0
  462. package/.next/server/app/doc/page/next-font-manifest.json +6 -0
  463. package/.next/server/app/doc/page/react-loadable-manifest.json +1 -0
  464. package/.next/server/app/doc/page/server-reference-manifest.json +4 -0
  465. package/.next/server/app/doc/page.js +16 -0
  466. package/.next/server/app/doc/page.js.map +5 -0
  467. package/.next/server/app/doc/page.js.nft.json +1 -0
  468. package/.next/server/app/doc/page_client-reference-manifest.js +3 -0
  469. package/.next/server/app/doc.html +1 -0
  470. package/.next/server/app/doc.meta +36 -0
  471. package/.next/server/app/doc.rsc +26 -0
  472. package/.next/server/app/doc.segments/_full.segment.rsc +26 -0
  473. package/.next/server/app/doc.segments/_tree.segment.rsc +4 -0
  474. package/.next/server/app/doc.segments/doc/__PAGE__.segment.rsc +32 -0
  475. package/.next/server/app/documentation/page/app-paths-manifest.json +3 -0
  476. package/.next/server/app/documentation/page/build-manifest.json +22 -0
  477. package/.next/server/app/documentation/page/next-font-manifest.json +6 -0
  478. package/.next/server/app/documentation/page/react-loadable-manifest.json +1 -0
  479. package/.next/server/app/documentation/page/server-reference-manifest.json +4 -0
  480. package/.next/server/app/documentation/page.js +16 -0
  481. package/.next/server/app/documentation/page.js.map +5 -0
  482. package/.next/server/app/documentation/page.js.nft.json +1 -0
  483. package/.next/server/app/documentation/page_client-reference-manifest.js +3 -0
  484. package/.next/server/app/documentation.html +1 -0
  485. package/.next/server/app/documentation.meta +36 -0
  486. package/.next/server/app/documentation.rsc +26 -0
  487. package/.next/server/app/documentation.segments/_full.segment.rsc +26 -0
  488. package/.next/server/app/documentation.segments/_tree.segment.rsc +4 -0
  489. package/.next/server/app/documentation.segments/documentation/__PAGE__.segment.rsc +32 -0
  490. package/.next/server/app/index.html +1 -0
  491. package/.next/server/app/index.meta +29 -0
  492. package/.next/server/app/index.rsc +26 -0
  493. package/.next/server/app/index.segments/__PAGE__.segment.rsc +31 -0
  494. package/.next/server/app/index.segments/_full.segment.rsc +26 -0
  495. package/.next/server/app/index.segments/_tree.segment.rsc +3 -0
  496. package/.next/server/app/login/page/app-paths-manifest.json +3 -0
  497. package/.next/server/app/login/page/build-manifest.json +22 -0
  498. package/.next/server/app/login/page/next-font-manifest.json +6 -0
  499. package/.next/server/app/login/page/react-loadable-manifest.json +1 -0
  500. package/.next/server/app/login/page/server-reference-manifest.json +4 -0
  501. package/.next/server/app/login/page.js +14 -0
  502. package/.next/server/app/login/page.js.map +5 -0
  503. package/.next/server/app/login/page.js.nft.json +1 -0
  504. package/.next/server/app/login/page_client-reference-manifest.js +3 -0
  505. package/.next/server/app/login.html +1 -0
  506. package/.next/server/app/login.meta +34 -0
  507. package/.next/server/app/login.rsc +27 -0
  508. package/.next/server/app/login.segments/_full.segment.rsc +27 -0
  509. package/.next/server/app/login.segments/_tree.segment.rsc +4 -0
  510. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +33 -0
  511. package/.next/server/app/page/app-paths-manifest.json +3 -0
  512. package/.next/server/app/page/build-manifest.json +22 -0
  513. package/.next/server/app/page/next-font-manifest.json +6 -0
  514. package/.next/server/app/page/react-loadable-manifest.json +1 -0
  515. package/.next/server/app/page/server-reference-manifest.json +4 -0
  516. package/.next/server/app/page.js +14 -0
  517. package/.next/server/app/page.js.map +5 -0
  518. package/.next/server/app/page.js.nft.json +1 -0
  519. package/.next/server/app/page_client-reference-manifest.js +3 -0
  520. package/.next/server/app/unsubscribe/page/app-paths-manifest.json +3 -0
  521. package/.next/server/app/unsubscribe/page/build-manifest.json +22 -0
  522. package/.next/server/app/unsubscribe/page/next-font-manifest.json +6 -0
  523. package/.next/server/app/unsubscribe/page/react-loadable-manifest.json +1 -0
  524. package/.next/server/app/unsubscribe/page/server-reference-manifest.json +4 -0
  525. package/.next/server/app/unsubscribe/page.js +14 -0
  526. package/.next/server/app/unsubscribe/page.js.map +5 -0
  527. package/.next/server/app/unsubscribe/page.js.nft.json +1 -0
  528. package/.next/server/app/unsubscribe/page_client-reference-manifest.js +3 -0
  529. package/.next/server/app/unsubscribe.html +1 -0
  530. package/.next/server/app/unsubscribe.meta +34 -0
  531. package/.next/server/app/unsubscribe.rsc +31 -0
  532. package/.next/server/app/unsubscribe.segments/_full.segment.rsc +31 -0
  533. package/.next/server/app/unsubscribe.segments/_tree.segment.rsc +4 -0
  534. package/.next/server/app/unsubscribe.segments/unsubscribe/__PAGE__.segment.rsc +37 -0
  535. package/.next/server/app-paths-manifest.json +63 -0
  536. package/.next/server/chunks/06xu_next_dist_esm_build_templates_app-route_0rhnea3oufq9j.js +3 -0
  537. package/.next/server/chunks/06xu_next_dist_esm_build_templates_app-route_0rhnea3oufq9j.js.map +1 -0
  538. package/.next/server/chunks/14u8_jose_dist_webapi_jwt_sign_0e9dnv3w_dkc3.js +3 -0
  539. package/.next/server/chunks/14u8_jose_dist_webapi_jwt_sign_0e9dnv3w_dkc3.js.map +1 -0
  540. package/.next/server/chunks/1oeh_server_app_api_settings_telegram_stats_route_actions_0y5ocpob4bzxr.js +3 -0
  541. package/.next/server/chunks/1oeh_server_app_api_settings_telegram_stats_route_actions_0y5ocpob4bzxr.js.map +1 -0
  542. package/.next/server/chunks/[externals]__15ba62yk88w55._.js +3 -0
  543. package/.next/server/chunks/[externals]__15ba62yk88w55._.js.map +1 -0
  544. package/.next/server/chunks/[externals]__1da-de2642zdu._.js +3 -0
  545. package/.next/server/chunks/[externals]__1da-de2642zdu._.js.map +1 -0
  546. package/.next/server/chunks/[root-of-the-server]__00t3s_fd941rt._.js +3 -0
  547. package/.next/server/chunks/[root-of-the-server]__00t3s_fd941rt._.js.map +1 -0
  548. package/.next/server/chunks/[root-of-the-server]__07pbetxujjj00._.js +3 -0
  549. package/.next/server/chunks/[root-of-the-server]__07pbetxujjj00._.js.map +1 -0
  550. package/.next/server/chunks/[root-of-the-server]__0a6x-tjsjctmn._.js +3 -0
  551. package/.next/server/chunks/[root-of-the-server]__0a6x-tjsjctmn._.js.map +1 -0
  552. package/.next/server/chunks/[root-of-the-server]__0bg8pg0fpimav._.js +3 -0
  553. package/.next/server/chunks/[root-of-the-server]__0bg8pg0fpimav._.js.map +1 -0
  554. package/.next/server/chunks/[root-of-the-server]__0e93ko_-d32s0._.js +3 -0
  555. package/.next/server/chunks/[root-of-the-server]__0e93ko_-d32s0._.js.map +1 -0
  556. package/.next/server/chunks/[root-of-the-server]__0m07o9851_xfr._.js +3 -0
  557. package/.next/server/chunks/[root-of-the-server]__0m07o9851_xfr._.js.map +1 -0
  558. package/.next/server/chunks/[root-of-the-server]__0mswm6179vwl1._.js +3 -0
  559. package/.next/server/chunks/[root-of-the-server]__0mswm6179vwl1._.js.map +1 -0
  560. package/.next/server/chunks/[root-of-the-server]__0mz1nms56oghw._.js +3 -0
  561. package/.next/server/chunks/[root-of-the-server]__0mz1nms56oghw._.js.map +1 -0
  562. package/.next/server/chunks/[root-of-the-server]__0rtfqbe0ob35m._.js +3 -0
  563. package/.next/server/chunks/[root-of-the-server]__0rtfqbe0ob35m._.js.map +1 -0
  564. package/.next/server/chunks/[root-of-the-server]__153ayjbkba0bf._.js +3 -0
  565. package/.next/server/chunks/[root-of-the-server]__153ayjbkba0bf._.js.map +1 -0
  566. package/.next/server/chunks/[root-of-the-server]__1ap2hmo6cbsb3._.js +3 -0
  567. package/.next/server/chunks/[root-of-the-server]__1ap2hmo6cbsb3._.js.map +1 -0
  568. package/.next/server/chunks/[root-of-the-server]__1em5dex851pk2._.js +63 -0
  569. package/.next/server/chunks/[root-of-the-server]__1em5dex851pk2._.js.map +1 -0
  570. package/.next/server/chunks/[root-of-the-server]__1llxcp69_fvli._.js +3 -0
  571. package/.next/server/chunks/[root-of-the-server]__1llxcp69_fvli._.js.map +1 -0
  572. package/.next/server/chunks/[root-of-the-server]__1oipwj090n6_7._.js +3 -0
  573. package/.next/server/chunks/[root-of-the-server]__1oipwj090n6_7._.js.map +1 -0
  574. package/.next/server/chunks/[root-of-the-server]__1zybyzpuf50yc._.js +3 -0
  575. package/.next/server/chunks/[root-of-the-server]__1zybyzpuf50yc._.js.map +1 -0
  576. package/.next/server/chunks/[root-of-the-server]__20eb2dgpl3qoj._.js +3 -0
  577. package/.next/server/chunks/[root-of-the-server]__20eb2dgpl3qoj._.js.map +1 -0
  578. package/.next/server/chunks/[turbopack]_runtime.js +935 -0
  579. package/.next/server/chunks/[turbopack]_runtime.js.map +10 -0
  580. package/.next/server/chunks/_016pksr_tokt8._.js +3 -0
  581. package/.next/server/chunks/_016pksr_tokt8._.js.map +1 -0
  582. package/.next/server/chunks/_01htjrztdn3g5._.js +3 -0
  583. package/.next/server/chunks/_01htjrztdn3g5._.js.map +1 -0
  584. package/.next/server/chunks/_01n_eoupdy17l._.js +3 -0
  585. package/.next/server/chunks/_01n_eoupdy17l._.js.map +1 -0
  586. package/.next/server/chunks/_03yxncv3hk3vr._.js +3 -0
  587. package/.next/server/chunks/_03yxncv3hk3vr._.js.map +1 -0
  588. package/.next/server/chunks/_040a09tcfi6x9._.js +3 -0
  589. package/.next/server/chunks/_040a09tcfi6x9._.js.map +1 -0
  590. package/.next/server/chunks/_04_9nfa-lxjd9._.js +3 -0
  591. package/.next/server/chunks/_04_9nfa-lxjd9._.js.map +1 -0
  592. package/.next/server/chunks/_04bjifcoxwu5o._.js +3 -0
  593. package/.next/server/chunks/_04bjifcoxwu5o._.js.map +1 -0
  594. package/.next/server/chunks/_07u19kpttm6vp._.js +3 -0
  595. package/.next/server/chunks/_07u19kpttm6vp._.js.map +1 -0
  596. package/.next/server/chunks/_09-td-68cdtha._.js +3 -0
  597. package/.next/server/chunks/_09-td-68cdtha._.js.map +1 -0
  598. package/.next/server/chunks/_09r_gh4zqv3wl._.js +3 -0
  599. package/.next/server/chunks/_09r_gh4zqv3wl._.js.map +1 -0
  600. package/.next/server/chunks/_0_-vw5kg2iooe._.js +3 -0
  601. package/.next/server/chunks/_0_-vw5kg2iooe._.js.map +1 -0
  602. package/.next/server/chunks/_0fyvad-iex4-9._.js +3 -0
  603. package/.next/server/chunks/_0fyvad-iex4-9._.js.map +1 -0
  604. package/.next/server/chunks/_0h--d0xv_53cr._.js +3 -0
  605. package/.next/server/chunks/_0h--d0xv_53cr._.js.map +1 -0
  606. package/.next/server/chunks/_0ih52_m6zdv66._.js +3 -0
  607. package/.next/server/chunks/_0ih52_m6zdv66._.js.map +1 -0
  608. package/.next/server/chunks/_0ioztrwebatxi._.js +3 -0
  609. package/.next/server/chunks/_0ioztrwebatxi._.js.map +1 -0
  610. package/.next/server/chunks/_0mf3thpvi2w9-._.js +3 -0
  611. package/.next/server/chunks/_0mf3thpvi2w9-._.js.map +1 -0
  612. package/.next/server/chunks/_0mxirr5hu7uvj._.js +3 -0
  613. package/.next/server/chunks/_0mxirr5hu7uvj._.js.map +1 -0
  614. package/.next/server/chunks/_0p2s1sp75f_j9._.js +3 -0
  615. package/.next/server/chunks/_0p2s1sp75f_j9._.js.map +1 -0
  616. package/.next/server/chunks/_0q47xwx7d_6ra._.js +3 -0
  617. package/.next/server/chunks/_0q47xwx7d_6ra._.js.map +1 -0
  618. package/.next/server/chunks/_0r4rhsoq7d2hp._.js +3 -0
  619. package/.next/server/chunks/_0r4rhsoq7d2hp._.js.map +1 -0
  620. package/.next/server/chunks/_0t_kwe5a4tov4._.js +3 -0
  621. package/.next/server/chunks/_0t_kwe5a4tov4._.js.map +1 -0
  622. package/.next/server/chunks/_0tx_colipxkxn._.js +3 -0
  623. package/.next/server/chunks/_0tx_colipxkxn._.js.map +1 -0
  624. package/.next/server/chunks/_0vpnhlc3j1p06._.js +3 -0
  625. package/.next/server/chunks/_0vpnhlc3j1p06._.js.map +1 -0
  626. package/.next/server/chunks/_1-ti64gr5yz18._.js +3 -0
  627. package/.next/server/chunks/_1-ti64gr5yz18._.js.map +1 -0
  628. package/.next/server/chunks/_1-xxzx1khwzji._.js +3 -0
  629. package/.next/server/chunks/_1-xxzx1khwzji._.js.map +1 -0
  630. package/.next/server/chunks/_18qgmv1t3_d91._.js +3 -0
  631. package/.next/server/chunks/_18qgmv1t3_d91._.js.map +1 -0
  632. package/.next/server/chunks/_18rxxnsk2a6wq._.js +3 -0
  633. package/.next/server/chunks/_18rxxnsk2a6wq._.js.map +1 -0
  634. package/.next/server/chunks/_1cwegmbbn2hju._.js +3 -0
  635. package/.next/server/chunks/_1cwegmbbn2hju._.js.map +1 -0
  636. package/.next/server/chunks/_1f94wdko3-7rw._.js +3 -0
  637. package/.next/server/chunks/_1f94wdko3-7rw._.js.map +1 -0
  638. package/.next/server/chunks/_1gp6hcs1274ln._.js +3 -0
  639. package/.next/server/chunks/_1gp6hcs1274ln._.js.map +1 -0
  640. package/.next/server/chunks/_1h445ssbyo_y5._.js +3 -0
  641. package/.next/server/chunks/_1h445ssbyo_y5._.js.map +1 -0
  642. package/.next/server/chunks/_1h6whc3etiive._.js +3 -0
  643. package/.next/server/chunks/_1h6whc3etiive._.js.map +1 -0
  644. package/.next/server/chunks/_1iji2r4-sk-we._.js +3 -0
  645. package/.next/server/chunks/_1iji2r4-sk-we._.js.map +1 -0
  646. package/.next/server/chunks/_1k4vlrzpby6a_._.js +3 -0
  647. package/.next/server/chunks/_1k4vlrzpby6a_._.js.map +1 -0
  648. package/.next/server/chunks/_1lv9rcsvu5f_o._.js +3 -0
  649. package/.next/server/chunks/_1lv9rcsvu5f_o._.js.map +1 -0
  650. package/.next/server/chunks/_1mz0a5he7e22i._.js +3 -0
  651. package/.next/server/chunks/_1mz0a5he7e22i._.js.map +1 -0
  652. package/.next/server/chunks/_1o0ng4bsm4gyq._.js +3 -0
  653. package/.next/server/chunks/_1o0ng4bsm4gyq._.js.map +1 -0
  654. package/.next/server/chunks/_1o2yk6-lm2_f5._.js +3 -0
  655. package/.next/server/chunks/_1o2yk6-lm2_f5._.js.map +1 -0
  656. package/.next/server/chunks/_1qu9xleffmuhh._.js +3 -0
  657. package/.next/server/chunks/_1qu9xleffmuhh._.js.map +1 -0
  658. package/.next/server/chunks/_1sma8mtgsvlrb._.js +3 -0
  659. package/.next/server/chunks/_1sma8mtgsvlrb._.js.map +1 -0
  660. package/.next/server/chunks/_1uilkda5rycrk._.js +3 -0
  661. package/.next/server/chunks/_1uilkda5rycrk._.js.map +1 -0
  662. package/.next/server/chunks/_1vclmxko_5xe0._.js +3 -0
  663. package/.next/server/chunks/_1vclmxko_5xe0._.js.map +1 -0
  664. package/.next/server/chunks/_1y1s5uiktpy3o._.js +3 -0
  665. package/.next/server/chunks/_1y1s5uiktpy3o._.js.map +1 -0
  666. package/.next/server/chunks/_next-internal_server_app_api_auth_login_route_actions_1ox7zi0683rx3.js +3 -0
  667. package/.next/server/chunks/_next-internal_server_app_api_auth_login_route_actions_1ox7zi0683rx3.js.map +1 -0
  668. package/.next/server/chunks/_next-internal_server_app_api_auth_logout_route_actions_0regwyrnie28t.js +3 -0
  669. package/.next/server/chunks/_next-internal_server_app_api_auth_logout_route_actions_0regwyrnie28t.js.map +1 -0
  670. package/.next/server/chunks/_next-internal_server_app_api_auth_session_route_actions_0-ylu5i7oqlzd.js +3 -0
  671. package/.next/server/chunks/_next-internal_server_app_api_auth_session_route_actions_0-ylu5i7oqlzd.js.map +1 -0
  672. package/.next/server/chunks/_next-internal_server_app_api_auth_setup_route_actions_14j5aonxk6m_0.js +3 -0
  673. package/.next/server/chunks/_next-internal_server_app_api_auth_setup_route_actions_14j5aonxk6m_0.js.map +1 -0
  674. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_publish_route_actions_09311-fzm8pgf.js +3 -0
  675. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_publish_route_actions_09311-fzm8pgf.js.map +1 -0
  676. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_route_actions_1a0zhdfdyla42.js +3 -0
  677. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_route_actions_1a0zhdfdyla42.js.map +1 -0
  678. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_send_route_actions_1av8d5nb-ear4.js +3 -0
  679. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_send_route_actions_1av8d5nb-ear4.js.map +1 -0
  680. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_stats_route_actions_06bh5t647rne9.js +3 -0
  681. package/.next/server/chunks/_next-internal_server_app_api_campaigns_[id]_stats_route_actions_06bh5t647rne9.js.map +1 -0
  682. package/.next/server/chunks/_next-internal_server_app_api_campaigns_all_route_actions_0vv-2ofeydk_2.js +3 -0
  683. package/.next/server/chunks/_next-internal_server_app_api_campaigns_all_route_actions_0vv-2ofeydk_2.js.map +1 -0
  684. package/.next/server/chunks/_next-internal_server_app_api_campaigns_route_actions_1z1l7o3vmwi8j.js +3 -0
  685. package/.next/server/chunks/_next-internal_server_app_api_campaigns_route_actions_1z1l7o3vmwi8j.js.map +1 -0
  686. package/.next/server/chunks/_next-internal_server_app_api_contacts_[id]_route_actions_0edp9gto9mrwd.js +3 -0
  687. package/.next/server/chunks/_next-internal_server_app_api_contacts_[id]_route_actions_0edp9gto9mrwd.js.map +1 -0
  688. package/.next/server/chunks/_next-internal_server_app_api_contacts_all_route_actions_1kp0fjcv5w1lz.js +3 -0
  689. package/.next/server/chunks/_next-internal_server_app_api_contacts_all_route_actions_1kp0fjcv5w1lz.js.map +1 -0
  690. package/.next/server/chunks/_next-internal_server_app_api_contacts_import_route_actions_1u0x5u848vtkc.js +3 -0
  691. package/.next/server/chunks/_next-internal_server_app_api_contacts_import_route_actions_1u0x5u848vtkc.js.map +1 -0
  692. package/.next/server/chunks/_next-internal_server_app_api_contacts_route_actions_1bx4umbpbb4es.js +3 -0
  693. package/.next/server/chunks/_next-internal_server_app_api_contacts_route_actions_1bx4umbpbb4es.js.map +1 -0
  694. package/.next/server/chunks/_next-internal_server_app_api_cron_route_actions_0hfzp9ksvuhv8.js +3 -0
  695. package/.next/server/chunks/_next-internal_server_app_api_cron_route_actions_0hfzp9ksvuhv8.js.map +1 -0
  696. package/.next/server/chunks/_next-internal_server_app_api_forms_[id]_route_actions_1zn9c6hm712n_.js +3 -0
  697. package/.next/server/chunks/_next-internal_server_app_api_forms_[id]_route_actions_1zn9c6hm712n_.js.map +1 -0
  698. package/.next/server/chunks/_next-internal_server_app_api_forms_[id]_submissions_route_actions_0npj-livx0neo.js +3 -0
  699. package/.next/server/chunks/_next-internal_server_app_api_forms_[id]_submissions_route_actions_0npj-livx0neo.js.map +1 -0
  700. package/.next/server/chunks/_next-internal_server_app_api_forms_[id]_submit_route_actions_1p_av2ya-hn__.js +3 -0
  701. package/.next/server/chunks/_next-internal_server_app_api_forms_[id]_submit_route_actions_1p_av2ya-hn__.js.map +1 -0
  702. package/.next/server/chunks/_next-internal_server_app_api_forms_route_actions_0wx1h14s4xiqj.js +3 -0
  703. package/.next/server/chunks/_next-internal_server_app_api_forms_route_actions_0wx1h14s4xiqj.js.map +1 -0
  704. package/.next/server/chunks/_next-internal_server_app_api_forms_templates_[id]_route_actions_1tjt-yf1ufx4t.js +3 -0
  705. package/.next/server/chunks/_next-internal_server_app_api_forms_templates_[id]_route_actions_1tjt-yf1ufx4t.js.map +1 -0
  706. package/.next/server/chunks/_next-internal_server_app_api_forms_templates_route_actions_0jx0yyx-a9e8a.js +3 -0
  707. package/.next/server/chunks/_next-internal_server_app_api_forms_templates_route_actions_0jx0yyx-a9e8a.js.map +1 -0
  708. package/.next/server/chunks/_next-internal_server_app_api_groups_[id]_contacts_route_actions_16zvoezq09gzs.js +3 -0
  709. package/.next/server/chunks/_next-internal_server_app_api_groups_[id]_contacts_route_actions_16zvoezq09gzs.js.map +1 -0
  710. package/.next/server/chunks/_next-internal_server_app_api_groups_[id]_route_actions_1a972-ku-88li.js +3 -0
  711. package/.next/server/chunks/_next-internal_server_app_api_groups_[id]_route_actions_1a972-ku-88li.js.map +1 -0
  712. package/.next/server/chunks/_next-internal_server_app_api_groups_route_actions_1g3bvao_xtom7.js +3 -0
  713. package/.next/server/chunks/_next-internal_server_app_api_groups_route_actions_1g3bvao_xtom7.js.map +1 -0
  714. package/.next/server/chunks/_next-internal_server_app_api_media_[name]_route_actions_1x1oymi5s9e43.js +3 -0
  715. package/.next/server/chunks/_next-internal_server_app_api_media_[name]_route_actions_1x1oymi5s9e43.js.map +1 -0
  716. package/.next/server/chunks/_next-internal_server_app_api_media_route_actions_08_28_1c7w9t_.js +3 -0
  717. package/.next/server/chunks/_next-internal_server_app_api_media_route_actions_08_28_1c7w9t_.js.map +1 -0
  718. package/.next/server/chunks/_next-internal_server_app_api_public_forms_[id]_route_actions_0qjba17y_8y2z.js +3 -0
  719. package/.next/server/chunks/_next-internal_server_app_api_public_forms_[id]_route_actions_0qjba17y_8y2z.js.map +1 -0
  720. package/.next/server/chunks/_next-internal_server_app_api_public_posts_[slug]_route_actions_0s-2m-qbt3a4g.js +3 -0
  721. package/.next/server/chunks/_next-internal_server_app_api_public_posts_[slug]_route_actions_0s-2m-qbt3a4g.js.map +1 -0
  722. package/.next/server/chunks/_next-internal_server_app_api_public_posts_route_actions_1coxdlltzg2ec.js +3 -0
  723. package/.next/server/chunks/_next-internal_server_app_api_public_posts_route_actions_1coxdlltzg2ec.js.map +1 -0
  724. package/.next/server/chunks/_next-internal_server_app_api_public_unsubscribe_route_actions_04pb699mm7zhs.js +3 -0
  725. package/.next/server/chunks/_next-internal_server_app_api_public_unsubscribe_route_actions_04pb699mm7zhs.js.map +1 -0
  726. package/.next/server/chunks/_next-internal_server_app_api_route_actions_1spy6egqqw5nf.js +3 -0
  727. package/.next/server/chunks/_next-internal_server_app_api_route_actions_1spy6egqqw5nf.js.map +1 -0
  728. package/.next/server/chunks/_next-internal_server_app_api_senders_[id]_route_actions_1acuhlzaull6v.js +3 -0
  729. package/.next/server/chunks/_next-internal_server_app_api_senders_[id]_route_actions_1acuhlzaull6v.js.map +1 -0
  730. package/.next/server/chunks/_next-internal_server_app_api_senders_route_actions_0hbw-3u122an8.js +3 -0
  731. package/.next/server/chunks/_next-internal_server_app_api_senders_route_actions_0hbw-3u122an8.js.map +1 -0
  732. package/.next/server/chunks/_next-internal_server_app_api_settings_telegram_route_actions_1ecznfq0kf4oi.js +3 -0
  733. package/.next/server/chunks/_next-internal_server_app_api_settings_telegram_route_actions_1ecznfq0kf4oi.js.map +1 -0
  734. package/.next/server/chunks/_next-internal_server_app_api_stats_route_actions_0o9u2yifvs5i8.js +3 -0
  735. package/.next/server/chunks/_next-internal_server_app_api_stats_route_actions_0o9u2yifvs5i8.js.map +1 -0
  736. package/.next/server/chunks/_next-internal_server_app_api_t_[token]_route_actions_1h2u1jcimhu0m.js +3 -0
  737. package/.next/server/chunks/_next-internal_server_app_api_t_[token]_route_actions_1h2u1jcimhu0m.js.map +1 -0
  738. package/.next/server/chunks/_next-internal_server_app_api_templates_[id]_route_actions_0w75q6vjtgysm.js +3 -0
  739. package/.next/server/chunks/_next-internal_server_app_api_templates_[id]_route_actions_0w75q6vjtgysm.js.map +1 -0
  740. package/.next/server/chunks/_next-internal_server_app_api_templates_route_actions_1c0yqgfnurom3.js +3 -0
  741. package/.next/server/chunks/_next-internal_server_app_api_templates_route_actions_1c0yqgfnurom3.js.map +1 -0
  742. package/.next/server/chunks/_next-internal_server_app_api_workflows_[id]_enroll_route_actions_1t3actfkyjz50.js +3 -0
  743. package/.next/server/chunks/_next-internal_server_app_api_workflows_[id]_enroll_route_actions_1t3actfkyjz50.js.map +1 -0
  744. package/.next/server/chunks/_next-internal_server_app_api_workflows_[id]_route_actions_0hdifc39l0kzl.js +3 -0
  745. package/.next/server/chunks/_next-internal_server_app_api_workflows_[id]_route_actions_0hdifc39l0kzl.js.map +1 -0
  746. package/.next/server/chunks/_next-internal_server_app_api_workflows_[id]_run_route_actions_0a0iqptu82a4a.js +3 -0
  747. package/.next/server/chunks/_next-internal_server_app_api_workflows_[id]_run_route_actions_0a0iqptu82a4a.js.map +1 -0
  748. package/.next/server/chunks/_next-internal_server_app_api_workflows_route_actions_1-qmgyxvh5cwy.js +3 -0
  749. package/.next/server/chunks/_next-internal_server_app_api_workflows_route_actions_1-qmgyxvh5cwy.js.map +1 -0
  750. package/.next/server/chunks/src_0x0k1ybx0poim._.js +3 -0
  751. package/.next/server/chunks/src_0x0k1ybx0poim._.js.map +1 -0
  752. package/.next/server/chunks/src_app_api_forms_[id]_submit_route_ts_1nivtdhvc93f6._.js +23 -0
  753. package/.next/server/chunks/src_app_api_forms_[id]_submit_route_ts_1nivtdhvc93f6._.js.map +1 -0
  754. package/.next/server/chunks/src_lib_automation_ts_0gl7ssziqm14z._.js +149 -0
  755. package/.next/server/chunks/src_lib_automation_ts_0gl7ssziqm14z._.js.map +1 -0
  756. package/.next/server/chunks/src_lib_automation_ts_1a34dych48thk._.js +3 -0
  757. package/.next/server/chunks/src_lib_automation_ts_1a34dych48thk._.js.map +1 -0
  758. package/.next/server/chunks/src_lib_automation_ts_207uuptnebs4l._.js +3 -0
  759. package/.next/server/chunks/src_lib_automation_ts_207uuptnebs4l._.js.map +1 -0
  760. package/.next/server/chunks/src_lib_db_ts_12rrbm4_je1ts._.js +3 -0
  761. package/.next/server/chunks/src_lib_db_ts_12rrbm4_je1ts._.js.map +1 -0
  762. package/.next/server/chunks/src_lib_email-template_ts_10pfim6kqnxua._.js +126 -0
  763. package/.next/server/chunks/src_lib_email-template_ts_10pfim6kqnxua._.js.map +1 -0
  764. package/.next/server/chunks/src_lib_form-builder_ts_1cp0xz7mqn56d._.js +3 -0
  765. package/.next/server/chunks/src_lib_form-builder_ts_1cp0xz7mqn56d._.js.map +1 -0
  766. package/.next/server/chunks/src_lib_gmail_ts_1s2ltf6xpps8u._.js +3 -0
  767. package/.next/server/chunks/src_lib_gmail_ts_1s2ltf6xpps8u._.js.map +1 -0
  768. package/.next/server/chunks/src_lib_supabase-storage_ts_1dfw8x9k0tgmv._.js +26 -0
  769. package/.next/server/chunks/src_lib_supabase-storage_ts_1dfw8x9k0tgmv._.js.map +1 -0
  770. package/.next/server/chunks/src_lib_telegram_ts_0ysg2aj42jeux._.js +3 -0
  771. package/.next/server/chunks/src_lib_telegram_ts_0ysg2aj42jeux._.js.map +1 -0
  772. package/.next/server/chunks/ssr/02c-_@radix-ui_react-dialog_dist_index_mjs_00ymwmtf3k3mw._.js +3 -0
  773. package/.next/server/chunks/ssr/02c-_@radix-ui_react-dialog_dist_index_mjs_00ymwmtf3k3mw._.js.map +1 -0
  774. package/.next/server/chunks/ssr/06xu_next_0r9zyafjirm2h._.js +32 -0
  775. package/.next/server/chunks/ssr/06xu_next_0r9zyafjirm2h._.js.map +1 -0
  776. package/.next/server/chunks/ssr/06xu_next_dist_0-pwksyiyjqj6._.js +6 -0
  777. package/.next/server/chunks/ssr/06xu_next_dist_0-pwksyiyjqj6._.js.map +1 -0
  778. package/.next/server/chunks/ssr/06xu_next_dist_0_wf08lquq9u4._.js +3 -0
  779. package/.next/server/chunks/ssr/06xu_next_dist_0_wf08lquq9u4._.js.map +1 -0
  780. package/.next/server/chunks/ssr/06xu_next_dist_0lnz__th3f5zr._.js +3 -0
  781. package/.next/server/chunks/ssr/06xu_next_dist_0lnz__th3f5zr._.js.map +1 -0
  782. package/.next/server/chunks/ssr/06xu_next_dist_0q5i7q4kqow99._.js +23 -0
  783. package/.next/server/chunks/ssr/06xu_next_dist_0q5i7q4kqow99._.js.map +1 -0
  784. package/.next/server/chunks/ssr/06xu_next_dist_0yftpqcu15_jh._.js +32 -0
  785. package/.next/server/chunks/ssr/06xu_next_dist_0yftpqcu15_jh._.js.map +1 -0
  786. package/.next/server/chunks/ssr/06xu_next_dist_1ysb4fqlnpjfg._.js +32 -0
  787. package/.next/server/chunks/ssr/06xu_next_dist_1ysb4fqlnpjfg._.js.map +1 -0
  788. package/.next/server/chunks/ssr/06xu_next_dist_client_components_0qj_uk660e2yb._.js +3 -0
  789. package/.next/server/chunks/ssr/06xu_next_dist_client_components_0qj_uk660e2yb._.js.map +1 -0
  790. package/.next/server/chunks/ssr/06xu_next_dist_client_components_15i6o-11_85p_._.js +33 -0
  791. package/.next/server/chunks/ssr/06xu_next_dist_client_components_15i6o-11_85p_._.js.map +1 -0
  792. package/.next/server/chunks/ssr/06xu_next_dist_client_components_builtin_forbidden_1vceoosdyq6ip.js +3 -0
  793. package/.next/server/chunks/ssr/06xu_next_dist_client_components_builtin_forbidden_1vceoosdyq6ip.js.map +1 -0
  794. package/.next/server/chunks/ssr/06xu_next_dist_client_components_builtin_global-error_1p7ftpe87ygv1.js +3 -0
  795. package/.next/server/chunks/ssr/06xu_next_dist_client_components_builtin_global-error_1p7ftpe87ygv1.js.map +1 -0
  796. package/.next/server/chunks/ssr/06xu_next_dist_client_components_builtin_unauthorized_002xbraemrk92.js +3 -0
  797. package/.next/server/chunks/ssr/06xu_next_dist_client_components_builtin_unauthorized_002xbraemrk92.js.map +1 -0
  798. package/.next/server/chunks/ssr/06xu_next_dist_compiled_@edge-runtime_cookies_index_0ieglv5lnsyri.js +3 -0
  799. package/.next/server/chunks/ssr/06xu_next_dist_compiled_@edge-runtime_cookies_index_0ieglv5lnsyri.js.map +1 -0
  800. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0-vqyq0vovi_i.js +3 -0
  801. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0-vqyq0vovi_i.js.map +1 -0
  802. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_02v5nrvtk32c6.js +3 -0
  803. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_02v5nrvtk32c6.js.map +1 -0
  804. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_03qrcs7au7ivq.js +3 -0
  805. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_03qrcs7au7ivq.js.map +1 -0
  806. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_045x_qclmi4m8.js +3 -0
  807. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_045x_qclmi4m8.js.map +1 -0
  808. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0_t0dbl5dozbx.js +3 -0
  809. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0_t0dbl5dozbx.js.map +1 -0
  810. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0c_t0os-4cbs3.js +3 -0
  811. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0c_t0os-4cbs3.js.map +1 -0
  812. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0h0emnvw_w9hz.js +3 -0
  813. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0h0emnvw_w9hz.js.map +1 -0
  814. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0hf32whzcuz52.js +3 -0
  815. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0hf32whzcuz52.js.map +1 -0
  816. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0jnsbu-6ck6mc.js +3 -0
  817. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0jnsbu-6ck6mc.js.map +1 -0
  818. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0o-vhcup-3b3z.js +3 -0
  819. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_0o-vhcup-3b3z.js.map +1 -0
  820. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_11l8elffx5v39.js +3 -0
  821. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_11l8elffx5v39.js.map +1 -0
  822. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_13788nvenj_0p.js +3 -0
  823. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_13788nvenj_0p.js.map +1 -0
  824. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_16f4zm9x692nw.js +3 -0
  825. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_16f4zm9x692nw.js.map +1 -0
  826. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1bootgt-epvt6.js +3 -0
  827. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1bootgt-epvt6.js.map +1 -0
  828. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1l1dlajssgq1c.js +3 -0
  829. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1l1dlajssgq1c.js.map +1 -0
  830. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1rlfqzolbd21n.js +3 -0
  831. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1rlfqzolbd21n.js.map +1 -0
  832. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1vxqj6-npabju.js +3 -0
  833. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_1vxqj6-npabju.js.map +1 -0
  834. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_20n28cdchbrpp.js +3 -0
  835. package/.next/server/chunks/ssr/06xu_next_dist_esm_build_templates_app-page_20n28cdchbrpp.js.map +1 -0
  836. package/.next/server/chunks/ssr/1l0a_@radix-ui_react-collection_dist_index_mjs_0rxx5d5lmo6u4._.js +3 -0
  837. package/.next/server/chunks/ssr/1l0a_@radix-ui_react-collection_dist_index_mjs_0rxx5d5lmo6u4._.js.map +1 -0
  838. package/.next/server/chunks/ssr/1saf_lucide-react_dist_esm_icons_flask-conical_1vs3jvn162eqg.js +3 -0
  839. package/.next/server/chunks/ssr/1saf_lucide-react_dist_esm_icons_flask-conical_1vs3jvn162eqg.js.map +1 -0
  840. package/.next/server/chunks/ssr/1saf_lucide-react_dist_esm_icons_globe_0jwul3h6rwm1l.js +3 -0
  841. package/.next/server/chunks/ssr/1saf_lucide-react_dist_esm_icons_globe_0jwul3h6rwm1l.js.map +1 -0
  842. package/.next/server/chunks/ssr/1saf_lucide-react_dist_esm_icons_menu_1jtgq-_6gw2ad.js +3 -0
  843. package/.next/server/chunks/ssr/1saf_lucide-react_dist_esm_icons_menu_1jtgq-_6gw2ad.js.map +1 -0
  844. package/.next/server/chunks/ssr/21ai_sonner_dist_index_mjs_0lemus0y9eb08._.js +3 -0
  845. package/.next/server/chunks/ssr/21ai_sonner_dist_index_mjs_0lemus0y9eb08._.js.map +1 -0
  846. package/.next/server/chunks/ssr/[root-of-the-server]__01mn3kop4h9ln._.js +3 -0
  847. package/.next/server/chunks/ssr/[root-of-the-server]__01mn3kop4h9ln._.js.map +1 -0
  848. package/.next/server/chunks/ssr/[root-of-the-server]__02jgmnf51m_bw._.js +3 -0
  849. package/.next/server/chunks/ssr/[root-of-the-server]__02jgmnf51m_bw._.js.map +1 -0
  850. package/.next/server/chunks/ssr/[root-of-the-server]__04f9g0ord6h_z._.js +3 -0
  851. package/.next/server/chunks/ssr/[root-of-the-server]__04f9g0ord6h_z._.js.map +1 -0
  852. package/.next/server/chunks/ssr/[root-of-the-server]__06666h874g5hp._.js +3 -0
  853. package/.next/server/chunks/ssr/[root-of-the-server]__06666h874g5hp._.js.map +1 -0
  854. package/.next/server/chunks/ssr/[root-of-the-server]__07me011e7ku2k._.js +3 -0
  855. package/.next/server/chunks/ssr/[root-of-the-server]__07me011e7ku2k._.js.map +1 -0
  856. package/.next/server/chunks/ssr/[root-of-the-server]__07pj5lrkqzifr._.js +3 -0
  857. package/.next/server/chunks/ssr/[root-of-the-server]__07pj5lrkqzifr._.js.map +1 -0
  858. package/.next/server/chunks/ssr/[root-of-the-server]__0dri3jnl96cro._.js +3 -0
  859. package/.next/server/chunks/ssr/[root-of-the-server]__0dri3jnl96cro._.js.map +1 -0
  860. package/.next/server/chunks/ssr/[root-of-the-server]__0e6ie8f1lflit._.js +3 -0
  861. package/.next/server/chunks/ssr/[root-of-the-server]__0e6ie8f1lflit._.js.map +1 -0
  862. package/.next/server/chunks/ssr/[root-of-the-server]__0ebwcvxo9acvx._.js +3 -0
  863. package/.next/server/chunks/ssr/[root-of-the-server]__0ebwcvxo9acvx._.js.map +1 -0
  864. package/.next/server/chunks/ssr/[root-of-the-server]__0idhg2fbiknzj._.js +3 -0
  865. package/.next/server/chunks/ssr/[root-of-the-server]__0idhg2fbiknzj._.js.map +1 -0
  866. package/.next/server/chunks/ssr/[root-of-the-server]__0k-w18w428_5_._.js +3 -0
  867. package/.next/server/chunks/ssr/[root-of-the-server]__0k-w18w428_5_._.js.map +1 -0
  868. package/.next/server/chunks/ssr/[root-of-the-server]__0qcpq09hg4us0._.js +3 -0
  869. package/.next/server/chunks/ssr/[root-of-the-server]__0qcpq09hg4us0._.js.map +1 -0
  870. package/.next/server/chunks/ssr/[root-of-the-server]__0ue6kxnxcsdwm._.js +3 -0
  871. package/.next/server/chunks/ssr/[root-of-the-server]__0ue6kxnxcsdwm._.js.map +1 -0
  872. package/.next/server/chunks/ssr/[root-of-the-server]__0ws8ymfetd__e._.js +3 -0
  873. package/.next/server/chunks/ssr/[root-of-the-server]__0ws8ymfetd__e._.js.map +1 -0
  874. package/.next/server/chunks/ssr/[root-of-the-server]__0x434x8kjfomg._.js +3 -0
  875. package/.next/server/chunks/ssr/[root-of-the-server]__0x434x8kjfomg._.js.map +1 -0
  876. package/.next/server/chunks/ssr/[root-of-the-server]__12ucz-z8gi2wm._.js +3 -0
  877. package/.next/server/chunks/ssr/[root-of-the-server]__12ucz-z8gi2wm._.js.map +1 -0
  878. package/.next/server/chunks/ssr/[root-of-the-server]__12v4b4ag6pnuz._.js +3 -0
  879. package/.next/server/chunks/ssr/[root-of-the-server]__12v4b4ag6pnuz._.js.map +1 -0
  880. package/.next/server/chunks/ssr/[root-of-the-server]__14-2op73282-w._.js +14 -0
  881. package/.next/server/chunks/ssr/[root-of-the-server]__14-2op73282-w._.js.map +1 -0
  882. package/.next/server/chunks/ssr/[root-of-the-server]__17gzuebq4v3qk._.js +3 -0
  883. package/.next/server/chunks/ssr/[root-of-the-server]__17gzuebq4v3qk._.js.map +1 -0
  884. package/.next/server/chunks/ssr/[root-of-the-server]__1csnvoh619028._.js +3 -0
  885. package/.next/server/chunks/ssr/[root-of-the-server]__1csnvoh619028._.js.map +1 -0
  886. package/.next/server/chunks/ssr/[root-of-the-server]__1m7dl-6i9qiqn._.js +3 -0
  887. package/.next/server/chunks/ssr/[root-of-the-server]__1m7dl-6i9qiqn._.js.map +1 -0
  888. package/.next/server/chunks/ssr/[root-of-the-server]__1rn9z04uwbxhb._.js +3 -0
  889. package/.next/server/chunks/ssr/[root-of-the-server]__1rn9z04uwbxhb._.js.map +1 -0
  890. package/.next/server/chunks/ssr/[root-of-the-server]__1wlwflqfou0bh._.js +3 -0
  891. package/.next/server/chunks/ssr/[root-of-the-server]__1wlwflqfou0bh._.js.map +1 -0
  892. package/.next/server/chunks/ssr/[root-of-the-server]__20ne3r6pcgicp._.js +3 -0
  893. package/.next/server/chunks/ssr/[root-of-the-server]__20ne3r6pcgicp._.js.map +1 -0
  894. package/.next/server/chunks/ssr/[turbopack]_runtime.js +935 -0
  895. package/.next/server/chunks/ssr/[turbopack]_runtime.js.map +10 -0
  896. package/.next/server/chunks/ssr/_0-pg9xcfzsxes._.js +3 -0
  897. package/.next/server/chunks/ssr/_0-pg9xcfzsxes._.js.map +1 -0
  898. package/.next/server/chunks/ssr/_00xm33jaybves._.js +3 -0
  899. package/.next/server/chunks/ssr/_00xm33jaybves._.js.map +1 -0
  900. package/.next/server/chunks/ssr/_026bi60jl1puk._.js +3 -0
  901. package/.next/server/chunks/ssr/_026bi60jl1puk._.js.map +1 -0
  902. package/.next/server/chunks/ssr/_055fzzctizrl9._.js +3 -0
  903. package/.next/server/chunks/ssr/_055fzzctizrl9._.js.map +1 -0
  904. package/.next/server/chunks/ssr/_05yfy_2w07awo._.js +3 -0
  905. package/.next/server/chunks/ssr/_05yfy_2w07awo._.js.map +1 -0
  906. package/.next/server/chunks/ssr/_07h0nhyqn2dzr._.js +3 -0
  907. package/.next/server/chunks/ssr/_07h0nhyqn2dzr._.js.map +1 -0
  908. package/.next/server/chunks/ssr/_07h_4c6z4aup2._.js +3 -0
  909. package/.next/server/chunks/ssr/_07h_4c6z4aup2._.js.map +1 -0
  910. package/.next/server/chunks/ssr/_07ns5-wirt2rm._.js +3 -0
  911. package/.next/server/chunks/ssr/_07ns5-wirt2rm._.js.map +1 -0
  912. package/.next/server/chunks/ssr/_07qibgb3c5l89._.js +3 -0
  913. package/.next/server/chunks/ssr/_07qibgb3c5l89._.js.map +1 -0
  914. package/.next/server/chunks/ssr/_0axhkh5eel9yw._.js +3 -0
  915. package/.next/server/chunks/ssr/_0axhkh5eel9yw._.js.map +1 -0
  916. package/.next/server/chunks/ssr/_0cw6p0eedzd28._.js +3 -0
  917. package/.next/server/chunks/ssr/_0cw6p0eedzd28._.js.map +1 -0
  918. package/.next/server/chunks/ssr/_0f8-6t0_oqza5._.js +9 -0
  919. package/.next/server/chunks/ssr/_0f8-6t0_oqza5._.js.map +1 -0
  920. package/.next/server/chunks/ssr/_0ijop4gxx3i74._.js +25 -0
  921. package/.next/server/chunks/ssr/_0ijop4gxx3i74._.js.map +1 -0
  922. package/.next/server/chunks/ssr/_0j7t-g9s-xw2k._.js +3 -0
  923. package/.next/server/chunks/ssr/_0j7t-g9s-xw2k._.js.map +1 -0
  924. package/.next/server/chunks/ssr/_0omyccx6813z2._.js +3 -0
  925. package/.next/server/chunks/ssr/_0omyccx6813z2._.js.map +1 -0
  926. package/.next/server/chunks/ssr/_0rs3zupho3jtn._.js +3 -0
  927. package/.next/server/chunks/ssr/_0rs3zupho3jtn._.js.map +1 -0
  928. package/.next/server/chunks/ssr/_0tpg1kyh-jvo_._.js +3 -0
  929. package/.next/server/chunks/ssr/_0tpg1kyh-jvo_._.js.map +1 -0
  930. package/.next/server/chunks/ssr/_0umx11tm2hknm._.js +3 -0
  931. package/.next/server/chunks/ssr/_0umx11tm2hknm._.js.map +1 -0
  932. package/.next/server/chunks/ssr/_100pig1hqblaj._.js +3 -0
  933. package/.next/server/chunks/ssr/_100pig1hqblaj._.js.map +1 -0
  934. package/.next/server/chunks/ssr/_10fls_hq4fpul._.js +3 -0
  935. package/.next/server/chunks/ssr/_10fls_hq4fpul._.js.map +1 -0
  936. package/.next/server/chunks/ssr/_135h5be3e-da_._.js +3 -0
  937. package/.next/server/chunks/ssr/_135h5be3e-da_._.js.map +1 -0
  938. package/.next/server/chunks/ssr/_15_m3et_qvi8o._.js +136 -0
  939. package/.next/server/chunks/ssr/_15_m3et_qvi8o._.js.map +1 -0
  940. package/.next/server/chunks/ssr/_17qjjfpo8bdyr._.js +3 -0
  941. package/.next/server/chunks/ssr/_17qjjfpo8bdyr._.js.map +1 -0
  942. package/.next/server/chunks/ssr/_1_zhi9sw7y-9k._.js +3 -0
  943. package/.next/server/chunks/ssr/_1_zhi9sw7y-9k._.js.map +1 -0
  944. package/.next/server/chunks/ssr/_1j3n0s5oa8ydl._.js +3 -0
  945. package/.next/server/chunks/ssr/_1j3n0s5oa8ydl._.js.map +1 -0
  946. package/.next/server/chunks/ssr/_1l_ctr5xszb5f._.js +3 -0
  947. package/.next/server/chunks/ssr/_1l_ctr5xszb5f._.js.map +1 -0
  948. package/.next/server/chunks/ssr/_1le90grlliyg5._.js +3 -0
  949. package/.next/server/chunks/ssr/_1le90grlliyg5._.js.map +1 -0
  950. package/.next/server/chunks/ssr/_1n1x5lti-0y_f._.js +3 -0
  951. package/.next/server/chunks/ssr/_1n1x5lti-0y_f._.js.map +1 -0
  952. package/.next/server/chunks/ssr/_1oaxfn6inhrly._.js +3 -0
  953. package/.next/server/chunks/ssr/_1oaxfn6inhrly._.js.map +1 -0
  954. package/.next/server/chunks/ssr/_1tk04py_mc595._.js +3 -0
  955. package/.next/server/chunks/ssr/_1tk04py_mc595._.js.map +1 -0
  956. package/.next/server/chunks/ssr/_1x4-igv-plryx._.js +3 -0
  957. package/.next/server/chunks/ssr/_1x4-igv-plryx._.js.map +1 -0
  958. package/.next/server/chunks/ssr/_1ydm1bpbu80ve._.js +3 -0
  959. package/.next/server/chunks/ssr/_1ydm1bpbu80ve._.js.map +1 -0
  960. package/.next/server/chunks/ssr/_1zpk-aphfnyrn._.js +3 -0
  961. package/.next/server/chunks/ssr/_1zpk-aphfnyrn._.js.map +1 -0
  962. package/.next/server/chunks/ssr/_208buljkex-zn._.js +3 -0
  963. package/.next/server/chunks/ssr/_208buljkex-zn._.js.map +1 -0
  964. package/.next/server/chunks/ssr/_21awjpye_8ftw._.js +3 -0
  965. package/.next/server/chunks/ssr/_21awjpye_8ftw._.js.map +1 -0
  966. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0zi5s8-psc_d2.js +3 -0
  967. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0zi5s8-psc_d2.js.map +1 -0
  968. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0pt47yrisjoev.js +3 -0
  969. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0pt47yrisjoev.js.map +1 -0
  970. package/.next/server/chunks/ssr/_next-internal_server_app_blog_[slug]_page_actions_1xd8lf61mupwf.js +3 -0
  971. package/.next/server/chunks/ssr/_next-internal_server_app_blog_[slug]_page_actions_1xd8lf61mupwf.js.map +1 -0
  972. package/.next/server/chunks/ssr/_next-internal_server_app_blog_page_actions_1nf9zawbhjeiv.js +3 -0
  973. package/.next/server/chunks/ssr/_next-internal_server_app_blog_page_actions_1nf9zawbhjeiv.js.map +1 -0
  974. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_automations_page_actions_0goq3aojk1w34.js +3 -0
  975. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_automations_page_actions_0goq3aojk1w34.js.map +1 -0
  976. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_campaigns_[id]_page_actions_0yprr1p1obhkv.js +3 -0
  977. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_campaigns_[id]_page_actions_0yprr1p1obhkv.js.map +1 -0
  978. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_campaigns_page_actions_0wxku62xg7-8d.js +3 -0
  979. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_campaigns_page_actions_0wxku62xg7-8d.js.map +1 -0
  980. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_contacts_page_actions_03nfyumhdne4o.js +3 -0
  981. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_contacts_page_actions_03nfyumhdne4o.js.map +1 -0
  982. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_forms_page_actions_0y0vhf1s8gskw.js +3 -0
  983. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_forms_page_actions_0y0vhf1s8gskw.js.map +1 -0
  984. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_media_page_actions_15b2td6gfl39a.js +3 -0
  985. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_media_page_actions_15b2td6gfl39a.js.map +1 -0
  986. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_page_actions_10dr1c56aj99-.js +3 -0
  987. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_page_actions_10dr1c56aj99-.js.map +1 -0
  988. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_senders_page_actions_1wuvc1b945nkt.js +3 -0
  989. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_senders_page_actions_1wuvc1b945nkt.js.map +1 -0
  990. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_settings_page_actions_0zse4882vcfr3.js +3 -0
  991. package/.next/server/chunks/ssr/_next-internal_server_app_dashboard_settings_page_actions_0zse4882vcfr3.js.map +1 -0
  992. package/.next/server/chunks/ssr/_next-internal_server_app_doc_page_actions_0rt535c9bfkq2.js +3 -0
  993. package/.next/server/chunks/ssr/_next-internal_server_app_doc_page_actions_0rt535c9bfkq2.js.map +1 -0
  994. package/.next/server/chunks/ssr/_next-internal_server_app_documentation_page_actions_1iy5tav034rd5.js +3 -0
  995. package/.next/server/chunks/ssr/_next-internal_server_app_documentation_page_actions_1iy5tav034rd5.js.map +1 -0
  996. package/.next/server/chunks/ssr/_next-internal_server_app_login_page_actions_04fnjo0ny9dmg.js +3 -0
  997. package/.next/server/chunks/ssr/_next-internal_server_app_login_page_actions_04fnjo0ny9dmg.js.map +1 -0
  998. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_0hhsz1jew5ls7.js +3 -0
  999. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_0hhsz1jew5ls7.js.map +1 -0
  1000. package/.next/server/chunks/ssr/_next-internal_server_app_unsubscribe_page_actions_0tw5uaxujcbgr.js +3 -0
  1001. package/.next/server/chunks/ssr/_next-internal_server_app_unsubscribe_page_actions_0tw5uaxujcbgr.js.map +1 -0
  1002. package/.next/server/chunks/ssr/node_modules__pnpm_09-vsdyv4rf07._.js +33 -0
  1003. package/.next/server/chunks/ssr/node_modules__pnpm_09-vsdyv4rf07._.js.map +1 -0
  1004. package/.next/server/chunks/ssr/node_modules__pnpm_0g_pkwhpxnn41._.js +3 -0
  1005. package/.next/server/chunks/ssr/node_modules__pnpm_0g_pkwhpxnn41._.js.map +1 -0
  1006. package/.next/server/chunks/ssr/node_modules__pnpm_0ish0pdmujvdk._.js +3 -0
  1007. package/.next/server/chunks/ssr/node_modules__pnpm_0ish0pdmujvdk._.js.map +1 -0
  1008. package/.next/server/chunks/ssr/node_modules__pnpm_0ki86aixwegwo._.js +3 -0
  1009. package/.next/server/chunks/ssr/node_modules__pnpm_0ki86aixwegwo._.js.map +1 -0
  1010. package/.next/server/chunks/ssr/node_modules__pnpm_19v8qxrrt436n._.js +3 -0
  1011. package/.next/server/chunks/ssr/node_modules__pnpm_19v8qxrrt436n._.js.map +1 -0
  1012. package/.next/server/chunks/ssr/node_modules__pnpm_1g-xnwqgszuwu._.js +3 -0
  1013. package/.next/server/chunks/ssr/node_modules__pnpm_1g-xnwqgszuwu._.js.map +1 -0
  1014. package/.next/server/chunks/ssr/src_app_blog_[slug]_page_tsx_1ug1kslm_svqp._.js +77 -0
  1015. package/.next/server/chunks/ssr/src_app_blog_[slug]_page_tsx_1ug1kslm_svqp._.js.map +1 -0
  1016. package/.next/server/chunks/ssr/src_app_dashboard_senders_page_tsx_1b3t4vyr5fnbx._.js +3 -0
  1017. package/.next/server/chunks/ssr/src_app_dashboard_senders_page_tsx_1b3t4vyr5fnbx._.js.map +1 -0
  1018. package/.next/server/chunks/ssr/src_app_unsubscribe_page_tsx_0o16gze50x9sf._.js +3 -0
  1019. package/.next/server/chunks/ssr/src_app_unsubscribe_page_tsx_0o16gze50x9sf._.js.map +1 -0
  1020. package/.next/server/chunks/ssr/src_components_12ptlsadu9zd7._.js +3 -0
  1021. package/.next/server/chunks/ssr/src_components_12ptlsadu9zd7._.js.map +1 -0
  1022. package/.next/server/chunks/ssr/src_components_app_0pk35_glzt8wq._.js +3 -0
  1023. package/.next/server/chunks/ssr/src_components_app_0pk35_glzt8wq._.js.map +1 -0
  1024. package/.next/server/chunks/ssr/src_components_app_auth_login-form_tsx_1r6tbf3s9mxu7._.js +3 -0
  1025. package/.next/server/chunks/ssr/src_components_app_auth_login-form_tsx_1r6tbf3s9mxu7._.js.map +1 -0
  1026. package/.next/server/chunks/ssr/src_components_app_campaigns_campaign-list_tsx_1-1uum6gsaisy._.js +3 -0
  1027. package/.next/server/chunks/ssr/src_components_app_campaigns_campaign-list_tsx_1-1uum6gsaisy._.js.map +1 -0
  1028. package/.next/server/chunks/ssr/src_components_app_contacts_contact-list_tsx_1f91x0dykt7wo._.js +3 -0
  1029. package/.next/server/chunks/ssr/src_components_app_contacts_contact-list_tsx_1f91x0dykt7wo._.js.map +1 -0
  1030. package/.next/server/chunks/ssr/src_components_app_forms_forms-section_tsx_15gbq9k8__4dn._.js +3 -0
  1031. package/.next/server/chunks/ssr/src_components_app_forms_forms-section_tsx_15gbq9k8__4dn._.js.map +1 -0
  1032. package/.next/server/chunks/ssr/src_components_app_media_media-manager_tsx_08p0-g5iq1xdy._.js +3 -0
  1033. package/.next/server/chunks/ssr/src_components_app_media_media-manager_tsx_08p0-g5iq1xdy._.js.map +1 -0
  1034. package/.next/server/chunks/ssr/src_components_app_overview_tsx_0106-5tj3j3_u._.js +3 -0
  1035. package/.next/server/chunks/ssr/src_components_app_overview_tsx_0106-5tj3j3_u._.js.map +1 -0
  1036. package/.next/server/chunks/ssr/src_components_app_settings_tsx_151892lqtlh2m._.js +3 -0
  1037. package/.next/server/chunks/ssr/src_components_app_settings_tsx_151892lqtlh2m._.js.map +1 -0
  1038. package/.next/server/chunks/ssr/src_components_landing_footer_tsx_17g4as_911h_z._.js +3 -0
  1039. package/.next/server/chunks/ssr/src_components_landing_footer_tsx_17g4as_911h_z._.js.map +1 -0
  1040. package/.next/server/chunks/ssr/src_components_landing_landing-page_tsx_0jt_enjh4367d._.js +3 -0
  1041. package/.next/server/chunks/ssr/src_components_landing_landing-page_tsx_0jt_enjh4367d._.js.map +1 -0
  1042. package/.next/server/chunks/ssr/src_components_landing_navbar_tsx_0ixz81r-fflfv._.js +3 -0
  1043. package/.next/server/chunks/ssr/src_components_landing_navbar_tsx_0ixz81r-fflfv._.js.map +1 -0
  1044. package/.next/server/chunks/ssr/src_components_ui_14xpyv0xpr1d4._.js +3 -0
  1045. package/.next/server/chunks/ssr/src_components_ui_14xpyv0xpr1d4._.js.map +1 -0
  1046. package/.next/server/chunks/ssr/src_components_ui_alert-dialog_tsx_0pzef58n2zd63._.js +3 -0
  1047. package/.next/server/chunks/ssr/src_components_ui_alert-dialog_tsx_0pzef58n2zd63._.js.map +1 -0
  1048. package/.next/server/chunks/ssr/src_components_ui_dialog_tsx_1tn-i_6d3rhzt._.js +3 -0
  1049. package/.next/server/chunks/ssr/src_components_ui_dialog_tsx_1tn-i_6d3rhzt._.js.map +1 -0
  1050. package/.next/server/chunks/ssr/src_lib_db_ts_16pqnef5-fsqp._.js +3 -0
  1051. package/.next/server/chunks/ssr/src_lib_db_ts_16pqnef5-fsqp._.js.map +1 -0
  1052. package/.next/server/edge/chunks/06xu_next_dist_esm_build_templates_edge-wrapper_0_zgqn351fy42.js.map +1 -0
  1053. package/.next/server/edge/chunks/06xu_next_dist_esm_build_templates_edge-wrapper_13xzu7i5n4bm6.js.map +1 -0
  1054. package/.next/server/edge/chunks/06xu_next_dist_esm_build_templates_edge-wrapper_1bso2q3tp24ts.js +3 -0
  1055. package/.next/server/edge/chunks/06xu_next_dist_esm_build_templates_edge-wrapper_1bso2q3tp24ts.js.map +1 -0
  1056. package/.next/server/edge/chunks/1v4i_next_dist_esm_build_templates_edge-wrapper_0_zgqn351fy42.js +3 -0
  1057. package/.next/server/edge/chunks/1v4i_next_dist_esm_build_templates_edge-wrapper_13xzu7i5n4bm6.js +3 -0
  1058. package/.next/server/edge/chunks/[root-of-the-server]__1hmjpfrn42nte._.js +11 -0
  1059. package/.next/server/edge/chunks/[root-of-the-server]__1hmjpfrn42nte._.js.map +1 -0
  1060. package/.next/server/edge/chunks/_0h6n282dfcei-._.js +3 -0
  1061. package/.next/server/edge/chunks/_0h6n282dfcei-._.js.map +1 -0
  1062. package/.next/server/functions-config-manifest.json +11 -0
  1063. package/.next/server/instrumentation/middleware-manifest.json +12 -0
  1064. package/.next/server/instrumentation.js +4 -0
  1065. package/.next/server/instrumentation.js.map +5 -0
  1066. package/.next/server/instrumentation.js.nft.json +1 -0
  1067. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  1068. package/.next/server/middleware/middleware-manifest.json +36 -0
  1069. package/.next/server/middleware-build-manifest.js +223 -0
  1070. package/.next/server/middleware-manifest.json +40 -0
  1071. package/.next/server/next-font-manifest.js +1 -0
  1072. package/.next/server/next-font-manifest.json +6 -0
  1073. package/.next/server/pages/404.html +1 -0
  1074. package/.next/server/pages/500.html +1 -0
  1075. package/.next/server/pages-manifest.json +4 -0
  1076. package/.next/server/prefetch-hints.json +90 -0
  1077. package/.next/server/preview-props.json +5 -0
  1078. package/.next/server/server-reference-manifest.js +1 -0
  1079. package/.next/server/server-reference-manifest.json +5 -0
  1080. package/.next/static/chunks/05aoy23ycul7p.js +1 -0
  1081. package/.next/static/chunks/05sohy0cbb3y1.js +1 -0
  1082. package/.next/static/chunks/0cz1d0mv5g_q7.js +1 -0
  1083. package/.next/static/chunks/0i_sn52ynzipf.js +1 -0
  1084. package/.next/static/chunks/0p7bxql_g7q64.js +1 -0
  1085. package/.next/static/chunks/0slfvme32bzta.js +1 -0
  1086. package/.next/static/chunks/0uofq2n85u5yc.js +1 -0
  1087. package/.next/static/chunks/0w4j5ek-0m_l6.js +1 -0
  1088. package/.next/static/chunks/0y6_igpmb5q25.js +1 -0
  1089. package/.next/static/chunks/10g8gc1_4dmb6.js +7 -0
  1090. package/.next/static/chunks/10r5b4lw40ag0.js +1 -0
  1091. package/.next/static/chunks/14e2j0tc9nsmf.js +1 -0
  1092. package/.next/static/chunks/1561y2t336828.js +132 -0
  1093. package/.next/static/chunks/19th1mnoh3o6j.js +1 -0
  1094. package/.next/static/chunks/1_-m6h07aqh30.js +134 -0
  1095. package/.next/static/chunks/1_x2f-g925jb6.js +1 -0
  1096. package/.next/static/chunks/1bitvurkxx2nz.js +1 -0
  1097. package/.next/static/chunks/1ecuhonper9l0.js +1 -0
  1098. package/.next/static/chunks/1h2_45-gp-481.js +1 -0
  1099. package/.next/static/chunks/1j3ehn_xw8a55.js +1 -0
  1100. package/.next/static/chunks/1l65wr07pb00x.js +1 -0
  1101. package/.next/static/chunks/1vu83p4si8fws.js +1 -0
  1102. package/.next/static/chunks/21bye8lfwlt44.js +1 -0
  1103. package/.next/static/chunks/2e9dsi1shhtgh.js +22 -0
  1104. package/.next/static/chunks/2k_rdgx_r4jwv.js +1 -0
  1105. package/.next/static/chunks/2lagivmzn853-.js +276 -0
  1106. package/.next/static/chunks/2pwymhlh1h5hq.js +1 -0
  1107. package/.next/static/chunks/2qh8jmvqq3j7u.js +1 -0
  1108. package/.next/static/chunks/30ut98lh7sgz_.js +1 -0
  1109. package/.next/static/chunks/31iu25a06-uq5.js +31 -0
  1110. package/.next/static/chunks/357eter5z_lqp.js +1 -0
  1111. package/.next/static/chunks/36ycf2tz4-z71.js +1 -0
  1112. package/.next/static/chunks/3ecdy1hiasj67.css +1 -0
  1113. package/.next/static/chunks/3h6bvrhsfedzo.js +1 -0
  1114. package/.next/static/chunks/3nv776qckior_.js +1 -0
  1115. package/.next/static/chunks/3w8vde_er6gsg.js +1 -0
  1116. package/.next/static/chunks/44l1w8l12d4mt.css +1 -0
  1117. package/.next/static/chunks/turbopack-2u1d16houkiyo.js +1 -0
  1118. package/.next/static/vK0UjQCR1UeWb0AjLM6gH/_buildManifest.js +11 -0
  1119. package/.next/static/vK0UjQCR1UeWb0AjLM6gH/_clientMiddlewareManifest.js +10 -0
  1120. package/.next/static/vK0UjQCR1UeWb0AjLM6gH/_ssgManifest.js +1 -0
  1121. package/.next/trace +2 -0
  1122. package/.next/trace-build +1 -0
  1123. package/.next/turbopack +0 -0
  1124. package/.next/types/cache-life.d.ts +114 -0
  1125. package/.next/types/root-params.d.ts +3 -0
  1126. package/.next/types/routes.d.ts +131 -0
  1127. package/.next/types/validator.ts +793 -0
  1128. package/README.md +36 -2
  1129. package/bin/lib/config.mjs +236 -0
  1130. package/bin/mailcast.mjs +567 -0
  1131. package/components.json +21 -0
  1132. package/next.config.mjs +13 -0
  1133. package/package.json +142 -4
  1134. package/postcss.config.mjs +5 -0
  1135. package/prisma/migrations/20261122000000_init/migration.sql +295 -0
  1136. package/prisma/migrations/migration_lock.toml +3 -0
  1137. package/prisma/schema.prisma +332 -0
  1138. package/public/logo.svg +29 -0
  1139. package/public/robots.txt +14 -0
  1140. package/scripts/load-env.mjs +12 -0
  1141. package/scripts/seed-admin.mjs +74 -0
  1142. package/src/app/api/auth/login/route.ts +69 -0
  1143. package/src/app/api/auth/logout/route.ts +35 -0
  1144. package/src/app/api/auth/session/route.ts +55 -0
  1145. package/src/app/api/auth/setup/route.ts +88 -0
  1146. package/src/app/api/campaigns/[id]/publish/route.ts +62 -0
  1147. package/src/app/api/campaigns/[id]/route.ts +180 -0
  1148. package/src/app/api/campaigns/[id]/send/route.ts +285 -0
  1149. package/src/app/api/campaigns/[id]/stats/route.ts +98 -0
  1150. package/src/app/api/campaigns/all/route.ts +15 -0
  1151. package/src/app/api/campaigns/route.ts +167 -0
  1152. package/src/app/api/contacts/[id]/route.ts +21 -0
  1153. package/src/app/api/contacts/all/route.ts +14 -0
  1154. package/src/app/api/contacts/import/route.ts +230 -0
  1155. package/src/app/api/contacts/route.ts +189 -0
  1156. package/src/app/api/cron/route.ts +36 -0
  1157. package/src/app/api/forms/[id]/route.ts +330 -0
  1158. package/src/app/api/forms/[id]/submissions/route.ts +72 -0
  1159. package/src/app/api/forms/[id]/submit/route.ts +448 -0
  1160. package/src/app/api/forms/route.ts +283 -0
  1161. package/src/app/api/forms/templates/[id]/route.ts +18 -0
  1162. package/src/app/api/forms/templates/route.ts +94 -0
  1163. package/src/app/api/groups/[id]/contacts/route.ts +201 -0
  1164. package/src/app/api/groups/[id]/route.ts +154 -0
  1165. package/src/app/api/groups/route.ts +105 -0
  1166. package/src/app/api/media/[name]/route.ts +19 -0
  1167. package/src/app/api/media/route.ts +52 -0
  1168. package/src/app/api/public/forms/[id]/route.ts +3 -0
  1169. package/src/app/api/public/posts/[slug]/route.ts +37 -0
  1170. package/src/app/api/public/posts/route.ts +27 -0
  1171. package/src/app/api/public/unsubscribe/route.ts +202 -0
  1172. package/src/app/api/route.ts +5 -0
  1173. package/src/app/api/senders/[id]/route.ts +28 -0
  1174. package/src/app/api/senders/route.ts +100 -0
  1175. package/src/app/api/settings/telegram/route.ts +110 -0
  1176. package/src/app/api/settings/telegram/stats/route.ts +45 -0
  1177. package/src/app/api/stats/route.ts +87 -0
  1178. package/src/app/api/t/[token]/route.ts +99 -0
  1179. package/src/app/api/templates/[id]/route.ts +97 -0
  1180. package/src/app/api/templates/route.ts +71 -0
  1181. package/src/app/api/workflows/[id]/enroll/route.ts +131 -0
  1182. package/src/app/api/workflows/[id]/route.ts +326 -0
  1183. package/src/app/api/workflows/[id]/run/route.ts +36 -0
  1184. package/src/app/api/workflows/route.ts +212 -0
  1185. package/src/app/blog/[slug]/page.tsx +66 -0
  1186. package/src/app/blog/page.tsx +69 -0
  1187. package/src/app/dashboard/automations/page.tsx +10 -0
  1188. package/src/app/dashboard/campaigns/[id]/page.tsx +10 -0
  1189. package/src/app/dashboard/campaigns/page.tsx +5 -0
  1190. package/src/app/dashboard/contacts/page.tsx +5 -0
  1191. package/src/app/dashboard/forms/page.tsx +5 -0
  1192. package/src/app/dashboard/layout.tsx +18 -0
  1193. package/src/app/dashboard/media/page.tsx +5 -0
  1194. package/src/app/dashboard/page.tsx +5 -0
  1195. package/src/app/dashboard/senders/page.tsx +20 -0
  1196. package/src/app/dashboard/settings/page.tsx +5 -0
  1197. package/src/app/doc/page.tsx +5 -0
  1198. package/src/app/documentation/page.tsx +5 -0
  1199. package/src/app/globals.css +146 -0
  1200. package/src/app/layout.tsx +48 -0
  1201. package/src/app/login/page.tsx +10 -0
  1202. package/src/app/page.tsx +5 -0
  1203. package/src/app/unsubscribe/page.tsx +333 -0
  1204. package/src/components/app/auth/login-form.tsx +237 -0
  1205. package/src/components/app/automations/automations-section.tsx +462 -0
  1206. package/src/components/app/automations/enroll-dialog.tsx +23 -0
  1207. package/src/components/app/automations/flow-nodes.tsx +203 -0
  1208. package/src/components/app/automations/node-library.tsx +192 -0
  1209. package/src/components/app/automations/node-types.ts +520 -0
  1210. package/src/components/app/automations/property-panel.tsx +1657 -0
  1211. package/src/components/app/automations/workflow-builder.tsx +751 -0
  1212. package/src/components/app/campaigns/campaign-editor.tsx +1603 -0
  1213. package/src/components/app/campaigns/campaign-list.tsx +227 -0
  1214. package/src/components/app/campaigns/rich-text-editor.tsx +296 -0
  1215. package/src/components/app/client-auth-gate.tsx +54 -0
  1216. package/src/components/app/contacts/contact-list.tsx +1174 -0
  1217. package/src/components/app/contacts/import-dialog.tsx +296 -0
  1218. package/src/components/app/dashboard-shell.tsx +43 -0
  1219. package/src/components/app/dashboard.tsx +93 -0
  1220. package/src/components/app/empty-state.tsx +43 -0
  1221. package/src/components/app/forms/embed-dialog.tsx +243 -0
  1222. package/src/components/app/forms/form-builder.tsx +1433 -0
  1223. package/src/components/app/forms/form-inspector.tsx +1560 -0
  1224. package/src/components/app/forms/form-preview.tsx +993 -0
  1225. package/src/components/app/forms/forms-section.tsx +315 -0
  1226. package/src/components/app/forms/submissions-dialog.tsx +245 -0
  1227. package/src/components/app/forms/types.ts +103 -0
  1228. package/src/components/app/media/media-manager.tsx +212 -0
  1229. package/src/components/app/overview.tsx +209 -0
  1230. package/src/components/app/quick-create.tsx +708 -0
  1231. package/src/components/app/section-heading.tsx +34 -0
  1232. package/src/components/app/senders/add-sender-dialog.tsx +179 -0
  1233. package/src/components/app/senders/sender-list.tsx +296 -0
  1234. package/src/components/app/settings.tsx +611 -0
  1235. package/src/components/app/sidebar.tsx +207 -0
  1236. package/src/components/app/stat-card.tsx +56 -0
  1237. package/src/components/app/status-badge.tsx +49 -0
  1238. package/src/components/app/templates/block-inspector.tsx +1594 -0
  1239. package/src/components/app/templates/canvas-block.tsx +541 -0
  1240. package/src/components/app/templates/email-builder-client.tsx +986 -0
  1241. package/src/components/app/templates/email-builder.tsx +23 -0
  1242. package/src/components/app/topbar.tsx +72 -0
  1243. package/src/components/app/use-api.ts +202 -0
  1244. package/src/components/landing/faq.tsx +84 -0
  1245. package/src/components/landing/features.tsx +147 -0
  1246. package/src/components/landing/final-cta.tsx +52 -0
  1247. package/src/components/landing/footer.tsx +89 -0
  1248. package/src/components/landing/hero.tsx +391 -0
  1249. package/src/components/landing/how-it-works.tsx +87 -0
  1250. package/src/components/landing/landing-page.tsx +45 -0
  1251. package/src/components/landing/logo.tsx +19 -0
  1252. package/src/components/landing/navbar.tsx +113 -0
  1253. package/src/components/landing/pricing.tsx +135 -0
  1254. package/src/components/landing/reveal.tsx +36 -0
  1255. package/src/components/landing/stats-bar.tsx +61 -0
  1256. package/src/components/ui/accordion.tsx +66 -0
  1257. package/src/components/ui/alert-dialog.tsx +157 -0
  1258. package/src/components/ui/alert.tsx +66 -0
  1259. package/src/components/ui/aspect-ratio.tsx +11 -0
  1260. package/src/components/ui/avatar.tsx +53 -0
  1261. package/src/components/ui/badge.tsx +46 -0
  1262. package/src/components/ui/breadcrumb.tsx +109 -0
  1263. package/src/components/ui/button.tsx +59 -0
  1264. package/src/components/ui/calendar.tsx +213 -0
  1265. package/src/components/ui/card.tsx +92 -0
  1266. package/src/components/ui/carousel.tsx +246 -0
  1267. package/src/components/ui/chart.tsx +353 -0
  1268. package/src/components/ui/checkbox.tsx +32 -0
  1269. package/src/components/ui/collapsible.tsx +33 -0
  1270. package/src/components/ui/command.tsx +184 -0
  1271. package/src/components/ui/context-menu.tsx +252 -0
  1272. package/src/components/ui/dialog.tsx +143 -0
  1273. package/src/components/ui/drawer.tsx +135 -0
  1274. package/src/components/ui/dropdown-menu.tsx +257 -0
  1275. package/src/components/ui/form.tsx +167 -0
  1276. package/src/components/ui/hover-card.tsx +44 -0
  1277. package/src/components/ui/input-otp.tsx +77 -0
  1278. package/src/components/ui/input.tsx +21 -0
  1279. package/src/components/ui/label.tsx +24 -0
  1280. package/src/components/ui/menubar.tsx +276 -0
  1281. package/src/components/ui/navigation-menu.tsx +168 -0
  1282. package/src/components/ui/pagination.tsx +127 -0
  1283. package/src/components/ui/popover.tsx +48 -0
  1284. package/src/components/ui/progress.tsx +31 -0
  1285. package/src/components/ui/radio-group.tsx +45 -0
  1286. package/src/components/ui/resizable.tsx +56 -0
  1287. package/src/components/ui/scroll-area.tsx +58 -0
  1288. package/src/components/ui/select.tsx +185 -0
  1289. package/src/components/ui/separator.tsx +28 -0
  1290. package/src/components/ui/sheet.tsx +139 -0
  1291. package/src/components/ui/sidebar.tsx +726 -0
  1292. package/src/components/ui/skeleton.tsx +13 -0
  1293. package/src/components/ui/slider.tsx +63 -0
  1294. package/src/components/ui/sonner.tsx +25 -0
  1295. package/src/components/ui/switch.tsx +31 -0
  1296. package/src/components/ui/table.tsx +116 -0
  1297. package/src/components/ui/tabs.tsx +66 -0
  1298. package/src/components/ui/textarea.tsx +18 -0
  1299. package/src/components/ui/toast.tsx +129 -0
  1300. package/src/components/ui/toaster.tsx +35 -0
  1301. package/src/components/ui/toggle-group.tsx +73 -0
  1302. package/src/components/ui/toggle.tsx +47 -0
  1303. package/src/components/ui/tooltip.tsx +61 -0
  1304. package/src/hooks/use-app-store.ts +57 -0
  1305. package/src/hooks/use-mobile.ts +21 -0
  1306. package/src/hooks/use-toast.ts +194 -0
  1307. package/src/instrumentation.ts +9 -0
  1308. package/src/lib/auth.ts +95 -0
  1309. package/src/lib/automation-engine.ts +1094 -0
  1310. package/src/lib/automation.ts +43 -0
  1311. package/src/lib/blog-render.ts +34 -0
  1312. package/src/lib/campaign-persist.ts +10 -0
  1313. package/src/lib/contact-import.ts +137 -0
  1314. package/src/lib/cron-runner.ts +61 -0
  1315. package/src/lib/cron.ts +203 -0
  1316. package/src/lib/crypto.ts +52 -0
  1317. package/src/lib/database-url.ts +30 -0
  1318. package/src/lib/db.ts +560 -0
  1319. package/src/lib/email-builder.ts +1558 -0
  1320. package/src/lib/email-cid.ts +53 -0
  1321. package/src/lib/email-font.ts +39 -0
  1322. package/src/lib/email-template.ts +182 -0
  1323. package/src/lib/file-types.ts +18 -0
  1324. package/src/lib/form-builder.ts +1489 -0
  1325. package/src/lib/form-response.ts +101 -0
  1326. package/src/lib/form-submission.ts +98 -0
  1327. package/src/lib/gmail.ts +185 -0
  1328. package/src/lib/grapes-config.ts +38 -0
  1329. package/src/lib/group-memberships.ts +13 -0
  1330. package/src/lib/markdown.ts +25 -0
  1331. package/src/lib/public-url.ts +14 -0
  1332. package/src/lib/send-result.ts +65 -0
  1333. package/src/lib/session-token.ts +42 -0
  1334. package/src/lib/supabase-storage.ts +219 -0
  1335. package/src/lib/telegram.ts +197 -0
  1336. package/src/lib/template-validation.ts +34 -0
  1337. package/src/lib/tracking-html.ts +29 -0
  1338. package/src/lib/tracking-store.ts +65 -0
  1339. package/src/lib/tracking.ts +46 -0
  1340. package/src/lib/unsubscribe-token.ts +79 -0
  1341. package/src/lib/utils.ts +6 -0
  1342. package/src/middleware.ts +59 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/add-base-path.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/app-call-server.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/app-dir/link.tsx","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/app-find-source-map-url.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/app-router-headers.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/app-router-state.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/links.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/render-tree.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/compute-changed-path.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/create-href-from-url.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/fetch-server-response.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/is-navigating-to-new-root-layout.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/reducers/committed-state.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/reducers/navigate-reducer.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/router-reducer-types.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/router-reducer/set-cache-busting-search-param.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/bfcache.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/cache-key.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/cache-map.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/cache.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/decode-server-response.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/fetch.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/lru.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/navigation-testing-lock.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/optimistic-routes.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/scheduler.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/types.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/segment-cache/vary-path.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/components/use-action-queue.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/flight-data-helpers.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/has-base-path.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/lib/javascript-url.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/navigation-build-id.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/normalize-trailing-slash.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/remove-base-path.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/route-params.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/sequential-call-server.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/client/use-merged-ref.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/lib/constants.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/app-router-types.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/deployment-id.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/hash.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/instant-messages.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/is-thenable.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/page-path/ensure-leading-slash.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/add-path-prefix.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/app-paths.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/cache-busting-search-param.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/format-url.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/interception-routes.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/is-local-url.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/parse-path.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/path-has-prefix.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/querystring.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/router/utils/remove-trailing-slash.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/rsc-transport.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/segment-cache/segment-value-encoding.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/segment-cache/vary-params-decoding.ts","../../../../node_modules/.pnpm/next%4016.4.6_%40babel%2Bcore%407.29.13_supports-color%407.2.0__%40types%2Bnode%4026.6.6_react-dom%4019.3.1_react%4019.3.1__react%4019.3.1/node_modules/next/src/shared/lib/utils.ts"],"sourcesContent":["import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function addBasePath(path: string, required?: boolean): string {\n return normalizePathTrailingSlash(\n process.env.__NEXT_MANUAL_CLIENT_BASE_PATH && !required\n ? path\n : addPathPrefix(path, basePath)\n )\n}\n","// The entry point for Server Actions: the \"action door\" into the router.\n// Server Actions are deliberately not a navigator operation (navigator.ts) —\n// the action queue is semantically separate from the router state queue —\n// but this module forks the same way: by default it re-exports the\n// sequential implementation, and when `experimental.concurrentRouterQueue`\n// is enabled, imports of this module resolve to './concurrent-call-server'\n// instead at the bundler level (see create-compiler-aliases.ts and\n// next_import_map.rs). Both implementations expose exactly this surface.\n\n/**\n * Invoke a Server Action. The returned promise resolves with the action's\n * return value once the response has been processed. Navigation and\n * revalidation side effects of the action are handled by the router; they are\n * not observable through the returned promise.\n */\nexport { callServer } from './sequential-call-server'\n","'use client'\n\nimport React, { createContext, useContext, useOptimistic, useRef } from 'react'\nimport type { UrlObject } from 'url'\nimport { formatUrl } from '../../shared/lib/router/utils/format-url'\nimport { AppRouterContext } from '../../shared/lib/app-router-context.shared-runtime'\nimport { useMergedRef } from '../use-merged-ref'\nimport { isAbsoluteUrl } from '../../shared/lib/utils'\nimport { addBasePath } from '../add-base-path'\nimport { ScrollBehavior } from '../components/router-reducer/router-reducer-types'\nimport type { PENDING_LINK_STATUS } from '../components/links'\nimport {\n IDLE_LINK_STATUS,\n mountLinkInstance,\n onNavigationIntent,\n unmountLinkForCurrentNavigation,\n unmountPrefetchableInstance,\n type LinkInstance,\n} from '../components/links'\nimport { isLocalURL } from '../../shared/lib/router/utils/is-local-url'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n} from '../components/segment-cache/types'\nimport type { RouterTransitionPrefetchIntent } from '../router-transition-types'\n\ntype Url = string | UrlObject\ntype RequiredKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? never : K\n}[keyof T]\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never\n}[keyof T]\n\ntype OnNavigateEventHandler = (event: { preventDefault: () => void }) => void\n\ntype InternalLinkProps = {\n /**\n * **Required**. The path or URL to navigate to. It can also be an object (similar to `URL`).\n *\n * @example\n * ```tsx\n * // Navigate to /dashboard:\n * <Link href=\"/dashboard\">Dashboard</Link>\n *\n * // Navigate to /about?name=test:\n * <Link href={{ pathname: '/about', query: { name: 'test' } }}>\n * About\n * </Link>\n * ```\n *\n * @remarks\n * - For external URLs, use a fully qualified URL such as `https://...`.\n * - In the App Router, dynamic routes must not include bracketed segments in `href`.\n */\n href: Url\n\n /**\n * @deprecated v10.0.0: `href` props pointing to a dynamic route are\n * automatically resolved and no longer require the `as` prop.\n */\n as?: Url\n\n /**\n * Replace the current `history` state instead of adding a new URL into the stack.\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/about\" replace>\n * About (replaces the history state)\n * </Link>\n * ```\n */\n replace?: boolean\n\n /**\n * Whether to override the default scroll behavior. If `true`, Next.js attempts to maintain\n * the scroll position if the newly navigated page is still visible. If not, it scrolls to the top.\n *\n * If `false`, Next.js will not modify the scroll behavior at all.\n *\n * @defaultValue `true`\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" scroll={false}>\n * No auto scroll\n * </Link>\n * ```\n */\n scroll?: boolean\n\n /**\n * Update the path of the current page without rerunning data fetching methods\n * like `getStaticProps`, `getServerSideProps`, or `getInitialProps`.\n *\n * @remarks\n * `shallow` only applies to the Pages Router. For the App Router, see the\n * [following documentation](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#using-the-native-history-api).\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/blog\" shallow>\n * Shallow navigation\n * </Link>\n * ```\n */\n shallow?: boolean\n\n /**\n * Forces `Link` to pass its `href` to the child component. Useful if the child is a custom\n * component that wraps an `<a>` tag, or if you're using certain styling libraries.\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" passHref legacyBehavior>\n * <MyStyledAnchor>Dashboard</MyStyledAnchor>\n * </Link>\n * ```\n */\n passHref?: boolean\n\n /**\n * Prefetch the page in the background.\n * Any `<Link />` that is in the viewport (initially or through scroll) will be prefetched.\n * Prefetch can be disabled by passing `prefetch={false}`.\n *\n * @remarks\n * Prefetching is only enabled in production.\n *\n * - In the **App Router**:\n * - `\"auto\"`, `null`, `undefined` (default): Prefetch behavior depends on static vs dynamic routes:\n * - Static routes: fully prefetched\n * - Dynamic routes: partial prefetch to the nearest segment with a `loading.js`\n * - `true`: Always prefetch the full route and data.\n * - `false`: Disable prefetching on both viewport and hover.\n * - In the **Pages Router**:\n * - `true` (default): Prefetches the route and data in the background on viewport or hover.\n * - `false`: Prefetch only on hover, not on viewport.\n *\n * @defaultValue `true` (Pages Router) or `null` (App Router)\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" prefetch={false}>\n * Dashboard\n * </Link>\n * ```\n */\n prefetch?: boolean | 'auto' | null\n\n /**\n * (unstable) Switch to a full prefetch on hover. Effectively the same as\n * updating the prefetch prop to `true` in a mouse event.\n */\n unstable_dynamicOnHover?: boolean\n\n /**\n * The active locale is automatically prepended in the Pages Router. `locale` allows for providing\n * a different locale, or can be set to `false` to opt out of automatic locale behavior.\n *\n * @remarks\n * Note: locale only applies in the Pages Router and is ignored in the App Router.\n *\n * @example\n * ```tsx\n * // Use the 'fr' locale:\n * <Link href=\"/about\" locale=\"fr\">\n * About (French)\n * </Link>\n *\n * // Disable locale prefix:\n * <Link href=\"/about\" locale={false}>\n * About (no locale prefix)\n * </Link>\n * ```\n */\n locale?: string | false\n\n /**\n * Enable legacy link behavior.\n *\n * @deprecated This will be removed in a future version\n * @defaultValue `false`\n * @see https://github.com/vercel/next.js/commit/489e65ed98544e69b0afd7e0cfc3f9f6c2b803b7\n */\n legacyBehavior?: boolean\n\n /**\n * Optional event handler for when the mouse pointer is moved onto the `<Link>`.\n */\n onMouseEnter?: React.MouseEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is touched.\n */\n onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is clicked.\n */\n onClick?: React.MouseEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is navigated.\n */\n onNavigate?: OnNavigateEventHandler\n\n /**\n * Transition types to apply when navigating. These types are passed to\n * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n * inside the navigation transition, enabling\n * [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components\n * to apply different animations based on the type of navigation.\n *\n * @example\n * ```tsx\n * <Link href=\"/about\" transitionTypes={['slide-in']}>About</Link>\n * ```\n */\n transitionTypes?: string[]\n}\n\n// TODO-APP: Include the full set of Anchor props\n// adding this to the publicly exported type currently breaks existing apps\n\n// `RouteInferType` is a stub here to avoid breaking `typedRoutes` when the type\n// isn't generated yet. It will be replaced when type generation runs.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type LinkProps<RouteInferType = any> = InternalLinkProps\ntype LinkPropsRequired = RequiredKeys<LinkProps>\ntype LinkPropsOptional = OptionalKeys<Omit<InternalLinkProps, 'locale'>>\n\nfunction isModifiedEvent(event: React.MouseEvent): boolean {\n const eventTarget = event.currentTarget as HTMLAnchorElement | SVGAElement\n const target = eventTarget.getAttribute('target')\n return (\n (target && target !== '_self') ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey || // triggers resource download\n (event.nativeEvent && event.nativeEvent.which === 2)\n )\n}\n\nfunction linkClicked(\n e: React.MouseEvent,\n href: string,\n linkInstanceRef: React.RefObject<LinkInstance | null>,\n replace?: boolean,\n scroll?: boolean,\n onNavigate?: OnNavigateEventHandler,\n transitionTypes?: string[],\n prefetchIntent: RouterTransitionPrefetchIntent = 'none'\n): void {\n if (typeof window !== 'undefined') {\n const { nodeName } = e.currentTarget\n\n // anchors inside an svg have a lowercase nodeName\n const isAnchorNodeName = nodeName.toUpperCase() === 'A'\n if (\n (isAnchorNodeName && isModifiedEvent(e)) ||\n e.currentTarget.hasAttribute('download')\n ) {\n // ignore click for browser’s default behavior\n return\n }\n\n if (!isLocalURL(href)) {\n if (replace) {\n // browser default behavior does not replace the history state\n // so we need to do it manually\n e.preventDefault()\n location.replace(href)\n }\n\n // ignore click for browser’s default behavior\n return\n }\n\n e.preventDefault()\n\n if (onNavigate) {\n let isDefaultPrevented = false\n\n onNavigate({\n preventDefault: () => {\n isDefaultPrevented = true\n },\n })\n\n if (isDefaultPrevented) {\n return\n }\n }\n\n const { navigate } =\n // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require-tsx\n require('../components/navigator') as typeof import('../components/navigator')\n\n navigate(\n href,\n replace ? 'replace' : 'push',\n scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,\n linkInstanceRef.current,\n transitionTypes,\n prefetchIntent\n )\n }\n}\n\nfunction formatStringOrUrl(urlObjOrString: UrlObject | string): string {\n if (typeof urlObjOrString === 'string') {\n return urlObjOrString\n }\n\n return formatUrl(urlObjOrString)\n}\n\n/**\n * A React component that extends the HTML `<a>` element to provide\n * [prefetching](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching)\n * and client-side navigation. This is the primary way to navigate between routes in Next.js.\n *\n * @remarks\n * - Prefetching is only enabled in production.\n *\n * @see https://nextjs.org/docs/app/api-reference/components/link\n */\nexport default function LinkComponent(\n props: LinkProps & {\n children: React.ReactNode\n ref: React.Ref<HTMLAnchorElement>\n }\n) {\n const [linkStatus, setOptimisticLinkStatus] = useOptimistic(IDLE_LINK_STATUS)\n\n let children: React.ReactNode\n\n const linkInstanceRef = useRef<LinkInstance | null>(null)\n\n const {\n href: hrefProp,\n as: asProp,\n children: childrenProp,\n prefetch: prefetchProp = null,\n passHref,\n replace,\n shallow,\n scroll,\n onClick,\n onMouseEnter: onMouseEnterProp,\n onTouchStart: onTouchStartProp,\n legacyBehavior = false,\n onNavigate,\n transitionTypes,\n ref: forwardedRef,\n unstable_dynamicOnHover,\n ...restProps\n } = props\n\n children = childrenProp\n\n if (\n legacyBehavior &&\n (typeof children === 'string' || typeof children === 'number')\n ) {\n children = <a>{children}</a>\n }\n\n const router = React.useContext(AppRouterContext)\n\n const prefetchEnabled = prefetchProp !== false\n const prefetchIntent: RouterTransitionPrefetchIntent =\n prefetchProp === false ? 'none' : prefetchProp === true ? 'full' : 'auto'\n\n const fetchStrategy =\n prefetchIntent !== 'none'\n ? getFetchStrategyFromPrefetchIntent(prefetchIntent)\n : // TODO: it makes no sense to assign a fetchStrategy when prefetching is disabled.\n FetchStrategy.PPR\n\n if (process.env.NODE_ENV !== 'production') {\n function createPropError(args: {\n key: string\n expected: string\n actual: string\n }) {\n return new Error(\n `Failed prop type: The prop \\`${args.key}\\` expects a ${args.expected} in \\`<Link>\\`, but got \\`${args.actual}\\` instead.` +\n (typeof window !== 'undefined'\n ? \"\\nOpen your browser's console to view the Component stack trace.\"\n : '')\n )\n }\n\n // TypeScript trick for type-guarding:\n const requiredPropsGuard: Record<LinkPropsRequired, true> = {\n href: true,\n } as const\n const requiredProps: LinkPropsRequired[] = Object.keys(\n requiredPropsGuard\n ) as LinkPropsRequired[]\n requiredProps.forEach((key: LinkPropsRequired) => {\n if (key === 'href') {\n if (\n props[key] == null ||\n (typeof props[key] !== 'string' && typeof props[key] !== 'object')\n ) {\n throw createPropError({\n key,\n expected: '`string` or `object`',\n actual: props[key] === null ? 'null' : typeof props[key],\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n const _: never = key\n }\n })\n\n // TypeScript trick for type-guarding:\n const optionalPropsGuard: Record<LinkPropsOptional, true> = {\n as: true,\n replace: true,\n scroll: true,\n shallow: true,\n passHref: true,\n prefetch: true,\n unstable_dynamicOnHover: true,\n onClick: true,\n onMouseEnter: true,\n onTouchStart: true,\n legacyBehavior: true,\n onNavigate: true,\n transitionTypes: true,\n } as const\n const optionalProps: LinkPropsOptional[] = Object.keys(\n optionalPropsGuard\n ) as LinkPropsOptional[]\n optionalProps.forEach((key: LinkPropsOptional) => {\n const valType = typeof props[key]\n\n if (key === 'as') {\n if (props[key] && valType !== 'string' && valType !== 'object') {\n throw createPropError({\n key,\n expected: '`string` or `object`',\n actual: valType,\n })\n }\n } else if (\n key === 'onClick' ||\n key === 'onMouseEnter' ||\n key === 'onTouchStart' ||\n key === 'onNavigate'\n ) {\n if (props[key] && valType !== 'function') {\n throw createPropError({\n key,\n expected: '`function`',\n actual: valType,\n })\n }\n } else if (\n key === 'replace' ||\n key === 'scroll' ||\n key === 'shallow' ||\n key === 'passHref' ||\n key === 'legacyBehavior' ||\n key === 'unstable_dynamicOnHover'\n ) {\n if (props[key] != null && valType !== 'boolean') {\n throw createPropError({\n key,\n expected: '`boolean`',\n actual: valType,\n })\n }\n } else if (key === 'prefetch') {\n if (\n props[key] != null &&\n valType !== 'boolean' &&\n props[key] !== 'auto'\n ) {\n throw createPropError({\n key,\n expected: '`boolean | \"auto\"`',\n actual: valType,\n })\n }\n } else if (key === 'transitionTypes') {\n if (props[key] != null && !Array.isArray(props[key])) {\n throw createPropError({\n key,\n expected: '`string[]`',\n actual: valType,\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n const _: never = key\n }\n })\n }\n\n const resolvedHref = asProp || hrefProp\n const formattedHref = formatStringOrUrl(resolvedHref)\n\n if (process.env.NODE_ENV !== 'production') {\n const { warnOnce } =\n require('../../shared/lib/utils/warn-once') as typeof import('../../shared/lib/utils/warn-once')\n if (props.locale) {\n warnOnce(\n 'The `locale` prop is not supported in `next/link` while using the `app` router. Read more about app router internalization: https://nextjs.org/docs/app/building-your-application/routing/internationalization'\n )\n }\n if (!asProp) {\n let href: string | undefined\n if (typeof resolvedHref === 'string') {\n href = resolvedHref\n } else if (\n typeof resolvedHref === 'object' &&\n typeof resolvedHref.pathname === 'string'\n ) {\n href = resolvedHref.pathname\n }\n\n if (href) {\n const hasDynamicSegment = href\n .split('/')\n .some((segment) => segment.startsWith('[') && segment.endsWith(']'))\n\n if (hasDynamicSegment) {\n throw new Error(\n `Dynamic href \\`${href}\\` found in <Link> while using the \\`/app\\` router, this is not supported. Read more: https://nextjs.org/docs/messages/app-dir-dynamic-href`\n )\n }\n }\n }\n }\n\n // This will return the first child, if multiple are provided it will throw an error\n let child: any\n if (legacyBehavior) {\n if ((children as any)?.$$typeof === Symbol.for('react.lazy')) {\n throw new Error(\n `\\`<Link legacyBehavior>\\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \\`<a>\\` tag.`\n )\n }\n\n if (process.env.NODE_ENV === 'development') {\n if (onClick) {\n console.warn(\n `\"onClick\" was passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but \"legacyBehavior\" was set. The legacy behavior requires onClick be set on the child of next/link`\n )\n }\n if (onMouseEnterProp) {\n console.warn(\n `\"onMouseEnter\" was passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but \"legacyBehavior\" was set. The legacy behavior requires onMouseEnter be set on the child of next/link`\n )\n }\n try {\n child = React.Children.only(children)\n } catch (err) {\n if (!children) {\n throw new Error(\n `No children were passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but one child is required https://nextjs.org/docs/messages/link-no-children`\n )\n }\n throw new Error(\n `Multiple children were passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children` +\n (typeof window !== 'undefined'\n ? \" \\nOpen your browser's console to view the Component stack trace.\"\n : '')\n )\n }\n } else {\n child = React.Children.only(children)\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if ((children as any)?.type === 'a') {\n throw new Error(\n 'Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'\n )\n }\n }\n }\n\n const childRef: any = legacyBehavior\n ? child && typeof child === 'object' && child.ref\n : forwardedRef\n\n // Capture the Owner Stack during render so dev-only warnings emitted later\n // at navigation time can be associated with the JSX that created\n // this <Link>.\n const ownerStack =\n process.env.NODE_ENV !== 'production' && process.env.__NEXT_CACHE_COMPONENTS\n ? // eslint-disable-next-line react-hooks/rules-of-hooks -- build time variables\n React.useMemo(() => {\n // Only capture when a warning might actually need it. Otherwise leave\n // it `undefined` so consumers can detect the opt-out and degrade\n // gracefully.\n if (fetchStrategy === FetchStrategy.Full) {\n return React.captureOwnerStack()\n }\n return undefined\n }, [fetchStrategy])\n : undefined\n\n // Use a callback ref to attach an IntersectionObserver to the anchor tag on\n // mount. In the future we will also use this to keep track of all the\n // currently mounted <Link> instances, e.g. so we can re-prefetch them after\n // a revalidation or refresh.\n const observeLinkVisibilityOnMount = React.useCallback(\n (element: HTMLAnchorElement | SVGAElement) => {\n if (router !== null) {\n linkInstanceRef.current = mountLinkInstance(\n element,\n formattedHref,\n router,\n fetchStrategy,\n prefetchEnabled,\n setOptimisticLinkStatus,\n ownerStack\n )\n }\n\n return () => {\n if (linkInstanceRef.current) {\n unmountLinkForCurrentNavigation(linkInstanceRef.current)\n linkInstanceRef.current = null\n }\n unmountPrefetchableInstance(element)\n }\n },\n [\n prefetchEnabled,\n formattedHref,\n router,\n fetchStrategy,\n setOptimisticLinkStatus,\n ownerStack,\n ]\n )\n\n const mergedRef = useMergedRef(observeLinkVisibilityOnMount, childRef)\n\n const childProps: {\n onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>\n onMouseEnter: React.MouseEventHandler<HTMLAnchorElement>\n onClick: React.MouseEventHandler<HTMLAnchorElement>\n href?: string\n ref?: any\n } = {\n ref: mergedRef,\n onClick(e) {\n if (process.env.NODE_ENV !== 'production') {\n if (!e) {\n throw new Error(\n `Component rendered inside next/link has to pass click event to \"onClick\" prop.`\n )\n }\n }\n\n if (!legacyBehavior && typeof onClick === 'function') {\n onClick(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onClick === 'function'\n ) {\n child.props.onClick(e)\n }\n\n if (!router) {\n return\n }\n if (e.defaultPrevented) {\n return\n }\n linkClicked(\n e,\n formattedHref,\n linkInstanceRef,\n replace,\n scroll,\n onNavigate,\n transitionTypes,\n prefetchIntent\n )\n },\n onMouseEnter(e) {\n if (!legacyBehavior && typeof onMouseEnterProp === 'function') {\n onMouseEnterProp(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onMouseEnter === 'function'\n ) {\n child.props.onMouseEnter(e)\n }\n\n if (!router) {\n return\n }\n if (!prefetchEnabled || process.env.NODE_ENV === 'development') {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(\n e.currentTarget as HTMLAnchorElement | SVGAElement,\n upgradeToDynamicPrefetch\n )\n },\n onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START\n ? undefined\n : function onTouchStart(e) {\n if (!legacyBehavior && typeof onTouchStartProp === 'function') {\n onTouchStartProp(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onTouchStart === 'function'\n ) {\n child.props.onTouchStart(e)\n }\n\n if (!router) {\n return\n }\n if (!prefetchEnabled) {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(\n e.currentTarget as HTMLAnchorElement | SVGAElement,\n upgradeToDynamicPrefetch\n )\n },\n }\n\n // If the url is absolute, we can bypass the logic to prepend the basePath.\n if (isAbsoluteUrl(formattedHref)) {\n childProps.href = formattedHref\n } else if (\n !legacyBehavior ||\n passHref ||\n (child.type === 'a' && !('href' in child.props))\n ) {\n childProps.href = addBasePath(formattedHref)\n }\n\n let link: React.ReactNode\n\n if (legacyBehavior) {\n if (process.env.NODE_ENV === 'development') {\n const { errorOnce } =\n require('../../shared/lib/utils/error-once') as typeof import('../../shared/lib/utils/error-once')\n errorOnce(\n '`legacyBehavior` is deprecated and will be removed in a future ' +\n 'release. A codemod is available to upgrade your components:\\n\\n' +\n 'npx @next/codemod@latest new-link .\\n\\n' +\n 'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components'\n )\n }\n link = React.cloneElement(child, childProps)\n } else {\n link = (\n <a {...restProps} {...childProps}>\n {children}\n </a>\n )\n }\n\n return (\n <LinkStatusContext.Provider value={linkStatus}>\n {link}\n </LinkStatusContext.Provider>\n )\n}\n\nconst LinkStatusContext = createContext<\n typeof PENDING_LINK_STATUS | typeof IDLE_LINK_STATUS\n>(IDLE_LINK_STATUS)\n\nexport const useLinkStatus = () => {\n return useContext(LinkStatusContext)\n}\n\nfunction getFetchStrategyFromPrefetchIntent(\n prefetchIntent: Exclude<RouterTransitionPrefetchIntent, 'none'>\n): PrefetchTaskFetchStrategy {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (prefetchIntent === 'full') {\n return FetchStrategy.Full\n }\n\n // `\"auto\"`: the default mode, where we will prefetch partially if the link is in the viewport.\n prefetchIntent satisfies 'auto'\n return FetchStrategy.PPR\n } else {\n return prefetchIntent === 'auto'\n ? // We default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.\n FetchStrategy.PPR\n : // In the old implementation without runtime prefetches, `prefetch={true}` (`'full'`) forces all dynamic\n // data to be prefetched, preserving backwards-compatibility.\n FetchStrategy.Full\n }\n}\n","const basePath = process.env.__NEXT_ROUTER_BASEPATH || ''\nconst pathname = `${basePath}/__nextjs_source-map`\n\nexport const findSourceMapURL =\n // Source maps are only served by the dev server.\n process.env.__NEXT_DEV_SERVER\n ? function findSourceMapURL(filename: string): string | null {\n if (filename === '') {\n return null\n }\n\n if (\n filename.startsWith(document.location.origin) &&\n filename.includes('/_next/static')\n ) {\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\n const url = new URL(pathname, document.location.origin)\n url.searchParams.set('filename', filename)\n\n return url.href\n }\n : undefined\n","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_URL = 'next-url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\n// Cookie for the Instant Navigation Testing API. Sent automatically with all\n// requests while a navigation lock is held; the server uses its presence to\n// render only the shell. Not exposed in production builds by default.\nexport const NEXT_INSTANT_TEST_COOKIE =\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","import type { RootRouteTree } from './segment-cache/cache'\nimport type {\n FlightRouterState,\n ScrollRef,\n} from '../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../shared/lib/app-router-types'\nimport { fetchServerResponse } from './router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n type RootNavigationTask,\n} from './render-tree'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport {\n EntryStatus,\n segmentCacheMap,\n type SegmentCacheEntry,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n spawnStaticStageCacheWrite,\n writeRuntimePrefetchStreamIntoCache,\n type FulfilledRouteCacheEntry,\n createRootRouteTree,\n} from './segment-cache/cache'\nimport { discoverKnownRoute } from './segment-cache/optimistic-routes'\nimport {\n createCacheKey,\n type NormalizedSearch,\n} from './segment-cache/cache-key'\nimport type { CacheMap } from './segment-cache/cache-map'\nimport { schedulePrefetchTask } from './segment-cache/scheduler'\nimport { PrefetchPriority, FetchStrategy } from './segment-cache/types'\nimport { getLinkForCurrentNavigation } from './links'\nimport type { AppRouterState } from './router-reducer/router-reducer-types'\nimport { ScrollBehavior } from './router-reducer/router-reducer-types'\nimport { computeChangedPath } from './router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../lib/javascript-url'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from './segment-cache/bfcache'\nimport { createLinkPrefetchPartialError } from '../../shared/lib/instant-messages'\nimport {\n createNavigationSeed,\n type NavigationSeed,\n} from './segment-cache/decode-server-response'\n\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 */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentRoot: RootRouteTree<CacheNode>,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentRoot,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentRoot,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n // An unlocked navigation is bound to the shared map.\n segmentCacheMap\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentRoot: RootRouteTree<CacheNode>,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\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(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentRoot,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock,\n map\n )\n }\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(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentRoot,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock,\n map\n )\n }\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(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentRoot,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n map\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentRoot: RootRouteTree<CacheNode>,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n debugInfo: Array<unknown> | null,\n // 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).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.root.tree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.root.tree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const navigation = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentRoot,\n navigationSeed.root,\n freshnessPolicy,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n map,\n restrictToShell\n )\n if (navigation !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n navigation,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n map,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n navigation,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentRoot: RootRouteTree<CacheNode>,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): AppRouterState {\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n root: route.root,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n // Not derived from a server response; no base to diverge from.\n treeDivergedFromBase: false,\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentRoot,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\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: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentRoot: RootRouteTree<CacheNode>,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the render\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\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\n const {\n transportData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n isResponsePartial,\n staticStageResponse,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = createNavigationSeed(\n now,\n currentFlightRouterState,\n transportData,\n // Navigation responses stream in incrementally, so their vary params\n // can't be drained here — and nothing consumes them from a navigation\n // seed (only segment-cache writes read vary params, and those decode\n // their own, buffered, payloads).\n null,\n isResponsePartial,\n // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null,\n renderedSearch,\n null,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.root,\n couldBeIntercepted,\n // Store a hashless canonical URL: the entry is shared across hashes, and\n // a later same-route hash nav appends `url.hash` to it.\n createHrefFromUrl(canonicalUrl, false),\n navigationSeed.renderedSearch,\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageResponse !== null) {\n spawnStaticStageCacheWrite(\n now,\n staticStageResponse,\n isResponsePartial,\n responseHeaders,\n currentFlightRouterState,\n renderedSearch,\n map\n )\n }\n\n if (runtimePrefetchStream !== null) {\n writeRuntimePrefetchStreamIntoCache(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch,\n map\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 // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentRoot,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n map,\n debugInfo,\n // 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 // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n scrollRef: state.scrollRef,\n root: state.root,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n navigation: RootNavigationTask,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const tree = navigation.tree.route\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\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\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\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: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on reused cache nodes remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.scrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\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\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.scrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n scrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.scrollRef.hashFragment,\n },\n root: createRootRouteTree(navigation.tree.node, navigation.head.node),\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n navigation: RootNavigationTask,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n scrollRef: state.scrollRef,\n root: createRootRouteTree(navigation.tree.node, navigation.head.node),\n // Restore provided tree\n tree: navigation.tree.route,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n/**\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 */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentRoot: RootRouteTree<CacheNode>,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves when the task completes — after every segment response the task\n // cares about has settled — so the navigation below reads present data\n // rather than a still-in-flight entry.\n const { beginNavigationLockPrefetch } =\n require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n const prefetchTask = schedulePrefetchTask(\n cacheKey,\n currentRoot,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache. The navigation inherits the map of\n // the prefetch task that drives it: the task was scheduled inside the lock\n // scope, so this is the scope's private map, and the navigation reads only\n // data fetched under the lock.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentRoot,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock,\n prefetchTask.segmentCacheMap\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n","import type { RootRouteTree } from './segment-cache/cache'\nimport type { CacheNode } from '../../shared/lib/app-router-types'\nimport type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n PrefetchPriority,\n} from './segment-cache/types'\nimport { createCacheKey } from './segment-cache/cache-key'\nimport {\n type PrefetchTask,\n schedulePrefetchTask as scheduleSegmentPrefetchTask,\n cancelPrefetchTask,\n reschedulePrefetchTask,\n isPrefetchTaskDirty,\n} from './segment-cache/scheduler'\nimport { startTransition } from 'react'\n\ntype LinkElement = HTMLAnchorElement | SVGAElement\n\ntype Element = LinkElement | HTMLFormElement\n\n// Properties that are shared between Link and Form instances. We use the same\n// shape for both to prevent a polymorphic de-opt in the VM.\ntype LinkOrFormInstanceShared = {\n router: AppRouterInstance\n fetchStrategy: PrefetchTaskFetchStrategy\n\n isVisible: boolean\n\n // The most recently initiated prefetch task. It may or may not have\n // already completed. The same prefetch task object can be reused across\n // multiple prefetches of the same link.\n prefetchTask: PrefetchTask | null\n}\n\nexport type FormInstance = LinkOrFormInstanceShared & {\n prefetchHref: string\n setOptimisticLinkStatus: null\n}\n\ntype PrefetchableLinkInstance = LinkOrFormInstanceShared & {\n // In dev, the Owner Stack captured at the time this Link was rendered, for\n // configurations where a warning might later fire.\n // `undefined` means we opted out of capturing the stack.\n // If you issue a warning, handle the `undefined` case separately\n // so it's clear in the logs when a warning is missing its source location.\n // A warning with an undefined ownerStack is considered a bug though so make\n // sure reaching the log site is a subset of codepaths that lead to capturing\n // the stack\n ownerStack: string | null | undefined\n prefetchHref: string\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n}\n\ntype NonPrefetchableLinkInstance = LinkOrFormInstanceShared & {\n ownerStack: string | null | undefined\n prefetchHref: null\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n}\n\ntype PrefetchableInstance = PrefetchableLinkInstance | FormInstance\n\nexport type LinkInstance =\n | PrefetchableLinkInstance\n | NonPrefetchableLinkInstance\n\n// Tracks the most recently navigated link instance. When null, indicates\n// the current navigation was not initiated by a link click.\nlet linkForMostRecentNavigation: LinkInstance | null = null\n\n// Status object indicating link is pending\nexport const PENDING_LINK_STATUS = { pending: true }\n\n// Status object indicating link is idle\nexport const IDLE_LINK_STATUS = { 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: LinkInstance | null) {\n startTransition(() => {\n linkForMostRecentNavigation?.setOptimisticLinkStatus(IDLE_LINK_STATUS)\n link?.setOptimisticLinkStatus(PENDING_LINK_STATUS)\n linkForMostRecentNavigation = link\n })\n}\n\n// Unmounts the current link instance from navigation tracking\nexport function unmountLinkForCurrentNavigation(link: LinkInstance) {\n if (linkForMostRecentNavigation === link) {\n linkForMostRecentNavigation = null\n }\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 */\nexport function getLinkForCurrentNavigation(): LinkInstance | null {\n return linkForMostRecentNavigation\n}\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:\n | WeakMap<Element, PrefetchableInstance>\n | Map<Element, PrefetchableInstance> =\n typeof WeakMap === 'function' ? new WeakMap() : new Map()\n\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: Set<PrefetchableInstance> = new Set()\n\n// A single IntersectionObserver instance shared by all <Link> components.\nconst observer: IntersectionObserver | null =\n typeof IntersectionObserver === 'function'\n ? new IntersectionObserver(handleIntersect, {\n rootMargin: '200px',\n })\n : null\n\nfunction observeVisibility(element: Element, instance: PrefetchableInstance) {\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}\n\nfunction coercePrefetchableUrl(href: string): URL | null {\n if (typeof window !== 'undefined') {\n const { createPrefetchURL } =\n // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require\n require('./app-router-utils') as typeof import('./app-router-utils')\n\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 =\n typeof reportError === 'function' ? reportError : console.error\n reportErrorFn(\n `Cannot prefetch '${href}' because it cannot be converted to a URL.`\n )\n return null\n }\n } else {\n return null\n }\n}\n\nexport function mountLinkInstance(\n element: LinkElement,\n href: string,\n router: AppRouterInstance,\n fetchStrategy: PrefetchTaskFetchStrategy,\n prefetchEnabled: boolean,\n setOptimisticLinkStatus: (status: { pending: boolean }) => void,\n ownerStack: string | null | undefined\n): LinkInstance {\n if (prefetchEnabled) {\n const prefetchURL = coercePrefetchableUrl(href)\n if (prefetchURL !== null) {\n const instance: PrefetchableLinkInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus,\n ownerStack,\n }\n // We only observe the link's visibility if it's prefetchable. For\n // example, this excludes links to external URLs.\n observeVisibility(element, instance)\n return instance\n }\n }\n // If the link is not prefetchable, we still create an instance so we can\n // track its optimistic state (i.e. useLinkStatus).\n const instance: NonPrefetchableLinkInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: null,\n setOptimisticLinkStatus,\n ownerStack,\n }\n return instance\n}\n\nexport function mountFormInstance(\n element: HTMLFormElement,\n href: string,\n router: AppRouterInstance,\n fetchStrategy: PrefetchTaskFetchStrategy\n): void {\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: FormInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus: null,\n }\n observeVisibility(element, instance)\n}\n\nexport function unmountPrefetchableInstance(element: 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}\n\nfunction handleIntersect(entries: Array<IntersectionObserverEntry>) {\n // Process the entries in reverse order. The prefetch scheduler assigns the\n // highest priority to the most recently scheduled task, so whichever link we\n // schedule *last* wins. When multiple links enter the viewport at once (e.g.\n // on initial load), the observer reports them in document order, so iterating\n // in reverse means the link nearest the top of the document is scheduled last\n // and therefore prioritized. The topmost link isn't guaranteed to be the most\n // important, but as a default heuristic it's more reasonable than prioritizing\n // whichever link happens to be lowest in the document.\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]\n // Some extremely old browsers or polyfills don't reliably support\n // isIntersecting so we check intersectionRatio instead. (Do we care? Not\n // really. But whatever this is fine.)\n const isVisible = entry.intersectionRatio > 0\n onLinkVisibilityChanged(entry.target as HTMLAnchorElement, isVisible)\n }\n}\n\nexport function onLinkVisibilityChanged(element: Element, isVisible: boolean) {\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\n const instance = prefetchable.get(element)\n if (instance === undefined) {\n return\n }\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}\n\nexport function onNavigationIntent(\n element: HTMLAnchorElement | SVGAElement,\n unstable_upgradeToDynamicPrefetch: boolean\n) {\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 (\n process.env.__NEXT_DYNAMIC_ON_HOVER &&\n unstable_upgradeToDynamicPrefetch\n ) {\n // Switch to a full prefetch\n instance.fetchStrategy = FetchStrategy.Full\n }\n rescheduleLinkPrefetch(instance, PrefetchPriority.Intent)\n }\n}\n\nfunction rescheduleLinkPrefetch(\n instance: PrefetchableInstance,\n priority: PrefetchPriority.Default | PrefetchPriority.Intent\n) {\n // Ensures that app-router-instance is not compiled in the server bundle\n if (typeof window !== 'undefined') {\n const existingPrefetchTask = instance.prefetchTask\n\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\n const { getCurrentAppRouterState } =\n // TODO(browser-variant): migrate to a .ts/.browser.ts split so the browser bundle drops the server branch; see scripts/generate-browser-variant-aliases.mjs\n // ast-grep-ignore: no-typeof-window-require\n require('./app-router-instance') as typeof import('./app-router-instance')\n\n const appRouterState = getCurrentAppRouterState()\n if (appRouterState !== null) {\n if (existingPrefetchTask === null) {\n // Initiate a prefetch task.\n const nextUrl = appRouterState.nextUrl\n const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)\n instance.prefetchTask = scheduleSegmentPrefetchTask(\n cacheKey,\n appRouterState.root,\n instance.fetchStrategy,\n priority,\n null,\n null // navigationLockPrefetch\n )\n } else {\n // We already have an old task object that we can reschedule. This is\n // effectively the same as canceling the old task and creating a new one.\n reschedulePrefetchTask(\n existingPrefetchTask,\n appRouterState.root,\n instance.fetchStrategy,\n priority\n )\n }\n }\n }\n}\n\nexport function pingVisibleLinks(\n nextUrl: string | null,\n root: RootRouteTree<CacheNode>\n) {\n // For each currently visible link, cancel the existing prefetch task (if it\n // exists) and schedule a new one. This is effectively the same as if all the\n // visible links left and then re-entered the viewport.\n //\n // This is called when the Next-Url or the active cache tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n for (const instance of prefetchableAndVisible) {\n const task = instance.prefetchTask\n if (task !== null && !isPrefetchTaskDirty(task, nextUrl, root)) {\n // The cache has not been invalidated, and none of the inputs have\n // changed. Bail out.\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(\n cacheKey,\n root,\n instance.fetchStrategy,\n PrefetchPriority.Default,\n null,\n null // navigationLockPrefetch\n )\n }\n}\n","import type { FlightRouterState } from '../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../shared/lib/app-router-types'\nimport type { ScrollRef } from '../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../shared/lib/app-router-types'\nimport {\n DEFAULT_SEGMENT_KEY,\n NOT_FOUND_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../shared/lib/segment'\nimport { HEAD_REQUEST_KEY } from '../../shared/lib/segment-cache/segment-value-encoding'\nimport { createHrefFromUrl } from './router-reducer/create-href-from-url'\nimport { fetchServerResponse } from './router-reducer/fetch-server-response'\nimport { dispatchAppRouterAction } from './use-action-queue'\nimport {\n ACTION_SERVER_PATCH,\n type ServerPatchAction,\n} from './router-reducer/router-reducer-types'\nimport { isNavigatingToNewRootLayout } from './router-reducer/is-navigating-to-new-root-layout'\nimport { getLastCommittedTree } from './router-reducer/reducers/committed-state'\nimport {\n createNavigationSeed,\n type NavigationSeed,\n} from './segment-cache/decode-server-response'\nimport {\n segmentCacheMap,\n type SegmentCacheEntry,\n type RouteTree,\n type RootRouteTree,\n type RSCSegmentData,\n type RefreshState,\n type FulfilledRouteCacheEntry,\n rebaseInactiveRouteTree,\n doesRouteStructureMatch,\n readSegmentCacheEntryForNavigation,\n waitForSegmentCacheEntry,\n invalidateRouteCacheEntries,\n spawnStaticStageCacheWrite,\n writeRuntimePrefetchStreamIntoCache,\n EntryStatus,\n MetadataOnlyRequestTree,\n} from './segment-cache/cache'\nimport { discoverKnownRoute } from './segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from './segment-cache/cache-key'\nimport type { CacheMap } from './segment-cache/cache-map'\nimport {\n getRenderedSearchFromVaryPath,\n compareParams,\n ParamsChange,\n didReadChangedParam,\n} from './segment-cache/vary-path'\nimport {\n readFromBFCache,\n readFromBFCacheDuringRegularNavigation,\n writeToBFCache,\n updateBFCacheEntryFromDynamicResponse,\n computeDynamicStaleAt,\n} from './segment-cache/bfcache'\nimport type { VaryParams } from '../../shared/lib/segment-cache/vary-params-decoding'\n\n// This is yet another tree type that is used to track pending promises that\n// need to be fulfilled once the dynamic data is received. The terminal nodes of\n// this tree represent the new Cache Node trees that were created during this\n// request. We can't use the Cache Node tree or Route State tree directly\n// because those include reused nodes, too. This tree is discarded as soon as\n// the navigation response is received.\nexport type NavigationTask = {\n status: NavigationTaskStatus\n // The router state that corresponds to the tree that this Task represents.\n route: FlightRouterState\n // The render tree being constructed by this task.\n node: RouteTree<CacheNode>\n // The tree sent to the server during the dynamic request. If all the segments\n // are static, then this will be null, and no server request is required.\n // Otherwise, this is the same as `route`, except with the `refetch` marker\n // set on the top-most segment that needs to be fetched.\n dynamicRequestTree: FlightRouterState | null\n children: Map<string, NavigationTask> | null\n}\n\n// The task-side counterpart of RootRouteTree; collapses into it once tasks\n// are route trees.\nexport type RootNavigationTask = {\n tree: NavigationTask\n head: NavigationTask\n}\n\nexport function createRootNavigationTask(\n tree: NavigationTask,\n head: NavigationTask\n): RootNavigationTask {\n return { tree, head }\n}\n\nexport const enum FreshnessPolicy {\n Default,\n Hydration,\n HistoryTraversal,\n RefreshAll,\n HMRRefresh,\n Gesture,\n}\n\nconst enum NavigationTaskStatus {\n Pending,\n Fulfilled,\n Rejected,\n}\n\n/**\n * When a NavigationTask finishes, there may or may not be data still missing,\n * necessitating a retry.\n */\nconst enum NavigationTaskExitStatus {\n /**\n * The request was superseded by a newer navigation and aborted. No retry is\n * needed; the newer request owns the tree from here.\n */\n Canceled = -1,\n /**\n * No additional navigation is required.\n */\n Done = 0,\n /**\n * Some data failed to load, presumably due to a route tree mismatch. Perform\n * a soft retry to reload the entire tree (re-fetching the dynamic data).\n */\n SoftRetry = 1,\n /**\n * Some data failed to load in an unrecoverable way, e.g. in an inactive\n * parallel route. Fall back to a hard (MPA-style) retry.\n */\n HardRetry = 2,\n /**\n * The route tree matched, but the request was redirected, so the navigation\n * committed the wrong canonical URL. The route cache is no longer reliable\n * (the redirect implies a server change the prediction couldn't account for),\n * so we re-resolve the route — but the data we already received is correct, so\n * the retry reuses it instead of re-fetching.\n */\n RedirectRetry = 3,\n}\n\nexport type NavigationRequestAccumulation = {\n separateRefreshUrls: Set<string> | null\n /**\n * Set when a navigation creates new leaf segments that should be\n * scrolled to. Stays null when no new segments are created (e.g.\n * during a refresh where the route structure didn't change).\n */\n scrollRef: ScrollRef | null\n}\n\n/**\n * A locked navigation's withheld-data gate, for the Instant Navigation Testing\n * API. Captured — as an immutable promise — when the navigation begins (via\n * `beginLockedNavigation`) or when router work spawns a dynamic write outside\n * a navigation (via `getCurrentNavigationLock`), and threaded to the write,\n * which awaits it before applying dynamic data. Resolves when a newer locked\n * navigation begins or the lock is released. Because the capture happens at\n * spawn time, a newer navigation's rollover releases this write rather than\n * re-gating it. Threaded as `NavigationLock | null`; null whenever the testing\n * API is not active.\n */\nexport type NavigationLock = Promise<void>\n\nconst noop = () => {}\n\nexport function createInitialRenderTreeForHydration(\n navigatedAt: number,\n initialRoot: RootRouteTree<RSCSegmentData | null>,\n seedDynamicStaleAt: number\n): RootNavigationTask {\n // Create the initial cache node tree, using the data embedded into the\n // HTML document.\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n const parentNeedsDynamicRequest = false\n const restrictToShell = false\n // Hydration is bound to the shared map.\n const map = segmentCacheMap\n const tree = createRenderTreeOnNavigation(\n navigatedAt,\n initialRoot.tree,\n FreshnessPolicy.Hydration,\n seedDynamicStaleAt,\n parentNeedsDynamicRequest,\n accumulation,\n map,\n restrictToShell\n )\n const head = createRenderTreeOnNavigation(\n navigatedAt,\n initialRoot.head,\n FreshnessPolicy.Hydration,\n seedDynamicStaleAt,\n parentNeedsDynamicRequest,\n accumulation,\n map,\n restrictToShell\n )\n return createRootNavigationTask(tree, head)\n}\n\n// Creates a new Cache Node tree (i.e. copy-on-write) that represents the\n// optimistic result of a navigation, using both the current Cache Node tree and\n// data that was prefetched prior to navigation.\n//\n// At the moment we call this function, we haven't yet received the navigation\n// response from the server. It could send back something completely different\n// from the tree that was prefetched — due to rewrites, default routes, parallel\n// routes, etc.\n//\n// But in most cases, it will return the same tree that we prefetched, just with\n// the dynamic holes filled in. So we optimistically assume this will happen,\n// and accept that the real result could be arbitrarily different.\n//\n// We'll reuse anything that was already in the previous tree, since that's what\n// the server does.\n//\n// New segments (ones that don't appear in the old tree) are assigned an\n// unresolved promise. The data for these promises will be fulfilled later, when\n// the navigation response is received.\n//\n// The tree can be rendered immediately after it is created (that's why this is\n// a synchronous function). Any new trees that do not have prefetch data will\n// suspend during rendering, until the dynamic data streams in.\n//\n// Returns the tasks for the route tree and the head, each containing both the\n// updated Cache Node and a path to the pending subtrees that need to be\n// resolved by the navigation response.\n//\n// A return value of `null` means a full-page (MPA) navigation is required.\nexport function startPPRNavigation(\n navigatedAt: number,\n oldUrl: URL,\n oldRenderedSearch: string,\n oldRoot: RootRouteTree<CacheNode>,\n newRoot: RootRouteTree<RSCSegmentData | null>,\n freshness: FreshnessPolicy,\n seedDynamicStaleAt: number,\n isSamePageNavigation: boolean,\n accumulation: NavigationRequestAccumulation,\n // The segment cache map this navigation is bound to: a locked navigation's\n // driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n // Instant Navigation Testing API only — restricts segment reads to shell\n // entries. Always false outside the testing API. See navigation-testing-lock.\n restrictToShell: boolean\n): RootNavigationTask | null {\n const parentNeedsDynamicRequest = false\n const parentRefreshState = null\n const oldRootRefreshState: RefreshState = {\n canonicalUrl: createHrefFromUrl(oldUrl),\n renderedSearch: oldRenderedSearch as NormalizedSearch,\n }\n const tree = updateRenderTreeOnNavigation(\n navigatedAt,\n oldRoot.tree,\n newRoot.tree,\n freshness,\n seedDynamicStaleAt,\n isSamePageNavigation,\n parentNeedsDynamicRequest,\n oldRootRefreshState,\n parentRefreshState,\n accumulation,\n map,\n restrictToShell\n )\n if (tree === null) {\n // The route tree changed at or above the root layout. Perform a full-page\n // navigation.\n return null\n }\n const head = updateRenderTreeOnNavigation(\n navigatedAt,\n oldRoot.head,\n newRoot.head,\n freshness,\n seedDynamicStaleAt,\n isSamePageNavigation,\n parentNeedsDynamicRequest,\n oldRootRefreshState,\n parentRefreshState,\n accumulation,\n map,\n restrictToShell\n )\n if (head === null) {\n // Unreachable: a one-node tree has no root layout to change and no slots.\n return null\n }\n return createRootNavigationTask(tree, head)\n}\n\n// TODO: Unify NavigationTask with CacheNode.\nfunction createNavigationTask(\n status: NavigationTaskStatus,\n route: FlightRouterState,\n node: RouteTree<CacheNode>,\n dynamicRequestTree: FlightRouterState | null,\n children: Map<string, NavigationTask> | null\n): NavigationTask {\n return {\n status,\n route,\n node,\n dynamicRequestTree,\n children,\n }\n}\n\nfunction updateRenderTreeOnNavigation(\n navigatedAt: number,\n oldRenderTree: RouteTree<CacheNode>,\n newRouteTree: RouteTree<RSCSegmentData | null>,\n freshness: FreshnessPolicy,\n seedDynamicStaleAt: number,\n isSamePageNavigation: boolean,\n parentNeedsDynamicRequest: boolean,\n oldRootRefreshState: RefreshState,\n parentRefreshState: RefreshState | null,\n accumulation: NavigationRequestAccumulation,\n map: CacheMap<SegmentCacheEntry>,\n // Instant Navigation Testing API only — restricts segment reads to shell\n // entries. Always false outside the testing API. See navigation-testing-lock.\n restrictToShell: boolean\n): NavigationTask | null {\n // Check if the route structure changed. If only the params changed, that's\n // handled further down.\n const newSegment = newRouteTree.segment\n if (!doesRouteStructureMatch(oldRenderTree, newRouteTree)) {\n // This segment does not match the previous route. We're now entering the\n // new part of the target route. Switch to the \"create\" path.\n if (\n // 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 this changed\n // segment is still at or above the root layout (IsRootLayoutOrAbove);\n // once we've descended past the root layout, a segment change can't alter\n // the root layout. We also only need to compare the subtree that is not\n // shared. In the common case, this branch is skipped completely.\n ((newRouteTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0 &&\n isNavigatingToNewRootLayout(oldRenderTree, newRouteTree)) ||\n // 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 ) {\n return null\n }\n return createRenderTreeOnNavigation(\n navigatedAt,\n newRouteTree,\n freshness,\n seedDynamicStaleAt,\n parentNeedsDynamicRequest,\n accumulation,\n map,\n restrictToShell\n )\n }\n\n const newSlots = newRouteTree.slots\n\n let shouldRefreshDynamicData: boolean = false\n switch (freshness) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Hydration:\n case FreshnessPolicy.Gesture:\n shouldRefreshDynamicData = false\n break\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n shouldRefreshDynamicData = true\n break\n default:\n freshness satisfies never\n break\n }\n\n const isLeafSegment = newSlots === null\n\n // Get the data for this segment. Since it was part of the previous route,\n // usually we just reuse the data from the old render tree. If the params\n // changed, or during a refresh or revalidation, consult the prefetch cache\n // or response seed instead.\n let newRenderTree: RouteTree<CacheNode>\n let needsDynamicRequest: boolean\n const paramsChange = compareParams(\n oldRenderTree.varyPath,\n newRouteTree.varyPath\n )\n if (paramsChange !== ParamsChange.None) {\n // Path params are part of LayoutRouter's React key, so changing one\n // remounts this segment and everything below it. Generate a new bfcacheId\n // to match. Search params aren't part of the key, so a page whose search\n // params changed keeps its existing id.\n let bfcacheId: number\n if (paramsChange === ParamsChange.PathParam) {\n bfcacheId = generateBFCacheId(freshness)\n } else {\n bfcacheId = oldRenderTree.data.bfcacheId\n }\n switch (freshness) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.Gesture: {\n // If the existing data didn't read any of the params that changed, we\n // can keep using it. Refreshes always fetch new data, and back/forward\n // navigations restore the entry from the BFCache instead.\n const oldCacheNode = oldRenderTree.data\n if (\n !didReadChangedParam(\n oldRenderTree.varyPath,\n newRouteTree.varyPath,\n oldCacheNode.varyParams\n )\n ) {\n const cacheNode = createCacheNode(\n oldCacheNode.rsc,\n oldCacheNode.prefetchRsc,\n oldCacheNode.varyParams,\n bfcacheId\n )\n if (freshness !== FreshnessPolicy.Gesture) {\n writeToBFCache(\n navigatedAt,\n newRouteTree.varyPath,\n cacheNode,\n seedDynamicStaleAt\n )\n }\n newRenderTree = createRenderTree(newRouteTree, cacheNode)\n needsDynamicRequest = false\n break\n }\n // Intentional fallthrough\n }\n case FreshnessPolicy.Hydration:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh: {\n const result = createRenderTreeForSegment(\n navigatedAt,\n newRouteTree,\n freshness,\n seedDynamicStaleAt,\n bfcacheId,\n map,\n restrictToShell\n )\n newRenderTree = result.node\n needsDynamicRequest = result.needsDynamicRequest\n break\n }\n }\n\n // A param change mostly acts the same as a refresh, except it does\n // trigger a scroll.\n if (isLeafSegment) {\n accumulateScrollRef(freshness, newRenderTree.data, accumulation)\n }\n } else if (\n shouldRefreshDynamicData ||\n // During a same-page navigation, we always refetch the page segments\n (isLeafSegment && isSamePageNavigation)\n ) {\n // This is a refresh of an existing segment. Ignore the existing render\n // tree and create a new one.\n const result = createRenderTreeForSegment(\n navigatedAt,\n newRouteTree,\n freshness,\n seedDynamicStaleAt,\n // Refreshing data preserves the identity of the active segment.\n oldRenderTree.data.bfcacheId,\n map,\n restrictToShell\n )\n newRenderTree = result.node\n needsDynamicRequest = result.needsDynamicRequest\n\n // Carry forward the old node's scrollRef. This preserves scroll intent\n // when a prior navigation's render tree is replaced by a refresh before\n // the scroll handler has had a chance to fire — e.g. when router.push()\n // and router.refresh() are called in the same startTransition batch.\n newRenderTree.data.scrollRef = oldRenderTree.data.scrollRef\n } else {\n // This segment appears in both the old and new routes. Reuse the existing\n // data without triggering a request.\n // TODO: Consider adding a fast path where if this segment is unchanged and\n // all of its children are unchanged, we return the exact same RenderTree\n // object. Reusing the exact previous object gives React more of a chance to\n // bail out of rendering.\n newRenderTree = createRenderTree(newRouteTree, oldRenderTree.data)\n needsDynamicRequest = false\n }\n\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 =\n maybeRefreshState !== undefined && maybeRefreshState !== null\n ? // This segment is not present in the current route. Track its\n // refresh URL as we continue traversing the tree.\n maybeRefreshState\n : // Inherit the refresh URL from the parent.\n parentRefreshState\n newRenderTree.refreshState = refreshState\n\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\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 [parallelRouteKey: string]: FlightRouterState\n } = {}\n let taskChildren = null\n\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 [parallelRouteKey: string]: FlightRouterState\n } = {}\n\n if (newSlots !== null) {\n const oldRenderTreeSlots = oldRenderTree.slots\n\n const newRenderTreeSlots = new Map<string, RouteTree<CacheNode>>()\n newRenderTree.slots = newRenderTreeSlots\n taskChildren = new Map()\n for (let [parallelRouteKey, newRouteTreeChild] of newSlots) {\n const oldRenderTreeChild = oldRenderTreeSlots?.get(parallelRouteKey)\n if (oldRenderTreeChild === undefined) {\n // This should never happen, but if it does, it suggests a malformed\n // server response. Trigger a full-page navigation.\n return null\n }\n\n const oldSegmentChild = oldRenderTreeChild.segment\n const newSegmentChild = newRouteTreeChild.segment\n if (\n // Skip this branch during a history traversal. We restore the tree that\n // was stashed in the history entry as-is.\n freshness !== FreshnessPolicy.HistoryTraversal &&\n newSegmentChild === DEFAULT_SEGMENT_KEY &&\n oldSegmentChild !== DEFAULT_SEGMENT_KEY &&\n // The active segment was rendered with this layout's params. If a\n // path param changed, we can't keep it. Use the default segment from\n // the server instead.\n paramsChange !== ParamsChange.PathParam\n ) {\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(\n oldRootRefreshState,\n oldRenderTreeChild\n )\n }\n\n const taskChild = updateRenderTreeOnNavigation(\n navigatedAt,\n oldRenderTreeChild,\n newRouteTreeChild,\n freshness,\n seedDynamicStaleAt,\n isSamePageNavigation,\n parentNeedsDynamicRequest || needsDynamicRequest,\n oldRootRefreshState,\n refreshState,\n accumulation,\n map,\n restrictToShell\n )\n\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\n // Recursively propagate up the child tasks.\n taskChildren.set(parallelRouteKey, taskChild)\n newRenderTreeSlots.set(parallelRouteKey, taskChild.node)\n\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\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\n const newFlightRouterState = createRouterStateForSegment(\n newRouteTree,\n patchedRouterStateChildren,\n refreshState\n )\n\n return createNavigationTask(\n needsDynamicRequest\n ? NavigationTaskStatus.Pending\n : NavigationTaskStatus.Fulfilled,\n newFlightRouterState,\n newRenderTree,\n createDynamicRequestTree(\n newFlightRouterState,\n dynamicRequestTreeChildren,\n needsDynamicRequest,\n childNeedsDynamicRequest,\n parentNeedsDynamicRequest\n ),\n taskChildren\n )\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 * Called for newly entered segments, and for segments whose params changed\n * (even if their data was reused). Refreshes keep the existing scroll ref.\n *\n * Skipped during hydration (initial render should not scroll) and\n * history traversal (scroll restoration is handled separately).\n *\n * The head passes through here as a leaf too; its `scrollRef` is never read\n * (only LayoutRouter reads one), and the page leaf sets the same shared ref.\n */\nfunction accumulateScrollRef(\n freshness: FreshnessPolicy,\n cacheNode: CacheNode,\n accumulation: NavigationRequestAccumulation\n): void {\n switch (freshness) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.Gesture:\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n if (accumulation.scrollRef === null) {\n accumulation.scrollRef = { current: true }\n }\n cacheNode.scrollRef = accumulation.scrollRef\n break\n case FreshnessPolicy.Hydration:\n // Initial render — no scroll.\n break\n case FreshnessPolicy.HistoryTraversal:\n // Back/forward — scroll restoration is handled separately.\n break\n default:\n freshness satisfies never\n break\n }\n}\n\nfunction createRenderTreeOnNavigation(\n navigatedAt: number,\n newRouteTree: RouteTree<RSCSegmentData | null>,\n freshness: FreshnessPolicy,\n seedDynamicStaleAt: number,\n parentNeedsDynamicRequest: boolean,\n accumulation: NavigationRequestAccumulation,\n map: CacheMap<SegmentCacheEntry>,\n // Instant Navigation Testing API only — restricts segment reads to shell\n // entries. Always false outside the testing API. See navigation-testing-lock.\n restrictToShell: boolean\n): NavigationTask {\n // Same traversal as updateRenderTreeOnNavigation, but simpler. We switch to this\n // path once we reach the part of the tree that was not in the previous route.\n // We don't need to diff against the old tree, we just need to create a new\n // one. We also don't need to worry about any refresh-related logic.\n //\n // For the most part, this is a subset of updateRenderTreeOnNavigation, so any\n // change that happens in this function likely needs to be applied to that\n // one, too. However there are some places where the behavior intentionally\n // diverges, which is why we keep them separate.\n\n const newSlots = newRouteTree.slots\n\n const result = createRenderTreeForSegment(\n navigatedAt,\n newRouteTree,\n freshness,\n seedDynamicStaleAt,\n // This segment was not part of the previous route, so mint a fresh\n // bfcacheId.\n generateBFCacheId(freshness),\n map,\n restrictToShell\n )\n const newRenderTree = result.node\n const needsDynamicRequest = result.needsDynamicRequest\n\n const isLeafSegment = newSlots === null\n if (isLeafSegment) {\n accumulateScrollRef(freshness, newRenderTree.data, accumulation)\n }\n\n let patchedRouterStateChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n let taskChildren = null\n\n let childNeedsDynamicRequest = false\n let dynamicRequestTreeChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n\n if (newSlots !== null) {\n const newRenderTreeSlots = new Map<string, RouteTree<CacheNode>>()\n newRenderTree.slots = newRenderTreeSlots\n taskChildren = new Map()\n for (const [parallelRouteKey, newRouteTreeChild] of newSlots) {\n const taskChild = createRenderTreeOnNavigation(\n navigatedAt,\n newRouteTreeChild,\n freshness,\n seedDynamicStaleAt,\n parentNeedsDynamicRequest || needsDynamicRequest,\n accumulation,\n map,\n restrictToShell\n )\n\n taskChildren.set(parallelRouteKey, taskChild)\n newRenderTreeSlots.set(parallelRouteKey, taskChild.node)\n\n const taskChildRoute = taskChild.route\n patchedRouterStateChildren[parallelRouteKey] = taskChildRoute\n\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\n // This route is not part of the current tree, so there's no reason to\n // track the refresh URL.\n const refreshState = null\n const newFlightRouterState = createRouterStateForSegment(\n newRouteTree,\n patchedRouterStateChildren,\n refreshState\n )\n\n return createNavigationTask(\n needsDynamicRequest\n ? NavigationTaskStatus.Pending\n : NavigationTaskStatus.Fulfilled,\n newFlightRouterState,\n newRenderTree,\n createDynamicRequestTree(\n newFlightRouterState,\n dynamicRequestTreeChildren,\n needsDynamicRequest,\n childNeedsDynamicRequest,\n parentNeedsDynamicRequest\n ),\n taskChildren\n )\n}\n\n// Converts a route tree node into the router state the client sends back to\n// the server. Page nodes carry their rendered search in its own slot.\nfunction createRouterStateForSegment(\n routeTree: RouteTree<RSCSegmentData | null>,\n children: { [parallelRouteKey: string]: FlightRouterState },\n refreshState: RefreshState | null\n): FlightRouterState {\n const routerState: FlightRouterState = [\n routeTree.segment,\n children,\n refreshState !== null\n ? [refreshState.canonicalUrl, refreshState.renderedSearch]\n : null,\n null,\n routeTree.prefetchHints,\n ]\n if (routeTree.segment === PAGE_SEGMENT_KEY) {\n const renderedSearch = getRenderedSearchFromVaryPath(routeTree.varyPath)\n if (renderedSearch !== null) {\n routerState[5] = renderedSearch\n }\n }\n return routerState\n}\n\nfunction patchRouterStateWithNewChildren(\n baseRouterState: FlightRouterState,\n newChildren: { [parallelRouteKey: string]: FlightRouterState }\n): FlightRouterState {\n const clone: FlightRouterState = [baseRouterState[0], newChildren]\n // Based on equivalent logic in apply-router-state-patch-to-tree, but should\n // confirm whether we need to copy all of these fields. Not sure the server\n // ever sends, e.g. the refetch marker.\n if (2 in baseRouterState) {\n clone[2] = baseRouterState[2]\n }\n if (3 in baseRouterState) {\n clone[3] = baseRouterState[3]\n }\n if (4 in baseRouterState) {\n clone[4] = baseRouterState[4]\n }\n if (5 in baseRouterState) {\n clone[5] = baseRouterState[5]\n }\n return clone\n}\n\nfunction createDynamicRequestTree(\n newRouterState: FlightRouterState,\n dynamicRequestTreeChildren: Record<string, FlightRouterState>,\n needsDynamicRequest: boolean,\n childNeedsDynamicRequest: boolean,\n parentNeedsDynamicRequest: boolean\n): FlightRouterState | null {\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: FlightRouterState | null = null\n if (needsDynamicRequest) {\n dynamicRequestTree = patchRouterStateWithNewChildren(\n newRouterState,\n dynamicRequestTreeChildren\n )\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(\n newRouterState,\n dynamicRequestTreeChildren\n )\n } else {\n dynamicRequestTree = null\n }\n return dynamicRequestTree\n}\n\nfunction accumulateRefreshUrl(\n accumulation: NavigationRequestAccumulation,\n refreshState: RefreshState\n) {\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([refreshUrl])\n } else {\n separateRefreshUrls.add(refreshUrl)\n }\n}\n\nfunction reuseActiveSegmentInDefaultSlot(\n oldRootRefreshState: RefreshState,\n oldRenderTree: RouteTree<CacheNode>\n): RouteTree<RSCSegmentData | null> {\n // This is a \"default\" segment. These are never sent by the server during a\n // soft navigation; instead, the client reuses whatever segment was already\n // active in that slot on the previous route. This means if we later need to\n // refresh the segment, it will have to be refetched from the previous route's\n // URL. We store the refresh context on the active render tree.\n\n let reusedUrl: string\n let reusedRenderedSearch: NormalizedSearch\n const oldRefreshState = oldRenderTree.refreshState\n if (oldRefreshState !== null) {\n // This segment was already reused from an even older route. Keep its\n // existing URL and refresh state.\n reusedUrl = oldRefreshState.canonicalUrl\n reusedRenderedSearch = oldRefreshState.renderedSearch\n } else {\n // Since this route didn't already have a refresh state, it must have been\n // reachable from the root of the old route. So we use the refresh state\n // that represents the old route.\n reusedUrl = oldRootRefreshState.canonicalUrl\n reusedRenderedSearch = oldRootRefreshState.renderedSearch\n }\n\n const reusedRouteTree = rebaseInactiveRouteTree(oldRenderTree)\n reusedRouteTree.refreshState = {\n canonicalUrl: reusedUrl,\n renderedSearch: reusedRenderedSearch,\n }\n return reusedRouteTree\n}\n\nfunction createRenderTree(\n routeTree: RouteTree<RSCSegmentData | null>,\n cacheNode: CacheNode\n): RouteTree<CacheNode> {\n return {\n requestKey: routeTree.requestKey,\n segment: routeTree.segment,\n shellVaryPath: routeTree.shellVaryPath,\n refreshState: null,\n data: cacheNode,\n varyPath: routeTree.varyPath,\n slots: null,\n prefetchHints: routeTree.prefetchHints,\n }\n}\n\nfunction createRenderTreeForSegment(\n now: number,\n // A route tree node, or the one-node metadata tree that stands in for the\n // head (see createMetadataRouteTree).\n tree: RouteTree<RSCSegmentData | null>,\n freshness: FreshnessPolicy,\n dynamicStaleAt: number,\n bfcacheId: number,\n map: CacheMap<SegmentCacheEntry>,\n // Instant Navigation Testing API only — restricts segment reads to shell\n // entries. Always false outside the testing API. See navigation-testing-lock.\n restrictToShell: boolean\n): { node: RouteTree<CacheNode>; needsDynamicRequest: boolean } {\n // Construct an owned render tree using data from the BFCache, the client's\n // Segment Cache, or seeded from a server response.\n //\n // If there's a cache miss, or if we only have a partial hit, we'll render\n // the partial state immediately, and spawn a request to the server to fill\n // in the missing data.\n //\n // If the segment is fully cached on the client already, we can omit this\n // segment from the server request.\n //\n // If we already have a dynamic data response associated with this navigation,\n // as in the case of a Server Action-initiated redirect or refresh, we may\n // also be able to use that data without spawning a new request. (This is\n // referred to as the \"seed\" data.)\n\n const seedData = tree.data\n const seedRsc = seedData !== null ? seedData.rsc : null\n const seedVaryParams = seedData !== null ? seedData.varyParams : null\n\n // During certain kinds of navigations, we may be able to render from\n // the BFCache.\n switch (freshness) {\n case FreshnessPolicy.Default: {\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(\n now,\n tree.varyPath\n )\n if (bfcacheEntry !== null) {\n // A regular navigation that happens to read cached data is still a\n // fresh navigation, so we use the caller-supplied bfcacheId — the\n // BFCacheEntry's id is only restored on history-traversal\n // navigations.\n return {\n node: createRenderTree(\n tree,\n createCacheNode(\n bfcacheEntry.rsc,\n bfcacheEntry.prefetchRsc,\n bfcacheEntry.varyParams,\n bfcacheId\n )\n ),\n needsDynamicRequest: false,\n }\n }\n break\n }\n case FreshnessPolicy.Hydration: {\n // This is not related to the BFCache but it is a special case.\n //\n // We should never spawn network requests during hydration. We must treat\n // the initial payload as authoritative, because the initial page load is\n // used as a last-ditch mechanism for recovering the app.\n //\n // This is also an important safety check because if this leaks into the\n // server rendering path (which theoretically it never should because the\n // server payload should be consistent), the server would hang because these\n // promises would never resolve.\n //\n // TODO: There is an existing case where the global \"not found\" boundary\n // triggers this path. But it does render correctly despite that. That's an\n // unusual render path so it's not surprising, but we should look into\n // modeling it in a more consistent way. See also the /_notFound special\n // case in updateRenderTreeOnNavigation.\n const cacheNode = createCacheNode(\n seedRsc,\n null,\n seedVaryParams,\n bfcacheId\n )\n writeToBFCache(now, tree.varyPath, cacheNode, dynamicStaleAt)\n return {\n node: createRenderTree(tree, cacheNode),\n needsDynamicRequest: false,\n }\n }\n case FreshnessPolicy.HistoryTraversal:\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 =\n !isDeferredRsc(oldRsc) || oldRsc.status !== 'pending'\n const dropPrefetchRsc = oldRscDidResolve\n // Restore the bfcacheId from the cached entry so that back/forward\n // navigations preserve the original id, regardless of whether\n // `cacheComponents` Activity preservation is enabled.\n return {\n node: createRenderTree(\n tree,\n createCacheNode(\n bfcacheEntry.rsc,\n dropPrefetchRsc ? null : bfcacheEntry.prefetchRsc,\n bfcacheEntry.varyParams,\n bfcacheEntry.bfcacheId\n )\n ),\n needsDynamicRequest: false,\n }\n }\n break\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n case FreshnessPolicy.Gesture:\n // Don't consult the BFCache.\n break\n default:\n freshness satisfies never\n break\n }\n\n let cachedRsc: React.ReactNode | null = null\n let isCachedRscPartial: boolean = true\n let cachedVaryParams: VaryParams | null = null\n\n const segmentEntry = readSegmentCacheEntryForNavigation(\n now,\n map,\n tree.varyPath,\n restrictToShell\n )\n if (segmentEntry !== null) {\n switch (segmentEntry.status) {\n case EntryStatus.Fulfilled: {\n // Happy path: a cache hit\n cachedRsc = segmentEntry.rsc\n isCachedRscPartial = segmentEntry.isPartial\n cachedVaryParams = segmentEntry.varyParams\n break\n }\n case EntryStatus.Pending: {\n // 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) =>\n entry !== null ? entry.rsc : null\n )\n // The entry's data hasn't arrived, and neither has the source of the\n // params it depends on; `cachedVaryParams` stays null.\n // Because the request is still pending, we typically don't know yet\n // whether the response will be partial. We shouldn't skip this segment\n // during the dynamic navigation request. Otherwise, we might need to\n // do yet another request to fill in the remaining data, creating\n // a waterfall.\n //\n // The one exception is if this segment is being fetched with via\n // prefetch={true} (i.e. the \"force stale\" or \"full\" strategy). If so,\n // we can assume the response will be full. This field is set to `false`\n // for such segments.\n isCachedRscPartial = segmentEntry.isPartial\n break\n }\n case EntryStatus.Empty:\n case EntryStatus.Rejected: {\n break\n }\n default: {\n segmentEntry satisfies never\n break\n }\n }\n }\n\n if (\n process.env.__NEXT_OPTIMISTIC_ROUTING &&\n tree.segment === HEAD_REQUEST_KEY &&\n isCachedRscPartial\n ) {\n // TODO: When optimistic routing is enabled, don't block on waiting for\n // the viewport to resolve. This is a temporary workaround until Vary\n // Params are tracked when rendering the metadata. We'll fix it before\n // this feature is stable. However, it's not a critical issue because 1)\n // it will stream in eventually anyway 2) metadata is wrapped in an\n // internal Suspense boundary, so is always non-blocking; this only\n // affects the viewport node, which is meant to blocking, however... 3)\n // before Segment Cache landed this wasn't always the case, anyway, so\n // it's unlikely that many people are relying on this behavior. Still,\n // will be fixed before stable. It's the very next step in the sequence of\n // work on this project.\n //\n // This line of code works because the App Router treats `null` as\n // \"no renderable head available\", rather than an empty head. React treats\n // an empty string as empty.\n cachedRsc = ''\n }\n\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\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: React.ReactNode | null\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: React.ReactNode | null\n // The source of the params `rsc` depends on. A server response or a\n // fulfilled segment cache entry carries one; a deferred `rsc` gets its\n // source when the response arrives (finishPendingCacheNode).\n let varyParams: VaryParams | null\n let doesSegmentNeedDynamicRequest: boolean\n\n if (seedRsc !== null) {\n // We already have a dynamic server response for this segment.\n if (isCachedRscPartial) {\n // The seed data may still be streaming in, so it's worth showing the\n // partial cached state in the meantime.\n prefetchRsc = cachedRsc\n rsc = seedRsc\n varyParams = seedVaryParams\n } else {\n // We already have a completely cached segment. Ignore the seed data,\n // which may still be streaming in. This shouldn't happen in the normal\n // case because the client will inform the server which segments are\n // already fully cached, and the server will skip rendering them.\n prefetchRsc = null\n rsc = cachedRsc\n varyParams = cachedVaryParams\n }\n doesSegmentNeedDynamicRequest = false\n } else {\n if (isCachedRscPartial) {\n // The cached data contains dynamic holes, or it's missing entirely. We'll\n // show the partial state immediately (if available), and stream in the\n // final data.\n //\n // Create a pending promise that we can later write to when the\n // data arrives from the server.\n prefetchRsc = cachedRsc\n rsc = createDeferredRsc()\n varyParams = null\n } else {\n // The data is fully cached.\n prefetchRsc = null\n rsc = cachedRsc\n varyParams = cachedVaryParams\n }\n doesSegmentNeedDynamicRequest = isCachedRscPartial\n }\n\n // Now that we're creating a new segment, write its data to the BFCache. A\n // subsequent back/forward navigation will reuse this same data, until or\n // unless it's cleared by a refresh/revalidation.\n //\n // Skip BFCache writes for optimistic navigations since they are transient\n // and will be replaced by the canonical navigation.\n const cacheNode = createCacheNode(rsc, prefetchRsc, varyParams, bfcacheId)\n if (freshness !== FreshnessPolicy.Gesture) {\n writeToBFCache(now, tree.varyPath, cacheNode, dynamicStaleAt)\n }\n\n return {\n node: createRenderTree(tree, cacheNode),\n // TODO: We should store this field on the CacheNode itself. I think we can\n // probably unify NavigationTask, CacheNode, and DeferredRsc into a\n // single type. Or at least CacheNode and DeferredRsc.\n needsDynamicRequest: doesSegmentNeedDynamicRequest,\n }\n}\n\nfunction createCacheNode(\n rsc: React.ReactNode | null,\n prefetchRsc: React.ReactNode | null,\n varyParams: VaryParams | null,\n bfcacheId: number,\n scrollRef: ScrollRef | null = null\n): CacheNode {\n return {\n rsc,\n prefetchRsc,\n varyParams,\n scrollRef,\n bfcacheId,\n }\n}\n\n// Globally-unique counter for fresh bfcacheIds. Incremented every time a new\n// CacheNode is created on the client. The id surfaces to user code as a\n// string via `useRouter().bfcacheId`.\nlet nextBFCacheId = 0\n\nfunction generateBFCacheId(freshness: FreshnessPolicy): number {\n // Server-side rendering and the initial client-side hydration tree both\n // use a fixed sentinel so they reconcile cleanly across hydration. The\n // counter only advances on real client-side navigations after hydration.\n if (typeof window === 'undefined') return 0\n if (freshness === FreshnessPolicy.Hydration) return 0\n return ++nextBFCacheId\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\n// Writes a dynamic server response into the tree created by\n// updateRenderTreeOnNavigation. All pending promises that were spawned by the\n// navigation will be resolved, either with dynamic data from the server, or\n// `null` to indicate that the data is missing.\n//\n// A `null` value will trigger a lazy fetch during render, which will then patch\n// up the tree using the same mechanism as the non-PPR implementation\n// (serverPatchReducer).\n//\n// Usually, the server will respond with exactly the subset of data that we're\n// waiting for — everything below the nearest shared layout. But technically,\n// the server can return anything it wants.\n//\n// This does _not_ create a new tree; it modifies the existing one in place.\n// Which means it must follow the Suspense rules of cache safety.\nexport function spawnDynamicRequests(\n navigation: RootNavigationTask,\n primaryUrl: URL,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n accumulation: NavigationRequestAccumulation,\n // 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).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n // 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.\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n // The segment cache map this navigation is bound to. See `segmentCacheMap`\n // in cache.ts.\n map: CacheMap<SegmentCacheEntry>,\n signal: AbortSignal | undefined\n): void {\n let dynamicRequestTree = navigation.tree.dynamicRequestTree\n if (dynamicRequestTree === null) {\n if (navigation.head.status === NavigationTaskStatus.Pending) {\n // Every segment is cached, but the head is not. Ask the server for the\n // head alone.\n dynamicRequestTree = MetadataOnlyRequestTree\n } else {\n // This navigation was fully cached. There are no dynamic requests to spawn.\n previousNavigationDidMismatch = false\n return\n }\n }\n\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(\n navigation.tree,\n navigation.head,\n dynamicRequestTree,\n primaryUrl,\n nextUrl,\n freshnessPolicy,\n routeCacheEntry,\n navigationLock,\n map,\n signal\n )\n\n const separateRefreshUrls = accumulation.separateRefreshUrls\n let refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null = 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\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\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 // We already initiated a request for the this URL, above. Skip it.\n // TODO: This only happens because the main URL is not tracked as\n // part of the separateRefreshURLs set. There's probably a better way\n // to structure this so this case doesn't happen.\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(\n fetchMissingDynamicData(\n navigation.tree,\n // The head belongs to the primary URL.\n null,\n scopedDynamicRequestTree,\n new URL(refreshUrl, location.origin),\n // 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,\n freshnessPolicy,\n routeCacheEntry,\n navigationLock,\n map,\n signal\n )\n )\n }\n }\n }\n\n // Further async operations are moved into this separate function to\n // discourage sequential network requests.\n const voidPromise = finishNavigationTask(\n navigation,\n nextUrl,\n primaryRequestPromise,\n refreshRequestPromises,\n routeCacheEntry,\n navigateType\n )\n // `finishNavigationTask` is responsible for error handling, so we can attach\n // noop callbacks to this promise.\n voidPromise.then(noop, noop)\n}\n\nasync function finishNavigationTask(\n navigation: RootNavigationTask,\n nextUrl: string | null,\n primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null,\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n navigateType: 'push' | 'replace'\n): Promise<void> {\n // Wait for all the requests to finish, or for the first one to fail.\n let exitStatus = await waitForRequestsToFinish(\n primaryRequestPromise,\n refreshRequestPromises\n )\n\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 === NavigationTaskExitStatus.Done) {\n exitStatus = abortRemainingPendingTasks(navigation.tree, null, null)\n // A response without a head is a mismatch, like any missing segment. The\n // head's deferred rsc must be resolved to `null` here, never rejected: it\n // renders at the app root, so a rejection would hit the root error\n // boundary while the retry is in flight.\n const headExitStatus = abortRemainingPendingTasks(\n navigation.head,\n null,\n null\n )\n if (headExitStatus > exitStatus) {\n exitStatus = headExitStatus\n }\n }\n\n switch (exitStatus) {\n case NavigationTaskExitStatus.Canceled: {\n // This navigation was superseded and its request aborted. Its cache nodes\n // may already be reused by the newer navigation, so leave them untouched\n // for the newer request to fulfill. If the tree was abandoned entirely,\n // it can be garbage collected along with its unresolved promises. We do\n // not retry or hard-navigate.\n return\n }\n case NavigationTaskExitStatus.Done: {\n // The task has completely finished. There's no missing data. Exit.\n previousNavigationDidMismatch = false\n return\n }\n case NavigationTaskExitStatus.SoftRetry: {\n // Some data failed to finish loading. Trigger a soft retry that re-fetches\n // the tree's dynamic data.\n // TODO: As an extra precaution against soft retry loops, consider\n // tracking whether a navigation was itself triggered by a retry. If two\n // happen in a row, fall back to a hard retry.\n const isHardRetry = false\n const primaryRequestResult = await primaryRequestPromise\n dispatchRetryDueToTreeMismatch(\n isHardRetry,\n primaryRequestResult.url,\n nextUrl,\n primaryRequestResult.seed,\n navigation,\n routeCacheEntry,\n navigateType,\n FreshnessPolicy.RefreshAll\n )\n return\n }\n case NavigationTaskExitStatus.RedirectRetry: {\n // The route matched, but the request was redirected, so we committed the\n // wrong canonical URL. Re-resolve the route to invalidate the now-stale\n // route cache and correct the URL — but reuse the data we already received\n // (HistoryTraversal) instead of re-fetching it. See issue #95195.\n const isHardRetry = false\n const primaryRequestResult = await primaryRequestPromise\n dispatchRetryDueToTreeMismatch(\n isHardRetry,\n primaryRequestResult.url,\n nextUrl,\n primaryRequestResult.seed,\n navigation,\n routeCacheEntry,\n navigateType,\n FreshnessPolicy.HistoryTraversal\n )\n return\n }\n case NavigationTaskExitStatus.HardRetry: {\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(\n isHardRetry,\n primaryRequestResult.url,\n nextUrl,\n primaryRequestResult.seed,\n navigation,\n routeCacheEntry,\n navigateType,\n FreshnessPolicy.RefreshAll\n )\n return\n }\n default: {\n return exitStatus satisfies never\n }\n }\n}\n\nfunction waitForRequestsToFinish(\n primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null\n) {\n // Custom async combinator logic. This could be replaced by Promise.any but\n // we don't assume that's available.\n //\n // Each promise resolves once the server responsds and the data is written\n // into the render tree. Resolve the combined promise once all the\n // requests finish.\n //\n // Or, resolve as soon as one of the requests fails, without waiting for the\n // others to finish.\n return new Promise<NavigationTaskExitStatus>((resolve) => {\n const onFulfill = (result: { exitStatus: NavigationTaskExitStatus }) => {\n if (result.exitStatus === NavigationTaskExitStatus.Done) {\n remainingCount--\n if (remainingCount === 0) {\n // All the requests finished successfully.\n resolve(NavigationTaskExitStatus.Done)\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(NavigationTaskExitStatus.HardRetry)\n\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) =>\n refreshRequestPromise.then(onFulfill, onReject)\n )\n }\n })\n}\n\nfunction dispatchRetryDueToTreeMismatch(\n isHardRetry: boolean,\n retryUrl: URL,\n retryNextUrl: string | null,\n seed: NavigationSeed | null,\n navigation: RootNavigationTask,\n // 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.\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n // The original navigation's push/replace intent.\n originalNavigateType: 'push' | 'replace',\n // Freshness policy for the retry navigation. `RefreshAll` re-fetches the\n // tree's dynamic data (used for genuine tree mismatches). `HistoryTraversal`\n // reuses the data already in the tree (used when only the URL needs\n // correcting after a redirect).\n retryFreshnessPolicy:\n | FreshnessPolicy.RefreshAll\n | FreshnessPolicy.HistoryTraversal\n) {\n // If the navigation used a route prediction, mark the node it was predicted\n // from as having a dynamic rewrite since it resulted in a mismatch. A route\n // entry the server resolved has nothing to mark: nothing was predicted\n // from it.\n if (routeCacheEntry !== null) {\n const predictedFrom = routeCacheEntry.predictedFrom\n if (predictedFrom !== null) {\n predictedFrom.hasDynamicRewrite = true\n }\n } else if (seed !== null) {\n // Even without a direct reference to the route cache entry, we can still\n // mark the route as having a dynamic rewrite by traversing the known route\n // tree. This handles cases where the navigation didn't originate from a\n // route prediction, but still needs to mark the pattern.\n const now = Date.now()\n discoverKnownRoute(\n now,\n retryUrl.pathname,\n retryUrl.search as NormalizedSearch,\n retryNextUrl,\n null,\n seed.root,\n false, // couldBeIntercepted - doesn't matter, we're just marking hasDynamicRewrite\n createHrefFromUrl(retryUrl),\n seed.renderedSearch,\n false, // supportsPerSegmentPrefetching - doesn't matter, we're just marking hasDynamicRewrite\n true // hasDynamicRewrite\n )\n }\n\n // Invalidate all route cache entries. If the navigation used a route entry\n // the server resolved, its tree is what the server just contradicted, so\n // the retry must re-fetch it rather than navigate with it again. This also\n // triggers re-prefetching of visible links.\n invalidateRouteCacheEntries(retryNextUrl, {\n tree: navigation.tree.node,\n head: navigation.head.node,\n })\n\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\n // If the original navigation hasn't committed to the browser history yet\n // (the transition suspended before React committed), inherit its push/replace\n // intent. Otherwise, the pushState already ran, so use 'replace' to avoid\n // creating a duplicate history entry.\n //\n // This works because React entangles the retry's state update with the\n // original pending transition — they commit together as a single batch,\n // so the navigate type from the retry is what HistoryUpdater ultimately sees.\n //\n // TODO: Ideally this check would happen right before we schedule the React\n // update (i.e., closer to where the action is dispatched into the queue),\n // not here where the action is constructed. But the current action queue\n // doesn't provide a natural place for that. Revisit when we refactor the\n // action queue into a more reactive navigation model.\n const baseTree = navigation.tree.route\n const lastCommitted = getLastCommittedTree()\n const retryNavigateType: 'push' | 'replace' =\n lastCommitted !== null && baseTree !== lastCommitted\n ? originalNavigateType\n : 'replace'\n\n const retryAction: ServerPatchAction = {\n type: ACTION_SERVER_PATCH,\n previousTree: baseTree,\n url: retryUrl,\n nextUrl: retryNextUrl,\n seed,\n mpa: isHardRetry,\n navigateType: retryNavigateType,\n freshnessPolicy: retryFreshnessPolicy,\n }\n dispatchAppRouterAction(retryAction)\n}\n\nasync function fetchMissingDynamicData(\n tree: NavigationTask,\n head: NavigationTask | null,\n dynamicRequestTree: FlightRouterState,\n url: URL,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n navigationLock: NavigationLock | null,\n map: CacheMap<SegmentCacheEntry>,\n signal: AbortSignal | undefined\n): Promise<{\n exitStatus: NavigationTaskExitStatus\n url: URL\n seed: NavigationSeed | null\n}> {\n try {\n const result = await fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n isHmrRefresh: freshnessPolicy === FreshnessPolicy.HMRRefresh,\n signal,\n })\n if (typeof result === 'string') {\n // fetchServerResponse will return an href to indicate that the SPA\n // navigation failed. For example, if the server triggered a hard\n // redirect, or the fetch request errored. Initiate an MPA navigation\n // to the given href.\n return {\n exitStatus: NavigationTaskExitStatus.HardRetry,\n url: new URL(result, location.origin),\n seed: null,\n }\n }\n const now = Date.now()\n\n const seed = createNavigationSeed(\n now,\n tree.route,\n result.transportData,\n // Navigation responses stream in incrementally, so their vary params\n // can't be drained here; they decode as null.\n null,\n result.isResponsePartial,\n // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null,\n result.renderedSearch,\n null,\n result.dynamicStaleTime\n )\n\n // If the navigation lock is active, wait for it to be released before\n // writing the dynamic data. This allows tests to assert on the prefetched\n // UI state.\n if (process.env.__NEXT_EXPOSE_TESTING_API && navigationLock !== null) {\n await navigationLock\n }\n\n if (routeCacheEntry !== null && result.staticStageResponse !== null) {\n spawnStaticStageCacheWrite(\n now,\n result.staticStageResponse,\n result.isResponsePartial,\n result.responseHeaders,\n dynamicRequestTree,\n result.renderedSearch,\n map\n )\n }\n\n if (routeCacheEntry !== null && result.runtimePrefetchStream !== null) {\n writeRuntimePrefetchStreamIntoCache(\n now,\n result.runtimePrefetchStream,\n dynamicRequestTree,\n result.renderedSearch,\n map\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 // 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\n const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(\n tree,\n seed.root.tree,\n dynamicStaleAt,\n result.debugInfo,\n result.revealAfter\n )\n\n if (head !== null) {\n writeDynamicDataIntoNavigationTask(\n head,\n seed.root.head,\n dynamicStaleAt,\n result.debugInfo,\n result.revealAfter\n )\n }\n\n const resolvedUrl = new URL(result.canonicalUrl, location.origin)\n\n // Decide whether the navigation needs to be retried.\n //\n // - A tree mismatch (unknown parallel route) means the data is incomplete,\n // so we soft-retry and re-fetch the whole tree.\n // - Otherwise, the navigation committed the canonical URL from the route\n // cache entry it used (a prediction or prefetch). If the request resolved\n // to a *different* canonical URL — e.g. a middleware/proxy redirect the\n // prediction didn't account for — then the committed URL is wrong and the\n // route cache it came from is no longer reliable (the redirect implies a\n // server change the prediction couldn't know about, like logging in or\n // out). We re-resolve the route to invalidate the stale cache and correct\n // the browser URL, reusing the data we just received rather than\n // re-fetching it. When the entry already reflects the redirect (e.g. a\n // prefetch that followed it), the committed URL matches and no retry is\n // needed. See issue #95195.\n let didCommitWrongUrl = false\n if (routeCacheEntry !== null) {\n const committedUrl = new URL(\n routeCacheEntry.canonicalUrl,\n location.origin\n )\n didCommitWrongUrl =\n committedUrl.pathname !== resolvedUrl.pathname ||\n committedUrl.search !== resolvedUrl.search\n }\n\n const exitStatus = didReceiveUnknownParallelRoute\n ? NavigationTaskExitStatus.SoftRetry\n : didCommitWrongUrl\n ? NavigationTaskExitStatus.RedirectRetry\n : NavigationTaskExitStatus.Done\n\n return {\n exitStatus,\n url: resolvedUrl,\n seed,\n }\n } catch {\n if (signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request. Treat\n // it as canceled rather than a failure, so we don't retry or\n // hard-navigate.\n return {\n exitStatus: NavigationTaskExitStatus.Canceled,\n url,\n seed: null,\n }\n }\n\n // This shouldn't happen because fetchServerResponse's entire body is\n // wrapped in a try/catch. If it does, though, it implies the server failed\n // to respond with any tree at all. So we must fall back to a hard retry.\n return {\n exitStatus: NavigationTaskExitStatus.HardRetry,\n url: url,\n seed: null,\n }\n }\n}\n\nfunction writeDynamicDataIntoNavigationTask(\n task: NavigationTask,\n serverRouteTree: RouteTree<RSCSegmentData | null>,\n dynamicStaleAt: number,\n debugInfo: Array<any> | null,\n revealAfter: Promise<void> | null\n): boolean {\n // A non-null data object means the response accounted for this segment,\n // even if it didn't render it (data.rsc may still be null, e.g. for the\n // intermediate segments on the path to a rendered subtree).\n const dynamicData = serverRouteTree.data\n if (task.status === NavigationTaskStatus.Pending && dynamicData !== null) {\n task.status = NavigationTaskStatus.Fulfilled\n const cacheNode = task.node.data\n finishPendingCacheNode(cacheNode, dynamicData, debugInfo, revealAfter)\n\n // The BFCache entry for this segment was written before the response\n // arrived. Bring it up to date with what the response filled in: its\n // staleAt (the per-page unstable_dynamicStaleTime if set, or the default\n // DYNAMIC_STALETIME_MS) and the source of the params its data depends\n // on. We only update segments that received dynamic data — static\n // segments are unaffected.\n updateBFCacheEntryFromDynamicResponse(\n serverRouteTree.varyPath,\n cacheNode,\n dynamicStaleAt\n )\n }\n\n const taskChildren = task.children\n const serverChildren = serverRouteTree.slots\n\n // Detect whether the server sends a parallel route slot that the client\n // doesn't know about.\n let didReceiveUnknownParallelRoute = false\n\n if (taskChildren !== null) {\n if (serverChildren !== null) {\n for (const [parallelRouteKey, serverRouteTreeChild] of serverChildren) {\n const taskChild = taskChildren.get(parallelRouteKey)\n if (taskChild === undefined) {\n // The server sent a child segment that the client doesn't know about.\n //\n // When we receive an unknown parallel route, we must consider it a\n // mismatch. This is unlike the case where the segment itself\n // mismatches, because multiple routes can be active simultaneously.\n // But a given layout should never have a mismatching set of\n // child slots.\n //\n // Theoretically, this should only happen in development during an HMR\n // refresh, because the set of parallel routes for a layout does not\n // change over the lifetime of a build/deployment. In production, we\n // should have already mismatched on either the build id or the segment\n // path. But as an extra precaution, we validate in prod, too.\n didReceiveUnknownParallelRoute = true\n } else {\n // Check that the response is for the route we expected: same route\n // structure and same params, including the page's search params.\n if (\n doesRouteStructureMatch(taskChild.node, serverRouteTreeChild) &&\n serverRouteTreeChild.data !== null &&\n compareParams(\n taskChild.node.varyPath,\n serverRouteTreeChild.varyPath\n ) === ParamsChange.None\n ) {\n // Found a match for this task. Keep traversing down the task tree.\n const childDidReceiveUnknownParallelRoute =\n writeDynamicDataIntoNavigationTask(\n taskChild,\n serverRouteTreeChild,\n dynamicStaleAt,\n debugInfo,\n revealAfter\n )\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\n return didReceiveUnknownParallelRoute\n}\n\nfunction finishPendingCacheNode(\n cacheNode: CacheNode,\n dynamicData: RSCSegmentData,\n debugInfo: Array<any> | null,\n revealAfter: Promise<void> | null\n): void {\n // Writes a dynamic response into an existing render tree. This does _not_\n // create a new tree, it updates the existing tree in-place. So it must follow\n // the Suspense rules of cache safety — it can resolve pending promises, but\n // it cannot overwrite existing data. It can add segments to the tree (because\n // a missing segment will cause the layout router to suspend) but it cannot\n // delete them.\n //\n // We must resolve every promise in the tree, or else it will suspend\n // indefinitely. If we did not receive data for a segment, we will resolve its\n // data promise to `null` to trigger a lazy fetch during render.\n\n // Use the dynamic data from the server to fulfill the deferred RSC promise.\n const rsc = cacheNode.rsc\n const dynamicSegmentData = dynamicData.rsc\n\n if (dynamicSegmentData === null) {\n // This particular server request did not\n // render this segment. There may be a separate pending request that will,\n // though, so we won't abort the task until all pending requests finish.\n return\n }\n\n // TODO: `varyParams` must always describe the render that produced `rsc`,\n // but nothing in the CacheNode type ties the two fields together; this\n // function keeps them in lockstep by writing both at once. Eventually the\n // whole CacheNode should be a thenable whose fields are populated through\n // dedicated helpers that own the state transition.\n if (rsc === null) {\n // This is a lazy cache node. We can overwrite it. This is only safe\n // because we know that the LayoutRouter suspends if `rsc` is `null`.\n cacheNode.rsc = dynamicSegmentData\n cacheNode.varyParams = dynamicData.varyParams\n } else if (isDeferredRsc(rsc) && rsc.status === 'pending') {\n // This is a deferred RSC promise. We can fulfill it with the data we just\n // received from the server. The source of the params that data depends\n // on travels with it.\n //\n // In the streaming dev render, defer the fill until `revealAfter` settles,\n // so React doesn't render the boundary's children before their row has been\n // decoded (otherwise it suspends on the still-pending children and commits\n // a premature fallback). Outside that render `revealAfter` is null and we\n // resolve immediately.\n cacheNode.varyParams = dynamicData.varyParams\n if (revealAfter !== null) {\n const resolveRsc = () => rsc.resolve(dynamicSegmentData, debugInfo)\n // Use the same callback for both outcomes: we don't expect `revealAfter`\n // to reject, but if it ever did (e.g. a connection drop mid-stream) we'd\n // still want to resolve the RSC.\n revealAfter.then(resolveRsc, resolveRsc)\n } else {\n rsc.resolve(dynamicSegmentData, debugInfo)\n }\n } else {\n // This is not a deferred RSC promise that's still pending, nor is it\n // empty, so it must have been populated by a different navigation. We\n // must not overwrite it (nor its dependency source).\n }\n}\n\nfunction abortRemainingPendingTasks(\n task: NavigationTask,\n error: any,\n debugInfo: Array<any> | null\n): NavigationTaskExitStatus {\n let exitStatus\n if (task.status === NavigationTaskStatus.Pending) {\n // The data for this segment is still missing.\n task.status = NavigationTaskStatus.Rejected\n abortPendingCacheNode(task.node.data, error, debugInfo)\n\n // If the server failed to fulfill the data for this segment, it implies\n // that the route tree received from the server mismatched the tree that\n // was previously prefetched.\n //\n // In an app with fully static routes and no proxy-driven redirects or\n // rewrites, this should never happen, because the route for a URL would\n // always be the same across multiple requests. So, this implies that some\n // runtime routing condition changed, likely in a proxy, without being\n // pushed to the client.\n //\n // When this happens, we treat this the same as a refresh(). The entire\n // tree will be re-rendered from the root.\n if (task.node.refreshState === null) {\n // Trigger a \"soft\" refresh. Essentially the same as calling `refresh()`\n // in a Server Action.\n exitStatus = NavigationTaskExitStatus.SoftRetry\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 = NavigationTaskExitStatus.HardRetry\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 = NavigationTaskExitStatus.Done\n }\n\n const taskChildren = task.children\n if (taskChildren !== null) {\n for (const [, taskChild] of taskChildren) {\n const childExitStatus = abortRemainingPendingTasks(\n taskChild,\n error,\n debugInfo\n )\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\n return exitStatus\n}\n\nfunction abortPendingCacheNode(\n cacheNode: CacheNode,\n error: any,\n debugInfo: Array<any> | null\n): void {\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}\n\nconst DEFERRED = Symbol()\n\ntype PendingDeferredRsc<T> = Promise<T> & {\n status: 'pending'\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype FulfilledDeferredRsc<T> = Promise<T> & {\n status: 'fulfilled'\n value: T\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype RejectedDeferredRsc<T> = Promise<T> & {\n status: 'rejected'\n reason: any\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype DeferredRsc<T extends React.ReactNode = React.ReactNode> =\n | PendingDeferredRsc<T>\n | FulfilledDeferredRsc<T>\n | RejectedDeferredRsc<T>\n\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: any): value is DeferredRsc {\n return value && typeof value === 'object' && value.tag === DEFERRED\n}\n\nfunction createDeferredRsc<\n T extends React.ReactNode = React.ReactNode,\n>(): PendingDeferredRsc<T> {\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\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: Array<any> = []\n\n let resolve: any\n let reject: any\n const pendingRsc = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n }) as PendingDeferredRsc<T>\n pendingRsc.status = 'pending'\n pendingRsc.resolve = (value: T, responseDebugInfo: Array<any> | null) => {\n if (pendingRsc.status === 'pending') {\n const fulfilledRsc: FulfilledDeferredRsc<T> = pendingRsc as any\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: any, responseDebugInfo: Array<any> | null) => {\n if (pendingRsc.status === 'pending') {\n const rejectedRsc: RejectedDeferredRsc<T> = pendingRsc as any\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\n return pendingRsc\n}\n\n/**\n * Helper for the Instant Navigation Testing API. Captures the withheld-data\n * gate of the locked navigation that is current when router work spawns a\n * dynamic write, so the write awaits that same gate even if a newer locked\n * navigation rolls the lock over before its response is applied.\n *\n * Not exposed in production builds by default.\n */\nexport function getCurrentNavigationLock(): NavigationLock | null {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { getCurrentNavigationGate } =\n require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')\n return getCurrentNavigationGate()\n }\n return null\n}\n\n/**\n * Helper for the Instant Navigation Testing API. Signals that a new locked\n * navigation is beginning: force-resolves the previous locked navigation's\n * withheld-data gate (without ending the scope) and returns a fresh gate for\n * this navigation, which the caller threads to its dynamic-data write. See\n * `beginLockedNavigation` in `navigation-testing-lock`.\n *\n * Not exposed in production builds by default.\n */\nexport function beginLockedNavigation(): NavigationLock | null {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { beginLockedNavigation: begin } =\n require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')\n return begin()\n }\n return null\n}\n\n/**\n * Helper for the Instant Navigation Testing API. Called during a history\n * traversal: resets the testing lock to a fresh pending scope, releasing any\n * withheld data from prior navigations. See `resetNavigationLockToPending` in\n * `navigation-testing-lock`.\n */\nexport function resetNavigationLockToPending(): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { resetNavigationLockToPending: reset } =\n require('./segment-cache/navigation-testing-lock') as typeof import('./segment-cache/navigation-testing-lock')\n reset()\n }\n}\n","import type {\n FlightRouterState,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport { INTERCEPTION_ROUTE_MARKERS } from '../../../shared/lib/router/utils/interception-routes'\nimport type { Params } from '../../../server/request/params'\nimport {\n isGroupSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\n\nconst removeLeadingSlash = (segment: string): string => {\n return segment[0] === '/' ? segment.slice(1) : segment\n}\n\nconst segmentToPathname = (segment: Segment): string => {\n if (typeof segment === 'string') {\n // 'children' is not a valid path -- it's technically a parallel route that corresponds with the current segment's page\n // if we don't skip it, then the computed pathname might be something like `/children` which doesn't make sense.\n if (segment === 'children') return ''\n\n return segment\n }\n\n return segment[1]\n}\n\nexport const segmentToSourcePagePathname = (segment: Segment): string => {\n if (typeof segment === 'string') {\n if (segment === 'children') return ''\n if (segment === PAGE_SEGMENT_KEY) return 'page'\n return segment\n }\n\n const [paramName, , dynamicParamType] = segment\n\n switch (dynamicParamType) {\n case 'c':\n return `[...${paramName}]`\n case 'ci(..)(..)':\n return `(..)(..)[...${paramName}]`\n case 'ci(.)':\n return `(.)[...${paramName}]`\n case 'ci(..)':\n return `(..)[...${paramName}]`\n case 'ci(...)':\n return `(...)[...${paramName}]`\n case 'oc':\n return `[[...${paramName}]]`\n case 'd':\n return `[${paramName}]`\n case 'di(..)(..)':\n return `(..)(..)[${paramName}]`\n case 'di(.)':\n return `(.)[${paramName}]`\n case 'di(..)':\n return `(..)[${paramName}]`\n case 'di(...)':\n return `(...)[${paramName}]`\n default:\n dynamicParamType satisfies never\n return `[${paramName}]`\n }\n}\n\nfunction normalizeSegments(segments: string[]): string {\n return (\n segments.reduce((acc, segment) => {\n segment = removeLeadingSlash(segment)\n if (segment === '' || isGroupSegment(segment)) {\n return acc\n }\n\n return `${acc}/${segment}`\n }, '') || '/'\n )\n}\n\nexport function extractPathFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string | undefined {\n const segment = Array.isArray(flightRouterState[0])\n ? flightRouterState[0][1]\n : flightRouterState[0]\n\n if (\n segment === DEFAULT_SEGMENT_KEY ||\n INTERCEPTION_ROUTE_MARKERS.some((m) => segment.startsWith(m))\n )\n return undefined\n\n if (segment === PAGE_SEGMENT_KEY) return ''\n\n const segments = [segmentToPathname(segment)]\n const parallelRoutes = flightRouterState[1] ?? {}\n\n const childrenPath = parallelRoutes.children\n ? extractPathFromFlightRouterState(parallelRoutes.children)\n : undefined\n\n if (childrenPath !== undefined) {\n segments.push(childrenPath)\n } else {\n for (const [key, value] of Object.entries(parallelRoutes)) {\n if (key === 'children') continue\n\n const childPath = extractPathFromFlightRouterState(value)\n\n if (childPath !== undefined) {\n segments.push(childPath)\n }\n }\n }\n\n return normalizeSegments(segments)\n}\n\nfunction extractSourcePageSegmentsFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string[] | undefined {\n const segment = segmentToSourcePagePathname(flightRouterState[0])\n\n if (segment === DEFAULT_SEGMENT_KEY) {\n return undefined\n }\n\n if (segment === 'page') {\n return [segment]\n }\n\n const parallelRoutes = flightRouterState[1] ?? {}\n\n const childrenPath = parallelRoutes.children\n ? extractSourcePageSegmentsFromFlightRouterState(parallelRoutes.children)\n : undefined\n\n if (childrenPath !== undefined) {\n return segment === ''\n ? childrenPath\n : [removeLeadingSlash(segment), ...childrenPath]\n }\n\n for (const [key, value] of Object.entries(parallelRoutes)) {\n if (key === 'children') continue\n\n const childPath = extractSourcePageSegmentsFromFlightRouterState(value)\n\n if (childPath !== undefined) {\n return segment === ''\n ? childPath\n : [removeLeadingSlash(segment), ...childPath]\n }\n }\n\n return undefined\n}\n\nexport function extractSourcePageFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string | undefined {\n const sourcePageSegments =\n extractSourcePageSegmentsFromFlightRouterState(flightRouterState)\n\n return sourcePageSegments ? `/${sourcePageSegments.join('/')}` : undefined\n}\n\nfunction computeChangedPathImpl(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const [segmentA, parallelRoutesA] = treeA\n const [segmentB, parallelRoutesB] = treeB\n\n const normalizedSegmentA = segmentToPathname(segmentA)\n const normalizedSegmentB = segmentToPathname(segmentB)\n\n if (\n INTERCEPTION_ROUTE_MARKERS.some(\n (m) =>\n normalizedSegmentA.startsWith(m) || normalizedSegmentB.startsWith(m)\n )\n ) {\n return ''\n }\n\n // Param types and static sibling hints don't affect the resulting pathname,\n // so only compare the segment name and param value.\n // TODO: computeChangedPath is only used to compute the Next-Url header.\n // We should refactor this data structure to be lower cardinality. For example\n // it doesn't need to include any of the concrete param values, just the\n // route structure.\n const didPathChange =\n typeof segmentA === 'string' || typeof segmentB === 'string'\n ? segmentA !== segmentB\n : segmentA[0] !== segmentB[0] || segmentA[1] !== segmentB[1]\n if (\n didPathChange ||\n // A change to the page's search params counts, too. (They used to be part\n // of the page segment string.)\n (segmentA === PAGE_SEGMENT_KEY && treeA[5] !== treeB[5])\n ) {\n // once we find where the tree changed, we compute the rest of the path by traversing the tree\n return extractPathFromFlightRouterState(treeB) ?? ''\n }\n\n for (const parallelRouterKey in parallelRoutesA) {\n if (parallelRoutesB[parallelRouterKey]) {\n const changedPath = computeChangedPathImpl(\n parallelRoutesA[parallelRouterKey],\n parallelRoutesB[parallelRouterKey]\n )\n if (changedPath !== null) {\n return `${segmentToPathname(segmentB)}/${changedPath}`\n }\n }\n }\n\n return null\n}\n\nexport function computeChangedPath(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const changedPath = computeChangedPathImpl(treeA, treeB)\n\n if (changedPath == null || changedPath === '/') {\n return changedPath\n }\n\n // lightweight normalization to remove route groups\n return normalizeSegments(changedPath.split('/'))\n}\n\n/**\n * Recursively extracts dynamic parameters from FlightRouterState.\n */\nexport function getSelectedParams(\n currentTree: FlightRouterState,\n params: Params = {}\n): Params {\n const parallelRoutes = currentTree[1]\n\n for (const parallelRoute of Object.values(parallelRoutes)) {\n const segment = parallelRoute[0]\n const isDynamicParameter = Array.isArray(segment)\n const segmentValue = isDynamicParameter ? segment[1] : segment\n if (!segmentValue || segmentValue === PAGE_SEGMENT_KEY) continue\n\n // Ensure catchAll and optional catchall are turned into an array\n const isCatchAll =\n isDynamicParameter && (segment[2] === 'c' || segment[2] === 'oc')\n\n if (isCatchAll) {\n params[segment[0]] = segment[1].split('/')\n } else if (isDynamicParameter) {\n params[segment[0]] = segment[1]\n }\n\n params = getSelectedParams(parallelRoute, params)\n }\n\n return params\n}\n","export function createHrefFromUrl(\n url: Pick<URL, 'pathname' | 'search' | 'hash'>,\n includeHash: boolean = true\n): string {\n return url.pathname + url.search + (includeHash ? url.hash : '')\n}\n","'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromReadableStream as createFromReadableStreamBrowser,\n createFromFetch as createFromFetchBrowser,\n} from 'react-server-dom-webpack/client'\n\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport { fetch } from '../segment-cache/fetch'\nimport type {\n DynamicNavigationFlightResponse,\n FlightRouterState,\n InitialRSCPayload,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport {\n type NEXT_ROUTER_PREFETCH_HEADER,\n type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_URL,\n RSC_HEADER,\n RSC_CONTENT_TYPE_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_DID_POSTPONE_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_REQUEST_ID_HEADER,\n} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers'\nimport type { PartialTransportData } from '../../../shared/lib/rsc-transport'\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param'\nimport { urlToUrlWithoutFlightMarker } from '../../route-params'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport { getDeploymentId } from '../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n stripIsPartialByte,\n bufferPrefetchResponseBody,\n} from '../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../segment-cache/bfcache'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\nconst createFromFetch =\n createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')\n ).createDebugChannel\n}\n\nexport interface FetchServerResponseOptions {\n readonly flightRouterState: FlightRouterState\n readonly nextUrl: string | null\n readonly isHmrRefresh?: boolean\n readonly signal?: AbortSignal\n}\n\ntype SpaFetchServerResponseResult = {\n transportData: PartialTransportData | null\n canonicalUrl: URL\n renderedSearch: NormalizedSearch\n couldBeIntercepted: boolean\n supportsPerSegmentPrefetching: boolean\n postponed: boolean\n dynamicStaleTime: number\n /**\n * Whether the response body was marked partial (contains unresolved\n * dynamic holes), read from the leading isPartial byte. Always false when\n * Cache Components is disabled. When `staticStageResponse` is non-null,\n * this is also its partiality: a complete response is cached whole, a\n * partial response is cached as its truncated static-stage prefix.\n */\n isResponsePartial: boolean\n staticStageResponse: NavigationFlightResponse | null\n runtimePrefetchStream: ReadableStream<Uint8Array> | null\n responseHeaders: Headers\n debugInfo: Array<any> | null\n /**\n * Dev only: resolves once the server has flushed the shell-stage content to\n * the stream (or earlier, on a cache miss). The navigation defers revealing\n * the response (resolving its deferred RSCs) until this settles, so React\n * doesn't render a boundary's children before their row has been decoded and\n * commit a premature Suspense fallback. `null` outside the streaming dev\n * render.\n */\n revealAfter: Promise<void> | null\n}\n\ntype MpaFetchServerResponseResult = string\n\nexport type FetchServerResponseResult =\n | MpaFetchServerResponseResult\n | SpaFetchServerResponseResult\n\nexport type RequestHeaders = {\n [RSC_HEADER]?: '1'\n [NEXT_ROUTER_STATE_TREE_HEADER]?: string\n [NEXT_URL]?: string\n [NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2' | '3'\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string\n 'x-deployment-id'?: string\n [NEXT_HMR_REFRESH_HEADER]?: '1'\n // A header that is only added in test mode to assert on fetch priority\n 'Next-Test-Fetch-Priority'?: RequestInit['priority']\n [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_REQUEST_ID_HEADER]?: string // dev-only\n}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()\n}\n\nlet isPageUnloading = false\n\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\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/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */\nexport async function fetchServerResponse(\n url: URL,\n options: FetchServerResponseOptions\n): Promise<FetchServerResponseResult> {\n const { flightRouterState, nextUrl } = options\n\n const headers: RequestHeaders = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n flightRouterState,\n options.isHmrRefresh\n ),\n }\n\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1'\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\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\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\n // During a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise. Navigations\n // only ever receive live-render responses (per-segment prefetch\n // responses, which omit some fields, are decoded by the segment cache\n // instead), so the decode is typed as the live-render variant.\n const res = await createFetch<DynamicNavigationFlightResponse>(\n url,\n headers,\n 'auto',\n true,\n options.signal\n )\n\n // If the fetch succeeds while we're in the offline state, notify the\n // offline module so it can short-circuit the polling loop.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { notifyOnline } =\n require('../offline') as typeof import('../offline')\n notifyOnline()\n }\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : originalUrl\n\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\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\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\n return doMpaNavigation(responseUrl.toString())\n }\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 (\n require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')\n ).waitForWebpackRuntimeHotUpdate()\n }\n\n // This request passed `true` to `shouldImmediatelyDecode`, so the Flight\n // response promise is always initialized.\n const flightResponsePromise = res.flightResponsePromise!\n\n const [flightResponse, cacheData] = await Promise.all([\n flightResponsePromise,\n res.cacheData,\n ])\n\n if (\n (res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==\n getNavigationBuildId()\n ) {\n // The server build does not match the client build.\n return doMpaNavigation(res.url)\n }\n\n if (flightResponse.n !== undefined) {\n // The server responded with an MPA navigation URL instead of a\n // SPA payload.\n return doMpaNavigation(flightResponse.n)\n }\n\n const staticStageResponse =\n cacheData !== null\n ? await resolveStaticStageResponse(cacheData, flightResponse, headers)\n : null\n\n return {\n transportData: flightResponse.t ?? null,\n canonicalUrl: canonicalUrl,\n // TODO: We should be able to read this from the rewrite header, not the\n // Flight response. Theoretically they should always agree, but there are\n // currently some cases where it's incorrect for interception routes. We\n // can always trust the value in the response body. However, per-segment\n // prefetch responses don't embed the value in the body; they rely on the\n // header alone. So we need to investigate why the header is sometimes\n // wrong for interception routes.\n renderedSearch: flightResponse.q as NormalizedSearch,\n couldBeIntercepted: interception,\n supportsPerSegmentPrefetching: flightResponse.S,\n postponed,\n // The dynamicStaleTime is only present in the response body when\n // a page exports unstable_dynamicStaleTime and this is a dynamic render.\n // When absent (UnknownDynamicStaleTime), the client falls back to the\n // global DYNAMIC_STALETIME_MS. The value is in seconds.\n dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,\n isResponsePartial:\n cacheData !== null ? cacheData.isResponsePartial : false,\n staticStageResponse,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n revealAfter: flightResponse._revealAfter ?? null,\n }\n } catch (err) {\n if (options.signal?.aborted) {\n // A newer HMR refresh superseded this one and aborted its request.\n // Rethrow so the caller treats it as canceled, rather than logging a\n // failure or falling back to an MPA navigation.\n throw err\n }\n\n // If the fetch rejected due to a network error, wait for connectivity\n // to be restored and then retry. checkOfflineError returns true for\n // network errors (and starts the polling loop); returns false for\n // intentional aborts/timeouts, which fall through to the MPA fallback.\n //\n // Note: when the user navigates multiple times while offline, each\n // navigation queues a separate retry here. Once connectivity returns,\n // all pending retries resume simultaneously. This is mitigated in PR 3\n // by reusing back-forward cache entries during offline navigation, which\n // avoids issuing new fetches in the first place.\n if (process.env.__NEXT_USE_OFFLINE && !isPageUnloading) {\n const { checkOfflineError, getOffline, waitForConnection } =\n require('../offline') as typeof import('../offline')\n if (checkOfflineError(err)) {\n const offline = getOffline()\n if (offline !== null) {\n await waitForConnection(offline)\n }\n return fetchServerResponse(url, options)\n }\n }\n\n if (!isPageUnloading) {\n console.error(\n `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,\n err\n )\n }\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// This is a subset of the standard Response type. We use a custom type for\n// this so we can limit which details about the response leak into the rest of\n// the codebase. For example, there's some custom logic for manually following\n// redirects, so \"redirected\" in this type could be a composite of multiple\n// browser fetch calls; however, this fact should not leak to the caller.\nexport type RSCResponse<T> = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null\n cacheData: Promise<FetchResponseCacheData | null>\n}\n\ntype FetchResponseCacheData = {\n isResponsePartial: boolean\n // Separate clones of the response body for stage extraction. The static\n // stage and shell stage are extracted from independent reads, so each\n // needs its own ReadableStream. Both are derived from a chain of `tee()`\n // calls in `processFetch`.\n staticBodyClone?: ReadableStream<Uint8Array>\n shellBodyClone?: ReadableStream<Uint8Array>\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 */\nexport async function processFetch(response: Response): Promise<{\n response: Response\n cacheData: FetchResponseCacheData | null\n}> {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (!response.body) {\n throw new InvariantError(\n 'Expected RSC navigation response to have a body'\n )\n }\n\n const { stream, isPartial } = await stripIsPartialByte(response.body)\n\n let responseStream: ReadableStream<Uint8Array>\n let cacheData: FetchResponseCacheData\n\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n // Three readers needed: the main Flight decoder, the static-stage\n // extractor, and the shell-stage extractor. Tee twice.\n const [stream1, rest] = stream.tee()\n const [staticBodyClone, shellBodyClone] = rest.tee()\n responseStream = stream1\n cacheData = {\n isResponsePartial: isPartial,\n staticBodyClone,\n shellBodyClone,\n }\n } else {\n responseStream = stream\n cacheData = { isResponsePartial: isPartial }\n }\n\n const strippedResponse = new Response(responseStream, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n })\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', { value: response.url })\n Object.defineProperty(strippedResponse, 'redirected', {\n value: response.redirected,\n })\n\n return { response: strippedResponse, cacheData }\n }\n\n return { response, cacheData: null }\n}\n\n/**\n * Resolves the static stage response from the raw `processFetch` outputs and\n * the decoded flight response, for writing into the segment cache. The\n * resolved response's partiality is the whole response's partiality\n * (`cacheData.isResponsePartial`): a complete response is resolved whole, a\n * partial one as its truncated static-stage prefix.\n *\n * - Fully static: use the decoded flight response as-is, no truncation needed.\n * - Not fully static + `l` field: truncate the body clone at the static stage\n * byte boundary and decode.\n * - Otherwise: no cache-worthy data.\n */\nasync function resolveStaticStageResponse<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<T | null> {\n const { isResponsePartial, staticBodyClone } = cacheData\n\n if (staticBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n staticBodyClone.cancel()\n\n return flightResponse\n }\n\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const staticStageByteLength = await flightResponse.l\n if (staticStageByteLength === 0) {\n staticBodyClone.cancel()\n return null\n }\n return decodeStageUntilBoundary<T>(\n staticBodyClone,\n staticStageByteLength,\n headers\n )\n }\n\n // No caching — cancel the unused clone.\n staticBodyClone.cancel()\n }\n\n return null\n}\n\n/**\n * Resolves the shell stage of a prerender response:\n *\n * - `a === undefined` (server didn't emit shell stage info) or no shell body\n * clone: no shell exists — returns null.\n * - `a` resolves to `null`: the shell IS the main response — returns\n * `flightResponse` itself (callers compare by reference).\n * - `a` resolves to a number: the shell is a strict prefix of the response —\n * returns a separate Flight decode of the byte prefix.\n */\nexport async function resolveShellStageResponse<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<T | null> {\n const { shellBodyClone } = cacheData\n\n if (!shellBodyClone) {\n return null\n }\n\n if (flightResponse.a === undefined) {\n // The render wasn't staged — no shell exists.\n shellBodyClone.cancel()\n return null\n }\n\n const shellByteLength = await flightResponse.a\n if (shellByteLength === 0) {\n shellBodyClone.cancel()\n return null\n }\n if (shellByteLength === null) {\n // The shell IS the full response (no shell/full split). Return the full\n // response itself — callers detect this case by reference equality —\n // rather than collapsing it into null, which would lose the distinction\n // from \"no shell exists\". This mirrors the convention of the per-segment\n // prefetch fetch (see fetchAndWritePerSegmentPrefetchResponse in cache.ts).\n shellBodyClone.cancel()\n return flightResponse\n }\n\n return decodeStageUntilBoundary<T>(shellBodyClone, shellByteLength, headers)\n}\n\n/**\n * Truncates and buffers a Flight stream clone at the given byte boundary and\n * decodes the prefix as an optional Flight payload. Returns null if extraction\n * fails or the root does not resolve before the next task. The caller can still\n * use the full response.\n */\nexport async function decodeStageUntilBoundary<T>(\n responseBodyClone: ReadableStream<Uint8Array>,\n byteLength: number,\n headers: RequestHeaders | undefined\n): Promise<T | null> {\n try {\n const buffer = await bufferPrefetchResponseBody(\n responseBodyClone,\n byteLength\n )\n const response = decodeBufferedStage<T>(buffer, headers)\n\n // The caller already has the full response root, but this prefix may omit\n // rows that the root needs. Bound this optional extraction so it cannot\n // hold up the full response. This deadline applies to the outer root, not\n // to Client Components that continue loading through lazy references.\n return await new Promise<T | null>((resolve) => {\n const timeout = setTimeout(() => resolve(null), 0)\n response.then(\n (root) => {\n clearTimeout(timeout)\n resolve(root)\n },\n () => {\n clearTimeout(timeout)\n resolve(null)\n }\n )\n })\n } catch {\n return null\n }\n}\n\n/**\n * Decodes already-buffered Flight response bytes as a stage payload. A\n * \"stage\" is a prefix of the staged server render — see `RenderStage` in\n * packages/next/src/server/app-render/staged-rendering.ts. The\n * bytes are delivered to Flight as a single chunk so all rows are processed\n * synchronously in one call — required for the thenable-status reads that\n * scope a response's late-resolving metadata (vary params, isPartial, ...)\n * to this decode.\n */\nexport function decodeBufferedStage<T>(\n buffer: Uint8Array,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(buffer)\n controller.close()\n },\n })\n return createFromNextReadableStream<T>(stream, headers, {\n allowPartialStream: true,\n })\n}\n\n// When an HMR refresh can be superseded, we decode its Flight response through\n// a wrapper stream we can close on abort. Closing the stream (rather than\n// letting the aborted fetch error it) makes React's Flight client mark\n// unresolved rows as halted: they suspend during render instead of rejecting,\n// so a superseded request never surfaces an error on an already-committed tree.\n// Because the stream is closed, there's also no unclosed-stream GC-root leak\n// (see #89610). The wrapper is created synchronously here so that the decode\n// starts at the same point `createFromNextFetch` would, preserving the\n// server-latency debug timing.\nfunction createHaltingFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal\n): Promise<T> & { _debugInfo?: Array<any> } {\n let closed = false\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n const wrapper = new ReadableStream<Uint8Array>({\n start(controller) {\n const onAbort = () => {\n closed = true\n try {\n controller.close()\n } catch {\n // The controller may already be closed; nothing to do.\n }\n if (reader !== null) {\n reader.cancel().catch(() => {})\n }\n }\n if (signal.aborted) {\n onAbort()\n } else {\n signal.addEventListener('abort', onAbort, { once: true })\n }\n },\n async pull(controller) {\n if (closed) {\n return\n }\n if (reader === null) {\n let response: Response\n try {\n response = await fetchPromise\n } catch (err) {\n // We don't inspect `err`. If the request was superseded, `onAbort`\n // already ran synchronously (abort listeners fire during\n // `signal.abort()`, before this rejection microtask), so `closed` is\n // true and the controller is already closed — erroring it would\n // throw, and a superseded request's failure is moot regardless of its\n // cause. Only a genuine, non-superseded failure reaches here with\n // `closed` still false; that is the case we surface.\n if (!closed) {\n controller.error(err)\n }\n return\n }\n if (closed) {\n // Aborted while awaiting the response. The `fetch` abort tears down\n // an in-flight request, but if it had already completed we still hold\n // an unread body; release it so it isn't left dangling.\n response.body?.cancel().catch(() => {})\n return\n }\n const body = response.body\n if (body === null) {\n controller.close()\n return\n }\n reader = body.getReader()\n }\n try {\n const { done, value } = await reader.read()\n if (closed) {\n return\n }\n if (done) {\n controller.close()\n } else {\n controller.enqueue(value)\n }\n } catch (err) {\n // Same as the fetch catch above: once superseded (`closed`) the\n // controller is already closed and the outcome is moot, so we swallow\n // the rejection unconditionally; only a real, non-superseded read\n // failure (`closed` still false) is surfaced.\n if (!closed) {\n controller.error(err)\n }\n }\n },\n })\n\n // React attaches `_debugInfo` to the returned promise at runtime.\n return createFromNextReadableStream<T>(wrapper, headers, {\n allowPartialStream: true,\n }) as Promise<T> & { _debugInfo?: Array<any> }\n}\n\n// Selects the Flight decode strategy: a halting wrapper for cancellable HMR\n// refreshes, otherwise the standard fetch-based decode. Gated to the dev server\n// (where HMR runs) so the wrapper is eliminated from production and\n// `--debug-prerender` bundles regardless of the flag.\nfunction decodeFlightResponse<T>(\n fetchPromise: Promise<Response>,\n headers: RequestHeaders,\n signal: AbortSignal | undefined\n): Promise<T> & { _debugInfo?: Array<any> } {\n if (\n process.env.__NEXT_DEV_SERVER &&\n process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION &&\n signal\n ) {\n return createHaltingFlightResponse<T>(fetchPromise, headers, signal)\n }\n return createFromNextFetch<T>(fetchPromise, headers)\n}\n\nexport async function createFetch<T>(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n shouldImmediatelyDecode: boolean,\n signal?: AbortSignal\n): Promise<RSCResponse<T>> {\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\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority\n }\n\n const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\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\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\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n const fetchOptions: RequestInit = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal,\n }\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url)\n await setCacheBustingSearchParam(fetchUrl, headers)\n let processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n let fetchPromise = processed.then(({ response }) => response)\n\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\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n let browserResponse = await fetchPromise\n\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\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 // The server did not perform a redirect.\n break\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n if (responseUrl.origin !== fetchUrl.origin) {\n // The server redirected to an external URL. The rest of the logic below\n // is not relevant, because it only applies to internal redirects.\n break\n }\n if (\n responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) ===\n fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)\n ) {\n // The redirected URL already includes the cache busting search param.\n // This was probably intentional. Regardless, there's no reason to\n // issue another request to this URL because it already has the param\n // value that we would have added below.\n break\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl)\n await setCacheBustingSearchParam(fetchUrl, headers)\n processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n fetchPromise = processed.then(({ response }) => response)\n flightResponsePromise = shouldImmediatelyDecode\n ? decodeFlightResponse<T>(fetchPromise, headers, signal)\n : null\n browserResponse = await fetchPromise\n // We just performed a manual redirect, so this is now true.\n redirected = true\n }\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\n const rscResponse: RSCResponse<T> = {\n url: responseUrl.href,\n\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\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\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\n cacheData: processed.then(({ cacheData }) => cacheData),\n }\n\n return rscResponse\n}\n\nexport function createFromNextReadableStream<T>(\n flightStream: ReadableStream<Uint8Array>,\n requestHeaders: RequestHeaders | undefined,\n options?: { allowPartialStream?: boolean }\n): Promise<T> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n unstable_allowPartialStream: options?.allowPartialStream,\n })\n}\n\nfunction createFromNextFetch<T>(\n promiseForResponse: Promise<Response>,\n requestHeaders: RequestHeaders\n): Promise<T> & { _debugInfo?: Array<any> } {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n","import { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport type { RouteTree } from '../segment-cache/cache'\n\nexport function isNavigatingToNewRootLayout<TCurrent, TNext>(\n currentTree: RouteTree<TCurrent>,\n nextTree: RouteTree<TNext>\n): boolean {\n // Decides whether navigating from currentTree to nextTree crosses into a\n // different root layout, which requires a full-page (MPA-style) navigation.\n //\n // The \"root layout\" is the highest-level layout in the tree. The segments at\n // or above it form the \"root layout prefix\", which the server marks with the\n // IsRootLayoutOrAbove hint. Two routes share a root layout iff their root\n // layout prefixes are structurally identical — same segments (ignoring\n // dynamic param *values*) for the same depth. So we walk the prefix in\n // lockstep and report a change as soon as the prefixes diverge.\n const currentInPrefix =\n (currentTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n const nextInPrefix =\n (nextTree.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n // Both trees have descended past the root layout with everything above\n // matching — same root layout.\n if (!currentInPrefix && !nextInPrefix) {\n return false\n }\n\n // One tree's root layout prefix is deeper than the other's, so the root\n // layout boundary moved — it must have changed.\n // E.g. /[lang]/layout.js -> /[lang]/[region]/layout.js\n if (currentInPrefix !== nextInPrefix) {\n return true\n }\n\n // Both segments are still inside the root layout prefix. They must match.\n // Compare dynamic param name and type but ignore the value: different values\n // (e.g. /[name] for slug1 vs slug2) still resolve to the same /[name]/layout.\n // E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js: (group1) changed\n // to (group2) inside the prefix, so the root layout changed.\n const currentTreeSegment = currentTree.segment\n const nextTreeSegment = nextTree.segment\n if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {\n if (\n currentTreeSegment[0] !== nextTreeSegment[0] ||\n currentTreeSegment[2] !== nextTreeSegment[2]\n ) {\n return true\n }\n } else if (currentTreeSegment !== nextTreeSegment) {\n return true\n }\n\n // Keep walking the prefix. (Above the root layout there is only a `children`\n // slot, but we traverse all slots defensively.)\n const slots = nextTree.slots\n const currentTreeChildren = currentTree.slots\n if (slots !== null) {\n for (const [slot, nextTreeChild] of slots) {\n const currentTreeChild = currentTreeChildren?.get(slot)\n if (\n currentTreeChild === undefined ||\n isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild)\n ) {\n return true\n }\n }\n }\n return false\n}\n","import type { FlightRouterState } from '../../../../shared/lib/app-router-types'\n\n// The tree from the last state that was committed to the browser history\n// (i.e., the last state for which HistoryUpdater's useInsertionEffect ran).\n// This lets the server-patch reducer distinguish between retrying a\n// navigation that already pushed a history entry vs one whose transition\n// suspended and never committed.\n//\n// Currently only used by the server-patch retry logic, but this module is a\n// stepping stone toward a broader refactor of the navigation queue. The\n// existing AppRouter action queue will eventually be replaced by a more\n// reactive model that explicitly tracks pending vs committed navigation\n// state. This file will likely evolve into (or be subsumed by) that new\n// implementation.\nlet lastCommittedTree: FlightRouterState | null = null\n\nexport function getLastCommittedTree(): FlightRouterState | null {\n return lastCommittedTree\n}\n\nexport function setLastCommittedTree(tree: FlightRouterState): void {\n lastCommittedTree = tree\n}\n","import type {\n NavigateAction,\n ReadonlyReducerState,\n ReducerState,\n} from '../router-reducer-types'\n\nimport {\n completeHardNavigation,\n navigate as navigateUsingSegmentCache,\n} from '../../app-router-state'\nimport { getStaleTimeMs } from '../../segment-cache/cache'\nimport { FreshnessPolicy } from '../../render-tree'\n\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 =\n Number(process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME) * 1000\n\nexport const STATIC_STALETIME_MS = getStaleTimeMs(\n Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME)\n)\n\nexport function navigateReducer(\n state: ReadonlyReducerState,\n action: NavigateAction\n): ReducerState {\n const { url, isExternalUrl, navigateType, scrollBehavior } = action\n\n if (isExternalUrl) {\n return completeHardNavigation(state, url, navigateType)\n }\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\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(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n state.root,\n state.tree,\n state.nextUrl,\n FreshnessPolicy.Default,\n scrollBehavior,\n navigateType\n )\n}\n","import type { RootRouteTree } from '../segment-cache/cache'\nimport type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { NavigationSeed } from '../segment-cache/decode-server-response'\nimport type { FetchServerResponseResult } from './fetch-server-response'\nimport type { FreshnessPolicy } from '../render-tree'\n\nexport 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\nexport type RouterChangeByServerResponse = ({\n navigatedAt,\n previousTree,\n serverResponse,\n}: {\n navigatedAt: number\n previousTree: FlightRouterState\n serverResponse: FetchServerResponseResult\n}) => void\n\n/**\n * Refresh triggers a refresh of the full page data.\n * - fetches the Flight data and fills rsc at the root of the cache.\n * - The router state is updated at the root.\n */\nexport interface RefreshAction {\n type: typeof ACTION_REFRESH\n /**\n * Bypass invalidating the segment cache. Used by the Instant Navigation\n * Testing API to preserve prefetched data when refreshing after an MPA\n * navigation. Not exposed in production builds by default.\n */\n bypassCacheInvalidation?: boolean\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n signal?: AbortSignal\n}\n\nexport type ServerActionDispatcher = (\n args: Omit<\n ServerActionAction,\n 'type' | 'mutable' | 'navigate' | 'changeByServerResponse' | 'cache'\n >\n) => void\n\nexport interface ServerActionAction {\n type: typeof ACTION_SERVER_ACTION\n actionId: string\n actionArgs: any[]\n resolve: (value: any) => void\n reject: (reason?: any) => void\n didRevalidate?: boolean\n}\n\n/**\n * Navigate triggers a navigation to the provided url. It supports two types: `push` and `replace`.\n *\n * `navigateType`:\n * - `push` - pushes a new history entry in the browser history\n * - `replace` - replaces the current history entry in the browser history\n *\n * Navigate has multiple cache heuristics:\n * - page was prefetched\n * - Apply router state tree from prefetch\n * - Apply Flight data from prefetch to the cache\n * - If Flight data is a string, it's a redirect and the state is updated to trigger a redirect\n * - Check if hard navigation is needed\n * - Hard navigation happens when a dynamic parameter below the common layout changed\n * - When hard navigation is needed the cache is invalidated below the flightSegmentPath\n * - The missing cache nodes of the page will be fetched in layout-router and trigger the SERVER_PATCH action\n * - If hard navigation is not needed\n * - The cache is reused\n * - If any cache nodes are missing they'll be fetched in layout-router and trigger the SERVER_PATCH action\n * - page was not prefetched\n * - The navigate was called from `next/router` (`router.push()` / `router.replace()`) / `next/link` without prefetched data available (e.g. the prefetch didn't come back from the server before clicking the link)\n * - Flight data is fetched in the reducer (suspends the reducer)\n * - Router state tree is created based on Flight data\n * - Cache is filled based on the Flight data\n *\n * Above steps explain 3 cases:\n * - `soft` - Reuses the existing cache and fetches missing nodes in layout-router.\n * - `hard` - Creates a new cache where cache nodes are removed below the common layout and fetches missing nodes in layout-router.\n * - `optimistic` (explicit no prefetch) - Creates a new cache and kicks off the data fetch in the reducer. The data fetch is awaited in the layout-router.\n */\nexport interface NavigateAction {\n type: typeof ACTION_NAVIGATE\n url: URL\n isExternalUrl: boolean\n locationSearch: Location['search']\n navigateType: 'push' | 'replace'\n scrollBehavior: ScrollBehavior\n}\n\n/**\n * Restore applies the provided router state.\n * - Used for `popstate` (back/forward navigation) where a known router state has to be applied.\n * - Also used when syncing the router state with `pushState`/`replaceState` calls.\n * - Router state is applied as-is from the history state, if available.\n * - If the history state does not contain the router state, the existing router state is used.\n * - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.\n * - If existing cache nodes match these are used.\n */\nexport interface RestoreAction {\n type: typeof ACTION_RESTORE\n url: URL\n historyState: AppHistoryState | undefined\n}\n\nexport type AppHistoryState = {\n tree: FlightRouterState\n renderedSearch: string\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n previousTree: FlightRouterState\n url: URL\n nextUrl: string | null\n seed: NavigationSeed | null\n mpa: boolean\n navigateType: 'push' | 'replace'\n /**\n * Freshness policy for the retry navigation. `RefreshAll` re-fetches the\n * tree's dynamic data (genuine tree mismatch). `HistoryTraversal` reuses the\n * data already in the tree (when only the URL needs correcting after a\n * redirect).\n */\n freshnessPolicy: FreshnessPolicy.RefreshAll | FreshnessPolicy.HistoryTraversal\n}\n\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 */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n}\n\nexport interface PushRef {\n /**\n * If the app-router should push a new history entry in app-router's useEffect()\n */\n pendingPush: boolean\n /**\n * Multi-page navigation through location.href.\n */\n mpaNavigation: boolean\n /**\n * Skip applying the router state to the browser history state.\n */\n preserveCustomHistoryState: boolean\n}\n\n/**\n * Controls the scroll behavior for a navigation.\n */\nexport const enum ScrollBehavior {\n /** Use per-node ScrollRef to decide whether to scroll. */\n Default = 0,\n /** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */\n NoScroll = 1,\n}\n\nexport type ScrollHandlerRef = {\n /**\n * The scroll ref from the most recent navigation. Set to whatever was\n * accumulated during tree construction (or null if nothing was\n * accumulated). On the next navigation, if new scroll targets are\n * created, the previous scrollRef is invalidated by setting\n * `current = false`.\n */\n scrollRef: ScrollRef | null\n /**\n * When true, the scroll handler uses the navigation-level `scrollRef`\n * for every segment regardless of per-node state. Used for hash-only\n * navigations where every segment should be treated as a scroll\n * target. When false, the handler checks `renderTree.data.scrollRef`\n * instead (per-node), so only segments that actually navigated scroll.\n */\n forceScroll: boolean\n /**\n * The hash fragment that should be scrolled to.\n */\n hashFragment: string | null\n /**\n * If only the URLs hash fragment changed\n */\n onlyHashChange: boolean\n}\n\n/**\n * Handles keeping the state of app-router.\n */\nexport type AppRouterState = {\n /**\n * The router state, this is written into the history state in app-router using replaceState/pushState.\n * - Has to be serializable as it is written into the history state.\n * - Holds which segments and parallel routes are shown on the screen.\n */\n tree: FlightRouterState\n /**\n * The render tree and the document head (see RootRouteTree). The tree holds\n * React nodes for every segment that is shown on screen as well as\n * previously shown segments, and in-progress data requests. The head is a\n * one-node render tree keyed at the metadata vary path.\n *\n * One object per committed navigation; the prefetch scheduler compares it by\n * identity (see PrefetchTask.renderTreeAtTimeOfPrefetch).\n */\n root: RootRouteTree<CacheNode>\n /**\n * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.\n */\n pushRef: PushRef\n /**\n * Decides if the update should apply scroll management.\n */\n scrollRef: ScrollHandlerRef\n /**\n * The canonical url that is pushed/replaced.\n * - This is the url you see in the browser.\n */\n canonicalUrl: string\n\n /**\n * The search query observed by the server during rendering. This may be\n * different from the canonical URL's search query if the server performed\n * a rewrite. Even though a client component won't observe this (unless it\n * were passed from a Server component), the client router needs to know this\n * so it can properly cache segment data; it'ss part of a page segment's\n * cache key.\n */\n renderedSearch: string\n\n /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n\n /**\n * The previous next-url that was used previous to a dynamic navigation.\n */\n previousNextUrl: string | null\n\n debugInfo: Array<unknown> | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState =\n | (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })\n | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | HmrRefreshAction\n | ServerActionAction\n>\n","'use client'\n\nimport {\n computeCacheBustingSearchParam,\n computeLegacyCacheBustingSearchParam,\n} from '../../../shared/lib/router/utils/cache-busting-search-param'\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n NEXT_RSC_UNION_QUERY,\n} from '../app-router-headers'\nimport type { RequestHeaders } from './fetch-server-response'\n\nasync function computeClientCacheBustingSearchParam(\n headers: RequestHeaders\n): Promise<string> {\n if (typeof globalThis.crypto?.subtle?.digest === 'function') {\n return computeCacheBustingSearchParam(\n headers[NEXT_ROUTER_PREFETCH_HEADER],\n headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],\n headers[NEXT_ROUTER_STATE_TREE_HEADER],\n headers[NEXT_URL]\n )\n }\n\n return computeLegacyCacheBustingSearchParam(\n headers[NEXT_ROUTER_PREFETCH_HEADER],\n headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],\n headers[NEXT_ROUTER_STATE_TREE_HEADER],\n headers[NEXT_URL]\n )\n}\n\n/**\n * Mutates the provided URL by adding a cache-busting search parameter for CDNs that don't\n * support custom headers. This helps avoid caching conflicts by making each request unique.\n *\n * Rather than relying on the Vary header which some CDNs ignore, we append a search param\n * to create a unique URL that forces a fresh request.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * Note: This function mutates the input URL directly and resolves once the\n * cache-busting value has been computed and applied.\n *\n * TODO: Since we need to use a search param anyway, we could simplify by removing the custom\n * headers approach entirely and just use search params.\n */\nexport const setCacheBustingSearchParam = async (\n url: URL,\n headers: RequestHeaders\n): Promise<void> => {\n const uniqueCacheKey = await computeClientCacheBustingSearchParam(headers)\n setCacheBustingSearchParamWithHash(url, uniqueCacheKey)\n}\n\n/**\n * Sets a cache-busting search parameter on a URL using a provided hash value.\n *\n * This function performs the same logic as `setCacheBustingSearchParam` but accepts\n * a pre-computed hash instead of computing it from headers.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * hash: \"abc123\"\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * If the hash is empty, we will set `_rsc` search param without a value.\n * Like this: https://example.com/path?query=1&_rsc\n *\n * Note: This function mutates the input URL directly and does not return anything.\n */\nexport const setCacheBustingSearchParamWithHash = (\n url: URL,\n hash: string\n): void => {\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 */\n const existingSearch = url.search\n const rawQuery = existingSearch.startsWith('?')\n ? existingSearch.slice(1)\n : existingSearch\n\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\n .split('&')\n .filter((pair) => pair && !pair.startsWith(`${NEXT_RSC_UNION_QUERY}=`))\n\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","import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { VaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport type { VaryPath } from './vary-path'\n\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 */\nexport const UnknownDynamicStaleTime = -1\n\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 */\nexport function computeDynamicStaleAt(\n now: number,\n dynamicStaleTimeSeconds: number\n): number {\n return dynamicStaleTimeSeconds !== UnknownDynamicStaleTime\n ? now + dynamicStaleTimeSeconds * 1000\n : now + DYNAMIC_STALETIME_MS\n}\nimport {\n setInCacheMap,\n getFromCacheMap,\n EntryStatus,\n type UnknownMapEntry,\n type CacheMap,\n createCacheMap,\n} from './cache-map'\n\nexport type BFCacheEntry = {\n rsc: React.ReactNode | null\n prefetchRsc: React.ReactNode | null\n\n // The source of the params `rsc` depends on, copied from the CacheNode that\n // wrote this entry (see CacheNode.varyParams). A restored node reads it to\n // decide whether a later navigation can keep its data.\n varyParams: VaryParams | null\n\n // The bfcacheId of the CacheNode that wrote this entry. Restored on\n // history-traversal navigations so that `useRouter().bfcacheId` is stable\n // across back/forward, even without `cacheComponents` Activity preservation.\n bfcacheId: number\n\n ref: UnknownMapEntry | null\n size: number\n // The time at which this data was received. Used to compute the stale time\n // for dynamic prefetches (which use STATIC_STALETIME_MS instead of\n // DYNAMIC_STALETIME_MS). Stored explicitly because staleAt may be\n // overridden by a per-page unstable_dynamicStaleTime, which would break\n // any reverse calculation from staleAt.\n navigatedAt: number\n staleAt: number\n version: number\n // A BFCacheEntry always represents a completed navigation, so the status is\n // always Fulfilled. The field exists so that BFCacheEntry conforms to the\n // MapValue protocol.\n status: EntryStatus.Fulfilled\n}\n\nconst bfcacheMap: CacheMap<BFCacheEntry> = createCacheMap()\n\nlet currentBfCacheVersion = 0\n\nexport function invalidateBfCache(): void {\n if (typeof window === 'undefined') {\n return\n }\n currentBfCacheVersion++\n}\n\nexport function writeToBFCache(\n now: number,\n varyPath: VaryPath,\n cacheNode: CacheNode,\n dynamicStaleAt: number\n): void {\n if (typeof window === 'undefined') {\n return\n }\n\n const entry: BFCacheEntry = {\n rsc: cacheNode.rsc,\n prefetchRsc: cacheNode.prefetchRsc,\n\n varyParams: cacheNode.varyParams,\n\n bfcacheId: cacheNode.bfcacheId,\n\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\n navigatedAt: now,\n\n // A back/forward navigation will disregard the stale time. This field is\n // only relevant when staleTimes.dynamic is enabled or unstable_dynamicStaleTime\n // is exported by a page.\n staleAt: dynamicStaleAt,\n version: currentBfCacheVersion,\n status: EntryStatus.Fulfilled,\n }\n const isRevalidation = false\n setInCacheMap(bfcacheMap, varyPath, entry, isRevalidation)\n}\n\n/**\n * Patches the entry written for a segment before its dynamic response\n * arrived, with what the response filled in on the segment's CacheNode: the\n * per-page stale time from `unstable_dynamicStaleTime` (authoritative over\n * the default DYNAMIC_STALETIME_MS the entry was written with) and the\n * source of the params its data depends on. The entry shares the node's\n * deferred `rsc` promise, which the response resolves in place. Only the entry\n * that shares the node's `rsc` is updated; a refresh may have replaced the\n * entry at the same vary path, and that entry belongs to the newer node.\n *\n * TODO: This function exists because the entry gets `rsc` when it is written\n * but the stale time and vary params only later, through a second write that\n * has to find the entry again. The response should fill in all three as one\n * unit: make the pending CacheNode itself the thenable (like DeferredRsc, but\n * for the whole node) with an explicit pending → fulfilled/rejected\n * transition, so the entry holds the node and observes its resolution\n * directly, with nothing to look up or patch afterwards.\n */\nexport function updateBFCacheEntryFromDynamicResponse(\n varyPath: VaryPath,\n cacheNode: CacheNode,\n newStaleAt: number\n): void {\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(\n -1,\n currentBfCacheVersion,\n bfcacheMap,\n varyPath,\n isRevalidation,\n false\n )\n if (entry !== null && entry.rsc === cacheNode.rsc) {\n entry.staleAt = newStaleAt\n entry.varyParams = cacheNode.varyParams\n }\n}\n\nexport function readFromBFCache(varyPath: VaryPath): BFCacheEntry | null {\n if (typeof window === 'undefined') {\n return null\n }\n const isRevalidation = false\n return getFromCacheMap(\n // 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,\n currentBfCacheVersion,\n bfcacheMap,\n varyPath,\n isRevalidation,\n false\n )\n}\n\nexport function readFromBFCacheDuringRegularNavigation(\n now: number,\n varyPath: VaryPath\n): BFCacheEntry | null {\n if (typeof window === 'undefined') {\n return null\n }\n const isRevalidation = false\n return getFromCacheMap(\n now,\n currentBfCacheVersion,\n bfcacheMap,\n varyPath,\n isRevalidation,\n false\n )\n}\n","// TypeScript trick to simulate opaque types, like in Flow.\ntype Opaque<K, T> = T & { __brand: K }\n\n// Only functions in this module should be allowed to create CacheKeys.\nexport type NormalizedPathname = Opaque<'NormalizedPathname', string>\nexport type NormalizedSearch = Opaque<'NormalizedSearch', string>\nexport type NormalizedNextUrl = Opaque<'NormalizedNextUrl', string>\n\nexport type RouteCacheKey = Opaque<\n 'RouteCacheKey',\n {\n pathname: NormalizedPathname\n search: NormalizedSearch\n nextUrl: NormalizedNextUrl | null\n\n // TODO: Eventually the dynamic params will be added here, too.\n }\n>\n\nexport function createCacheKey(\n originalHref: string,\n nextUrl: string | null\n): RouteCacheKey {\n const originalUrl = new URL(originalHref)\n const cacheKey = {\n pathname: originalUrl.pathname as NormalizedPathname,\n search: originalUrl.search as NormalizedSearch,\n nextUrl: nextUrl as NormalizedNextUrl | null,\n } as RouteCacheKey\n return cacheKey\n}\n\n/**\n * Splits a pathname into its non-empty parts. Equivalent to\n * `pathname.split('/').filter((p) => p !== '')` — empty tokens produced by\n * leading, trailing, or consecutive slashes are skipped.\n *\n * We use a manual loop instead of `split` + `filter` because\n * `String.prototype.split` can return arrays with either the packed or holey\n * elements kind depending on internal fast paths, and `filter`/`slice`\n * propagate the kind. Mixing holey and packed arrays at the same call sites\n * makes downstream array method loads (`slice`, `join`, `length`) polymorphic\n * and causes repeated \"wrong map\" deoptimizations in hot route-matching code.\n * Pushing into an array literal guarantees a packed elements kind.\n */\nexport function splitPathnameIntoParts(pathname: string): Array<string> {\n const parts: Array<string> = []\n let start = 0\n for (let i = 0; i < pathname.length; i++) {\n if (pathname.charCodeAt(i) === 47 /* '/' */) {\n if (i > start) {\n parts.push(pathname.slice(start, i))\n }\n start = i + 1\n }\n }\n if (start < pathname.length) {\n parts.push(pathname.slice(start))\n }\n return parts\n}\n","import type { VaryPathNode } from './vary-path'\nimport { lruPut, updateLruSize, deleteFromLru } from './lru'\n\n/**\n * A specialized data type for storing multi-key cache entries.\n *\n * The basic structure is a map whose keys are tuples, called the keypath.\n * When querying the cache, keypaths are compared per-element.\n *\n * Example:\n * set(map, ['https://localhost', 'foo/bar/baz'], 'yay');\n * get(map, ['https://localhost', 'foo/bar/baz']) -> 'yay'\n *\n * NOTE: Array syntax is used in these examples for illustration purposes, but\n * in reality the paths are lists.\n * \n * The parts of the keypath represent the different inputs that contribute\n * to the entry value. To illustrate, if you were to use this data type to store\n * HTTP responses, the keypath would include the URL and everything listed by\n * the Vary header.\n * \n * See vary-path.ts for more details.\n *\n * The order of elements in a keypath must be consistent between lookups to\n * be considered the same, but besides that, the order of the keys is not\n * semantically meaningful.\n *\n * Keypaths may include a special kind of key called Fallback. When an entry is\n * stored with Fallback as part of its keypath, it means that the entry does not\n * vary by that key. When querying the cache, if an exact match is not found for\n * a keypath, the cache will check for a Fallback match instead. Each element of\n * the keypath may have a Fallback, so retrieval is an O(n ^ 2) operation, but\n * it's expected that keypaths are relatively short.\n *\n * Example:\n * set(cacheMap, ['store', 'product', 1], PRODUCT_PAGE_1);\n * set(cacheMap, ['store', 'product', Fallback], GENERIC_PRODUCT_PAGE);\n *\n * // Exact match\n * get(cacheMap, ['store', 'product', 1]) -> PRODUCT_PAGE_1\n *\n * // Fallback match\n * get(cacheMap, ['store', 'product', 2]) -> GENERIC_PRODUCT_PAGE\n *\n * Because we have the Fallback mechanism, we can impose a constraint that\n * regular JS maps do not have: a value cannot be stored at multiple keypaths\n * simultaneously. These cases should be expressed with Fallback keys instead.\n *\n * Additionally, because values only exist at a single keypath at a time, we\n * can optimize successive lookups by caching the internal map entry on the\n * value itself, using the `ref` field. This is especially useful because it\n * lets us skip the O(n ^ 2) lookup that occurs when Fallback entries\n * are present.\n *\n\n * How to decide if stuff belongs in here, or in cache.ts?\n * -------------------------------------------------------\n * \n * Anything to do with retrival, lifetimes, or eviction needs to go in this\n * module because it affects the fallback algorithm. For example, when\n * performing a lookup, if an entry is stale, it needs to be treated as\n * semantically equivalent to if the entry was not present at all.\n * \n * If there's logic that's not related to the fallback algorithm, though, we\n * should prefer to put it in cache.ts.\n */\n\n/**\n * Tracks the status of a cache entry as it progresses from no data (Empty),\n * waiting for server data (Pending), and finished (either Fulfilled or\n * Rejected depending on the response from the server.\n *\n * This is defined here, rather than in cache.ts, because cache-map.ts needs to\n * inspect the status when performing a `onlyMatchFulfilled` lookup.\n */\nexport const enum EntryStatus {\n Empty = 0,\n Pending = 1,\n Fulfilled = 2,\n Rejected = 3,\n}\n\n// The protocol that values must implement. In practice, the only types that\n// we ever actually deal with in this module are RouteCacheEntry,\n// SegmentCacheEntry, and BFCacheEntry; this is just to keep track of the\n// coupling so we don't leak concerns between the modules unnecessarily.\nexport interface MapValue {\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n status: EntryStatus\n}\n\n/**\n * Represents a node in the cache map and LRU.\n * MapEntry<V> structurally satisfies this interface for any V extends MapValue.\n *\n * The LRU can contain entries of different value types\n * (e.g., both RouteCacheEntry and SegmentCacheEntry). This interface captures\n * the common structure needed for cache map and LRU operations without\n * requiring knowledge of the specific value type.\n */\nexport interface MapEntry<V extends MapValue> {\n // Cache map structure fields\n parent: MapEntry<V> | null\n key: unknown\n map: Map<unknown, MapEntry<V>> | null\n value: V | null\n\n // LRU linked list fields\n prev: MapEntry<V> | null\n next: MapEntry<V> | null\n size: number\n}\n\n/**\n * A looser type for MapEntry\n * This allows the LRU to work with entries of different\n * value types while still providing type safety.\n *\n * The `map` field lets Map<unknown, MapEntry<V>> be assignable to this\n * type since we're only reading from the map, not inserting into it.\n */\nexport type UnknownMapEntry = {\n parent: UnknownMapEntry | null\n key: unknown\n map: Pick<Map<unknown, UnknownMapEntry>, 'get' | 'delete' | 'size'> | null\n value: MapValue | null\n\n prev: UnknownMapEntry | null\n next: UnknownMapEntry | null\n size: number\n}\n\n// The CacheMap type is just the root entry of the map.\nexport type CacheMap<V extends MapValue> = MapEntry<V>\n\nexport type FallbackType = { __brand: 'Fallback' }\nexport const Fallback = {} as FallbackType\n\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 = {}\n\nexport function createCacheMap<V extends MapValue>(): CacheMap<V> {\n const cacheMap: MapEntry<V> = {\n parent: null,\n key: null,\n value: null,\n map: null,\n\n // LRU-related fields\n prev: null,\n next: null,\n size: 0,\n }\n return cacheMap\n}\n\nfunction getOrInitialize<V extends MapValue>(\n cacheMap: CacheMap<V>,\n keys: VaryPathNode,\n isRevalidation: boolean\n): MapEntry<V> {\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: VaryPathNode | null = keys\n let key: unknown | null = 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\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\n // Otheriwse, create a child entry.\n key = Revalidation\n } else {\n // There are no more keys. This is the terminal entry.\n break\n }\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: MapEntry<V> = {\n parent: entry,\n key,\n value: null,\n map: null,\n\n // LRU-related fields\n prev: null,\n next: null,\n size: 0,\n }\n map.set(key, newEntry)\n entry = newEntry\n }\n\n return entry\n}\n\nexport function getFromCacheMap<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n rootEntry: CacheMap<V>,\n keys: VaryPathNode,\n isRevalidation: boolean,\n // When true, terminal entries whose status is not Fulfilled are skipped, so\n // the lookup falls through to a less-specific Fallback entry. Use this\n // during a navigation to prefer a Fulfilled shell entry over a more-specific\n // Pending entry that may still be in-flight. Callers that want to also\n // accept non-Fulfilled entries should perform a second lookup with this set\n // to false.\n onlyMatchFulfilled: boolean\n): V | null {\n const entry = getEntryWithFallbackImpl(\n now,\n currentCacheVersion,\n rootEntry,\n keys,\n isRevalidation,\n 0,\n onlyMatchFulfilled\n )\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}\n\nexport function isValueExpired(\n now: number,\n currentCacheVersion: number,\n value: MapValue\n): boolean {\n return value.staleAt <= now || value.version < currentCacheVersion\n}\n\nfunction lazilyEvictIfNeeded<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n entry: MapEntry<V>,\n onlyMatchFulfilled: boolean\n) {\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\n if (entry.value === null) {\n // This entry has no value, so there's nothing to evict.\n return entry\n }\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\n if (onlyMatchFulfilled && value.status !== EntryStatus.Fulfilled) {\n // The entry is fresh but is not Fulfilled. Treat as a non-match so the\n // recursion can continue and try a Fallback entry.\n return null\n }\n\n // The matched entry has not expired. Return it.\n return entry\n}\n\nfunction getEntryWithFallbackImpl<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n entry: MapEntry<V>,\n keys: VaryPathNode | null,\n isRevalidation: boolean,\n previousKey: unknown | null,\n onlyMatchFulfilled: boolean\n): MapEntry<V> | null {\n // This is similar to getExactEntry, but if an exact match is not found for\n // a key, it will return the fallback entry instead. This is recursive at\n // every level, e.g. an entry with keypath [a, Fallback, c, Fallback] is\n // valid match for [a, b, c, d].\n //\n // It will return the most specific match available.\n //\n // When `onlyMatchFulfilled` is true, terminal entries that aren't Fulfilled\n // are treated as non-matches, so the recursion will continue searching for\n // a Fallback match. See getFromCacheMap for the rationale.\n let key\n let remainingKeys: VaryPathNode | null\n if (keys !== null) {\n key = keys.value\n remainingKeys = keys.parent\n } else if (isRevalidation && previousKey !== Revalidation) {\n // During a revalidation, we append an internal \"Revalidation\" key to\n // the end of the keypath.\n key = Revalidation\n remainingKeys = null\n } else {\n // There are no more keys. This is the terminal entry.\n return lazilyEvictIfNeeded(\n now,\n currentCacheVersion,\n entry,\n onlyMatchFulfilled\n )\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(\n now,\n currentCacheVersion,\n existingEntry,\n remainingKeys,\n isRevalidation,\n key,\n onlyMatchFulfilled\n )\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(\n now,\n currentCacheVersion,\n fallbackEntry,\n remainingKeys,\n isRevalidation,\n key,\n onlyMatchFulfilled\n )\n }\n }\n return null\n}\n\nexport function setInCacheMap<V extends MapValue>(\n cacheMap: CacheMap<V>,\n keys: VaryPathNode,\n value: V,\n isRevalidation: boolean\n): void {\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\n // This is an LRU access. Move the entry to the front of the list.\n lruPut(entry)\n updateLruSize(entry, value.size)\n}\n\nfunction setMapEntryValue(entry: UnknownMapEntry, value: MapValue): void {\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\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\n entry.value = value\n value.ref = entry\n\n updateLruSize(entry, value.size)\n\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}\n\nexport function deleteFromCacheMap(value: MapValue): void {\n const entry = value.ref\n if (entry === null) {\n // This value is not a member of any map.\n return\n }\n\n dropRef(value)\n deleteMapEntry(entry)\n}\n\nfunction dropRef(value: MapValue): void {\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}\n\nexport function deleteMapEntry(entry: UnknownMapEntry): void {\n // Delete the entry from the cache.\n entry.value = null\n\n deleteFromLru(entry)\n\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 // The parent is not empty. Stop garbage collecting.\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}\n\nexport function setSizeInCacheMap<V extends MapValue>(\n value: V,\n size: number\n): void {\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","import type { CacheNode, Segment } from '../../../shared/lib/app-router-types'\nimport type React from 'react'\nimport {\n PrefetchHint,\n StaticAttemptHints,\n} from '../../../shared/lib/app-router-types'\nimport {\n createVaryParams,\n readVaryParams,\n SEARCH_PARAMS_VARY_ID,\n type VaryParams,\n} from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport { readFulfilledValue } from '../../../shared/lib/rsc-transport'\nimport {\n NEXT_DID_POSTPONE_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STALE_TIME_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_CONTENT_TYPE_HEADER,\n RSC_HEADER,\n} from '../app-router-headers'\nimport {\n createFetch,\n createFromNextReadableStream,\n decodeBufferedStage,\n resolveShellStageResponse,\n type RSCResponse,\n type RequestHeaders,\n} from '../router-reducer/fetch-server-response'\nimport { fetch } from './fetch'\nimport {\n pingPrefetchTask,\n isPrefetchTaskDirty,\n type PrefetchTask,\n type PrefetchSubtaskResult,\n} from './scheduler'\nimport {\n type RouteVaryPath,\n type VaryPath,\n type PartialVaryPath,\n getRouteVaryPath,\n getFulfilledRouteVaryPath,\n getFulfilledSegmentVaryPath,\n getSegmentVaryPathForRequest,\n getShellSegmentVaryPath,\n cloneVaryPathWithNewSearchParams,\n getPartialVaryPath,\n} from './vary-path'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n NormalizedNextUrl,\n RouteCacheKey,\n} from './cache-key'\nimport { createCacheKey as createPrefetchRequestKey } from './cache-key'\nimport {\n getPathnameFromRequestURL,\n getRenderedPathname,\n getRenderedSearch,\n normalizeRenderedSearch,\n} from '../../route-params'\nimport {\n createCacheMap,\n getFromCacheMap,\n setInCacheMap,\n setSizeInCacheMap,\n deleteFromCacheMap,\n isValueExpired,\n EntryStatus,\n type CacheMap,\n type UnknownMapEntry,\n} from './cache-map'\nexport { EntryStatus } from './cache-map'\nimport {\n appendSegmentRequestKeyPart,\n convertSegmentPathToStaticExportFilename,\n createSegmentRequestKeyPart,\n HEAD_REQUEST_KEY,\n ROOT_SEGMENT_REQUEST_KEY,\n type SegmentRequestKey,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport type {\n DynamicNavigationFlightResponse,\n FlightRouterState,\n NavigationFlightResponse,\n PrefetchFlightResponse,\n} from '../../../shared/lib/app-router-types'\nimport { prepareFlightRouterStateForRequest } from '../../flight-data-helpers'\nimport { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'\nimport { pingVisibleLinks } from '../links'\nimport { FetchStrategy } from './types'\nimport { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'\nimport { readFromBFCache, UnknownDynamicStaleTime } from './bfcache'\nimport {\n discoverKnownRoute,\n matchKnownRoute,\n type KnownRoutePart,\n} from './optimistic-routes'\nimport {\n createNavigationSeed,\n decodeTransportTreeIntoRouteTree,\n createRouteTreeNode,\n readFulfilledStaleTimeSeconds,\n} from './decode-server-response'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\n\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 */\nexport function getStaleTimeMs(staleTimeSeconds: number): number {\n return Math.max(staleTimeSeconds, 30) * 1000\n}\n\n// How long a rejected cache entry blocks re-fetching before it may be\n// retried (its staleAt is set this far in the future).\nconst REJECTION_BACKOFF_MS = 10 * 1000\n\n/**\n * The staleAt to reject entries with when a prefetch fails: if we're\n * offline, expire immediately (-1) so the entry is re-fetched once the\n * scheduler is re-pinged after connectivity is restored; otherwise apply a\n * short backoff. (Unlike navigations and server actions, prefetches don't\n * await `waitForConnection`.)\n */\nfunction getPrefetchErrorStaleAt(error: unknown): number {\n if (process.env.__NEXT_USE_OFFLINE) {\n const { checkOfflineError } =\n require('../offline') as typeof import('../offline')\n if (checkOfflineError(error)) {\n return -1\n }\n }\n return Date.now() + REJECTION_BACKOFF_MS\n}\n\n// A note on async/await when working in the prefetch cache:\n//\n// Most async operations in the prefetch cache should *not* use async/await,\n// Instead, spawn a subtask that writes the results to a cache entry, and attach\n// a \"ping\" listener to notify the prefetch queue to try again.\n//\n// The reason is we need to be able to access the segment cache and traverse its\n// data structures synchronously. For example, if there's a synchronous update\n// we can take an immediate snapshot of the cache to produce something we can\n// render. Limiting the use of async/await also makes it easier to avoid race\n// conditions, which is especially important because is cache is mutable.\n//\n// Another reason is that while we're performing async work, it's possible for\n// existing entries to become stale, or for Link prefetches to be removed from\n// the queue. For optimal scheduling, we need to be able to \"cancel\" subtasks\n// that are no longer needed. So, when a segment is received from the server, we\n// restart from the root of the tree that's being prefetched, to confirm all the\n// parent segments are still cached. If the segment is no longer reachable from\n// the root, then it's effectively canceled. This is similar to the design of\n// Rust Futures, or React Suspense.\n\n/**\n * The output of a single segment from an RSC server response, stored\n * directly on the RouteTree node it describes.\n *\n * `rsc` may be null: that means the response skipped this segment — it\n * acknowledged the position without rendering it (e.g. an ancestor of a\n * rendered subtree that the client is expected to already have). This is\n * distinct from the RouteTree node's `data` slot being null, which means\n * the response carried no information about the segment at all.\n */\nexport type RSCSegmentData = {\n rsc: React.ReactNode\n /**\n * Whether anything in the segment's output is not fully resolved:\n * dynamic holes, runtime holes, anything suspended.\n * Resolved at the decode boundary from whichever signal is authoritative\n * for the response's wire form: the staged per-node encoding of\n * per-segment prefetch responses, or the response-level partiality for\n * boolean-form responses (see the `isPartial` derivation in\n * decodeTransportNode).\n *\n * This absolute definition holds for every settled cache entry too; the\n * one deliberate exception is a Pending Full entry, which pre-sets\n * `isPartial: false` before any data exists (see the Pending-Full\n * convention in upgradeToPendingSegment).\n */\n isPartial: boolean\n /**\n * The source of the params this segment's output depends on (root params\n * included). Null means unknown — tracking wasn't enabled, or the decode\n * had no root params to union in — so consumers key on all params.\n */\n varyParams: VaryParams | null\n /**\n * The segment's own staleTime in seconds, when the response carries one\n * (per-segment prefetch responses only — see TransportSegmentData['s']).\n * Null means the response-level staleness governs this segment.\n */\n staleTimeSeconds: number | null\n}\n\nexport type RouteTree<TData> = {\n requestKey: SegmentRequestKey\n segment: Segment\n varyPath: VaryPath\n // The vary path used for shell-scoped keying of this segment: the\n // segment's vary path with every non-root param replaced with Fallback\n // (see getShellSegmentVaryPath), so one shell-tier entry serves all param\n // values below the root. Precomputed once during tree construction so we\n // don't have to recompute it on every shell request.\n shellVaryPath: VaryPath\n refreshState: RefreshState | null\n data: TData\n // Keyed by parallel route slot name. Stored as a Map rather than a plain\n // object because slot names are app-defined; with a plain object, every\n // distinct combination of slot names creates a different hidden class,\n // making keyed access to the slots megamorphic.\n slots: null | Map<string, RouteTree<TData>>\n // Bitmask of PrefetchHint flags. Encodes route structure metadata:\n // root layout, loading boundaries, instant configs, and runtime prefetch\n // hints.\n prefetchHints: number\n}\n\nexport type RefreshState = {\n canonicalUrl: string\n renderedSearch: NormalizedSearch\n}\n\n// A route's complete render structure. The head is fetched, cached, and\n// rendered like a page segment, but it has no position in the route tree, so\n// it sits beside the tree as its own one-node tree (see\n// createMetadataRouteTree). This is the shape a server response decodes to,\n// the router state holds, and a navigation produces.\nexport type RootRouteTree<TData> = {\n tree: RouteTree<TData>\n head: RouteTree<TData>\n}\n\nexport function createRootRouteTree<TData>(\n tree: RouteTree<TData>,\n head: RouteTree<TData>\n): RootRouteTree<TData> {\n return { tree, head }\n}\n\nexport function doesRouteStructureMatch<TCurrent, TNext>(\n currentTree: RouteTree<TCurrent>,\n nextTree: RouteTree<TNext>\n): boolean {\n // The request key includes the param names and types, but not the values.\n if (currentTree.requestKey !== nextTree.requestKey) {\n return false\n }\n // The root request key is always empty (even for global Not Found), so we\n // have to compare the root segment directly.\n return (\n nextTree.requestKey !== ROOT_SEGMENT_REQUEST_KEY ||\n currentTree.segment === nextTree.segment\n )\n}\n\ntype RouteCacheEntryShared = {\n // This is false only if we're certain the route cannot be intercepted. It's\n // true in all other cases, including on initialization when we haven't yet\n // received a response from the server.\n couldBeIntercepted: boolean\n\n // The node in the known route tree whose pattern this entry was predicted\n // from (see matchKnownRoute); the path from the root to that node is the\n // URL shape. Null for entries the server resolved. A predicted entry is a\n // guess that the URL's rewrite (if any) behaves statically; if the server's\n // rendered tree diverges from it, the node is marked so the shape is never\n // predicted again (see KnownRoutePart.hasDynamicRewrite).\n //\n // This is declared on every entry variant (not just fulfilled entries) so\n // that all RouteCacheEntry objects share a single hidden class; it is\n // pre-initialized to `null` when the entry is created.\n predictedFrom: KnownRoutePart | null\n\n // Map-related fields.\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\nexport type PendingRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Empty | EntryStatus.Pending\n blockedTasks: Set<PrefetchTask> | null\n canonicalUrl: null\n renderedSearch: null\n root: null\n supportsPerSegmentPrefetching: false\n}\n\ntype RejectedRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Rejected\n blockedTasks: Set<PrefetchTask> | null\n canonicalUrl: null\n renderedSearch: null\n root: null\n supportsPerSegmentPrefetching: boolean\n}\n\nexport type FulfilledRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Fulfilled\n blockedTasks: null\n canonicalUrl: string\n renderedSearch: NormalizedSearch\n root: RootRouteTree<null>\n supportsPerSegmentPrefetching: boolean\n}\n\nexport type RouteCacheEntry =\n | PendingRouteCacheEntry\n | FulfilledRouteCacheEntry\n | RejectedRouteCacheEntry\n\ntype SegmentCacheEntryShared = {\n /**\n * The fetch strategy this entry's content EFFECTIVELY corresponds to,\n * which may be deeper than the strategy that requested it: an entry is\n * recorded at the tier of the payload that fully satisfied it (e.g. a\n * shell-spawned entry fulfilled by a response whose shell IS the full\n * response is recorded at the concrete tier — and keyed by it too: without\n * server vary evidence the entry is re-keyed to the concrete vary path\n * rather than parked in the shell slot; see the keying derivation in\n * writeSegmentDataIntoCache). Compared via\n * `canNewFetchStrategyProvideMoreContent` to decide whether a new request\n * could yield more content than what's already cached.\n *\n * \"Effectively\" spans both of the tier axes, static-vs-runtime included: a\n * static response that accessed no runtime data is as complete as a runtime\n * response of the same variant, so it records the RUNTIME tier (see\n * `recordedFetchStrategy` in writeSegmentDataIntoCache). That is what lets\n * \"would a runtime request return more?\" be answered by comparing tiers,\n * with no separate per-entry signal — the question the scheduler asks in\n * `wouldRuntimeRequestProvideMore`.\n */\n fetchStrategy: FetchStrategy\n\n /**\n * True if this entry was fulfilled from a fallback shell response (the page\n * had not yet been prerendered with concrete params). The scheduler uses\n * this to retry the static prefetch, since a more complete version may\n * become available once the server's background regeneration finishes.\n *\n * Distinct from `isPartial`: a fully-prerendered PPR page can have partial\n * segments that should NOT be retried. See `NavigationFlightResponse['f']`.\n */\n isUpgradeableISRFallback: boolean\n\n // Map-related fields.\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\nexport type EmptySegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Empty\n blockedTasks: Set<PrefetchTask> | null\n rsc: null\n isPartial: true\n promise: null\n}\n\nexport type PendingSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Pending\n blockedTasks: Set<PrefetchTask> | null\n rsc: null\n // True while pending (there's no output yet, so nothing is resolved),\n // with one deliberate exception: a Pending Full entry pre-sets false as a\n // \"may be omitted from navigation requests\" signal before any data\n // exists — see the Pending-Full convention in upgradeToPendingSegment.\n isPartial: boolean\n promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>\n}\n\ntype RejectedSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Rejected\n blockedTasks: Set<PrefetchTask> | null\n rsc: null\n isPartial: true\n promise: null\n}\n\nexport type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Fulfilled\n blockedTasks: null\n rsc: React.ReactNode | null\n isPartial: boolean\n // The source of the params `rsc` depends on, recorded under exactly the\n // condition the entry's key trusts it (see the re-key derivation in\n // writeSegmentDataIntoCache). Null means unknown: consumers assume the\n // output depends on every param. A navigation that renders this entry's\n // `rsc` as its final data carries it onto the CacheNode.\n varyParams: VaryParams | null\n promise: null\n}\n\nexport type SegmentCacheEntry =\n | EmptySegmentCacheEntry\n | PendingSegmentCacheEntry\n | RejectedSegmentCacheEntry\n | FulfilledSegmentCacheEntry\n\nexport type NonEmptySegmentCacheEntry = Exclude<\n SegmentCacheEntry,\n EmptySegmentCacheEntry\n>\n\nconst isOutputExportMode =\n process.env.NODE_ENV === 'production' &&\n process.env.__NEXT_CONFIG_OUTPUT === 'export'\n\nexport const MetadataOnlyRequestTree: FlightRouterState = [\n '',\n {},\n null,\n 'metadata-only',\n]\n\nconst routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()\n\n/**\n * The shared segment cache map. Segment cache functions do not access this\n * ambiently — every unit of work is bound to a map when it is created, and\n * reads and writes receive that map explicitly:\n *\n * - A prefetch task captures its map when it is scheduled\n * (`PrefetchTask.segmentCacheMap` in scheduler.ts). Almost always this one;\n * a task scheduled while the Instant Navigation Testing lock is held gets\n * the lock scope's private map instead (which starts empty and is discarded\n * at release), so a locked navigation observes only data fetched under the\n * lock — never a stale entry left in the shared cache by an earlier\n * navigation, prefetch, or scope.\n * - A locked navigation inherits the map of the prefetch task that drives it\n * (see `ensurePrefetchThenNavigate` in navigation.ts).\n * - Everything else — unlocked navigations, hydration, and router work that\n * is not a captured navigation (refreshes, history-traversal restores,\n * server-action redirects, server patches) — uses this shared map\n * directly, even while a lock is held.\n *\n * Binding at creation means a task queued before a lock scope begins never\n * leaks entries into the scope's map (or reads out of it), and a scope task's\n * late responses never leak into the shared map.\n */\nexport const segmentCacheMap: CacheMap<SegmentCacheEntry> = createCacheMap()\n\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: Set<PrefetchTask> | null = null\n\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\n\nexport function getCurrentRouteCacheVersion(): number {\n return currentRouteCacheVersion\n}\n\nexport function getCurrentSegmentCacheVersion(): number {\n return currentSegmentCacheVersion\n}\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 */\nexport function invalidateEntirePrefetchCache(\n nextUrl: string | null,\n root: RootRouteTree<CacheNode>\n): void {\n currentRouteCacheVersion++\n currentSegmentCacheVersion++\n\n pingVisibleLinks(nextUrl, root)\n pingInvalidationListeners(nextUrl, root)\n}\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 */\nexport function invalidateRouteCacheEntries(\n nextUrl: string | null,\n root: RootRouteTree<CacheNode>\n): void {\n currentRouteCacheVersion++\n\n pingVisibleLinks(nextUrl, root)\n pingInvalidationListeners(nextUrl, root)\n}\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 */\nexport function invalidateSegmentCacheEntries(\n nextUrl: string | null,\n root: RootRouteTree<CacheNode>\n): void {\n currentSegmentCacheVersion++\n\n pingVisibleLinks(nextUrl, root)\n pingInvalidationListeners(nextUrl, root)\n}\n\nfunction attachInvalidationListener(task: PrefetchTask): void {\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([task])\n } else {\n invalidationListeners.add(task)\n }\n }\n}\n\nfunction notifyInvalidationListener(task: PrefetchTask): void {\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\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}\n\nexport function pingInvalidationListeners(\n nextUrl: string | null,\n root: RootRouteTree<CacheNode>\n): void {\n // The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.\n // This is called when the Next-Url or the base tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n if (invalidationListeners !== null) {\n const tasks = invalidationListeners\n invalidationListeners = null\n for (const task of tasks) {\n if (isPrefetchTaskDirty(task, nextUrl, root)) {\n notifyInvalidationListener(task)\n }\n }\n }\n}\n\nexport function readRouteCacheEntry(\n now: number,\n key: RouteCacheKey\n): RouteCacheEntry | null {\n const varyPath: RouteVaryPath = getRouteVaryPath(\n key.pathname,\n key.search,\n key.nextUrl\n )\n const isRevalidation = false\n const existingEntry = getFromCacheMap(\n now,\n getCurrentRouteCacheVersion(),\n routeCacheMap,\n varyPath,\n isRevalidation,\n false\n )\n if (existingEntry !== null) {\n return existingEntry\n }\n\n // No cache hit. Attempt to construct from template using the new\n // optimistic routing mechanism (pattern-based matching).\n if (process.env.__NEXT_OPTIMISTIC_ROUTING) {\n return matchKnownRoute(now, key.pathname, key.search)\n }\n\n return null\n}\n\n/**\n * Reads the cache entry for a segment during a navigation. Unlike a plain\n * lookup, prefers a Fulfilled entry over a more-specific Pending or Rejected\n * entry: during a navigation, a less-specific shell entry (e.g. params ->\n * Fallback) should be rendered immediately rather than blocking on a\n * more-specific Pending entry that may still be in-flight.\n *\n * Performs up to two lookups:\n * 1. An `onlyMatchFulfilled` lookup that walks past Pending/Rejected entries\n * at more-specific keypaths to find a Fulfilled fallback (e.g. a cached\n * shell).\n * 2. If no Fulfilled entry is found, a regular lookup that returns the most\n * specific match regardless of status.\n */\nexport function readSegmentCacheEntryForNavigation(\n now: number,\n // The map the navigation is bound to: a locked navigation's driving-task\n // map, or the shared map otherwise.\n map: CacheMap<SegmentCacheEntry>,\n varyPath: VaryPath,\n restrictToShell: boolean = false\n): SegmentCacheEntry | null {\n const isRevalidation = false\n\n let lookupVaryPath = varyPath\n if (process.env.__NEXT_EXPOSE_TESTING_API && restrictToShell) {\n // Instant Navigation Testing API: we're navigating to a link that 1) has\n // Partial Prefetching enabled, and 2) does not have a prefetch prop set.\n // Only the shell may render, not anything that varies on concrete route\n // params.\n lookupVaryPath = getShellSegmentVaryPath(varyPath)\n }\n\n // Prefer a Fulfilled entry (e.g. a cached shell) over a more-specific\n // Pending/Rejected one so it renders immediately instead of blocking on an\n // in-flight entry.\n const fulfilled = getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n map,\n lookupVaryPath,\n isRevalidation,\n true\n )\n if (fulfilled !== null) {\n return fulfilled\n }\n return getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n map,\n lookupVaryPath,\n isRevalidation,\n false\n )\n}\n\nfunction readRevalidatingSegmentCacheEntry(\n now: number,\n map: CacheMap<SegmentCacheEntry>,\n varyPath: VaryPath\n): SegmentCacheEntry | null {\n const isRevalidation = true\n return getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n map,\n varyPath,\n isRevalidation,\n false\n )\n}\n\nexport function waitForSegmentCacheEntry(\n pendingEntry: PendingSegmentCacheEntry\n): Promise<FulfilledSegmentCacheEntry | null> {\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 =\n createPromiseWithResolvers<FulfilledSegmentCacheEntry | null>()\n } else {\n // There's already a promise we can use\n }\n return promiseWithResolvers.promise\n}\n\nfunction createDetachedRouteCacheEntry(): PendingRouteCacheEntry {\n return {\n canonicalUrl: null,\n status: EntryStatus.Empty,\n blockedTasks: null,\n root: null,\n // This is initialized to true because we don't know yet whether the route\n // could be intercepted. It's only set to false once we receive a response\n // from the server.\n couldBeIntercepted: true,\n // Similarly, we don't yet know if the route supports PPR.\n supportsPerSegmentPrefetching: false,\n predictedFrom: null,\n renderedSearch: null,\n\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/**\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 */\nexport function readOrCreateRouteCacheEntry(\n now: number,\n task: PrefetchTask,\n key: RouteCacheKey\n): RouteCacheEntry {\n attachInvalidationListener(task)\n\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: RouteVaryPath = getRouteVaryPath(\n key.pathname,\n key.search,\n key.nextUrl\n )\n const isRevalidation = false\n setInCacheMap(routeCacheMap, varyPath, pendingEntry, isRevalidation)\n return pendingEntry\n}\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(\n now: number,\n requestedUrl: URL,\n nextUrl: string | null\n): FulfilledRouteCacheEntry | null {\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\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 as NormalizedSearch\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(\n now,\n createPrefetchRequestKey(urlWithoutSearchParams.href, nextUrl)\n )\n\n if (\n routeWithNoSearchParams === null ||\n routeWithNoSearchParams.status !== EntryStatus.Fulfilled\n ) {\n // Bail out of constructing an optimistic route tree. This will result in\n // a blocking, unprefetched navigation.\n return null\n }\n\n // Now we have a base route tree we can \"patch\" with our optimistic values.\n\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(\n routeWithNoSearchParams.canonicalUrl,\n requestedUrl.origin\n )\n const optimisticCanonicalSearch =\n canonicalUrlForRouteWithNoSearchParams.search !== ''\n ? // Base route was redirected. Reuse the same redirected search string.\n canonicalUrlForRouteWithNoSearchParams.search\n : requestedSearch\n\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 =\n routeWithNoSearchParams.renderedSearch !== ''\n ? // Base route was rewritten. Reuse the same rewritten search string.\n routeWithNoSearchParams.renderedSearch\n : normalizeRenderedSearch(requestedSearch)\n\n const optimisticUrl = new URL(\n routeWithNoSearchParams.canonicalUrl,\n location.origin\n )\n optimisticUrl.search = optimisticCanonicalSearch\n const optimisticCanonicalUrl = createHrefFromUrl(optimisticUrl)\n\n const optimisticRouteTree = deprecated_createOptimisticRouteTree(\n routeWithNoSearchParams.root.tree,\n optimisticRenderedSearch\n )\n const baseMetadataTree = routeWithNoSearchParams.root.head\n const optimisticMetadataTree = createMetadataRouteTree(\n cloneVaryPathWithNewSearchParams(\n baseMetadataTree.varyPath,\n optimisticRenderedSearch\n ),\n baseMetadataTree.prefetchHints,\n null\n )\n\n // Clone the base route tree, and override the relevant fields with our\n // optimistic values.\n const optimisticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: optimisticCanonicalUrl,\n\n status: EntryStatus.Fulfilled,\n // This isn't cloned because it's instance-specific\n blockedTasks: null,\n root: createRootRouteTree(optimisticRouteTree, optimisticMetadataTree),\n couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,\n supportsPerSegmentPrefetching:\n routeWithNoSearchParams.supportsPerSegmentPrefetching,\n predictedFrom: null,\n\n // Override the rendered search with the optimistic value.\n renderedSearch: optimisticRenderedSearch,\n\n // Map-related fields\n ref: null,\n size: 0,\n staleAt: routeWithNoSearchParams.staleAt,\n version: routeWithNoSearchParams.version,\n }\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}\n\nfunction deprecated_createOptimisticRouteTree(\n tree: RouteTree<null>,\n newRenderedSearch: NormalizedSearch\n): RouteTree<null> {\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\n let clonedSlots: Map<string, RouteTree<null>> | null = null\n const originalSlots = tree.slots\n if (originalSlots !== null) {\n clonedSlots = new Map()\n for (const [parallelRouteKey, childTree] of originalSlots) {\n clonedSlots.set(\n parallelRouteKey,\n deprecated_createOptimisticRouteTree(childTree, newRenderedSearch)\n )\n }\n }\n\n // The shell vary path Fallbacks search params, so it's unaffected by the\n // new rendered search and can be reused as-is.\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n shellVaryPath: tree.shellVaryPath,\n refreshState: tree.refreshState,\n // Optimistic trees are structure-only. (The input tree comes from the\n // route cache, which never carries render output.)\n data: null,\n varyPath: cloneVaryPathWithNewSearchParams(\n tree.varyPath,\n newRenderedSearch\n ),\n slots: clonedSlots,\n prefetchHints: tree.prefetchHints,\n }\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 */\nexport function readOrCreateSegmentCacheEntry(\n now: number,\n // The map the calling task operates in (`PrefetchTask.segmentCacheMap`,\n // captured when the task was scheduled).\n map: CacheMap<SegmentCacheEntry>,\n fetchStrategy: FetchStrategy,\n tree: RouteTree<RSCSegmentData | null>\n): SegmentCacheEntry {\n const existingEntry = getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n map,\n tree.varyPath,\n false,\n false\n )\n if (existingEntry !== null) {\n return existingEntry\n }\n return insertEmptySegmentCacheEntry(now, map, fetchStrategy, tree)\n}\n\n/**\n * Creates an empty segment cache entry and inserts it into the cache, keyed\n * at the vary path a request made with the given fetch strategy is stored\n * under. The stale time is set to a default value; the actual stale time will\n * be set when the entry is fulfilled with data from the server response.\n */\nfunction insertEmptySegmentCacheEntry(\n now: number,\n map: CacheMap<SegmentCacheEntry>,\n fetchStrategy: FetchStrategy,\n tree: RouteTree<RSCSegmentData | null>\n): EmptySegmentCacheEntry {\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const emptyEntry = createDetachedSegmentCacheEntry(now)\n const isRevalidation = false\n setInCacheMap(map, varyPathForRequest, emptyEntry, isRevalidation)\n return emptyEntry\n}\n\nexport function readOrCreateRevalidatingSegmentEntry(\n now: number,\n // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\n map: CacheMap<SegmentCacheEntry>,\n fetchStrategy: FetchStrategy,\n tree: RouteTree<RSCSegmentData | null>\n): SegmentCacheEntry {\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\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(\n now,\n map,\n tree.varyPath\n )\n if (existingEntry !== null) {\n return existingEntry\n }\n // Create a pending entry and add it to the cache. The stale time is set to a\n // default value; the actual stale time will be set when the entry is\n // fulfilled with data from the server response.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(now)\n const isRevalidation = true\n setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)\n return pendingEntry\n}\n\nexport function overwriteRevalidatingSegmentCacheEntry(\n now: number,\n // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\n map: CacheMap<SegmentCacheEntry>,\n fetchStrategy: FetchStrategy,\n tree: RouteTree<RSCSegmentData | null>\n) {\n // This function is called when we've already decided to replace an existing\n // revalidation entry. Create a new entry and write it into the cache,\n // overwriting the previous value. The stale time is set to a default value;\n // the actual stale time will be set when the entry is fulfilled with data\n // from the server response.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(now)\n const isRevalidation = true\n setInCacheMap(map, varyPathForRequest, pendingEntry, isRevalidation)\n return pendingEntry\n}\n\n/**\n * Whether an existing cache entry is preferred over an incoming candidate —\n * i.e. the candidate does NOT supersede it. (On an exact tie — same fetch\n * strategy, same partialness — this returns false, so the candidate replaces\n * the existing entry.) This is the precedence rule used both when deciding\n * whether an upsert may replace the entry at its own keypath, and when\n * deciding whether an entry at a more specific keypath may be evicted because\n * it shadows a just-inserted candidate (see `evictShadowingSegmentEntries`).\n *\n * Note that \"less/more specific\" in the comments below refers to fetch\n * strategy content tiers (how much content a strategy can produce), not the\n * vary-path specificity the eviction docs are concerned with.\n */\nfunction isExistingSegmentEntryPreferred(\n existingEntry: SegmentCacheEntry,\n candidateEntry: SegmentCacheEntry\n): boolean {\n if (existingEntry.status === EntryStatus.Empty) {\n // An Empty entry is a placeholder that carries no data, and its\n // fetchStrategy is a spawn-time default, not a fact about any content —\n // it must never win a precedence comparison. (Without this, a candidate\n // fetched at a tier below the placeholder's default would be discarded\n // in favor of an entry with nothing in it.)\n return false\n }\n return (\n // We fetched the new segment using a different, less specific fetch\n // strategy than the segment we already have in the cache, so it can't\n // have more content.\n (candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&\n !canNewFetchStrategyProvideMoreContent(\n existingEntry.fetchStrategy,\n candidateEntry.fetchStrategy\n )) ||\n // 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 )\n}\n\nexport function upsertSegmentEntry(\n now: number,\n // The map the whole upsert (existing-entry read, insert, shadow eviction)\n // operates in. Prefetch response-write paths pass the spawning task's map\n // (`PrefetchTask.segmentCacheMap`), so a response that lands after a\n // testing-lock scope boundary still writes into the map its entries\n // live in.\n map: CacheMap<SegmentCacheEntry>,\n varyPath: VaryPath,\n candidateEntry: SegmentCacheEntry,\n // The fully concrete vary path a read for this segment position resolves\n // against (all concrete param values, i.e. `tree.varyPath`) — the most\n // specific path a read would use. Note this is the opposite of the\n // generalized keying path that `getSegmentVaryPathForRequest` computes.\n // Used to detect and evict stale entries at more specific keypaths that\n // would otherwise shadow the candidate. Pass null when there's no request\n // context; the shadow check is skipped.\n lookupVaryPath: VaryPath | null\n): SegmentCacheEntry | null {\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\n if (isValueExpired(now, getCurrentSegmentCacheVersion(), candidateEntry)) {\n // The entry is expired. We cannot upsert it.\n return null\n }\n\n const existingEntry = getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n map,\n varyPath,\n false,\n false\n )\n if (existingEntry !== null) {\n // Don't replace a more specific segment with a less-specific one. A case where this\n // might happen is if the existing segment was fetched via\n // `<Link prefetch={true}>`.\n if (isExistingSegmentEntryPreferred(existingEntry, candidateEntry)) {\n // The candidate does not supersede the existing entry. Leave the\n // existing entry in place and discard the candidate by not inserting it.\n //\n // We must not mutate the candidate here (e.g. downgrade it to Rejected or\n // null out its `rsc`). The caller does not transfer exclusive ownership\n // of it: it may already have been fulfilled, resolving its promise to a\n // waiter that holds the entry and reads `rsc` off it later. A navigation\n // seed is such a waiter, via `waitForSegmentCacheEntry`. Nulling `rsc`\n // after the fact resolves that read to `null`, so the waiter loses the\n // data it was about to render. Declining to insert it is enough: the\n // existing entry stays canonical, and the candidate keeps its valid (if\n // less complete) data for any waiter that already took it.\n return null\n }\n\n // Ping any tasks blocked on the existing entry before replacing it so they\n // re-run and pick up the new entry. Without this, tasks waiting on the\n // existing Empty/Pending entry would be stranded — the new fulfilled\n // candidate has no blockedTasks of its own.\n if (\n existingEntry.status === EntryStatus.Empty ||\n existingEntry.status === EntryStatus.Pending\n ) {\n pingBlockedTasks(existingEntry)\n }\n\n // Replace the existing entry by writing the candidate over its keypath\n // below (the same mechanism `overwriteRevalidatingSegmentCacheEntry`\n // uses). We intentionally do NOT call `deleteFromCacheMap` first: deleting\n // vacates the canonical slot, and `deleteMapEntry` promotes a pending\n // Revalidation-slot entry into the vacated slot — which the immediate\n // insert below would then silently overwrite. The in-flight revalidation\n // would vanish from the map, so the next scheduler pass would find an\n // empty revalidation slot and spawn a duplicate request instead of\n // deduping against it. Replacing in place never vacates the slot, so\n // promotion never runs and the pending revalidating entry stays in its\n // Revalidation slot where `readOrCreateRevalidatingSegmentEntry`'s dedupe\n // finds it.\n //\n // The displaced entry's map/LRU accounting is handled by the replacement\n // itself: `setMapEntryValue` drops the displaced value's `ref` and\n // `updateLruSize` swaps its size for the candidate's, which is exactly\n // what delete-then-insert did.\n }\n\n const isRevalidation = false\n setInCacheMap(map, varyPath, candidateEntry, isRevalidation)\n\n if (lookupVaryPath !== null) {\n evictShadowingSegmentEntries(now, map, lookupVaryPath, candidateEntry)\n }\n\n return candidateEntry\n}\n\n/**\n * Evicts stale entries at more specific keypaths that shadow a just-inserted\n * candidate entry.\n *\n * A response can be written to the cache at a MORE GENERIC vary path than the\n * path the request was issued against — for example, the server may report\n * that a segment doesn't vary on a param, so the entry is re-keyed with that\n * param as Fallback. Meanwhile, an older, less useful entry can exist at a\n * more specific path within the same fallback chain — for example, a partial\n * shell entry keyed with root params concrete (see\n * `getShellSegmentVaryPath`). Because segment lookup is\n * most-specific-match-wins, every subsequent read at the concrete request\n * path keeps returning the stale specific entry, and the more complete\n * generic entry is unreachable from that URL. That both wastes the completed\n * request and can loop: a prefetch task that revalidated the segment reads\n * back the same stale entry, decides it needs to revalidate again, and\n * repeats forever.\n *\n * The upsert is the one moment we know the ordering between the two entries:\n * the candidate was produced by a request for this segment position, and\n * `lookupVaryPath` is the fully concrete path a read for that position\n * resolves against, so any entry that a read at that path would return in the\n * candidate's stead is directly comparable to it. If such an entry is settled\n * and the candidate supersedes it — under the same precedence rules the\n * upsert applies at its own keypath — we know we never want to match against\n * it again, so delete it, making the candidate reachable.\n *\n * Pending entries are never evicted here: they're owned by an in-flight\n * request that will settle them. Empty entries ARE evictable — they're\n * unclaimed placeholders with nothing in them, so they must not shadow real\n * data; their blocked tasks are pinged so they re-run against the candidate.\n */\nfunction evictShadowingSegmentEntries(\n now: number,\n map: CacheMap<SegmentCacheEntry>,\n lookupVaryPath: VaryPath,\n candidateEntry: SegmentCacheEntry\n): void {\n // There can in principle be multiple shadowing entries at successively less\n // specific keypaths, so loop until the read returns the candidate (or an\n // entry we don't supersede). Each iteration re-reads and re-checks from\n // scratch (in part because `deleteFromCacheMap` can promote a settled\n // Revalidation-slot value into the just-vacated slot, surfacing a new entry\n // at the same keypath). Each iteration deletes an entry from the map, so\n // the loop terminates naturally; the bound is defensive, and 32 is far\n // beyond any real fallback chain, which is bounded by the vary\n // path's length.\n for (let i = 0; i < 32; i++) {\n const shadowEntry = getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n map,\n lookupVaryPath,\n false,\n false\n )\n if (shadowEntry === null || shadowEntry === candidateEntry) {\n // The candidate is reachable from the lookup path (or the read missed\n // entirely, e.g. because the candidate expired). Done.\n return\n }\n if (shadowEntry.status === EntryStatus.Pending) {\n // A Pending entry may not be evicted: it's held by an in-flight\n // request and will settle on its own. (An Empty shadow entry, by\n // contrast, is an unclaimed placeholder with nothing in it — never\n // preferred over the candidate, per isExistingSegmentEntryPreferred —\n // so it falls through to the eviction below, waking any tasks blocked\n // on it so they re-run and find the candidate.)\n return\n }\n if (isExistingSegmentEntryPreferred(shadowEntry, candidateEntry)) {\n // The shadowing entry is preferred over the candidate (e.g. it's a\n // complete entry fetched with a more specific strategy). Leave it —\n // reads at this path should keep matching it.\n return\n }\n // The candidate supersedes the shadowing entry. Evict it. Settled entries\n // shouldn't have blocked tasks (Fulfilled always has `blockedTasks:\n // null`, and Rejected entries were pinged at rejection), but an Empty\n // entry may have them — ping before deleting, matching the upsert-evict\n // pattern above.\n pingBlockedTasks(shadowEntry)\n deleteFromCacheMap(shadowEntry)\n }\n}\n\nexport function createDetachedSegmentCacheEntry(\n now: number\n): EmptySegmentCacheEntry {\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: EmptySegmentCacheEntry = {\n status: EntryStatus.Empty,\n blockedTasks: null,\n // Default to assuming the fetch strategy will be PPR. This will be updated\n // when a fetch is actually initiated.\n fetchStrategy: FetchStrategy.PPR,\n rsc: null,\n isPartial: true,\n isUpgradeableISRFallback: false,\n promise: null,\n\n // Map-related fields\n ref: null,\n size: 0,\n staleAt,\n version: 0,\n }\n return emptyEntry\n}\n\nexport function upgradeToPendingSegment(\n emptyEntry: EmptySegmentCacheEntry,\n fetchStrategy: FetchStrategy\n): PendingSegmentCacheEntry {\n const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any\n pendingEntry.status = EntryStatus.Pending\n pendingEntry.fetchStrategy = fetchStrategy\n\n if (fetchStrategy === FetchStrategy.Full) {\n // The Pending-Full convention: pre-set isPartial to false before any\n // data exists. Normally partiality is absolute — anything unresolved in\n // the entry's output makes it true, and a pending entry has no output at\n // all — but a Full response is a complete navigation payload, so this\n // segment may already be omitted from navigation requests that happen\n // while the data is still in flight. That \"may be omitted\" signal is\n // exactly what isPartial: false means to a navigation, so this\n // deliberately breaks the absolute definition for the pending window.\n pendingEntry.isPartial = false\n }\n\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\n return pendingEntry\n}\n\nexport function attemptToFulfillDynamicSegmentFromBFCache(\n now: number,\n segment: EmptySegmentCacheEntry,\n tree: RouteTree<RSCSegmentData | null>\n): FulfilledSegmentCacheEntry | null {\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\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\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 =\n bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n if (now > dynamicPrefetchStaleAt) {\n return null\n }\n\n const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full)\n const isPartial = false\n return fulfillSegmentCacheEntry(\n pendingSegment,\n bfcacheEntry.rsc,\n dynamicPrefetchStaleAt,\n isPartial,\n bfcacheEntry.varyParams,\n // bfcache data is concrete, never an ISR fallback.\n false,\n FetchStrategy.Full\n )\n }\n return null\n}\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 */\nexport function attemptToUpgradeSegmentFromBFCache(\n now: number,\n // The map the calling task operates in (`PrefetchTask.segmentCacheMap`).\n map: CacheMap<SegmentCacheEntry>,\n tree: RouteTree<RSCSegmentData | null>\n): FulfilledSegmentCacheEntry | null {\n const varyPath = tree.varyPath\n const bfcacheEntry = readFromBFCache(varyPath)\n if (bfcacheEntry !== null) {\n const dynamicPrefetchStaleAt =\n bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n if (now > dynamicPrefetchStaleAt) {\n return null\n }\n const pendingSegment = upgradeToPendingSegment(\n createDetachedSegmentCacheEntry(now),\n FetchStrategy.Full\n )\n const isPartial = false\n const newEntry = fulfillSegmentCacheEntry(\n pendingSegment,\n bfcacheEntry.rsc,\n dynamicPrefetchStaleAt,\n isPartial,\n bfcacheEntry.varyParams,\n // bfcache data is concrete, never an ISR fallback.\n false,\n FetchStrategy.Full\n )\n const segmentVaryPath = getSegmentVaryPathForRequest(\n FetchStrategy.Full,\n tree\n )\n const upserted = upsertSegmentEntry(\n now,\n map,\n segmentVaryPath,\n newEntry,\n // The concrete lookup path this BFCache upgrade applies to. (In\n // practice a Full request path is already fully concrete, so nothing\n // can shadow the new entry and the shadow check is a no-op.)\n tree.varyPath\n )\n if (upserted !== null && upserted.status === EntryStatus.Fulfilled) {\n return upserted\n }\n }\n return null\n}\n\nfunction pingBlockedTasks(entry: {\n blockedTasks: Set<PrefetchTask> | null\n}): void {\n const blockedTasks = entry.blockedTasks\n if (blockedTasks !== null) {\n for (const task of blockedTasks) {\n pingPrefetchTask(task)\n }\n entry.blockedTasks = null\n }\n}\n\n/**\n * The head's request key on the client. The server's own key for the head,\n * HEAD_REQUEST_KEY, carries no path information: there is only one head per\n * URL, so the server has no need to distinguish parallel pages. On the client\n * the request key is the head's cache identity and what doesRouteStructureMatch\n * compares, so the head takes its page's request key with HEAD_REQUEST_KEY\n * appended — the key the server would have assigned had the head been a\n * segment below the page — and two pages' heads never match. The head varies\n * on the same params as its page, so the rest of its vary path is the page's.\n * The page must be the route's own: a page in a slot retained from another\n * URL (one with a refresh state) belongs to that URL's head. When a route has\n * multiple parallel pages of its own, the first one is used; the keys only\n * differ in route groups and slot names, so any of them works as long as it\n * is always the same one.\n */\nexport function getHeadRequestKey(\n pageRequestKey: SegmentRequestKey\n): SegmentRequestKey {\n return (pageRequestKey + HEAD_REQUEST_KEY) as SegmentRequestKey\n}\n\nexport function createMetadataRouteTree<TData>(\n metadataVaryPath: VaryPath,\n // The route root's prefetch hints. The head has no node of its own on the\n // wire, so the route-level hint that applies to it is copied from the root.\n rootPrefetchHints: number,\n // The head's payload, with the same lifetimes as a segment node's `data`\n // (see RouteTree): null in the route cache, the response's decoded\n // head on a navigation seed, a CacheNode on the router state.\n data: TData\n): RouteTree<TData> {\n // The head is a one-node tree beside the route tree (see RootRouteTree). It\n // has no position in the route tree, but it's fetched, cached, compared, and\n // rendered like a segment, so it is a RouteTree node like any other.\n const metadata: RouteTree<TData> = {\n // The first entry of the head's vary path (see getHeadRequestKey). The\n // server knows nothing of this key; it is always asked for\n // HEAD_REQUEST_KEY, which is why the segment stays the bare marker.\n requestKey: metadataVaryPath.value,\n segment: HEAD_REQUEST_KEY,\n shellVaryPath: getShellSegmentVaryPath(metadataVaryPath),\n refreshState: null,\n data,\n varyPath: metadataVaryPath,\n slots: null,\n // Only the static-attempt bits apply to the head: it's a route-level\n // fact (\"static per-segment responses may exist for this route\"), and\n // it's what lets a shell-tier cached head attempt a static head fetch\n // before deopting to a runtime request (see the shell-tier eligibility\n // check in pingSegmentBundle). The other bits describe tree structure\n // the head doesn't participate in.\n prefetchHints: rootPrefetchHints & StaticAttemptHints,\n }\n return metadata\n}\n\n/**\n * Returns an equivalent tree with `data: null` at every node, cloning only\n * the subtrees that carry data. Called when a tree is stored in the route\n * cache: route cache entries live indefinitely, so retaining render output\n * there would pin RSC payloads in memory outside the segment cache's eviction\n * control. See the lifecycle note on RouteTree.\n */\nfunction stripDataFromRouteTree(\n tree: RouteTree<RSCSegmentData | null>\n): RouteTree<null> {\n let clonedSlots: Map<string, RouteTree<null>> | null = null\n const slots = tree.slots\n if (slots !== null) {\n for (const [parallelRouteKey, childTree] of slots) {\n const strippedChild = stripDataFromRouteTree(childTree)\n if (strippedChild !== childTree && clonedSlots === null) {\n // Sound cast: any copied value that isn't overwritten below is one\n // where stripDataFromRouteTree returned the child unchanged, which\n // means that subtree carries no data.\n clonedSlots = new Map(slots) as Map<string, RouteTree<null>>\n }\n if (clonedSlots !== null) {\n clonedSlots.set(parallelRouteKey, strippedChild)\n }\n }\n }\n if (tree.data === null && clonedSlots === null) {\n // Neither this node nor any descendant carries data. Reuse it as-is.\n // This is the common case for trees that never carried render output\n // (e.g. route tree prefetch responses). Sound cast for the same reason.\n return tree as RouteTree<null>\n }\n // Sound cast: clonedSlots is null here only if every child subtree was\n // verified data-free by the loop above.\n const strippedSlots = (clonedSlots ?? slots) as Map<\n string,\n RouteTree<null>\n > | null\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n shellVaryPath: tree.shellVaryPath,\n refreshState: tree.refreshState,\n data: null,\n varyPath: tree.varyPath,\n slots: strippedSlots,\n prefetchHints: tree.prefetchHints,\n }\n}\n\nexport function fulfillRouteCacheEntry(\n now: number,\n entry: PendingRouteCacheEntry,\n root: RootRouteTree<RSCSegmentData | null>,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n renderedSearch: NormalizedSearch,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n const tree = root.tree\n const fulfilledEntry: FulfilledRouteCacheEntry = entry as any\n fulfilledEntry.status = EntryStatus.Fulfilled\n fulfilledEntry.root = createRootRouteTree(\n stripDataFromRouteTree(tree),\n stripDataFromRouteTree(root.head)\n )\n // Route structure is essentially static — it only changes on deploy.\n // Always use the static stale time.\n // NOTE: An exception is rewrites/redirects in middleware or proxy, which can\n // change routes dynamically. We have other strategies for handling those.\n //\n // If the route tree has stale inlining hints (e.g. the initial RSC payload\n // for a build-time static page, generated before collectPrefetchHints ran),\n // immediately expire the entry so it gets re-fetched with correct hints.\n // The segment data itself is still valid — only the route tree (which\n // contains the hint bits) needs to be re-fetched.\n if (tree.prefetchHints & PrefetchHint.InliningHintsStale) {\n fulfilledEntry.staleAt = -1\n } else {\n fulfilledEntry.staleAt = now + STATIC_STALETIME_MS\n }\n fulfilledEntry.couldBeIntercepted = couldBeIntercepted\n fulfilledEntry.canonicalUrl = canonicalUrl\n fulfilledEntry.renderedSearch = renderedSearch\n fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching\n pingBlockedTasks(entry)\n return fulfilledEntry\n}\n\nexport function writeRouteIntoCache(\n now: number,\n pathname: NormalizedPathname,\n search: NormalizedSearch,\n nextUrl: string | null,\n root: RootRouteTree<RSCSegmentData | null>,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n renderedSearch: NormalizedSearch,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n const pendingEntry = createDetachedRouteCacheEntry()\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n const varyPath = getFulfilledRouteVaryPath(\n pathname,\n search,\n nextUrl as NormalizedNextUrl | null,\n couldBeIntercepted\n )\n const isRevalidation = false\n setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation)\n return fulfilledEntry\n}\n\nfunction fulfillSegmentCacheEntry(\n segmentCacheEntry: PendingSegmentCacheEntry,\n rsc: React.ReactNode,\n staleAt: number,\n isPartial: boolean,\n varyParams: VaryParams | null,\n // Only static (per-segment PPR) responses can be ISR fallbacks; all other\n // callers pass false. Always assigned (even when false) so that re-fulfilling\n // a previously-fallback entry with a concrete response clears the flag and\n // ends the retry loop.\n isUpgradeableISRFallback: boolean,\n // The strategy tier describing the CONTENT this entry is fulfilled with —\n // which comes from the response, not the tier the entry was requested at.\n // Usually the two agree, but when a response's shell payload IS the full\n // response (no shell/full split), shell-spawned entries are fulfilled with\n // full-tier content and recorded as such (see the promotion in\n // writeSegmentDataIntoCache). Always assigned, replacing\n // the spawn-time strategy set by upgradeToPendingSegment; the write walks'\n // matching and keying decisions all happen against the spawn-time\n // strategy, before fulfillment, so they are unaffected. See\n // SegmentCacheEntryShared['fetchStrategy'].\n fetchStrategy: FetchStrategy\n): FulfilledSegmentCacheEntry {\n const fulfilledEntry: FulfilledSegmentCacheEntry = segmentCacheEntry as any\n fulfilledEntry.status = EntryStatus.Fulfilled\n fulfilledEntry.rsc = rsc\n fulfilledEntry.staleAt = staleAt\n fulfilledEntry.isPartial = isPartial\n fulfilledEntry.varyParams = varyParams\n fulfilledEntry.isUpgradeableISRFallback = isUpgradeableISRFallback\n fulfilledEntry.fetchStrategy = fetchStrategy\n // Resolve any listeners that were waiting for this data.\n if (segmentCacheEntry.promise !== null) {\n segmentCacheEntry.promise.resolve(fulfilledEntry)\n // Free the promise for garbage collection.\n fulfilledEntry.promise = null\n }\n pingBlockedTasks(segmentCacheEntry)\n return fulfilledEntry\n}\n\nfunction rejectRouteCacheEntry(\n entry: PendingRouteCacheEntry,\n staleAt: number\n): void {\n const rejectedEntry: RejectedRouteCacheEntry = entry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.staleAt = staleAt\n pingBlockedTasks(entry)\n}\n\nfunction rejectSegmentCacheEntry(\n entry: PendingSegmentCacheEntry,\n staleAt: number\n): void {\n const rejectedEntry: RejectedSegmentCacheEntry = entry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.staleAt = staleAt\n if (entry.promise !== null) {\n // NOTE: We don't currently propagate the reason the prefetch was canceled\n // but we could by accepting a `reason` argument.\n entry.promise.resolve(null)\n entry.promise = null\n }\n pingBlockedTasks(entry)\n}\n\nexport type RouteTreeAccumulator = {\n metadataVaryPath: VaryPath | null\n // Whether the decoded tree's segment identities diverged from the base\n // tree it was overlaid onto. See NavigationSeed.treeDivergedFromBase.\n treeDivergedFromBase: boolean\n}\n\nexport function convertRootFlightRouterStateToRouteTree(\n flightRouterState: FlightRouterState,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<null> {\n return convertFlightRouterStateToRouteTree(\n flightRouterState,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n acc\n )\n}\n\nexport function rebaseInactiveRouteTree<TData>(\n treeToRebase: RouteTree<TData>\n): RouteTree<null> {\n // A parallel route slot that the target route doesn't provide keeps the\n // slot already active on the current route, under the new parent. The slot\n // sits at the same route position, so its request keys and vary paths are\n // unchanged: copy the structure and drop the payloads, which belong to the\n // previous render and are reused separately by render-tree.\n let slots: Map<string, RouteTree<null>> | null = null\n if (treeToRebase.slots !== null) {\n slots = new Map()\n for (const [parallelRouteKey, child] of treeToRebase.slots) {\n slots.set(parallelRouteKey, rebaseInactiveRouteTree(child))\n }\n }\n return {\n requestKey: treeToRebase.requestKey,\n segment: treeToRebase.segment,\n varyPath: treeToRebase.varyPath,\n shellVaryPath: treeToRebase.shellVaryPath,\n refreshState: treeToRebase.refreshState,\n data: null,\n slots,\n prefetchHints: treeToRebase.prefetchHints,\n }\n}\n\nexport function convertFlightRouterStateToRouteTree(\n flightRouterState: FlightRouterState,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialVaryPath | null,\n parentRenderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<null> {\n const originalSegment = flightRouterState[0]\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam =\n ((flightRouterState[4] ?? 0) & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\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 =\n compressedRefreshState !== null\n ? {\n canonicalUrl: compressedRefreshState[0] as string,\n renderedSearch: compressedRefreshState[1] as NormalizedSearch,\n }\n : null\n // Use the incoming search params, even if the response has no new data for\n // this segment. The base tree may still have the previous URL's. History\n // restores pass in their saved search params instead.\n const renderedSearch =\n refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n const tree = createRouteTreeNode<null>(\n originalSegment,\n isRootParam,\n requestKey,\n parentPartialVaryPath,\n renderedSearch,\n refreshState,\n acc\n )\n const partialVaryPath = getPartialVaryPath(tree.varyPath)\n\n let slots: Map<string, RouteTree<null>> | null = null\n\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(\n requestKey,\n parallelRouteKey,\n childRequestKeyPart\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childRouterState,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n\n tree.slots = slots\n tree.prefetchHints = flightRouterState[4] ?? 0\n return tree\n}\n\nexport function convertRouteTreeToFlightRouterState<TData>(\n routeTree: RouteTree<TData>\n): FlightRouterState {\n const parallelRoutes: Record<string, FlightRouterState> = {}\n const slots = routeTree.slots\n if (slots !== null) {\n for (const [parallelRouteKey, childTree] of slots) {\n parallelRoutes[parallelRouteKey] =\n convertRouteTreeToFlightRouterState(childTree)\n }\n }\n const flightRouterState: FlightRouterState = [\n routeTree.segment,\n parallelRoutes,\n null,\n null,\n ]\n if (routeTree.prefetchHints !== 0) {\n flightRouterState[4] = routeTree.prefetchHints\n }\n return flightRouterState\n}\n\nexport async function fetchRouteOnCacheMiss(\n entry: PendingRouteCacheEntry,\n key: RouteCacheKey\n): Promise<PrefetchSubtaskResult<null> | null> {\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' as SegmentRequestKey\n\n const headers: RequestHeaders = {\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\n try {\n const url = new URL(pathname + search, location.origin)\n let response\n let urlAfterRedirects\n if (isOutputExportMode) {\n // In output: \"export\" mode, we can't use headers to request a particular\n // segment. Instead, we encode the extra request information into the URL.\n // This is not part of the \"public\" interface of the app; it's an internal\n // Next.js implementation detail that the app developer should not need to\n // concern themselves with.\n //\n // For example, to request a segment:\n //\n // Path passed to <Link>: /path/to/page\n // Path passed to fetch: /path/to/page/__next-segments/_tree\n //\n // (This is not the exact protocol, just an illustration.)\n //\n // Before we do that, though, we need to account for redirects. Even in\n // output: \"export\" mode, a proxy might redirect the page to a different\n // location, but we shouldn't assume or expect that they also redirect all\n // the segment files, too.\n //\n // To check whether the page is redirected, previously we perform a range\n // request of 64 bytes of the HTML document to check if the target page\n // is part of this app (by checking if build id matches). Only if the target\n // page is part of this app do we determine the final canonical URL.\n //\n // However, as mentioned in https://github.com/vercel/next.js/pull/85903,\n // some popular static hosting providers (like Cloudflare Pages or Render.com)\n // do not support range requests, in the worst case, the entire HTML instead\n // of 64 bytes could be returned, which is wasteful.\n //\n // So instead, we drops the check for build id here, and simply perform\n // a HEAD request to rejects 1xx/4xx/5xx responses, and then determine the\n // final URL after redirects.\n //\n // NOTE: We could embed the route tree into the HTML document, to avoid\n // a second request. We're not doing that currently because it would make\n // the HTML document larger and affect normal page loads.\n const headResponse = await fetch(url, {\n method: 'HEAD',\n })\n if (headResponse.status < 200 || headResponse.status >= 400) {\n // The target page responded w/o a successful status code\n // Could be a WAF serving a 403, or a 5xx from a backend\n //\n // Note that we can't use headResponse.ok here, because\n // Response#ok returns `false` with 3xx responses.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS)\n return null\n }\n\n urlAfterRedirects = headResponse.redirected\n ? new URL(headResponse.url)\n : url\n\n response = await fetchPrefetchResponse(\n addSegmentPathToUrlInOutputExportMode(urlAfterRedirects, segmentPath),\n headers\n )\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 =\n response !== null && response.redirected ? new URL(response.url) : url\n }\n\n if (!response || !response.ok || !response.body) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS)\n return null\n }\n\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\n // Check whether the response varies based on the Next-Url header.\n const varyHeader = response.headers.get('vary')\n const couldBeIntercepted =\n varyHeader !== null && varyHeader.includes(NEXT_URL)\n\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<void>()\n\n // Note this doesn't imply PPR is enabled for the route: fully static\n // routes serve from the per-segment cache too. What it does tell us is\n // that per-segment prefetching is supported, which is what the route\n // entry records below.\n const supportsPerSegmentPrefetching = wasServedFromPerSegmentCache(response)\n\n // Decode the response. Routes that support per-segment prefetching\n // respond from static storage; other routes respond with a live render\n // (see the isRouteTreePrefetchRequest branch in\n // walk-tree-with-flight-router-state). Both are\n // NavigationFlightResponses carrying a buildId and a structure-only\n // transport tree — which is all this flow reads — so one decode path\n // serves both.\n const buffer = await bufferPrefetchResponseBody(response.body)\n closed.resolve()\n setSizeInCacheMap(entry, buffer.byteLength)\n const serverData = await decodeBufferedStage<NavigationFlightResponse>(\n buffer,\n headers\n )\n\n if (\n (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b) !==\n getNavigationBuildId()\n ) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: We should cache the fact that this is an MPA navigation.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS)\n return null\n }\n\n const transportData = serverData.t\n if (transportData === undefined || serverData.n !== undefined) {\n // The response carries no route tree (e.g. it's an MPA navigation), so\n // there's nothing to cache.\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS)\n return null\n }\n\n // Get the params that were used to render the target page. These may\n // be different from the params in the request URL, if the page\n // was rewritten. The rendered pathname is also used to fill in the param\n // values the server omitted from the response (omitting them keeps the\n // response cacheable across param values).\n const renderedPathname = getRenderedPathname(response)\n const renderedSearch = getRenderedSearch(response)\n\n // Decode the server-sent tree into the RouteTree format used by the\n // client cache.\n //\n // During this traversal, we accumulate additional data into this\n // \"accumulator\" object.\n const acc: RouteTreeAccumulator = {\n metadataVaryPath: null,\n treeDivergedFromBase: false,\n }\n const routeTree = decodeTransportTreeIntoRouteTree(\n transportData.t,\n null,\n // The tree is structure-only (no data nodes), so there are no vary\n // params to decode...\n null,\n // ...and no partiality either; the conservative value is never read.\n true,\n renderedPathname,\n renderedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, Date.now() + REJECTION_BACKOFF_MS)\n return null\n }\n\n discoverKnownRoute(\n Date.now(),\n pathname,\n search,\n nextUrl,\n entry,\n {\n tree: routeTree,\n head: createMetadataRouteTree(\n metadataVaryPath,\n routeTree.prefetchHints,\n null\n ),\n },\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\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\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: RouteVaryPath = getFulfilledRouteVaryPath(\n pathname,\n search,\n nextUrl,\n couldBeIntercepted\n )\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 { value: null, closed: closed.promise }\n } catch (error) {\n // Either the connection itself failed, or something bad happened while\n // decoding the response.\n rejectRouteCacheEntry(entry, getPrefetchErrorStaleAt(error))\n return null\n }\n}\n\n// When a static (per-segment PPR) prefetch receives an upgradeable fallback\n// shell, the localized retry loop re-issues the same fetch after this delay to\n// pick up the concrete version once the server's background regeneration\n// finishes.\nconst FALLBACK_RETRY_DELAY_MS = 2000\n\n// Maximum number of fallback retries per task, to avoid looping indefinitely\n// if the server keeps returning a fallback (e.g. misconfiguration).\nconst MAX_FALLBACK_RETRIES = 3\n\nexport async function fetchSegmentPrefetchesUsingStaticRequest(\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree<RSCSegmentData | null>,\n // The pending cache entries this task spawned for the bundle, keyed by\n // segment request key. The response fulfills them when it arrives.\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n // Which walk spawned the bundle's entries. The request on the wire is\n // identical either way; this only decides which payload of the response\n // fulfills the entries.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): Promise<PrefetchSubtaskResult<null> | null> {\n // This function is allowed to use async/await because it contains the actual\n // fetch that gets issued on a cache miss. Notice it writes the result to the\n // cache entry directly, rather than return data that is then written by\n // the caller.\n //\n // Segment fetches are non-blocking so we don't need to ping the scheduler\n // on completion.\n let isUpgradeableISRFallback\n try {\n isUpgradeableISRFallback = await fetchAndWritePerSegmentPrefetchResponse(\n task,\n route,\n routeKey,\n tree,\n spawnedEntries,\n fetchStrategy,\n // Write the response even if it's an upgradeable fallback shell — the\n // fallback content is better than nothing while the retry loop waits\n // for the concrete version.\n false\n )\n } catch (error) {\n // The connection failed, or the response couldn't be decoded. Reject the\n // pending entries so they don't stay Pending forever, and get retried\n // once the entry expires.\n rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n getPrefetchErrorStaleAt(error)\n )\n return null\n }\n\n if (isUpgradeableISRFallback === null) {\n // The response was fetched but isn't usable yet (server error/miss, empty\n // data, or a build-id mismatch — the server may be transiently unready).\n // Reject with a short backoff so the entries are retried soon.\n rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n Date.now() + REJECTION_BACKOFF_MS\n )\n return null\n }\n\n return {\n value: null,\n // The response is fully buffered before it's decoded, so the network\n // connection is already closed by the time the fetch returns. See TODO\n // in fetchRouteOnCacheMiss about removing `closed` for buffered\n // prefetch paths.\n closed: Promise.resolve(),\n }\n}\n\n/**\n * Issues a single segment-bundle prefetch request, validates and decodes the\n * response, and writes every payload of it into the cache — the full\n * payload, and, when the response carries a shell byte boundary, a second\n * decode of the same bytes truncated at that boundary, the segments'\n * shell-stage variant — through the shared payload-write orchestration\n * (writeResponsePayloadsIntoCache), which owns which payload fulfills the\n * spawned entries and the tier each payload is written at.\n *\n * Returns whether the response was an upgradeable ISR fallback shell (the\n * page hadn't been prerendered with concrete params yet), or `null` if the\n * response was fetched but isn't usable yet (server error/miss, empty data,\n * or a build-id mismatch — the server may be transiently unready, so it's\n * worth retrying; nothing is written and no entries are rejected). THROWS if\n * the connection failed or the response couldn't be decoded; re-issuing the\n * identical request won't fix that, so callers should give up rather\n * than retry.\n *\n * When the response is an upgradeable fallback shell, this also starts the\n * task's localized fallback-retry loop (at most one per task, ever), BEFORE\n * writing the fallback content — see the comment on the transition below.\n *\n * Calling this again with the same arguments reproduces the exact same\n * request. The retry loop uses that to re-issue the request until the server\n * has the concrete version, passing `discardFallbackResponse` so a response\n * that is STILL a fallback isn't pointlessly re-written over the identical\n * fallback content the initial fetch already cached. (The retry's entries\n * are already settled, so its writes are all detached upserts.)\n */\nasync function fetchAndWritePerSegmentPrefetchResponse(\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree<RSCSegmentData | null>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,\n // When true, a response that is still an upgradeable fallback shell is\n // discarded instead of written (the fallback-retry loop's re-issued\n // requests).\n discardFallbackResponse: boolean\n): Promise<boolean | null> {\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\n let normalizedRequestKey: SegmentRequestKey\n if (tree.segment === HEAD_REQUEST_KEY) {\n // The head's request key is its client cache identity; the server only\n // knows the head by its bare marker, which is also the head node's\n // segment (see createMetadataRouteTree).\n normalizedRequestKey = HEAD_REQUEST_KEY\n } else if (tree.requestKey === ROOT_SEGMENT_REQUEST_KEY) {\n // The root segment is a special case. To simplify the server-side\n // handling of these requests, we encode the root segment path as\n // `_index` instead of as an empty string. This should be treated as\n // an implementation detail and not as a stable part of the protocol.\n // It just needs to match the equivalent logic that happens when\n // prerendering the responses. It should not leak outside of Next.js.\n normalizedRequestKey = '/_index' as SegmentRequestKey\n } else {\n normalizedRequestKey = tree.requestKey\n }\n\n const headers: RequestHeaders = {\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\n const requestUrl = isOutputExportMode\n ? // In output: \"export\" mode, we need to add the segment path to the URL.\n addSegmentPathToUrlInOutputExportMode(url, normalizedRequestKey)\n : url\n\n const response = await fetchPrefetchResponse(requestUrl, headers)\n if (\n !response ||\n !response.ok ||\n // Theoretically this check should never fail, because we only issue\n // requests for segments once we've verified that the route supports PPR.\n !wasServedFromPerSegmentCache(response) ||\n !response.body\n ) {\n // Server responded with an error or a miss — fetched but not usable.\n return null\n }\n\n const buffer = await bufferPrefetchResponseBody(response.body)\n\n // Parse the response. Always a PrefetchFlightResponse. A connection drop\n // or malformed stream throws here, which propagates to the caller as a\n // non-retryable failure.\n const serverResponse = await decodeBufferedStage<PrefetchFlightResponse>(\n buffer,\n headers\n )\n\n if (serverResponse.t === undefined) {\n // The response carries no segment data at all — not usable.\n // writeServerResponseIntoCache checks this again, but this fetch-layer\n // copy is deliberate: it must run before the fallback-retry loop is\n // started and before the payload writes below, neither of which should\n // happen for an empty response.\n return null\n }\n if (\n (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n serverResponse.b) !== getNavigationBuildId()\n ) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n return null\n }\n\n // True if the server served an upgradeable fallback shell (the page hadn't\n // been prerendered with concrete params yet, but the route can be\n // upgraded once the server's background regeneration finishes).\n const isUpgradeableISRFallback = serverResponse.f === true\n if (isUpgradeableISRFallback) {\n if (discardFallbackResponse) {\n // Still a fallback — the server hasn't finished regenerating. Don't\n // write it; the retry loop will re-issue the request.\n return true\n }\n // Drive a localized retry loop to pick up the concrete version once the\n // server's background regeneration finishes. Only the first fallback\n // response per task starts a loop (`fallbackRetryStatus === Empty`);\n // once it leaves Empty, no second loop is started — sibling bundle\n // responses that also got a fallback don't, and neither does a re-hover.\n //\n // The transition to Pending must happen BEFORE the fallback content is\n // written below: fulfilling an entry pings the tasks blocked on it, and\n // a scheduler pass that ran before the transition would observe a\n // fulfilled fallback entry with the retry gate still Empty and spawn a\n // duplicate revalidation request (see isUpgradeableISRFallbackRetry in\n // pingSegmentBundle in scheduler.ts).\n if (task.fallbackRetryStatus === EntryStatus.Empty && !task.isCanceled) {\n task.fallbackRetryStatus = EntryStatus.Pending\n // Fire-and-forget: the loop drives itself via timers and pings the\n // task on success.\n void retryUpgradeableFallbackPrefetch(\n task,\n route,\n routeKey,\n tree,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n\n // Extract the shell payload, if the response carries a distinct one\n // (positive shell byte offset): decode the buffered bytes a SECOND time,\n // truncated at the boundary. The truncation is what produces the shell\n // variant: each segment's param-dependent rows land past the boundary and\n // decode as still-pending, which renders as the param fallback. It also\n // rewinds the response's signals — `needsRuntimeRequest` and `isPartial`\n // fulfillments past the boundary read as pending in this decode, so a\n // post-shell runtime-data access doesn't mark the shell variant itself as\n // needing a runtime request.\n // (A 0 offset means the response carries no shell: the server emits a\n // fulfilled 0 when the page wasn't staged at all — see the `a` resolution\n // in collect-segment-data — and 0 is also the default read of an\n // unfulfilled `a`, which would be a Next.js bug since the full buffer is\n // present. Both read the same here: no shell, and the scheduler skips the\n // affected segments rather than falling back to a runtime request — see\n // the no-shell handling in writeResponsePayloadsIntoCache. Failing in that\n // direction costs a shell prefetch but never leaks post-shell content into\n // shell positions. 0 can double as \"none\" on the wire precisely because\n // it's never a valid offset — see the `a` field doc on\n // NavigationFlightResponse.)\n const shellOffset =\n serverResponse.a !== undefined ? readFulfilledValue(serverResponse.a, 0) : 0\n let shellResponse: PrefetchFlightResponse | null\n if (shellOffset === null) {\n shellResponse = serverResponse\n } else if (shellOffset === 0) {\n shellResponse = null\n } else {\n try {\n shellResponse = await decodeBufferedStage<PrefetchFlightResponse>(\n buffer.subarray(0, shellOffset),\n headers\n )\n } catch {\n // The truncated prefix couldn't be decoded. Treat it as if no shell\n // exists; the full payload is still usable. (For a StaticShell-spawned\n // bundle this means the spawned entries are rejected — the scheduler\n // then skips them rather than issuing a runtime substitute; see the\n // no-shell handling in writeResponsePayloadsIntoCache.)\n shellResponse = null\n }\n }\n\n // The pathname the page was rendered for, derived the same way the route\n // tree fetch derives it (the rewritten-path header when the request was\n // rewritten, the request URL otherwise) so the vary paths computed from\n // this response's decoded tree agree with the ones on the route entry's\n // tree. In output: \"export\" mode the response URL has the segment filename\n // appended to the pathname, so derive it from the page URL instead\n // (rewrites don't exist on a static host).\n const renderedPathname = isOutputExportMode\n ? getPathnameFromRequestURL(url)\n : getRenderedPathname(response)\n\n // Write the payloads into the cache. Each payload is decoded like any\n // other server response — a root-anchored tree plus an optional head, with\n // no base overlay (the response covers its own spine) — and written\n // through the same path as a live-render response. Notes on the\n // arguments:\n // - Dynamic segments the server sent without a param value (`k: null`) are\n // parsed from the rendered pathname, and the rendered search is the one\n // the route tree was built with, so the decoded tree's vary paths agree\n // with the ones on the route entry's tree.\n // - The build id was already verified above, so none is passed.\n // - The response-level staleness is only a fallback, for segments that\n // don't carry their own staleTime (per-segment responses normally\n // always do).\n // - Response-level partiality is unused for per-segment writes — each\n // segment (and the head) carries its own partiality via the staged\n // promise encoding, which the decode reads in preference to the\n // response-level value — so the conservative value (true) is passed.\n // - The head is keyed at the route's own metadata vary path: the head has\n // no tree position, so the decode could only derive a vary path for it\n // from a page node in the payload's own tree. A per-segment response\n // carries only the spine from the root to the requested segment, so any\n // response whose terminal isn't a page has no page node to key the head\n // from; the standalone head response is one such case.\n const now = Date.now()\n const metadataVaryPath = route.root.head.varyPath\n writeResponsePayloadsIntoCache(\n now,\n fetchStrategy,\n serverResponse,\n shellResponse,\n null,\n // The payloads are root-anchored (no base tree), so there's no\n // prediction to diverge from.\n null,\n renderedPathname,\n route.renderedSearch,\n undefined,\n now + STATIC_STALETIME_MS,\n true,\n metadataVaryPath,\n spawnedEntries,\n buffer.byteLength,\n task.segmentCacheMap\n )\n return isUpgradeableISRFallback\n}\n\n/**\n * Reads a stale-at time from the staleTime async iterable of a fully-buffered\n * response — stage decodes, which go through\n * `bufferPrefetchResponseBody`. Drains synchronously via\n * `readFulfilledStaleTimeSeconds` (see decode-server-response). A missing\n * iterable, or a truncated shell decode whose value landed past the\n * boundary, reads as absent and falls back to the static stale time.\n *\n * For the one response kind that isn't buffered when read — a dynamic `Full`\n * response (fetchStrategy.Full with Partial Prefetching disabled) — use\n * `resolveStaleAt` instead, since its values aren't materialized synchronously.\n */\nfunction readFulfilledStaleAt(\n now: number,\n staleTime: AsyncIterable<number> | undefined\n): number {\n if (staleTime === undefined) {\n return now + STATIC_STALETIME_MS\n }\n const staleTimeSeconds = readFulfilledStaleTimeSeconds(staleTime)\n if (staleTimeSeconds === null) {\n return now + STATIC_STALETIME_MS\n }\n return now + getStaleTimeMs(staleTimeSeconds)\n}\n\n/**\n * The localized retry loop for an upgradeable fallback shell. Re-issues the\n * exact same segment-bundle request up to MAX_FALLBACK_RETRIES times,\n * FALLBACK_RETRY_DELAY_MS apart, until the server returns the concrete\n * (upgraded) version. The fetch writes the upgraded response through the\n * same payload writes as the initial fetch, so every slot the initial fetch\n * wrote — including the shell paths, even when the upgraded response is\n * fully static (shell === full) — is upgraded; the spawned entries were\n * already settled by the initial fetch, so every write is a detached upsert\n * that replaces the fallback. On success the loop pings the task, so the\n * task's *other* fallback segments get re-attempted. If every attempt is\n * still a fallback (or fails), it gives up.\n *\n * A loop runs at most once per task, ever (fetchAndWritePerSegmentPrefetchResponse\n * gates on `fallbackRetryStatus === Empty`, set to `Pending` before this runs\n * and never reset to `Empty`). The sleep timer is never `clearTimeout`-ed, so\n * the awaited sleep always settles; the loop simply checks `isCanceled` after\n * waking and bails if the task was canceled in the meantime. On success the\n * status becomes `Fulfilled`; on any non-success exit (exhausted retries,\n * fetch error, or cancel) it becomes `Rejected`.\n */\nasync function retryUpgradeableFallbackPrefetch(\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree<RSCSegmentData | null>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n // The strategy the initial fetch wrote its payloads with.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): Promise<void> {\n for (let attempt = 0; attempt < MAX_FALLBACK_RETRIES; attempt++) {\n await new Promise<void>((resolve) =>\n setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)\n )\n\n if (task.isCanceled) {\n break\n }\n\n let isUpgradeableISRFallback\n try {\n isUpgradeableISRFallback = await fetchAndWritePerSegmentPrefetchResponse(\n task,\n route,\n routeKey,\n tree,\n spawnedEntries,\n fetchStrategy,\n // A response that is still a fallback shell is discarded rather than\n // pointlessly re-written over the identical fallback content the\n // initial fetch already cached.\n true\n )\n } catch {\n // A hard failure (connection dropped, or the response couldn't be\n // decoded). Re-issuing the identical request won't fix it, so give up.\n break\n }\n if (task.isCanceled) {\n break\n }\n if (isUpgradeableISRFallback === null) {\n // Got a response that wasn't usable yet (the server hasn't finished\n // regenerating). Try again, or give up once the budget is exhausted.\n continue\n }\n if (isUpgradeableISRFallback) {\n // Still a fallback shell — the server hasn't finished regenerating yet.\n continue\n }\n\n // Success: the server returned the concrete (upgraded) version, and the\n // fetch wrote it into the cache. The task's other fallback segments are\n // now allowed to revalidate.\n task.fallbackRetryStatus = EntryStatus.Fulfilled\n pingPrefetchTask(task)\n return\n }\n\n // The loop finished without success (exhausted its retries, broke out on a\n // fetch error, or the task was canceled). It won't run again for this task.\n task.fallbackRetryStatus = EntryStatus.Rejected\n}\n\n// The runtime counterpart of the per-segment static prefetch flow\n// (fetchSegmentPrefetchesUsingStaticRequest). The two flows differ in how\n// they obtain their payloads — one runtime request here (streamed for Full\n// prefetches), versus a buffered per-segment response with a shell\n// double-decode there — but share the payload write orchestration\n// (writeResponsePayloadsIntoCache).\nexport async function fetchSegmentPrefetchesUsingRuntimeRequest(\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.RuntimeShell\n | FetchStrategy.Full,\n requestTree: FlightRouterState,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n const key = task.key\n const url = new URL(route.canonicalUrl, location.origin)\n const nextUrl = key.nextUrl\n\n // When the request tree was derived from a predicted route entry, pass the\n // node it was predicted from to the write path so the prediction can be\n // disabled if the server's rendered tree diverges from it. For an entry\n // the server resolved this is null: a divergence from it says nothing\n // about route prediction, and its unfulfilled entries take the usual\n // backoff.\n let dynamicRequestTree: FlightRouterState\n let predictedFrom: KnownRoutePart | null\n if (\n spawnedEntries.size === 1 &&\n spawnedEntries.has(route.root.head.requestKey)\n ) {\n // Only the head is pending, so ask the server for metadata only: it skips\n // the segments and renders just the head. The stub is not derived from\n // the route entry, so divergence from it carries no signal.\n dynamicRequestTree = MetadataOnlyRequestTree\n predictedFrom = null\n } else {\n dynamicRequestTree = requestTree\n predictedFrom = route.predictedFrom\n }\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_STATE_TREE_HEADER]:\n prepareFlightRouterStateForRequest(dynamicRequestTree),\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n switch (fetchStrategy) {\n case FetchStrategy.Full: {\n // We omit the prefetch header from a full prefetch because it's essentially\n // just a navigation request that happens ahead of time — it should include\n // all the same data in the response.\n break\n }\n case FetchStrategy.PPRRuntime: {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '2'\n break\n }\n case FetchStrategy.RuntimeShell: {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '3'\n break\n }\n case FetchStrategy.LoadingBoundary: {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n break\n }\n default: {\n fetchStrategy satisfies never\n }\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(\n spawnedEntries,\n Date.now() + REJECTION_BACKOFF_MS\n )\n return null\n }\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(\n spawnedEntries,\n Date.now() + REJECTION_BACKOFF_MS\n )\n return null\n }\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<void>()\n\n let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null = null\n let bufferedResponseSize: number | null = null\n let serverDataPromise: Promise<DynamicNavigationFlightResponse>\n if (fetchStrategy === FetchStrategy.Full) {\n // Full prefetches are dynamic responses stored in the prefetch cache.\n // They don't carry vary params or other cache metadata, so there's no\n // need to buffer them. Use the incremental version to allow data to be\n // processed as it arrives.\n const prefetchStream = createIncrementalPrefetchResponseStream(\n response.body,\n closed.resolve,\n 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 )\n serverDataPromise =\n createFromNextReadableStream<DynamicNavigationFlightResponse>(\n prefetchStream,\n headers,\n { allowPartialStream: true }\n )\n } else {\n const buffer = await bufferPrefetchResponseBody(response.body)\n closed.resolve()\n bufferedResponseSize = buffer.byteLength\n serverDataPromise = decodeBufferedStage<DynamicNavigationFlightResponse>(\n buffer,\n headers\n )\n }\n\n const [serverData, cacheData] = await Promise.all([\n serverDataPromise,\n response.cacheData,\n ])\n\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, serverData.s, response)\n const buildId =\n response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n\n // Extract the response's shell-stage payload, when it carries one. No\n // shell can be extracted without cache metadata (only present when\n // Cached Navigations is enabled); for responses without a distinct\n // shell stage the extraction is a no-op anyway\n // (`resolveShellStageResponse` returns null), so the null check just\n // short-circuits that case.\n const shellResponse =\n cacheData !== null\n ? await resolveShellStageResponse(cacheData, serverData, headers)\n : null\n\n // Runtime prefetch responses (PPRRuntime and RuntimeShell requests) are\n // partial when the server marks the response as '~' (Partial).\n // Full/LoadingBoundary prefetch responses are always complete.\n const isFullResponsePartial =\n (fetchStrategy === FetchStrategy.PPRRuntime ||\n fetchStrategy === FetchStrategy.RuntimeShell) &&\n (cacheData?.isResponsePartial ?? false)\n\n // Aside from writing the data into the cache, this also returns the\n // entries that were fulfilled, so we can streamingly update their sizes\n // in the LRU as more data comes in (Full responses, which stream).\n fulfilledEntries = writeResponsePayloadsIntoCache(\n now,\n fetchStrategy,\n serverData,\n shellResponse,\n dynamicRequestTree,\n predictedFrom,\n // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null,\n renderedSearch,\n buildId,\n staleAt,\n isFullResponsePartial,\n null,\n spawnedEntries,\n bufferedResponseSize,\n task.segmentCacheMap\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 { value: null, closed: closed.promise }\n } catch (error) {\n rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n getPrefetchErrorStaleAt(error)\n )\n return null\n }\n}\n\nfunction rejectSegmentEntriesIfStillPending(\n entries: Map<SegmentRequestKey, SegmentCacheEntry>,\n staleAt: number\n): void {\n for (const entry of entries.values()) {\n if (entry.status === EntryStatus.Pending) {\n rejectSegmentCacheEntry(entry, staleAt)\n }\n }\n}\n\n/**\n * Writes a prefetch response's payloads into the cache: the full payload,\n * plus its shell payload when the response carries one. This is the write\n * orchestration shared by the prefetch response kinds — per-segment\n * static responses (fetchAndWritePerSegmentPrefetchResponse) and\n * live-render responses (fetchSegmentPrefetchesUsingRuntimeRequest, and the\n * embedded runtime prefetch stream via writeRuntimePrefetchStreamIntoCache)\n * — which differ in how they obtain their payloads but not in what must\n * happen to them.\n *\n * Returns the entries the fulfilling payload's write produced content into\n * (so the streaming caller can keep updating their LRU sizes as bytes\n * arrive), or null if nothing entered the cache.\n */\nfunction writeResponsePayloadsIntoCache(\n now: number,\n // The strategy of the request that produced the response. Decides which\n // payload fulfills the spawned entries and their keying, and identifies\n // the response family: PPR/StaticShell are per-segment static responses,\n // everything else a live-render response.\n fetchStrategy: FetchStrategy,\n fullPayload: NavigationFlightResponse,\n // The response's shell payload: null (the response carries no shell),\n // `fullPayload` itself (the shell IS the full response), or a distinct\n // stage decode truncated at the shell byte boundary.\n shellPayload: NavigationFlightResponse | null,\n // The next five are threaded through to every write; see\n // writeServerResponseIntoCache for their meaning.\n baseTree: FlightRouterState | null,\n predictedFrom: KnownRoutePart | null,\n renderedPathname: string | null,\n renderedSearch: string,\n buildId: string | undefined,\n // Response-level staleness of the full payload. The shell payload's own\n // staleness is read off the shell decode below (a shell payload is always\n // fully buffered).\n staleAt: number,\n // Whether anything in the full payload is not fully resolved (dynamic or runtime holes, anything suspended). Shell-tier\n // writes don't consume it: a shell payload is partial by construction.\n // (Per-segment payloads encode partiality per node and ignore the\n // response-level value entirely.)\n isFullResponsePartial: boolean,\n metadataVaryPath: VaryPath | null,\n // The pending entries this response fulfills. Null when the caller owns\n // none (the embedded runtime prefetch stream), in which case every write\n // is a detached upsert.\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,\n // The response's size in bytes, distributed across the entries the\n // fulfilling payload's write produced; null when unknown (streamed Full\n // responses — the caller sizes those incrementally as bytes\n // arrive instead).\n responseByteLength: number | null,\n // The map the work that spawned this response's request is bound to. See\n // writeServerResponseIntoCache.\n map: CacheMap<SegmentCacheEntry>\n): Array<FulfilledSegmentCacheEntry> | null {\n let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null\n if (\n shellPayload === null ||\n // `FetchStrategy.LoadingBoundary` is not used in Cache Components,\n // and we only recover shells in Cache Components.\n fetchStrategy === FetchStrategy.LoadingBoundary\n ) {\n if (fetchStrategy === FetchStrategy.StaticShell) {\n // A static shell was requested but the response carries no shell (its\n // shell byte offset read as 0 — a bug in Next.js itself — or the\n // shell prefix couldn't be decoded). The full payload is still\n // usable, so it's written detached at the concrete tier; the spawned\n // entries are rejected so the task isn't stranded blocking on them.\n // Note the scheduler does NOT fall back to a runtime request for\n // rejected segments — it skips them outright (see the Rejected case\n // in pingSegmentBundle in scheduler.ts), so these segments get no\n // shell prefetch and no runtime substitute until the rejection's\n // backoff expires.\n writeServerResponseIntoCache(\n now,\n FetchStrategy.PPR,\n fullPayload,\n baseTree,\n predictedFrom,\n renderedPathname,\n renderedSearch,\n buildId,\n staleAt,\n isFullResponsePartial,\n metadataVaryPath,\n null,\n null,\n map\n )\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n now + REJECTION_BACKOFF_MS\n )\n }\n return null\n }\n // This request either:\n // - didn't allow recovering a shell (no staged rendering),\n // - or was a (runtime) shell request (that was NOT served by a fully static prerender)\n // so we already have a shell without recovering anything.\n // In either case, we don't have anything to consider other than the request itself,\n // so the payload simply fulfills the spawned entries at the request's own keying.\n fulfilledEntries = writeServerResponseIntoCache(\n now,\n fetchStrategy,\n fullPayload,\n baseTree,\n predictedFrom,\n renderedPathname,\n renderedSearch,\n buildId,\n staleAt,\n isFullResponsePartial,\n metadataVaryPath,\n spawnedEntries,\n null,\n map\n )\n } else if (shellPayload === fullPayload) {\n // The shell IS the full response (reference-equal — a page with nothing\n // below its shell). One payload fulfills the spawned entries, recording\n // the strategy that describes the CONTENT — the full payload's tier.\n // The content tier also drives the entries' keying: content that isn't\n // shell-grade is param-independent only on the server's vary-params\n // evidence, so it must not be parked in the shell slot on the strength\n // of the missing split alone (see the keying derivation in\n // writeSegmentDataIntoCache).\n\n let contentFetchStrategy:\n | FetchStrategy.PPR\n | FetchStrategy.PPRRuntime\n | null\n\n switch (fetchStrategy) {\n case FetchStrategy.StaticShell: {\n // a StaticShell always uses a PPR-tier request, so we need to fulfill\n // the spawned shell entries at the PPR tier.\n contentFetchStrategy = FetchStrategy.PPR\n break\n }\n case FetchStrategy.RuntimeShell: {\n // a runtime shell request is not normally rewindable, but fully static pages\n // the server will return a static prerender result, which *is* rewindable.\n contentFetchStrategy = FetchStrategy.PPRRuntime\n break\n }\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full: {\n // No shell was requested, so we don't need to override the fetch strategy.\n contentFetchStrategy = null\n }\n }\n\n fulfilledEntries = writeServerResponseIntoCache(\n now,\n fetchStrategy,\n fullPayload,\n baseTree,\n predictedFrom,\n renderedPathname,\n renderedSearch,\n buildId,\n staleAt,\n isFullResponsePartial,\n metadataVaryPath,\n spawnedEntries,\n contentFetchStrategy,\n map\n )\n } else {\n // The shell is a strict prefix of the response. Write both payloads.\n // The payload matching the tier the spawned entries were requested at\n // fulfills them; the other is written detached (no owned entries —\n // every write is an upsert). Fulfilling a spawned shell entry with the\n // concrete payload would store content that doesn't match the entry's\n // shell vary path — wrong for every later read at that key, and\n // immediately observable during a navigation, where a pending entry can\n // be rendered as a promise that resolves to its eventual value.\n //\n // The full payload is written first. The order is not observable: the\n // two writes key at different tiers, upsert precedence between a full\n // payload and its own shell payload is order-independent (the full\n // payload always wins the comparison — a shell segment is never\n // complete where its full counterpart is partial, see\n // readFulfilledIsPartial), and fulfillment pings only enqueue scheduler\n // work that runs after this synchronous block. Full-first is preferred\n // so the shell write's precedence checks and shadow eviction compare\n // against the fresh concrete entry rather than whatever stale entry\n // preceded it.\n\n let responseFetchStrategy: FetchStrategy\n let shellFetchStrategy: FetchStrategy\n switch (fetchStrategy) {\n case FetchStrategy.StaticShell:\n case FetchStrategy.PPR: {\n // Static request.\n // a StaticShell fetch strategy performs a request that returns\n // a PPR-tier response that can be rewound to a StaticShell response,\n // So we upgrade the full response's strategy to `PPR`.\n // (A static response's tier may be raised if we know that a static request\n // would satisfy a runtime request -- see `recordedFetchStrategy` in\n // `writeSegmentDataIntoCache`)\n responseFetchStrategy = FetchStrategy.PPR\n shellFetchStrategy = FetchStrategy.StaticShell\n break\n }\n case FetchStrategy.RuntimeShell: {\n // A runtime shell request is normally not rewindable -- it only produces\n // the shell itself. However, if a page is fully static, a runtime shell\n // will return a static prerender, i.e. the static content with an embedded shell.\n // The page is static, so we can treat the content as runtime-complete.\n responseFetchStrategy = FetchStrategy.PPRRuntime\n shellFetchStrategy = FetchStrategy.RuntimeShell\n break\n }\n case FetchStrategy.PPRRuntime: {\n // A runtime prefetch response can be rewound into a runtime shell.\n // (This may also be a fully static response, same as RuntimeShell above,\n // in which case we also know that the shell is equivalent to a runtime shell)\n responseFetchStrategy = FetchStrategy.PPRRuntime\n shellFetchStrategy = FetchStrategy.RuntimeShell\n break\n }\n case FetchStrategy.Full: {\n // Navigation responses can be rewound into a *static* app shell.\n // On PPF routes they also contain a runtime prefetch stream which will give us\n // a runtime shell/prefetch, but that's handled separately from the main response.\n // (see `writeRuntimePrefetchStreamIntoCache`)\n responseFetchStrategy = FetchStrategy.Full\n shellFetchStrategy = FetchStrategy.StaticShell\n break\n }\n }\n\n // We have to fulfill the correct pending entries depending on what was requested:\n // - If we originally needed a shell but and got more content, the spawned entries\n // should be fulfilled using the shell.\n // - If we needed a speculative or full request but rewound it into a shell,\n // the spawned entries should be fulfilled using the full response.\n const wasShellRequested =\n fetchStrategy === FetchStrategy.StaticShell ||\n fetchStrategy === FetchStrategy.RuntimeShell\n\n const fullFulfilledEntries = writeServerResponseIntoCache(\n now,\n responseFetchStrategy,\n fullPayload,\n baseTree,\n predictedFrom,\n renderedPathname,\n renderedSearch,\n buildId,\n staleAt,\n isFullResponsePartial,\n metadataVaryPath,\n wasShellRequested ? null : spawnedEntries,\n null,\n map\n )\n\n const shellFulfilledEntries = writeServerResponseIntoCache(\n now,\n shellFetchStrategy,\n shellPayload,\n baseTree,\n predictedFrom,\n renderedPathname,\n renderedSearch,\n buildId,\n // The shell payload carries its own staleness, independent of the\n // full payload's. Shell decodes are fully buffered, so it's read\n // synchronously; when absent (per-segment responses carry staleTime\n // per node instead) this falls back to the same static stale time the\n // per-segment writes use as their response-level fallback.\n readFulfilledStaleAt(now, shellPayload.s),\n // A shell payload is a strict subset of the full response, so it does\n // not represent the entire UI of the target page — it's partial\n // by construction.\n true,\n metadataVaryPath,\n wasShellRequested ? spawnedEntries : null,\n null,\n map\n )\n fulfilledEntries = wasShellRequested\n ? shellFulfilledEntries\n : fullFulfilledEntries\n }\n\n // Entries created by a detached write aren't sized: one wire response is\n // only charged to the LRU once, to the entries it fulfilled.\n if (\n responseByteLength !== null &&\n fulfilledEntries !== null &&\n fulfilledEntries.length > 0\n ) {\n const averageSize = responseByteLength / fulfilledEntries.length\n for (const entry of fulfilledEntries) {\n setSizeInCacheMap(entry, averageSize)\n }\n }\n return fulfilledEntries\n}\n\n/**\n * Writes a decoded server response into the segment cache: decodes the\n * response's transport tree into a RouteTree — overlaid on `baseTree` when\n * the response is an overlay over existing client state, root-anchored when\n * it covers its own spine (per-segment prefetch payloads) — then writes\n * every rendered segment, plus the head, into the cache. Fulfills the\n * entries in `spawnedEntries` that the response covers; rejects the rest, so\n * a task blocked on them isn't stranded. Returns the entries the write\n * produced content into — fulfilled spawned entries plus installed detached\n * upserts — for LRU size accounting, or null if nothing entered the cache.\n *\n * Serves every response kind: live-render prefetch responses (runtime\n * prefetches, and Full/LoadingBoundary prefetches in the\n * non-Partial-Prefetching regime), prerender stage decodes (shell-stage\n * extraction, cached navigations, the initial payload), embedded runtime\n * prefetch streams, and the payloads of per-segment prefetch responses.\n */\nfunction writeServerResponseIntoCache(\n now: number,\n fetchStrategy: FetchStrategy,\n // The decoded response payload to write. For a per-segment prefetch\n // response this is one of its payloads: the full response, or the\n // truncated shell decode.\n response: NavigationFlightResponse,\n // The base router state the response overlays. Null when the response's\n // tree is root-anchored (per-segment prefetch payloads).\n baseTree: FlightRouterState | null,\n // Non-null when `baseTree` was predicted: the node in the known route tree\n // whose pattern it was predicted from (see matchKnownRoute). The\n // prediction assumes the URL's rewrite (if any) behaves statically; if the\n // server's rendered tree diverges from the base, that prediction failed —\n // the rewrite behaves dynamically, so the params baked into the request\n // are wrong. The node is marked so the shape is never predicted again, and\n // the entries that could not be fulfilled are rejected with immediate\n // expiration so the task retries right away — against the server-resolved\n // route this time. The response data is still written into the cache: it's\n // real data keyed by what the server actually rendered, useful regardless\n // of whether the prediction matched.\n predictedFrom: KnownRoutePart | null,\n // The pathname the response was rendered for, used to resolve dynamic\n // segments the server sent without a param value (`k: null`). Null for\n // responses that always carry concrete values (navigation responses).\n renderedPathname: string | null,\n renderedSearch: string,\n buildId: string | undefined,\n // Response-level staleness; a segment (or the head) with its own\n // staleTime overrides it.\n staleAt: number,\n // Whether anything in the response is not fully resolved: dynamic holes, runtime holes, anything suspended.\n // Threaded into the decode, where each segment's (and the head's)\n // partiality is resolved from it and the wire form (see\n // createNavigationSeed). Per-segment prefetch responses encode\n // partiality per node, so their writes pass the conservative value\n // (true), which is never read.\n isResponsePartial: boolean,\n // Where to key the head; see createNavigationSeed.\n metadataVaryPath: VaryPath | null,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,\n // The strategy tier describing the CONTENT of the payload being written,\n // when it differs from `fetchStrategy` (which drives matching and\n // keying); null when they agree. See the param docs on\n // writeSegmentDataIntoCache.\n contentFetchStrategy: FetchStrategy.PPR | FetchStrategy.PPRRuntime | null,\n // The map the work that spawned this response's request is bound to: the\n // spawning task's `PrefetchTask.segmentCacheMap` for prefetches, the\n // navigation's map for navigation-side writes. Binding the write to the\n // requesting work means a response that lands after a testing-lock scope\n // boundary still writes into the map its entries live in.\n map: CacheMap<SegmentCacheEntry>\n): Array<FulfilledSegmentCacheEntry> | null {\n // Which layer owns the buildId check differs by flow. The route and\n // segment fetch layers check it themselves (see fetchRouteOnCacheMiss and\n // fetchAndWritePerSegmentPrefetchResponse) because they need the early-out\n // before side effects this layer can't undo — starting the fallback-retry\n // loop, writing the second (shell) payload — and then pass no buildId\n // here. This check owns it for the flows that don't: live-render prefetch\n // responses and navigation static-stage writes, which pass their\n // buildId through.\n if (buildId && buildId !== getNavigationBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n now + REJECTION_BACKOFF_MS\n )\n }\n return null\n }\n\n const transportData = response.t\n if (transportData === undefined) {\n // The response carries no tree. Settle anything we own so a task blocked\n // on it isn't stranded.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n now + REJECTION_BACKOFF_MS\n )\n }\n return null\n }\n\n const navigationSeed = createNavigationSeed(\n now,\n baseTree,\n transportData,\n // Root params are emitted once at the top level of the response; the\n // decode unions them into the head's and each segment's own set. For\n // per-segment prefetch responses this must be read from the payload\n // being written: a truncated shell decode rewinds the response's\n // late-resolving values to the shell stage.\n response.r ?? null,\n // The decode resolves each segment's partiality from this and the wire:\n // boolean-form nodes resolve to this response-level value; staged\n // (promise-form) nodes encode partiality per node and ignore it.\n isResponsePartial,\n renderedPathname,\n renderedSearch,\n metadataVaryPath,\n // Only navigations consume the seed's dynamicStaleAt; cache writes pass\n // unknown to use the default.\n UnknownDynamicStaleTime\n )\n const requiresRuntimeCompleteness =\n (navigationSeed.root.tree.prefetchHints &\n PrefetchHint.SubtreeHasPartialPrefetching) !==\n 0\n\n const treeDivergedFromPrediction =\n predictedFrom !== null && navigationSeed.treeDivergedFromBase\n if (treeDivergedFromPrediction) {\n predictedFrom.hasDynamicRewrite = true\n }\n\n // Only static (per-segment) responses can be ISR fallbacks (`f`). A\n // present `u` means the response carries a stage-scoped runtime-data\n // verdict — per-segment prefetch responses always emit one, and so does\n // any prerendered page payload, which embeds the prerender's runtime-data\n // probe; live renders emit none. A response without one decodes to a null\n // verdict, and its entries record their request's own strategy unrefined\n // (see writeSegmentDataIntoCache).\n // `u` is deliberately read here, off THIS decode's thenable status, rather\n // than normalized where the response is fetched: the read scopes it to the\n // payload being written — a truncated shell decode reads a post-shell\n // runtime access as pending, i.e. `false`, because the shell variant\n // itself doesn't need that data. The read is load-bearing in one direction\n // only: a false `true` costs a wasted runtime request; a false `false`\n // would record too high a tier and skip a runtime request that had more\n // content. A rejected row (an aborted prerender errors rows that were\n // still pending at the abort) must therefore read as `true`, matching the\n // server's own read of the page payload's flag (see the `u` read in\n // collect-segment-data.tsx).\n const isUpgradeableISRFallback = response.f === true\n const responseNeedsRuntimeRequest =\n response.u !== undefined\n ? readFulfilledValue(response.u, false, /* rejectedValue */ true)\n : null\n\n const routeTree = navigationSeed.root.tree\n\n // The route tree carries the render output of every segment the response\n // included, so a single traversal from the root writes all of it into\n // the cache.\n const writtenEntries: Array<FulfilledSegmentCacheEntry> = []\n writeTreeDataIntoCache(\n now,\n map,\n fetchStrategy,\n routeTree,\n staleAt,\n spawnedEntries,\n contentFetchStrategy,\n isUpgradeableISRFallback,\n requiresRuntimeCompleteness,\n responseNeedsRuntimeRequest,\n writtenEntries\n )\n\n const metadataTree = navigationSeed.root.head\n const headData = metadataTree.data\n if (headData !== null && headData.rsc !== null) {\n // The head follows the same stale-time rules as a segment.\n const headStaleAt =\n headData.staleTimeSeconds !== null\n ? now + getStaleTimeMs(headData.staleTimeSeconds)\n : staleAt\n\n // A head has no loading boundary. Match the scheduler, which spawns\n // LoadingBoundary head entries using the concrete Full strategy (see the\n // head's runtime fetch in pingRootRouteTree).\n const headFetchStrategy =\n fetchStrategy === FetchStrategy.LoadingBoundary\n ? FetchStrategy.Full\n : fetchStrategy\n const writtenHeadEntry = writeSegmentDataIntoCache(\n now,\n map,\n headFetchStrategy,\n headData.rsc,\n // The decode already resolved the head's partiality from the wire\n // form and the response-level value — see the head read in\n // createNavigationSeed.\n headData.isPartial,\n headStaleAt,\n headData.varyParams,\n metadataTree,\n spawnedEntries,\n contentFetchStrategy,\n isUpgradeableISRFallback,\n requiresRuntimeCompleteness,\n responseNeedsRuntimeRequest\n )\n if (writtenHeadEntry !== null) {\n writtenEntries.push(writtenHeadEntry)\n }\n }\n // Any entry that's still pending was intentionally not rendered by the\n // server, because it was inside the loading boundary. Mark them as rejected\n // so we know not to fetch them again.\n // TODO: If PPR is enabled on some routes but not others, then it's possible\n // that a different page is able to do a per-segment prefetch of one of the\n // segments we're marking as rejected here. We should mark on the segment\n // somehow that the reason for the rejection is because of a non-PPR prefetch.\n // That way a per-segment prefetch knows to disregard the rejection.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n // When the response diverged from the prediction, the leftover entries\n // can never be fulfilled — their keys were derived from the wrong\n // tree. Reject with an immediate expiration instead of the usual\n // backoff so the task retries right away. The prediction was disabled\n // above, so the retry resolves the route on the server instead of\n // predicting it again.\n treeDivergedFromPrediction ? -1 : now + REJECTION_BACKOFF_MS\n )\n }\n return writtenEntries.length > 0 ? writtenEntries : null\n}\n\nfunction writeTreeDataIntoCache(\n now: number,\n map: CacheMap<SegmentCacheEntry>,\n fetchStrategy: FetchStrategy,\n tree: RouteTree<RSCSegmentData | null>,\n staleAt: number,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,\n contentFetchStrategy: FetchStrategy.PPR | FetchStrategy.PPRRuntime | null,\n isUpgradeableISRFallback: boolean,\n requiresRuntimeCompleteness: boolean,\n responseNeedsRuntimeRequest: boolean | null,\n // Accumulates the entries the walk wrote content into (fulfilled spawned\n // entries and installed detached upserts), for LRU size accounting.\n writtenEntries: Array<FulfilledSegmentCacheEntry>\n) {\n // Writes the render output embedded in the route tree into the\n // prefetch cache.\n const data = tree.data\n if (data !== null && data.rsc !== null) {\n // A segment carries its own staleTime only in per-segment prefetch\n // responses; everywhere else the response-level staleness governs.\n const entryStaleAt =\n data.staleTimeSeconds !== null\n ? now + getStaleTimeMs(data.staleTimeSeconds)\n : staleAt\n const writtenEntry = writeSegmentDataIntoCache(\n now,\n map,\n fetchStrategy,\n data.rsc,\n data.isPartial,\n entryStaleAt,\n data.varyParams,\n tree,\n spawnedEntries,\n contentFetchStrategy,\n isUpgradeableISRFallback,\n requiresRuntimeCompleteness,\n responseNeedsRuntimeRequest\n )\n if (writtenEntry !== null) {\n writtenEntries.push(writtenEntry)\n }\n } else {\n // Either the response carried no information for this segment (no data\n // object — e.g. the identity spine of a per-segment prefetch response,\n // or a slot reused from the base tree), or it acknowledged the position\n // without rendering it (a data object with a null rsc — an intermediate\n // position on the path to a rendered subtree). Nothing to write either\n // way, but the children may have output, so keep descending.\n }\n\n // Recursively write the child data into the cache.\n const slots = tree.slots\n if (slots !== null) {\n for (const childTree of slots.values()) {\n writeTreeDataIntoCache(\n now,\n map,\n fetchStrategy,\n childTree,\n staleAt,\n spawnedEntries,\n contentFetchStrategy,\n isUpgradeableISRFallback,\n requiresRuntimeCompleteness,\n responseNeedsRuntimeRequest,\n writtenEntries\n )\n }\n }\n}\n\n/**\n * Writes one segment's render output into the cache: fulfills the entry at\n * the same tree position if this task owns one, otherwise creates one (or\n * upserts a detached one). Shared by every response kind; responses that\n * carry a runtime-data verdict (per-segment prefetch responses and\n * prerendered page payloads) additionally refine the tier the entry\n * records — see `recordedFetchStrategy` below.\n *\n * Returns the entry this write produced content into — the fulfilled spawned\n * entry, or the detached entry the upsert installed — so the caller can\n * charge the response's size to it. Null when nothing entered the cache (the\n * upsert declined a detached candidate).\n */\nfunction writeSegmentDataIntoCache(\n now: number,\n map: CacheMap<SegmentCacheEntry>,\n fetchStrategy: FetchStrategy,\n rsc: React.ReactNode,\n isPartial: boolean,\n staleAt: number,\n segmentVaryParams: VaryParams | null,\n tree: RouteTree<RSCSegmentData | null>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,\n // The strategy tier describing the CONTENT of the payload this write came\n // from, when it differs from the write's own `fetchStrategy` (which\n // drives matching and keying); null when they agree. It differs only for\n // the coincident-shell case: a write that fulfills shell-keyed entries\n // with a payload that IS the full response passes the full payload's tier\n // — see writeResponsePayloadsIntoCache.\n contentFetchStrategy: FetchStrategy.PPR | FetchStrategy.PPRRuntime | null,\n // Whether the response is an upgradeable fallback shell. Always false for\n // live-render responses — they are never ISR fallbacks.\n isUpgradeableISRFallback: boolean,\n // The response's runtime-data verdict: whether the render that produced\n // this payload accessed runtime data (page-global; combined with the\n // segment's own `isPartial` to decide the tier the entry records below).\n // Null when the response carries no verdict (`u`) — live renders emit\n // none; per-segment prefetch responses and prerendered page payloads\n // (including the truncated initial payload) do — in which case the entry\n // records the payload's tier unrefined.\n requiresRuntimeCompleteness: boolean,\n responseNeedsRuntimeRequest: boolean | null\n): FulfilledSegmentCacheEntry | null {\n // The strategy tier recorded on the entry — the tier of the content that\n // actually satisfied it, which spans both axes: shell-vs-concrete AND\n // static-vs-runtime. The payload's content tier (`fetchStrategy`, unless\n // the caller passed a distinct `contentFetchStrategy`), refined by the\n // response's runtime-data verdict when it carries one:\n //\n // A runtime prefetch can only provide more content than this entry if the\n // render accessed runtime data AND this particular segment has holes — a\n // fully static segment gains nothing from a runtime request no matter\n // what the page accessed. When this payload fully satisfied the segment —\n // no runtime request needed — the content is as complete as a RUNTIME\n // response of the same variant would have been, so it records that\n // runtime tier. That's what lets the scheduler decide \"would a runtime\n // request return more?\" by comparing tiers alone, with no separate signal\n // to consult. Otherwise the content is only as complete as the static\n // tier it was requested at, so a follow-up runtime request can still\n // supersede it.\n let recordedFetchStrategy: FetchStrategy\n if (responseNeedsRuntimeRequest === null) {\n // The response carries no verdict — a live render's, or the synthesized\n // initial-payload subset's (see create-initial-router-state): record\n // the payload's tier as-is. A verdict is honored wherever it appears:\n // prerendered page payloads carry one too (the prerender's runtime-data\n // probe), and refining on it is correct — a prerendered response whose\n // verdict is `false` is genuinely runtime-complete content.\n recordedFetchStrategy = contentFetchStrategy ?? fetchStrategy\n } else if (responseNeedsRuntimeRequest && isPartial) {\n // A runtime request would provide more than this payload, so no runtime\n // tier is recorded — but the entry must still honor the payload's\n // CONTENT grade. In the coincident-shell case the payload that satisfied\n // a shell-keyed entry IS the full response, whose content grades at the\n // concrete static tier (`contentFetchStrategy`, PPR — the verdict only\n // rides static-family responses, so no higher grade can appear here).\n // The verdict is consistent with that grade: it says the runtime tiers\n // would provide more, which they would over PPR just as over the shell\n // tier.\n recordedFetchStrategy = contentFetchStrategy ?? fetchStrategy\n } else {\n const payloadFetchStrategy = contentFetchStrategy ?? fetchStrategy\n if (requiresRuntimeCompleteness) {\n // The verdict says this payload does not need a runtime request.\n // If we requested it at a static tier, raise the recorded tier up to the\n // runtime tier of the same variant.\n // This also makes the verdict a noop for Full payloads, which matters because\n // the Full flow decodes incrementally, and synchronously reading `response.u`\n // is only sound for a buffered payload.\n recordedFetchStrategy =\n payloadFetchStrategy === FetchStrategy.StaticShell\n ? FetchStrategy.RuntimeShell\n : payloadFetchStrategy === FetchStrategy.PPR\n ? FetchStrategy.PPRRuntime\n : payloadFetchStrategy\n } else {\n // Only upgrade static segments to their runtime equivalents if the route\n // can use runtime requests. Otherwise, when re-using a shell segment across\n // params, `pingSegmentBundle` for a PPR strategy would see a `ShellRuntime`\n // shell entry and incorrectly decide that a new PPR request would not\n // provide more content.\n recordedFetchStrategy = payloadFetchStrategy\n }\n }\n\n // Decide whether to re-key the entry under a more generic vary path based on\n // which params the segment actually depends on.\n //\n // Skip re-keying for Full prefetches: as of today, `varyParams` tracking only\n // works within the static stage portion of a response. A Full prefetch\n // response covers all stages, and we can't track params during the dynamic\n // stage without dead-locking the Flight stream, so the server-reported set is\n // incomplete and can't be trusted for the full response. Re-keying with an\n // untrustworthy set could replace concrete params with Fallback and let\n // unrelated URLs read each other's content from the cache.\n //\n // Key the entry by which params the server said this segment depends on\n // (judged by the payload's CONTENT: contentFetchStrategy differs from\n // fetchStrategy exactly when a shell request's response turned out to\n // carry more — the coincident case). Reusing one copy across param values\n // is the point of the shell, but it requires knowing the content doesn't\n // depend on those params, and the server's report is the direct evidence\n // of that.\n //\n // Without that report, assume every param varies — a response without a\n // shell/full split is also what a page fully prerendered at concrete\n // params looks like, and keying that at the shell path would serve one\n // slug's content to every sibling. The exception is a shell variant,\n // which reduces param-dependent content to param fallbacks, so it really\n // is good for any value of them (its request path below IS the shell\n // vary path).\n const payloadStrategy = contentFetchStrategy ?? fetchStrategy\n let fulfilledVaryPath: VaryPath | null = null\n // The dependency source the entry records, so a navigation that renders\n // its content can tell which params that content read. It is the same\n // evidence the key derivation below trusts, under the same condition, with\n // the same correction; otherwise null, and consumers assume every param.\n let recordedVaryParams: VaryParams | null = null\n if (\n process.env.__NEXT_VARY_PARAMS &&\n payloadStrategy !== FetchStrategy.Full &&\n segmentVaryParams !== null\n ) {\n // Read the reported set now, when the key is chosen. The payload is fully\n // buffered by the time it's written, so the source has settled; a read of\n // null means the report is unavailable and every param varies.\n let varyParams = readVaryParams(segmentVaryParams)\n if (varyParams !== null) {\n if (\n payloadStrategy === FetchStrategy.RuntimeShell &&\n varyParams.has(SEARCH_PARAMS_VARY_ID)\n ) {\n // SPECIAL CASE: for a RuntimeShell payload, the search params entry\n // is dropped from the server's vary evidence before deriving the\n // key, so the search component of the resulting path is marked as\n // the fallback. This exists ONLY because of a known compromise in\n // how the server reports search params: accessing `searchParams`\n // records a dependency on them at access time, even when the render\n // suspends on that access and cuts the content at the param\n // fallback. A shell render's page and head segments therefore report\n // the search params while the emitted bytes contain no\n // search-dependent content.\n // Trusting that report would key shell-grade content at a concrete\n // search value, where shell-restricted reads (which generalize every\n // non-root param — see getShellSegmentVaryPath) can never find it. A\n // RuntimeShell payload's search-dependent content is reduced to\n // fallbacks by construction, so its key must not vary on search\n // regardless of the over-reported evidence. Every other component of\n // the evidence is still honored as-is.\n //\n // Nothing else should rely on this branch; for every other payload\n // grade — and every other param — the server's evidence\n // is authoritative.\n //\n // TODO: Reconsider special-casing this on the server instead: don't\n // report a param access that never resolved past the fallback cut in\n // the emitted stage. A shell payload's evidence would then be\n // accurate, and this branch could be deleted.\n varyParams = new Set(varyParams)\n varyParams.delete(SEARCH_PARAMS_VARY_ID)\n recordedVaryParams = createVaryParams(varyParams)\n } else {\n recordedVaryParams = segmentVaryParams\n }\n fulfilledVaryPath = getFulfilledSegmentVaryPath(tree.varyPath, varyParams)\n }\n }\n\n // The canonical path to (re-)key the entry at. When the derivation above\n // produced a path, use that; otherwise fall back to the payload's own\n // keying (this is load-bearing for entries spawned as revalidations:\n // without the re-key they'd stay in their Revalidation slot forever,\n // invisible to canonical reads, and the partial entry that prompted the\n // revalidation would keep serving navigations). Full responses are\n // excluded, matching the varyParams re-key: they're spawned as canonical\n // entries at their final path, and their vary tracking can't be trusted\n // for re-keying (see the fulfilledVaryPath derivation above).\n const canonicalVaryPath =\n fulfilledVaryPath !== null\n ? fulfilledVaryPath\n : payloadStrategy !== FetchStrategy.Full\n ? getSegmentVaryPathForRequest(payloadStrategy, tree)\n : null\n\n // We should only write into cache entries that are owned by us. Or create\n // a new one and write into that. We must never write over an entry that was\n // created by a different task, because that causes data races.\n //\n // The status check matters for the fallback-retry loop, which re-writes a\n // response over entries the initial fetch already settled: those writes\n // must fall through to the detached path below.\n const ownedEntry =\n spawnedEntries !== null ? spawnedEntries.get(tree.requestKey) : undefined\n const isOwned =\n ownedEntry !== undefined && ownedEntry.status === EntryStatus.Pending\n let fulfilledEntry: FulfilledSegmentCacheEntry\n let insertVaryPath: VaryPath | null\n if (isOwned) {\n // We own this entry — fulfill it directly.\n fulfilledEntry = fulfillSegmentCacheEntry(\n ownedEntry,\n rsc,\n staleAt,\n isPartial,\n recordedVaryParams,\n isUpgradeableISRFallback,\n recordedFetchStrategy\n )\n // Re-key the fulfilled entry at its canonical path. Owned Full entries\n // are the exception (canonicalVaryPath is null): they were spawned as\n // canonical entries at their final path, so no re-key happens.\n insertVaryPath = canonicalVaryPath\n } else {\n // We don't own an entry for this segment. Create a detached one and\n // attempt to insert it at the canonical path — or, for a Full response\n // (which has no canonical re-key), at the request's own path.\n fulfilledEntry = fulfillSegmentCacheEntry(\n upgradeToPendingSegment(\n createDetachedSegmentCacheEntry(now),\n fetchStrategy\n ),\n rsc,\n staleAt,\n isPartial,\n recordedVaryParams,\n isUpgradeableISRFallback,\n recordedFetchStrategy\n )\n insertVaryPath =\n canonicalVaryPath !== null\n ? canonicalVaryPath\n : getSegmentVaryPathForRequest(fetchStrategy, tree)\n }\n if (insertVaryPath !== null) {\n // Insert through the upsert so the usual precedence rules apply — an\n // existing entry with more complete content is never downgraded, and a\n // shadowed Empty/Pending entry's blocked tasks are pinged. (In the\n // common case the slot already holds the entry we just fulfilled, which\n // the upsert replaces in place; but the re-key is load-bearing for\n // entries whose spawn path differs from the canonical path — e.g.\n // spawned revalidations, which would otherwise stay in their\n // Revalidation slot forever, invisible to canonical reads, while the\n // partial entry that prompted the revalidation kept serving\n // navigations.)\n //\n // The concrete lookup path (tree.varyPath) is passed so that when the\n // canonical path is more generic, any stale settled entry — or unclaimed\n // Empty placeholder — at a more specific path that would shadow the\n // fulfilled entry is evicted. Without this, a shadowed re-keyed entry is\n // unreachable at the concrete read path: the scheduler would keep\n // re-reading the stale entry and, for a revalidation, respawn it\n // forever. See evictShadowingSegmentEntries.\n const installedEntry = upsertSegmentEntry(\n now,\n map,\n insertVaryPath,\n fulfilledEntry,\n tree.varyPath\n )\n if (installedEntry === null && !isOwned) {\n // The upsert declined the detached candidate (an existing entry took\n // precedence, or the candidate was already expired), so no cache slot\n // holds this write's content — nothing for the caller to charge to\n // the LRU. (An owned entry is returned regardless: it was fulfilled\n // above and stays live for waiters that hold it, whether or not the\n // re-key installed it.)\n return null\n }\n }\n return fulfilledEntry\n}\n\nasync function fetchPrefetchResponse<T>(\n url: URL,\n headers: RequestHeaders\n): Promise<RSCResponse<T> | null> {\n const fetchPriority = 'low'\n // When issuing a prefetch request, don't immediately decode the response; we\n // use the lower level `createFromResponse` API instead because we need to do\n // some extra processing of the response stream. See\n // `bufferPrefetchResponseBody` for more details.\n const shouldImmediatelyDecode = false\n const response = await createFetch<T>(\n url,\n headers,\n fetchPriority,\n shouldImmediatelyDecode\n )\n if (!response.ok) {\n return null\n }\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 =\n contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n if (!isFlightResponse) {\n return null\n }\n }\n return response\n}\n\n/**\n * Whether the response was served from the per-segment-capable static\n * prerender, rather than the old prefetching flow. If this fails, it implies\n * that PPR is disabled on the route.\n */\nfunction wasServedFromPerSegmentCache(response: RSCResponse<unknown>): boolean {\n return (\n response.headers.get(NEXT_DID_POSTPONE_HEADER) === '2' ||\n // In output: \"export\" mode, we can't rely on response headers. But if we\n // receive a well-formed response, we can assume it's a static response,\n // because all data is static in this mode.\n isOutputExportMode\n )\n}\n\n/**\n * Reads a prefetch response body to completion — optionally truncating at\n * `byteLimit` — and returns the bytes as a single contiguous buffer.\n *\n * Buffering the entire response before passing it to the Flight client\n * ensures that when Flight processes the stream, all model data is available\n * synchronously. This is what makes the decode boundary's thenable-status\n * reads (vary params, isPartial, staleTime — see decode-server-response)\n * sound: if data arrived in multiple network chunks, the thenables might not\n * yet be fulfilled. (`decodeBufferedStage` performs the matching\n * single-chunk decode.)\n *\n * TODO: There are too many intermediate stream transformations in the\n * prefetch response pipeline (e.g. stripIsPartialByte, this function).\n * These could all be consolidated into a single transformation. Refactor\n * once the cached navigations experiment lands.\n */\nexport async function bufferPrefetchResponseBody(\n body: ReadableStream<Uint8Array>,\n byteLimit?: number\n): Promise<Uint8Array> {\n // Read the response from the network, optionally truncating at byteLimit.\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n if (byteLimit !== undefined && size + value.byteLength >= byteLimit) {\n const remaining = byteLimit - size\n if (remaining > 0) {\n chunks.push(\n value.byteLength > remaining ? value.subarray(0, remaining) : value\n )\n size += remaining\n }\n reader.cancel()\n break\n }\n chunks.push(value)\n size += value.byteLength\n }\n // Concatenate into a single chunk so that Flight's processBinaryChunk\n // processes all rows synchronously in one call. Multiple chunks would not\n // be sufficient: even though reader.read() resolves as a microtask for\n // already-enqueued data, the `await` continuation from\n // createFromReadableStream can interleave between chunks. If the root\n // model row isn't the first row (e.g. outlined values come first), the\n // PromiseResolveThenableJob from `await` can cause the root to initialize\n // eagerly, scheduling the continuation before remaining chunks (including\n // promise value rows) are processed. A single chunk avoids this.\n if (chunks.length === 1) {\n return chunks[0]\n } else if (chunks.length > 1) {\n const buffer = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n buffer.set(chunk, offset)\n offset += chunk.byteLength\n }\n return buffer\n } else {\n return new Uint8Array(0)\n }\n}\n\n/**\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 */\nfunction createIncrementalPrefetchResponseStream(\n originalFlightStream: ReadableStream<Uint8Array>,\n onStreamClose: () => void,\n onResponseSizeUpdate: (size: number) => void\n): ReadableStream<Uint8Array> {\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\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}\n\nfunction addSegmentPathToUrlInOutputExportMode(\n url: URL,\n segmentPath: SegmentRequestKey\n): URL {\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('/')\n ? staticUrl.pathname.slice(0, -1)\n : staticUrl.pathname\n const staticExportFilename =\n convertSegmentPathToStaticExportFilename(segmentPath)\n staticUrl.pathname = `${routeDir}/${staticExportFilename}`\n return staticUrl\n }\n return url\n}\n\n/**\n * Checks whether the new fetch strategy is likely to provide more content than the old one.\n *\n * Generally, when an app uses dynamic data, a \"more specific\" fetch strategy is expected to provide more content:\n * - `LoadingBoundary` only provides static layouts\n * - `StaticShell` provides the shell-stage variant extracted from a static response —\n * param-dependent content reduced to pending fallbacks, and never any content that\n * depends on session data (cookies, headers)\n * - `RuntimeShell` provides the shell stage rendered by a runtime request, which can\n * additionally include shell-stage content that depends on session data\n * - `PPR` can provide static shells for each segment, including prerendered param-dependent\n * content at concrete paths (excluding dynamic data)\n * - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies\n * - `Full` includes all the content, even if it uses dynamic data\n *\n * However, it's possible that a more specific fetch strategy *won't* give us more content if:\n * - a segment is fully static\n * (then, `PPR`/`PPRRuntime`/`Full` will all yield equivalent results)\n * - providing searchParams/params/cookies doesn't reveal any more content, e.g. because of an `await connection()`\n * (then, `PPR` and `PPRRuntime` will yield equivalent results, only `Full` will give us more)\n * Because of this, when comparing two segments, we should also check if the existing segment is partial.\n * If it's not partial, then there's no need to prefetch it again, even using a \"more specific\" strategy.\n * There's currently no way to know if `PPRRuntime` will yield more data that `PPR`, so we have to assume it will.\n *\n * Also note that, in practice, we don't expect to be comparing `LoadingBoundary` to `PPR`/`PPRRuntime`,\n * because a non-PPR-enabled route wouldn't ever use the latter strategies. It might however use `Full`.\n */\nexport function canNewFetchStrategyProvideMoreContent(\n currentStrategy: FetchStrategy,\n newStrategy: FetchStrategy\n): boolean {\n return currentStrategy < newStrategy\n}\n\nfunction getStaleAtFromHeader(\n now: number,\n response: RSCResponse<unknown>\n): number {\n const staleTimeSeconds = parseInt(\n response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER) ?? '',\n 10\n )\n\n const staleTimeMs = !isNaN(staleTimeSeconds)\n ? getStaleTimeMs(staleTimeSeconds)\n : STATIC_STALETIME_MS\n\n return now + staleTimeMs\n}\n\n/**\n * Reads a stale-at time by `await`ing the staleTime async iterable (last\n * yielded value wins) and, if a `response` is given and the iterable yields\n * nothing, falling back to the `Next-Router-Stale-Time` header.\n *\n * The async form is required for the two things `readFulfilledStaleAt` can't\n * do: the header fallback, and reading a dynamic `Full` response\n * (fetchStrategy.Full with Partial Prefetching disabled) — the one response\n * kind that isn't buffered before it's read, so its iterable values must be\n * awaited rather than drained synchronously off their thenable status.\n *\n * Buffered responses (static PPR, runtime prefetch, stage decodes) don't need\n * the async form: segment bundles and the shell-stage decode already read\n * staleTime synchronously via `readFulfilledStaleAt`, and the remaining\n * buffered callers here could be moved to it too.\n */\nexport async function resolveStaleAt(\n now: number,\n staleTimeIterable: AsyncIterable<number> | undefined,\n response?: RSCResponse<unknown>\n): Promise<number> {\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: number | undefined\n for await (const value of staleTimeIterable) {\n staleTimeSeconds = value\n }\n\n if (staleTimeSeconds !== undefined) {\n const staleTimeMs = isNaN(staleTimeSeconds)\n ? STATIC_STALETIME_MS\n : getStaleTimeMs(staleTimeSeconds)\n\n return now + staleTimeMs\n }\n }\n\n if (response !== undefined) {\n return getStaleAtFromHeader(now, response)\n }\n\n return now + STATIC_STALETIME_MS\n}\n\n/**\n * Fire-and-forget (\"spawn\"), unlike the synchronous cache-write family it\n * wraps (writeServerResponseIntoCache and below): the stage's staleTime must\n * be resolved asynchronously from the response's own `s` field before the\n * write can happen, and failures are swallowed — a failed cache write is not\n * fatal to the render that produced the response.\n *\n * Writes the static stage of a navigation response — or of the initial RSC\n * payload — into the segment cache, so subsequent navigations can serve\n * cached static segments instantly.\n */\nexport function spawnStaticStageCacheWrite(\n now: number,\n response: NavigationFlightResponse,\n isResponsePartial: boolean,\n // The navigation response's headers, used to derive the buildId for the\n // write-layer build check (the deployment header, falling back to the\n // response's `b` field). Null for the initial payload, which arrived in\n // the HTML document and has no build-id check.\n responseHeaders: Headers | null,\n baseTree: FlightRouterState,\n renderedSearch: string,\n // The map the work that spawned this response's request is bound to. See\n // writeServerResponseIntoCache.\n map: CacheMap<SegmentCacheEntry>\n): void {\n const buildId =\n responseHeaders !== null\n ? (responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? response.b)\n : undefined\n resolveStaleAt(now, response.s)\n .then((staleAt) => {\n // TODO: This entire write is legacy and will be deleted in a future\n // PR: caching is organized around the conceptual shell vs not-shell\n // distinction, not around the static vs runtime render stages, so a\n // static-stage write has no place in the model. It's kept only until\n // its removal PR lands — do not extend it (e.g. with shell\n // extraction).\n writeServerResponseIntoCache(\n now,\n FetchStrategy.PPR,\n response,\n baseTree,\n // The base tree is the navigation's current tree, not a prediction;\n // divergence from it carries no signal.\n null,\n // Navigation responses always include the param values in the tree,\n // so there's no pathname to parse them from (nor a need to).\n null,\n renderedSearch,\n buildId,\n staleAt,\n isResponsePartial,\n null,\n // No owned entries; every write is a detached upsert.\n null,\n null,\n map\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the render\n // completed normally, we just won't write into the cache.\n })\n}\n\n/**\n * Decodes an embedded runtime prefetch Flight stream and writes it into the\n * segment cache, so subsequent navigations can serve runtime-prefetchable\n * content from cache without a separate prefetch request.\n *\n * The stream is buffered before it's decoded, like every prefetch response\n * that carries cache metadata: the shell byte offset (`a`) and staleTime are\n * read synchronously off their thenable status, and extracting a distinct\n * shell stage requires re-decoding a truncated copy of the same bytes. The\n * writes go through the shared payload-pair orchestration\n * (writeResponsePayloadsIntoCache): the full payload is written at\n * PPRRuntime and a distinct shell stage at the shell tier (RuntimeShell),\n * like any other runtime prefetch response. This flow owns no pending\n * entries, so every write is a detached upsert.\n */\nexport async function writeRuntimePrefetchStreamIntoCache(\n now: number,\n runtimePrefetchStream: ReadableStream<Uint8Array>,\n baseTree: FlightRouterState,\n renderedSearch: string,\n // The map the work that spawned this response's request is bound to. See\n // writeServerResponseIntoCache.\n map: CacheMap<SegmentCacheEntry>\n): Promise<void> {\n const { stream, isPartial } = await stripIsPartialByte(runtimePrefetchStream)\n\n const buffer = await bufferPrefetchResponseBody(stream)\n const serverData = await decodeBufferedStage<NavigationFlightResponse>(\n buffer,\n undefined\n )\n\n // Extract the shell payload, when the response carries one. Same wire\n // convention as the other live-render responses (see\n // resolveShellStageResponse): `a` absent means the render wasn't staged —\n // no shell exists; `null` means the shell IS the full response; a number\n // is the byte boundary of a distinct shell prefix, which is re-decoded\n // from a truncated copy of the buffer. An unreadable `a` — pending or\n // rejected, which only an aborted render produces — conservatively reads\n // as no shell: the full payload is still written, there's just no shell\n // stage to extract from it.\n let shellResponse: NavigationFlightResponse | null = null\n if (serverData.a !== undefined) {\n const shellByteLength = readFulfilledValue(serverData.a, undefined)\n if (shellByteLength === null) {\n shellResponse = serverData\n } else if (shellByteLength !== undefined) {\n try {\n shellResponse = await decodeBufferedStage<NavigationFlightResponse>(\n buffer.subarray(0, shellByteLength),\n undefined\n )\n } catch {\n // The truncated prefix couldn't be decoded. Treat it as if no shell\n // exists; the full payload is still usable.\n shellResponse = null\n }\n }\n }\n\n writeResponsePayloadsIntoCache(\n now,\n // A runtime prefetch stream is by definition a runtime prefetch.\n FetchStrategy.PPRRuntime,\n serverData,\n shellResponse,\n baseTree,\n // The base tree is the navigation's current tree, not a prediction;\n // divergence from it carries no signal.\n null,\n // Navigation responses always include the param values in the tree, so\n // there's no pathname to parse them from (nor a need to).\n null,\n renderedSearch,\n serverData.b,\n // The response is fully buffered, so staleTime is read synchronously.\n readFulfilledStaleAt(now, serverData.s),\n isPartial,\n null,\n // This flow owns no pending entries; every write is a detached upsert.\n null,\n // Detached writes aren't sized; see writeResponsePayloadsIntoCache.\n null,\n map\n )\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 */\nexport async function stripIsPartialByte(\n stream: ReadableStream<Uint8Array>\n): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> {\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\n const reader = stream.getReader()\n const { done, value } = await reader.read()\n\n if (done || !value || value.byteLength === 0) {\n return {\n stream: new ReadableStream({ start: (c) => c.close() }),\n isPartial: defaultIsPartial,\n }\n }\n\n const firstByte = value[0]\n const hasMarker = firstByte === 0x23 || firstByte === 0x7e\n const isPartial = hasMarker ? firstByte === 0x7e : defaultIsPartial\n\n const remainder = hasMarker\n ? value.byteLength > 1\n ? value.subarray(1)\n : null\n : value\n\n return {\n isPartial,\n stream: new ReadableStream<Uint8Array>({\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 * Decoding of RSC server responses (the transport format defined in\n * shared/lib/rsc-transport) into the client's own representations. This is\n * the only place on the client that consumes transport types; everything\n * downstream operates on RouteTree / NavigationSeed / CacheNode.\n */\n\nimport type {\n FlightRouterState,\n Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type {\n PartialTransportData,\n PartialTransportNode,\n TransportSegment,\n} from '../../../shared/lib/rsc-transport'\nimport { readFulfilledValue } from '../../../shared/lib/rsc-transport'\nimport type { VaryParamsIterable } from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport { decodeVaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n type SegmentRequestKey,\n ROOT_SEGMENT_REQUEST_KEY,\n appendSegmentRequestKeyPart,\n createSegmentRequestKeyPart,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport {\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport {\n doesStaticSegmentAppearInURL,\n getCacheKeyForDynamicParam,\n parseDynamicParamFromURLPart,\n} from '../../route-params'\nimport type { NormalizedSearch } from './cache-key'\nimport { splitPathnameIntoParts } from './cache-key'\nimport type { PartialVaryPath, VaryPath } from './vary-path'\nimport {\n appendLayoutVaryPath,\n finalizeVaryPath,\n getPartialVaryPath,\n getShellSegmentVaryPath,\n} from './vary-path'\nimport {\n type RouteTree,\n type RootRouteTree,\n type RSCSegmentData,\n type RefreshState,\n type RouteTreeAccumulator,\n convertFlightRouterStateToRouteTree,\n convertRootFlightRouterStateToRouteTree,\n createMetadataRouteTree,\n createRootRouteTree,\n getHeadRequestKey,\n} from './cache'\nimport { computeDynamicStaleAt } from './bfcache'\n\nexport type NavigationSeed = {\n renderedSearch: NormalizedSearch\n /**\n * The decoded response. The head's `data` is decoded exactly like a segment\n * node's: null when the response carries no head.\n */\n root: RootRouteTree<RSCSegmentData | null>\n dynamicStaleAt: number\n // Whether the response rendered a segment whose identity differs from the\n // base tree's at the same position (inactive parallel route branches are\n // expected to differ and don't count). Only meaningful when the base is a\n // request tree derived from a cached route entry, as during a prefetch:\n // divergence then means the entry doesn't describe what the server renders\n // — the URL has a rewrite that behaves dynamically (see\n // fetchSegmentPrefetchesUsingRuntimeRequest). During a navigation the base\n // is the current page's tree, so divergence carries no signal. False when\n // there was no base to compare against.\n treeDivergedFromBase: boolean\n}\n\n/**\n * During a client navigation or prefetch, the server responds with a\n * transport tree that covers only the parts of the route that have changed.\n * This overlays it onto the base tree to produce a full RouteTree — slots the\n * response carries no information about are reused from the client's current\n * state — with the response's render output (RSCSegmentData) attached to\n * each node.\n *\n * \"Create\", not \"decode\": callers may pass no transport data at all\n * (refreshes and history restores do), in which case this converts the base\n * tree alone rather than decoding a response.\n */\nexport function createNavigationSeed(\n now: number,\n // Null when the response is not an overlay over existing client state —\n // per-segment prefetch responses, whose root-anchored tree covers its own\n // spine. Must be non-null when transportData is null (there'd be nothing\n // to convert otherwise).\n currentTree: FlightRouterState | null,\n transportData: PartialTransportData | null,\n // The response's root vary params (its `r` field): the root params\n // accessed anywhere in the response, emitted once at the response level\n // and unioned into the head's and every segment's own drained set here at\n // the decode boundary. Pass null when the response streams in\n // incrementally (navigation and reducer flows): the wire iterables can\n // only be drained completely from a fully-buffered response, so their sets\n // decode as null (\"unknown; key on all params\") without touching the wire\n // iterables.\n rootVaryParams: VaryParamsIterable | null,\n // Whether anything in the response is not fully resolved: dynamic holes, runtime holes, anything suspended.\n // Boolean-form nodes resolve their partiality to this value (their wire\n // boolean is a render-wide constant that carries no per-node information —\n // see decodeTransportNode), and under Cache Components so does a\n // boolean-form head (see the head read below); staged (promise-form)\n // nodes encode it per-node and ignore it. Only segment-cache writes\n // consume the decoded partiality, so callers whose seeds are never\n // written to the cache may pass the conservative value (true).\n isResponsePartial: boolean,\n // The pathname the response was rendered for. Required to resolve dynamic\n // segments the server sent without a param value (`k: null`); see\n // decodeTransportTreeIntoRouteTree. Callers whose responses always carry\n // concrete values (navigation responses) may pass null.\n renderedPathname: string | null,\n // Already normalized by the response reader (see getRenderedSearch); the\n // router state stores it as a plain string, so it is re-branded here.\n renderedSearch: string,\n // Where to key the head. Null derives it from the route's own first page\n // node (see createRouteTreeNode). Per-segment prefetch payloads pass the\n // route's own metadata vary path instead: a standalone head response's tree\n // is a bare root identity with no page node.\n metadataVaryPath: VaryPath | null,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n const normalizedRenderedSearch = renderedSearch as NormalizedSearch\n const acc: RouteTreeAccumulator = {\n metadataVaryPath: null,\n treeDivergedFromBase: false,\n }\n let routeTree: RouteTree<RSCSegmentData | null>\n let headData: RSCSegmentData | null = null\n if (transportData !== null) {\n routeTree = decodeTransportTreeIntoRouteTree(\n transportData.t,\n currentTree,\n rootVaryParams,\n isResponsePartial,\n renderedPathname,\n normalizedRenderedSearch,\n acc\n )\n const transportHead = transportData.h\n if (transportHead !== undefined) {\n // The wire form of `p` determines which signal is authoritative for\n // the head's partiality, mirroring the per-node rule in\n // decodeTransportNode:\n //\n // - Promise form (per-segment prefetch responses, fully buffered\n // before they're decoded): partiality is encoded exactly, per node,\n // via the staged encoding, so the thenable-status read is\n // authoritative.\n // - Boolean form (navigation and live-render responses): when Cache\n // Components is enabled, the server's flag (isPossiblyPartialHead in\n // app-render.tsx) is unreliable: it's computed before the head is\n // serialized, so it's conservatively `true` for every\n // statically-generated PPR page — even pages whose head is actually\n // complete — and it's `false` for live-render responses whose head\n // is actually partial (e.g. a route with an async\n // `generateMetadata`). So we ignore it and derive the head's\n // partiality from whether the response itself was partial, exactly\n // as the per-node rule does for segments. A non-partial response\n // carries a complete head; a partial (postponed) one does not.\n // Without Cache Components, the server sends the correct\n // isHeadPartial, so the wire boolean is used as-is.\n headData = {\n rsc: transportHead.r,\n isPartial:\n typeof transportHead.p === 'boolean'\n ? process.env.__NEXT_CACHE_COMPONENTS\n ? isResponsePartial\n : transportHead.p\n : readFulfilledIsPartial(transportHead.p),\n varyParams: decodeVaryParams(transportHead.v, rootVaryParams),\n staleTimeSeconds:\n transportHead.s !== undefined\n ? readFulfilledStaleTimeSeconds(transportHead.s)\n : null,\n }\n }\n } else {\n if (currentTree === null) {\n throw new InvariantError(\n 'Cannot convert a server response with no transport data and no ' +\n 'base tree.'\n )\n }\n routeTree = convertRootFlightRouterStateToRouteTree(\n currentTree,\n normalizedRenderedSearch,\n acc\n )\n }\n\n if (metadataVaryPath === null) {\n metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n // Every route renders a page, so a rendered tree always has a node to\n // key the head under.\n throw new InvariantError(\n 'Cannot key the head of a server response: its tree has no page ' +\n 'segment.'\n )\n }\n }\n\n return {\n root: createRootRouteTree(\n routeTree,\n createMetadataRouteTree(\n metadataVaryPath,\n routeTree.prefetchHints,\n headData\n )\n ),\n renderedSearch: normalizedRenderedSearch,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n treeDivergedFromBase: acc.treeDivergedFromBase,\n }\n}\n\n/**\n * Creates a RouteTree node for a segment, with its identity and cache-key\n * information (vary paths, the normalized segment value, the refresh state)\n * initialized, and the remaining fields set to their defaults. The caller\n * finishes initializing those in place after recursing into the children.\n * Shared by FlightRouterState conversion, transport decoding, and subtree\n * rebasing so their routing identity stays consistent.\n */\nexport function createRouteTreeNode<TData>(\n originalSegment: FlightRouterStateSegment,\n isRootParam: boolean,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialVaryPath | null,\n renderedSearch: NormalizedSearch,\n refreshState: RefreshState | null,\n acc: RouteTreeAccumulator\n): RouteTree<TData | null> {\n let segment: FlightRouterStateSegment\n let partialVaryPath: PartialVaryPath | null\n let varyPath: VaryPath\n if (Array.isArray(originalSegment)) {\n const paramCacheKey = originalSegment[1]\n const paramName = originalSegment[0]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n paramCacheKey,\n paramName,\n isRootParam\n )\n varyPath = finalizeVaryPath(requestKey, null, partialVaryPath)\n segment = originalSegment\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n segment = PAGE_SEGMENT_KEY\n varyPath = finalizeVaryPath(requestKey, renderedSearch, partialVaryPath)\n // The head is keyed under the route's own first page and varies on the\n // same params as that page (see getHeadRequestKey). A page reused from\n // another URL carries a refresh state and never keys it.\n if (refreshState === null && acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeVaryPath(\n getHeadRequestKey(requestKey),\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n segment = originalSegment\n varyPath = finalizeVaryPath(requestKey, null, partialVaryPath)\n }\n }\n return {\n requestKey,\n segment,\n shellVaryPath: getShellSegmentVaryPath(varyPath),\n refreshState,\n data: null,\n varyPath,\n slots: null,\n prefetchHints: 0,\n }\n}\n\n/**\n * Decodes a response's transport tree into a RouteTree, using the client's\n * current router state as the base for the parts of the route the response\n * carries no information about.\n *\n * The response is an overlay over the base:\n *\n * - Nodes with rendered output — and nodes with no data at all, which are\n * server-sent structure whose output the client fetches lazily — are\n * authoritative: their identity, hints, and subtree come entirely from\n * the response.\n * - Skipped nodes (data with a null rsc) sit on the path from the root down\n * to the rendered subtrees. The client is expected to already have them,\n * so their refresh state and hints are inherited from the base tree, and\n * any slot the response doesn't mention is reused from the base as-is.\n *\n * TODO: The base is a FlightRouterState only because that's the\n * representation the client router currently renders from (the router\n * reducer's `state.tree`, which the render tree and layout-router are\n * keyed against). Once the rendering path is updated to use RouteTree as its\n * source of truth, the base tree here can be a RouteTree, and the base-only\n * conversion path (convertFlightRouterStateToRouteTree) goes away with it.\n */\nexport function decodeTransportTreeIntoRouteTree(\n transportNode: PartialTransportNode,\n baseRouterState: FlightRouterState | null,\n // The response's root vary params, unioned into every segment's drained\n // set. Pass null when vary params are unavailable or unwanted; see\n // createNavigationSeed.\n rootVaryParams: VaryParamsIterable | null,\n // The response-level partiality, which boolean-form nodes resolve their\n // own partiality to; see createNavigationSeed.\n isResponsePartial: boolean,\n // The pathname the response was rendered for (from the response headers).\n // Required to resolve dynamic segments the server sent without a param\n // value (`k: null` — per-segment prefetch responses omit the value to stay\n // cacheable across param values); the client parses the value from the\n // pathname instead. Callers whose responses always carry concrete values\n // (navigation responses) may pass null.\n renderedPathname: string | null,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n const pathnameParts =\n renderedPathname !== null ? splitPathnameIntoParts(renderedPathname) : null\n return decodeTransportNode(\n transportNode,\n resolveTransportSegment(transportNode.s, pathnameParts, 0),\n baseRouterState ?? undefined,\n baseRouterState ?? undefined,\n rootVaryParams,\n isResponsePartial,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n pathnameParts,\n 0,\n acc\n )\n}\n\n/**\n * Converts a segment's wire identity to the client `Segment` type, resolving\n * dynamic segments whose param value the server omitted (`k: null`) by\n * parsing the value from the rendered pathname. `pathnamePartsIndex` is the\n * URL position this segment occupies (tracked by the tree walk: incremented\n * only for segments that appear in the URL, so route groups and other\n * virtual segments don't consume a part).\n */\nfunction resolveTransportSegment(\n transportSegment: TransportSegment,\n pathnameParts: Array<string> | null,\n pathnamePartsIndex: number\n): FlightRouterStateSegment {\n if (typeof transportSegment === 'string') {\n return transportSegment\n }\n const paramKey = transportSegment.k\n if (paramKey !== null) {\n return [\n transportSegment.n,\n paramKey,\n transportSegment.t,\n transportSegment.s,\n ]\n }\n if (pathnameParts === null) {\n throw new InvariantError(\n 'Cannot resolve a dynamic segment that has no param value: the ' +\n 'response provides no rendered pathname to parse it from.'\n )\n }\n const paramValue = parseDynamicParamFromURLPart(\n transportSegment.t,\n pathnameParts,\n pathnamePartsIndex\n )\n return [\n transportSegment.n,\n getCacheKeyForDynamicParam(paramValue),\n transportSegment.t,\n transportSegment.s,\n ]\n}\n\nfunction doSegmentsMatch(\n baseSegment: FlightRouterStateSegment,\n segment: FlightRouterStateSegment\n): boolean {\n if (typeof baseSegment === 'string' || typeof segment === 'string') {\n // Static segments have to match exactly.\n return baseSegment === segment\n }\n // Both segments are dynamic. The static sibling hints aren't part of the\n // segment's identity, so only compare the param name, type, and value.\n const [baseParamName, baseParamValue, baseParamType] = baseSegment\n const [paramName, paramValue, paramType] = segment\n return (\n baseParamName === paramName &&\n baseParamType === paramType &&\n baseParamValue === paramValue\n )\n}\n\nfunction decodeTransportNode(\n node: PartialTransportNode,\n // The node's identity, already resolved by the caller (the parent's child\n // loop, which has the URL position needed to parse omitted param values).\n originalSegment: FlightRouterStateSegment,\n base: FlightRouterState | undefined,\n // The base node to compare segment identities against (see\n // NavigationSeed.treeDivergedFromBase). Tracked separately from `base`:\n // inheritance drops the base inside authoritative subtrees, where the\n // comparison must continue, and keeps it through inactive parallel routes,\n // where the comparison must stop.\n compareBase: FlightRouterState | undefined,\n rootVaryParams: VaryParamsIterable | null,\n isResponsePartial: boolean,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialVaryPath | null,\n parentRenderedSearch: NormalizedSearch,\n pathnameParts: Array<string> | null,\n // The URL position this node's children read from.\n pathnamePartsIndex: number,\n acc: RouteTreeAccumulator\n): RouteTree<RSCSegmentData | null> {\n const nodeData = node.d\n const inheritsFromBase = nodeData !== undefined && nodeData.r === null\n // The base node this position inherits from, when it does.\n const inheritedBase = inheritsFromBase ? base : undefined\n\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n // Every transport node echoes the segment's identity, even \"skipped\"\n // ones, so each position can be compared against the base.\n const transportSegment = node.s\n if (typeof transportSegment !== 'string' && transportSegment.k == null) {\n // The server omitted the param value for the client to parse from the\n // URL (see resolveTransportSegment). Nothing to compare; the children\n // are still checked.\n } else {\n const baseSegment = compareBase[0]\n if (originalSegment === DEFAULT_SEGMENT_KEY) {\n // A default filled in by the server is not a claim about the\n // position's identity.\n } else if (!doSegmentsMatch(baseSegment, originalSegment)) {\n acc.treeDivergedFromBase = true\n }\n }\n }\n\n const baseHints = inheritedBase !== undefined ? (inheritedBase[4] ?? 0) : 0\n let prefetchHints = node.h ?? baseHints\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam = (prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n // Inherited positions keep the base tree's refresh state. Its rendered\n // search is updated to this response's, since all pages within the same\n // response share the same search value. (The refresh state acts like a\n // \"context provider\" for inactive parallel routes.)\n const baseCompressedRefreshState =\n inheritedBase !== undefined ? (inheritedBase[2] ?? null) : null\n const refreshState: RefreshState | null =\n baseCompressedRefreshState !== null\n ? {\n canonicalUrl: baseCompressedRefreshState[0] as string,\n renderedSearch: parentRenderedSearch,\n }\n : null\n const renderedSearch =\n refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n const tree = createRouteTreeNode<RSCSegmentData>(\n originalSegment,\n isRootParam,\n requestKey,\n parentPartialVaryPath,\n renderedSearch,\n refreshState,\n acc\n )\n const partialVaryPath = getPartialVaryPath(tree.varyPath)\n\n let slots: Map<string, RouteTree<RSCSegmentData | null>> | null = null\n const transportChildren = node.c\n const baseChildren =\n inheritedBase !== undefined ? inheritedBase[1] : undefined\n if (transportChildren !== undefined) {\n for (const [parallelRouteKey, childNode] of transportChildren) {\n const childBase =\n baseChildren !== undefined ? baseChildren[parallelRouteKey] : undefined\n const childSegment = resolveTransportSegment(\n childNode.s,\n pathnameParts,\n pathnamePartsIndex\n )\n\n let childCompareBase: FlightRouterState | undefined\n if (compareBase !== undefined && !acc.treeDivergedFromBase) {\n const childCompareCandidate = compareBase[1][parallelRouteKey]\n if (childCompareCandidate === undefined) {\n // A slot the base tree doesn't have. Unless the server merely\n // filled it with a default, the trees have different structures.\n if (childSegment !== DEFAULT_SEGMENT_KEY) {\n acc.treeDivergedFromBase = true\n }\n } else if ((childCompareCandidate[2] ?? null) !== null) {\n // The base branch carries a refresh state: an inactive parallel\n // route reused from a different route (e.g. a \"default\" slot). The\n // server's answer is expected to differ, so skip the branch.\n } else {\n childCompareBase = childCompareCandidate\n }\n }\n\n // Only advance the URL position for segments that appear in the URL.\n // Virtual segments, like route groups, don't consume a part.\n const childDoesAppearInURL =\n typeof childSegment === 'string'\n ? doesStaticSegmentAppearInURL(childSegment)\n : true\n const childPathnamePartsIndex = childDoesAppearInURL\n ? pathnamePartsIndex + 1\n : pathnamePartsIndex\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childSegment)\n )\n const childTree = decodeTransportNode(\n childNode,\n childSegment,\n childBase,\n childCompareBase,\n rootVaryParams,\n isResponsePartial,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n pathnameParts,\n childPathnamePartsIndex,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n if (baseChildren !== undefined) {\n // Slots the response carries no information about are reused from the\n // base tree, structure-only.\n for (const parallelRouteKey in baseChildren) {\n if (\n transportChildren !== undefined &&\n transportChildren.has(parallelRouteKey)\n ) {\n continue\n }\n const childBase = baseChildren[parallelRouteKey]\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n createSegmentRequestKeyPart(childBase[0])\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childBase,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = new Map()\n }\n slots.set(parallelRouteKey, childTree)\n }\n }\n\n if (inheritsFromBase) {\n // Recompute the propagated \"subtree\" prefetch hints for this segment,\n // since its children may combine response and base subtrees. Mirrors the\n // propagation done on the server in createTransportTreeFromLoaderTree.\n let propagated = prefetchHints & ~SubtreePrefetchHints\n if (slots !== null) {\n for (const childTree of slots.values()) {\n propagated = propagateSubtreeBits(propagated, childTree.prefetchHints)\n }\n }\n prefetchHints = propagated\n }\n\n if (nodeData !== undefined) {\n tree.data = {\n rsc: nodeData.r,\n // The wire form of `p` determines which signal is authoritative for\n // this segment's partiality:\n //\n // - Boolean form (navigation and live-render responses): the wire\n // value is a render-wide constant (`isPossiblyPartialResponse` in\n // create-component-tree.tsx), identical on every node, so it carries\n // no per-node information — and it's inaccurate in both directions:\n // `true` for every node of a statically-generated PPR page even when\n // the page is actually complete, and `false` for every node of a\n // dynamic render even when this decode is a truncated stage prefix\n // whose dynamic rows landed past the boundary. The caller's\n // response-level value captures both (the `~`/`#` marker for whole\n // responses; truncation-implied partiality for stage decodes), so it\n // replaces the wire boolean here.\n // - Promise form (per-segment prefetch responses, fully buffered\n // before they're decoded): partiality is encoded per node, exactly,\n // and survives the truncated shell double-decode — a fulfillment row\n // past the boundary reads as partial. The fulfillment (or its\n // absence) is already visible on the thenable's status, so it's\n // authoritative and the response-level value is ignored.\n isPartial:\n typeof nodeData.p === 'boolean'\n ? isResponsePartial\n : readFulfilledIsPartial(nodeData.p),\n // The source of the params this segment's output depends on: the\n // segment's wire iterable, drained here, unioning in the response-level\n // root params (same buffered-read reasoning as `p` above), or decoded\n // as null (\"unknown\") when the caller passed no root params — see\n // createNavigationSeed.\n varyParams: decodeVaryParams(nodeData.v, rootVaryParams),\n // Per-node staleTime, only present in per-segment prefetch responses\n // (same buffered-read reasoning as `p` above).\n staleTimeSeconds:\n nodeData.s !== undefined\n ? readFulfilledStaleTimeSeconds(nodeData.s)\n : null,\n }\n }\n\n tree.slots = slots\n tree.prefetchHints = prefetchHints\n return tree\n}\n\n// A sentinel `readFulfilledValue` fallback that no fulfillment can produce,\n// for reads that only care whether the row settled at all.\nconst notFulfilled = Symbol()\n\n/**\n * Reads a segment's partialness from its `isPartial` promise. (The\n * fulfillment value is void — partialness is encoded as the ABSENCE of a\n * fulfillment.) The server fulfills it only for a fully-static segment and\n * leaves it pending for a partial one (see the promise form of\n * `TransportSegmentData['p']`), so partial == not fulfilled. A pending row,\n * or a truncated shell decode whose fulfillment landed past the boundary,\n * reads as partial, which is correct either way.\n */\nexport function readFulfilledIsPartial(isPartial: Promise<void>): boolean {\n return readFulfilledValue(isPartial, notFulfilled) === notFulfilled\n}\n\n/**\n * Reads a staleTime (in seconds) from the staleTime async iterable of a\n * fully-buffered response. Because the bytes are all present, each yielded\n * value is already visible on its chunk's thenable status, so this drains\n * synchronously and takes the last value (the final staleTime, matching the\n * async `resolveStaleAt` in cache.ts). Returns null when no usable value was\n * yielded — e.g. a truncated shell decode whose value landed past the\n * boundary — so the caller can fall back to its response-level staleness.\n */\nexport function readFulfilledStaleTimeSeconds(\n staleTime: AsyncIterable<number>\n): number | null {\n const iterator = staleTime[Symbol.asyncIterator]()\n let staleTimeSeconds: number | undefined\n while (true) {\n const chunk = readFulfilledValue(iterator.next(), undefined)\n if (chunk === undefined || chunk.done) {\n break\n }\n staleTimeSeconds = chunk.value\n }\n if (staleTimeSeconds === undefined || isNaN(staleTimeSeconds)) {\n return null\n }\n return staleTimeSeconds\n}\n","import { getPreLockFetch } from './navigation-testing-lock'\n\n/**\n * Internal `fetch` used by the Next.js client router.\n *\n * When the Instant Navigation Testing API is enabled, the navigation lock may\n * install a blocking override on `window.fetch` for the duration of a lock\n * scope. To let internal fetches bypass the lock, callers go through a wrapper\n * that falls back to the pre-lock fetch captured at lock-acquire time.\n *\n * When the testing API is not enabled, this calls window.fetch directly.\n */\nfunction fetchInternal(\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const preLockFetch = getPreLockFetch()\n if (preLockFetch !== null) {\n return preLockFetch(input, init)\n }\n }\n return fetch(input, init)\n}\n\nexport { fetchInternal as fetch }\n","import { deleteMapEntry } from './cache-map'\nimport type { UnknownMapEntry } from './cache-map'\nimport { pingPrefetchScheduler } from './scheduler'\n\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.\n\nlet head: UnknownMapEntry | null = null\nlet lruSize: number = 0\n\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: UnknownMapEntry) {\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\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}\n\nexport function updateLruSize(node: UnknownMapEntry, newNodeSize: number) {\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}\n\nexport function deleteFromLru(deleted: UnknownMapEntry) {\n const next = deleted.next\n const prev = deleted.prev\n if (next !== null && prev !== null) {\n lruSize -= deleted.size\n\n deleted.next = null\n deleted.prev = null\n\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}\n\nfunction ensureCleanupIsScheduled() {\n if (lruSize <= maxLruSize) {\n return\n }\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}\n\nexport function cleanup() {\n if (lruSize <= maxLruSize) {\n return\n }\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 * Navigation lock for the Instant Navigation Testing API.\n *\n * Manages the in-memory lock (a promise) that gates dynamic data writes\n * during instant navigation captures, and owns all cookie state\n * transitions (pending → captured-MPA, pending → captured-SPA).\n *\n * External actors (Playwright, devtools) set [0] to start a lock scope\n * and delete the cookie to end one. Next.js writes captured values.\n * The CookieStore handler distinguishes them by value: pending = external,\n * captured = self-write (ignored).\n *\n * This module assumes the Instant Navigation Testing API is enabled. When it\n * is disabled, the bundler resolves this module to\n * `./navigation-testing-lock.disabled` instead (see\n * `create-compiler-aliases.ts` for webpack and\n * `crates/next-core/src/next_import_map.rs` for Turbopack), so none of this\n * code ships in the browser bundle.\n */\n\nimport {\n PrefetchHint,\n type FlightRouterState,\n type InstantCookie,\n} from '../../../shared/lib/app-router-types'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue'\nimport { needsSpeculativePrefetch } from './scheduler'\nimport type { SegmentCacheEntry } from './cache'\nimport { createCacheMap, type CacheMap } from './cache-map'\nimport type { PrefetchTaskFetchStrategy } from './types'\n\ntype InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'\n\nfunction parseCookieValue(raw: string): InstantNavCookieState {\n if (raw === '') {\n return 'empty'\n }\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed)) {\n if (parsed.length >= 3) {\n const rawState = parsed[2]\n return rawState === null ? 'mpa' : 'spa'\n }\n }\n } catch {}\n return 'pending'\n}\n\nfunction writeDocumentCookie(\n value: InstantCookie,\n options: { domain?: string | null; path?: string | null }\n): void {\n if (typeof document === 'undefined') {\n return\n }\n let cookie = `${NEXT_INSTANT_TEST_COOKIE}=${JSON.stringify(value)}; Path=${\n options.path ?? '/'\n }`\n if (options.domain) {\n cookie += `; Domain=${options.domain}`\n }\n document.cookie = cookie\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), then\n // write back with the new value. This updates the same cookie entry that the\n // external actor created, regardless of how it was scoped. The read goes\n // through `cookieStore.get` because `document.cookie` exposes only names and\n // values, not the domain/path we need to preserve. The write goes through\n // document.cookie because WebKit exposes Cookie Store on localhost but does\n // not commit cookies written through cookieStore.set() there.\n //\n // Capture the current lockState and compare it in the callback so we only\n // write if the lock we observed at call time is still held. This guards\n // against two races: (a) the scope ended between get and set (lockState is\n // now null), and (b) the scope ended and a new one was acquired in the same\n // gap (lockState is a different object). In either case we must not write —\n // doing so would leak stale state into the next scope or outlive the current\n // one. It cannot close one window, though: the callback can run after an\n // external delete but before the deleted-event handler nulls lockState, so\n // the guard still passes and we resurrect the cookie. The deleted handler\n // clears any such entry once the lock is released (see the `event.deleted`\n // loop below).\n const lockAtCall = lockState\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {\n if (existing && lockState === lockAtCall && lockAtCall !== null) {\n writeDocumentCookie(value, existing)\n }\n })\n}\n\n/**\n * The \"wait for the locked navigation's prefetch to fulfill\" state for a single\n * locked navigation. `promise` resolves when the driving prefetch task\n * completes — which the scheduler only allows after a full pass has observed\n * every segment response it cares about (see `blockTaskOnPendingResponse` in\n * scheduler.ts) — so the navigation reads present data rather than a\n * still-in-flight entry. Owned by the prefetch task (one per navigation, so\n * successive navigations in a scope resolve independently) and also tracked\n * in `NavigationLockState.activePrefetches` so the lock can force-resolve any\n * that are still pending when it's released.\n */\nexport type NavigationLockPrefetch = {\n promise: Promise<void>\n resolve: () => void\n}\n\nexport type NavigationLockState = {\n // Resolves when the lock is released (the testing scope ends). Out-of-band\n // user fetches blocked by `globalFetchOverride` wait on this so they dispatch\n // only once the scope ends. (A locked navigation's *withheld dynamic write*\n // waits on `currentNavigation` instead — see below.)\n released: Promise<void>\n resolveReleased: () => void\n // The pre-lock `window.fetch`, captured at `acquireLock` time and\n // restored at `releaseLock`. Internal Next.js code reads this via\n // `getPreLockFetch` to bypass the override we install on `window.fetch`\n // during a lock scope.\n fetch: typeof fetch\n // Every prefetch-completion state for this scope that hasn't resolved yet.\n // A prefetch removes itself when its driving task completes; on release, any\n // still here are force-resolved so no navigation hangs waiting on a prefetch\n // that the scope ended before it could finish.\n activePrefetches: Set<NavigationLockPrefetch>\n // The scope's private segment cache. Prefetch tasks scheduled while the\n // lock is held are bound to this map instead of the shared one, and a\n // locked navigation inherits the map of the task that drives it (see\n // `segmentCacheMap` in cache.ts). It starts empty, so each instant()\n // navigation observes only data fetched under the lock — a \"clean read\" —\n // and never matches a stale entry left in the shared cache by an earlier\n // navigation, prefetch, or scope. Discarded when the lock is released; its\n // entries are reclaimed by the LRU under memory pressure.\n segmentCacheMap: CacheMap<SegmentCacheEntry>\n // The withheld-data gate for the current locked navigation. A locked\n // navigation's dynamic write waits on this rather than on the scope-wide\n // `released`. Each navigation captures the promise when it begins (via\n // `beginLockedNavigation` or `getCurrentNavigationGate`) and awaits that\n // immutable snapshot, never this mutable field. `beginLockedNavigation`\n // rolls the field over on each new locked navigation: it resolves the\n // current promise — so the *previous* navigation's withheld data is written\n // out and the cache nodes it produced stop holding pending deferred promises\n // that a reused shared segment would otherwise suspend on — then installs a\n // fresh one. `releaseLock` resolves it too. Net effect: only the most recent\n // navigation's data stays withheld; a new navigation always releases the\n // previous one.\n currentNavigation: Promise<void>\n resolveCurrentNavigation: () => void\n}\n\nlet lockState: NavigationLockState | null = null\n\nexport function getPreLockFetch(): typeof fetch | null {\n return lockState !== null ? lockState.fetch : null\n}\n\n/**\n * Creates the \"wait for prefetch to fulfill\" state for one locked navigation,\n * registers it on the current lock, and returns it (the caller stores it on the\n * prefetch task and awaits `.promise`). Returns null if no lock is held.\n * Resolved by the scheduler via `resolveNavigationLockPrefetch` when the\n * driving prefetch task completes.\n */\nexport function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {\n if (lockState !== null) {\n let resolve: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n const prefetch: NavigationLockPrefetch = {\n promise,\n resolve: resolve!,\n }\n lockState.activePrefetches.add(prefetch)\n return prefetch\n }\n return null\n}\n\n/**\n * Returns the current lock scope's private segment cache map, or null when no\n * lock is held. See `NavigationLockState.segmentCacheMap`.\n */\nexport function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {\n return lockState !== null ? lockState.segmentCacheMap : null\n}\n\n/**\n * Called by the scheduler when the locked-navigation prefetch task completes.\n * A task only completes after a full pass observed every segment response it\n * cares about, so the data the navigation will read has settled by this\n * point. Unregisters from the lock (if still held) and resolves. Resolving is\n * idempotent, so it's safe even if the lock already force-resolved this on\n * release.\n */\nexport function resolveNavigationLockPrefetch(\n prefetch: NavigationLockPrefetch\n): void {\n if (lockState !== null) {\n lockState.activePrefetches.delete(prefetch)\n }\n prefetch.resolve()\n}\n\nfunction acquireLock(): void {\n if (lockState !== null) {\n return\n }\n let resolveReleased: () => void\n const released = new Promise<void>((r) => {\n resolveReleased = r\n })\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState = {\n released,\n resolveReleased: resolveReleased!,\n fetch: window.fetch,\n activePrefetches: new Set(),\n segmentCacheMap: createCacheMap(),\n currentNavigation,\n resolveCurrentNavigation: resolveCurrentNavigation!,\n }\n\n // Install the fetch blocker. We only intercept `window.fetch` for the\n // duration of the lock so that — outside of a testing scope — user-\n // installed overrides of `window.fetch` are untouched.\n window.fetch = globalFetchOverride\n}\n\nfunction releaseLock(): void {\n if (lockState === null) {\n return\n }\n // Restore the pre-lock `window.fetch` before resolving the lock promise\n // so any fetches queued on the promise see the restored fetch.\n window.fetch = lockState.fetch\n const { resolveReleased, activePrefetches, resolveCurrentNavigation } =\n lockState\n lockState = null\n // Force-resolve every prefetch that hasn't finished, so a navigation still\n // waiting on one doesn't hang now that the scope is ending.\n for (const prefetch of activePrefetches) {\n prefetch.resolve()\n }\n // Resolve the current locked navigation's withheld-data gate, so its gated\n // dynamic write unblocks now that the scope is ending.\n resolveCurrentNavigation()\n // Resolve the release promise so blocked out-of-band fetches dispatch too.\n resolveReleased()\n}\n\n/**\n * Called when a new locked navigation begins (from `navigate` while the lock is\n * held). Rolls over the lock's withheld-data gate: it resolves the current\n * `currentNavigation` promise — so the *previous* locked navigation's withheld\n * dynamic write proceeds and the cache nodes it produced stop holding pending\n * deferred `rsc` promises that a reused shared segment in this navigation would\n * otherwise suspend on — then installs a fresh promise for this navigation.\n * Only the most recent navigation's data stays withheld; a new navigation\n * always releases the previous one. Returns this navigation's gate — the\n * immutable promise its dynamic write awaits — or null when no lock is held.\n *\n * This is the testing-lock behavior for repeated navigations while paused. It\n * is not a principled fix for the underlying `useDeferredValue`/reuse-suspend\n * behavior; it just ensures that, under the lock, a reused segment never\n * carries a still-pending deferred `rsc` from an earlier navigation.\n */\nexport function beginLockedNavigation(): Promise<void> | null {\n if (lockState === null) {\n return null\n }\n // Release the previous locked navigation's withheld data, then roll over to a\n // fresh gate for this navigation — all without ending the scope.\n lockState.resolveCurrentNavigation()\n let resolveCurrentNavigation: () => void\n const currentNavigation = new Promise<void>((r) => {\n resolveCurrentNavigation = r\n })\n lockState.currentNavigation = currentNavigation\n lockState.resolveCurrentNavigation = resolveCurrentNavigation!\n return currentNavigation\n}\n\n/**\n * Called when the router applies a history traversal (Back/Forward restore) while\n * the testing lock is active. A traversal is not a capture — the mental model is\n * that history entries are already cached — so it must not participate in the\n * current capture. Instead it resets the lock to a fresh pending scope:\n *\n * - `releaseLock` flushes every still-withheld write from prior forward\n * navigations, so the pages you navigated away from finish streaming.\n * - `acquireLock` immediately re-arms a fresh pending scope (no gap where the\n * lock or fetch blocker is down).\n * - the cookie flips from the captured state back to pending.\n *\n * The traversal's own dynamic requests are spawned ungated by the caller (see\n * `restore-reducer`), so they render from cache or fetch normally rather than\n * being withheld.\n */\nexport function resetNavigationLockToPending(): void {\n if (lockState === null || typeof document === 'undefined') {\n return\n }\n releaseLock()\n acquireLock()\n writeCookieValue([0, `c${Math.random()}`])\n}\n\n/**\n * Returns true if the request targets a dev-server endpoint — one of the\n * hot-reloader middleware routes (error overlay, source maps, launch-editor,\n * devtools). They all share the `/__nextjs_` path prefix and are always\n * requested root-relative on the same origin.\n */\nfunction isDevServerRequest(input: RequestInfo | URL): boolean {\n let url: URL\n try {\n url = new URL(\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input\n : input.url,\n window.location.href\n )\n } catch {\n return false\n }\n return (\n url.origin === window.location.origin &&\n url.pathname.startsWith('/__nextjs_')\n )\n}\n\n/**\n * Global fetch override\n *\n * While the navigation lock is active, we install this as `window.fetch` so\n * out-of-band client-side fetches (e.g. `fetch('/api/data')` inside a\n * useEffect) are blocked until the lock is released. Next.js internals\n * bypass the override by importing `fetch` from `./fetch`, which reads the\n * captured pre-lock fetch via `getPreLockFetch`.\n *\n * NOTE: This override only affects environments where the Instant Navigation\n * Testing API is enabled. It has no impact on live production behavior.\n */\nfunction globalFetchOverride(\n input: RequestInfo | URL,\n init?: RequestInit\n): Promise<Response> {\n if (lockState === null) {\n // Lock is not active. Fall through to the global fetch — we reach this\n // only if a caller captured a reference to this function during a lock\n // scope and invoked it after release.\n return fetch(input, init)\n }\n if (process.env.__NEXT_DEV_SERVER && isDevServerRequest(input)) {\n // Dev-server requests must not be gated on the testing lock — blocking\n // them would break the error overlay, source maps, and devtools for the\n // whole scope. Dispatch immediately through the pre-lock fetch. Copy to a\n // local so the call doesn't bind `this` to the lock state object (native\n // fetch throws \"Illegal invocation\" for a foreign receiver).\n const preLockFetch = lockState.fetch\n return preLockFetch(input, init)\n }\n // Block user-initiated fetches until the lock is released, then dispatch\n // through the fetch captured at acquire time. Reading from `lockState`\n // (rather than `window.fetch`) pins to the capture even if `window.fetch`\n // is reassigned after release.\n const currentLock = lockState\n return currentLock.released.then(() => {\n const preLockFetch = currentLock.fetch\n return preLockFetch(input, init)\n })\n}\n\n/**\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 the server served a shell, this is an MPA page load\n // while the lock is held. Transition to captured-MPA and acquire.\n if (self.__next_instant_test) {\n if (typeof cookieStore !== 'undefined') {\n // If the cookie was already cleared during the MPA page\n // transition, reload to get the full dynamic page.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie: any) => {\n if (!cookie) {\n window.location.reload()\n }\n })\n }\n\n // Acquire the lock before writing the cookie. writeCookieValue's\n // guard requires lockState to be non-null at call time (so a stale\n // write can't outlive its scope). On a fresh page load that scope\n // is the one we're about to establish, so we have to establish it\n // first.\n acquireLock()\n writeCookieValue([1, `c${Math.random()}`, null])\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 // External actor starting a new lock scope.\n if (lockState !== null) {\n // This can be the delayed CookieStore event for the pending\n // cookie that was already observed synchronously from\n // document.cookie. Keep the existing lock identity so work that\n // captured it keeps waiting on the same promise.\n return\n }\n acquireLock()\n }\n // Captured value (our own transition) or empty. Ignore.\n return\n }\n }\n\n for (const cookie of event.deleted) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n if (lockState === null) {\n // Either no lock is active, or this is the re-entrant change event\n // from the defensive clear below (which runs after releaseLock).\n // Nothing to release either way.\n return\n }\n releaseLock()\n // A captured write from this page's bootstrap can resurrect the\n // cookie in the narrow gap between the external delete and this\n // handler: writeCookieValue's guard only rejects the write once the\n // lock is torn down, which happens here. Now that the lock is\n // released, no further captured write can re-add the cookie, so clear\n // any entry that was resurrected in that gap. Otherwise an unlock\n // that falls back to a hard reload (when the shell has not yet\n // hydrated) would carry the stale cookie, be served the shell again,\n // and re-enter instant mode with no scope left to release it.\n if (typeof document !== 'undefined') {\n document.cookie = `${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0`\n }\n refreshOnInstantNavigationUnlock()\n return\n }\n }\n })\n}\n\n/**\n * Transitions the cookie from pending to captured-SPA once the prefetch resolves\n * and the navigation is known to be an SPA.\n */\nexport function updateCapturedSPAToTree(\n fromTree: FlightRouterState,\n toTree: FlightRouterState\n): void {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n}\n\n/**\n * Returns true if the navigation lock is currently active.\n */\nexport function isNavigationLocked(): boolean {\n if (lockState !== null) {\n return true\n }\n\n // If `lockState` is null, fall back to reading the test cookie\n // synchronously from `document.cookie`. This accounts for a small race\n // between `cookieStore.set(...)` and its corresponding `change` event.\n // During that gap `lockState` is still null even though the cookie\n // indicates a new lock scope is starting.\n if (typeof document === 'undefined') {\n return false\n }\n const allCookies = document.cookie\n if (!allCookies.includes(NEXT_INSTANT_TEST_COOKIE)) {\n // Fast bail-out: in almost every navigation the test cookie is not\n // set at all.\n return false\n }\n const target = NEXT_INSTANT_TEST_COOKIE + '='\n for (const segment of allCookies.split(';')) {\n const trimmed = segment.trim()\n if (\n trimmed.startsWith(target) &&\n parseCookieValue(trimmed.slice(target.length)) === 'pending'\n ) {\n // The cookie was set by an external actor but the change event was not\n // yet dispatched. Acquire the lock synchronously.\n acquireLock()\n return true\n }\n }\n return false\n}\n\n/**\n * Returns the current locked navigation's withheld-data gate — the same\n * immutable promise `beginLockedNavigation` handed that navigation — or null\n * when no lock is held. For router work that spawns a dynamic write without\n * beginning a navigation of its own (refreshes, server actions, server\n * patches): it gates behind the navigation that is current when it spawns, so\n * the next locked navigation (or unlock) releases it.\n */\nexport function getCurrentNavigationGate(): Promise<void> | null {\n return lockState !== null ? lockState.currentNavigation : null\n}\n\n/**\n * Decides whether segment reads during a navigation should be restricted to\n * shell entries (every param substituted with Fallback) rather than matching\n * entries that vary on concrete route params.\n *\n * The testing tools (Navigation Inspector, instant()) simulate what a user\n * would see with a warm cache. When the lock is held, partial prefetching is\n * enabled for the target route, and no whole-route (\"speculative\") prefetch\n * would have been made, only the shell is prefetched — so that's all a\n * navigation should be allowed to match. A speculative prefetch happens for a\n * `<Link prefetch={true}>`, in which case the concrete-param entry is genuinely\n * warm and may be matched.\n *\n * Always returns false outside the testing API, via the aliased\n * `navigation-testing-lock.disabled` module.\n */\nexport function shouldRestrictNavigationToShell(\n rootPrefetchHints: number,\n linkFetchStrategy: PrefetchTaskFetchStrategy\n): boolean {\n return (\n isNavigationLocked() &&\n (rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0 &&\n !needsSpeculativePrefetch(linkFetchStrategy, rootPrefetchHints)\n )\n}\n","/**\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 */\n\nimport type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport type {\n RouteTree,\n RootRouteTree,\n RSCSegmentData,\n FulfilledRouteCacheEntry,\n} from './cache'\nimport {\n EntryStatus,\n writeRouteIntoCache,\n fulfillRouteCacheEntry,\n getCurrentRouteCacheVersion,\n type PendingRouteCacheEntry,\n createMetadataRouteTree,\n createRootRouteTree,\n getHeadRequestKey,\n} from './cache'\nimport { isValueExpired } from './cache-map'\nimport {\n canonicalizeURLPart,\n normalizeRenderedSearch,\n doesStaticSegmentAppearInURL,\n} from '../../route-params'\nimport type { NormalizedPathname, NormalizedSearch } from './cache-key'\nimport { splitPathnameIntoParts } from './cache-key'\nimport {\n appendLayoutVaryPath,\n finalizeVaryPath,\n getShellSegmentVaryPath,\n type PartialVaryPath,\n type VaryPath,\n} from './vary-path'\n\n/**\n * The known route tree is analogous to a route table. A different routing\n * implementation might use regexes or URLPattern; ours uses a trie indexed\n * by URL path segments.\n *\n * Each node (KnownRoutePart) represents a position in the URL and can have:\n * - staticChildren: Map of literal segments to child nodes\n * - dynamicChild: A single dynamic segment node ([slug], [...params], etc.)\n * - pattern: A cache entry template for routes that terminate here\n *\n * This tree only contains segments that correspond to actual filesystem routes.\n * Route groups like (marketing) and parallel routes like @modal are not\n * included since they don't appear in URLs. Similarly, if a URL is rewritten\n * to a different filesystem path, the original URL segments don't appear here\n * — only the resolved filesystem route structure is stored.\n *\n * Example tree after learning /blog/[slug], /blog/featured, and /about:\n *\n * ├── about\n * └── blog\n * ├── featured\n * └── [slug]\n *\n * When matching /blog/hello:\n * 1. \"blog\" matches static child\n * 2. \"hello\" doesn't match \"featured\", falls through to [slug]\n * 3. Returns [slug]'s pattern with resolved param { slug: \"hello\" }\n */\ntype KnownRoutePartBase = {\n // Known static paths at this level. The null vs Map distinction is\n // semantically meaningful:\n // - null: Static siblings are UNKNOWN at this level (e.g., webpack dev mode\n // where routes are compiled on-demand). If there's a dynamicChild, we\n // can't safely match it because the URL might be an unknown static sibling.\n // - Map (even if empty): Static siblings are KNOWN. We can safely match a\n // dynamicChild if the URL doesn't match any entry in the Map.\n staticChildren: Map<string, KnownRoutePart> | null\n\n // The cache entry that serves as a pattern for this route.\n // When a URL matches, we clone this and substitute param values.\n // null means we know this path exists (from static siblings) but haven't\n // learned its structure yet.\n pattern: FulfilledRouteCacheEntry | null\n\n // True when parallel route branches disagree about the dynamic segment at\n // this level — different param name or type, e.g. an @modal/[...catchAll]\n // slot alongside [username]. The trie can only model one dynamic child per\n // level, so prediction below this level would bind one branch's URL parts\n // to another branch's params. Once set, discovery stops storing patterns\n // beneath this level and matching bails out to server resolution.\n //\n // TODO: Consider including conflicting sibling dynamic params in the route\n // tree, like we do for static siblings, and attempting to match both.\n hasConflictingDynamicChildren: boolean\n\n // True once a prediction made from this node's pattern was contradicted by\n // the server: the URL has a rewrite or redirect that behaves dynamically\n // (e.g. /docs/changelog redirects to /changelog while /docs/alpha renders\n // [collection]/[...slug]). Since rewrite behavior can vary by param value,\n // no URL terminating at this node can be predicted safely, so matching\n // bails out to server resolution. Lives on the node rather than on the\n // pattern entry so it survives the pattern being evicted (by staleness or\n // cache invalidation) and re-learned from a later response.\n hasDynamicRewrite: boolean\n\n // TODO: For prefix rewrite support. When true, this part may not appear in\n // the candidate URL because it was injected by a rewrite. Today, discovery\n // refuses to store a pattern for such routes (see the cache key comparison\n // in discoverKnownRoutePart); this field would let them be predicted.\n // mayBeSkippedInURL: boolean\n}\n\n// The dynamic child fields are structured as a union so that narrowing on\n// dynamicChild also narrows dynamicChildParamName and dynamicChildParamType.\ntype KnownRoutePartWithoutDynamicChild = KnownRoutePartBase & {\n dynamicChild: null\n dynamicChildParamName: null\n dynamicChildParamType: null\n}\n\ntype KnownRoutePartWithDynamicChild = KnownRoutePartBase & {\n dynamicChild: KnownRoutePart\n dynamicChildParamName: string\n dynamicChildParamType: DynamicParamTypesShort\n}\n\nexport type KnownRoutePart =\n | KnownRoutePartWithoutDynamicChild\n | KnownRoutePartWithDynamicChild\n\n/**\n * Param values extracted during URL matching. Used to reify the template.\n * Values are always strings: catch-all [...param] and optional catch-all\n * [[...param]] values are joined with '/' at the time they're resolved, which\n * matches how the rest of the system models catch-all cache keys (an empty\n * optional catch-all is the empty string). Keeping a single value type keeps\n * reads of this map monomorphic.\n */\ntype ResolvedParams = Map<string, string>\n\n/**\n * Read the pattern from a KnownRoutePart, evicting it if expired.\n *\n * This prevents stale patterns (e.g. from InliningHintsStale route entries\n * with staleAt = -1) from being cloned into synthetic entries indefinitely.\n * Once evicted, the pattern slot can be repopulated by the next\n * discoverKnownRoute call with a fresh entry from a /_tree response.\n */\nfunction readPattern(\n now: number,\n part: KnownRoutePart\n): FulfilledRouteCacheEntry | null {\n const pattern = part.pattern\n if (pattern === null) {\n return null\n }\n if (isValueExpired(now, getCurrentRouteCacheVersion(), pattern)) {\n // The pattern is expired. Null it out so the slot can be repopulated.\n part.pattern = null\n return null\n }\n return pattern\n}\n\nfunction createEmptyPart(): KnownRoutePart {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null,\n hasConflictingDynamicChildren: false,\n hasDynamicRewrite: false,\n }\n}\n\n// The root of the known route tree.\nlet knownRouteTreeRoot: KnownRoutePart = createEmptyPart()\n\n/**\n * Learns a route pattern from a server response and inserts it into the cache.\n *\n * Called after receiving a route tree from the server (initial load, navigation,\n * or prefetch). Traverses the route tree, compares URL parts to segments, and\n * populates the known route tree if they match. Routes are always inserted into\n * the cache regardless of whether the URL matches the route structure.\n *\n * When pendingEntry is provided, it's fulfilled and used. When null, an entry\n * is created and inserted into the route cache map.\n *\n * When hasDynamicRewrite is true, the node the route terminates at is marked\n * as having a dynamic rewrite, which prevents URLs of its shape from being\n * predicted. This is set when we detect a mismatch between what we predicted\n * and what the server returned.\n *\n * Returns the fulfilled route cache entry.\n */\nexport function discoverKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n pendingEntry: PendingRouteCacheEntry | null,\n root: RootRouteTree<RSCSegmentData | null>,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n renderedSearch: NormalizedSearch,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const tree = root.tree\n\n const pathnameParts = splitPathnameIntoParts(pathname)\n\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\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(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n fulfilledEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n return fulfilledEntry\n }\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(\n knownRouteTreeRoot,\n tree,\n pathnameParts,\n 0,\n null,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n}\n\n/**\n * Bail out of populating the known route tree when discovery detects that the\n * URL doesn't match the route structure (a rewrite). The route entry is still\n * inserted into the cache for direct lookup — we just don't store it as a\n * pattern, since the URL and the tree describe different shapes.\n */\nfunction handleMismatchDueToRewrite(\n existingEntry: FulfilledRouteCacheEntry | null,\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n root: RootRouteTree<RSCSegmentData | null>,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n renderedSearch: NormalizedSearch,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n if (existingEntry !== null) {\n return existingEntry\n }\n return writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n}\n\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart. A node can\n * have at most one dynamic child. Sibling filesystem routes can't declare two\n * different params at the same level, but parallel route branches can (e.g.\n * @modal/[...catchAll] alongside [username]) — the caller detects that case\n * and marks the level as conflicted instead of calling this.\n */\nfunction discoverDynamicChild(\n part: KnownRoutePart,\n paramName: string,\n paramType: DynamicParamTypesShort\n): KnownRoutePart {\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 as unknown as KnownRoutePartWithDynamicChild\n mutablePart.dynamicChild = newChild\n mutablePart.dynamicChildParamName = paramName\n mutablePart.dynamicChildParamType = paramType\n return newChild\n}\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 */\nfunction discoverKnownRoutePart(\n parentKnownRoutePart: KnownRoutePart,\n routeTree: RouteTree<RSCSegmentData | null>,\n pathnameParts: readonly string[],\n partIndex: number,\n existingEntry: FulfilledRouteCacheEntry | null,\n // These are passed through unchanged for entry creation at the leaf\n now: number,\n pathname: string,\n search: NormalizedSearch,\n nextUrl: string | null,\n root: RootRouteTree<RSCSegmentData | null>,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n renderedSearch: NormalizedSearch,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const segment = routeTree.segment\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n let knownRoutePart: KnownRoutePart = parentKnownRoutePart\n let nextPartIndex = partIndex\n\n if (typeof segment === 'string') {\n if (doesStaticSegmentAppearInURL(segment)) {\n // A visible static segment must consume exactly one URL part that\n // equals the segment. If the URL is exhausted or the URL part doesn't\n // match, the URL doesn't fit the route shape — the response was\n // rewrite-affected. Bail out.\n if (urlPart === null || urlPart !== segment) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n let existingChild = parentKnownRoutePart.staticChildren.get(urlPart)\n if (existingChild === undefined) {\n existingChild = createEmptyPart()\n parentKnownRoutePart.staticChildren.set(urlPart, existingChild)\n }\n knownRoutePart = existingChild\n\n // Advance to next URL part.\n nextPartIndex = partIndex + 1\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n const paramName: string = segment[0]\n const paramCacheKey: string = segment[1]\n const paramType: DynamicParamTypesShort = segment[2]\n const staticSiblings: readonly string[] | null = segment[3]\n\n if (paramType !== 'oc' && urlPart === null) {\n // Every dynamic segment except the optional catch-all (`[[...param]]`)\n // must consume at least one URL part at runtime. If discovery reached\n // this segment with no URL parts left to consume, the URL doesn't fit\n // the route shape — the response was rewrite-affected. Bail out.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n\n if (\n staticSiblings !== null &&\n urlPart !== null &&\n staticSiblings.includes(urlPart)\n ) {\n // The route tree says this is a dynamic sibling, but the canonical URL\n // is a known static sibling. This is a mismatch.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n\n // The param's cache key holds the value parsed from the *rendered*\n // pathname. If the URL part(s) this segment would consume don't equal\n // that value, the response was rewrite-affected in a way that shifts\n // which URL part maps to which segment (e.g. a proxy injected a leading\n // locale segment). A static segment catches this above by failing to\n // match its URL part; a dynamic segment consumes whatever part is in\n // front of it, so compare against the rendered value instead. Bail out.\n switch (paramType) {\n case 'd': {\n // Canonicalize the URL part to the same encoded form the server used\n // for the cache key.\n if (\n urlPart !== null &&\n canonicalizeURLPart(urlPart) !== paramCacheKey\n ) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n break\n }\n case 'c':\n case 'oc': {\n // Catch-alls consume every remaining URL part; their cache keys are\n // the rendered parts joined with '/' (empty string for an empty\n // optional catch-all). Comparing the joined remainder also catches a\n // rewrite that appended segments the URL doesn't have.\n const joinedRemainingParts = pathnameParts\n .slice(partIndex)\n .map(canonicalizeURLPart)\n .join('/')\n if (joinedRemainingParts !== paramCacheKey) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n break\n }\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n // Interception params embed relative markers in their values, and\n // patterns containing them are never used for prediction anyway (see\n // matchKnownRoutePart), so skip the comparison.\n break\n default:\n paramType satisfies never\n }\n\n if (\n parentKnownRoutePart.hasConflictingDynamicChildren ||\n (parentKnownRoutePart.dynamicChild !== null &&\n (parentKnownRoutePart.dynamicChildParamName !== paramName ||\n parentKnownRoutePart.dynamicChildParamType !== paramType))\n ) {\n // A different parallel route branch already claimed the dynamic child\n // at this level with a different param. Mark the level as conflicted\n // so matching bails out, and don't store a pattern via this branch.\n parentKnownRoutePart.hasConflictingDynamicChildren = true\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n\n // URL matches route structure. Build the known route tree.\n knownRoutePart = discoverDynamicChild(\n parentKnownRoutePart,\n paramName,\n paramType\n )\n\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\n // Advance to next URL part. Catch-all segments (`[...param]` and\n // `[[...param]]`) absorb every remaining URL part at runtime (see\n // `matchKnownRoutePart`, which slices the rest of `pathnameParts`).\n if (paramType === 'c' || paramType === 'oc') {\n nextPartIndex = pathnameParts.length\n } else {\n nextPartIndex = partIndex + 1\n }\n }\n\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: FulfilledRouteCacheEntry | null = null\n if (slots !== null) {\n for (const childRouteTree of slots.values()) {\n // Skip branches with refreshState set - these were reused from a\n // different route (e.g., a \"default\" parallel slot) and don't represent\n // the actual route structure for this URL.\n if (childRouteTree.refreshState !== null) {\n continue\n }\n const result = discoverKnownRoutePart(\n knownRoutePart,\n childRouteTree,\n pathnameParts,\n nextPartIndex,\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n // All parallel route branches share the same URL, so they should all\n // reach compatible leaf nodes. We capture any result.\n resultFromChildren = result\n }\n if (resultFromChildren !== null) {\n return resultFromChildren\n }\n // Defensive fallback: no children returned a result. This shouldn't happen\n // for valid route trees, but handle it gracefully.\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node (`__PAGE__` leaf). If there are still URL parts\n // left to consume, the route tree is shorter than the URL, which means\n // the URL doesn't match the route structure (likely a rewrite).\n if (nextPartIndex < pathnameParts.length) {\n return handleMismatchDueToRewrite(\n existingEntry,\n now,\n pathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node: the URL terminates here.\n if (hasDynamicRewrite) {\n knownRoutePart.hasDynamicRewrite = true\n }\n\n // Create/get the route cache entry and store as a pattern. First, check if\n // there's already a pattern for this route.\n const existingPattern = readPattern(now, knownRoutePart)\n if (existingPattern !== null) {\n return existingPattern\n }\n\n // Get or create the entry\n let entry: FulfilledRouteCacheEntry\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(\n now,\n pathname as NormalizedPathname,\n search,\n nextUrl,\n root,\n couldBeIntercepted,\n canonicalUrl,\n renderedSearch,\n supportsPerSegmentPrefetching\n )\n }\n\n // Store as pattern\n knownRoutePart.pattern = entry\n return entry\n}\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 */\nexport function matchKnownRoute(\n now: number,\n pathname: string,\n search: NormalizedSearch\n): FulfilledRouteCacheEntry | null {\n const pathnameParts = splitPathnameIntoParts(pathname)\n const resolvedParams: ResolvedParams = new Map()\n const match = matchKnownRoutePart(\n now,\n knownRouteTreeRoot,\n pathnameParts,\n 0,\n resolvedParams\n )\n\n if (match === null) {\n return null\n }\n\n const matchedPart = match.part\n const pattern = match.pattern\n\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\n // Closed parameters affect whether the route exists, even when none of its\n // components read them. Resolve the target URL on the server instead of\n // combining a predicted tree with UI cached for an allowed parameter value.\n if (\n pattern.root.tree.prefetchHints &\n (PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)\n ) {\n return null\n }\n\n // \"Reify\" the pattern: clone the template tree with concrete param values.\n // This substitutes resolved params (e.g., slug: \"hello\") into dynamic\n // segments and recomputes vary paths for correct segment cache keying.\n const renderedSearch = normalizeRenderedSearch(search)\n const acc: ReifyAccumulator = { metadataVaryPath: null }\n const reifiedTree = reifyRouteTree(\n pattern.root.tree,\n resolvedParams,\n renderedSearch,\n null, // Start with null partial vary path at the root\n acc\n )\n\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(\n metadataVaryPath,\n reifiedTree.prefetchHints,\n null\n )\n\n // Create a synthetic (predicted) entry. It's not inserted into the route\n // cache; it lives only as long as the task or navigation that read it. It\n // records the node it was predicted from so that if the prediction turns\n // out to be wrong (the server renders a different tree due to a dynamic\n // rewrite), the node can be marked and the shape is never predicted again\n // (see KnownRoutePart.hasDynamicRewrite).\n const syntheticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n root: createRootRouteTree(reifiedTree, reifiedMetadata),\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n predictedFrom: matchedPart,\n renderedSearch,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version,\n }\n\n return syntheticEntry\n}\n\n/**\n * Result of a successful match: the matched tree node and its pattern.\n * We return both because the synthetic entry records the node it was\n * predicted from (for dynamic rewrite detection).\n */\ntype KnownRouteMatch = {\n part: KnownRoutePart\n pattern: FulfilledRouteCacheEntry\n} | null\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 */\nfunction matchKnownRoutePart(\n now: number,\n part: KnownRoutePart,\n pathnameParts: string[],\n partIndex: number,\n resolvedParams: ResolvedParams\n): KnownRouteMatch {\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n // If staticChildren is null, we don't know what static routes exist at this\n // level. This happens in webpack dev mode where routes are compiled\n // on-demand. We can't safely match a dynamicChild because the URL part might\n // be a static sibling we haven't discovered yet. Example: We know\n // /blog/[slug] exists, but haven't compiled /blog/featured. A request for\n // /blog/featured would incorrectly match /blog/[slug].\n if (part.staticChildren === null) {\n // The only safe match is a direct pattern when no URL parts remain.\n if (urlPart === null && !part.hasDynamicRewrite) {\n const pattern = readPattern(now, part)\n if (pattern !== null) {\n return { part, pattern }\n }\n }\n return null\n }\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 (\n staticChild.pattern === null &&\n staticChild.dynamicChild === null &&\n staticChild.staticChildren === null\n ) {\n // Bail out - server must resolve this route.\n return null\n }\n const match = matchKnownRoutePart(\n now,\n staticChild,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\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\n // Try dynamic child. Skip it entirely if parallel route branches disagree\n // about the dynamic segment at this level — any pattern stored beneath it\n // was learned under a conflicting model.\n if (part.dynamicChild !== null && !part.hasConflictingDynamicChildren) {\n const dynamicPart = part.dynamicChild\n const paramName = part.dynamicChildParamName\n const paramType = part.dynamicChildParamType\n // Catch-alls terminate at the dynamic child, so a dynamic rewrite marked\n // there rules out predicting any URL that would end in it.\n const dynamicPattern = dynamicPart.hasDynamicRewrite\n ? null\n : readPattern(now, dynamicPart)\n\n switch (paramType) {\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (dynamicPattern !== null && urlPart !== null) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n break\n case 'oc': {\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null) {\n if (urlPart !== null) {\n resolvedParams.set(\n paramName,\n pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/')\n )\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n // urlPart is null - can match with zero parts, but a direct pattern\n // (e.g., page.tsx alongside [[...param]]) takes precedence.\n const directPattern = part.hasDynamicRewrite\n ? null\n : readPattern(now, part)\n if (directPattern === null) {\n resolvedParams.set(paramName, '')\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n }\n break\n }\n case 'd':\n // Regular dynamic [param]: consumes exactly 1 URL part.\n // Unlike catch-all which terminates here, regular dynamic must\n // continue recursing to find the leaf pattern.\n if (urlPart !== null) {\n resolvedParams.set(paramName, canonicalizeURLPart(urlPart))\n return matchKnownRoutePart(\n now,\n dynamicPart,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\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 satisfies never\n }\n }\n\n // No children matched. If we've consumed all URL parts, check for a direct\n // pattern at this node (the route terminates here).\n if (urlPart === null && !part.hasDynamicRewrite) {\n const pattern = readPattern(now, part)\n if (pattern !== null) {\n return { part, pattern }\n }\n }\n\n return null\n}\n\n/**\n * Accumulator for collecting data during reifyRouteTree traversal.\n * metadataVaryPath is collected from the first page node encountered\n * (parallel routes may have multiple pages, but metadata uses the first).\n */\ntype ReifyAccumulator = {\n metadataVaryPath: VaryPath | null\n}\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 */\nfunction reifyRouteTree(\n pattern: RouteTree<null>,\n resolvedParams: ResolvedParams,\n search: NormalizedSearch,\n parentPartialVaryPath: PartialVaryPath | null,\n acc: ReifyAccumulator\n): RouteTree<null> {\n const originalSegment = pattern.segment\n\n // This segment's param (if any) is a root param iff the segment is at or\n // above the root layout, which the server marks directly.\n const isRootParam =\n (pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0\n\n let newSegment = originalSegment\n let partialVaryPath: PartialVaryPath | null\n\n if (typeof originalSegment !== 'string') {\n // Dynamic segment: compute new cache key and append to partial vary path\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const staticSiblings = originalSegment[3]\n const newValue = resolvedParams.get(paramName)\n if (newValue !== undefined) {\n // Catch-all values are already joined into a single string when they're\n // resolved in matchKnownRoutePart, so the value can be used directly.\n const newCacheKey = newValue\n newSegment = [paramName, newCacheKey, paramType, staticSiblings]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n newCacheKey,\n paramName,\n isRootParam\n )\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\n // Recurse into children with the (possibly updated) partial vary path\n let newSlots: Map<string, RouteTree<null>> | null = null\n const patternSlots = pattern.slots\n if (patternSlots !== null) {\n newSlots = new Map()\n for (const [key, childPattern] of patternSlots) {\n newSlots.set(\n key,\n reifyRouteTree(\n childPattern,\n resolvedParams,\n search,\n partialVaryPath,\n acc\n )\n )\n }\n }\n\n let newVaryPath: VaryPath\n if (originalSegment === PAGE_SEGMENT_KEY) {\n // Page segment: finalize with search params\n newVaryPath = finalizeVaryPath(pattern.requestKey, search, partialVaryPath)\n // Collect metadata vary path (first page wins; see getHeadRequestKey)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeVaryPath(\n getHeadRequestKey(pattern.requestKey),\n search,\n partialVaryPath\n )\n }\n } else {\n // Layout segment: finalize without search params\n newVaryPath = finalizeVaryPath(pattern.requestKey, null, partialVaryPath)\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n shellVaryPath: getShellSegmentVaryPath(newVaryPath),\n refreshState: pattern.refreshState,\n // Route cache patterns never carry seed data (see\n // stripDataFromRouteTree), so neither do trees reified from them.\n data: null,\n varyPath: newVaryPath,\n slots: newSlots,\n prefetchHints: pattern.prefetchHints,\n }\n}\n\n/**\n * Resets the known route tree. Called during development when routes may\n * change due to hot reloading.\n */\nexport function resetKnownRoutes(): void {\n knownRouteTreeRoot = createEmptyPart()\n}\n","import { compareParams, ParamsChange } from './vary-path'\nimport type {\n FlightRouterState,\n CacheNode,\n} from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n StaticPrefetchDisabled,\n} from '../../../shared/lib/app-router-types'\nimport {\n readOrCreateRouteCacheEntry,\n readRouteCacheEntry,\n readOrCreateSegmentCacheEntry,\n fetchRouteOnCacheMiss,\n fetchSegmentPrefetchesUsingStaticRequest,\n EntryStatus,\n type FulfilledRouteCacheEntry,\n type RouteCacheEntry,\n type RouteTree,\n type RootRouteTree,\n fetchSegmentPrefetchesUsingRuntimeRequest,\n type PendingSegmentCacheEntry,\n type SegmentCacheEntry,\n convertRouteTreeToFlightRouterState,\n doesRouteStructureMatch,\n readOrCreateRevalidatingSegmentEntry,\n upgradeToPendingSegment,\n overwriteRevalidatingSegmentCacheEntry,\n canNewFetchStrategyProvideMoreContent,\n attemptToFulfillDynamicSegmentFromBFCache,\n attemptToUpgradeSegmentFromBFCache,\n} from './cache'\nimport type { RouteCacheKey } from './cache-key'\nimport { createCacheKey } from './cache-key'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n PrefetchPriority,\n} from './types'\nimport {\n segmentCacheMap,\n getCurrentRouteCacheVersion,\n getCurrentSegmentCacheVersion,\n} from './cache'\nimport type { CacheMap } from './cache-map'\nimport type { NavigationLockPrefetch } from './navigation-testing-lock'\nimport type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport { cleanup } from './lru'\n\nconst scheduleMicrotask =\n typeof queueMicrotask === 'function'\n ? queueMicrotask\n : (fn: () => unknown) =>\n Promise.resolve()\n .then(fn)\n .catch((error) =>\n setTimeout(() => {\n throw error\n })\n )\n\nexport type PrefetchTask = {\n key: RouteCacheKey\n\n // The active render tree and head when this task was scheduled. The walks\n // compare the target route against these to decide which segments the\n // navigation would keep and which it would fetch. Compared by identity in\n // isPrefetchTaskDirty, which relies on the router state holding one\n // RootRouteTree object per committed navigation (see AppRouterState.root).\n renderTreeAtTimeOfPrefetch: RootRouteTree<CacheNode>\n\n /**\n * The cache versions at the time the task was initiated. Used to determine\n * if the cache was invalidated since the task was initiated. Route and\n * segment caches have separate versions so they can be invalidated\n * independently.\n */\n routeCacheVersion: number\n segmentCacheVersion: number\n\n /**\n * The segment cache map this task operates in, captured when the task was\n * scheduled. Every segment read the task performs and every write its\n * responses perform target this map. Almost always the shared map; a task\n * scheduled while the Instant Navigation Testing lock is held gets the\n * lock scope's private map instead. Binding the map to the task means\n * tasks queued before a lock scope never leak entries into (or read out\n * of) the scope's map, and a scope task's late responses never leak into\n * the shared map. See `segmentCacheMap` in cache.ts.\n */\n segmentCacheMap: CacheMap<SegmentCacheEntry>\n\n /**\n * Whether to prefetch dynamic data, in addition to static data. This is\n * used by `<Link prefetch={true}>`.\n *\n * Note that a task with `FetchStrategy.PPR` might need to use\n * `FetchStrategy.LoadingBoundary` instead if we find out that a route\n * does not support PPR after doing the initial route prefetch.\n */\n fetchStrategy: PrefetchTaskFetchStrategy\n\n /**\n * sortId is an incrementing counter\n *\n * Newer prefetches are prioritized over older ones, so that as new links\n * enter the viewport, they are not starved by older links that are no\n * longer relevant. In the future, we can add additional prioritization\n * heuristics, like removing prefetches once a link leaves the viewport.\n *\n * The sortId is assigned when the prefetch is initiated, and reassigned if\n * the same task is prefetched again (effectively bumping it to the top of\n * the queue).\n *\n * TODO: We can add additional fields here to indicate what kind of prefetch\n * it is. For example, was it initiated by a link? Or was it an imperative\n * call? If it was initiated by a link, we can remove it from the queue when\n * the link leaves the viewport, but if it was an imperative call, then we\n * should keep it in the queue until it's fulfilled.\n *\n * We can also add priority levels. For example, hovering over a link could\n * increase the priority of its prefetch.\n */\n sortId: number\n\n /**\n * The priority of the task. Like sortId, this affects the task's position in\n * the queue, so it must never be updated without resifting the heap.\n */\n priority: PrefetchPriority\n\n /**\n * The phase of the task. Tasks are split into multiple phases so that their\n * priority can be adjusted based on what kind of work they're doing.\n * Concretely, prefetching the route tree is higher priority than prefetching\n * segment data.\n */\n phase: PrefetchPhase\n\n /**\n * These fields are temporary state for tracking the currently running task.\n * They are reset after each iteration of the task queue.\n */\n hasBackgroundWork: boolean\n /**\n * Set during a pass when the task spawned a segment request, or encountered\n * one that was already in flight (a Pending entry) — i.e. a response the\n * pass cares about but hasn't received yet. The task blocks instead of\n * advancing, and is re-pinged as each awaited entry settles; see\n * blockTaskOnPendingResponse for the full rationale. Each ping re-runs a\n * full traversal for the task, so expect roughly one re-pass per settling\n * entry. Re-runs don't re-spawn revalidations: when a completed\n * revalidation was re-keyed, its upsert evicts any superseded entry that\n * would shadow it (see upsertSegmentEntry in cache.ts), and when its upsert\n * was declined, the settled entry left in the revalidation slot dedupes\n * further attempts (see pingFullSegmentRevalidation).\n */\n hasPendingResponses: boolean\n spawnedRuntimePrefetches: Set<SegmentRequestKey> | null\n\n /**\n * True if the prefetch was cancelled.\n */\n isCanceled: boolean\n\n /**\n * Tracks whether the task has attempted to upgrade a fallback ISR response\n * to one based on concrete params.\n *\n * When the server serves an upgradeable fallback shell (the page hadn't been\n * prerendered with concrete params yet, but the route can be upgraded), we\n * poll the server a few times until the upgrade is complete, or until we\n * reach a limit and give up.\n *\n * - `Empty`: no loop has run yet.\n * - `Pending`: a loop is currently running.\n * - `Fulfilled`: a loop completed and obtained the upgraded version.\n * - `Rejected`: a loop ran but gave up (exhausted its retries, hit an error,\n * or the task was canceled).\n *\n * To prevent against unbounded upgrade attempts, the loop is only attempted\n * once per task, even a Link's prefetch is rescheduled many times.\n */\n fallbackRetryStatus: EntryStatus\n\n /**\n * The callback passed to `router.prefetch`, if given.\n */\n onInvalidate: null | (() => void)\n\n /**\n * The index of the task in the heap's backing array. Used to efficiently\n * change the priority of a task by re-sifting it, which requires knowing\n * where it is in the array. This is only used internally by the heap\n * algorithm. The naive alternative is indexOf every time a task is queued,\n * which has O(n) complexity.\n *\n * We also use this field to check whether a task is currently in the queue.\n */\n _heapIndex: number\n\n /**\n * Instant Navigation Testing API only. Non-null when this prefetch task drives\n * a locked navigation (the `ensurePrefetchThenNavigate` path). Holds that\n * navigation's \"wait for prefetch to fulfill\" state, resolved when the task\n * completes. See navigation-testing-lock.ts.\n */\n _navigationLockPrefetch?: NavigationLockPrefetch | null\n}\n\nconst enum PrefetchTaskExitStatus {\n /**\n * The task yielded because there are too many requests in progress.\n */\n InProgress,\n\n /**\n * The task is blocked. It needs more data before it can proceed.\n */\n Blocked,\n\n /**\n * There's nothing left to prefetch.\n */\n Done,\n}\n\n/**\n * Prefetch tasks are processed in phases so that high-leverage work runs\n * before per-link work:\n *\n * - RouteTree: fetch the route's tree structure.\n * - Shell: fetch each segment's shell-stage variant, keyed to be reusable\n * across all params below the root (root params are kept) — the phase's\n * target is the conceptual App Shell. Runs if the route can produce a\n * shell and the feature is enabled. Bounded by\n * filesystem-route count, not link count — so all Shell prefetches across\n * queued tasks complete before any Speculative prefetch runs, because\n * shell responses are shared across every navigation to the same route.\n * - Speculative: fetch the route's concrete per-link segment data.\n *\n * Higher numbers run earlier (matches heap-sort convention).\n */\nconst enum PrefetchPhase {\n RouteTree = 2,\n Shell = 1,\n Speculative = 0,\n}\n\nexport type PrefetchSubtaskResult<T> = {\n /**\n * A promise that resolves when the network connection is closed.\n */\n closed: Promise<void>\n value: T\n}\n\nconst taskHeap: Array<PrefetchTask> = []\n\nlet inProgressRequests = 0\n\nlet sortIdCounter = 0\nlet didScheduleMicrotask = false\n\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: PrefetchTask | null = null\n\n// CDN cache propagation delay after revalidation (in milliseconds)\nconst REVALIDATION_COOLDOWN_MS = 300\n\n// Timeout handle for the revalidation cooldown. When non-null, prefetch\n// requests are blocked to allow CDN cache propagation.\nlet revalidationCooldownTimeoutHandle: ReturnType<typeof setTimeout> | null =\n null\n\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 */\nexport function startRevalidationCooldown(): void {\n // Clear any existing timeout in case multiple revalidations happen\n // in quick succession.\n if (revalidationCooldownTimeoutHandle !== null) {\n clearTimeout(revalidationCooldownTimeoutHandle)\n }\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\nexport type IncludeDynamicData = null | 'full' | 'dynamic'\n\n/**\n * Initiates a prefetch task for the given URL. If a prefetch for the same URL\n * is already in progress, this will bump it to the top of the queue.\n *\n * This is not a user-facing function. By the time this is called, the href is\n * expected to be validated and normalized.\n *\n * @param key The RouteCacheKey to prefetch.\n * @param renderTreeAtTimeOfPrefetch The active render tree and head, and\n * their vary paths\n * @param fetchStrategy Whether to prefetch dynamic data, in addition to\n * static data. This is used by `<Link prefetch={true}>`.\n * @param navigationLockPrefetch Testing API only. Non-null when this prefetch\n * drives a locked navigation (from `ensurePrefetchThenNavigate`); carries that\n * navigation's \"wait for prefetch to fulfill\" state. Null otherwise.\n */\nexport function schedulePrefetchTask(\n key: RouteCacheKey,\n renderTreeAtTimeOfPrefetch: RootRouteTree<CacheNode>,\n fetchStrategy: PrefetchTaskFetchStrategy,\n priority: PrefetchPriority,\n onInvalidate: null | (() => void),\n navigationLockPrefetch: NavigationLockPrefetch | null\n): PrefetchTask {\n // Bind the task to the segment cache map that is active right now: the\n // shared map, unless the Instant Navigation Testing lock is held, in which\n // case the task gets the lock scope's private map. This is the single\n // place work is bound to a map based on lock state — everything downstream\n // receives the map explicitly. See `segmentCacheMap` in cache.ts.\n let taskSegmentCacheMap = segmentCacheMap\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { getNavigationLockSegmentCacheMap } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const lockMap = getNavigationLockSegmentCacheMap()\n if (lockMap !== null) {\n taskSegmentCacheMap = lockMap\n }\n }\n\n // Spawn a new prefetch task\n const task: PrefetchTask = {\n key,\n renderTreeAtTimeOfPrefetch,\n routeCacheVersion: getCurrentRouteCacheVersion(),\n segmentCacheVersion: getCurrentSegmentCacheVersion(),\n segmentCacheMap: taskSegmentCacheMap,\n priority,\n phase: PrefetchPhase.RouteTree,\n hasBackgroundWork: false,\n hasPendingResponses: false,\n spawnedRuntimePrefetches: null,\n fetchStrategy,\n sortId: sortIdCounter++,\n isCanceled: false,\n fallbackRetryStatus: EntryStatus.Empty,\n onInvalidate,\n _heapIndex: -1,\n }\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n task._navigationLockPrefetch = navigationLockPrefetch\n }\n\n trackMostRecentlyHoveredLink(task)\n\n heapPush(taskHeap, task)\n\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\n return task\n}\n\nexport function cancelPrefetchTask(task: PrefetchTask): void {\n // Remove the prefetch task from the queue. If the task already completed,\n // then this is a no-op.\n //\n // We must also explicitly mark the task as canceled so that a blocked task\n // does not get added back to the queue when it's pinged by the network.\n task.isCanceled = true\n // A running fallback-retry loop notices `isCanceled` when it next wakes and\n // bails (settling its status to Rejected), so there's nothing to clean up here.\n heapDelete(taskHeap, task)\n}\n\nexport function reschedulePrefetchTask(\n task: PrefetchTask,\n renderTreeAtTimeOfPrefetch: RootRouteTree<CacheNode>,\n fetchStrategy: PrefetchTaskFetchStrategy,\n priority: PrefetchPriority\n): void {\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 // Un-cancel the task, in case it was previously canceled.\n task.isCanceled = false\n task.phase = PrefetchPhase.RouteTree\n\n // Note: fallback-retry state is deliberately NOT reset here. A retry loop runs\n // at most once per task, even across reschedules, so a re-hover never starts a\n // second loop. A loop already running simply continues (it only stops on\n // cancel); `fallbackRetryStatus` never returns to `Empty` once it leaves it.\n\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 =\n // 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\n task.renderTreeAtTimeOfPrefetch = renderTreeAtTimeOfPrefetch\n task.fetchStrategy = fetchStrategy\n\n trackMostRecentlyHoveredLink(task)\n\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}\n\nexport function isPrefetchTaskDirty(\n task: PrefetchTask,\n nextUrl: string | null,\n root: RootRouteTree<CacheNode>\n): boolean {\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 (\n task.routeCacheVersion !== getCurrentRouteCacheVersion() ||\n task.segmentCacheVersion !== getCurrentSegmentCacheVersion() ||\n task.renderTreeAtTimeOfPrefetch !== root ||\n task.key.nextUrl !== nextUrl\n )\n}\n\nfunction trackMostRecentlyHoveredLink(task: PrefetchTask) {\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 (\n task.priority === PrefetchPriority.Intent &&\n task !== mostRecentlyHoveredLink\n ) {\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}\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/**\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 */\nfunction hasNetworkBandwidth(task: PrefetchTask): boolean {\n // When offline, don't issue any prefetch requests. The scheduler will be\n // re-pinged when connectivity is restored.\n if (process.env.__NEXT_USE_OFFLINE) {\n const { getOffline } = require('../offline') as typeof import('../offline')\n if (getOffline()) {\n return false\n }\n }\n\n // Check if we're within the revalidation cooldown window\n if (revalidationCooldownTimeoutHandle !== null) {\n // We're within the cooldown window. Return false to prevent prefetching.\n // When the cooldown expires, the timeout will call ensureWorkIsScheduled()\n // to retry the queue.\n return false\n }\n\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\n // TODO: Consider reserving some amount of bandwidth for static prefetches.\n\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\n // The default limit is lower than the limit for a hovered link.\n return inProgressRequests < 4\n}\n\nfunction spawnPrefetchSubtask<T>(\n prefetchSubtask: Promise<PrefetchSubtaskResult<T> | null>\n): Promise<T | null> {\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}\n\nfunction onPrefetchConnectionClosed(): void {\n inProgressRequests--\n\n // Notify the scheduler that we have more bandwidth, and can continue\n // processing tasks.\n pingPrefetchScheduler()\n}\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 */\nexport function pingPrefetchTask(task: PrefetchTask) {\n // \"Ping\" a prefetch that's already in progress to notify it of new data.\n if (\n // Check if prefetch was canceled.\n task.isCanceled ||\n // Check if prefetch is already queued.\n task._heapIndex !== -1\n ) {\n return\n }\n // Add the task back to the queue.\n heapPush(taskHeap, task)\n pingPrefetchScheduler()\n}\n\nfunction processQueueInMicrotask() {\n didScheduleMicrotask = false\n\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\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\n const exitStatus = pingRoute(now, task)\n\n // These fields are only valid for a single \"pass\" — one pingRoute\n // invocation for a task, which is what the comments here also call an\n // attempt or an iteration. Reset them after each iteration of the\n // task queue.\n const hasBackgroundWork = task.hasBackgroundWork\n task.hasBackgroundWork = false\n task.hasPendingResponses = false\n task.spawnedRuntimePrefetches = null\n\n switch (exitStatus) {\n case PrefetchTaskExitStatus.InProgress:\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 PrefetchTaskExitStatus.Blocked:\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 PrefetchTaskExitStatus.Done:\n if (task.phase === PrefetchPhase.RouteTree) {\n // Finished prefetching the route tree. The two-phase (Shell then\n // Speculative) flow only applies to routes that have opted into\n // Partial Prefetching — either globally via the `partialPrefetching`\n // config or per segment (`prefetch: 'partial'`), both surfaced as the\n // `SubtreeHasPartialPrefetching` hint on the route tree. Every other\n // route skips the Shell phase and goes straight to Speculative.\n //\n // The route entry is fulfilled at this point (the RouteTree phase\n // just completed), so its prefetch hints are available.\n const route = readRouteCacheEntry(now, task.key)\n const routeHasPartialPrefetching =\n route !== null &&\n route.status === EntryStatus.Fulfilled &&\n (route.root.tree.prefetchHints &\n PrefetchHint.SubtreeHasPartialPrefetching) !==\n 0\n task.phase = routeHasPartialPrefetching\n ? PrefetchPhase.Shell\n : PrefetchPhase.Speculative\n heapResift(taskHeap, task)\n } else if (task.phase === PrefetchPhase.Shell) {\n // Shell phase complete — a Done exit means the pass observed every\n // response it cares about (otherwise it would have exited Blocked;\n // see hasPendingResponses). Always advance to Speculative regardless\n // of whether Shell-phase work fired — Speculative is responsible\n // for the per-link concrete work and runs even on routes whose\n // shell phase was a no-op.\n task.phase = PrefetchPhase.Speculative\n heapResift(taskHeap, task)\n } else if (hasBackgroundWork) {\n // The task spawned additional background work. Reschedule the task\n // at background priority.\n task.priority = PrefetchPriority.Background\n heapResift(taskHeap, task)\n } else {\n // The prefetch is complete. Continue to the next task.\n //\n // Completion is terminal in the normal flow: a task only completes\n // after a full pass observed every response it cares about. In rare\n // cases, though, a task can complete while still registered on an\n // entry from an earlier pass whose subtree the final pass no longer\n // reached; when that entry later settles, it re-pings the completed\n // task. The re-run is a harmless idempotent no-op, but any\n // per-completion side effect added here must be idempotent or\n // once-guarded — in particular, the navigation-lock release below\n // must not fire twice (hence the nulling).\n if (\n process.env.__NEXT_EXPOSE_TESTING_API &&\n task._navigationLockPrefetch != null\n ) {\n // This locked-navigation prefetch is complete: the final pass\n // observed every segment response it cares about, so the data the\n // navigation will read has settled. Resolve the prefetch's\n // promise (awaited by `ensurePrefetchThenNavigate`) so the\n // navigation proceeds against present data rather than a\n // still-in-flight entry.\n const { resolveNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n resolveNavigationLockPrefetch(task._navigationLockPrefetch)\n // Release at most once per task: a stale registration from an\n // earlier pass can re-ping a completed task (see above), so it can\n // pass through here again.\n task._navigationLockPrefetch = null\n }\n heapPop(taskHeap)\n }\n task = heapPeek(taskHeap)\n continue\n default:\n exitStatus satisfies never\n }\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/**\n * Check this during a prefetch task to determine if background work can be\n * performed. If so, it evaluates to `true`. Otherwise, it returns `false`,\n * while also scheduling a background task to run later. Usage:\n *\n * @example\n * if (background(task)) {\n * // Perform background-pri work\n * }\n *\n * TODO: Model \"background\" as a phase (like Shell / Speculative) rather\n * than as a priority. Conceptually it's the same pattern: defer work\n * until a later pass over the task. The current priority-based encoding\n * predates the phase model and could be unified.\n */\nfunction background(task: PrefetchTask): boolean {\n if (task.priority === PrefetchPriority.Background) {\n return true\n }\n task.hasBackgroundWork = true\n return false\n}\n\nfunction pingRoute(\n now: number,\n task: PrefetchTask\n):\n | PrefetchTaskExitStatus.InProgress\n | PrefetchTaskExitStatus.Blocked\n | PrefetchTaskExitStatus.Done {\n const key = task.key\n const route = readOrCreateRouteCacheEntry(now, task, key)\n const exitStatus = pingRootRouteTree(now, task, route)\n\n if (exitStatus !== PrefetchTaskExitStatus.InProgress && 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(\n now,\n task,\n keyWithoutSearch\n )\n switch (routeWithoutSearch.status) {\n case EntryStatus.Empty: {\n if (background(task)) {\n routeWithoutSearch.status = EntryStatus.Pending\n spawnPrefetchSubtask(\n fetchRouteOnCacheMiss(routeWithoutSearch, keyWithoutSearch)\n )\n }\n break\n }\n case EntryStatus.Pending:\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected: {\n // Either the route tree is already cached, or there's already a\n // request in progress. Since we don't need to fetch any segment data\n // for this route, there's nothing left to do.\n break\n }\n default:\n routeWithoutSearch satisfies never\n }\n }\n\n if (exitStatus === PrefetchTaskExitStatus.Done && task.hasPendingResponses) {\n // The pass traversed the whole tree, but some segment responses haven't\n // arrived yet, so the current phase isn't actually complete. Block until\n // they do (see blockTaskOnPendingResponse for the full rationale).\n return PrefetchTaskExitStatus.Blocked\n }\n\n return exitStatus\n}\n\nfunction pingRootRouteTree(\n now: number,\n task: PrefetchTask,\n route: RouteCacheEntry\n):\n | PrefetchTaskExitStatus.InProgress\n | PrefetchTaskExitStatus.Blocked\n | PrefetchTaskExitStatus.Done {\n switch (route.status) {\n case EntryStatus.Empty: {\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\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\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\n // Upgrade to Pending so we know there's already a request in progress\n route.status = EntryStatus.Pending\n\n // Intentional fallthrough to the Pending branch\n }\n case EntryStatus.Pending: {\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([task])\n } else {\n blockedTasks.add(task)\n }\n return PrefetchTaskExitStatus.Blocked\n }\n case EntryStatus.Rejected: {\n // Route tree failed to load. Treat as a 404.\n return PrefetchTaskExitStatus.Done\n }\n case EntryStatus.Fulfilled: {\n if (task.phase === PrefetchPhase.RouteTree) {\n // Do not prefetch segment data during the route tree phase.\n return PrefetchTaskExitStatus.Done\n }\n // Recursively fill in the segment tree.\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n const tree = route.root.tree\n\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: FetchStrategy\n if (tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n // If Partial Prefetching is enabled anywhere on the target route,\n // ignore the fetch strategy and switch to unified strategy used by\n // Cache Components (called `PPR` for now, will likely be renamed).\n //\n // In practice, this just means that a \"full\" prefetch (<Link\n // prefetch={true}>) has no effect. You're meant to use Runtime\n // Prefetching instead — that's the new pattern that replaces\n // prefetch={true}.\n //\n // The reason we check for the Partial Prefetching opt-in rather than\n // the `cacheComponents` flag is to support incremental adoption.\n // `prefetch={true}` will continue to work until you opt into\n // Partial Prefetching.\n fetchStrategy = FetchStrategy.PPR\n } else if (task.fetchStrategy === FetchStrategy.PPR) {\n fetchStrategy = route.supportsPerSegmentPrefetching\n ? FetchStrategy.PPR\n : FetchStrategy.LoadingBoundary\n } else {\n fetchStrategy = task.fetchStrategy\n }\n\n switch (fetchStrategy) {\n case FetchStrategy.PPR: {\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\n // Derive the static walk's parameters once per pass; the walk\n // functions below receive them as arguments and are phase-agnostic.\n // During the Shell phase the walk requests each segment's\n // shell-stage variant (keyed at the shell vary paths); otherwise\n // it's the ordinary per-segment static strategy. This is the only\n // place the phase is consulted — everything below keys off\n // the strategy.\n const staticWalkStrategy =\n task.phase === PrefetchPhase.Shell\n ? FetchStrategy.StaticShell\n : FetchStrategy.PPR\n\n // In PPF, links may skip speculative prefetching if they only need a shell.\n if (\n staticWalkStrategy === FetchStrategy.PPR &&\n !needsSpeculativePrefetch(\n task.fetchStrategy,\n route.root.tree.prefetchHints\n )\n ) {\n return PrefetchTaskExitStatus.Done\n }\n\n // The head is a one-node tree beside the route tree (see\n // createMetadataRouteTree in cache.ts); it takes the same walk as\n // a segment the current page doesn't have. If the head was inlined\n // into a page's bundle (HeadOutlined is NOT set on the root), skip\n // the standalone walk — the head data will arrive as part of that\n // page's response, and its runtime-completeness signal is carried\n // by that page's own entries.\n const head = route.root.head\n if (\n !process.env.__NEXT_PREFETCH_INLINING ||\n (route.root.tree.prefetchHints & PrefetchHint.HeadOutlined) !== 0 ||\n // An inlined head that can't attempt a static fetch still deopts\n // to the runtime request (the first check of the decision point\n // in pingSegmentInCacheComponentsTree); only the static fetch\n // itself is skipped for an inlined head.\n (walkCanUseRuntimeRequests(staticWalkStrategy, route) &&\n !shouldSegmentAttemptStaticRequest(staticWalkStrategy, head))\n ) {\n const headExitStatus = pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n head,\n null,\n staticWalkStrategy\n )\n if (headExitStatus === PrefetchTaskExitStatus.InProgress) {\n return PrefetchTaskExitStatus.InProgress\n }\n }\n\n const exitStatus = pingSharedPartOfCacheComponentsTree(\n now,\n task,\n route,\n task.renderTreeAtTimeOfPrefetch.tree,\n tree,\n null,\n staticWalkStrategy\n )\n if (exitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n\n // `pingSegmentInCacheComponentsTree` may have determined that\n // we need to do a runtime prefetch for one or more segments.\n // Bail out early if runtime prefetches are not permitted for this route.\n if (walkCanUseRuntimeRequests(staticWalkStrategy, route)) {\n const runtimeStrategy =\n staticWalkStrategy === FetchStrategy.StaticShell\n ? FetchStrategy.RuntimeShell\n : FetchStrategy.PPRRuntime\n\n // spawnedRuntimePrefetches was populated during the traversal\n // above: every subtree in the new part of the tree that needs a\n // runtime prefetch, the head included — it registers under its\n // own request key, like any segment, when its own static attempt\n // was insufficient or never happened.\n //\n // If it's null, nothing in the new part of the tree is a candidate\n // for runtime prefetching, and we don't fetch the head, either —\n // the head is runtime prefetched only if something is.\n const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches\n if (spawnedRuntimePrefetches !== null) {\n const spawnedEntries = new Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n >()\n // The head has no position in the request tree — a runtime\n // response carries it beside the segments (see\n // writeServerResponseIntoCache in cache.ts) — so the head's\n // own request tree is discarded.\n pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n head,\n false,\n spawnedEntries,\n runtimeStrategy\n )\n const requestTree = pingRuntimePrefetches(\n now,\n task,\n route,\n tree,\n spawnedRuntimePrefetches,\n spawnedEntries,\n runtimeStrategy\n )\n if (spawnedEntries.size > 0) {\n spawnPrefetchSubtask(\n fetchSegmentPrefetchesUsingRuntimeRequest(\n task,\n route,\n runtimeStrategy,\n requestTree,\n spawnedEntries\n )\n )\n }\n }\n }\n\n return PrefetchTaskExitStatus.Done\n }\n case FetchStrategy.Full:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.LoadingBoundary: {\n if (task.phase === PrefetchPhase.Shell) {\n // Shell phase only does work on routes that use the PPR strategy\n // (Cache Components routes). Other strategies are Shell no-ops\n // and fall through to Speculative.\n return PrefetchTaskExitStatus.Done\n }\n // Prefetch multiple segments using a single runtime request.\n // TODO: We can consolidate this branch with previous one by modeling\n // it as if the first segment in the new tree has runtime prefetching\n // enabled. Will do this as a follow-up refactor. Might want to remove\n // the special metatdata case below first. In the meantime, it's not\n // really that much duplication, just would be nice to remove one of\n // these codepaths.\n const spawnedEntries = new Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n >()\n // The head has no position in the request tree — a runtime response\n // carries it beside the segments (see writeServerResponseIntoCache\n // in cache.ts) — so the head's own request tree is discarded.\n const head = route.root.head\n pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n head,\n false,\n spawnedEntries,\n // When prefetching the head, there's no difference between Full\n // and LoadingBoundary: the head has no loading boundary, so a\n // LoadingBoundary request would skip it.\n fetchStrategy === FetchStrategy.LoadingBoundary\n ? FetchStrategy.Full\n : fetchStrategy\n )\n const dynamicRequestTree = diffRouteTreeAgainstCurrent(\n now,\n task,\n route,\n task.renderTreeAtTimeOfPrefetch.tree,\n tree,\n spawnedEntries,\n fetchStrategy\n )\n let needsDynamicRequest = spawnedEntries.size > 0\n if (needsDynamicRequest) {\n spawnPrefetchSubtask(\n fetchSegmentPrefetchesUsingRuntimeRequest(\n task,\n route,\n fetchStrategy,\n dynamicRequestTree,\n spawnedEntries\n )\n )\n }\n return PrefetchTaskExitStatus.Done\n }\n default:\n fetchStrategy satisfies never\n }\n break\n }\n default: {\n route satisfies never\n }\n }\n return PrefetchTaskExitStatus.Done\n}\n\n/**\n * A linked list tracking the segments to fulfill from a single prefetch\n * response, accumulated during the tree walk. The head is the requested\n * segment; subsequent nodes are parent segments whose data is bundled into\n * the same response by the server. When segments are not bundled, the list\n * has a single node.\n *\n * The chain only exists during the walk: when it's finalized,\n * pingSegmentBundle converts it into the map of spawned entries the fetch\n * fulfills (keyed by segment request key).\n */\ntype SegmentBundle = {\n // Null when the segment has prefetching disabled entirely\n // (prefetch: 'force-disabled' / instant = false; Partial Prefetching\n // segments have static data and occupy a real node). The bundle chain\n // passes through it but no cache entry is created for it.\n tree: RouteTree<null> | null\n entry: SegmentCacheEntry | null\n parent: SegmentBundle | null\n}\n\n/**\n * Whether the task can use runtime requests to prefetch the content.\n *\n * This is true for every walk of a route that opts into Partial Prefetching\n * (any segment with a partial-prefetching config, or the global `partialPrefetching`\n * flag, indicated by `SubtreeHasPartialPrefetching` on the route root),\n * in both the Shell and Speculative phases.\n *\n * Note that this does not mean that the route *will* use runtime requests --\n * it might be optimized statically, either because it does not use runtime data\n * in the shell/prefetch, or if it's forced to use static requests by\n * `export const ensureStatic = \"shell\" | \"prefetch\" | \"navigation\"`.\n *\n * Routes without Partial Prefetching never use runtime requests for prefetches\n * (excluding `Full` prefetches)\n */\nfunction walkCanUseRuntimeRequests(\n staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,\n route: FulfilledRouteCacheEntry\n): boolean {\n if (staticWalkStrategy === FetchStrategy.StaticShell) {\n // `FetchStrategy.StaticShell` is only used on PPF routes.\n return true\n }\n // `FetchStrategy.PPR` can only use runtime requests if PPF is enabled on the route.\n return (\n (route.root.tree.prefetchHints &\n PrefetchHint.SubtreeHasPartialPrefetching) !==\n 0\n )\n}\n\n/**\n * Whether a static request for this segment should be attempted.\n * This may vary on the static walk's strategy, because we might e.g.\n * have a shell that's static, but a prefetch that requires runtime requests.\n *\n * NOTE: Should only be used on Partial Prefetching routes, where\n * `walkCanUseRuntimeRequests` is true.\n * */\nfunction shouldSegmentAttemptStaticRequest(\n staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,\n tree: RouteTree<any>\n): boolean {\n const { prefetchHints } = tree\n switch (staticWalkStrategy) {\n case FetchStrategy.StaticShell:\n return (prefetchHints & PrefetchHint.ShouldAttemptStaticShell) !== 0\n case FetchStrategy.PPR:\n return (prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0\n default:\n staticWalkStrategy satisfies never\n return false\n }\n}\n\n/**\n * The runtime counterpart of a pass's static walk strategy: the strategy the\n * batched runtime request uses if this walk deopts. Each phase has exactly one\n * — the Shell phase escalates to a shell-scoped runtime request\n * (RuntimeShell), the Speculative phase to a per-link concrete\n * runtime prefetch.\n */\nfunction getRuntimeStrategyForWalk(\n staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): FetchStrategy.RuntimeShell | FetchStrategy.PPRRuntime {\n return staticWalkStrategy === FetchStrategy.StaticShell\n ? FetchStrategy.RuntimeShell\n : FetchStrategy.PPRRuntime\n}\n\n/**\n * Whether this phase's runtime request would return more content for a\n * fulfilled entry than the entry already holds.\n *\n * An entry records the tier its CONTENT achieved, not the one it was requested\n * at, and that tier spans both axes — so a static response that needed no\n * runtime data records the runtime counterpart of its own variant (see\n * `recordedFetchStrategy` in cache.ts). That makes this a pure tier\n * comparison: an entry at or above the phase's runtime tier has nothing to\n * gain from it.\n */\nfunction wouldRuntimeRequestProvideMore(\n entry: SegmentCacheEntry,\n staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): boolean {\n return canNewFetchStrategyProvideMoreContent(\n entry.fetchStrategy,\n getRuntimeStrategyForWalk(staticWalkStrategy)\n )\n}\n\n/**\n * Whether a fulfilled shell-tier entry should take a static attempt (a\n * spawned revalidation at the walk's static tier) before its position deopts\n * to a runtime request. A shell-tier recorded entry (StaticShell or\n * RuntimeShell) is not evidence that a static attempt would be pointless —\n * unlike a concrete static (PPR) entry, where a static re-fetch would return\n * the same bytes — so when the segment's hint says a static attempt is\n * worthwhile (the build-time prerender accessed no runtime data), the\n * attempt is taken and its response's own verdict decides whether to\n * escalate afterward.\n *\n * Consults the revalidation slot so an attempt that already ran and settled\n * without healing the entry (a rejected attempt: server miss or network\n * error; a successful one upserts over the shell-tier entry, so the caller\n * reads the healed entry instead) doesn't suppress the runtime deopt\n * forever. The slot read creates an Empty placeholder on first evaluation —\n * there is no read-only variant — which is harmless: when the entry is\n * eligible, the spawn that follows claims the same slot.\n */\nfunction isShellEntryEligibleForStaticAttempt(\n now: number,\n map: CacheMap<SegmentCacheEntry>,\n entry: SegmentCacheEntry,\n tree: RouteTree<null>,\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): boolean {\n if (\n !(\n (entry.fetchStrategy === FetchStrategy.StaticShell ||\n entry.fetchStrategy === FetchStrategy.RuntimeShell) &&\n shouldSegmentAttemptStaticRequest(fetchStrategy, tree) &&\n // if the `fetchStrategy` is `FetchStrategy.PPR`, it might provide more content\n // (e.g. static params that this shell doesn't have)\n canNewFetchStrategyProvideMoreContent(entry.fetchStrategy, fetchStrategy)\n )\n ) {\n return false\n }\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(\n now,\n map,\n fetchStrategy,\n tree\n )\n return (\n revalidatingEntry.status === EntryStatus.Empty ||\n revalidatingEntry.status === EntryStatus.Pending\n )\n}\n\n/**\n * Register a subtree root (the head is one, under its own request key) for\n * the batched runtime request issued by the gate at the end of\n * pingRootRouteTree.\n */\nfunction addSpawnedRuntimePrefetch(\n task: PrefetchTask,\n requestKey: SegmentRequestKey\n): void {\n if (task.spawnedRuntimePrefetches === null) {\n task.spawnedRuntimePrefetches = new Set([requestKey])\n } else {\n task.spawnedRuntimePrefetches.add(requestKey)\n }\n}\n\n// TODO: Rename dynamic -> runtime throughout this module\n\n/**\n * The static walk over the part of the target route that also exists on the\n * current page: the current page's node and the target route's node at the\n * same position in the tree. It mirrors the navigation's traversal order (see\n * updateRenderTreeOnNavigation in render-tree.ts): first whether the route\n * position still matches — if not, this node begins the new part of the route\n * (pingNewPartOfCacheComponentsTree) — and then whether any of the node's\n * param values changed — if so, the node and everything below it begin the\n * new part of the route too. The walk does not consult which params a\n * segment read, so it prefetches more than the navigation replaces: the\n * navigation keeps data whose read params did not change and decides each\n * descendant on its own. A node the walk keeps is prefetched at the ordinary\n * static tier.\n * Its children continue here wherever the current page has a child in the\n * same slot; a child in a slot the current page doesn't have enters the new\n * part of the route directly.\n *\n * Bundle chains must not cross the strategy boundary: a kept node walks at\n * PPR while a Shell-phase new part walks at StaticShell, and a chain spanning\n * both would fulfill the kept node's concrete-path entry with shell-variant\n * data. Nor may the chain be finished by fetching the new-part node at PPR\n * — that would prefetch new-part segments at the concrete tier during the\n * Shell phase, which only the Speculative phase is allowed to do. So the\n * chain is dropped wherever the walk hands off to the new part during a\n * StaticShell walk, exactly like the drop sites in\n * pingSegmentInCacheComponentsTree: nothing in a dropped chain was upgraded\n * to Pending, so no entry is stranded, and the inlined kept data is fetched\n * by the Speculative pass whenever its walk of the new part permits the\n * child fetch.\n */\nfunction pingSharedPartOfCacheComponentsTree(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n currentTree: RouteTree<CacheNode>,\n newTree: RouteTree<null>,\n parentBundle: SegmentBundle | null,\n // The per-pass static walk strategy; see pingRootRouteTree where\n // it's derived.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {\n if (!doesRouteStructureMatch(currentTree, newTree)) {\n // We're entering the part of the target route that doesn't exist on the\n // current page.\n return pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n newTree,\n fetchStrategy === FetchStrategy.StaticShell ? null : parentBundle,\n fetchStrategy\n )\n }\n if (\n compareParams(currentTree.varyPath, newTree.varyPath) !== ParamsChange.None\n ) {\n // A param changed. The navigation replaces only the data that read it and\n // decides each descendant on its own (see updateRenderTreeOnNavigation in\n // render-tree.ts); this walk doesn't know what each segment read, so it\n // prefetches the whole subtree.\n return pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n newTree,\n fetchStrategy === FetchStrategy.StaticShell ? null : parentBundle,\n fetchStrategy\n )\n }\n\n // The navigation keeps this segment's current data. A kept segment always\n // performs the ordinary static (PPR) prefetch, regardless of phase.\n // Phase-specific strategies — the runtime shell request and the Shell\n // phase's StaticShell walk — apply only to the new part of the tree, so the\n // per-pass walk strategy is irrelevant here. (The needs-runtime signal is\n // ignored: kept segments are already rendered on the current page, so a\n // runtime prefetch has nothing to add.)\n const bundleInProgress = accumulateSegmentBundle(\n now,\n task,\n route,\n newTree,\n parentBundle,\n FetchStrategy.PPR,\n true\n ).bundle\n\n // Recursively ping the children, continuing in lockstep with the current\n // page wherever it has a child in the same slot.\n const newTreeChildren = newTree.slots\n if (newTreeChildren !== null) {\n const currentSlots = currentTree.slots\n for (const [parallelRouteKey, newTreeChild] of newTreeChildren) {\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n // Only pass the bundle to the child that accepts it. A parent is\n // only ever bundled into one child.\n const bundleForChild =\n process.env.__NEXT_PREFETCH_INLINING &&\n bundleInProgress !== null &&\n newTreeChild.prefetchHints & PrefetchHint.ParentInlinedIntoSelf\n ? bundleInProgress\n : null\n let currentTreeChild: RouteTree<CacheNode> | undefined = undefined\n if (currentSlots !== null) {\n currentTreeChild = currentSlots.get(parallelRouteKey)\n }\n let childExitStatus:\n | PrefetchTaskExitStatus.InProgress\n | PrefetchTaskExitStatus.Done\n if (currentTreeChild !== undefined) {\n childExitStatus = pingSharedPartOfCacheComponentsTree(\n now,\n task,\n route,\n currentTreeChild,\n newTreeChild,\n bundleForChild,\n fetchStrategy\n )\n } else {\n childExitStatus = pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n newTreeChild,\n fetchStrategy === FetchStrategy.StaticShell ? null : bundleForChild,\n fetchStrategy\n )\n }\n if (childExitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n }\n }\n\n // The static attempt was sufficient for this segment (each child is its\n // own decision point) — or parts of it are still in flight, in which case\n // the task is blocked and the decision re-runs against the received\n // responses.\n return PrefetchTaskExitStatus.Done\n}\n\n/**\n * The static walk over the part of the target route that doesn't exist on\n * the current page. Nothing here is compared against the current tree: every\n * segment goes through the per-segment decision point.\n */\nfunction pingNewPartOfCacheComponentsTree(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree<null>,\n parentBundle: SegmentBundle | null,\n // The per-pass static walk strategy; see pingRootRouteTree where\n // it's derived.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {\n const accumulation = pingSegmentInCacheComponentsTree(\n now,\n task,\n route,\n tree,\n parentBundle,\n fetchStrategy\n )\n if (accumulation === null) {\n return PrefetchTaskExitStatus.Done\n }\n const bundleInProgress = accumulation.bundle\n\n // Recursively ping the children.\n const treeChildren = tree.slots\n if (treeChildren !== null) {\n for (const treeChild of treeChildren.values()) {\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n // Only pass the bundle to the child that accepts it. A parent is\n // only ever bundled into one child.\n const bundleForChild =\n process.env.__NEXT_PREFETCH_INLINING &&\n bundleInProgress !== null &&\n treeChild.prefetchHints & PrefetchHint.ParentInlinedIntoSelf\n ? bundleInProgress\n : null\n const childExitStatus = pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n treeChild,\n bundleForChild,\n fetchStrategy\n )\n if (childExitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n }\n }\n\n // The static attempt was sufficient for this segment (each child is its\n // own decision point) — or parts of it are still in flight, in which case\n // the task is blocked and the decision re-runs against the received\n // responses.\n return PrefetchTaskExitStatus.Done\n}\n\n/**\n * The per-segment decision point of the static walk: the one place that\n * decides how a segment in the new part of the route — one the navigation\n * won't keep — is prefetched (pingNewPartOfCacheComponentsTree).\n *\n * When Cache Components is enabled (or PPR, or a fully static route when PPR\n * is disabled; those cases are treated equivalently to Cache Components), we\n * prefetch each segment individually, statically, at the per-pass strategy\n * derived in pingRootRouteTree.\n *\n * This is where we decide whether we should use runtime requests, if the walk\n * is allowed to do so (see `walkCanUseRuntimeRequests`).\n *\n * If runtime requests are allowed, but the segment's node has one of the\n * `ShouldAttemptStatic{Shell,Prefetch}` hints set (either because the build-time\n * prerender accessed no runtime data, or because of `ensureStatic`), then its\n * subtree should be prefetched statically first.\n * However, the hint may be stale after a revalidation, so we'll also check the\n * `needsRuntimeRequest` promise on the static response, and will follow up with\n * a runtime request if needed.\n * Pending responses block the task, so the attempt is serial, never raced:\n * static attempt → observe → runtime (if needed).\n *\n * The static hints and `needsRuntimeRequest` have no effect if runtime requests\n * are not allowed (i.e. outside of Partial Prefetching).\n *\n * Returns the segment's bundle accumulation when the walk should continue\n * into its children, and null when the walk stops at this segment: the link\n * needs no speculative prefetch, or the segment deopted and the batched\n * runtime request covers the whole subtree.\n */\nfunction pingSegmentInCacheComponentsTree(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree<null>,\n parentBundle: SegmentBundle | null,\n // The per-pass static walk strategy; see pingRootRouteTree where\n // it's derived.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): { bundle: SegmentBundle | null; needsRuntimeRequest: boolean } | null {\n // In PPF, links may skip speculative prefetching if they only need a shell.\n if (\n fetchStrategy === FetchStrategy.PPR &&\n !needsSpeculativePrefetch(task.fetchStrategy, route.root.tree.prefetchHints)\n ) {\n return null\n }\n\n // Constant for the whole pass; recomputed here only because the walk is\n // recursive and the check is cheap.\n const canUseRuntimeRequests = walkCanUseRuntimeRequests(fetchStrategy, route)\n\n // A force-disabled segment deliberately does NOT deopt here: disabling\n // prefetch is passive. It never initiates a request — its accumulation\n // below contributes nothing — and must never be the reason a runtime\n // prefetch spawns, though it may ride along in a runtime response issued\n // on another segment's behalf.\n\n if (\n canUseRuntimeRequests &&\n !shouldSegmentAttemptStaticRequest(fetchStrategy, tree)\n ) {\n // Deopt directly to a runtime prefetch, without a static attempt.\n addSpawnedRuntimePrefetch(task, tree.requestKey)\n // If there's a pending static bundle from a parent, we need to finish\n // prefetching it before bailing out to runtime prefetching.\n if (parentBundle !== null) {\n finishStaticBundleOnRuntimeBailout(\n now,\n task,\n route,\n tree,\n parentBundle,\n fetchStrategy\n )\n }\n return null\n }\n\n // Prefetch this segment and its subtree statically, using the normal\n // static bundling walk.\n const accumulation = accumulateSegmentBundle(\n now,\n task,\n route,\n tree,\n parentBundle,\n fetchStrategy,\n true\n )\n\n if (canUseRuntimeRequests && accumulation.needsRuntimeRequest) {\n // The static attempt for this segment was insufficient. Stop the walk\n // and deopt — the runtime prefetch covers the whole subtree. (Unlike the\n // direct deopt above, any open bundle is dropped rather than finished: a\n // fulfilled InlinedIntoChild node can report a true signal while its\n // chain is still open. That's safe — nothing in an un-pinged chain was\n // upgraded to Pending, so no entry is stranded blocking the task, and\n // Empty entries in the dropped chain are re-fetched by a later pass.)\n addSpawnedRuntimePrefetch(task, tree.requestKey)\n return null\n }\n\n return accumulation\n}\n\nfunction diffRouteTreeAgainstCurrent(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n oldTree: RouteTree<CacheNode>,\n newTree: RouteTree<null>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.LoadingBoundary\n): FlightRouterState {\n // This is a single recursive traversal that does multiple things:\n // - Finds the segments that differ from the current route, comparing each\n // segment the same way the navigation will (see\n // updateRenderTreeOnNavigation in render-tree.ts): its route position,\n // then whether any of its param values changed.\n // - Constructs a request tree (FlightRouterState) that describes which\n // segments need to be prefetched and which ones are already cached.\n // - Creates a set of pending cache entries for the segments that need to\n // be prefetched, so that a subsequent prefetch task does not request the\n // same segments again.\n const oldSlots = oldTree.slots\n const newTreeChildren = newTree.slots\n let requestTreeChildren: Record<string, FlightRouterState> = {}\n if (newTreeChildren !== null) {\n for (const [parallelRouteKey, newTreeChild] of newTreeChildren) {\n const oldTreeChild = oldSlots?.get(parallelRouteKey)\n requestTreeChildren[parallelRouteKey] = diffSegmentAgainstCurrent(\n now,\n task,\n route,\n oldTreeChild,\n newTreeChild,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n const requestTree: FlightRouterState = [\n newTree.segment,\n requestTreeChildren,\n null,\n null,\n ]\n if (newTree.prefetchHints !== 0) {\n requestTree[4] = newTree.prefetchHints\n }\n return requestTree\n}\n\n/**\n * The per-segment decision of a runtime request's tree walk\n * (diffRouteTreeAgainstCurrent): the segment at this position of the target\n * route, and the current page's segment at the same position, if it has one.\n * A segment the navigation keeps — same route position, and none of its param\n * values changed — is omitted from the request and the walk continues into\n * its children. Otherwise this segment begins a part of the tree that needs\n * to be prefetched (unless everything is already cached), requested according\n * to the strategy.\n */\nfunction diffSegmentAgainstCurrent(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n oldTree: RouteTree<CacheNode> | undefined,\n newTree: RouteTree<null>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.LoadingBoundary\n): FlightRouterState {\n if (oldTree !== undefined && doesRouteStructureMatch(oldTree, newTree)) {\n // This segment is already part of the current route.\n if (\n compareParams(oldTree.varyPath, newTree.varyPath) === ParamsChange.None\n ) {\n // The navigation keeps its data. Keep traversing.\n return diffRouteTreeAgainstCurrent(\n now,\n task,\n route,\n oldTree,\n newTree,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n // This segment is not part of the current route, or the navigation\n // replaces its data. We're entering a part of the tree that we need to\n // prefetch (unless everything is already cached).\n switch (fetchStrategy) {\n case FetchStrategy.LoadingBoundary: {\n // When PPR is disabled, we can't prefetch per segment. We must\n // fallback to the old prefetch behavior and send a runtime request.\n // Only routes that include a loading boundary can be prefetched in\n // this way.\n //\n // This is simlar to a \"full\" prefetch, but we're much more\n // conservative about which segments to include in the request.\n //\n // The server will only render up to the first loading boundary\n // inside new part of the tree. If there's no loading boundary\n // anywhere in the tree, the server will never return any data, so\n // we can skip the request.\n const subtreeHasLoadingBoundary =\n (newTree.prefetchHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)) !==\n 0\n if (subtreeHasLoadingBoundary) {\n return pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now,\n task,\n route,\n newTree,\n null,\n spawnedEntries\n )\n }\n // There's no loading boundary within this tree. Bail out.\n return convertRouteTreeToFlightRouterState(newTree)\n }\n case FetchStrategy.PPRRuntime: {\n // This is a runtime prefetch. Fetch all cacheable data in the tree,\n // not just the static PPR shell.\n return pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n newTree,\n false,\n spawnedEntries,\n fetchStrategy\n )\n }\n case FetchStrategy.Full: {\n // This is a \"full\" prefetch. Fetch all the data in the tree, both\n // static and dynamic. We issue roughly the same request that we\n // would during a real navigation. The goal is that once the\n // navigation occurs, the router should not have to fetch any\n // additional data.\n //\n // Although the response will include dynamic data, opting into a\n // Full prefetch — via <Link prefetch={true}> — implicitly\n // instructs the cache to treat the response as \"static\", or non-\n // dynamic, since the whole point is to cache it for\n // future navigations.\n //\n // Construct a tree (currently a FlightRouterState) that represents\n // which segments need to be prefetched and which ones are already\n // cached. If the tree is empty, then we can exit. Otherwise, we'll\n // send the request tree to the server and use the response to\n // populate the segment cache.\n return pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n newTree,\n false,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n}\n\nfunction pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree<null>,\n refetchMarkerContext: 'refetch' | 'inside-shared-layout' | null,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): FlightRouterState {\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\n // \"inside-shared-layout\" tells the server where to start looking for a\n // loading boundary.\n let refetchMarker: 'refetch' | 'inside-shared-layout' | null =\n refetchMarkerContext === null ? 'inside-shared-layout' : null\n\n const segment = readOrCreateSegmentCacheEntry(\n now,\n task.segmentCacheMap,\n task.fetchStrategy,\n tree\n )\n switch (segment.status) {\n case EntryStatus.Empty: {\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\n // Add the pending cache entry to the result map.\n const pendingSegment = upgradeToPendingSegment(\n segment,\n // 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 )\n spawnedEntries.set(tree.requestKey, pendingSegment)\n // The pass blocks on every request it spawns, not just requests it\n // finds already in flight.\n blockTaskOnPendingResponse(task, pendingSegment)\n if (refetchMarkerContext !== 'refetch') {\n refetchMarker = refetchMarkerContext = 'refetch'\n } else {\n // There's already a parent with a refetch marker, so we don't need\n // to add another one.\n }\n break\n }\n case EntryStatus.Fulfilled: {\n // The segment is already cached.\n const segmentHasLoadingBoundary =\n (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 // NOTE: If the cached segment were fetched using PPR, then it might be\n // partial. We could get a more complete version of the segment by\n // including it in this non-PPR request.\n //\n // We're intentionally choosing not to, though, because it's generally\n // better to avoid doing a full prefetch whenever possible.\n break\n }\n case EntryStatus.Pending: {\n // There's another prefetch currently in progress. Don't add the refetch\n // marker yet, so the server knows it can skip rendering this segment.\n // The pass still depends on the in-flight response, so wait for it\n // before the phase can complete.\n blockTaskOnPendingResponse(task, segment)\n break\n }\n case EntryStatus.Rejected: {\n // The segment failed to load, or the server intentionally omitted it\n // from a response (both are encoded as Rejected). Skip it and keep\n // prefetching the rest of the tree; the entry's staleAt governs when it\n // may be retried. Don't register the task on the rejected entry —\n // nothing ever pings a Rejected entry.\n break\n }\n default:\n segment satisfies never\n }\n const requestTreeChildren: Record<string, FlightRouterState> = {}\n if (tree.slots !== null) {\n for (const [parallelRouteKey, childTree] of tree.slots) {\n requestTreeChildren[parallelRouteKey] =\n pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now,\n task,\n route,\n childTree,\n refetchMarkerContext,\n spawnedEntries\n )\n }\n }\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker,\n ]\n if (tree.prefetchHints !== 0) {\n requestTree[4] = tree.prefetchHints\n }\n return requestTree\n}\n\n/**\n * Called during a pass when a segment's response hasn't been received yet —\n * whether the request was just spawned by this pass or was already in flight.\n * Marks the task as blocked: a phase only completes once a full pass observes\n * every segment response it cares about, because later decisions (like\n * whether a segment needs a follow-up runtime request) are made against the\n * contents of those responses, and a phase may need to restart its work based\n * on what they contain. The task is re-pinged (via pingBlockedTasks in\n * cache.ts) when the entry resolves, re-running the pass against the\n * received data. Only a pass that observes every response may advance the\n * phase or complete the task.\n *\n * Never call this for an entry that's already Rejected — nothing ever pings\n * a Rejected entry, so registering on one would strand the task. A rejected\n * segment is simply skipped: the pass keeps prefetching the rest of the tree\n * without it.\n */\nfunction blockTaskOnPendingResponse(\n task: PrefetchTask,\n segment: { blockedTasks: Set<PrefetchTask> | null }\n): void {\n // This state is reset after each iteration of the task queue. We use it to\n // inform the scheduler that the task is blocked.\n task.hasPendingResponses = true\n // Add the task to this segment's blocked tasks, so it can be rescheduled\n // once the segment finishes loading.\n if (segment.blockedTasks === null) {\n segment.blockedTasks = new Set([task])\n } else {\n segment.blockedTasks.add(task)\n }\n}\n\nfunction pingRouteTreeAndIncludeDynamicData(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree<null>,\n isInsideRefetchingParent: boolean,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.RuntimeShell\n): FlightRouterState {\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(\n now,\n task.segmentCacheMap,\n // 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,\n tree\n )\n\n let spawnedSegment: PendingSegmentCacheEntry | null = null\n\n switch (segment.status) {\n case EntryStatus.Empty: {\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(\n now,\n segment,\n tree\n )\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 // The segment is already cached.\n if (\n segment.isPartial &&\n canNewFetchStrategyProvideMoreContent(\n segment.fetchStrategy,\n fetchStrategy\n )\n ) {\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(\n now,\n task.segmentCacheMap,\n tree\n )\n if (fulfilled !== null) {\n break\n }\n }\n spawnedSegment = pingFullSegmentRevalidation(\n now,\n task,\n tree,\n fetchStrategy\n )\n }\n break\n }\n case EntryStatus.Pending:\n case EntryStatus.Rejected: {\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 (\n canNewFetchStrategyProvideMoreContent(\n segment.fetchStrategy,\n fetchStrategy\n )\n ) {\n spawnedSegment = pingFullSegmentRevalidation(\n now,\n task,\n tree,\n fetchStrategy\n )\n }\n if (segment.status === EntryStatus.Pending) {\n // A response for this segment is still in flight. The pass must\n // observe it before the phase can complete.\n blockTaskOnPendingResponse(task, segment)\n } else {\n // The segment failed to load, or the server intentionally omitted it\n // from a response (both are encoded as Rejected). Skip it and keep\n // prefetching the rest of the tree; the entry's staleAt governs when\n // it may be retried. Don't register the task on the rejected entry —\n // nothing ever pings a Rejected entry.\n //\n // TODO: The cache encodes real failures and intentional server\n // omissions identically (both Rejected); with per-segment skipping\n // this has no task-lifecycle consequence, but distinguishing them\n // could still be useful someday.\n }\n break\n }\n default:\n segment satisfies never\n }\n\n if (spawnedSegment !== null) {\n // A pass must observe the response for every request it spawns before\n // its phase can complete — not just requests it finds already in flight.\n // Block on the entry we just spawned; the task is re-pinged when it's\n // fulfilled or rejected.\n blockTaskOnPendingResponse(task, spawnedSegment)\n }\n\n const requestTreeChildren: Record<string, FlightRouterState> = {}\n if (tree.slots !== null) {\n for (const [parallelRouteKey, childTree] of tree.slots) {\n requestTreeChildren[parallelRouteKey] =\n pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n childTree,\n isInsideRefetchingParent || spawnedSegment !== null,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n\n if (spawnedSegment !== null) {\n // Add the pending entry to the result map.\n spawnedEntries.set(tree.requestKey, spawnedSegment)\n }\n\n // Don't bother to add a refetch marker if one is already present in a parent.\n const refetchMarker =\n !isInsideRefetchingParent && spawnedSegment !== null ? 'refetch' : null\n\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker,\n ]\n if (tree.prefetchHints !== 0) {\n requestTree[4] = tree.prefetchHints\n }\n return requestTree\n}\n\nfunction pingRuntimePrefetches(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree<null>,\n spawnedRuntimePrefetches: Set<SegmentRequestKey>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy: FetchStrategy.PPRRuntime | FetchStrategy.RuntimeShell\n): FlightRouterState {\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(\n now,\n task,\n route,\n tree,\n false,\n spawnedEntries,\n fetchStrategy\n )\n }\n let requestTreeChildren: Record<string, FlightRouterState> = {}\n const slots = tree.slots\n if (slots !== null) {\n for (const [parallelRouteKey, childTree] of slots) {\n requestTreeChildren[parallelRouteKey] = pingRuntimePrefetches(\n now,\n task,\n route,\n childTree,\n spawnedRuntimePrefetches,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n\n // This segment is not part of the runtime prefetch. Clone the base tree.\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n null,\n ]\n if (tree.prefetchHints !== 0) {\n requestTree[4] = tree.prefetchHints\n }\n return requestTree\n}\n\n/**\n * Walk a SegmentBundle, apply status-based logic to each entry, and if any\n * entries need data, spawn a single fetch request for the whole bundle.\n *\n * Returns true if a fulfilled entry in the bundle reported that a runtime\n * request would return more content than the entry contains\n * (needsRuntimeRequest, derived at write time from the response that\n * produced the entry). The callers surface this signal to the per-segment\n * decision point in pingSegmentInCacheComponentsTree, which uses it during\n * a static attempt to decide whether to fall back to a runtime prefetch. One\n * exception withholds the signal: a shell-tier entry whose segment carries\n * the static-attempt hint spawns a concrete static attempt first — see the\n * Fulfilled case.\n */\nfunction pingSegmentBundle(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree<null>,\n segments: SegmentBundle,\n // Per-pass static walk strategy; see pingRootRouteTree where it's derived.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,\n // False when finishing an open bundle chain on a runtime-prefetch bailout\n // (finishStaticBundleOnRuntimeBailout). The finish exists only to fetch\n // data the batched runtime request won't cover — Empty entries in the\n // chain — so it must not spawn revalidations over entries that are\n // already settled or in flight: the chain's terminal segments are inside\n // the deopted subtree, and re-fetching their static bundle would at best\n // duplicate the runtime request and at worst replace a runtime-complete\n // entry (e.g. a RuntimeShell-tier entry) with a less complete static\n // fallback response.\n spawnRevalidations: boolean\n): boolean {\n let needsRuntimeRequest = false\n // The pending entries this task owns — Empty entries upgraded here, plus\n // any revalidations spawned here — keyed by segment request key. If any\n // accumulate, a single fetch is spawned for the whole bundle, and the\n // response fulfills them.\n let spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null =\n null\n let node: SegmentBundle | null = segments\n while (node !== null) {\n const nodeEntry = node.entry\n const nodeTree = node.tree\n if (nodeEntry === null || nodeTree === null) {\n node = node.parent\n continue\n }\n switch (nodeEntry.status) {\n case EntryStatus.Empty: {\n const pendingEntry = upgradeToPendingSegment(nodeEntry, fetchStrategy)\n if (spawnedEntries === null) {\n spawnedEntries = new Map()\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry)\n // The pass blocks on every request it spawns, not just requests it\n // finds already in flight.\n blockTaskOnPendingResponse(task, pendingEntry)\n break\n }\n case EntryStatus.Pending:\n if (\n spawnRevalidations &&\n // During a static shell attempt, never spawn revalidations — just\n // wait for the in-flight response (blocked below); its sufficiency\n // is checked on the re-run pass.\n fetchStrategy === FetchStrategy.PPR &&\n canNewFetchStrategyProvideMoreContent(\n nodeEntry.fetchStrategy,\n fetchStrategy\n )\n ) {\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(\n now,\n task.segmentCacheMap,\n fetchStrategy,\n nodeTree\n )\n if (revalidatingEntry.status === EntryStatus.Empty) {\n const pendingEntry = upgradeToPendingSegment(\n revalidatingEntry,\n fetchStrategy\n )\n if (spawnedEntries === null) {\n spawnedEntries = new Map()\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry)\n // Block on the revalidation request we just spawned, in\n // addition to the original in-flight entry (blocked below).\n blockTaskOnPendingResponse(task, pendingEntry)\n }\n }\n blockTaskOnPendingResponse(task, nodeEntry)\n break\n case EntryStatus.Rejected:\n if (\n spawnRevalidations &&\n // During a static shell attempt, a rejected entry is skipped\n // outright: no retry revalidation, and — deliberately — no runtime\n // fallback either (per-segment rejection semantics; the entry's\n // staleAt governs when it may be retried). Note that the cache\n // path encodes \"no shell exists\" (a static response whose shell\n // byte offset is 0, i.e. the page wasn't produced by staged\n // rendering) as a rejection too, so such segments get no shell\n // prefetch at all — an edge that shouldn't occur for hint-set\n // Cache Components routes.\n fetchStrategy === FetchStrategy.PPR &&\n canNewFetchStrategyProvideMoreContent(\n nodeEntry.fetchStrategy,\n fetchStrategy\n )\n ) {\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(\n now,\n task.segmentCacheMap,\n fetchStrategy,\n nodeTree\n )\n if (revalidatingEntry.status === EntryStatus.Empty) {\n const pendingEntry = upgradeToPendingSegment(\n revalidatingEntry,\n fetchStrategy\n )\n if (spawnedEntries === null) {\n spawnedEntries = new Map()\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry)\n // Block on the retry revalidation we just spawned, like any\n // other pending response. If the retry succeeds, its upsert\n // evicts the rejected entry (see evictShadowingSegmentEntries\n // in cache.ts) and the re-run pass reads the healed data. If it\n // rejects too, the re-run observes a settled revalidation and\n // moves on.\n blockTaskOnPendingResponse(task, pendingEntry)\n }\n }\n // The segment failed to load, or the server intentionally omitted it\n // from a response (both are encoded as Rejected). Skip it and keep\n // prefetching the rest of the bundle; the entry's staleAt governs\n // when it may be retried. Don't register the task on the rejected\n // entry itself — nothing ever pings a Rejected entry.\n break\n case EntryStatus.Fulfilled: {\n let willBeSupersededByRuntimeRequest = false\n if (walkCanUseRuntimeRequests(fetchStrategy, route)) {\n const runtimeWouldProvideMore = wouldRuntimeRequestProvideMore(\n nodeEntry,\n fetchStrategy\n )\n\n // An eligible shell-tier entry takes the static attempt path below\n // (the revalidation) instead of deopting straight to a runtime\n // request; see isShellEntryEligibleForStaticAttempt. The attempt\n // can't recur: its response records at least the concrete static\n // tier, which fails the shell-tier check on the re-run pass — and an\n // attempt that already settled without healing the entry reads as\n // ineligible, so the deopt proceeds after all.\n const shellEntryEligibleForStaticAttempt =\n isShellEntryEligibleForStaticAttempt(\n now,\n task.segmentCacheMap,\n nodeEntry,\n nodeTree,\n fetchStrategy\n )\n\n if (runtimeWouldProvideMore && !shellEntryEligibleForStaticAttempt) {\n // A runtime request would return more content for this segment\n // than the entry contains. Surface it via the return value, so the\n // caller can deopt this subtree to a runtime prefetch. (An\n // eligible shell-tier entry withholds the signal for this pass:\n // the static attempt spawned below blocks the task, and the re-run\n // pass reads the attempt's result instead.)\n\n needsRuntimeRequest = true\n\n // If a runtime request would return more content skip the static path\n // entirely — unless the entry is an eligible shell-tier entry (see above),\n // whose static attempt IS this upgrade.\n // Otherwise the runtime request covers this segment and supersedes\n // anything a static fetch could add, so a static upgrade would at best\n // duplicate it — delivering the same content twice — and at worst replace\n // runtime content with static content.\n willBeSupersededByRuntimeRequest = true\n }\n }\n\n // If this is the speculative phase (not the shell phase), check if we\n // should attempt to upgrade a fallback ISR response to a concrete\n // version.\n //\n // For entries below this phase's tier, upgrade during the phase\n // itself — no background deferral, since the whole point of the\n // Speculative phase is to bring the cache up to the\n // per-link-concrete tier. `isPartial` ensures a complete entry isn't\n // re-fetched.\n //\n // If we can use runtime requests and a runtime request would provide more\n // data, we also skip the upgrade (see `willBeSupersededByRuntimeRequest`)\n const isUpgradeableISRFallbackRetry =\n fetchStrategy === FetchStrategy.PPR &&\n nodeEntry.isUpgradeableISRFallback &&\n // If the status is empty, then we haven't yet attempted to upgrade\n // the fallback.\n //\n // If the status is fulfilled, then the fallback was\n // successfully upgraded to a concrete version.\n //\n // Do not attempt to upgrade if the status is Pending or Rejected.\n (task.fallbackRetryStatus === EntryStatus.Empty ||\n task.fallbackRetryStatus === EntryStatus.Fulfilled)\n\n if (\n spawnRevalidations &&\n !willBeSupersededByRuntimeRequest &&\n ((nodeEntry.isPartial &&\n canNewFetchStrategyProvideMoreContent(\n nodeEntry.fetchStrategy,\n fetchStrategy\n )) ||\n isUpgradeableISRFallbackRetry)\n ) {\n const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(\n now,\n task.segmentCacheMap,\n fetchStrategy,\n nodeTree\n )\n if (revalidatingEntry.status === EntryStatus.Empty) {\n const pendingEntry = upgradeToPendingSegment(\n revalidatingEntry,\n fetchStrategy\n )\n if (spawnedEntries === null) {\n spawnedEntries = new Map()\n }\n spawnedEntries.set(nodeTree.requestKey, pendingEntry)\n // The pass blocks on every request it spawns, including\n // revalidations of an already-fulfilled entry.\n blockTaskOnPendingResponse(task, pendingEntry)\n } else {\n // A non-empty revalidating entry means a request is already in\n // flight (or recently settled), so we dedupe and don't issue a\n // competing one — including for ISR-fallback upgrades, which then\n // share the same revalidation across tasks.\n if (revalidatingEntry.status === EntryStatus.Pending) {\n // The deduped-against revalidation is still in flight, and this\n // pass depends on its response. Wait for it before the phase\n // can complete. (A settled revalidation we chose not to use\n // needs no waiting and is not a prefetch failure — the base\n // entry here is already Fulfilled. A settled revalidation\n // can't strand an eligible shell-tier entry either:\n // isShellEntryEligibleForStaticAttempt reads the slot, so a\n // settled attempt makes the entry ineligible and the runtime\n // deopt proceeds above.)\n blockTaskOnPendingResponse(task, revalidatingEntry)\n }\n }\n }\n break\n }\n default:\n nodeEntry satisfies never\n }\n node = node.parent\n }\n if (spawnedEntries !== null) {\n spawnPrefetchSubtask(\n fetchSegmentPrefetchesUsingStaticRequest(\n task,\n route,\n routeKey,\n tree,\n spawnedEntries,\n fetchStrategy\n )\n )\n }\n return needsRuntimeRequest\n}\n\n/**\n * During the tree walk, decide whether this segment should be added to the\n * in-progress bundle (if it has InlinedIntoChild) or finalize the bundle\n * and ping it, triggering a fetch if any of its entries need data (if it\n * doesn't). Returns the updated bundle to pass to children (null if the\n * bundle was finalized here), along with the needs-runtime signal from the\n * bundle ping, if one happened (always false otherwise).\n */\nfunction accumulateSegmentBundle(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree<null>,\n parentBundle: SegmentBundle | null,\n // Per-pass static walk strategy; see pingRootRouteTree where it's derived.\n // PPR for the normal static bundling walk; StaticShell during the Shell\n // phase's static shell attempt, whose entries are keyed at the shell\n // vary paths.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,\n // False when finishing a chain on a runtime-prefetch bailout; see\n // pingSegmentBundle.\n spawnRevalidations: boolean\n): { bundle: SegmentBundle | null; needsRuntimeRequest: boolean } {\n // Prefetching is disabled for this segment (prefetch: 'force-disabled'):\n // the server emits identity only for its response node, and it\n // participates in the bundle chain with null tree/entry — no cache entry\n // is created for it.\n // (Partial Prefetching segments are NOT in this mask — the server emits\n // static data for them unconditionally.) Intentionally not gated by the\n // prefetch inlining flag: we never statically prefetch unprefetchable\n // segments.\n if (tree.prefetchHints & StaticPrefetchDisabled) {\n return {\n bundle: { tree: null, entry: null, parent: parentBundle },\n needsRuntimeRequest: false,\n }\n }\n\n const segment = readOrCreateSegmentCacheEntry(\n now,\n task.segmentCacheMap,\n fetchStrategy,\n tree\n )\n\n if (\n process.env.__NEXT_PREFETCH_INLINING &&\n tree.prefetchHints & PrefetchHint.InlinedIntoChild\n ) {\n if (segment.status === EntryStatus.Pending) {\n // The chain this entry joins may be dropped before it's ever pinged\n // (see the drop sites in pingSegmentInCacheComponentsTree), and only\n // the ping blocks on Pending entries. Register on the in-flight\n // response at read time instead, so the pass observes it before the\n // phase can complete even if the chain is dropped. When the chain does\n // get pinged, the ping's own registration dedupes against this one.\n blockTaskOnPendingResponse(task, segment)\n }\n return {\n bundle: { tree, entry: segment, parent: parentBundle },\n // No bundle ping happens here, but the node's own entry may already be\n // fulfilled and insufficient. Report that signal directly: the chain\n // ping only reaches the terminal descendant, and if that descendant is\n // itself a decision point it consumes the signal for its own subtree,\n // leaving this ancestor's insufficiency invisible to the decision\n // point above it. An eligible shell-tier entry withholds the signal,\n // the same exception the bundle ping applies: deopting here would\n // pre-empt the static attempt the chain ping spawns for this node when\n // it reaches the terminal descendant (its Fulfilled case runs for\n // every node in the chain).\n needsRuntimeRequest:\n segment.status === EntryStatus.Fulfilled &&\n wouldRuntimeRequestProvideMore(segment, fetchStrategy) &&\n !isShellEntryEligibleForStaticAttempt(\n now,\n task.segmentCacheMap,\n segment,\n tree,\n fetchStrategy\n ),\n }\n }\n\n // Not bundled. Build a single-node bundle and ping it. If this page\n // accepts the head (HeadInlinedIntoSelf), prepend the head's cache entry\n // to the bundle.\n let effectiveParent: SegmentBundle | null = parentBundle\n if (\n process.env.__NEXT_PREFETCH_INLINING &&\n tree.prefetchHints & PrefetchHint.HeadInlinedIntoSelf\n ) {\n effectiveParent = {\n tree: route.root.head,\n entry: readOrCreateSegmentCacheEntry(\n now,\n task.segmentCacheMap,\n fetchStrategy,\n route.root.head\n ),\n parent: parentBundle,\n }\n }\n\n const segments: SegmentBundle = {\n tree,\n entry: segment,\n parent: effectiveParent,\n }\n\n const needsRuntimeRequest = pingSegmentBundle(\n now,\n task,\n route,\n task.key,\n tree,\n segments,\n fetchStrategy,\n spawnRevalidations\n )\n return { bundle: null, needsRuntimeRequest }\n}\n\nfunction finishStaticBundleOnRuntimeBailout(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree<null>,\n parentBundle: SegmentBundle,\n // The same static walk strategy the parent bundle was accumulated with.\n // Any needs-runtime signal from finishing the bundle is dropped: the\n // caller is already deopting this subtree to a runtime prefetch.\n fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell\n): void {\n const bundle = accumulateSegmentBundle(\n now,\n task,\n route,\n tree,\n parentBundle,\n fetchStrategy,\n // The batched runtime request covers the deopted subtree; only fetch\n // Empty entries the chain would otherwise strand — never spawn\n // revalidations over settled or in-flight ones. See pingSegmentBundle.\n false\n ).bundle\n if (bundle === null) {\n return\n }\n if (tree.slots !== null) {\n for (const childTree of tree.slots.values()) {\n if (childTree.prefetchHints & PrefetchHint.ParentInlinedIntoSelf) {\n finishStaticBundleOnRuntimeBailout(\n now,\n task,\n route,\n childTree,\n bundle,\n fetchStrategy\n )\n return\n }\n }\n }\n}\n\nfunction pingFullSegmentRevalidation(\n now: number,\n task: PrefetchTask,\n tree: RouteTree<null>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.RuntimeShell\n): PendingSegmentCacheEntry | null {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(\n now,\n task.segmentCacheMap,\n fetchStrategy,\n tree\n )\n if (revalidatingSegment.status === EntryStatus.Empty) {\n // During a Full/PPRRuntime prefetch, a single runtime request is made for\n // all the segments that we need. So we don't initiate a request here\n // directly. By returning a pending entry from this function, it signals\n // to the caller that this segment should be included in the request\n // that's sent to the server.\n const pendingSegment = upgradeToPendingSegment(\n revalidatingSegment,\n fetchStrategy\n )\n // The upsert is handled by writeSegmentDataIntoCache\n // when the runtime request's response is written into the cache.\n return pendingSegment\n } else {\n // There's already a revalidation in progress.\n const nonEmptyRevalidatingSegment = revalidatingSegment\n if (\n canNewFetchStrategyProvideMoreContent(\n nonEmptyRevalidatingSegment.fetchStrategy,\n fetchStrategy\n )\n ) {\n // The existing revalidation was fetched using a less specific strategy.\n // Reset it and start a new revalidation.\n const emptySegment = overwriteRevalidatingSegmentCacheEntry(\n now,\n task.segmentCacheMap,\n fetchStrategy,\n tree\n )\n const pendingSegment = upgradeToPendingSegment(\n emptySegment,\n fetchStrategy\n )\n // The upsert is handled by writeSegmentDataIntoCache\n // when the runtime request's response is written into the cache.\n return pendingSegment\n }\n switch (nonEmptyRevalidatingSegment.status) {\n case EntryStatus.Pending:\n // There's already an in-progress prefetch that includes this segment.\n // The pass needs the contents of that response, too. Wait for it\n // before the phase can complete.\n blockTaskOnPendingResponse(task, nonEmptyRevalidatingSegment)\n return null\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n // A previous revalidation attempt finished, but we chose not to replace\n // the existing entry in the cache. Don't try again until or unless the\n // revalidation entry expires.\n return null\n default:\n nonEmptyRevalidatingSegment satisfies never\n return null\n }\n }\n}\n\n/**\n * Decides whether to speculatively prefetch a subtree. Under Partial\n * Prefetching we only do this if the Link's prefetch prop is set to true —\n * otherwise the subtree relies on the shell that the Shell phase prefetches.\n */\nexport function needsSpeculativePrefetch(\n taskfetchStrategy: PrefetchTaskFetchStrategy,\n rootPrefetchHints: number\n): boolean {\n if ((rootPrefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0) {\n // PPF - only needs a speculative prefetch if this is a `<Link prefetch={true}>`.\n return taskfetchStrategy === FetchStrategy.Full\n } else {\n // non-PPF -- all prefetches are speculative.\n return true\n }\n}\n\n// -----------------------------------------------------------------------------\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// -----------------------------------------------------------------------------\n\nfunction compareQueuePriority(a: PrefetchTask, b: PrefetchTask) {\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\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\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\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}\n\nfunction heapPush(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = heap.length\n heap.push(node)\n node._heapIndex = index\n heapSiftUp(heap, node, index)\n}\n\nfunction heapPeek(heap: Array<PrefetchTask>): PrefetchTask | null {\n return heap.length === 0 ? null : heap[0]\n}\n\nfunction heapPop(heap: Array<PrefetchTask>): PrefetchTask | null {\n if (heap.length === 0) {\n return null\n }\n const first = heap[0]\n first._heapIndex = -1\n const last = heap.pop() as PrefetchTask\n if (last !== first) {\n heap[0] = last\n last._heapIndex = 0\n heapSiftDown(heap, last, 0)\n }\n return first\n}\n\nfunction heapDelete(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = node._heapIndex\n if (index !== -1) {\n node._heapIndex = -1\n if (heap.length !== 0) {\n const last = heap.pop() as PrefetchTask\n if (last !== node) {\n heap[index] = last\n last._heapIndex = index\n heapSiftDown(heap, last, index)\n }\n }\n }\n}\n\nfunction heapResift(heap: Array<PrefetchTask>, node: PrefetchTask): void {\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}\n\nfunction heapSiftUp(\n heap: Array<PrefetchTask>,\n node: PrefetchTask,\n i: number\n): void {\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\n index = parentIndex\n } else {\n // The parent is smaller. Exit.\n return\n }\n }\n}\n\nfunction heapSiftDown(\n heap: Array<PrefetchTask>,\n node: PrefetchTask,\n i: number\n): void {\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\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\n index = rightIndex\n } else {\n heap[index] = left\n left._heapIndex = index\n heap[leftIndex] = node\n node._heapIndex = leftIndex\n\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\n index = rightIndex\n } else {\n // Neither child is smaller. Exit.\n return\n }\n }\n}\n","/**\n * Shared types and constants for the Segment Cache.\n */\n\nexport const enum NavigationResultTag {\n MPA,\n Success,\n NoOp,\n Async,\n}\n\n/**\n * The priority of the prefetch task. Higher numbers are higher priority.\n */\nexport const enum 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 */\n Intent = 2,\n /**\n * The default priority for prefetch tasks.\n */\n Default = 1,\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 */\n Background = 0,\n}\n\nexport const enum FetchStrategy {\n // Deliberately ordered so we can easily compare two segments\n // and determine if one segment is \"more specific\" than another\n // (i.e. if it's likely that it contains more data). See\n // canNewFetchStrategyProvideMoreContent in cache.ts for what each tier can\n // contain relative to the others.\n //\n // Full and LoadingBoundary belong to the non-Partial-Prefetching regime:\n // they're only relevant in modes where the staging concepts (shell tiers,\n // runtime prefetches) don't apply. They sit on this single ordered ladder\n // as an accepted convenience, because cross-regime comparisons exist\n // (e.g. canNewFetchStrategyProvideMoreContent).\n //\n // These numeric values are client-internal and never cross the wire — the\n // `next-router-prefetch` request header values are mapped explicitly in\n // fetchSegmentPrefetchesUsingRuntimeRequest (cache.ts) — so the members can\n // be renumbered freely as long as the relative order is preserved.\n LoadingBoundary = 0,\n // The shell-stage variant extracted from a static per-segment prefetch\n // response: every segment's param-dependent content is reduced to pending\n // references that render as the param fallback, keyed at the shell vary\n // paths (only root params kept concrete). The Shell PHASE that issues\n // these requests targets the conceptual App Shell; the strategy itself is\n // just this mechanical truncation and keying. Less complete than\n // RuntimeShell — a static response can't include content that depends on\n // session data (cookies, headers) — and less complete than PPR at concrete\n // paths, which includes prerendered param-dependent content.\n StaticShell = 1,\n RuntimeShell = 2,\n PPR = 3,\n PPRRuntime = 4,\n Full = 5,\n}\n\n/**\n * A subset of fetch strategies used for prefetch tasks.\n * A prefetch task can't know if it should use `PPR` or `LoadingBoundary`\n * until we complete the initial tree prefetch request, so we use `PPR` to signal both cases\n * and adjust it based on the route when actually fetching.\n * */\nexport type PrefetchTaskFetchStrategy =\n | FetchStrategy.PPR\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full\n","import { FetchStrategy } from './types'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n NormalizedNextUrl,\n} from './cache-key'\nimport type { RouteTree } from './cache'\nimport { Fallback, type FallbackType } from './cache-map'\nimport type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport {\n readVaryParams,\n SEARCH_PARAMS_VARY_ID,\n type VaryParamId,\n type VaryParams,\n} from '../../../shared/lib/segment-cache/vary-params-decoding'\n\ntype Opaque<T, K> = T & { __brand: K }\n\n/**\n * A linked-list of all the params (or other param-like) inputs that a cache\n * entry may vary by. This is used by the CacheMap module to reuse cache entries\n * across different param values. If a param has a value of Fallback, it means\n * the cache entry is reusable for all possible values of that param. See\n * cache-map.ts for details.\n *\n * A segment's vary path is a pure function of a segment's position in a\n * particular route tree and the (post-rewrite) URL that is being queried. More\n * concretely, successive queries of the cache for the same segment always use\n * the same vary path.\n *\n * A route's vary path is simpler: it's comprised of the pathname, search\n * string, and Next-URL header.\n */\nexport type VaryPathNode = {\n /**\n * Identifies which param this vary path node corresponds to. Used by\n * getFulfilledSegmentVaryPath to determine which params to replace with\n * Fallback based on the varyParams set from the server.\n *\n * - For path params: the param name (e.g., 'slug')\n * - For search params: SEARCH_PARAMS_VARY_ID\n * - For non-param nodes (request keys, etc.): null\n */\n id: VaryParamId | null\n value: string | null | FallbackType\n /**\n * Whether this node corresponds to a root param — a path param at or above\n * the application's root layout. Root params may appear in the App Shell, so\n * the shell vary path keeps their concrete value instead of replacing it with\n * Fallback. See getShellSegmentVaryPath. Only ever true on path param nodes;\n * false for structural and search param nodes.\n *\n * Always a boolean (never undefined) so that every VaryPathNode shares a\n * single hidden class, keeping the cache hot paths monomorphic.\n */\n isRootParam: boolean\n parent: VaryPathNode | null\n}\n\n// Because it's so important for vary paths to line up across cache accesses,\n// we use opaque type aliases to ensure these are only created within\n// this module.\n\n// requestKey -> searchParams -> nextUrl\nexport type RouteVaryPath = Opaque<\n {\n id: null\n value: NormalizedPathname\n isRootParam: false\n parent: {\n id: typeof SEARCH_PARAMS_VARY_ID\n value: NormalizedSearch\n isRootParam: false\n parent: {\n id: null\n value: NormalizedNextUrl | null | FallbackType\n isRootParam: false\n parent: null\n }\n }\n },\n 'RouteVaryPath'\n>\n\n// requestKey -> [searchParams] -> pathParams\n//\n// The first entry is the request key (id: null). It is followed by the search\n// params entry (id: SEARCH_PARAMS_VARY_ID) when the segment varies on search\n// params, and then by the path params (id: param name), one entry per param,\n// nearest first.\nexport type VaryPath = Opaque<\n {\n id: null\n value: SegmentRequestKey\n isRootParam: false\n parent: VaryPathNode | null\n },\n 'VaryPath'\n>\n\n// Intermediate type used when building a vary path during a recursive traversal\n// of the route tree.\nexport type PartialVaryPath = Opaque<VaryPathNode, 'PartialVaryPath'>\n\nexport function getRouteVaryPath(\n pathname: NormalizedPathname,\n search: NormalizedSearch,\n nextUrl: NormalizedNextUrl | null\n): RouteVaryPath {\n // requestKey -> searchParams -> nextUrl\n const varyPath: VaryPathNode = {\n id: null,\n value: pathname,\n isRootParam: false,\n parent: {\n id: SEARCH_PARAMS_VARY_ID,\n value: search,\n isRootParam: false,\n parent: {\n id: null,\n value: nextUrl,\n isRootParam: false,\n parent: null,\n },\n },\n }\n return varyPath as RouteVaryPath\n}\n\nexport function getFulfilledRouteVaryPath(\n pathname: NormalizedPathname,\n search: NormalizedSearch,\n nextUrl: NormalizedNextUrl | null,\n couldBeIntercepted: boolean\n): RouteVaryPath {\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: VaryPathNode = {\n id: null,\n value: pathname,\n isRootParam: false,\n parent: {\n id: SEARCH_PARAMS_VARY_ID,\n value: search,\n isRootParam: false,\n parent: {\n id: null,\n value: couldBeIntercepted ? nextUrl : Fallback,\n isRootParam: false,\n parent: null,\n },\n },\n }\n return varyPath as RouteVaryPath\n}\n\nexport function appendLayoutVaryPath(\n parentPath: PartialVaryPath | null,\n cacheKey: string,\n paramName: string,\n isRootParam: boolean\n): PartialVaryPath {\n const varyPathPart: VaryPathNode = {\n id: paramName,\n value: cacheKey,\n isRootParam,\n parent: parentPath,\n }\n return varyPathPart as PartialVaryPath\n}\n\nexport function finalizeVaryPath(\n requestKey: SegmentRequestKey,\n // Non-null when the segment varies on search params: the search entry is\n // spliced in between the request key and the path params. Fallback keys an\n // entry that is reusable across all search strings.\n searchParams: NormalizedSearch | FallbackType | null,\n partialVaryPath: PartialVaryPath | null\n): VaryPath {\n // requestKey -> [searchParams] -> pathParams\n let parent: VaryPathNode | null = partialVaryPath\n if (searchParams !== null) {\n parent = {\n id: SEARCH_PARAMS_VARY_ID,\n value: searchParams,\n isRootParam: false,\n parent: partialVaryPath,\n }\n }\n const varyPath: VaryPathNode = {\n id: null,\n value: requestKey,\n isRootParam: false,\n parent,\n }\n return varyPath as VaryPath\n}\n\nexport function getPartialVaryPath(\n finalizedVaryPath: VaryPath\n): PartialVaryPath | null {\n // This is the inverse of finalizeVaryPath: strip the request key, and the\n // search params entry if there is one.\n const parent = finalizedVaryPath.parent\n if (parent !== null && parent.id === SEARCH_PARAMS_VARY_ID) {\n return parent.parent as PartialVaryPath | null\n }\n return parent as PartialVaryPath | null\n}\n\nexport function getSegmentVaryPathForRequest<TData>(\n fetchStrategy: FetchStrategy,\n tree: RouteTree<TData>\n): VaryPath {\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\n if (\n fetchStrategy === FetchStrategy.RuntimeShell ||\n fetchStrategy === FetchStrategy.StaticShell\n ) {\n // Both shell strategies produce the App Shell variant of a segment —\n // RuntimeShell via a runtime render with non-root params omitted,\n // StaticShell by truncating a static per-segment response at the shell\n // byte boundary. Either way, the resulting entry is reusable across all\n // concrete values of the non-root params, so we key it at the precomputed\n // shell vary path (every non-root param substituted with Fallback; root\n // params keep their concrete value).\n return tree.shellVaryPath\n }\n\n // The vary path includes a search params entry only when the segment varies\n // on search params.\n const searchParamsVaryPath = originalVaryPath.parent\n if (\n searchParamsVaryPath !== null &&\n searchParamsVaryPath.id === SEARCH_PARAMS_VARY_ID\n ) {\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 =\n fetchStrategy === FetchStrategy.Full ||\n fetchStrategy === FetchStrategy.PPRRuntime\n\n if (!doesVaryOnSearchParams) {\n // The response from the the server will not vary on search params.\n // Rebuild the vary path with the search params replaced by Fallback.\n //\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with Fallback\n return finalizeVaryPath(\n originalVaryPath.value,\n Fallback,\n getPartialVaryPath(originalVaryPath)\n )\n }\n }\n\n // The request does vary on search params. We don't need to modify anything.\n return originalVaryPath\n}\n\nexport function cloneVaryPathWithNewSearchParams(\n originalVaryPath: VaryPath,\n newSearch: NormalizedSearch\n): VaryPath {\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with newSearch\n const searchParamsVaryPath = originalVaryPath.parent\n if (\n searchParamsVaryPath === null ||\n searchParamsVaryPath.id !== SEARCH_PARAMS_VARY_ID\n ) {\n // No search params entry; nothing to replace.\n return originalVaryPath\n }\n return finalizeVaryPath(\n originalVaryPath.value,\n newSearch,\n getPartialVaryPath(originalVaryPath)\n )\n}\n\n/**\n * Returns the rendered value of the vary path's search params entry when the\n * vary path has one with a concrete value, null otherwise. Only a segment that\n * varies on search params carries the entry; on every other vary path, and on\n * one whose search params entry is Fallback, this is null.\n */\nexport function getRenderedSearchFromVaryPath(\n varyPath: VaryPath\n): NormalizedSearch | null {\n let node: VaryPathNode | null = varyPath\n while (node !== null) {\n if (node.id === SEARCH_PARAMS_VARY_ID) {\n const search = node.value\n if (typeof search === 'string') {\n return search as NormalizedSearch\n }\n return null\n }\n node = node.parent\n }\n return null\n}\n\n/**\n * The kind of param change between two vary paths for the same segment. A path\n * param change takes precedence, because path params are part of\n * LayoutRouter's React key: the segment remounts either way.\n */\nexport const enum ParamsChange {\n None,\n SearchParams,\n PathParam,\n}\n\nexport function compareParams(\n currentVaryPath: VaryPath,\n nextVaryPath: VaryPath\n): ParamsChange {\n // Both vary paths are for the same segment, so they list the same params in\n // the same order. Walk them together. This includes params inherited from\n // parent layouts, since those may have changed, too.\n let current: VaryPathNode | null = currentVaryPath\n let next: VaryPathNode | null = nextVaryPath\n let change = ParamsChange.None\n while (current !== null && next !== null) {\n if (current.value !== next.value) {\n const id = current.id\n if (id === null) {\n // The request key. Callers check that the route structure matches\n // first, so it's always the same.\n } else if (id === SEARCH_PARAMS_VARY_ID) {\n change = ParamsChange.SearchParams\n } else {\n return ParamsChange.PathParam\n }\n }\n current = current.parent\n next = next.parent\n }\n return change\n}\n\nexport function didReadChangedParam(\n currentVaryPath: VaryPath,\n nextVaryPath: VaryPath,\n varyParams: VaryParams | null\n): boolean {\n // Returns true if the output rendered with `currentVaryPath` read a param\n // whose value is different in `nextVaryPath`. `varyParams` is the set of\n // params the output read, or null if we don't know.\n //\n // Same traversal as compareParams. Only read the set if a param changed.\n let current: VaryPathNode | null = currentVaryPath\n let next: VaryPathNode | null = nextVaryPath\n let total: Set<VaryParamId> | null = null\n while (current !== null && next !== null) {\n if (current.value !== next.value) {\n const id = current.id\n if (id === null) {\n // The request key. Callers check that the route structure matches\n // first, so it's always the same.\n } else {\n if (total === null) {\n if (varyParams === null) {\n // We don't know. Assume it read the param.\n return true\n }\n total = readVaryParams(varyParams)\n if (total === null) {\n // The render hasn't finished, or it aborted. Assume it read the\n // param.\n return true\n }\n }\n if (total.has(id)) {\n return true\n }\n }\n }\n current = current.parent\n next = next.parent\n }\n return false\n}\n\nexport function getFulfilledSegmentVaryPath(\n original: VaryPathNode,\n varyParams: Set<VaryParamId>\n): VaryPath {\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\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: VaryPathNode = {\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:\n original.id === null || varyParams.has(original.id)\n ? original.value\n : Fallback,\n isRootParam: original.isRootParam,\n parent:\n original.parent === null\n ? null\n : getFulfilledSegmentVaryPath(original.parent, varyParams),\n }\n return clone as VaryPath\n}\n\nexport function getShellSegmentVaryPath(original: VaryPathNode): VaryPath {\n // Re-keys a segment's vary path to identify the \"App Shell\" entry for this\n // segment position — a reusable loading state that can be served for any\n // concrete navigation to this segment. The shell is rendered with params\n // omitted, with one exception: root params (path params at or above the root\n // layout) may be accessed during the shell render, so the shell varies on\n // them. Accordingly, we keep the concrete value of structural nodes (request\n // keys, etc.) and root param nodes, and replace every other param node (non-\n // root path params and search params) with Fallback.\n const clone: VaryPathNode = {\n id: original.id,\n value:\n original.id === null || original.isRootParam === true\n ? original.value\n : Fallback,\n isRootParam: original.isRootParam,\n parent:\n original.parent === null\n ? null\n : getShellSegmentVaryPath(original.parent),\n }\n return clone as VaryPath\n}\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","import type {\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n InitialRSCPayload,\n} from '../shared/lib/app-router-types'\nimport type {\n FullTransportNode,\n TransportSegment,\n} from '../shared/lib/rsc-transport'\nimport {\n getCacheKeyForDynamicParam,\n parseDynamicParamFromURLPart,\n doesStaticSegmentAppearInURL,\n getRenderedPathname,\n getRenderedSearch,\n} from './route-params'\nimport { createHrefFromUrl } from './components/router-reducer/create-href-from-url'\n\nexport function createInitialRSCPayloadFromFallbackPrerender(\n response: Response,\n fallbackInitialRSCPayload: InitialRSCPayload\n): InitialRSCPayload {\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\n // Patch the transport tree sent by the server with the correct params\n // parsed from the URL + response object.\n const renderedPathname = getRenderedPathname(response)\n const renderedSearch = getRenderedSearch(response)\n const canonicalUrl = createHrefFromUrl(new URL(location.href))\n const fallbackTransportData = fallbackInitialRSCPayload.t\n const payload: InitialRSCPayload = {\n c: canonicalUrl.split('/'),\n q: renderedSearch,\n i: fallbackInitialRSCPayload.i,\n t: {\n t: fillInFallbackTransportTree(\n fallbackTransportData.t,\n renderedPathname.split('/').filter((part) => part !== ''),\n 0\n ),\n h: fallbackTransportData.h,\n },\n m: fallbackInitialRSCPayload.m,\n G: fallbackInitialRSCPayload.G,\n S: fallbackInitialRSCPayload.S,\n }\n if (fallbackInitialRSCPayload.b) {\n payload.b = fallbackInitialRSCPayload.b\n }\n return payload\n}\n\n/**\n * A fallback prerender is rendered without concrete param values. Fill them\n * in by parsing the rendered pathname, so the hydrated tree has the same\n * identity a direct render of this URL would have.\n */\nfunction fillInFallbackTransportTree(\n node: FullTransportNode,\n pathnameParts: Array<string>,\n pathnamePartsIndex: number\n): FullTransportNode {\n const originalSegment = node.s\n let newSegment: TransportSegment\n let doesAppearInURL: boolean\n if (typeof originalSegment === 'string') {\n newSegment = originalSegment\n doesAppearInURL = doesStaticSegmentAppearInURL(originalSegment)\n } else {\n const paramValue = parseDynamicParamFromURLPart(\n originalSegment.t,\n pathnameParts,\n pathnamePartsIndex\n )\n newSegment = {\n n: originalSegment.n,\n t: originalSegment.t,\n k: getCacheKeyForDynamicParam(paramValue),\n s: originalSegment.s,\n }\n doesAppearInURL = true\n }\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\n ? pathnamePartsIndex + 1\n : pathnamePartsIndex\n\n const children = node.c\n let newChildren: Map<string, FullTransportNode> | undefined\n if (children !== undefined) {\n newChildren = new Map()\n for (const [parallelRouteKey, childNode] of children) {\n newChildren.set(\n parallelRouteKey,\n fillInFallbackTransportTree(\n childNode,\n pathnameParts,\n childPathnamePartsIndex\n )\n )\n }\n }\n\n const newNode: FullTransportNode = {\n s: newSegment,\n d: node.d,\n }\n if (node.h !== undefined) {\n newNode.h = node.h\n }\n if (newChildren !== undefined) {\n newNode.c = newChildren\n }\n return newNode\n}\n\nexport function getNextFlightSegmentPath(\n flightSegmentPath: FlightSegmentPath\n): FlightSegmentPath {\n // Since `FlightSegmentPath` is a repeated tuple of `Segment` and `ParallelRouteKey`, we slice off two items\n // to get the next segment path.\n return flightSegmentPath.slice(2)\n}\n\n/**\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 */\nexport function prepareFlightRouterStateForRequest(\n flightRouterState: FlightRouterState,\n isHmrRefresh?: boolean\n): string {\n // HMR requests need the complete, unmodified state for proper functionality\n if (isHmrRefresh) {\n return encodeURIComponent(JSON.stringify(flightRouterState))\n }\n\n return encodeURIComponent(\n JSON.stringify(stripClientOnlyDataFromFlightRouterState(flightRouterState))\n )\n}\n\n/**\n * Recursively strips client-only data from FlightRouterState while preserving\n * server-needed information for proper rendering decisions.\n */\nfunction stripClientOnlyDataFromFlightRouterState(\n flightRouterState: FlightRouterState\n): FlightRouterState {\n const [\n segment,\n parallelRoutes,\n _refreshState, // Intentionally unused - URLs are client-only\n refreshMarker,\n prefetchHints,\n ] = flightRouterState\n\n // Strip client-only data from the segment\n const cleanedSegment = stripClientOnlyDataFromSegment(segment)\n\n // Recursively process parallel routes\n const cleanedParallelRoutes: { [key: string]: FlightRouterState } = {}\n for (const [key, childState] of Object.entries(parallelRoutes)) {\n cleanedParallelRoutes[key] =\n stripClientOnlyDataFromFlightRouterState(childState)\n }\n\n const result: FlightRouterState = [cleanedSegment, cleanedParallelRoutes]\n if (refreshMarker) {\n result[2] = null // null slightly more compact than undefined\n result[3] = refreshMarker\n }\n\n // Append optional fields if present\n if (prefetchHints !== undefined) {\n result[4] = prefetchHints\n }\n\n // Leave out the page's search params. They're only used by the client, and\n // request headers may be forwarded through redirects.\n return result\n}\n\n/**\n * Strips client-only data from segments:\n * - staticSiblings from dynamic segment tuples (only needed for client-side\n * prefetch reuse decisions)\n */\nfunction stripClientOnlyDataFromSegment(segment: Segment): Segment {\n if (typeof segment === 'string') {\n return segment\n }\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n // Strip staticSiblings (4th element) since server doesn't need it\n const [paramName, paramCacheKey, paramType] = segment\n return [paramName, paramCacheKey, paramType, null]\n}\n","import { pathHasPrefix } from '../shared/lib/router/utils/path-has-prefix'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function hasBasePath(path: string): boolean {\n return pathHasPrefix(path, basePath)\n}\n","// Adapted from React's sanitizeURL function found here: https://github.com/facebook/react/blob/b565373afd0cc1988497e1107106e851e8cfb261/packages/react-dom-bindings/src/shared/sanitizeURL.js\n\n// A javascript: URL can contain leading C0 control or \\u0020 SPACE,\n// and any newline or tab are filtered out as if they're not part of the URL.\n// https://url.spec.whatwg.org/#url-parsing\n// Tab or newline are defined as \\r\\n\\t:\n// https://infra.spec.whatwg.org/#ascii-tab-or-newline\n// A C0 control is a code point in the range \\u0000 NULL to \\u001F\n// INFORMATION SEPARATOR ONE, inclusive:\n// https://infra.spec.whatwg.org/#c0-control-or-space\n\nconst isJavaScriptProtocol =\n // eslint-disable-next-line no-control-regex\n /^[\\u0000-\\u001F ]*j[\\r\\n\\t]*a[\\r\\n\\t]*v[\\r\\n\\t]*a[\\r\\n\\t]*s[\\r\\n\\t]*c[\\r\\n\\t]*r[\\r\\n\\t]*i[\\r\\n\\t]*p[\\r\\n\\t]*t[\\r\\n\\t]*:/i\n\nexport function isJavaScriptURLString(url: string): boolean {\n return isJavaScriptProtocol.test('' + (url as unknown as string))\n}\n","// This gets assigned as a side-effect during app initialization. Because it\n// represents the build used to create the JS bundle, it should never change\n// after being set, so we store it in a global variable.\n//\n// When performing RSC requests, if the incoming data has a different build ID,\n// we perform an MPA navigation/refresh to load the updated build and ensure\n// that the client and server in sync.\n//\n// Starts as an empty string. In practice, because setNavigationBuildId is called during initialization\n// before hydration starts, this will always get reassigned to the actual ID before it's ever needed\n// by a navigation. If for some reasons it didn't, due to a bug or race condition, then on\n// navigation the build comparision would fail and trigger an MPA navigation.\n//\n// Note that this can also be initialized with the deployment id instead (if available). So it's not\n// the same as \"the build id\", but we are running out of alternative names for \"build id or\n// deployment id\".\nlet globalBuildId: string = ''\n\nexport function setNavigationBuildId(buildId: string) {\n globalBuildId = buildId\n}\n\nexport function getNavigationBuildId(): string {\n return globalBuildId\n}\n","import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { parsePath } from '../shared/lib/router/utils/parse-path'\n\n/**\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string) => {\n // 47 is the char code for '/'\n if (path.charCodeAt(0) !== 47 || process.env.__NEXT_MANUAL_TRAILING_SLASH) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n if (process.env.__NEXT_TRAILING_SLASH) {\n if (/\\.[^/]+\\/?$/.test(pathname)) {\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n } else if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n } else {\n return `${pathname}/${query}${hash}`\n }\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n","import { hasBasePath } from './has-base-path'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function removeBasePath(path: string): string {\n if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {\n if (!hasBasePath(path)) {\n return path\n }\n }\n\n // Can't trim the basePath if it has zero length!\n if (basePath.length === 0) return path\n\n path = path.slice(basePath.length)\n if (!path.startsWith('/')) path = `/${path}`\n return path\n}\n","import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'\nimport { DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../shared/lib/segment'\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'\nimport {\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from './components/app-router-headers'\nimport { hasBasePath } from './has-base-path'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\nimport { removeBasePath } from './remove-base-path'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n} from './components/segment-cache/cache-key'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\nimport type { ParsedUrlQuery } from 'querystring'\nimport { getRenderedSearch as getRenderedSearchFromQuery } from '../shared/lib/router/utils/querystring'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport function normalizeRenderedSearch(search: string): NormalizedSearch {\n // The same search params should produce the same string whether they came\n // from the URL, a rewrite header, or the response (e.g. '+' vs '%20'). Only\n // used for the rendered search. Request URLs keep their original form,\n // since middleware and rewrites may depend on it.\n const query = urlSearchParamsToParsedUrlQuery(new URLSearchParams(search))\n return getRenderedSearchFromQuery(query) as NormalizedSearch\n}\n\nexport function getRenderedSearch(\n response: RSCResponse<unknown> | Response\n): NormalizedSearch {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)\n if (rewrittenQuery !== null) {\n return normalizeRenderedSearch(rewrittenQuery)\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return normalizeRenderedSearch(\n urlToUrlWithoutFlightMarker(new URL(response.url)).search\n )\n}\n\nexport function getRenderedPathname(\n response: RSCResponse<unknown> | Response\n): NormalizedPathname {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)\n if (rewrittenPath !== null) {\n return rewrittenPath as NormalizedPathname\n }\n\n const pathname = urlToUrlWithoutFlightMarker(new URL(response.url)).pathname\n return (\n hasBasePath(pathname) ? removeBasePath(pathname) : pathname\n ) as NormalizedPathname\n}\n\n/**\n * Like getRenderedPathname, but derived from the request URL rather than the\n * response. Used in output: \"export\" mode, where the response URL has the\n * segment filename appended to the pathname — and where rewrites don't\n * exist, so the request pathname is always the rendered pathname.\n */\nexport function getPathnameFromRequestURL(url: URL): NormalizedPathname {\n const pathname = url.pathname\n return (\n hasBasePath(pathname) ? removeBasePath(pathname) : pathname\n ) as NormalizedPathname\n}\n\n// Pathname parts come from `URL.pathname.split('/')`, so they are already\n// in the encoded form the URL parser produces. The server-side equivalent\n// (`get-dynamic-param.ts`) starts from a decoded param value and applies\n// `encodeURIComponent` once. The two encodings are not the same — for\n// example, the URL parser leaves `,` and `:` untouched while\n// `encodeURIComponent` percent-encodes them. To produce the same canonical\n// form on the client (and avoid double-encoding `%xx` sequences such as\n// `%2F` → `%252F`), we decode the URL part first and re-encode it.\nexport function canonicalizeURLPart(part: string): string {\n try {\n return encodeURIComponent(decodeURIComponent(part))\n } catch {\n // `decodeURIComponent` throws on malformed sequences. Fall back to the\n // already-encoded form rather than failing the navigation.\n return part\n }\n}\n\nexport function parseDynamicParamFromURLPart(\n paramType: DynamicParamTypesShort,\n pathnameParts: Array<string>,\n partIndex: number\n): RouteParamValue {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch (paramType) {\n // Catchalls\n case 'c': {\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\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : []\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)': {\n const prefix = paramType.length - 2\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s, i) => {\n if (i === 0) {\n return canonicalizeURLPart(s.slice(prefix))\n }\n\n return canonicalizeURLPart(s)\n })\n : []\n }\n // Optional catchalls\n case 'oc': {\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\n ? pathnameParts.slice(partIndex).map((s) => canonicalizeURLPart(s))\n : null\n }\n // Dynamic\n case 'd': {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n return canonicalizeURLPart(pathnameParts[partIndex])\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)': {\n 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\n return canonicalizeURLPart(pathnameParts[partIndex].slice(prefix))\n }\n default:\n paramType satisfies never\n return ''\n }\n}\n\nexport function doesStaticSegmentAppearInURL(segment: string): boolean {\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 (\n segment === ROOT_SEGMENT_REQUEST_KEY ||\n // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment === PAGE_SEGMENT_KEY ||\n // Route groups.\n (segment[0] === '(' && segment.endsWith(')')) ||\n segment === DEFAULT_SEGMENT_KEY ||\n segment === '/_not-found'\n ) {\n return false\n } else {\n // All other segment types appear in the URL\n return true\n }\n}\n\nexport function getCacheKeyForDynamicParam(\n paramValue: RouteParamValue\n): string {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n return paramValue\n } else if (paramValue === null) {\n return ''\n } else {\n return paramValue.join('/')\n }\n}\n\nexport function urlToUrlWithoutFlightMarker(url: URL): URL {\n const urlWithoutFlightParameters = new URL(url)\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)\n if (process.env.NODE_ENV === 'production') {\n if (\n process.env.__NEXT_CONFIG_OUTPUT === 'export' &&\n urlWithoutFlightParameters.pathname.endsWith('.txt')\n ) {\n const { pathname } = urlWithoutFlightParameters\n // Undo the marker appended in `fetchServerResponse`, which is keyed on\n // whether the requested pathname ended with a slash: `index.txt` for\n // `/foo/`, `.txt` for `/foo`. Slicing off only `index.txt` keeps that\n // slash, then `normalizePathTrailingSlash` applies the configured\n // policy so we don't hand-roll a second one here.\n const length = pathname.endsWith('/index.txt') ? 9 : 4\n urlWithoutFlightParameters.pathname = normalizePathTrailingSlash(\n pathname.slice(0, -length)\n )\n }\n }\n return urlWithoutFlightParameters\n}\n\nexport function getParamValueFromCacheKey(\n paramCacheKey: string,\n paramType: DynamicParamTypesShort\n) {\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}\n\nexport function urlSearchParamsToParsedUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\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: ParsedUrlQuery = {}\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] = [result[key], value]\n }\n }\n return result\n}\n","// The sequential implementation of callServer (app-call-server.ts): Server\n// Actions are dispatched into the sequential router action queue. Callers\n// must never import this module directly; they import './app-call-server',\n// which resolves here unless `experimental.concurrentRouterQueue` swaps in\n// './concurrent-call-server' at the bundler level (see\n// create-compiler-aliases.ts and next_import_map.rs).\n//\n// This module must remain free of side effects at module scope: in addition\n// to the browser bundle, a statically-resolved copy may be compiled into the\n// pre-compiled app-page runtime bundles, where the bundler alias cannot\n// reach. Only the browser copy ever runs.\n\nimport { startTransition } from 'react'\nimport { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'\nimport { dispatchAppRouterAction } from './components/use-action-queue'\n\nexport async function callServer(actionId: string, actionArgs: any[]) {\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","import { useCallback, useRef, type Ref } from 'react'\n\n// This is a compatibility hook to support React 18 and 19 refs.\n// In 19, a cleanup function from refs may be returned.\n// In 18, returning a cleanup function creates a warning.\n// Since we take userspace refs, we don't know ahead of time if a cleanup function will be returned.\n// This implements cleanup functions with the old behavior in 18.\n// We know refs are always called alternating with `null` and then `T`.\n// So a call with `null` means we need to call the previous cleanup functions.\nexport function useMergedRef<TElement>(\n refA: Ref<TElement>,\n refB: Ref<TElement>\n): Ref<TElement> {\n const cleanupA = useRef<(() => void) | null>(null)\n const cleanupB = useRef<(() => void) | null>(null)\n\n // NOTE: In theory, we could skip the wrapping if only one of the refs is non-null.\n // (this happens often if the user doesn't pass a ref to Link/Form/Image)\n // But this can cause us to leak a cleanup-ref into user code (previously via `<Link legacyBehavior>`),\n // and the user might pass that ref into ref-merging library that doesn't support cleanup refs\n // (because it hasn't been updated for React 19)\n // which can then cause things to blow up, because a cleanup-returning ref gets called with `null`.\n // So in practice, it's safer to be defensive and always wrap the ref, even on React 19.\n return useCallback(\n (current: TElement | null): void => {\n if (current === null) {\n const cleanupFnA = cleanupA.current\n if (cleanupFnA) {\n cleanupA.current = null\n cleanupFnA()\n }\n const cleanupFnB = cleanupB.current\n if (cleanupFnB) {\n cleanupB.current = null\n cleanupFnB()\n }\n } else {\n if (refA) {\n cleanupA.current = applyRef(refA, current)\n }\n if (refB) {\n cleanupB.current = applyRef(refB, current)\n }\n }\n },\n [refA, refB]\n )\n}\n\nfunction applyRef<TElement>(\n refA: NonNullable<Ref<TElement>>,\n current: TElement\n) {\n if (typeof refA === 'function') {\n const cleanup = refA(current)\n if (typeof cleanup === 'function') {\n return cleanup\n } else {\n return () => refA(null)\n }\n } else {\n refA.current = current\n return () => {\n refA.current = null\n }\n }\n}\n","import type { ServerRuntime } from '../types'\n\nexport 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'\n\nexport const MATCHED_PATH_HEADER = 'x-matched-path'\nexport const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'\nexport const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =\n 'x-prerender-revalidate-if-generated'\n\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'\n\nexport const NEXT_NAV_DEPLOYMENT_ID_HEADER = 'x-nextjs-deployment-id'\n\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 =\n 'x-next-revalidate-tag-token'\n\nexport const NEXT_RESUME_HEADER = 'next-resume'\nexport const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length'\n\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\n// in seconds\nexport const CACHE_ONE_YEAR_SECONDS = 31536000\n\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\n// Patterns to detect middleware files\nexport const MIDDLEWARE_FILENAME = 'middleware'\nexport const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`\n\n// Patterns to detect proxy files (replacement for middleware)\nexport const PROXY_FILENAME = 'proxy'\nexport const PROXY_LOCATION_REGEXP = `(?:src/)?${PROXY_FILENAME}`\n\n// Pattern to detect instrumentation hooks file\nexport const INSTRUMENTATION_HOOK_FILENAME = 'instrumentation'\n\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 =\n 'private-next-rsc-track-dynamic-import'\nexport const RSC_ACTION_ENCRYPTION_ALIAS = 'private-next-rsc-action-encryption'\nexport const RSC_ACTION_CLIENT_WRAPPER_ALIAS =\n 'private-next-rsc-action-client-wrapper'\n\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`\n\nexport const SSG_GET_INITIAL_PROPS_CONFLICT = `You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps`\n\nexport const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.`\n\nexport const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`\n\nexport const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props`\n\nexport const SERVER_PROPS_EXPORT_ERROR = `pages with \\`getServerSideProps\\` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export`\n\nexport const GSP_NO_RETURNED_VALUE =\n 'Your `getStaticProps` function did not return an object. Did you forget to add a `return`?'\nexport const GSSP_NO_RETURNED_VALUE =\n 'Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?'\n\nexport const UNSTABLE_REVALIDATE_RENAME_ERROR =\n 'The `unstable_revalidate` property is available for general use.\\n' +\n 'Please use `revalidate` instead.'\n\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`\n\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`\n\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`\n\nexport const ESLINT_DEFAULT_DIRS = ['app', 'pages', 'components', 'lib', 'src']\n\nexport const SERVER_RUNTIME: Record<string, ServerRuntime> = {\n edge: 'edge',\n experimentalEdge: 'experimental-edge',\n nodejs: 'nodejs',\n}\n\nexport const WEB_SOCKET_MAX_RECONNECTIONS = 12\n\n/**\n * The names of the webpack layers. These layers are the primitives for the\n * webpack chunks.\n */\nconst WEBPACK_LAYERS_NAMES = {\n /**\n * The layer for the shared code between the client and server bundles.\n */\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 */\n reactServerComponents: 'rsc',\n /**\n * Server Side Rendering layer for app (ssr).\n */\n serverSideRendering: 'ssr',\n /**\n * The browser client bundle layer for actions.\n */\n actionBrowser: 'action-browser',\n /**\n * The Node.js bundle layer for the API routes.\n */\n apiNode: 'api-node',\n /**\n * The Edge Lite bundle layer for the API routes.\n */\n apiEdge: 'api-edge',\n /**\n * The layer for the middleware code.\n */\n middleware: 'middleware',\n /**\n * The layer for the instrumentation hooks.\n */\n instrument: 'instrument',\n /**\n * The layer for assets on the edge.\n */\n edgeAsset: 'edge-asset',\n /**\n * The browser client bundle layer for App directory.\n */\n appPagesBrowser: 'app-pages-browser',\n /**\n * The browser client bundle layer for Pages directory.\n */\n pagesDirBrowser: 'pages-dir-browser',\n /**\n * The Edge Lite bundle layer for Pages directory.\n */\n pagesDirEdge: 'pages-dir-edge',\n /**\n * The Node.js bundle layer for Pages directory.\n */\n pagesDirNode: 'pages-dir-node',\n} as const\n\nexport type WebpackLayerName =\n (typeof WEBPACK_LAYERS_NAMES)[keyof typeof WEBPACK_LAYERS_NAMES]\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}\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}\n\nexport { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES }\n","/**\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 */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\nimport type {\n VaryParams,\n VaryParamsIterable,\n} from './segment-cache/vary-params-decoding'\nimport type { FullTransportData, PartialTransportData } from './rsc-transport'\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\n/**\n * Render state for a segment. Reuse this object while its data is unchanged;\n * create a new one when a navigation replaces the segment's data.\n */\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * <LayoutRouter> component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n /**\n * The source of the params `rsc` depends on, from the response that\n * produced it. Null when unknown: the data came from the segment cache, or\n * from a render that didn't track params, or `rsc` is still pending — it\n * is set alongside `rsc` when the response arrives. A navigation that only\n * changes params this output did not depend on can keep rendering it.\n */\n varyParams: VaryParams | null\n\n /**\n * A shared mutable ref that tracks whether this segment should be scrolled\n * to. All new segments created during a single navigation share the same\n * ref. When any segment's scroll handler fires, it sets `current` to\n * `false` so no other segment scrolls for the same navigation.\n *\n * `null` means this segment is not a scroll target (e.g., a reused shared\n * layout segment).\n */\n scrollRef: ScrollRef | null\n\n /**\n * Globally-unique identifier minted from a monotonic counter when the\n * CacheNode is freshly created. Surfaced to user code as a string via\n * `useRouter().bfcacheId` and intended to be used as a React `key` to\n * opt out of Activity-based state preservation on fresh navigations.\n *\n * Preserved when the CacheNode is reused (shared layouts, refresh,\n * search/hash-only navigations) or restored from the BFCache during a\n * back/forward navigation.\n */\n bfcacheId: number\n}\n\n/**\n * A mutable ref shared across all new segments created during a single\n * navigation. Used to ensure that only one segment scrolls per navigation.\n */\nexport type ScrollRef = { current: boolean }\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\n// The tuple form of a segment, used for dynamic route params\nexport type DynamicSegmentTuple = [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n // Static sibling segments at the same URL level. Used by the client\n // router to determine if a prefetch can be reused when navigating to\n // a static sibling of a dynamic route. For example, if the route is\n // /products/[id] and there's also /products/sale, then staticSiblings\n // would be ['sale']. null means the siblings are unknown (e.g. in\n // webpack dev mode).\n staticSiblings: readonly string[] | null,\n]\n\nexport type Segment = string | DynamicSegmentTuple\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n refreshState?: CompressedRefreshState | null,\n /**\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,\n /**\n * Bitmask of PrefetchHint flags. Encodes route structure metadata:\n * root layout, loading boundaries, instant configs, and prefetch strategy\n * hints. Only set when non-zero. JSON encodes an omitted slot as null when\n * a later slot is present.\n */\n prefetchHints?: number | null,\n /**\n * The rendered search params of a page segment. An empty string means there\n * are none. Only set on page nodes, and left out of request headers.\n * TODO: Revisit this as part of the larger FlightRouterState refactor.\n */\n renderedSearch?: string,\n]\n\n/**\n * When rendering a parallel route, some of the parallel paths may not match\n * the current URL. In that case, the Next client has to render something,\n * so it will render whichever was the last route to match that slot. We use\n * this type to track when this has happened. It's a tuple of the original\n * URL that was used to fetch the segment, and the (possibly rewritten) search\n * query that was rendered by the server. The URL is needed when performing\n * a refresh of the segment, and the search query is needed for looking up\n * matching entries in the segment cache.\n */\nexport type CompressedRefreshState = [url: string, renderedSearch: string]\n\nexport const enum PrefetchHint {\n // NOTE: The 0b00001 bit was previously HasRuntimePrefetch (prefetch:\n // 'allow-runtime'). Partial Prefetching allows using runtime requests\n // for every segment, so the bit was removed. Do not reuse it without\n // considering caches populated by older builds.\n\n // This segment or one of its descendants opts into Partial Prefetching, i.e.\n // uses the two-phase (Shell then Speculative) prefetch flow. Set when\n // `prefetch` is 'partial' (including the default implied by the global\n // `partialPrefetching` config). Propagates upward so the root segment\n // reflects the entire subtree.\n //\n // Partial Prefetching routes may use runtime requests for both shells\n // and prefetches. They *may* be optimized to a use a static request\n // if no runtime data was accessed during the prerender.\n // However, If the route has `ensureStatic` configured to \"shell\", \"prefetch\",\n // or \"navigation\", we *must* use static requests for the shell (and possibly the\n // prefetch).\n // Both of these cases are signalled to the scheduler via the\n // `ShouldAttemptStatic{Shell,Prefetch}` hints and the `needsRuntimeRequest`\n // promise.\n SubtreeHasPartialPrefetching = 0b00010,\n // This segment itself has a loading.tsx boundary.\n SegmentHasLoadingBoundary = 0b00100,\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n SubtreeHasLoadingBoundary = 0b01000,\n // This segment is at or above the application's root layout — the root layout\n // segment itself and all of its ancestors. A dynamic param in one of these\n // segments is a \"root param\".\n IsRootLayoutOrAbove = 0b10000,\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 ParentInlinedIntoSelf = 0b100000,\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 InlinedIntoChild = 0b1000000,\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // in its transport data (PartialTransportData's `h`).\n HeadInlinedIntoSelf = 0b10000000,\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 HeadOutlined = 0b100000000,\n // The inlining hints in this tree may be stale because the tree was\n // generated before collectPrefetchHints ran (e.g. the initial RSC payload\n // for a fully static page at build time). When writing this tree into the\n // cache, the route entry should be immediately expired so it gets\n // re-fetched with correct hints. Only set during build-time prerendering,\n // never at runtime.\n InliningHintsStale = 0b1000000000,\n // This segment has prefetch = 'force-disabled'. The opt-out is passive\n // and applies to this segment only: it never INITIATES a prefetch — no\n // static data is emitted or fetched, and it's never the reason a runtime\n // prefetch spawns — but it may ride along in a runtime response issued on\n // another segment's behalf. Descendants prefetch normally.\n //\n // TODO: Also set as an internal fallback when the prefetch hints manifest\n // is unavailable (see #91407 mitigations), which only means \"no static\n // prefetch data exists\" — not a user opt-out. Split the fallback into its\n // own bit so the two intents can diverge.\n PrefetchDisabled = 0b10000000000,\n // NOTE: The 0b100000000000 bit was previously SubtreeHasRuntimePrefetch.\n // Partial Prefetching now implies runtime completeness for every segment\n // (see SubtreeHasPartialPrefetching), so the bit was removed. Do not reuse\n // it without considering caches populated by older builds.\n\n // NOTE: The 0b1000000000000 bit was previously SubtreeHasEagerPrefetch\n // (prefetch: 'unstable_eager', plus every segment that did not opt into\n // Partial Prefetching). After `unstable_eager` was removed, it's no longer needed.\n\n // This segment or one of its descendants exports `instant = false`,\n // explicitly opting out of Partial Prefetching. Propagates upward so the root\n // reflects the entire subtree. Used only to suppress the dev-time\n // `<Link prefetch={true}>` warning — unlike PrefetchDisabled, it has no effect\n // on the actual prefetch behavior.\n SubtreeHasInstantFalse = 0b10000000000000,\n // The client should attempt a static prefetch for this route: the\n // build-time prerender did not access any runtime data (cookies, headers,\n // searchParams, ...), so a static prefetch is expected to be as complete\n // as a runtime one. A fallback-param access only unsets the bit when the\n // route can never be upgraded from a fallback to a concrete prerender —\n // on an upgradeable route, ISR later produces the concrete prerender a\n // static attempt would hit (until then, the static responses' own\n // signal reports the insufficiency per response). Purely advisory, and\n // both error directions are safe: if set when a runtime request is\n // actually needed, that same response-level signal (the load-bearing\n // `needsRuntimeRequest` promise combined with each segment's `isPartial`)\n // directs the client to follow up — the cost is a wasted static attempt.\n // If unset when static would have sufficed, the client goes straight to a\n // runtime prefetch, which is a superset of the static response — the cost\n // is only reduced cacheability. Like the other bits, this one is computed\n // once per build and stays constant for the build's lifetime; it rides\n // the prefetch-hints manifest into every response that carries hints —\n // `/_tree` prefetch responses and the FlightRouterState of dynamic\n // navigations alike. (Routes missing from the manifest — see the #91407\n // fallbacks — simply never carry it.) Set on every node of the tree, but\n // does not propagate.\n ShouldAttemptStaticShell = 0b100000000000000,\n ShouldAttemptStaticPrefetch = 0b1000000000000000,\n // This dynamic segment only accepts build-time parameter values. Kept on\n // the affected node, without propagating or copying it to other segments.\n // Until the client knows the allowed values, any such node prevents route\n // prediction, even when the route's components never read the parameter.\n IsClosedParam = 0b10000000000000000,\n // A descendant segment (but not this one) has a closed parameter. Propagates\n // upward so route prediction can check the root instead of walking the tree.\n SubtreeHasClosedParams = 0b100000000000000000,\n}\n\n/**\n * Bitmask for checking whether a segment's static prefetch is skipped — i.e.\n * the server emits no static data for it (its node in a segment response\n * carries identity only, and it participates in a bundle only as a\n * pass-through) and the client never issues a static request for it.\n *\n * Static prefetching is disabled ONLY by `prefetch: 'force-disabled'`\n * (PrefetchDisabled). Notably, Partial Prefetching segments DO have static\n * data even though they can use runtime requests: the server emits it\n * unconditionally — it can't be gated on the ShouldAttemptStatic{Shell,Prefetch}\n * hints, because which segments carry static data must be deterministic\n * from build-time config. A runtime request may still be needed for the\n * segment, but the scheduler may attempt a static prefetch first (per the\n * ShouldAttemptStatic{Shell,Prefetch} hints) and skip the runtime request if the\n * static response proves sufficient.\n *\n * Usage: `(hints & StaticPrefetchDisabled) !== 0`\n */\nexport const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled\n\nexport const StaticAttemptHints =\n PrefetchHint.ShouldAttemptStaticShell |\n PrefetchHint.ShouldAttemptStaticPrefetch\n\n/**\n * The subset of PrefetchHint bits that propagate upward from a child segment to\n * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary\n * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them\n * from a node's children.\n */\nexport const SubtreePrefetchHints =\n PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasLoadingBoundary |\n PrefetchHint.SubtreeHasInstantFalse |\n PrefetchHint.SubtreeHasClosedParams\n\n/**\n * Folds a child segment's prefetch hints into its parent's, propagating the\n * \"subtree\" flags. A child's segment-local flag (e.g. it has a loading\n * boundary) becomes the corresponding \"subtree\" flag on the parent, so the\n * root segment ends up reflecting the entire subtree.\n *\n * Used wherever a route tree is assembled bottom-up: on the server when building\n * a transport tree (createTransportTreeFromLoaderTree) and on the client when\n * overlaying a navigation response onto the existing tree\n * (createNavigationSeed). Keep these in sync by routing both through\n * this helper.\n */\nexport function propagateSubtreeBits(\n parentHints: number,\n childHints: number\n): number {\n if (childHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n parentHints |= PrefetchHint.SubtreeHasPartialPrefetching\n }\n // A child with a loading boundary (directly, or anywhere in its subtree) makes\n // this a SubtreeHasLoadingBoundary on the parent.\n if (\n childHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)\n ) {\n parentHints |= PrefetchHint.SubtreeHasLoadingBoundary\n }\n // And for `instant = false`. The bit is set directly on each opted-out\n // segment, so there's no separate segment-local flag — propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasInstantFalse) {\n parentHints |= PrefetchHint.SubtreeHasInstantFalse\n }\n if (\n childHints &\n (PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)\n ) {\n parentHints |= PrefetchHint.SubtreeHasClosedParams\n }\n return parentHints\n}\n\n/**\n * A path through the segment tree: a repeating sequence of segment and\n * parallel route key. Used by the client to address positions in the\n * render tree (see layout-router).\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Per-route prefetch hints computed at build time. Mirrors the shape of the\n * loader tree so hints can be traversed in parallel during router state\n * creation. Each node stores a bitmask of PrefetchHint flags\n * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size\n * measurement pass.\n *\n * Persisted to prefetch-hints.json as Record<string, PrefetchHints> (keyed\n * by route pattern) and loaded at server startup.\n */\nexport type PrefetchHints = {\n /** Bitmask of PrefetchHint flags for this segment. */\n hints: number\n /** Child hint nodes, keyed by parallel route key. */\n slots: Record<string, PrefetchHints> | null\n}\n\nexport type ActionResult = Promise<any>\n\nexport type InitialRSCPayload = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initial transport data — the tree + head for hydration */\n t: FullTransportData\n /** missingSlots */\n m: Set<string> | undefined\n /** GlobalError */\n G: [React.ComponentType<any>, React.ReactNode | undefined]\n /** supportsPerSegmentPrefetching */\n S: boolean\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params, rather than the server folding them into each set.\n */\n r?: VaryParamsIterable\n /** staleTime in seconds - Only present when Cache Components is enabled. */\n s?: AsyncIterable<number>\n /**\n * runtimeDataAccessed — whether the render has accessed a data source that\n * hangs during a static prerender but would resolve during a runtime\n * prerender (cookies, headers, fallback params, searchParams, ...). The\n * flag is monotonic (false → true, at most once), so it's encoded as a\n * promise: resolved `true` at the moment of first access — the fulfillment\n * row's position in the stream records the stage the access happened in —\n * or resolved `false` when the prerender completes without one, a row that\n * lands past every stage boundary. A truncated (shell) decode therefore\n * reads the answer as of the shell stage: fulfilled `true` iff the access\n * happened during a stage it includes, pending (⇒ no access) otherwise.\n * Unlike an async iterable, a pending promise costs Flight no abort\n * listener on the render. Used when generating per-segment prefetch\n * responses (forwarded as each response's own `u`).\n * The build-time constant `PrefetchHint.ShouldAttemptStatic{Shell,Prefetch}`\n * hint is tracked separately.\n * Only present for static prerenders when Cache Components is enabled.\n */\n u?: Promise<boolean>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n/**\n * The fields shared by every navigation/prefetch response kind. Not used\n * directly — see NavigationFlightResponse (the general form) and the\n * per-context aliases DynamicNavigationFlightResponse and\n * PrefetchFlightResponse below. Fields that only apply to some response\n * kinds are optional.\n */\ntype NavigationFlightResponseBase = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /**\n * transport data — present iff the response carries a SPA payload.\n * Absent when the response renders nothing (see `n` for MPA navigations).\n *\n * In a per-segment prefetch response the tree is root-anchored with `d`\n * present on exactly the segments whose data is bundled into the response\n * (the requested segment and any ancestors inlined into it, per the\n * build-time prefetch hints); the remaining nodes — the spine above the\n * bundle, and segments with static prefetching disabled — carry identity\n * but no data. Every node carries the same hints the `/_tree` response\n * emits for it, so the tree decodes like any other transport tree. Data\n * nodes use the staged encodings: `p` is a promise and `s` is present\n * (see TransportSegmentData). The head (`h`) is present iff it's bundled\n * into the response: the standalone head response (whose tree is a bare\n * root identity), or a page response whose bundle accepted the head\n * (PrefetchHint.HeadInlinedIntoSelf).\n */\n t?: PartialTransportData\n /**\n * MPA navigation URL — present iff the client should hard-navigate to\n * this URL instead of applying a SPA payload. Reserved: no server path\n * emits it today (hard navigations are signaled by non-RSC content types\n * or a build-id mismatch), but the client honors it.\n */\n n?: string\n /** staleTime - Only present in live-render responses.\n * Per-segment prefetch responses carry staleTime per node instead (see\n * TransportSegmentData). */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n *\n * In a per-segment prefetch response this is the shell byte boundary the\n * client uses for the shell double-decode: re-decoding the buffered\n * response truncated at the offset yields the shell variant of every\n * segment (param-dependent content reduced to still-pending references).\n * `0` means no shell exists (the page wasn't produced by staged\n * rendering) — never a valid offset, so it doubles as the \"none\"\n * sentinel. The resolution row flushes past the boundary, so a truncated\n * shell decode reads it as pending, which is harmless. The client's\n * buffered read leans on the same fact from the other side: 0 read from\n * an unfulfilled `a` implies a bug — see the shell-extraction comment in\n * fetchAndWritePerSegmentPrefetchResponse (segment-cache/cache.ts).\n */\n a?: Promise<number | null>\n /**\n * needsRuntimeRequest — presence means the response carries a stage-scoped\n * runtime-data verdict. Per-segment prefetch responses always emit one,\n * and so does any prerendered page payload, which embeds the prerender's\n * runtime-data probe — that covers navigation responses served from\n * prerender output and the truncated initial payload alike. Live renders\n * emit none. Only per-segment responses additionally promise-encode the\n * head's partiality (see TransportSegmentData). The value is the page's\n * runtime-data-access flag (the page payload's own `u`; per-segment\n * responses forward it from the staged decode of the page data).\n * Fulfilled `true` means a runtime prefetch would return more\n * than this static response; pending or fulfilled `false` means it\n * wouldn't. Promise-encoded so the answer rewinds with a truncated\n * decode: the fulfillment row lands on the same side of the shell byte\n * boundary (`a`) as the access it records. Tracking is page-global, so it\n * lives on the response, not on each segment; per-segment granularity\n * comes from combining it with each segment's partiality:\n * needsRuntimeRequest(segment) = (settled true) && (isPartial pending).\n * The derived value must never falsely claim that no runtime request is\n * needed, so every fallback is conservative: pages that carry no `u`\n * (legacy render paths) forward an already-resolved `true`. Unlike the\n * build-constant prefetch hints, this is computed per render and may\n * change between responses for the same build — it reflects THIS\n * response.\n */\n u?: Promise<boolean>\n /**\n * shellUsedSessionData — present only in runtime-shell prefetch\n * responses: true if resolving session data unblocked new content in the\n * shell. Only meaningful where there's a proper session shell.\n * Promise-encoded so the answer rewinds with a truncated decode.\n * Currently has no client consumer; emitted for forward compatibility.\n */\n w?: Promise<boolean>\n /**\n * isUpgradeableISRFallback — present (true) iff this is a per-segment\n * prefetch response generated from a fallback shell render (i.e. the page\n * had not yet been prerendered with concrete params, so it was rendered\n * with `fallbackRouteParams`). The client uses this to schedule a retry,\n * since a more complete version may become available once the server's\n * background regeneration finishes.\n *\n * Note: this is distinct from per-segment partiality. A fully-prerendered\n * PPR page can have partial segments (dynamic holes filled by runtime\n * requests); those should not be retried. This flag specifically means a\n * more complete *static* version may become available.\n */\n f?: boolean\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params.\n */\n r?: VaryParamsIterable\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n/**\n * A live-render response: navigations, refreshes, runtime prefetches, and\n * dynamic route tree prefetches. Live renders always emit `S`, `q`, and `i`,\n * so they're required here — used at the sites that produce these responses\n * (app-render) and the decode sites that only ever receive them, so a\n * malformed response fails the type rather than being masked by a fallback.\n */\nexport type DynamicNavigationFlightResponse = NavigationFlightResponseBase & {\n /**\n * supportsPerSegmentPrefetching — whether per-segment prefetch responses\n * can be served for this route.\n */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\n/**\n * A per-segment prefetch response served from static storage: the `/_tree`\n * route tree prefetch and the per-segment responses generated by\n * collect-segment-data. Never carries `S` (implied by the response's\n * existence), `q` (search-agnostic; the client writes these responses into\n * the cache using the rendered search already recorded on the route tree\n * entry), or `i` (the client reads the Vary header instead). Structurally\n * the shared base — the alias marks the response kind at the sites that\n * produce and decode it.\n */\nexport type PrefetchFlightResponse = NavigationFlightResponseBase\n\n/**\n * The general form: a response that may be either kind, for the flows that\n * handle both (the `/_tree` fetch, which receives a live render when\n * per-segment prefetching is unsupported, and the shared cache-write path).\n * Both aliases above are assignable to it.\n */\nexport type NavigationFlightResponse = NavigationFlightResponseBase & {\n /**\n * supportsPerSegmentPrefetching — present in live-render responses;\n * absent in per-segment prefetch responses served from static storage\n * (where it's implied by the response's existence).\n */\n S?: boolean\n /**\n * renderedSearch — present in live-render responses; absent in\n * per-segment prefetch responses, which are search-agnostic (the client\n * writes them into the cache using the rendered search already recorded\n * on the route tree entry).\n */\n q?: string\n /**\n * couldBeIntercepted — present in live-render responses; absent in\n * per-segment prefetch responses (the client reads the Vary header\n * instead).\n */\n i?: boolean\n}\n\n// Response from `createFromFetch` for server actions.\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /**\n * transport data — present iff the action response re-rendered the page.\n * Absent when the action rendered nothing (see `n` for MPA navigations).\n */\n t?: PartialTransportData\n /**\n * MPA navigation URL — present iff the client should hard-navigate to\n * this URL instead of applying a SPA payload. Reserved: no server path\n * emits it today, but the client honors it.\n */\n n?: string\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n\nexport type 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","let deploymentId: string | undefined\n\nif (typeof window !== 'undefined') {\n deploymentId = document.documentElement.dataset.dplId\n // Immediately remove the attribute to prevent hydration errors (the dplId was inserted into the\n // HTML only), React isn't aware of it at all.\n document.documentElement.removeAttribute('data-dpl-id')\n} else {\n // Client side: replaced with globalThis.NEXT_DEPLOYMENT_ID\n // Server side: left as is or replaced with a string or replaced with false\n deploymentId = process.env.NEXT_DEPLOYMENT_ID || undefined\n}\n\nexport function getDeploymentId(): string | undefined {\n return deploymentId\n}\n\nexport function getDeploymentIdQuery(ampersand = false): string {\n let id = getDeploymentId()\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`\n }\n return ''\n}\n\nexport function getAssetToken(): string | undefined {\n return process.env.NEXT_SUPPORTS_IMMUTABLE_ASSETS\n ? undefined\n : process.env.NEXT_DEPLOYMENT_ID\n}\n\nexport function getAssetTokenQuery(ampersand = false): string {\n let id = getAssetToken()\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`\n }\n return ''\n}\n","// 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: string) {\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}\n\nexport function hexHash(str: string) {\n return djb2Hash(str).toString(36).slice(0, 5)\n}\n","export function createUnrenderedSegmentError(\n route: string,\n missingFiles: readonly string[]\n): Error {\n let message = `Route \"${route}\": Could not validate that a segment in your UI has instant navigation.`\n if (missingFiles.length > 0) {\n const label =\n missingFiles.length === 1 ? 'Dropped segment' : 'Dropped segments'\n message +=\n `\\n\\nThis segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.` +\n `\\n\\n${label}:\\n${missingFiles.map((p) => ` ${p}`).join('\\n')}` +\n `\\n\\nWays to fix this:` +\n `\\n - [render] Render the dropped segment` +\n `\\n - [ignore] Set \\`export const instant = false\\` to opt the dropped segment out of instant-navigation validation` +\n `\\n\\nLearn more: https://nextjs.org/docs/messages/instant-unrendered-segment`\n }\n return new Error(message)\n}\n\nexport function createLinkPrefetchPartialError(pathname: string): Error {\n return new Error(\n `Next.js encountered dynamic data during prefetching for \"${pathname}\".\\n\\n` +\n `This will lead to slower, more expensive prefetches.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [upgrade] Opt into Partial Prefetching by exporting \\`const prefetch = 'partial'\\` from the page or layout, or by setting \\`partialPrefetching: true\\` in next.config to opt the whole app in\\n` +\n ` - [disable] Remove \\`prefetch={true}\\` from the <Link> to use the default prefetch\\n` +\n ` - [ignore] Set \\`export const instant = false\\` to opt the route out of instant-navigation validation\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial`\n )\n}\n","/**\n * Check to see if a value is Thenable.\n *\n * @param promise the maybe-thenable value\n * @returns true if the value is thenable\n */\nexport function isThenable<T = unknown>(\n promise: Promise<T> | T\n): promise is Promise<T> {\n return (\n promise !== null &&\n typeof promise === 'object' &&\n 'then' in promise &&\n typeof promise.then === 'function'\n )\n}\n","/**\n * For a given page path, this function ensures that there is a leading slash.\n * If there is not a leading slash, one is added, otherwise it is noop.\n */\nexport function ensureLeadingSlash(path: string) {\n return path.startsWith('/') ? path : `/${path}`\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string) {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n","import { ensureLeadingSlash } from '../../page-path/ensure-leading-slash'\nimport { isGroupSegment } from '../../segment'\n\n/**\n * Normalizes an app route so it represents the actual request path. Essentially\n * performing the following transformations:\n *\n * - `/(dashboard)/user/[id]/page` to `/user/[id]`\n * - `/(dashboard)/account/page` to `/account`\n * - `/user/[id]/page` to `/user/[id]`\n * - `/account/page` to `/account`\n * - `/page` to `/`\n * - `/(dashboard)/user/[id]/route` to `/user/[id]`\n * - `/(dashboard)/account/route` to `/account`\n * - `/user/[id]/route` to `/user/[id]`\n * - `/account/route` to `/account`\n * - `/route` to `/`\n * - `/` to `/`\n *\n * @param route the app route to normalize\n * @returns the normalized pathname\n */\nexport function normalizeAppPath(route: string) {\n return ensureLeadingSlash(\n route.split('/').reduce((pathname, segment, index, segments) => {\n // Empty segments are ignored.\n if (!segment) {\n return pathname\n }\n\n // Groups are ignored.\n if (isGroupSegment(segment)) {\n return pathname\n }\n\n // Parallel segments are ignored.\n if (segment[0] === '@') {\n return pathname\n }\n\n // The last segment (if it's a leaf) should be ignored.\n if (\n (segment === 'page' || segment === 'route') &&\n index === segments.length - 1\n ) {\n return pathname\n }\n\n return `${pathname}/${segment}`\n }, '')\n )\n}\n\n/**\n * Comparator for sorting app paths so that parallel slot paths (containing\n * `/@`) come before the children/root page path. This keeps the direct\n * children/root page last so it can be selected as the canonical entry.\n *\n * Without this, route group prefixes like `(group)` (char code 0x28) sort\n * before `@` (0x40), causing the children page to sort first instead of last\n * and leading to a manifest mismatch / 404 in webpack dev mode.\n */\nexport function compareAppPaths(a: string, b: string): number {\n const aHasSlot = a.includes('/@')\n const bHasSlot = b.includes('/@')\n if (aHasSlot && !bHasSlot) return -1\n if (!aHasSlot && bHasSlot) return 1\n return a.localeCompare(b)\n}\n\nfunction normalizeAppPageEntryPathname(appPath: string): string {\n // Webpack app entries preserve escaped underscore segments as `%5F`, while\n // normalized request pathnames expose the decoded `_` segment.\n return normalizeAppPath(appPath).replace(/%5F/g, '_')\n}\n\n/**\n * Selects the app path that owns the compiled entry for a normalized route.\n * Catch-all normalization can add app paths from other routes, so only direct\n * paths are candidates. Among those, compareAppPaths deterministically prefers\n * the children/root page, or a stable slot when the route only has slots.\n */\nexport function selectAppPageEntry(\n pathname: string,\n appPaths: readonly string[],\n normalizePathname: (appPath: string) => string = normalizeAppPageEntryPathname\n): string {\n let entry: string | undefined\n\n for (const appPath of appPaths) {\n if (normalizePathname(appPath) !== pathname) continue\n\n if (entry === undefined || compareAppPaths(entry, appPath) < 0) {\n entry = appPath\n }\n }\n\n if (entry === undefined) {\n throw new Error(`Invariant: no direct app page entry found for ${pathname}`)\n }\n\n return entry\n}\n\n/**\n * Strips the `.rsc` extension if it's in the pathname.\n * Since this function is used on full urls it checks `?` for searchParams handling.\n */\nexport function normalizeRscURL(url: string) {\n return url.replace(\n /\\.rsc($|\\?)/,\n // $1 ensures `?` is preserved\n '$1'\n )\n}\n","import { hexHash } from '../../hash'\n\nconst CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12\nconst textEncoder = new TextEncoder()\n\nfunction encodeCacheBustingSearchParam(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i])\n }\n\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction normalizeCacheBustingInput(\n value: string | string[] | undefined\n): string {\n if (value === undefined) {\n return '0'\n }\n return Array.isArray(value) ? value.join(',') : value\n}\n\nfunction createCacheBustingSearchParamInput(\n prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): string | null {\n if (\n (prefetchHeader === undefined || prefetchHeader === '0') &&\n segmentPrefetchHeader === undefined &&\n stateTreeHeader === undefined &&\n nextUrlHeader === undefined\n ) {\n return null\n }\n\n return [\n prefetchHeader ?? '0',\n normalizeCacheBustingInput(segmentPrefetchHeader),\n normalizeCacheBustingInput(stateTreeHeader),\n normalizeCacheBustingInput(nextUrlHeader),\n ].join(',')\n}\n\nasync function computeCacheBustingSearchParamFromInput(\n input: string\n): Promise<string> {\n // Truncate SHA-256 to 96 bits to keep `_rsc` compact\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n textEncoder.encode(input)\n )\n return encodeCacheBustingSearchParam(\n new Uint8Array(digest).subarray(0, CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES)\n )\n}\n\nexport async function computeCacheBustingSearchParam(\n prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): Promise<string> {\n const input = createCacheBustingSearchParamInput(\n prefetchHeader,\n segmentPrefetchHeader,\n stateTreeHeader,\n nextUrlHeader\n )\n if (input === null) {\n return ''\n }\n\n return computeCacheBustingSearchParamFromInput(input)\n}\n\nexport function computeLegacyCacheBustingSearchParam(\n prefetchHeader: '1' | '2' | '3' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): string {\n const input = createCacheBustingSearchParamInput(\n prefetchHeader,\n segmentPrefetchHeader,\n stateTreeHeader,\n nextUrlHeader\n )\n if (input === null) {\n return ''\n }\n\n return hexHash(input)\n}\n","// Format function modified from nodejs\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { UrlObject } from 'url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport * as querystring from './querystring'\n\nconst slashedProtocols = /https?|ftp|gopher|file/\n\nexport function formatUrl(urlObj: UrlObject) {\n let { auth, hostname } = urlObj\n let protocol = urlObj.protocol || ''\n let pathname = urlObj.pathname || ''\n let hash = urlObj.hash || ''\n let query = urlObj.query || ''\n let host: string | false = false\n\n auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''\n\n if (urlObj.host) {\n host = auth + urlObj.host\n } else if (hostname) {\n host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname)\n if (urlObj.port) {\n host += ':' + urlObj.port\n }\n }\n\n if (query && typeof query === 'object') {\n query = String(querystring.urlQueryToSearchParams(query as ParsedUrlQuery))\n }\n\n let search = urlObj.search || (query && `?${query}`) || ''\n\n if (protocol && !protocol.endsWith(':')) protocol += ':'\n\n if (\n urlObj.slashes ||\n ((!protocol || slashedProtocols.test(protocol)) && host !== false)\n ) {\n host = '//' + (host || '')\n if (pathname && pathname[0] !== '/') pathname = '/' + pathname\n } else if (!host) {\n host = ''\n }\n\n if (hash && hash[0] !== '#') hash = '#' + hash\n if (search && search[0] !== '?') search = '?' + search\n\n pathname = pathname.replace(/[?#]/g, encodeURIComponent)\n search = search.replace('#', '%23')\n\n return `${protocol}${host}${pathname}${search}${hash}`\n}\n\nexport const urlObjectKeys = [\n 'auth',\n 'hash',\n 'host',\n 'hostname',\n 'href',\n 'path',\n 'pathname',\n 'port',\n 'protocol',\n 'query',\n 'search',\n 'slashes',\n]\n\nexport function formatWithValidation(url: UrlObject): string {\n if (process.env.NODE_ENV === 'development') {\n if (url !== null && typeof url === 'object') {\n Object.keys(url).forEach((key) => {\n if (!urlObjectKeys.includes(key)) {\n console.warn(\n `Unknown key passed via urlObject into url.format: ${key}`\n )\n }\n })\n }\n }\n\n return formatUrl(url)\n}\n","import { normalizeAppPath } from './app-paths'\n\n// order matters here, the first match will be used\nexport const INTERCEPTION_ROUTE_MARKERS = [\n '(..)(..)',\n '(.)',\n '(..)',\n '(...)',\n] as const\n\nexport type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]\n\nexport type MissingCanonicalInterceptionRoute = {\n interceptionRoute: string\n canonicalRoute: string\n}\n\ntype RoutePattern = {\n prefix: Array<string | null>\n minLength: number\n unbounded: boolean\n}\n\nfunction parseRoutePattern(route: string): RoutePattern {\n const segments = route.split('/').filter(Boolean)\n const tail = segments.at(-1)\n const isOptionalCatchAll =\n tail !== undefined && tail.startsWith('[[...') && tail.endsWith(']]')\n const isCatchAll =\n tail !== undefined && tail.startsWith('[...') && tail.endsWith(']')\n const unbounded = isOptionalCatchAll || isCatchAll\n const prefixSegments = unbounded ? segments.slice(0, -1) : segments\n\n return {\n prefix: prefixSegments.map((segment) =>\n segment.startsWith('[') && segment.endsWith(']') ? null : segment\n ),\n minLength:\n prefixSegments.length + (isCatchAll && !isOptionalCatchAll ? 1 : 0),\n unbounded,\n }\n}\n\nfunction acceptsLength(pattern: RoutePattern, length: number): boolean {\n return pattern.unbounded\n ? length >= pattern.minLength\n : length === pattern.minLength\n}\n\nfunction prefixCovers(\n canonical: RoutePattern,\n intercepted: RoutePattern\n): boolean {\n return canonical.prefix.every((canonicalSegment, index) => {\n if (canonicalSegment === null) return true\n\n const interceptedSegment = intercepted.prefix[index]\n return (\n interceptedSegment !== undefined &&\n interceptedSegment !== null &&\n canonicalSegment === interceptedSegment\n )\n })\n}\n\nfunction patternCoversAtLength(\n canonical: RoutePattern,\n intercepted: RoutePattern,\n length: number\n): boolean {\n return (\n acceptsLength(canonical, length) &&\n acceptsLength(intercepted, length) &&\n prefixCovers(canonical, intercepted)\n )\n}\n\n/** Returns whether ordinary route patterns cover every URL in `route`. */\nfunction isRoutePatternCovered(route: string, ordinaryRoutes: RoutePattern[]) {\n const intercepted = parseRoutePattern(route)\n\n if (!intercepted.unbounded) {\n return ordinaryRoutes.some((pattern) =>\n patternCoversAtLength(pattern, intercepted, intercepted.minLength)\n )\n }\n\n let unboundedCoverageStart = Infinity\n for (const pattern of ordinaryRoutes) {\n if (pattern.unbounded && prefixCovers(pattern, intercepted)) {\n unboundedCoverageStart = Math.min(\n unboundedCoverageStart,\n Math.max(intercepted.minLength, pattern.minLength)\n )\n }\n }\n\n if (unboundedCoverageStart === Infinity) return false\n\n // An optional or required catchall can have its shorter paths covered by\n // fixed routes before another catchall takes over the remaining suffix.\n for (\n let length = intercepted.minLength;\n length < unboundedCoverageStart;\n length++\n ) {\n if (\n !ordinaryRoutes.some((pattern) =>\n patternCoversAtLength(pattern, intercepted, length)\n )\n ) {\n return false\n }\n }\n\n return true\n}\n\nexport function isInterceptionRouteAppPath(path: string): boolean {\n // TODO-APP: add more serious validation\n return (\n path\n .split('/')\n .find((segment) =>\n INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n ) !== undefined\n )\n}\n\ntype InterceptionRouteInformation = {\n /**\n * The intercepting route. This is the route that is being intercepted or the\n * route that the user was coming from. This is matched by the Next-Url\n * header.\n */\n interceptingRoute: string\n\n /**\n * The intercepted route. This is the route that is being intercepted or the\n * route that the user is going to. This is matched by the request pathname.\n */\n interceptedRoute: string\n}\n\nexport function extractInterceptionRouteInformation(\n path: string\n): InterceptionRouteInformation {\n let interceptingRoute: string | undefined\n let marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined\n let interceptedRoute: string | undefined\n\n for (const segment of path.split('/')) {\n marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n if (marker) {\n ;[interceptingRoute, interceptedRoute] = path.split(marker, 2)\n break\n }\n }\n\n if (!interceptingRoute || !marker || !interceptedRoute) {\n throw new Error(\n `Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`\n )\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 new Error(\n `Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`\n )\n }\n interceptedRoute = interceptingRoute\n .split('/')\n .slice(0, -1)\n .concat(interceptedRoute)\n .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\n const splitInterceptingRoute = interceptingRoute.split('/')\n if (splitInterceptingRoute.length <= 2) {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`\n )\n }\n\n interceptedRoute = splitInterceptingRoute\n .slice(0, -2)\n .concat(interceptedRoute)\n .join('/')\n break\n default:\n throw new Error('Invariant: unexpected marker')\n }\n\n return { interceptingRoute, interceptedRoute }\n}\n\n/**\n * Finds interception matchers that cannot be loaded as an ordinary request.\n *\n * This must run after catch-all normalization and pruning so `appPaths`\n * contains the final matcher set rather than every possible matcher candidate.\n */\nexport function findMissingCanonicalInterceptionRoutes(\n appPaths: Record<string, string[]>\n): MissingCanonicalInterceptionRoute[] {\n const canonicalRoutes = Object.keys(appPaths).filter(\n (route) => !isInterceptionRouteAppPath(route)\n )\n const canonicalRoutePatterns = canonicalRoutes.map(parseRoutePattern)\n\n return Object.keys(appPaths)\n .filter(isInterceptionRouteAppPath)\n .map((interceptionRoute) => ({\n interceptionRoute,\n canonicalRoute:\n extractInterceptionRouteInformation(interceptionRoute).interceptedRoute,\n }))\n .filter(\n ({ canonicalRoute }) =>\n !isRoutePatternCovered(canonicalRoute, canonicalRoutePatterns)\n )\n .sort((a, b) => a.interceptionRoute.localeCompare(b.interceptionRoute))\n}\n","import { isAbsoluteUrl, getLocationOrigin } from '../../utils'\nimport { hasBasePath } from '../../../../client/has-base-path'\n\n/**\n * Detects whether a given url is routable by the Next.js router (browser only).\n */\nexport function isLocalURL(url: string): boolean {\n // prevent a hydration mismatch on href for url with anchor refs\n if (!isAbsoluteUrl(url)) return true\n try {\n // absolute urls can be local if they are on the same origin\n const locationOrigin = getLocationOrigin()\n const resolved = new URL(url, locationOrigin)\n return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)\n } catch (_) {\n return false\n }\n}\n","/**\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nexport function parsePath(path: string) {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery\n ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined)\n : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return { pathname: path, query: '', hash: '' }\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nexport function pathHasPrefix(path: string, prefix: string) {\n if (typeof path !== 'string') {\n return false\n }\n\n const { pathname } = parsePath(path)\n return pathname === prefix || pathname.startsWith(prefix + '/')\n}\n","import type { ParsedUrlQuery } from 'querystring'\n\nexport function getRenderedSearch(query: ParsedUrlQuery): string {\n // Inlined implementation of querystring.encode, which is not available in\n // the Edge runtime.\n const pairs = []\n for (const key in query) {\n const value = query[key]\n if (value == null) continue\n if (Array.isArray(value)) {\n for (const v of value) {\n pairs.push(\n `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`\n )\n }\n } else {\n pairs.push(\n `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`\n )\n }\n }\n\n // The result should match the format of a web URL's `search` property, since\n // this is the format that's stored in the App Router state.\n // TODO: We're a bit inconsistent about this. The x-nextjs-rewritten-query\n // header omits the leading question mark. Should refactor to always do\n // that instead.\n if (pairs.length === 0) {\n // If the search string is empty, return an empty string.\n return ''\n }\n // Prepend '?' to the search params string.\n return '?' + pairs.join('&')\n}\n\nexport function searchParamsToUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n const query: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n const existing = query[key]\n if (typeof existing === 'undefined') {\n query[key] = value\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n query[key] = [existing, value]\n }\n }\n return query\n}\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n if (typeof param === 'string') {\n return param\n }\n\n if (\n (typeof param === 'number' && !isNaN(param)) ||\n typeof param === 'boolean'\n ) {\n return String(param)\n } else {\n return ''\n }\n}\n\nexport function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, stringifyUrlQueryParam(item))\n }\n } else {\n searchParams.set(key, stringifyUrlQueryParam(value))\n }\n }\n return searchParams\n}\n\nexport function assign(\n target: URLSearchParams,\n ...searchParamsList: URLSearchParams[]\n): URLSearchParams {\n for (const searchParams of searchParamsList) {\n for (const key of searchParams.keys()) {\n target.delete(key)\n }\n\n for (const [key, value] of searchParams.entries()) {\n target.append(key, value)\n }\n }\n\n return target\n}\n","/**\n * Removes the trailing slash for a given route or page path. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n *\n * Uses charCodeAt (47 === '/') instead of regex to avoid the overhead of\n * compiling and executing a RegExp on every call (~3-5x faster).\n */\nexport function removeTrailingSlash(route: string) {\n return route.charCodeAt(route.length - 1) === 47 && route.length > 1\n ? route.slice(0, -1)\n : route\n}\n","import { PAGE_SEGMENT_KEY } from './segment'\n/**\n * The transport format for RSC responses.\n *\n * Every type in this module is prefixed with `Transport` to distinguish the\n * wire format from client-local types (`Segment`, `RouteTree`, `CacheNode`,\n * `FlightRouterState`). Client code converts out of Transport types at the\n * decode boundary and never stores them.\n *\n * A response carries a single tree, anchored at the root segment, where each\n * node has both its identity and (optionally) its render output. Partial\n * responses are expressed per node: the convention across the format is that\n * absence means \"nothing here\" — an omitted `d` means the segment was not\n * rendered as part of the response, an omitted slot key means the response\n * carries no information about that slot.\n */\n\nimport type React from 'react'\nimport type {\n DynamicParamTypesShort,\n FlightRouterState,\n Segment,\n} from './app-router-types'\nimport type { VaryParamsIterable } from './segment-cache/vary-params-decoding'\n\n/**\n * Segment identity on the wire. A string for static segments; an object for\n * dynamic (parameterized) segments.\n *\n * Page segments are always `__PAGE__`. The search params are sent separately,\n * in the response's `q` field.\n */\nexport type TransportSegment = string | TransportDynamicSegment\n\nexport type TransportDynamicSegment = {\n /** name — the param name, e.g. 'id' for [id] */\n n: string\n /** type — dynamic param type */\n t: DynamicParamTypesShort\n /**\n * key — the param value / cache key. null when the client is expected to\n * parse the value from the URL itself, which keeps the response cacheable\n * across param values.\n */\n k: string | null\n /** siblings — static sibling segments at this URL level; null = unknown */\n s: readonly string[] | null\n}\n\n/**\n * Render output for a single segment. Grouped into one object so a node's\n * \"rendered vs skipped\" state is a single presence check. Also used for the\n * head (metadata/viewport), which is output without structure.\n *\n * `r` may be null: the segment was skipped — the response acknowledges its\n * position without rendering anything for it, e.g. a shared layout the\n * client is expected to already have. This is distinct from `d` being absent\n * on the node, which means the response makes no claim about the segment's\n * output at all (the client should fetch it lazily if it doesn't have it).\n */\nexport type TransportSegmentData = {\n /** rsc — the React node for this segment; null = skipped (not rendered) */\n r: React.ReactNode\n /**\n * isPartial — whether anything in the segment's output is not fully\n * resolved: dynamic holes, runtime holes, anything suspended.\n *\n * Navigation responses carry a plain boolean, known at render time. It is\n * a render-wide constant (isPossiblyPartialResponse in\n * create-component-tree.tsx), identical on every node and only\n * conservatively accurate, so the client resolves a boolean-form node's\n * actual partiality from the response-level signal instead (see\n * decodeTransportNode).\n *\n * Per-segment prefetch responses carry the rewindable promise encoding\n * instead: fulfilled = complete, pending forever = partial. Partiality is\n * only discovered there by probing the buffered prerender (a partial\n * segment's probe never resolves, the same way Flight encodes the holes\n * themselves), and the encoding must survive the client's shell\n * double-decode — the response buffer is decoded a second time truncated\n * at the shell byte boundary (`a`), and a fulfillment row that landed past\n * the boundary must read as \"partial\" in that decode. The promise form is\n * only ever read off a fully-buffered decode's thenable status.\n */\n p: boolean | Promise<void>\n /**\n * varyParams — an iterable of the route params this segment's output\n * depends on (one name per yield, deduped). Used by the client router to\n * determine cache key specificity: segments that only access certain\n * params can be reused across navigations where unaccessed params change.\n *\n * Does NOT include root params; those are emitted once at the response\n * level (`r` on the response wrapper) and unioned in by the consumer.\n *\n * - null: tracking was not enabled for this render (e.g., not a\n * prerender). Treat conservatively — assume all params vary.\n * - Drains to empty: segment accesses no params (e.g., client components,\n * or server components that don't read params). Can be shared across\n * all param values.\n * - Drains to non-empty: segment depends on those params. Can only be\n * reused when those specific params match.\n */\n v: VaryParamsIterable | null\n /**\n * staleTime in seconds — present only in per-segment prefetch responses,\n * where staleness is tracked per node. Navigation responses carry\n * staleness at the response level instead (the wrapper's `s` iterable or\n * the Next-Router-Stale-Time header).\n *\n * An async iterable rather than a plain number because the final value is\n * only known late in the stream, and the iterable form survives a\n * truncated/rewound shell decode (read via thenable status from the\n * buffered response). The client takes the last yielded value.\n */\n s?: AsyncIterable<number>\n}\n\n/**\n * Structure of a segment node, independent of whether render output\n * is attached. Shared by both response variants.\n */\ntype TransportNodeShape = {\n /** segment — identity */\n s: TransportSegment\n /** hints — PrefetchHint bitmask; omitted when zero or unknown */\n h?: number\n}\n\n/**\n * A node in a FULL response tree: every node carries data, and slot maps are\n * exhaustive. Produced by full renders: the initial document payload and\n * error payloads. \"Full\" means the response accounts for every node — there\n * is nothing for the client to fetch lazily. Data-level holes\n * (`d.p === true`) and skipped nodes (`d.r === null`) are still possible.\n */\nexport type FullTransportNode = TransportNodeShape & {\n /** data — always present in a full tree */\n d: TransportSegmentData\n /**\n * children — parallel routes; omitted for leaf segments. A Map rather\n * than a plain object because slot names are app-defined; with a plain\n * object, every distinct combination of slot names creates a different\n * hidden class, making keyed access megamorphic.\n */\n c?: Map<string, FullTransportNode>\n}\n\n/**\n * A node in a PARTIAL response tree: produced by navigations, refreshes, and\n * actions — anywhere the server diffs against client state or renders a\n * subset of the route.\n *\n * The client treats the response as an overlay over its current tree:\n *\n * - A node present in the tree is authoritative for that position's identity.\n * - `d` present: the response accounts for this segment. Its output is `d.r`,\n * which may be null when the segment was skipped — not rendered because\n * the client already has it (e.g. a shared layout).\n * - `d` omitted: the response makes no claim about this segment's output.\n * The client keeps what it has, or lazily fetches when it renders (e.g.\n * segments beneath a loading boundary in a non-PPR prefetch).\n * - A slot key omitted from `c` (or `c` omitted): on a skipped node\n * (`d.r === null`), the response carries no information about that slot\n * and the client keeps its subtree untouched. On any other node the\n * subtree is authoritative, so an omitted slot is simply absent.\n * - `h` omitted: on a skipped node, the client keeps its existing hints for\n * the segment; on any other node it means the hints are zero.\n *\n * The client's cache write descends through nodes with `d` omitted (see\n * writeTreeDataIntoCache), so data may appear at any depth below a no-claim\n * node — the identity spine of a per-segment prefetch response is the\n * canonical producer of that shape.\n */\nexport type PartialTransportNode = TransportNodeShape & {\n /** data — omitted when this segment was not rendered in this response */\n d?: TransportSegmentData\n /** children — omitted field or key = no information about those slots */\n c?: Map<string, PartialTransportNode>\n}\n\n/**\n * Shared type for code that walks either variant. Note: FullTransportNode is\n * structurally assignable to PartialTransportNode, so this union collapses\n * to PartialTransportNode for the type checker; the union spelling\n * documents intent.\n */\nexport type TransportNode = FullTransportNode | PartialTransportNode\n\n/**\n * The tree + head bundle of a response.\n */\nexport type FullTransportData = {\n /** tree */\n t: FullTransportNode\n /** head — always present and complete in a full response */\n h: TransportSegmentData\n}\n\nexport type PartialTransportData = {\n t: PartialTransportNode\n /** omitted = this response carries no head (e.g. router-state-only responses) */\n h?: TransportSegmentData\n}\n\nexport type TransportData = FullTransportData | PartialTransportData\n\n/**\n * Creates the data for a skipped segment: a null `r` marks the position as\n * acknowledged by the response, with no output attached (see the note on\n * TransportSegmentData). Used by producers for the segments along the path\n * from the root down to the rendered subtrees.\n */\nexport function createSkippedSegmentData(): TransportSegmentData {\n return { r: null, p: true, v: null }\n}\n\n/**\n * Reads a late-resolving value from a fully-buffered Flight decode via the\n * thenable's status. Flight sets `status`/`value` on a row's promise once\n * its bytes are processed, and a buffered decode processes every byte\n * synchronously, so any row that made it into the payload is readable\n * without awaiting. Returns `unresolvedValue` for a row that is pending or\n * absent in this decode — e.g. one whose fulfillment landed past a\n * truncated shell decode's boundary; that's what scopes a response's\n * late-resolving signals to the payload being decoded. Returns\n * `rejectedValue` (defaults to `unresolvedValue`) for a rejected row — an\n * aborted render errors rows that were still pending when it happened.\n *\n * Shared by client and server: the client reads buffered prefetch\n * responses; the server (collect-segment-data) reads the buffered page\n * payload it re-serializes into per-segment responses.\n */\nexport function readFulfilledValue<T, TFallback>(\n valueFromServer: PromiseLike<T>,\n unresolvedValue: TFallback,\n rejectedValue: T | TFallback = unresolvedValue\n): T | TFallback {\n const thenable = valueFromServer as PromiseLike<T> & {\n status?: string\n value?: T\n }\n // Force Flight to unwrap a received-but-not-yet-settled row.\n thenable.then(noop, noop)\n switch (thenable.status) {\n case 'fulfilled':\n return thenable.value as T\n case 'rejected':\n return rejectedValue\n // No status yet: the row is still pending, or absent from this decode.\n case undefined:\n default:\n return unresolvedValue\n }\n}\n\nconst noop = () => {}\n\n/**\n * Converts a segment's client/server-internal representation to its wire\n * representation.\n */\nexport function segmentToTransportSegment(segment: Segment): TransportSegment {\n if (typeof segment === 'string') {\n return segment\n }\n return {\n n: segment[0],\n t: segment[2],\n k: segment[1],\n s: segment[3],\n }\n}\n\n/**\n * Converts a segment's wire representation to the client/server-internal\n * `Segment` type.\n */\nexport function transportSegmentToSegment(\n transportSegment: TransportSegment\n): Segment {\n if (typeof transportSegment === 'string') {\n return transportSegment\n }\n return [\n transportSegment.n,\n // `k` may be null when the client is expected to parse the param value\n // from the URL (per-segment prefetch responses). Callers that need the\n // real value resolve it from the rendered pathname instead of using this\n // function (see resolveTransportSegment in decode-server-response); the\n // remaining callers are value-insensitive (segment request keys, which\n // never include param values) or only see concrete keys.\n transportSegment.k ?? '',\n transportSegment.t,\n transportSegment.s,\n ]\n}\n\n/**\n * Derives a FlightRouterState from a transport tree. Used where the client\n * needs a router-state representation of a full response (e.g. the initial\n * hydration payload). Render output (`d`) is not carried over.\n */\nexport function transportNodeToFlightRouterState(\n node: TransportNode,\n renderedSearch: string\n): FlightRouterState {\n const parallelRoutes: Record<string, FlightRouterState> = {}\n const children = node.c\n if (children !== undefined) {\n for (const [parallelRouteKey, childNode] of children) {\n parallelRoutes[parallelRouteKey] = transportNodeToFlightRouterState(\n childNode,\n renderedSearch\n )\n }\n }\n const flightRouterState: FlightRouterState = [\n transportSegmentToSegment(node.s),\n parallelRoutes,\n ]\n if (node.h !== undefined) {\n flightRouterState[4] = node.h\n }\n if (flightRouterState[0] === PAGE_SEGMENT_KEY) {\n flightRouterState[5] = renderedSearch\n }\n return flightRouterState\n}\n","import type { Segment as FlightRouterStateSegment } from '../app-router-types'\n\n// TypeScript trick to simulate opaque types, like in Flow.\ntype Opaque<K, T> = T & { __brand: K }\n\nexport type SegmentRequestKeyPart = Opaque<'SegmentRequestKeyPart', string>\nexport type SegmentRequestKey = Opaque<'SegmentRequestKey', string>\n\nexport const ROOT_SEGMENT_REQUEST_KEY = '' as SegmentRequestKey\n\nexport const HEAD_REQUEST_KEY = '/_head' as SegmentRequestKey\n\nexport function createSegmentRequestKeyPart(\n segment: FlightRouterStateSegment\n): SegmentRequestKeyPart {\n if (typeof segment === 'string') {\n const safeName =\n // 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'\n ? '_not-found'\n : 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 as SegmentRequestKeyPart\n }\n\n const name = segment[0]\n const paramType = segment[2]\n const safeName = encodeToFilesystemAndURLSafeString(name)\n\n const encodedName = '$' + paramType + '$' + safeName\n return encodedName as SegmentRequestKeyPart\n}\n\nexport function appendSegmentRequestKeyPart(\n parentRequestKey: SegmentRequestKey,\n parallelRouteKey: string,\n childRequestKeyPart: SegmentRequestKeyPart\n): SegmentRequestKey {\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\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 =\n parallelRouteKey === 'children'\n ? childRequestKeyPart\n : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childRequestKeyPart}`\n return (parentRequestKey + '/' + slotKey) as SegmentRequestKey\n}\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\\-_@]+$/\n\nfunction encodeToFilesystemAndURLSafeString(value: string) {\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)\n .replace(/\\+/g, '-') // Replace '+' with '-'\n .replace(/\\//g, '_') // Replace '/' with '_'\n .replace(/=+$/, '') // Remove trailing '='\n return '!' + base64url\n}\n\nexport function convertSegmentPathToStaticExportFilename(\n segmentPath: string\n): string {\n return `__next${segmentPath.replace(/\\//g, '.')}.txt`\n}\n","/**\n * Vary Params Decoding\n *\n * This module is shared between server and client.\n */\n\nimport { readFulfilledValue } from '../rsc-transport'\n\n/**\n * The vary path id for search params. Path params are identified by their\n * name. Search params don't have a fixed set of names, so any access to them\n * is reported under this one id, and the segment is keyed by the whole search\n * string (see createVaryingSearchParams in app-render/vary-params.ts).\n *\n * It's a number so it can't collide with a param name. `app/[?]/page.tsx` is a\n * valid route.\n */\nexport const SEARCH_PARAMS_VARY_ID = 0\n\n// Path param names, and SEARCH_PARAMS_VARY_ID for the search params.\nexport type VaryParamId = string | number\n\n/**\n * The params a piece of rendered output depends on — the ids of the vary path\n * nodes it read: path param names, and SEARCH_PARAMS_VARY_ID for the search\n * params — as the source that reports them rather than a snapshot of it.\n *\n * The wire iterables can only be drained from a fully-buffered response; they\n * are drained once at decode into an already-settled thenable, and read at the\n * point a decision needs the set (readVaryParams).\n */\nexport type VaryParams = PromiseLike<Set<VaryParamId>>\n\n/**\n * Vary params are serialized into the Flight stream as an\n * `AsyncIterable<VaryParamId>` that yields each accessed param id exactly once\n * (the server dedupes before emitting). Because each access is flushed into the\n * stream as it happens, there's no step at the end of the render that has to\n * run for the client to read anything. If a prerender is aborted by sync I/O,\n * the params yielded before the abort are already in the stream, and they're\n * exactly the params the partial response actually depends on.\n *\n * Root params are NOT included in a segment's own iterable. They're emitted\n * once at the top level of the response (as a separate iterable) and unioned in\n * by `decodeVaryParams`, because root params can be accessed at any point\n * during the render — folding them into every segment would otherwise require\n * a merge once the whole render is complete.\n */\nexport type VaryParamsIterable = AsyncIterable<VaryParamId>\n\n/**\n * Synchronously drains a vary params `AsyncIterable`, adding each yielded name\n * to `target`.\n *\n * By the time this runs (on the client, or in collectSegmentData), the Flight\n * stream has been fully buffered, so every yielded value is already\n * materialized and can be read without awaiting: each iterator result is a\n * Flight chunk whose settled state `readFulfilledValue` reads off the\n * thenable's status.\n *\n * We add \"every param yielded up to the point the stream suspends\": a\n * normally-closed iterable drains fully, while one left hanging (a sync-I/O\n * abort, or a `close()` whose row hasn't flushed yet) drains to the prefix\n * already in the stream. Both are correct — a segment's param accesses are all\n * flushed as they happen during its render, so the prefix is exactly the set\n * the response depends on. We therefore never need the terminating `done` row\n * to be present; it's only stream hygiene.\n */\nfunction drainVaryParams(\n iterable: VaryParamsIterable,\n target: Set<VaryParamId>\n): void {\n const iterator = iterable[Symbol.asyncIterator]()\n while (true) {\n const step = readFulfilledValue(iterator.next(), undefined)\n if (step === undefined || step.done) {\n // Either the stream suspended here — everything yielded before this\n // point has already been added — or the iterable finished cleanly.\n return\n }\n target.add(step.value)\n }\n}\n\n/**\n * Converts a segment's (or the head's) vary params off the wire, at the\n * decode boundary, unioning in the response-level root params.\n *\n * Root params are emitted once at the top level rather than folded into every\n * segment by the server, so every decode recombines them here — building the\n * merge into the decode means a caller can't forget it, and it's done in a\n * single pass with no intermediate set.\n *\n * Returns null (\"unknown\", key on all params) unless BOTH iterables are\n * present. A null/absent `iterable` means the segment's own tracking wasn't\n * enabled (e.g. not a prerender). A null/absent `rootIterable` means root\n * params weren't tracked — and since a segment's own iterable never includes\n * root params (those are accessed in layouts above it), narrowing on the\n * segment set alone would wrongly assume no root params were accessed. In\n * either case we stay conservative.\n *\n * When both are present each is authoritative even when it drains to the empty\n * set — a tracked segment that read no params, with no root params accessed,\n * can be shared across all param values.\n */\nexport function decodeVaryParams(\n iterable: VaryParamsIterable | null | undefined,\n rootIterable: VaryParamsIterable | null | undefined\n): VaryParams | null {\n if (\n iterable === null ||\n iterable === undefined ||\n rootIterable === null ||\n rootIterable === undefined\n ) {\n return null\n }\n const total: Set<VaryParamId> = new Set()\n drainVaryParams(iterable, total)\n drainVaryParams(rootIterable, total)\n return createVaryParams(total)\n}\n\n/**\n * Wraps an already-known set as a vary params source. Shaped like a settled\n * Flight promise so readVaryParams can read it off the thenable's status.\n */\nexport function createVaryParams(total: Set<VaryParamId>): VaryParams {\n // TODO: Don't need to use a native promise. Just inline a thenable that\n // immediately calls its listener.\n const settled = Promise.resolve(total) as Promise<Set<VaryParamId>> & {\n status: 'fulfilled'\n value: Set<VaryParamId>\n }\n settled.status = 'fulfilled'\n settled.value = total\n return settled\n}\n\n/**\n * Reads the set from a vary params source. Null when it is not available;\n * the reader assumes every param varies.\n */\nexport function readVaryParams(\n varyParams: VaryParams\n): Set<VaryParamId> | null {\n return readFulfilledValue(varyParams, null)\n}\n","import type { HtmlProps } from './html-context.shared-runtime'\nimport type { ComponentType, JSX } from 'react'\nimport type { DomainLocale } from '../../server/config'\nimport type { Env } from '@next/env'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextRouter } from './router/router'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { PreviewData } from '../../types'\nimport type { COMPILER_NAMES } from './constants'\nimport type fs from 'fs'\n\nexport type NextComponentType<\n Context extends BaseContext = NextPageContext,\n InitialProps = {},\n Props = {},\n> = ComponentType<Props> & {\n /**\n * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.\n * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.\n * @param context Context of `page`\n */\n getInitialProps?(context: Context): InitialProps | Promise<InitialProps>\n}\n\nexport type DocumentType = NextComponentType<\n DocumentContext,\n DocumentInitialProps,\n DocumentProps\n>\n\nexport type AppType<P = {}> = NextComponentType<\n AppContextType,\n P,\n AppPropsType<any, P>\n>\n\nexport type AppTreeType = ComponentType<\n AppInitialProps & { [name: string]: any }\n>\n\n/**\n * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.\n * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting\n */\nexport const WEB_VITALS = ['CLS', 'FCP', 'INP', 'LCP', 'TTFB'] as const\nexport type NextWebVitalsMetric = {\n id: string\n startTime: number\n value: number\n attribution?: { [key: string]: unknown }\n} & (\n | {\n label: 'web-vital'\n name: (typeof WEB_VITALS)[number]\n }\n | {\n label: 'custom'\n name:\n | 'Next.js-hydration'\n | 'Next.js-route-change-to-render'\n | 'Next.js-render'\n }\n)\n\nexport type Enhancer<C> = (Component: C) => C\n\nexport type ComponentsEnhancer =\n | {\n enhanceApp?: Enhancer<AppType>\n enhanceComponent?: Enhancer<NextComponentType>\n }\n | Enhancer<NextComponentType>\n\nexport type RenderPageResult = {\n html: string\n head?: Array<JSX.Element | null>\n}\n\nexport type RenderPage = (\n options?: ComponentsEnhancer\n) => DocumentInitialProps | Promise<DocumentInitialProps>\n\nexport type BaseContext = {\n res?: ServerResponse\n [k: string]: any\n}\n\nexport type NEXT_DATA = {\n props: Record<string, any>\n page: string\n query: ParsedUrlQuery\n buildId: string\n assetPrefix?: string\n nextExport?: boolean\n autoExport?: boolean\n isFallback?: boolean\n isExperimentalCompile?: boolean\n dynamicIds?: (string | number)[]\n err?: Error & {\n statusCode?: number\n source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n }\n gsp?: boolean\n gssp?: boolean\n customServer?: boolean\n gip?: boolean\n appGip?: boolean\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n scriptLoader?: any[]\n isPreview?: boolean\n notFoundSrcPage?: string\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n /**\n * Error object if encountered during rendering\n */\n err?: (Error & { statusCode?: number }) | null\n /**\n * `HTTP` request object.\n */\n req?: IncomingMessage\n /**\n * `HTTP` response object.\n */\n res?: ServerResponse\n /**\n * Path section of `URL`.\n */\n pathname: string\n /**\n * Query string section of `URL` parsed as an object.\n */\n query: ParsedUrlQuery\n /**\n * `String` of the actual path including query.\n */\n asPath?: string\n /**\n * The currently active locale\n */\n locale?: string\n /**\n * All configured locales\n */\n locales?: readonly string[]\n /**\n * The configured default locale\n */\n defaultLocale?: string\n /**\n * `Component` the tree of the App to use if needing to render separately\n */\n AppTree: AppTreeType\n}\n\nexport type AppContextType<Router extends NextRouter = NextRouter> = {\n Component: NextComponentType<NextPageContext>\n AppTree: AppTreeType\n ctx: NextPageContext\n router: Router\n}\n\nexport type AppInitialProps<PageProps = any> = {\n pageProps: PageProps\n}\n\nexport type AppPropsType<\n Router extends NextRouter = NextRouter,\n PageProps = {},\n> = AppInitialProps<PageProps> & {\n Component: NextComponentType<NextPageContext, any, any>\n router: Router\n __N_SSG?: boolean\n __N_SSP?: boolean\n}\n\nexport type DocumentContext = NextPageContext & {\n renderPage: RenderPage\n defaultGetInitialProps(\n ctx: DocumentContext,\n options?: { nonce?: string }\n ): Promise<DocumentInitialProps>\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n styles?: React.ReactElement[] | Iterable<React.ReactNode> | JSX.Element\n}\n\nexport type DocumentProps = DocumentInitialProps & HtmlProps\n\n/**\n * Next `API` route request\n */\nexport interface NextApiRequest extends IncomingMessage {\n /**\n * Object of `query` values from url\n */\n query: Partial<{\n [key: string]: string | string[]\n }>\n /**\n * Object of `cookies` from header\n */\n cookies: Partial<{\n [key: string]: string\n }>\n\n body: any\n\n env: Env\n\n draftMode?: boolean\n\n preview?: boolean\n /**\n * Preview data set on the request, if any\n * */\n previewData?: PreviewData\n}\n\n/**\n * Send body of response\n */\ntype Send<T> = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse<Data = any> = ServerResponse & {\n /**\n * Send data `any` data in response\n */\n send: Send<Data>\n /**\n * Send data `json` data in response\n */\n json: Send<Data>\n status: (statusCode: number) => NextApiResponse<Data>\n redirect(url: string): NextApiResponse<Data>\n redirect(status: number, url: string): NextApiResponse<Data>\n\n /**\n * Set draft mode\n */\n setDraftMode: (options: { enable: boolean }) => NextApiResponse<Data>\n\n /**\n * Set preview data for Next.js' prerender mode\n */\n setPreviewData: (\n data: object | string,\n options?: {\n /**\n * Specifies the number (in seconds) for the preview session to last for.\n * The given number will be converted to an integer by rounding down.\n * By default, no maximum age is set and the preview session finishes\n * when the client shuts down (browser is closed).\n */\n maxAge?: number\n /**\n * Specifies the path for the preview session to work under. By default,\n * the path is considered the \"default path\", i.e., any pages under \"/\".\n */\n path?: string\n }\n ) => NextApiResponse<Data>\n\n /**\n * Clear preview data for Next.js' prerender mode\n */\n clearPreviewData: (options?: { path?: string }) => NextApiResponse<Data>\n\n /**\n * Revalidate a specific page and regenerate it using On-Demand Incremental\n * Static Regeneration.\n * The path should be an actual path, not a rewritten path. E.g. for\n * \"/blog/[slug]\" this should be \"/blog/post-1\".\n * @link https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation-with-revalidatepath\n */\n revalidate: (\n urlPath: string,\n opts?: {\n unstable_onlyGenerated?: boolean\n }\n ) => Promise<void>\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler<T = any> = (\n req: NextApiRequest,\n res: NextApiResponse<T>\n) => unknown | Promise<unknown>\n\n/**\n * Utils\n */\nexport function execOnce<T extends (...args: any[]) => ReturnType<T>>(\n fn: T\n): T {\n let used = false\n let result: ReturnType<T>\n\n return ((...args: any[]) => {\n if (!used) {\n used = true\n result = fn(...args)\n }\n return result\n }) as T\n}\n\n// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1\n// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\nconst ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\\d+\\-.]*?:/\nexport const isAbsoluteUrl = (url: string) => {\n // Fast path: an absolute URL must start with a letter (the scheme).\n // Check for a-z and A-Z without the cost of the regex.\n const c = url.charCodeAt(0)\n const isLetter =\n (c >= 65 /* A */ && c <= 90) /* Z */ ||\n (c >= 97 /* a */ && c <= 122) /* z */\n if (!isLetter) {\n return false\n }\n\n return ABSOLUTE_URL_REGEX.test(url)\n}\n\nexport function getLocationOrigin() {\n const { protocol, hostname, port } = window.location\n return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n const { href } = window.location\n const origin = getLocationOrigin()\n return href.substring(origin.length)\n}\n\nexport function getDisplayName<P>(Component: ComponentType<P>) {\n return typeof Component === 'string'\n ? Component\n : Component.displayName || Component.name || 'Unknown'\n}\n\nexport function isResSent(res: ServerResponse) {\n return res.finished || res.headersSent\n}\n\nexport function normalizeRepeatedSlashes(url: string) {\n const urlParts = url.split('?')\n const urlNoQuery = urlParts[0]\n\n return (\n urlNoQuery\n // first we replace any non-encoded backslashes with forward\n // then normalize repeated forward slashes\n .replace(/\\\\/g, '/')\n .replace(/\\/\\/+/g, '/') +\n (urlParts[1] ? `?${urlParts.slice(1).join('?')}` : '')\n )\n}\n\nexport async function loadGetInitialProps<\n C extends BaseContext,\n IP = {},\n P = {},\n>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {\n if (process.env.NODE_ENV !== 'production') {\n if (App.prototype?.getInitialProps) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.`\n throw new Error(message)\n }\n }\n // when called from _app `ctx` is nested in `ctx`\n const res = ctx.res || (ctx.ctx && ctx.ctx.res)\n\n if (!App.getInitialProps) {\n if (ctx.ctx && ctx.Component) {\n // @ts-ignore pageProps default\n return {\n pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx),\n }\n }\n return {} as IP\n }\n\n const props = await App.getInitialProps(ctx)\n\n if (res && isResSent(res)) {\n return props\n }\n\n if (!props) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" should resolve to an object. But found \"${props}\" instead.`\n throw new Error(message)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (Object.keys(props).length === 0 && !ctx.ctx) {\n console.warn(\n `${getDisplayName(\n App\n )} returned an empty object from \\`getInitialProps\\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps`\n )\n }\n }\n\n return props\n}\n\nexport const SP = typeof performance !== 'undefined'\nexport const ST =\n SP &&\n (['mark', 'measure', 'getEntriesByName'] as const).every(\n (method) => typeof performance[method] === 'function'\n )\n\nexport class DecodeError extends Error {}\nexport class NormalizeError extends Error {}\nexport class PageNotFoundError extends Error {\n code: string\n\n constructor(page: string) {\n super()\n this.code = 'ENOENT'\n this.name = 'PageNotFoundError'\n this.message = `Cannot find module for page: ${page}`\n }\n}\n\nexport class MissingStaticPage extends Error {\n constructor(page: string, message: string) {\n super()\n this.message = `Failed to load static file for page: ${page} ${message}`\n }\n}\n\nexport class MiddlewareNotFoundError extends Error {\n code: string\n constructor() {\n super()\n this.code = 'ENOENT'\n this.message = `Cannot find the middleware module`\n }\n}\n\nexport interface CacheFs {\n existsSync: typeof fs.existsSync\n readFile: typeof fs.promises.readFile\n readFileSync: typeof fs.readFileSync\n writeFile(f: string, d: any): Promise<void>\n /** Publish a complete file without replacing an existing destination. */\n writeFileAtomic?(f: string, d: any): Promise<boolean>\n mkdir(dir: string): Promise<void | string>\n stat(f: string): Promise<{ mtime: Date }>\n}\n\nexport function stringifyError(error: Error) {\n return JSON.stringify({ message: error.message, stack: error.stack })\n}\n"],"names":["addBasePath","basePath","process","env","__NEXT_ROUTER_BASEPATH","path","required","normalizePathTrailingSlash","__NEXT_MANUAL_CLIENT_BASE_PATH","addPathPrefix","callServer","LinkComponent","useLinkStatus","isModifiedEvent","event","eventTarget","currentTarget","target","getAttribute","metaKey","ctrlKey","shiftKey","altKey","nativeEvent","which","linkClicked","e","href","linkInstanceRef","replace","scroll","onNavigate","transitionTypes","prefetchIntent","window","nodeName","isAnchorNodeName","toUpperCase","hasAttribute","isLocalURL","preventDefault","location","isDefaultPrevented","navigate","require","ScrollBehavior","NoScroll","Default","current","formatStringOrUrl","urlObjOrString","formatUrl","props","linkStatus","setOptimisticLinkStatus","useOptimistic","IDLE_LINK_STATUS","children","useRef","hrefProp","as","asProp","childrenProp","prefetch","prefetchProp","passHref","shallow","onClick","onMouseEnter","onMouseEnterProp","onTouchStart","onTouchStartProp","legacyBehavior","ref","forwardedRef","unstable_dynamicOnHover","restProps","a","router","React","useContext","AppRouterContext","prefetchEnabled","fetchStrategy","getFetchStrategyFromPrefetchIntent","FetchStrategy","PPR","NODE_ENV","createPropError","args","Error","key","expected","actual","requiredPropsGuard","requiredProps","Object","keys","forEach","_","optionalPropsGuard","optionalProps","valType","Array","isArray","resolvedHref","formattedHref","warnOnce","locale","pathname","hasDynamicSegment","split","some","segment","startsWith","endsWith","child","$$typeof","Symbol","for","console","warn","Children","only","err","type","childRef","ownerStack","__NEXT_CACHE_COMPONENTS","useMemo","Full","captureOwnerStack","undefined","observeLinkVisibilityOnMount","useCallback","element","mountLinkInstance","unmountLinkForCurrentNavigation","unmountPrefetchableInstance","mergedRef","useMergedRef","childProps","defaultPrevented","upgradeToDynamicPrefetch","onNavigationIntent","__NEXT_LINK_NO_TOUCH_START","isAbsoluteUrl","link","errorOnce","cloneElement","LinkStatusContext","Provider","value","createContext","findSourceMapURL","__NEXT_DEV_SERVER","filename","document","origin","includes","url","URL","searchParams","set","ACTION_HEADER","FLIGHT_HEADERS","NEXT_ACTION_NOT_FOUND_HEADER","NEXT_ACTION_REVALIDATED_HEADER","NEXT_DID_POSTPONE_HEADER","NEXT_HMR_REFRESH_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_INSTANT_TEST_COOKIE","NEXT_IS_PRERENDER_HEADER","NEXT_REQUEST_ID_HEADER","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_ROUTER_STALE_TIME_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_RSC_UNION_QUERY","NEXT_URL","RSC_CONTENT_TYPE_HEADER","RSC_HEADER","completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","navigateToKnownRoute","state","currentUrl","currentRenderedSearch","currentRoot","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","beginLockedNavigation","ensurePrefetchThenNavigate","navigateImpl","segmentCacheMap","map","now","Date","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","getLinkForCurrentNavigation","root","tree","prefetchHints","PrefetchHint","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","createLinkPrefetchPartialError","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","navigation","startPPRNavigation","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","renderedSearch","hash","prefetchSeed","computeDynamicStaleAt","UnknownDynamicStaleTime","treeDivergedFromBase","DynamicRequestTreeForEntireRoute","dynamicRequestTree","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","transportData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","isResponsePartial","staticStageResponse","runtimePrefetchStream","responseHeaders","createNavigationSeed","discoverKnownRoute","search","createHrefFromUrl","spawnStaticStageCacheWrite","writeRuntimePrefetchStreamIntoCache","revealAfter","isJavaScriptURLString","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","oldScrollRef","hashFragment","decodeURIComponent","slice","createRootRouteTree","node","head","beginNavigationLockPrefetch","navigationLockPrefetch","prefetchTask","schedulePrefetchTask","PrefetchPriority","promise","updateCapturedSPAToTree","PENDING_LINK_STATUS","mountFormInstance","onLinkVisibilityChanged","pingVisibleLinks","setLinkForCurrentNavigation","linkForMostRecentNavigation","pending","startTransition","prefetchable","WeakMap","Map","prefetchableAndVisible","Set","observer","IntersectionObserver","handleIntersect","rootMargin","observeVisibility","instance","existingInstance","get","observe","coercePrefetchableUrl","createPrefetchURL","reportErrorFn","reportError","prefetchURL","isVisible","prefetchHref","delete","cancelPrefetchTask","unobserve","entries","i","length","entry","intersectionRatio","add","rescheduleLinkPrefetch","unstable_upgradeToDynamicPrefetch","__NEXT_DYNAMIC_ON_HOVER","Intent","priority","existingPrefetchTask","getCurrentAppRouterState","appRouterState","scheduleSegmentPrefetchTask","reschedulePrefetchTask","task","isPrefetchTaskDirty","createInitialRenderTreeForHydration","createRootNavigationTask","getCurrentNavigationLock","isDeferredRsc","resetNavigationLockToPending","noop","navigatedAt","initialRoot","seedDynamicStaleAt","parentNeedsDynamicRequest","createRenderTreeOnNavigation","oldRenderedSearch","oldRoot","newRoot","freshness","parentRefreshState","oldRootRefreshState","updateRenderTreeOnNavigation","createNavigationTask","oldRenderTree","newRouteTree","newSegment","doesRouteStructureMatch","IsRootLayoutOrAbove","isNavigatingToNewRootLayout","NOT_FOUND_SEGMENT_KEY","newSlots","slots","shouldRefreshDynamicData","isLeafSegment","newRenderTree","needsDynamicRequest","paramsChange","compareParams","varyPath","ParamsChange","None","bfcacheId","PathParam","generateBFCacheId","data","oldCacheNode","didReadChangedParam","varyParams","cacheNode","createCacheNode","rsc","prefetchRsc","writeToBFCache","createRenderTree","createRenderTreeForSegment","accumulateScrollRef","maybeRefreshState","refreshState","accumulateRefreshUrl","patchedRouterStateChildren","taskChildren","childNeedsDynamicRequest","dynamicRequestTreeChildren","oldRenderTreeSlots","newRenderTreeSlots","parallelRouteKey","newRouteTreeChild","oldRenderTreeChild","oldSegmentChild","newSegmentChild","DEFAULT_SEGMENT_KEY","reuseActiveSegmentInDefaultSlot","taskChild","taskChildRoute","dynamicRequestTreeChild","newFlightRouterState","createRouterStateForSegment","createDynamicRequestTree","routeTree","routerState","PAGE_SEGMENT_KEY","getRenderedSearchFromVaryPath","patchRouterStateWithNewChildren","baseRouterState","newChildren","clone","newRouterState","refreshUrl","reusedUrl","reusedRenderedSearch","oldRefreshState","reusedRouteTree","rebaseInactiveRouteTree","requestKey","shellVaryPath","seedData","seedRsc","seedVaryParams","bfcacheEntry","readFromBFCacheDuringRegularNavigation","readFromBFCache","oldRsc","oldRscDidResolve","dropPrefetchRsc","cachedRsc","isCachedRscPartial","cachedVaryParams","segmentEntry","readSegmentCacheEntryForNavigation","isPartial","Pending","promiseForFulfilledEntry","waitForSegmentCacheEntry","then","Empty","HEAD_REQUEST_KEY","doesSegmentNeedDynamicRequest","createDeferredRsc","nextBFCacheId","previousNavigationDidMismatch","primaryUrl","MetadataOnlyRequestTree","primaryRequestPromise","fetchMissingDynamicData","refreshRequestPromises","scopedDynamicRequestTree","push","voidPromise","finishNavigationTask","exitStatus","waitForRequestsToFinish","abortRemainingPendingTasks","headExitStatus","isHardRetry","primaryRequestResult","dispatchRetryDueToTreeMismatch","seed","Promise","resolve","onFulfill","remainingCount","onReject","refreshRequestPromise","retryUrl","retryNextUrl","originalNavigateType","retryFreshnessPolicy","predictedFrom","hasDynamicRewrite","invalidateRouteCacheEntries","baseTree","lastCommitted","getLastCommittedTree","retryNavigateType","retryAction","ACTION_SERVER_PATCH","previousTree","mpa","dispatchAppRouterAction","isHmrRefresh","didReceiveUnknownParallelRoute","writeDynamicDataIntoNavigationTask","resolvedUrl","didCommitWrongUrl","committedUrl","aborted","serverRouteTree","dynamicData","finishPendingCacheNode","updateBFCacheEntryFromDynamicResponse","serverChildren","serverRouteTreeChild","childDidReceiveUnknownParallelRoute","dynamicSegmentData","resolveRsc","abortPendingCacheNode","childExitStatus","reject","DEFERRED","tag","pendingRsc","res","rej","responseDebugInfo","fulfilledRsc","apply","rejectedRsc","reason","_debugInfo","getCurrentNavigationGate","begin","reset","extractPathFromFlightRouterState","extractSourcePageFromFlightRouterState","getSelectedParams","segmentToSourcePagePathname","removeLeadingSlash","segmentToPathname","paramName","dynamicParamType","normalizeSegments","segments","reduce","acc","isGroupSegment","INTERCEPTION_ROUTE_MARKERS","m","parallelRoutes","childrenPath","childPath","extractSourcePageSegmentsFromFlightRouterState","sourcePageSegments","join","computeChangedPathImpl","treeA","treeB","segmentA","parallelRoutesA","segmentB","parallelRoutesB","normalizedSegmentA","normalizedSegmentB","didPathChange","parallelRouterKey","currentTree","params","parallelRoute","values","isDynamicParameter","segmentValue","isCatchAll","includeHash","createFetch","createFromNextReadableStream","decodeBufferedStage","decodeStageUntilBoundary","processFetch","resolveShellStageResponse","createFromReadableStream","createFromReadableStreamBrowser","createFromFetch","createFromFetchBrowser","createDebugChannel","__NEXT_REACT_DEBUG_CHANNEL","doMpaNavigation","urlToUrlWithoutFlightMarker","toString","isPageUnloading","addEventListener","options","headers","prepareFlightRouterStateForRequest","originalUrl","__NEXT_CONFIG_OUTPUT","__NEXT_USE_OFFLINE","notifyOnline","responseUrl","redirected","contentType","interception","postponed","isFlightResponse","ok","body","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightResponsePromise","flightResponse","cacheData","all","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","getNavigationBuildId","n","resolveStaticStageResponse","t","q","S","d","p","_revealAfter","checkOfflineError","getOffline","waitForConnection","offline","response","InvariantError","stream","stripIsPartialByte","responseStream","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","stream1","rest","tee","staticBodyClone","shellBodyClone","strippedResponse","Response","statusText","defineProperty","cancel","l","staticStageByteLength","shellByteLength","responseBodyClone","byteLength","buffer","bufferPrefetchResponseBody","timeout","setTimeout","clearTimeout","ReadableStream","start","controller","enqueue","close","allowPartialStream","createHaltingFlightResponse","fetchPromise","closed","reader","wrapper","onAbort","once","pull","getReader","done","read","decodeFlightResponse","__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION","createFromNextFetch","fetchPriority","shouldImmediatelyDecode","__NEXT_TEST_MODE","deploymentId","getDeploymentId","self","__next_r","crypto","getRandomValues","Uint32Array","fetchOptions","credentials","fetchUrl","setCacheBustingSearchParam","processed","fetch","browserResponse","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","rscResponse","flightStream","requestHeaders","debugChannel","unstable_allowPartialStream","promiseForResponse","nextTree","currentInPrefix","nextInPrefix","currentTreeSegment","nextTreeSegment","currentTreeChildren","slot","nextTreeChild","currentTreeChild","setLastCommittedTree","lastCommittedTree","DYNAMIC_STALETIME_MS","STATIC_STALETIME_MS","navigateReducer","Number","__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME","getStaleTimeMs","__NEXT_CLIENT_ROUTER_STATIC_STALETIME","action","isExternalUrl","getElementById","navigateUsingSegmentCache","ACTION_HMR_REFRESH","ACTION_NAVIGATE","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","PrefetchKind","setCacheBustingSearchParamWithHash","computeClientCacheBustingSearchParam","globalThis","subtle","digest","computeCacheBustingSearchParam","computeLegacyCacheBustingSearchParam","uniqueCacheKey","existingSearch","rawQuery","pairs","filter","pair","invalidateBfCache","dynamicStaleTimeSeconds","bfcacheMap","createCacheMap","currentBfCacheVersion","size","staleAt","version","isRevalidation","setInCacheMap","newStaleAt","getFromCacheMap","splitPathnameIntoParts","originalHref","parts","charCodeAt","Fallback","deleteFromCacheMap","deleteMapEntry","isValueExpired","setSizeInCacheMap","Revalidation","cacheMap","parent","prev","next","getOrInitialize","remainingKeys","previousKey","existingEntry","newEntry","currentCacheVersion","rootEntry","onlyMatchFulfilled","getEntryWithFallbackImpl","lruPut","lazilyEvictIfNeeded","fallbackEntry","setMapEntryValue","updateLruSize","dropRef","oldEntry","deleteFromLru","parentMap","revalidatingEntry","attemptToFulfillDynamicSegmentFromBFCache","attemptToUpgradeSegmentFromBFCache","canNewFetchStrategyProvideMoreContent","convertFlightRouterStateToRouteTree","convertRootFlightRouterStateToRouteTree","convertRouteTreeToFlightRouterState","createDetachedSegmentCacheEntry","createMetadataRouteTree","fetchRouteOnCacheMiss","fetchSegmentPrefetchesUsingRuntimeRequest","fetchSegmentPrefetchesUsingStaticRequest","fulfillRouteCacheEntry","getCurrentRouteCacheVersion","getCurrentSegmentCacheVersion","getHeadRequestKey","invalidateEntirePrefetchCache","invalidateSegmentCacheEntries","overwriteRevalidatingSegmentCacheEntry","pingInvalidationListeners","readOrCreateRevalidatingSegmentEntry","readOrCreateRouteCacheEntry","readOrCreateSegmentCacheEntry","resolveStaleAt","upgradeToPendingSegment","upsertSegmentEntry","writeRouteIntoCache","staleTimeSeconds","Math","max","REJECTION_BACKOFF_MS","getPrefetchErrorStaleAt","ROOT_SEGMENT_REQUEST_KEY","isOutputExportMode","routeCacheMap","invalidationListeners","currentRouteCacheVersion","currentSegmentCacheVersion","attachInvalidationListener","onInvalidate","notifyInvalidationListener","tasks","getRouteVaryPath","matchKnownRoute","lookupVaryPath","getShellSegmentVaryPath","fulfilled","readRevalidatingSegmentCacheEntry","pendingEntry","promiseWithResolvers","createPromiseWithResolvers","createDetachedRouteCacheEntry","blockedTasks","Infinity","requestedUrl","requestedSearch","urlWithoutSearchParams","routeWithNoSearchParams","createPrefetchRequestKey","canonicalUrlForRouteWithNoSearchParams","optimisticCanonicalSearch","optimisticRenderedSearch","normalizeRenderedSearch","optimisticUrl","optimisticCanonicalUrl","optimisticRouteTree","deprecated_createOptimisticRouteTree","baseMetadataTree","optimisticMetadataTree","cloneVaryPathWithNewSearchParams","optimisticEntry","newRenderedSearch","clonedSlots","originalSlots","childTree","insertEmptySegmentCacheEntry","varyPathForRequest","getSegmentVaryPathForRequest","emptyEntry","isExistingSegmentEntryPreferred","candidateEntry","pingBlockedTasks","evictShadowingSegmentEntries","shadowEntry","isUpgradeableISRFallback","dynamicPrefetchStaleAt","pendingSegment","fulfillSegmentCacheEntry","segmentVaryPath","upserted","pingPrefetchTask","pageRequestKey","metadataVaryPath","rootPrefetchHints","metadata","StaticAttemptHints","stripDataFromRouteTree","strippedChild","strippedSlots","fulfilledEntry","InliningHintsStale","getFulfilledRouteVaryPath","segmentCacheEntry","rejectRouteCacheEntry","rejectedEntry","rejectSegmentCacheEntry","treeToRebase","parentPartialVaryPath","parentRenderedSearch","originalSegment","isRootParam","compressedRefreshState","createRouteTreeNode","partialVaryPath","getPartialVaryPath","childRouterState","childSegment","childRequestKeyPart","createSegmentRequestKeyPart","childRequestKey","appendSegmentRequestKeyPart","segmentPath","urlAfterRedirects","headResponse","method","fetchPrefetchResponse","addSegmentPathToUrlInOutputExportMode","varyHeader","wasServedFromPerSegmentCache","serverData","renderedPathname","getRenderedPathname","getRenderedSearch","decodeTransportTreeIntoRouteTree","fulfilledVaryPath","FALLBACK_RETRY_DELAY_MS","MAX_FALLBACK_RETRIES","routeKey","spawnedEntries","fetchAndWritePerSegmentPrefetchResponse","rejectSegmentEntriesIfStillPending","discardFallbackResponse","normalizedRequestKey","requestUrl","serverResponse","f","fallbackRetryStatus","isCanceled","retryUpgradeableFallbackPrefetch","shellOffset","readFulfilledValue","shellResponse","subarray","getPathnameFromRequestURL","writeResponsePayloadsIntoCache","readFulfilledStaleAt","staleTime","readFulfilledStaleTimeSeconds","attempt","requestTree","has","PPRRuntime","RuntimeShell","LoadingBoundary","fulfilledEntries","bufferedResponseSize","serverDataPromise","prefetchStream","createIncrementalPrefetchResponseStream","onResponseSizeUpdate","totalBytesReceivedSoFar","averageSize","s","buildId","isFullResponsePartial","fullPayload","shellPayload","responseByteLength","StaticShell","writeServerResponseIntoCache","contentFetchStrategy","responseFetchStrategy","shellFetchStrategy","wasShellRequested","fullFulfilledEntries","shellFulfilledEntries","r","requiresRuntimeCompleteness","treeDivergedFromPrediction","responseNeedsRuntimeRequest","u","writtenEntries","writeTreeDataIntoCache","metadataTree","headData","headStaleAt","headFetchStrategy","writtenHeadEntry","writeSegmentDataIntoCache","entryStaleAt","writtenEntry","segmentVaryParams","recordedFetchStrategy","payloadFetchStrategy","payloadStrategy","recordedVaryParams","__NEXT_VARY_PARAMS","readVaryParams","SEARCH_PARAMS_VARY_ID","createVaryParams","getFulfilledSegmentVaryPath","canonicalVaryPath","ownedEntry","isOwned","insertVaryPath","installedEntry","byteLimit","chunks","remaining","Uint8Array","offset","chunk","originalFlightStream","onStreamClose","totalByteLength","staticUrl","routeDir","staticExportFilename","convertSegmentPathToStaticExportFilename","currentStrategy","newStrategy","getStaleAtFromHeader","parseInt","staleTimeMs","isNaN","staleTimeIterable","defaultIsPartial","c","firstByte","hasMarker","remainder","readFulfilledIsPartial","rootVaryParams","normalizedRenderedSearch","transportHead","h","decodeVaryParams","v","paramCacheKey","appendLayoutVaryPath","finalizeVaryPath","transportNode","pathnameParts","decodeTransportNode","resolveTransportSegment","transportSegment","pathnamePartsIndex","paramKey","k","paramValue","parseDynamicParamFromURLPart","getCacheKeyForDynamicParam","doSegmentsMatch","baseSegment","baseParamName","baseParamValue","baseParamType","paramType","base","compareBase","nodeData","inheritsFromBase","inheritedBase","baseHints","baseCompressedRefreshState","transportChildren","baseChildren","childNode","childBase","childCompareBase","childCompareCandidate","childDoesAppearInURL","doesStaticSegmentAppearInURL","childPathnamePartsIndex","propagated","SubtreePrefetchHints","propagateSubtreeBits","notFulfilled","iterator","asyncIterator","fetchInternal","input","init","preLockFetch","getPreLockFetch","cleanup","lruSize","maxLruSize","ensureCleanupIsScheduled","tail","newNodeSize","prevNodeSize","deleted","pingPrefetchScheduler","ninetyPercentMax","getNavigationLockSegmentCacheMap","resolveNavigationLockPrefetch","startListeningForInstantNavigationCookie","parseCookieValue","raw","parsed","JSON","parse","rawState","writeDocumentCookie","cookie","stringify","domain","writeCookieValue","cookieStore","lockAtCall","lockState","existing","activePrefetches","acquireLock","resolveReleased","released","resolveCurrentNavigation","currentNavigation","globalFetchOverride","releaseLock","random","isDevServerRequest","currentLock","__next_instant_test","reload","changed","refreshOnInstantNavigationUnlock","fromTree","toTree","from","to","allCookies","trimmed","trim","linkFetchStrategy","needsSpeculativePrefetch","resetKnownRoutes","readPattern","part","pattern","createEmptyPart","staticChildren","dynamicChild","dynamicChildParamName","dynamicChildParamType","hasConflictingDynamicChildren","knownRouteTreeRoot","discoverKnownRoutePart","handleMismatchDueToRewrite","discoverDynamicChild","newChild","mutablePart","parentKnownRoutePart","partIndex","urlPart","knownRoutePart","nextPartIndex","existingChild","staticSiblings","canonicalizeURLPart","joinedRemainingParts","sibling","resultFromChildren","childRouteTree","existingPattern","resolvedParams","match","matchKnownRoutePart","matchedPart","IsClosedParam","SubtreeHasClosedParams","reifiedTree","reifyRouteTree","reifiedMetadata","syntheticEntry","staticChild","dynamicPart","dynamicPattern","directPattern","newValue","newCacheKey","patternSlots","childPattern","newVaryPath","startRevalidationCooldown","scheduleMicrotask","queueMicrotask","fn","taskHeap","inProgressRequests","sortIdCounter","didScheduleMicrotask","mostRecentlyHoveredLink","REVALIDATION_COOLDOWN_MS","revalidationCooldownTimeoutHandle","renderTreeAtTimeOfPrefetch","taskSegmentCacheMap","lockMap","routeCacheVersion","segmentCacheVersion","phase","hasBackgroundWork","hasPendingResponses","spawnedRuntimePrefetches","sortId","_heapIndex","_navigationLockPrefetch","trackMostRecentlyHoveredLink","heapPush","heapDelete","heapResift","Background","processQueueInMicrotask","hasNetworkBandwidth","spawnPrefetchSubtask","prefetchSubtask","onPrefetchConnectionClosed","heapPeek","pingRoute","heapPop","routeHasPartialPrefetching","background","pingRootRouteTree","keyWithoutSearch","routeWithoutSearch","staticWalkStrategy","__NEXT_PREFETCH_INLINING","HeadOutlined","walkCanUseRuntimeRequests","shouldSegmentAttemptStaticRequest","pingNewPartOfCacheComponentsTree","pingSharedPartOfCacheComponentsTree","runtimeStrategy","pingRouteTreeAndIncludeDynamicData","pingRuntimePrefetches","diffRouteTreeAgainstCurrent","ShouldAttemptStaticShell","ShouldAttemptStaticPrefetch","getRuntimeStrategyForWalk","wouldRuntimeRequestProvideMore","isShellEntryEligibleForStaticAttempt","addSpawnedRuntimePrefetch","newTree","parentBundle","bundleInProgress","accumulateSegmentBundle","bundle","newTreeChildren","currentSlots","newTreeChild","bundleForChild","ParentInlinedIntoSelf","pingSegmentInCacheComponentsTree","treeChildren","treeChild","canUseRuntimeRequests","finishStaticBundleOnRuntimeBailout","needsRuntimeRequest","oldTree","oldSlots","requestTreeChildren","oldTreeChild","diffSegmentAgainstCurrent","subtreeHasLoadingBoundary","SegmentHasLoadingBoundary","SubtreeHasLoadingBoundary","pingPPRDisabledRouteTreeUpToLoadingBoundary","refetchMarkerContext","refetchMarker","blockTaskOnPendingResponse","segmentHasLoadingBoundary","isInsideRefetchingParent","spawnedSegment","pingFullSegmentRevalidation","pingSegmentBundle","spawnRevalidations","nodeEntry","nodeTree","willBeSupersededByRuntimeRequest","runtimeWouldProvideMore","shellEntryEligibleForStaticAttempt","isUpgradeableISRFallbackRetry","StaticPrefetchDisabled","InlinedIntoChild","effectiveParent","HeadInlinedIntoSelf","revalidatingSegment","nonEmptyRevalidatingSegment","emptySegment","taskfetchStrategy","compareQueuePriority","priorityDiff","phaseDiff","heap","index","heapSiftUp","first","last","pop","heapSiftDown","parentIndex","halfLength","leftIndex","left","rightIndex","right","NavigationResultTag","id","parentPath","varyPathPart","finalizedVaryPath","originalVaryPath","searchParamsVaryPath","doesVaryOnSearchParams","newSearch","currentVaryPath","nextVaryPath","change","total","original","dispatchGestureState","useActionQueue","dispatch","bypassCacheInvalidation","setGestureRouterState","__DEV__","promisesWithDebugInfo","actionQueue","canonicalState","setState","useState","setGesture","nextDispatch","useAppDevRenderingIndicator","appDevRenderingIndicator","stateWithDebugInfo","isThenable","promiseWithDebugInfo","asyncState","use","createInitialRSCPayloadFromFallbackPrerender","getNextFlightSegmentPath","fallbackInitialRSCPayload","fallbackTransportData","payload","fillInFallbackTransportTree","G","doesAppearInURL","newNode","flightSegmentPath","encodeURIComponent","stripClientOnlyDataFromFlightRouterState","_refreshState","refreshMarker","cleanedSegment","stripClientOnlyDataFromSegment","cleanedParallelRoutes","childState","hasBasePath","pathHasPrefix","isJavaScriptProtocol","test","setNavigationBuildId","globalBuildId","__NEXT_MANUAL_TRAILING_SLASH","query","parsePath","__NEXT_TRAILING_SLASH","removeTrailingSlash","removeBasePath","getParamValueFromCacheKey","urlSearchParamsToParsedUrlQuery","URLSearchParams","getRenderedSearchFromQuery","rewrittenQuery","rewrittenPath","prefix","urlWithoutFlightParameters","actionId","actionArgs","refA","refB","cleanupA","cleanupB","cleanupFnA","cleanupFnB","applyRef","ACTION_SUFFIX","APP_DIR_ALIAS","CACHE_ONE_YEAR_SECONDS","DOT_NEXT_ALIAS","ESLINT_DEFAULT_DIRS","GSP_NO_RETURNED_VALUE","GSSP_COMPONENT_MEMBER_ERROR","GSSP_NO_RETURNED_VALUE","HTML_CONTENT_TYPE_HEADER","INFINITE_CACHE","INSTRUMENTATION_HOOK_FILENAME","JSON_CONTENT_TYPE_HEADER","MATCHED_PATH_HEADER","MIDDLEWARE_FILENAME","MIDDLEWARE_LOCATION_REGEXP","NEXT_BODY_SUFFIX","NEXT_CACHE_IMPLICIT_TAG_ID","NEXT_CACHE_REVALIDATED_TAGS_HEADER","NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER","NEXT_CACHE_ROOT_PARAM_TAG_ID","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","NEXT_CACHE_TAGS_HEADER","NEXT_CACHE_TAG_MAX_ITEMS","NEXT_CACHE_TAG_MAX_LENGTH","NEXT_DATA_SUFFIX","NEXT_INTERCEPTION_MARKER_PREFIX","NEXT_META_SUFFIX","NEXT_QUERY_PARAM_PREFIX","NEXT_RESUME_HEADER","NEXT_RESUME_STATE_LENGTH_HEADER","NON_STANDARD_NODE_ENV","PAGES_DIR_ALIAS","PRERENDER_REVALIDATE_HEADER","PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER","PROXY_FILENAME","PROXY_LOCATION_REGEXP","PUBLIC_DIR_MIDDLEWARE_CONFLICT","ROOT_DIR_ALIAS","RSC_ACTION_CLIENT_WRAPPER_ALIAS","RSC_ACTION_ENCRYPTION_ALIAS","RSC_ACTION_PROXY_ALIAS","RSC_ACTION_VALIDATE_ALIAS","RSC_CACHE_WRAPPER_ALIAS","RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS","RSC_MOD_REF_PROXY_ALIAS","RSC_SEGMENTS_DIR_SUFFIX","RSC_SEGMENT_SUFFIX","RSC_SUFFIX","SERVER_PROPS_EXPORT_ERROR","SERVER_PROPS_GET_INIT_PROPS_CONFLICT","SERVER_PROPS_SSG_CONFLICT","SERVER_RUNTIME","SSG_FALLBACK_EXPORT_ERROR","SSG_GET_INITIAL_PROPS_CONFLICT","STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR","TEXT_PLAIN_CONTENT_TYPE_HEADER","UNSTABLE_REVALIDATE_RENAME_ERROR","WEBPACK_LAYERS","WEBPACK_RESOURCE_QUERIES","WEB_SOCKET_MAX_RECONNECTIONS","edge","experimentalEdge","nodejs","WEBPACK_LAYERS_NAMES","shared","reactServerComponents","serverSideRendering","actionBrowser","apiNode","apiEdge","middleware","instrument","edgeAsset","appPagesBrowser","pagesDirBrowser","pagesDirEdge","pagesDirNode","GROUP","builtinReact","serverOnly","neutralTarget","clientOnly","bundled","appPages","edgeSSREntry","metadataRoute","metadataImageMeta","parentHints","childHints","getAssetToken","getAssetTokenQuery","getDeploymentIdQuery","documentElement","dataset","dplId","removeAttribute","NEXT_DEPLOYMENT_ID","ampersand","NEXT_SUPPORTS_IMMUTABLE_ASSETS","djb2Hash","hexHash","str","char","createUnrenderedSegmentError","missingFiles","label","ensureLeadingSlash","compareAppPaths","normalizeAppPath","normalizeRscURL","selectAppPageEntry","aHasSlot","bHasSlot","localeCompare","normalizeAppPageEntryPathname","appPath","appPaths","normalizePathname","CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES","textEncoder","TextEncoder","encodeCacheBustingSearchParam","bytes","binary","String","fromCharCode","btoa","normalizeCacheBustingInput","createCacheBustingSearchParamInput","prefetchHeader","segmentPrefetchHeader","stateTreeHeader","nextUrlHeader","computeCacheBustingSearchParamFromInput","encode","formatWithValidation","urlObjectKeys","slashedProtocols","urlObj","auth","hostname","protocol","host","indexOf","port","querystring","urlQueryToSearchParams","slashes","extractInterceptionRouteInformation","findMissingCanonicalInterceptionRoutes","isInterceptionRouteAppPath","parseRoutePattern","Boolean","at","isOptionalCatchAll","unbounded","prefixSegments","minLength","acceptsLength","prefixCovers","canonical","intercepted","every","canonicalSegment","interceptedSegment","patternCoversAtLength","isRoutePatternCovered","ordinaryRoutes","unboundedCoverageStart","min","find","interceptingRoute","marker","interceptedRoute","concat","splitInterceptingRoute","canonicalRoutes","canonicalRoutePatterns","interceptionRoute","canonicalRoute","sort","locationOrigin","getLocationOrigin","resolved","hashIndex","queryIndex","hasQuery","substring","assign","searchParamsToUrlQuery","stringifyUrlQueryParam","param","item","append","searchParamsList","createSkippedSegmentData","segmentToTransportSegment","transportNodeToFlightRouterState","transportSegmentToSegment","valueFromServer","unresolvedValue","rejectedValue","thenable","safeName","encodeToFilesystemAndURLSafeString","encodedName","parentRequestKey","slotKey","simpleParamValueRegex","base64url","drainVaryParams","iterable","step","rootIterable","settled","DecodeError","MiddlewareNotFoundError","MissingStaticPage","NormalizeError","PageNotFoundError","SP","ST","WEB_VITALS","execOnce","getDisplayName","getURL","isResSent","loadGetInitialProps","normalizeRepeatedSlashes","stringifyError","used","ABSOLUTE_URL_REGEX","isLetter","Component","displayName","finished","headersSent","urlParts","urlNoQuery","App","ctx","prototype","getInitialProps","pageProps","performance","constructor","page","code"],"mappings":"sHAKgBA,cAAAA,qCAAAA,aALc,CAAA,CAAA,IAAA,OACa,CAAA,CAAA,IAAA,GAIpC,SAASA,EAAYK,CAAY,CAAEC,C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