@farm.js/core 0.1.67 → 0.1.68

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 (281) hide show
  1. package/dist/{agent-mcp.d-BFu9xHAi.d.ts → agent-mcp.d-Uh5xr7aX.d.ts} +1 -1
  2. package/dist/{agent-mcp.d-DWyWkTSy.d.mts → agent-mcp.d-wkVPK1GA.d.mts} +1 -1
  3. package/dist/agent-runtime.d.mts +5 -3
  4. package/dist/agent-runtime.d.ts +5 -3
  5. package/dist/{analyzer-TTIIXXMQ.mjs → analyzer-CQDU7E3Y.mjs} +2 -2
  6. package/dist/analyzer-PPAHM4AW.cjs +16 -0
  7. package/dist/api/node.d.mts +7 -5
  8. package/dist/api/node.d.ts +7 -5
  9. package/dist/api/route-manager.d.mts +7 -5
  10. package/dist/api/route-manager.d.ts +7 -5
  11. package/dist/api/runtime.d.mts +6 -4
  12. package/dist/api/runtime.d.ts +6 -4
  13. package/dist/api.d.mts +8 -6
  14. package/dist/api.d.ts +8 -6
  15. package/dist/{app-manifest.d-CwfhGrVR.d.ts → app-manifest.d-BT5i2F-o.d.ts} +1 -1
  16. package/dist/{app-manifest.d-CRmjN5j9.d.mts → app-manifest.d-Dd4q5CFx.d.mts} +1 -1
  17. package/dist/app-markdown.cjs +3 -3
  18. package/dist/app-markdown.d.mts +10 -10
  19. package/dist/app-markdown.d.ts +10 -10
  20. package/dist/app-markdown.mjs +2 -2
  21. package/dist/{app.d-BX9LVTiP.d.ts → app.d-BVOpL_f2.d.ts} +6 -6
  22. package/dist/{app.d-uBBUxwyV.d.mts → app.d-BhiDXex_.d.mts} +6 -6
  23. package/dist/{chunk-23PVOIPT.cjs → chunk-225APHKC.cjs} +3 -3
  24. package/dist/{chunk-4JX3M4C6.cjs → chunk-23VJEGKC.cjs} +2 -1
  25. package/dist/{chunk-Q37INCXG.cjs → chunk-3EEINK7G.cjs} +11 -2
  26. package/dist/{chunk-BRWIVOV4.cjs → chunk-3GNHJ3RN.cjs} +10 -8
  27. package/dist/{chunk-QJVW76JG.mjs → chunk-3Y52TWYU.mjs} +2 -2
  28. package/dist/{chunk-OB3IFUK6.cjs → chunk-437QZIC2.cjs} +4 -4
  29. package/dist/{chunk-WGHY3OL5.mjs → chunk-4UAQB5LB.mjs} +232 -49
  30. package/dist/{chunk-JWSI5WO4.mjs → chunk-4ZXKYCYK.mjs} +1 -1
  31. package/dist/{chunk-N35YPV4N.mjs → chunk-57QAQU4F.mjs} +9 -7
  32. package/dist/{chunk-AQDLVHNF.mjs → chunk-5FBZJJGA.mjs} +17 -0
  33. package/dist/{chunk-PL6RTBDE.cjs → chunk-5JKDFRTK.cjs} +2 -2
  34. package/dist/{chunk-CO3YMZFD.mjs → chunk-6OFOIMNS.mjs} +1 -1
  35. package/dist/{chunk-556H7JCE.cjs → chunk-7LK5CTUM.cjs} +14 -14
  36. package/dist/{chunk-E6CD45JK.mjs → chunk-A3T445WK.mjs} +19 -5
  37. package/dist/{chunk-DQJ2CIH7.cjs → chunk-ASYOWPSR.cjs} +2 -1
  38. package/dist/{chunk-QGJ4FI2G.mjs → chunk-C6HGUTXB.mjs} +113 -29
  39. package/dist/{chunk-IRA2CZAY.mjs → chunk-CRVSYDHV.mjs} +2 -2
  40. package/dist/{chunk-XNZWMXCF.mjs → chunk-DIXFKAPM.mjs} +183 -76
  41. package/dist/{chunk-QGQP6QKO.cjs → chunk-DWLNLU55.cjs} +2 -2
  42. package/dist/{chunk-52Y3C3HG.mjs → chunk-E7VF3LQ5.mjs} +3 -2
  43. package/dist/{chunk-N5DQMOAG.cjs → chunk-F36LS2C7.cjs} +273 -90
  44. package/dist/{chunk-H37MDCPR.mjs → chunk-F6CMGWAL.mjs} +1 -1
  45. package/dist/{chunk-HNVAZGQD.cjs → chunk-FJMC24KG.cjs} +2 -2
  46. package/dist/{chunk-KCY52OUQ.cjs → chunk-FSODPZRT.cjs} +1 -1
  47. package/dist/{chunk-PPX7UOFY.cjs → chunk-FVYBEMOD.cjs} +55 -38
  48. package/dist/{chunk-6YBYX4K4.mjs → chunk-G7NBPP7H.mjs} +1 -1
  49. package/dist/{chunk-HFHJJXSV.mjs → chunk-GFPS7MNE.mjs} +1 -1
  50. package/dist/{chunk-3T5TLFCQ.mjs → chunk-HEJM46HQ.mjs} +11 -2
  51. package/dist/chunk-HHLEYA4B.cjs +17 -0
  52. package/dist/{chunk-F43OG25P.cjs → chunk-I7J5RLGO.cjs} +15 -1
  53. package/dist/chunk-ICFPTHXM.mjs +97 -0
  54. package/dist/{chunk-6V5YWI4W.cjs → chunk-IGDYL2IA.cjs} +2 -2
  55. package/dist/{chunk-TEG6HJVF.mjs → chunk-JL2YW5KX.mjs} +1 -0
  56. package/dist/{chunk-JVM3DKZE.mjs → chunk-KDO6T6OB.mjs} +1 -1
  57. package/dist/{chunk-QITSS4TD.cjs → chunk-KWCZKJYU.cjs} +352 -245
  58. package/dist/{chunk-DCXSIEFE.cjs → chunk-LDEXTX4I.cjs} +51 -37
  59. package/dist/{chunk-3T7ALZJF.cjs → chunk-LR4KP3I7.cjs} +2 -2
  60. package/dist/{chunk-VFXE6NWR.mjs → chunk-MGKWYPE3.mjs} +2 -1
  61. package/dist/{chunk-5TA63JD3.mjs → chunk-MGZVDX4R.mjs} +1 -1
  62. package/dist/{chunk-6SQZXRJ2.cjs → chunk-MMDKYJ5V.cjs} +7 -7
  63. package/dist/{chunk-HP2DQGQH.mjs → chunk-MNJDNTGO.mjs} +1 -1
  64. package/dist/{chunk-5Y2P454O.cjs → chunk-MTBDJ326.cjs} +6 -5
  65. package/dist/{chunk-XUES6OET.mjs → chunk-MV7NWU23.mjs} +1 -1
  66. package/dist/{chunk-4DRINDGN.cjs → chunk-MZ4CRSY7.cjs} +254 -125
  67. package/dist/{chunk-4IHMHFQB.cjs → chunk-NG2EZ6QS.cjs} +28 -1
  68. package/dist/{chunk-WDD5CTZW.mjs → chunk-NT4W4H52.mjs} +6 -6
  69. package/dist/{chunk-F7JKVHU2.mjs → chunk-NVOMQLI2.mjs} +15 -1
  70. package/dist/{chunk-22IWL4YD.cjs → chunk-OCNV4CI2.cjs} +21 -2
  71. package/dist/{chunk-72KCTHLV.cjs → chunk-PRL7FXG4.cjs} +113 -29
  72. package/dist/{chunk-YVTS3S3F.cjs → chunk-QOGIZKSO.cjs} +3 -3
  73. package/dist/{chunk-DB2HSHQA.cjs → chunk-QSUYB3RH.cjs} +14 -14
  74. package/dist/chunk-QYNZ3CTI.mjs +17 -0
  75. package/dist/{chunk-724MGMIL.mjs → chunk-R2ZHU37O.mjs} +19 -0
  76. package/dist/{chunk-YQYTQJZN.mjs → chunk-RLH5AH2M.mjs} +1 -1
  77. package/dist/{chunk-HM7AGSKU.cjs → chunk-SQ6IWJ3H.cjs} +1 -1
  78. package/dist/{chunk-V5MQMQ2P.mjs → chunk-T5XFZQCL.mjs} +1 -1
  79. package/dist/{chunk-Q5UX55YA.cjs → chunk-TNK2TVRS.cjs} +831 -470
  80. package/dist/{chunk-J7JHVCWA.cjs → chunk-UKZ6AWKZ.cjs} +2 -1
  81. package/dist/{chunk-V5RTHYJB.cjs → chunk-URN7VFO7.cjs} +91 -22
  82. package/dist/{chunk-HRPTMX5C.mjs → chunk-VFNAK6A5.mjs} +2 -2
  83. package/dist/{chunk-VK54PDQ6.mjs → chunk-VRGY3X2I.mjs} +86 -17
  84. package/dist/chunk-W44X6IC2.cjs +97 -0
  85. package/dist/{chunk-GTV2ABO7.mjs → chunk-WPB67LE5.mjs} +162 -33
  86. package/dist/{chunk-UHE5JUKB.mjs → chunk-XCAQTCGK.mjs} +1 -1
  87. package/dist/{chunk-DGOFR7D5.cjs → chunk-Y6KHPJDB.cjs} +2 -2
  88. package/dist/{chunk-LPIZMU7D.cjs → chunk-YTNBCXCW.cjs} +4 -4
  89. package/dist/{chunk-KWFNUODD.mjs → chunk-YVPX5PI5.mjs} +1 -0
  90. package/dist/{chunk-6R53ZWX2.cjs → chunk-Z3PW3DIR.cjs} +3 -3
  91. package/dist/{chunk-UHNSY2PQ.mjs → chunk-Z6SOXHAD.mjs} +772 -411
  92. package/dist/{chunk-5FE5YT2N.mjs → chunk-ZZGQD3LL.mjs} +28 -1
  93. package/dist/{client-component.d-CDRvRmbU.d.mts → client-component.d-BvQOxSqh.d.mts} +2 -2
  94. package/dist/{client-component.d-DWRKyAp5.d.ts → client-component.d-DNVSLEPi.d.ts} +2 -2
  95. package/dist/{client-plugins.d-BNILjfX3.d.mts → client-plugins.d-CE1lVK2R.d.mts} +23 -234
  96. package/dist/{client-plugins.d-CrKZiNSN.d.ts → client-plugins.d-CNDqcAuf.d.ts} +23 -234
  97. package/dist/client-plugins.d.mts +5 -3
  98. package/dist/client-plugins.d.ts +5 -3
  99. package/dist/client.cjs +6 -6
  100. package/dist/client.d.mts +10 -8
  101. package/dist/client.d.ts +10 -8
  102. package/dist/client.mjs +5 -5
  103. package/dist/config.d.mts +5 -3
  104. package/dist/config.d.ts +5 -3
  105. package/dist/deployment.cjs +4 -2
  106. package/dist/deployment.d.mts +15 -1
  107. package/dist/deployment.d.ts +15 -1
  108. package/dist/deployment.mjs +3 -1
  109. package/dist/desktop.d.mts +6 -4
  110. package/dist/desktop.d.ts +6 -4
  111. package/dist/{devtools-UFQYT3VA.mjs → devtools-2A2GPC7B.mjs} +6 -6
  112. package/dist/{devtools-RZVT4JVN.cjs → devtools-R27T3BRY.cjs} +7 -7
  113. package/dist/docs.cjs +9 -9
  114. package/dist/docs.d.mts +6 -4
  115. package/dist/docs.d.ts +6 -4
  116. package/dist/docs.mjs +8 -8
  117. package/dist/environment/vite.cjs +5 -5
  118. package/dist/environment/vite.d.mts +1 -1
  119. package/dist/environment/vite.d.ts +1 -1
  120. package/dist/environment/vite.mjs +4 -4
  121. package/dist/{generate-route-types.d-BL2pq6xC.d.ts → generate-route-types.d-B76M5R11.d.ts} +1 -1
  122. package/dist/{generate-route-types.d-BoVDU8qX.d.mts → generate-route-types.d-CaGMIaNI.d.mts} +1 -1
  123. package/dist/index.cjs +41 -36
  124. package/dist/{index.d-Bdm6866n.d.mts → index.d-Bt3kl19W.d.mts} +1 -1
  125. package/dist/{index.d-Dey5T14f.d.ts → index.d-Cx_-DaKV.d.ts} +1 -1
  126. package/dist/index.d.mts +25 -22
  127. package/dist/index.d.ts +25 -22
  128. package/dist/index.mjs +43 -38
  129. package/dist/instrumentation.cjs +3 -3
  130. package/dist/instrumentation.mjs +2 -2
  131. package/dist/integrations/orm.d.mts +5 -3
  132. package/dist/integrations/orm.d.ts +5 -3
  133. package/dist/integrations.d.mts +5 -3
  134. package/dist/integrations.d.ts +5 -3
  135. package/dist/internal/app-markdown-runtime.cjs +2 -2
  136. package/dist/internal/app-markdown-runtime.d.mts +12 -5
  137. package/dist/internal/app-markdown-runtime.d.ts +12 -5
  138. package/dist/internal/app-markdown-runtime.mjs +1 -1
  139. package/dist/internal/build-runtime.cjs +33 -30
  140. package/dist/internal/build-runtime.d.mts +7 -5
  141. package/dist/internal/build-runtime.d.ts +7 -5
  142. package/dist/internal/build-runtime.mjs +32 -29
  143. package/dist/internal/cli-runtime.cjs +10 -10
  144. package/dist/internal/cli-runtime.mjs +9 -9
  145. package/dist/internal/client-error-overlay.cjs +4 -4
  146. package/dist/internal/client-error-overlay.mjs +1 -1
  147. package/dist/internal/client-runtime.cjs +31 -36
  148. package/dist/internal/client-runtime.d.mts +8 -6
  149. package/dist/internal/client-runtime.d.ts +8 -6
  150. package/dist/internal/client-runtime.mjs +22 -27
  151. package/dist/internal/compression-runtime.d.mts +5 -3
  152. package/dist/internal/compression-runtime.d.ts +5 -3
  153. package/dist/internal/config-runtime.cjs +8 -8
  154. package/dist/internal/config-runtime.d.mts +9 -7
  155. package/dist/internal/config-runtime.d.ts +9 -7
  156. package/dist/internal/config-runtime.mjs +7 -7
  157. package/dist/internal/form-actions.cjs +7 -2
  158. package/dist/internal/form-actions.d.mts +10 -3
  159. package/dist/internal/form-actions.d.ts +10 -3
  160. package/dist/internal/form-actions.mjs +8 -3
  161. package/dist/internal/infra-analytics-runtime.cjs +6 -6
  162. package/dist/internal/infra-analytics-runtime.mjs +4 -4
  163. package/dist/internal/islands-boot.cjs +6 -1
  164. package/dist/internal/islands-boot.mjs +6 -1
  165. package/dist/internal/native-server-fns.cjs +4 -4
  166. package/dist/internal/native-server-fns.mjs +3 -3
  167. package/dist/internal/product-telemetry-runtime.cjs +3 -3
  168. package/dist/internal/product-telemetry-runtime.mjs +2 -2
  169. package/dist/internal/production-node-env.cjs +4 -2
  170. package/dist/internal/production-node-env.d.mts +22 -1
  171. package/dist/internal/production-node-env.d.ts +22 -1
  172. package/dist/internal/production-node-env.mjs +3 -1
  173. package/dist/internal/production-runtime.cjs +13 -9
  174. package/dist/internal/production-runtime.d.mts +21 -16
  175. package/dist/internal/production-runtime.d.ts +21 -16
  176. package/dist/internal/production-runtime.mjs +13 -9
  177. package/dist/internal/server-tree.cjs +2 -2
  178. package/dist/internal/server-tree.d.mts +0 -5
  179. package/dist/internal/server-tree.d.ts +0 -5
  180. package/dist/internal/server-tree.mjs +1 -1
  181. package/dist/internal/vercel-edge-middleware.cjs +87 -0
  182. package/dist/internal/vercel-edge-middleware.d.mts +39 -0
  183. package/dist/internal/vercel-edge-middleware.d.ts +39 -0
  184. package/dist/internal/vercel-edge-middleware.mjs +87 -0
  185. package/dist/layers-7P4RLKVX.cjs +20 -0
  186. package/dist/{layers-T55SA47E.mjs → layers-XQ7VFMWO.mjs} +4 -2
  187. package/dist/{layers.d-CcS42OGR.d.mts → layers.d-CH0bC4QL.d.mts} +2 -1
  188. package/dist/{layers.d-CcS42OGR.d.ts → layers.d-CH0bC4QL.d.ts} +2 -1
  189. package/dist/markdown.d.mts +5 -3
  190. package/dist/markdown.d.ts +5 -3
  191. package/dist/middleware.cjs +4 -4
  192. package/dist/middleware.d.mts +8 -5
  193. package/dist/middleware.d.ts +8 -5
  194. package/dist/middleware.mjs +6 -6
  195. package/dist/mobile.d.mts +4 -4
  196. package/dist/mobile.d.ts +4 -4
  197. package/dist/{mount.d-BP0nLYQO.d.mts → mount.d-Bki4pOaJ.d.mts} +1 -1
  198. package/dist/{mount.d-CkiPky_F.d.ts → mount.d-DjR5aerM.d.ts} +1 -1
  199. package/dist/{navigation-delegate.d-DchcGzAQ.d.ts → navigation-delegate.d-CtghaSP3.d.ts} +1 -1
  200. package/dist/{navigation-delegate.d-CdBP-hkZ.d.mts → navigation-delegate.d-VDkziXTK.d.mts} +1 -1
  201. package/dist/navigation.cjs +5 -5
  202. package/dist/navigation.d.mts +8 -6
  203. package/dist/navigation.d.ts +8 -6
  204. package/dist/navigation.mjs +4 -4
  205. package/dist/{nitro-55YOZWRA.mjs → nitro-NSTXT7LB.mjs} +2 -2
  206. package/dist/{nitro-EEX2J3KB.cjs → nitro-Y3LGITW3.cjs} +4 -4
  207. package/dist/node-module-bundle-LIZ2KMVW.cjs +13 -0
  208. package/dist/node-module-bundle-VR6NV6AI.mjs +13 -0
  209. package/dist/plugin.cjs +20 -20
  210. package/dist/plugin.d.mts +7 -5
  211. package/dist/plugin.d.ts +7 -5
  212. package/dist/plugin.mjs +19 -19
  213. package/dist/{production-runtime.d-Dou_Htas.d.ts → production-runtime.d-BMyyLGBB.d.ts} +3 -57
  214. package/dist/{production-runtime.d-VwsBzIee.d.mts → production-runtime.d-DMZY3OgV.d.mts} +3 -57
  215. package/dist/query/client.cjs +6 -6
  216. package/dist/query/client.mjs +2 -2
  217. package/dist/{render-plan.d-LKymStDJ.d.mts → render-plan.d-BSwV8PE4.d.mts} +1 -1
  218. package/dist/{render-plan.d-D8UakAIk.d.ts → render-plan.d-i9sI4tc9.d.ts} +1 -1
  219. package/dist/renderer/react/server.cjs +2 -2
  220. package/dist/renderer/react/server.mjs +1 -1
  221. package/dist/renderer-client.cjs +5 -5
  222. package/dist/renderer-client.d.mts +8 -6
  223. package/dist/renderer-client.d.ts +8 -6
  224. package/dist/renderer-client.mjs +2 -2
  225. package/dist/renderer.d.mts +5 -0
  226. package/dist/renderer.d.ts +5 -0
  227. package/dist/{request.d-KG-4d2eG.d.mts → request.d-C24FNQ_7.d.mts} +1 -1
  228. package/dist/{request.d-B928QjWy.d.ts → request.d-Dgln8tuI.d.ts} +1 -1
  229. package/dist/request.d.mts +6 -4
  230. package/dist/request.d.ts +6 -4
  231. package/dist/{route-rendering.d-DoEe_w9t.d.ts → route-rendering.d-CUylZKJA.d.ts} +1 -1
  232. package/dist/{route-rendering.d-NIHQeb4m.d.mts → route-rendering.d-Ds0BfwQi.d.mts} +1 -1
  233. package/dist/{router.d-DYnRHQwz.d.ts → router.d-B56rMOFm.d.ts} +1 -1
  234. package/dist/{router.d-B8PkJSGp.d.mts → router.d-CFPcbqzc.d.mts} +1 -1
  235. package/dist/{routes.d-uUBZyWoK.d.ts → routes.d-9GFFNioh.d.ts} +1 -1
  236. package/dist/{routes.d-DgZ_jgGG.d.mts → routes.d-CrEy0lJS.d.mts} +1 -1
  237. package/dist/routes.d.mts +5 -3
  238. package/dist/routes.d.ts +5 -3
  239. package/dist/{rsc-pipeline-7K5H2RPH.cjs → rsc-pipeline-3T7V6OUT.cjs} +10 -9
  240. package/dist/{rsc-pipeline-4OJ5ZQNZ.mjs → rsc-pipeline-GA4AQWZI.mjs} +9 -8
  241. package/dist/{runtime-X52Q7JFR.cjs → runtime-REUTNTI5.cjs} +20 -20
  242. package/dist/{runtime-U7O3HZOZ.mjs → runtime-ZYCKKY7L.mjs} +12 -12
  243. package/dist/{runtime.d-BxQIzwfy.d.mts → runtime.d-DLRO-ExG.d.mts} +1 -1
  244. package/dist/{runtime.d-DP7mEkEF.d.ts → runtime.d-H7k9hOQE.d.ts} +1 -1
  245. package/dist/server-http.d-rAe7lAQc.d.mts +70 -0
  246. package/dist/server-http.d-rAe7lAQc.d.ts +70 -0
  247. package/dist/server-plugins.d.mts +6 -4
  248. package/dist/server-plugins.d.ts +6 -4
  249. package/dist/server.cjs +46 -44
  250. package/dist/server.d-C5FFrZAo.d.ts +57 -0
  251. package/dist/server.d-DgC8xew5.d.mts +57 -0
  252. package/dist/server.d.mts +13 -11
  253. package/dist/server.d.ts +13 -11
  254. package/dist/server.mjs +28 -26
  255. package/dist/{spa-router.d-DsFDHTsv.d.ts → spa-router.d-Dr7oanhl.d.ts} +2 -2
  256. package/dist/{spa-router.d-BgHPVMhz.d.mts → spa-router.d-g4CzhEH1.d.mts} +2 -2
  257. package/dist/testing.d.mts +5 -3
  258. package/dist/testing.d.ts +5 -3
  259. package/dist/types.d-xCIhyjOq.d.mts +233 -0
  260. package/dist/types.d-xCIhyjOq.d.ts +233 -0
  261. package/dist/{utils.d-zxAVcf_V.d.ts → utils.d-BxxyDEb8.d.ts} +1 -1
  262. package/dist/{utils.d-BKyKDBR1.d.mts → utils.d-HIla3pD_.d.mts} +1 -1
  263. package/dist/version.cjs +2 -2
  264. package/dist/version.mjs +1 -1
  265. package/dist/vite.cjs +20 -20
  266. package/dist/vite.d.mts +10 -8
  267. package/dist/vite.d.ts +10 -8
  268. package/dist/vite.mjs +19 -19
  269. package/dist/workflows.cjs +2 -2
  270. package/dist/workflows.d.mts +121 -1
  271. package/dist/workflows.d.ts +121 -1
  272. package/dist/workflows.mjs +1 -1
  273. package/package.json +7 -2
  274. package/dist/analyzer-KVZGVY5Q.cjs +0 -16
  275. package/dist/chunk-CLFEQGET.cjs +0 -60
  276. package/dist/chunk-MK5E44WP.mjs +0 -60
  277. package/dist/layers-DMRXRL7F.cjs +0 -18
  278. package/dist/node-module-bundle-7JHPPF6B.mjs +0 -11
  279. package/dist/node-module-bundle-YJGYBOGK.cjs +0 -11
  280. package/dist/workflows.d-CRMzQZ3k.d.mts +0 -188
  281. package/dist/workflows.d-CRMzQZ3k.d.ts +0 -188
@@ -1,3 +1,6 @@
1
+ import {
2
+ hasFarmServerRuntimePlugins
3
+ } from "./chunk-QYNZ3CTI.mjs";
1
4
  import {
2
5
  FARM_MOBILE_CLIENT_ENTRY_NAME,
3
6
  FARM_MOBILE_SHELL_CLIENT_PLACEHOLDER,
@@ -7,6 +10,9 @@ import {
7
10
  hasFarmMobileClientEntry,
8
11
  removeFarmMobileClientManifest
9
12
  } from "./chunk-TM2E623I.mjs";
13
+ import {
14
+ loadFarmProductionVite
15
+ } from "./chunk-PSUYE5HR.mjs";
10
16
  import {
11
17
  FARM_COMPILE_CACHE_DIR,
12
18
  FARM_DESKTOP_ENV_MODULE_FILE,
@@ -17,15 +23,13 @@ import {
17
23
  createFarmBunServerEntry,
18
24
  createFarmCompileCacheLauncher,
19
25
  createFarmNodeServerEntry,
26
+ createReactProductionModePlugin,
20
27
  withProductionNodeEnv
21
- } from "./chunk-5FE5YT2N.mjs";
22
- import {
23
- loadFarmProductionVite
24
- } from "./chunk-PSUYE5HR.mjs";
28
+ } from "./chunk-ZZGQD3LL.mjs";
25
29
  import {
26
30
  collectFarmNativeServerFns,
27
31
  findFarmNativeScreenFiles
28
- } from "./chunk-HP2DQGQH.mjs";
32
+ } from "./chunk-MNJDNTGO.mjs";
29
33
  import {
30
34
  generateNativeMCPPluginSource
31
35
  } from "./chunk-KQH2COEJ.mjs";
@@ -36,9 +40,10 @@ import {
36
40
  assertFarmDocsAdapterServesNoGuardedPages,
37
41
  compileFarmDocsAdapterEdgeManifest,
38
42
  createFarmDocsAPIHandler,
43
+ farmDocsAdapterServesGuardedPages,
39
44
  hasFarmDocsRuntimeAdapter,
40
45
  listFarmDocsAdapterPages
41
- } from "./chunk-E6CD45JK.mjs";
46
+ } from "./chunk-A3T445WK.mjs";
42
47
  import {
43
48
  FARM_DOCS_LAST_MODIFIED_MANIFEST,
44
49
  createFarmDocsHandler,
@@ -47,18 +52,22 @@ import {
47
52
  getFarmDocsMarkdownPath,
48
53
  getFarmDocsRoots,
49
54
  getFarmDocsRouteTypeEntries,
55
+ listFarmDocsBuiltInPrerenderPages,
50
56
  loadFarmDocsPage,
51
57
  resolveFarmDocsContentDir,
52
58
  toFarmDocsMarkdownPage
53
- } from "./chunk-AQDLVHNF.mjs";
59
+ } from "./chunk-5FBZJJGA.mjs";
54
60
  import {
55
61
  generateFarmDocsSearchClientRuntime,
56
62
  isFarmDocsSearchEnabled,
57
63
  resolveFarmDocsSearchClientModule
58
64
  } from "./chunk-ALEUMLJN.mjs";
65
+ import {
66
+ CDN_CACHE_CONTROL_HEADERS
67
+ } from "./chunk-JL2YW5KX.mjs";
59
68
  import {
60
69
  FARM_PRERENDER_ENV
61
- } from "./chunk-JVM3DKZE.mjs";
70
+ } from "./chunk-KDO6T6OB.mjs";
62
71
  import {
63
72
  loadFarmDocsEngine
64
73
  } from "./chunk-VE3FWJBO.mjs";
@@ -67,17 +76,19 @@ import {
67
76
  getDeployTargetForPreset,
68
77
  hasCustomFarmRouteContext,
69
78
  resolveDeployOutputPath
70
- } from "./chunk-WDD5CTZW.mjs";
79
+ } from "./chunk-NT4W4H52.mjs";
71
80
  import {
72
81
  resolveFarmInstrumentationFile
73
- } from "./chunk-N35YPV4N.mjs";
82
+ } from "./chunk-57QAQU4F.mjs";
74
83
  import {
75
84
  resolveFarmInstrumentationRuntime
76
85
  } from "./chunk-WNDAISB7.mjs";
77
86
  import {
78
87
  DEFAULT_NOT_FOUND_STYLES,
79
88
  FARM_LAYOUT_ELEMENT_CLIENT_SOURCE,
89
+ FARM_NAVIGATION_SCRIPT_SOURCE,
80
90
  FARM_NAVIGATION_STREAM_READER_SOURCE,
91
+ FARM_REFRESH_FIELDS_SOURCE,
81
92
  FARM_SERVER_TREE_LAYOUT_CLIENT_SOURCE,
82
93
  SHARP_INSTALL_HINT,
83
94
  canBootFarmIslandsClient,
@@ -85,8 +96,10 @@ import {
85
96
  createFarmApp,
86
97
  createFarmSourceAlias,
87
98
  createFarmThemeCssPlugin,
99
+ exactIdPattern,
88
100
  farmDocsClientConfigPlugin,
89
101
  farmFontImportsPlugin,
102
+ fileNamePattern,
90
103
  generateClientCachePersistenceCode,
91
104
  generateFarmIntegrationProviderClientCode,
92
105
  generateFarmIntegrationProviderServerModules,
@@ -99,7 +112,7 @@ import {
99
112
  resolveFarmImageServerRuntime,
100
113
  resolveFarmNotFoundComponentPath,
101
114
  resolveFarmRouteRootStrategy
102
- } from "./chunk-WGHY3OL5.mjs";
115
+ } from "./chunk-4UAQB5LB.mjs";
103
116
  import {
104
117
  generateFarmClientPluginEntryCode,
105
118
  loadTailwindVitePlugin
@@ -111,7 +124,7 @@ import {
111
124
  generateFarmTypeArtifacts,
112
125
  readRouteRenderingDirectiveFromFile,
113
126
  resolveRouteRenderingConfigFromFile
114
- } from "./chunk-6YBYX4K4.mjs";
127
+ } from "./chunk-G7NBPP7H.mjs";
115
128
  import {
116
129
  HOISTED_HEAD_ELEMENT,
117
130
  appMiddlewareMayHandlePath,
@@ -138,7 +151,7 @@ import {
138
151
  listFarmBuiltInRoutePaths,
139
152
  resolveFarmApiCatalogInput,
140
153
  resolveFarmAppManifestInput
141
- } from "./chunk-HRPTMX5C.mjs";
154
+ } from "./chunk-VFNAK6A5.mjs";
142
155
  import {
143
156
  FARM_DEFAULT_MCP_PATH,
144
157
  createFarmDefaultMCPServer,
@@ -146,7 +159,7 @@ import {
146
159
  } from "./chunk-K6SXMVXO.mjs";
147
160
  import {
148
161
  isFarmPreviewDeploymentEnvironment
149
- } from "./chunk-V5MQMQ2P.mjs";
162
+ } from "./chunk-T5XFZQCL.mjs";
150
163
  import {
151
164
  FARM_NATIVE_SERVER_FN_PLUGIN
152
165
  } from "./chunk-L4RTTTVE.mjs";
@@ -164,7 +177,7 @@ import {
164
177
  usePackageClientBoundaryCacheFile,
165
178
  usesFarmServerTree,
166
179
  withPackageClientBoundaryCache
167
- } from "./chunk-GTV2ABO7.mjs";
180
+ } from "./chunk-WPB67LE5.mjs";
168
181
  import {
169
182
  generateFarmDocsAdapterClientRuntime,
170
183
  getFarmDocsAdapterConfigModule
@@ -174,8 +187,9 @@ import {
174
187
  toFarmDocsPublicFontAssets
175
188
  } from "./chunk-NRNAHZ57.mjs";
176
189
  import {
190
+ nitroRouteRulesBelowBasePath,
177
191
  routeRulesToNitroRouteRules
178
- } from "./chunk-724MGMIL.mjs";
192
+ } from "./chunk-R2ZHU37O.mjs";
179
193
  import {
180
194
  applyFarmCspHashesToHtml,
181
195
  createFarmCspNonce
@@ -185,7 +199,7 @@ import {
185
199
  } from "./chunk-4QENVMG7.mjs";
186
200
  import {
187
201
  getFarmAppDirectories
188
- } from "./chunk-52Y3C3HG.mjs";
202
+ } from "./chunk-E7VF3LQ5.mjs";
189
203
  import {
190
204
  REACT_RENDERER,
191
205
  getFarmRendererCapabilities,
@@ -210,7 +224,7 @@ import {
210
224
  } from "./chunk-N33DLJBC.mjs";
211
225
  import {
212
226
  isFarmMarkdownPageFile
213
- } from "./chunk-3T5TLFCQ.mjs";
227
+ } from "./chunk-HEJM46HQ.mjs";
214
228
  import {
215
229
  resolveFarmMdxComponentsModulePath,
216
230
  resolveMdxConfig
@@ -218,10 +232,13 @@ import {
218
232
  import {
219
233
  getFarmMarkdownAlternatePath
220
234
  } from "./chunk-IFR74W6S.mjs";
235
+ import {
236
+ withPlainDiagnostics
237
+ } from "./chunk-MGKWYPE3.mjs";
221
238
  import {
222
239
  applyFarmWorkflowVercelCrons,
223
240
  prepareFarmWorkflowsForNitro
224
- } from "./chunk-5TA63JD3.mjs";
241
+ } from "./chunk-MGZVDX4R.mjs";
225
242
  import {
226
243
  getFarmIntegrationPluginServerRuntime,
227
244
  getIntegrationProviders
@@ -266,14 +283,19 @@ import {
266
283
  } from "./chunk-2I6PUKWJ.mjs";
267
284
  import {
268
285
  FARM_VERSION
269
- } from "./chunk-H37MDCPR.mjs";
286
+ } from "./chunk-F6CMGWAL.mjs";
287
+ import {
288
+ normalizeFarmTrailingSlashPathname
289
+ } from "./chunk-YVPX5PI5.mjs";
270
290
  import {
271
- getFarmPresetRuntime
272
- } from "./chunk-F7JKVHU2.mjs";
291
+ getFarmPresetRuntime,
292
+ resolveCloudflareProcessEnvFlags
293
+ } from "./chunk-NVOMQLI2.mjs";
273
294
  import {
274
295
  _runWithFarmCspNonce
275
296
  } from "./chunk-5OFNUETM.mjs";
276
297
  import {
298
+ applyFarmBasePath,
277
299
  normalizeFarmBasePath,
278
300
  stripFarmBasePath
279
301
  } from "./chunk-SF3JB56B.mjs";
@@ -282,7 +304,7 @@ import {
282
304
  } from "./chunk-AYP2YFVN.mjs";
283
305
 
284
306
  // src/build/index.ts
285
- import path12 from "path";
307
+ import path13 from "path";
286
308
  import { existsSync as existsSync3 } from "fs";
287
309
 
288
310
  // src/nitro/universal-build.ts
@@ -347,10 +369,10 @@ async function resolveHashedClientJsSrc(clientOutputDir) {
347
369
 
348
370
  // src/nitro/universal-build.ts
349
371
  import os from "os";
350
- import path11 from "path";
372
+ import path12 from "path";
351
373
  import { constants as fsConstants, existsSync as existsSync2, readFileSync, realpathSync as realpathSync2, statSync } from "fs";
352
374
  import { fileURLToPath } from "url";
353
- import { builtinModules, createRequire } from "module";
375
+ import { builtinModules, createRequire as createRequire2 } from "module";
354
376
  import { isDeepStrictEqual } from "util";
355
377
 
356
378
  // src/docs/compiler.ts
@@ -943,12 +965,13 @@ function createFarmVercelImmutableAssetRoute() {
943
965
  };
944
966
  }
945
967
  function buildFarmVercelRoutes(options) {
946
- const { presetRoutes, runtimeRoutes } = options;
968
+ const { presetRoutes, runtimeRoutes, middlewareRoutes = [] } = options;
947
969
  const filesystemIndex = presetRoutes.findIndex((route) => route.handle === "filesystem");
948
970
  const sourceRoutes = filesystemIndex >= 0 ? presetRoutes.slice(0, filesystemIndex) : [];
949
971
  const preservedSourceRoutes = sourceRoutes.filter((route) => route.continue !== true);
950
972
  return [
951
973
  ...preservedSourceRoutes,
974
+ ...middlewareRoutes,
952
975
  createFarmVercelImmutableAssetRoute(),
953
976
  { handle: "filesystem" },
954
977
  ...runtimeRoutes,
@@ -1216,14 +1239,17 @@ function farmStripPlatformConfigPlugin(configFiles) {
1216
1239
  // Before the TypeScript transform, so its import elision also drops imports only the
1217
1240
  // removed block used (`readFileSync` for a version, say).
1218
1241
  enforce: "pre",
1219
- async transform(code, id) {
1220
- const file = id.split("?", 1)[0];
1221
- if (!files.has(path9.resolve(file)) && !files.has(realPath(file))) return null;
1222
- const { parseAst } = await import("rolldown/parseAst");
1223
- const extension = path9.extname(file).slice(1);
1224
- const lang = /^[cm]?tsx?$/.test(extension) ? extension.endsWith("x") ? "tsx" : "ts" : extension.endsWith("x") ? "jsx" : "js";
1225
- const stripped = stripPlatformConfigSource(code, (source) => parseAst(source, { lang }));
1226
- return stripped === null ? null : { code: stripped, map: null };
1242
+ transform: {
1243
+ filter: { id: fileNamePattern(configFiles) },
1244
+ async handler(code, id) {
1245
+ const file = id.split("?", 1)[0];
1246
+ if (!files.has(path9.resolve(file)) && !files.has(realPath(file))) return null;
1247
+ const { parseAst } = await import("rolldown/parseAst");
1248
+ const extension = path9.extname(file).slice(1);
1249
+ const lang = /^[cm]?tsx?$/.test(extension) ? extension.endsWith("x") ? "tsx" : "ts" : extension.endsWith("x") ? "jsx" : "js";
1250
+ const stripped = stripPlatformConfigSource(code, (source) => parseAst(source, { lang }));
1251
+ return stripped === null ? null : { code: stripped, map: null };
1252
+ }
1227
1253
  }
1228
1254
  };
1229
1255
  }
@@ -1306,6 +1332,11 @@ function readStaticMiddlewareConfig(program) {
1306
1332
  for (const property of init.properties) {
1307
1333
  if (property.type !== "Property" || property.computed) return "unknown";
1308
1334
  const key = property.key?.name ?? property.key?.value;
1335
+ if (key === "runtime") {
1336
+ const runtime = literalMatcher(unwrap(property.value));
1337
+ if (runtime === "edge" || runtime === "nodejs") config.runtime = runtime;
1338
+ continue;
1339
+ }
1309
1340
  if (key !== "matcher" && key !== "exclude") continue;
1310
1341
  const matchers = literalMatchers(unwrap(property.value));
1311
1342
  if (!matchers) return "unknown";
@@ -1328,6 +1359,164 @@ async function readMiddlewareFileConfig(filePath) {
1328
1359
  }
1329
1360
  }
1330
1361
 
1362
+ // src/nitro/vercel-edge-middleware.ts
1363
+ import { createRequire, isBuiltin } from "module";
1364
+ import path11 from "path";
1365
+ import { gzipSync } from "zlib";
1366
+ var FARM_VERCEL_EDGE_MIDDLEWARE_FUNCTION = "_farm_middleware";
1367
+ var FARM_VERCEL_EDGE_NOT_FOUND_PATH = "/__farm/not-found";
1368
+ var EDGE_NODE_MODULES = /* @__PURE__ */ new Set(["async_hooks", "events", "buffer", "assert", "util"]);
1369
+ var EDGE_FUNCTION_SIZE_WARNING_BYTES = 1024 * 1024;
1370
+ function farmTargetRunsEdgeMiddleware(preset) {
1371
+ return preset === "vercel";
1372
+ }
1373
+ function isFarmEdgeMiddlewareRoute(route) {
1374
+ return typeof route.config === "object" && route.config?.runtime === "edge";
1375
+ }
1376
+ function escapeRegExp2(value) {
1377
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1378
+ }
1379
+ function toFarmVercelEdgeGuardedUrls(pathnames, basePath) {
1380
+ return [
1381
+ ...new Set(pathnames.flatMap((pathname) => [pathname, applyFarmBasePath(pathname, basePath)]))
1382
+ ];
1383
+ }
1384
+ function createFarmVercelEdgeMiddlewareRoute(pathnames, basePath = "/") {
1385
+ const publicPaths = toFarmVercelEdgeGuardedUrls(pathnames, basePath);
1386
+ const alternatives = publicPaths.map((pathname) => {
1387
+ const trimmed = pathname.replace(/\/+$/, "");
1388
+ return trimmed ? `${escapeRegExp2(trimmed)}(?:/|/index\\.html|\\.html)?` : "/(?:index\\.html)?";
1389
+ });
1390
+ return {
1391
+ src: `^(?:${alternatives.join("|")})$`,
1392
+ middlewarePath: FARM_VERCEL_EDGE_MIDDLEWARE_FUNCTION,
1393
+ middlewareRawSrc: publicPaths,
1394
+ continue: true
1395
+ };
1396
+ }
1397
+ function generateFarmVercelEdgeMiddlewareEntry(routes, config, guardedPages) {
1398
+ const imports = routes.map(
1399
+ (route, index) => `import * as farmEdgeMiddleware${index} from ${JSON.stringify(route.filePath.replace(/\\/g, "/"))};`
1400
+ );
1401
+ const modules = routes.map(
1402
+ (route, index) => ` { path: ${JSON.stringify(route.path)}, filePath: ${JSON.stringify(route.filePath)}, module: farmEdgeMiddleware${index} },`
1403
+ );
1404
+ return `import { createFarmVercelEdgeMiddleware } from "@farm.js/core/internal/vercel-edge-middleware";
1405
+ ${imports.join("\n")}
1406
+
1407
+ export default createFarmVercelEdgeMiddleware({
1408
+ modules: [
1409
+ ${modules.join("\n")}
1410
+ ],
1411
+ i18n: ${JSON.stringify(config.i18n)},
1412
+ server: ${JSON.stringify({ trustProxy: config.server?.trustProxy === true })},
1413
+ apiBasePath: ${JSON.stringify(resolveFarmAPIServerBasePath(config.api))},
1414
+ notFoundPath: ${JSON.stringify(applyFarmBasePath(FARM_VERCEL_EDGE_NOT_FOUND_PATH, config.basePath))},
1415
+ pages: ${JSON.stringify(toFarmVercelEdgeGuardedUrls(guardedPages, config.basePath))},
1416
+ });
1417
+ `;
1418
+ }
1419
+ async function resolveFarmCoreDir(root, fs4) {
1420
+ const runtimeEntry = createRequire(path11.join(root, "package.json")).resolve(
1421
+ "@farm.js/core/internal/vercel-edge-middleware"
1422
+ );
1423
+ return fs4.realpath(path11.resolve(path11.dirname(runtimeEntry), "..", ".."));
1424
+ }
1425
+ function edgeNodeModulesPlugin(coreDir, unsupported) {
1426
+ const streamStub = "\0farm-edge-node-stream";
1427
+ const corePrefix = coreDir + path11.sep;
1428
+ return {
1429
+ name: "farm-vercel-edge-node-modules",
1430
+ resolveId(source, importer) {
1431
+ if (!isBuiltin(source)) return null;
1432
+ const name = source.replace(/^node:/, "").split("/")[0];
1433
+ if (EDGE_NODE_MODULES.has(name)) return { id: `node:${name}`, external: true };
1434
+ if (name === "stream" && importer && path11.resolve(importer).startsWith(corePrefix)) {
1435
+ return streamStub;
1436
+ }
1437
+ unsupported.add(`${source} (imported by ${importer ?? "the entry"})`);
1438
+ return { id: source, external: true };
1439
+ },
1440
+ load(id) {
1441
+ if (id !== streamStub) return null;
1442
+ return `export const Readable = { toWeb() { throw new Error("[Farm.js] Node streams are not available in Vercel edge middleware."); } };`;
1443
+ }
1444
+ };
1445
+ }
1446
+ async function writeFarmVercelEdgeMiddlewareFunction(options) {
1447
+ const { root, outputDir, buildDir, config, routes, guardedPages, fs: fs4 } = options;
1448
+ const functionDir = path11.join(
1449
+ outputDir,
1450
+ "functions",
1451
+ `${FARM_VERCEL_EDGE_MIDDLEWARE_FUNCTION}.func`
1452
+ );
1453
+ const entryPath = path11.join(buildDir, "vercel-edge-middleware-entry.mjs");
1454
+ await fs4.mkdir(path11.dirname(entryPath), { recursive: true });
1455
+ await fs4.writeFile(
1456
+ entryPath,
1457
+ generateFarmVercelEdgeMiddlewareEntry(routes, config, guardedPages)
1458
+ );
1459
+ const unsupported = /* @__PURE__ */ new Set();
1460
+ const coreDir = await resolveFarmCoreDir(root, fs4);
1461
+ const { rolldown } = await import("rolldown");
1462
+ let code;
1463
+ try {
1464
+ const bundle = await rolldown({
1465
+ cwd: root,
1466
+ input: entryPath,
1467
+ platform: "browser",
1468
+ logLevel: "silent",
1469
+ plugins: [edgeNodeModulesPlugin(coreDir, unsupported)],
1470
+ resolve: {
1471
+ alias: createFarmSourceAlias(root, config.srcDir),
1472
+ conditionNames: ["edge-light", "worker", "browser", "import", "module", "default"]
1473
+ },
1474
+ transform: {
1475
+ target: "es2022",
1476
+ define: { "process.env.NODE_ENV": JSON.stringify("production") }
1477
+ }
1478
+ });
1479
+ try {
1480
+ const { output } = await bundle.generate({
1481
+ format: "esm",
1482
+ codeSplitting: false,
1483
+ minify: true
1484
+ });
1485
+ code = output[0].code;
1486
+ } finally {
1487
+ await bundle.close();
1488
+ }
1489
+ } catch (error) {
1490
+ throw withPlainDiagnostics(error);
1491
+ } finally {
1492
+ await fs4.rm(entryPath, { force: true });
1493
+ }
1494
+ if (unsupported.size > 0) {
1495
+ throw new Error(
1496
+ `[Farm.js] runtime: "edge" middleware runs in Vercel's Edge runtime, which does not provide these Node modules:
1497
+ ` + [...unsupported].map((entry) => ` - ${entry}`).join("\n") + `
1498
+ Remove them from the middleware (Edge provides ${[...EDGE_NODE_MODULES].join(", ")}), or remove runtime: "edge" so the middleware runs in the server and its pages render on request.`
1499
+ );
1500
+ }
1501
+ await fs4.rm(functionDir, { recursive: true, force: true });
1502
+ await fs4.mkdir(functionDir, { recursive: true });
1503
+ await fs4.writeFile(path11.join(functionDir, "index.js"), code);
1504
+ await fs4.writeFile(
1505
+ path11.join(functionDir, ".vc-config.json"),
1506
+ `${JSON.stringify({ runtime: "edge", entrypoint: "index.js" }, null, 2)}
1507
+ `
1508
+ );
1509
+ const gzippedBytes = gzipSync(code).length;
1510
+ if (gzippedBytes > EDGE_FUNCTION_SIZE_WARNING_BYTES) {
1511
+ logger.warn(
1512
+ `Vercel edge middleware is ${(gzippedBytes / 1024 / 1024).toFixed(2)} MB gzipped, over the Hobby plan's 1 MB Edge function limit (Pro allows 2 MB, Enterprise 4 MB).`
1513
+ );
1514
+ }
1515
+ logger.info(
1516
+ `\u{1F6E1}\uFE0F Vercel edge middleware: ${routes.length} middleware file(s) guard their prerendered pages before the CDN serves them`
1517
+ );
1518
+ }
1519
+
1331
1520
  // src/nitro/universal-build.ts
1332
1521
  var FARM_NATIVE_STYLESHEETS_PLACEHOLDER = "__FARM_NATIVE_STYLESHEETS__";
1333
1522
  async function readFarmNativeStylesheets(clientOutputDir, clientCssHref) {
@@ -1335,7 +1524,7 @@ async function readFarmNativeStylesheets(clientOutputDir, clientCssHref) {
1335
1524
  try {
1336
1525
  return {
1337
1526
  [clientCssHref]: await fs4.readFile(
1338
- path11.join(clientOutputDir, clientCssHref.slice(1)),
1527
+ path12.join(clientOutputDir, clientCssHref.slice(1)),
1339
1528
  "utf8"
1340
1529
  )
1341
1530
  };
@@ -1350,18 +1539,18 @@ function preloadFarmNitroBuilder() {
1350
1539
  );
1351
1540
  }
1352
1541
  var _filename = typeof import.meta.url !== "undefined" ? fileURLToPath(import.meta.url) : "";
1353
- var _dirname = path11.dirname(_filename);
1542
+ var _dirname = path12.dirname(_filename);
1354
1543
  function findFarmCoreRoot(from) {
1355
- let dir = path11.dirname(from);
1356
- while (dir !== path11.dirname(dir)) {
1357
- const manifest = path11.join(dir, "package.json");
1544
+ let dir = path12.dirname(from);
1545
+ while (dir !== path12.dirname(dir)) {
1546
+ const manifest = path12.join(dir, "package.json");
1358
1547
  if (existsSync2(manifest)) {
1359
1548
  try {
1360
1549
  if (JSON.parse(readFileSync(manifest, "utf8")).name === "@farm.js/core") return dir;
1361
1550
  } catch {
1362
1551
  }
1363
1552
  }
1364
- dir = path11.dirname(dir);
1553
+ dir = path12.dirname(dir);
1365
1554
  }
1366
1555
  return null;
1367
1556
  }
@@ -1371,16 +1560,16 @@ function toModulePath(file) {
1371
1560
  return process.platform === "win32" ? normalized.toLowerCase() : normalized;
1372
1561
  }
1373
1562
  function findInstalledPackageDir(name, from) {
1374
- for (let dir = from; ; dir = path11.dirname(dir)) {
1375
- const candidate = path11.join(dir, "node_modules", name);
1376
- if (existsSync2(path11.join(candidate, "package.json"))) {
1563
+ for (let dir = from; ; dir = path12.dirname(dir)) {
1564
+ const candidate = path12.join(dir, "node_modules", name);
1565
+ if (existsSync2(path12.join(candidate, "package.json"))) {
1377
1566
  try {
1378
1567
  return realpathSync2(candidate);
1379
1568
  } catch {
1380
1569
  return null;
1381
1570
  }
1382
1571
  }
1383
- if (dir === path11.dirname(dir)) return null;
1572
+ if (dir === path12.dirname(dir)) return null;
1384
1573
  }
1385
1574
  }
1386
1575
  function collectFarmDependencyDirs(root) {
@@ -1391,7 +1580,7 @@ function collectFarmDependencyDirs(root) {
1391
1580
  seen.add(dir);
1392
1581
  let manifest;
1393
1582
  try {
1394
- manifest = JSON.parse(readFileSync(path11.join(dir, "package.json"), "utf8"));
1583
+ manifest = JSON.parse(readFileSync(path12.join(dir, "package.json"), "utf8"));
1395
1584
  } catch {
1396
1585
  return;
1397
1586
  }
@@ -1402,7 +1591,7 @@ function collectFarmDependencyDirs(root) {
1402
1591
  if (farmCoreRoot) visit(realpathSync2(farmCoreRoot));
1403
1592
  queue.push({ name: "@farm.js/core", from: root });
1404
1593
  try {
1405
- const manifest = JSON.parse(readFileSync(path11.join(root, "package.json"), "utf8"));
1594
+ const manifest = JSON.parse(readFileSync(path12.join(root, "package.json"), "utf8"));
1406
1595
  for (const field of ["dependencies", "devDependencies"]) {
1407
1596
  for (const name of Object.keys(manifest[field] ?? {})) {
1408
1597
  if (name.startsWith("@farm.js/")) queue.push({ name, from: root });
@@ -1469,17 +1658,17 @@ var FARM_SSR_PACKAGE_IMPORT = "#farm-ssr-entry";
1469
1658
  var FARM_SSR_OUTPUT_DIR = "farm-ssr";
1470
1659
  var FARM_CLIENT_BUILD_TARGET = ["es2020", "edge88", "firefox78", "chrome87", "safari14"];
1471
1660
  function resolveNitroRuntimeDependency(root, specifier) {
1472
- return createRequire(resolveNitroPackageEntry(root)).resolve(specifier).split(path11.sep).join("/");
1661
+ return createRequire2(resolveNitroPackageEntry(root)).resolve(specifier).split(path12.sep).join("/");
1473
1662
  }
1474
1663
  function resolveNitroInternalRuntimeAliases(root) {
1475
1664
  const nitroEntry = resolveNitroPackageEntry(root);
1476
- const runtimeDir = path11.dirname(nitroEntry);
1477
- const nitroRequire = createRequire(nitroEntry);
1665
+ const runtimeDir = path12.dirname(nitroEntry);
1666
+ const nitroRequire = createRequire2(nitroEntry);
1478
1667
  return {
1479
1668
  ...Object.fromEntries(
1480
1669
  ["app", "error/hooks", "runtime-config", "shutdown", "task"].map((moduleName) => [
1481
1670
  `#nitro/runtime/${moduleName}`,
1482
- path11.join(runtimeDir, "internal", `${moduleName}.mjs`).split(path11.sep).join("/")
1671
+ path12.join(runtimeDir, "internal", `${moduleName}.mjs`).split(path12.sep).join("/")
1483
1672
  ])
1484
1673
  ),
1485
1674
  // Farm's generated workflow and cron wrappers live under `.farm/` and
@@ -1488,7 +1677,7 @@ function resolveNitroInternalRuntimeAliases(root) {
1488
1677
  ...Object.fromEntries(
1489
1678
  ["nitro/app", "nitro/h3", "nitro/task"].map((specifier) => [
1490
1679
  specifier,
1491
- nitroRequire.resolve(specifier).split(path11.sep).join("/")
1680
+ nitroRequire.resolve(specifier).split(path12.sep).join("/")
1492
1681
  ])
1493
1682
  )
1494
1683
  };
@@ -1499,7 +1688,7 @@ function createPrerenderRuntimeResolverPlugin(root, resolveNitroEntry = resolveN
1499
1688
  name: "farm-prerender-runtime-resolver",
1500
1689
  async resolveId(id, _importer, options) {
1501
1690
  if (options.custom?.farmPrerenderRuntimeResolve) return null;
1502
- if (id.startsWith("\0") || id.startsWith(".") || id.startsWith("#") || id.startsWith("virtual:") || path11.isAbsolute(id) || NODE_BUILTIN_MODULES.has(id)) {
1691
+ if (id.startsWith("\0") || id.startsWith(".") || id.startsWith("#") || id.startsWith("virtual:") || path12.isAbsolute(id) || NODE_BUILTIN_MODULES.has(id)) {
1503
1692
  return null;
1504
1693
  }
1505
1694
  if (nitroEntry === void 0) {
@@ -1522,10 +1711,10 @@ function createFarmStorageModuleRegistration(config) {
1522
1711
  const modules = _collectFarmStorageModules(config.storage);
1523
1712
  if (modules.length === 0) return "";
1524
1713
  const root = config.root || process.cwd();
1525
- const projectRequire = createRequire(path11.join(root, "package.json"));
1714
+ const projectRequire = createRequire2(path12.join(root, "package.json"));
1526
1715
  let runtimeRequire = projectRequire;
1527
1716
  try {
1528
- runtimeRequire = createRequire(projectRequire.resolve("@farm.js/core"));
1717
+ runtimeRequire = createRequire2(projectRequire.resolve("@farm.js/core"));
1529
1718
  } catch {
1530
1719
  }
1531
1720
  const loaders = [];
@@ -1549,10 +1738,10 @@ ${loaders.join("\n")}
1549
1738
  });` : "";
1550
1739
  }
1551
1740
  function resolveNitroPackageEntry(root) {
1552
- const projectRequire = createRequire(path11.join(root, "package.json"));
1741
+ const projectRequire = createRequire2(path12.join(root, "package.json"));
1553
1742
  let runtimeRequire = projectRequire;
1554
1743
  try {
1555
- runtimeRequire = createRequire(projectRequire.resolve("@farm.js/core"));
1744
+ runtimeRequire = createRequire2(projectRequire.resolve("@farm.js/core"));
1556
1745
  } catch {
1557
1746
  }
1558
1747
  return runtimeRequire.resolve("nitro");
@@ -1619,7 +1808,7 @@ function createFarmReactWebServerAlias(hasEdgeBuild) {
1619
1808
  }
1620
1809
  function hasReactDomEdgeServerBuild(root) {
1621
1810
  try {
1622
- createRequire(path11.join(root, "package.json")).resolve("react-dom/server.edge");
1811
+ createRequire2(path12.join(root, "package.json")).resolve("react-dom/server.edge");
1623
1812
  return true;
1624
1813
  } catch {
1625
1814
  return false;
@@ -1648,23 +1837,11 @@ function isNitroRollupExternal(id) {
1648
1837
  return NODE_BUILTIN_MODULES.has(id) || NITRO_EXTERNAL_MODULES.has(id) || normalizedId.startsWith(".prisma/") || normalizedId.includes("/node_modules/@prisma/client/") || normalizedId.includes("/node_modules/.prisma/client/");
1649
1838
  }
1650
1839
  var FARM_METADATA_IMAGE_WASM_PREFIX = "\0farm-metadata-image-wasm:";
1651
- function createReactProductionModePlugin() {
1652
- const nodeEnvExpression = ["process", "env", "NODE_ENV"].join(".");
1653
- return {
1654
- name: "farm-react-production-mode",
1655
- transform(code, id) {
1656
- const normalizedId = id.replace(/\\/g, "/");
1657
- const isReactRuntime = normalizedId.includes("/node_modules/react/") || normalizedId.includes("/node_modules/react-dom/");
1658
- if (!isReactRuntime || !code.includes(nodeEnvExpression)) return null;
1659
- return { code: code.split(nodeEnvExpression).join('"production"'), map: null };
1660
- }
1661
- };
1662
- }
1663
1840
  var FARM_OMITTED_METADATA_IMAGE_RUNTIME_ID = "\0farm-omitted-metadata-image-runtime";
1664
1841
  function isFarmCoreModule(file) {
1665
- let dir = path11.dirname(file.split("?", 1)[0]);
1666
- while (dir !== path11.dirname(dir)) {
1667
- const manifest = path11.join(dir, "package.json");
1842
+ let dir = path12.dirname(file.split("?", 1)[0]);
1843
+ while (dir !== path12.dirname(dir)) {
1844
+ const manifest = path12.join(dir, "package.json");
1668
1845
  if (existsSync2(manifest)) {
1669
1846
  try {
1670
1847
  return JSON.parse(readFileSync(manifest, "utf8")).name === "@farm.js/core";
@@ -1672,40 +1849,46 @@ function isFarmCoreModule(file) {
1672
1849
  return false;
1673
1850
  }
1674
1851
  }
1675
- dir = path11.dirname(dir);
1852
+ dir = path12.dirname(dir);
1676
1853
  }
1677
1854
  return false;
1678
1855
  }
1679
1856
  function createOmittedMetadataImageRuntimePlugin(externalizeOtherImports) {
1680
1857
  return {
1681
1858
  name: "farm-omitted-metadata-image-runtime",
1682
- resolveId(source, importer) {
1683
- if (source !== "@vercel/og") return null;
1684
- const fromCoreRuntime = importer !== void 0 && isFarmCoreModule(importer) && !/^og\.[cm]?[jt]sx?$/.test(path11.basename(importer.split("?", 1)[0]));
1685
- if (fromCoreRuntime) return FARM_OMITTED_METADATA_IMAGE_RUNTIME_ID;
1686
- return externalizeOtherImports ? { id: source, external: true } : null;
1859
+ resolveId: {
1860
+ filter: { id: exactIdPattern(["@vercel/og"]) },
1861
+ handler(source, importer) {
1862
+ if (source !== "@vercel/og") return null;
1863
+ const fromCoreRuntime = importer !== void 0 && isFarmCoreModule(importer) && !/^og\.[cm]?[jt]sx?$/.test(path12.basename(importer.split("?", 1)[0]));
1864
+ if (fromCoreRuntime) return FARM_OMITTED_METADATA_IMAGE_RUNTIME_ID;
1865
+ return externalizeOtherImports ? { id: source, external: true } : null;
1866
+ }
1687
1867
  },
1688
- load(id) {
1689
- if (id !== FARM_OMITTED_METADATA_IMAGE_RUNTIME_ID) return null;
1690
- return `
1868
+ load: {
1869
+ filter: { id: exactIdPattern([FARM_OMITTED_METADATA_IMAGE_RUNTIME_ID]) },
1870
+ handler(id) {
1871
+ if (id !== FARM_OMITTED_METADATA_IMAGE_RUNTIME_ID) return null;
1872
+ return `
1691
1873
  export class ImageResponse {
1692
1874
  constructor() {
1693
1875
  throw new Error("@vercel/og is not in this server build because the app has no generated metadata image route.");
1694
1876
  }
1695
1877
  }
1696
1878
  `;
1879
+ }
1697
1880
  }
1698
1881
  };
1699
1882
  }
1700
1883
  function readVercelOgManifest(file) {
1701
- let dir = path11.dirname(file.split("?", 1)[0]);
1702
- while (dir !== path11.dirname(dir)) {
1703
- const manifestPath = path11.join(dir, "package.json");
1884
+ let dir = path12.dirname(file.split("?", 1)[0]);
1885
+ while (dir !== path12.dirname(dir)) {
1886
+ const manifestPath = path12.join(dir, "package.json");
1704
1887
  if (existsSync2(manifestPath)) {
1705
1888
  const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
1706
1889
  return manifest.name === "@vercel/og" ? { dir, manifest } : null;
1707
1890
  }
1708
- dir = path11.dirname(dir);
1891
+ dir = path12.dirname(dir);
1709
1892
  }
1710
1893
  return null;
1711
1894
  }
@@ -1713,7 +1896,7 @@ function resolveVercelOgConditionEntry(resolvedId, condition) {
1713
1896
  const vercelOg = readVercelOgManifest(resolvedId);
1714
1897
  const entry = vercelOg?.manifest.exports?.["."]?.[condition];
1715
1898
  const file = typeof entry === "string" ? entry : entry?.default;
1716
- return vercelOg && typeof file === "string" ? path11.join(vercelOg.dir, file) : null;
1899
+ return vercelOg && typeof file === "string" ? path12.join(vercelOg.dir, file) : null;
1717
1900
  }
1718
1901
  function createEdgeMetadataImageRuntimePlugin({
1719
1902
  condition,
@@ -1731,7 +1914,7 @@ function createEdgeMetadataImageRuntimePlugin({
1731
1914
  if (wasm !== "module" || !source.endsWith(".wasm?module") || !importer?.replace(/\\/g, "/").includes("/@vercel/og/")) {
1732
1915
  return null;
1733
1916
  }
1734
- const resolvedPath = path11.resolve(path11.dirname(importer.split("?", 1)[0]), source);
1917
+ const resolvedPath = path12.resolve(path12.dirname(importer.split("?", 1)[0]), source);
1735
1918
  return { id: toPosixPath(resolvedPath), external: "absolute" };
1736
1919
  }
1737
1920
  };
@@ -1746,7 +1929,7 @@ function createVercelOgFontInlinePlugin(runtime = "Cloudflare Workers") {
1746
1929
  return null;
1747
1930
  }
1748
1931
  const inlined = code.replace(VERCEL_OG_FONT_FETCH, (_match, _quote, request) => {
1749
- const encoded = readFileSync(path11.resolve(path11.dirname(file), request)).toString("base64");
1932
+ const encoded = readFileSync(path12.resolve(path12.dirname(file), request)).toString("base64");
1750
1933
  return `Promise.resolve({ arrayBuffer: () => Uint8Array.from(atob(${JSON.stringify(encoded)}), (character) => character.charCodeAt(0)).buffer })`;
1751
1934
  });
1752
1935
  if (inlined !== code) return { code: inlined, map: null };
@@ -1765,7 +1948,7 @@ function createMetadataImageWasmPlugin() {
1765
1948
  return null;
1766
1949
  }
1767
1950
  const requestPath = source.slice(0, -"?module".length);
1768
- const resolvedPath = path11.isAbsolute(requestPath) ? requestPath : path11.resolve(path11.dirname(importer.split("?", 1)[0]), requestPath);
1951
+ const resolvedPath = path12.isAbsolute(requestPath) ? requestPath : path12.resolve(path12.dirname(importer.split("?", 1)[0]), requestPath);
1769
1952
  return `${FARM_METADATA_IMAGE_WASM_PREFIX}${resolvedPath}`;
1770
1953
  },
1771
1954
  load(id) {
@@ -1790,11 +1973,11 @@ function collectSSRExternalPackages(ssrBundle) {
1790
1973
  for (const importId of [...output.imports, ...output.dynamicImports]) {
1791
1974
  const normalizedImportId = importId.replace(/\\/g, "/");
1792
1975
  const normalizedId = normalizedImportId.replace(/^\.\//, "");
1793
- const resolvedRelativeId = normalizedImportId.startsWith("./") || normalizedImportId.startsWith("../") ? path11.posix.normalize(path11.posix.join(path11.posix.dirname(fileName), normalizedImportId)) : null;
1976
+ const resolvedRelativeId = normalizedImportId.startsWith("./") || normalizedImportId.startsWith("../") ? path12.posix.normalize(path12.posix.join(path12.posix.dirname(fileName), normalizedImportId)) : null;
1794
1977
  if (emittedFiles.has(normalizedId) || resolvedRelativeId !== null && emittedFiles.has(resolvedRelativeId) || NODE_BUILTIN_MODULES.has(importId) || importId.startsWith("node:")) {
1795
1978
  continue;
1796
1979
  }
1797
- if (path11.isAbsolute(importId) || /^[A-Za-z]:[\\/]/.test(importId) || importId.startsWith("#") || importId.startsWith("\0")) {
1980
+ if (path12.isAbsolute(importId) || /^[A-Za-z]:[\\/]/.test(importId) || importId.startsWith("#") || importId.startsWith("\0")) {
1798
1981
  externalPackages.add(importId);
1799
1982
  continue;
1800
1983
  }
@@ -1806,15 +1989,15 @@ function collectSSRExternalPackages(ssrBundle) {
1806
1989
  return externalPackages;
1807
1990
  }
1808
1991
  function createExternalSSRBundlePlugin(nitroEntryPath, ssrOutputDir, ssrEntryFile) {
1809
- const resolvedNitroEntry = path11.resolve(nitroEntryPath);
1810
- const resolvedSSREntry = path11.resolve(ssrOutputDir, ssrEntryFile);
1992
+ const resolvedNitroEntry = path12.resolve(nitroEntryPath);
1993
+ const resolvedSSREntry = path12.resolve(ssrOutputDir, ssrEntryFile);
1811
1994
  return {
1812
1995
  name: "farm-externalize-prebuilt-ssr",
1813
1996
  resolveId(source, importer) {
1814
- if (!importer || path11.resolve(importer) !== resolvedNitroEntry) {
1997
+ if (!importer || path12.resolve(importer) !== resolvedNitroEntry) {
1815
1998
  return null;
1816
1999
  }
1817
- const resolvedImport = path11.resolve(path11.dirname(importer), source);
2000
+ const resolvedImport = path12.resolve(path12.dirname(importer), source);
1818
2001
  if (resolvedImport !== resolvedSSREntry) return null;
1819
2002
  return { id: FARM_SSR_PACKAGE_IMPORT, external: true };
1820
2003
  }
@@ -1947,13 +2130,13 @@ function trimSlashes(value) {
1947
2130
  function resolveBuildDocsContentDir(docs, root, srcDir) {
1948
2131
  const configuredContentDir = docs.contentDir || docs.config.contentDir;
1949
2132
  if (typeof configuredContentDir === "string" && configuredContentDir.trim()) {
1950
- const contentDir = path11.isAbsolute(configuredContentDir) ? configuredContentDir : path11.join(root, configuredContentDir);
2133
+ const contentDir = path12.isAbsolute(configuredContentDir) ? configuredContentDir : path12.join(root, configuredContentDir);
1951
2134
  return existsSync2(contentDir) ? contentDir : null;
1952
2135
  }
1953
2136
  const entryDir = docs.config.entry || trimSlashes(docs.entry) || "docs";
1954
- const appDocsDir = path11.join(root, srcDir || "src", "app", entryDir);
2137
+ const appDocsDir = path12.join(root, srcDir || "src", "app", entryDir);
1955
2138
  if (existsSync2(appDocsDir)) return appDocsDir;
1956
- const rootDocsDir = path11.join(root, entryDir);
2139
+ const rootDocsDir = path12.join(root, entryDir);
1957
2140
  return existsSync2(rootDocsDir) ? rootDocsDir : null;
1958
2141
  }
1959
2142
  function hasProjectPostcssConfig(root) {
@@ -1970,7 +2153,7 @@ function hasProjectPostcssConfig(root) {
1970
2153
  ".postcssrc.mjs",
1971
2154
  ".postcssrc.ts"
1972
2155
  ];
1973
- const projectRequire = createRequire(path11.join(root, "package.json"));
2156
+ const projectRequire = createRequire2(path12.join(root, "package.json"));
1974
2157
  return candidates.some((file) => {
1975
2158
  try {
1976
2159
  projectRequire.resolve(`./${file}`);
@@ -1993,7 +2176,7 @@ async function findFarmConfigPath(root) {
1993
2176
  "config.mjs"
1994
2177
  ];
1995
2178
  for (const candidate of candidates) {
1996
- const resolvedPath = path11.join(root, candidate);
2179
+ const resolvedPath = path12.join(root, candidate);
1997
2180
  try {
1998
2181
  await fs4.access(resolvedPath);
1999
2182
  return resolvedPath;
@@ -2002,14 +2185,6 @@ async function findFarmConfigPath(root) {
2002
2185
  }
2003
2186
  return null;
2004
2187
  }
2005
- function hasFarmServerRuntimePlugins(config) {
2006
- return (config.plugins || []).some((plugin) => {
2007
- if (getFarmIntegrationPluginServerRuntime(plugin) === false) return false;
2008
- return Boolean(
2009
- plugin.setup || plugin.init || plugin.ready || plugin.shutdown || plugin.runtime || plugin.router || plugin.render || plugin.beforeRouteMatch || plugin.afterRouteMatch || plugin.beforeRender || plugin.afterRender || plugin.onError || plugin.transformHTML
2010
- );
2011
- });
2012
- }
2013
2188
  function hasFarmPluginRoutes(config) {
2014
2189
  return (config.plugins || []).some((plugin) => Boolean(plugin.routes));
2015
2190
  }
@@ -2038,7 +2213,7 @@ async function discoverMiddlewareRoutes(appDir) {
2038
2213
  discovered.push({
2039
2214
  path: routePath,
2040
2215
  directory,
2041
- filePath: path11.join(dir, middlewareFile.name)
2216
+ filePath: path12.join(dir, middlewareFile.name)
2042
2217
  });
2043
2218
  }
2044
2219
  for (const entry of entries) {
@@ -2046,7 +2221,7 @@ async function discoverMiddlewareRoutes(appDir) {
2046
2221
  continue;
2047
2222
  }
2048
2223
  await walk(
2049
- path11.join(dir, entry.name),
2224
+ path12.join(dir, entry.name),
2050
2225
  appendMiddlewareRoutePath(routePath, entry.name),
2051
2226
  appendMiddlewareDirectory(directory, entry.name),
2052
2227
  discovered
@@ -2122,7 +2297,7 @@ async function buildUniversal(config, routeManager, apiRouteManager, serverRende
2122
2297
  logger.info(`\u{1F4CB} Found ${pageRoutes.length} page routes`);
2123
2298
  const fs4 = await import("fs/promises");
2124
2299
  const layoutRoutes = [];
2125
- const appDir = path11.join(root, srcDir, "app");
2300
+ const appDir = path12.join(root, srcDir, "app");
2126
2301
  async function findLayoutsForClient(dir, routePrefix = "/") {
2127
2302
  try {
2128
2303
  const entries = await fs4.readdir(dir, { withFileTypes: true });
@@ -2130,11 +2305,11 @@ async function buildUniversal(config, routeManager, apiRouteManager, serverRende
2130
2305
  if (entry.isFile() && entry.name.match(/^layout\.(tsx?|jsx?|vue|svelte)$/)) {
2131
2306
  layoutRoutes.push({
2132
2307
  pattern: routePrefix,
2133
- modulePath: path11.join(dir, entry.name)
2308
+ modulePath: path12.join(dir, entry.name)
2134
2309
  });
2135
2310
  } else if (entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.startsWith("_")) {
2136
2311
  const childPrefix = routePrefix === "/" ? `/${entry.name}` : `${routePrefix}/${entry.name}`;
2137
- await findLayoutsForClient(path11.join(dir, entry.name), childPrefix);
2312
+ await findLayoutsForClient(path12.join(dir, entry.name), childPrefix);
2138
2313
  }
2139
2314
  }
2140
2315
  } catch {
@@ -2158,7 +2333,7 @@ ${islandsErrors.map((error) => ` - ${error}`).join("\n")}`
2158
2333
  );
2159
2334
  }
2160
2335
  const hydrationPlanCache = /* @__PURE__ */ new Map();
2161
- const clientOutputDir = path11.join(root, distDir, "client");
2336
+ const clientOutputDir = path12.join(root, distDir, "client");
2162
2337
  const [productionViteResult] = await productionViteResultPromise;
2163
2338
  if (productionViteResult.status === "rejected") {
2164
2339
  await routeRuntimeManifestResultPromise;
@@ -2283,10 +2458,10 @@ ${islandsErrors.map((error) => ` - ${error}`).join("\n")}`
2283
2458
  lifecyclePluginManager
2284
2459
  );
2285
2460
  const runtimeManifestPath = await writeFarmRouteRuntimeManifest(
2286
- path11.join(root, distDir),
2461
+ path12.join(root, distDir),
2287
2462
  routeRuntimeManifest
2288
2463
  );
2289
- logger.info(`\u{1F4CB} Route runtime manifest: ${path11.relative(root, runtimeManifestPath)}`);
2464
+ logger.info(`\u{1F4CB} Route runtime manifest: ${path12.relative(root, runtimeManifestPath)}`);
2290
2465
  } catch (error) {
2291
2466
  if (lifecyclePluginManager) {
2292
2467
  await lifecyclePluginManager.runHookParallel("onError", {
@@ -2327,8 +2502,8 @@ async function writeSSRAssetsToClient(bundle, outputDir) {
2327
2502
  await mergeBuiltFontCss(outputDir, output.source);
2328
2503
  continue;
2329
2504
  }
2330
- const filePath = path11.join(outputDir, fileName);
2331
- await fs4.mkdir(path11.dirname(filePath), { recursive: true });
2505
+ const filePath = path12.join(outputDir, fileName);
2506
+ await fs4.mkdir(path12.dirname(filePath), { recursive: true });
2332
2507
  await fs4.writeFile(filePath, output.source);
2333
2508
  }
2334
2509
  }
@@ -2336,15 +2511,15 @@ async function copyFarmDocsFontAssetsToClient(root, outputDir) {
2336
2511
  const fs4 = await import("fs/promises");
2337
2512
  await Promise.all(
2338
2513
  resolveFarmDocsFontAssets(root).map(async ({ sourcePath, url }) => {
2339
- const targetPath = path11.join(outputDir, url.replace(/^\/+/, ""));
2340
- await fs4.mkdir(path11.dirname(targetPath), { recursive: true });
2514
+ const targetPath = path12.join(outputDir, url.replace(/^\/+/, ""));
2515
+ await fs4.mkdir(path12.dirname(targetPath), { recursive: true });
2341
2516
  await fs4.copyFile(sourcePath, targetPath);
2342
2517
  })
2343
2518
  );
2344
2519
  }
2345
2520
  async function mergeBuiltFontCss(outputDir, fontCssSource) {
2346
2521
  const fs4 = await import("fs/promises");
2347
- const fontCssPath = path11.join(outputDir, "farm-fonts.css");
2522
+ const fontCssPath = path12.join(outputDir, "farm-fonts.css");
2348
2523
  let fontCss = fontCssSource;
2349
2524
  if (fontCss === void 0) {
2350
2525
  try {
@@ -2353,7 +2528,7 @@ async function mergeBuiltFontCss(outputDir, fontCssSource) {
2353
2528
  return;
2354
2529
  }
2355
2530
  }
2356
- const clientCssPath = path11.join(outputDir, "farm-client.css");
2531
+ const clientCssPath = path12.join(outputDir, "farm-client.css");
2357
2532
  let clientCss = "";
2358
2533
  try {
2359
2534
  clientCss = await fs4.readFile(clientCssPath, "utf8");
@@ -2363,6 +2538,13 @@ async function mergeBuiltFontCss(outputDir, fontCssSource) {
2363
2538
  await fs4.writeFile(fontCssPath, normalizedFontCss);
2364
2539
  await fs4.writeFile(clientCssPath, mergeFarmFontCss(clientCss, normalizedFontCss));
2365
2540
  }
2541
+ function importsFarmClientBlockedPackage(id, packageName) {
2542
+ return id === packageName || id.startsWith(`${packageName}/`);
2543
+ }
2544
+ function importsFarmApiRouteModule(id) {
2545
+ const specifier = id.replace(/\\/g, "/").split("?", 1)[0];
2546
+ return /(?:^|\/)api\/(?:.*\/)?route(?:\.[cm]?[jt]sx?)?$/.test(specifier);
2547
+ }
2366
2548
  var IncompleteClientBuildOutputError = class extends Error {
2367
2549
  constructor(detail) {
2368
2550
  super(`Farm client build produced incomplete output: ${detail}`);
@@ -2372,7 +2554,7 @@ var IncompleteClientBuildOutputError = class extends Error {
2372
2554
  async function validateClientBuildOutput(root, srcDir, outputDir) {
2373
2555
  const fs4 = await import("fs/promises");
2374
2556
  const fingerprinted = await findFingerprintedClientEntry(outputDir);
2375
- const clientEntryPath = path11.join(outputDir, fingerprinted ?? "farm-client.js");
2557
+ const clientEntryPath = path12.join(outputDir, fingerprinted ?? "farm-client.js");
2376
2558
  let clientEntrySize = 0;
2377
2559
  try {
2378
2560
  const clientEntry = await fs4.stat(clientEntryPath);
@@ -2382,8 +2564,8 @@ async function validateClientBuildOutput(root, srcDir, outputDir) {
2382
2564
  if (clientEntrySize === 0) {
2383
2565
  throw new IncompleteClientBuildOutputError("farm-client.js is missing or empty");
2384
2566
  }
2385
- const clientCssPath = path11.join(outputDir, "farm-client.css");
2386
- const globalsCssPath = path11.join(root, srcDir, "app", "globals.css");
2567
+ const clientCssPath = path12.join(outputDir, "farm-client.css");
2568
+ const globalsCssPath = path12.join(root, srcDir, "app", "globals.css");
2387
2569
  let expectsCss = false;
2388
2570
  try {
2389
2571
  const globalsCss = await fs4.readFile(globalsCssPath, "utf8");
@@ -2404,7 +2586,7 @@ async function validateClientBuildOutput(root, srcDir, outputDir) {
2404
2586
  }
2405
2587
  }
2406
2588
  function getCachedClientModuleHydrationPlan(modulePath, root, mode, cache, options = {}) {
2407
- const key = `${path11.resolve(root)}\0${mode}\0${options.asyncOwnerIslands === true}\0${options.serverOwners === true}\0${options.serverTreeLayouts === true}\0${path11.resolve(modulePath)}`;
2589
+ const key = `${path12.resolve(root)}\0${mode}\0${options.asyncOwnerIslands === true}\0${options.serverOwners === true}\0${options.serverTreeLayouts === true}\0${path12.resolve(modulePath)}`;
2408
2590
  let plan = cache.get(key);
2409
2591
  if (!plan) {
2410
2592
  plan = getClientModuleHydrationPlan(modulePath, root, mode, options);
@@ -2413,7 +2595,7 @@ function getCachedClientModuleHydrationPlan(modulePath, root, mode, cache, optio
2413
2595
  return { ...plan, isolatedBoundaries: [...plan.isolatedBoundaries] };
2414
2596
  }
2415
2597
  async function buildClient(productionVite, config, root, srcDir, outputDir, pageRoutes, layoutRoutes = [], routeSlots = [], isolatedClientBoundaryModules = /* @__PURE__ */ new Set(), hydrationPlanCache = /* @__PURE__ */ new Map(), rendererBuildLifetime, programmaticClientRoutes, mobile = false) {
2416
- if (!mobile) await removeFarmMobileClientManifest(path11.dirname(outputDir));
2598
+ if (!mobile) await removeFarmMobileClientManifest(path12.dirname(outputDir));
2417
2599
  const viteBuild = productionVite.build;
2418
2600
  const { farmPlugin, farmServerOnlyEntriesPlugin } = await import("./vite.mjs");
2419
2601
  const { PluginManager: PluginManager2 } = await import("./plugin-SAS22JL7.mjs");
@@ -2647,6 +2829,7 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2647
2829
  ) ? hydrationStrategies[0] ?? "load" : "load";
2648
2830
  const docsClientRoutes = syntheticDocsPatterns.map((pattern) => ({
2649
2831
  pattern,
2832
+ docs: true,
2650
2833
  modulePath: "",
2651
2834
  relativePath: "",
2652
2835
  pageShouldHydrate: false,
@@ -2672,10 +2855,10 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2672
2855
  `\u{1F4F1} Total hydratable routes detected: ${clientPages.length} pages, ${clientLayouts.filter((layout) => layout.shouldHydrate || layout.hasIsolatedClientBoundaries).length} layouts, and ${clientRouteSlots.length} slots`
2673
2856
  );
2674
2857
  const buildTarget = async (platform) => {
2675
- const clientEntryRoot = path11.join(root, ".farm", "tmp");
2858
+ const clientEntryRoot = path12.join(root, ".farm", "tmp");
2676
2859
  await fs4.mkdir(clientEntryRoot, { recursive: true });
2677
- const clientEntryDir = await fs4.mkdtemp(path11.join(clientEntryRoot, "client-entry-"));
2678
- const clientEntryPath = path11.join(clientEntryDir, "farm-client-entry.tsx");
2860
+ const clientEntryDir = await fs4.mkdtemp(path12.join(clientEntryRoot, "client-entry-"));
2861
+ const clientEntryPath = path12.join(clientEntryDir, "farm-client-entry.tsx");
2679
2862
  const clientHydrationCode = generateClientHydrationEntry(
2680
2863
  clientPages,
2681
2864
  clientLayouts,
@@ -2709,11 +2892,11 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2709
2892
  const clientEntry = islandsMode && platform === "web" && clientHydrationCode.includes("/*farm-router-stub*/") ? splitFarmClientRouter(clientHydrationCode) : { entry: clientHydrationCode, router: void 0 };
2710
2893
  await fs4.writeFile(clientEntryPath, clientEntry.entry);
2711
2894
  if (clientEntry.router !== void 0) {
2712
- await fs4.writeFile(path11.join(clientEntryDir, "farm-client-router.tsx"), clientEntry.router);
2895
+ await fs4.writeFile(path12.join(clientEntryDir, "farm-client-router.tsx"), clientEntry.router);
2713
2896
  }
2714
2897
  const clientInput = { [entryName]: clientEntryPath };
2715
2898
  if (platform === "web" && canBootFarmIslandsClient(config)) {
2716
- const clientBootPath = path11.join(clientEntryDir, "farm-client-boot.tsx");
2899
+ const clientBootPath = path12.join(clientEntryDir, "farm-client-boot.tsx");
2717
2900
  await fs4.writeFile(
2718
2901
  clientBootPath,
2719
2902
  'import { startFarmIslandsBoot } from "@farm.js/core/internal/islands-boot";\nstartFarmIslandsBoot();\n'
@@ -2730,7 +2913,7 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2730
2913
  if (hasScopedPostcssConfig) {
2731
2914
  logger.info("\u{1F4E6} Using project PostCSS/Tailwind configuration");
2732
2915
  } else {
2733
- const postcssConfigPath = path11.join(clientEntryDir, "postcss.config.cjs");
2916
+ const postcssConfigPath = path12.join(clientEntryDir, "postcss.config.cjs");
2734
2917
  await fs4.writeFile(postcssConfigPath, "module.exports = { plugins: [] };\n");
2735
2918
  postcssSearchPath = clientEntryDir;
2736
2919
  tailwindVitePlugin = await loadTailwindVitePlugin({
@@ -2776,7 +2959,7 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2776
2959
  // A browser cannot load a Node builtin: farmServerOnlyEntriesPlugin
2777
2960
  // resolves one to Farm's browser module for it instead.
2778
2961
  external: (id) => {
2779
- if (id === "fsevents" || id.includes("fsevents") || id.endsWith(".node")) {
2962
+ if (importsFarmClientBlockedPackage(id, "fsevents") || id.endsWith(".node")) {
2780
2963
  return true;
2781
2964
  }
2782
2965
  return false;
@@ -2786,24 +2969,24 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2786
2969
  plugins: [
2787
2970
  createFarmThemeCssPlugin(config.theme, config.basePath),
2788
2971
  createFarmPrivateClientSourcemapsPlugin({
2789
- outDir: path11.join(
2790
- path11.dirname(outputDir),
2972
+ outDir: path12.join(
2973
+ path12.dirname(outputDir),
2791
2974
  platform === "mobile" ? `${FARM_CLIENT_SOURCEMAPS_DIR}-mobile` : FARM_CLIENT_SOURCEMAPS_DIR
2792
2975
  )
2793
2976
  }),
2794
2977
  // The web client's preload manifests; the mobile client records its files instead.
2795
2978
  platform === "mobile" ? createFarmMobileClientManifestPlugin({
2796
- buildDir: path11.dirname(outputDir),
2979
+ buildDir: path12.dirname(outputDir),
2797
2980
  entryName
2798
2981
  }) : createFarmClientModulePreloadPlugin({
2799
2982
  root,
2800
- buildDir: path11.dirname(outputDir),
2983
+ buildDir: path12.dirname(outputDir),
2801
2984
  entryName: "farm-client"
2802
2985
  }),
2803
2986
  ...adapterOwnsDocsRuntime && platform === "web" ? [
2804
2987
  createFarmDocsModulePreloadPlugin({
2805
2988
  root,
2806
- buildDir: path11.dirname(outputDir),
2989
+ buildDir: path12.dirname(outputDir),
2807
2990
  importer: clientEntryPath,
2808
2991
  entryName: "farm-client",
2809
2992
  modules: [
@@ -2823,47 +3006,63 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2823
3006
  {
2824
3007
  name: "farm-client-only-imports",
2825
3008
  enforce: "pre",
2826
- resolveId(id) {
2827
- if (id === "@farm.js/core") {
2828
- return { id: "\0farm-client-exports", external: false };
2829
- }
2830
- if (id === "@farm.js/core/i18n/server") {
2831
- return { id: "\0farm-i18n-client-bridge", external: false };
2832
- }
2833
- if (id === "@farm.js/core/server" || id === "@farm.js/core/api" || id === "@farm.js/core/middleware" || id === "@farm.js/core/headers" || id === "@farm.js/core/config" || id.includes("@farm.js/core/middleware") || id.includes("@farm.js/core/query/server")) {
2834
- return { id: "\0empty-module", external: false };
2835
- }
2836
- if (id.includes("/api/") && id.includes("/route")) {
2837
- return { id: "\0empty-api-route", external: false };
2838
- }
2839
- if (id === "fsevents" || id.includes("fsevents") || id.endsWith(".node") || id === "nitro" || id === "vite" || id === "esbuild" || id === "rolldown" || id.startsWith("rolldown/") || id === "rollup" || id.startsWith("nitro/") || id.includes("node-pre-gyp") || id.includes("nf3")) {
2840
- return { id: "\0empty-module", external: false };
3009
+ resolveId: {
3010
+ // Every specifier the handler redirects, as a superset of its checks.
3011
+ filter: {
3012
+ id: /@farm\.js\/core|\/api\/|fsevents|\.node$|node-pre-gyp|nf3|^(?:nitro|vite|esbuild|rolldown|rollup)(?:\/|$)/
3013
+ },
3014
+ handler(id) {
3015
+ if (id === "@farm.js/core") {
3016
+ return { id: "\0farm-client-exports", external: false };
3017
+ }
3018
+ if (id === "@farm.js/core/i18n/server") {
3019
+ return { id: "\0farm-i18n-client-bridge", external: false };
3020
+ }
3021
+ if (id === "@farm.js/core/server" || id === "@farm.js/core/api" || id === "@farm.js/core/middleware" || id === "@farm.js/core/headers" || id === "@farm.js/core/config" || id.includes("@farm.js/core/middleware") || id.includes("@farm.js/core/query/server")) {
3022
+ return { id: "\0empty-module", external: false };
3023
+ }
3024
+ if (importsFarmApiRouteModule(id)) {
3025
+ return { id: "\0empty-api-route", external: false };
3026
+ }
3027
+ if (importsFarmClientBlockedPackage(id, "fsevents") || id.endsWith(".node") || id === "nitro" || id === "vite" || id === "esbuild" || id === "rolldown" || id.startsWith("rolldown/") || id === "rollup" || id.startsWith("nitro/") || importsFarmClientBlockedPackage(id, "node-pre-gyp") || importsFarmClientBlockedPackage(id, "@mapbox/node-pre-gyp") || importsFarmClientBlockedPackage(id, "nf3")) {
3028
+ return { id: "\0empty-module", external: false };
3029
+ }
3030
+ return null;
2841
3031
  }
2842
- return null;
2843
3032
  },
2844
- load(id) {
2845
- if (id === "\0empty-module") {
2846
- return "const emptyMiddlewareStore = new Map(); export default {}; export const getMiddlewareContext = () => emptyMiddlewareStore; export const getMiddlewareData = () => emptyMiddlewareStore; export const getMiddlewareValue = () => undefined; export const middleware = () => ({});";
2847
- }
2848
- if (id === "\0empty-api-route") {
2849
- return "export const GET = () => {}; export const HEAD = () => {}; export const QUERY = () => {}; export const POST = () => {}; export const PUT = () => {}; export const DELETE = () => {}; export const PATCH = () => {}; export const OPTIONS = () => {}; export default {};";
2850
- }
2851
- if (id === "\0farm-i18n-client-bridge") {
2852
- return 'export { createTranslator, format, getLocale, getLocaleSource, t } from "@farm.js/core/i18n/client";';
2853
- }
2854
- if (id === "\0farm-client-exports") {
2855
- return [
2856
- "// Farm.js Client Exports - Safe for browser bundling",
2857
- 'export { Link } from "@farm.js/core/client";',
2858
- 'export { useRouter } from "@farm.js/core/client";',
2859
- 'export { usePathname, useSearchParams } from "@farm.js/core/navigation";',
2860
- // A page that hydrates ships to the browser with its notFound()/redirect() calls.
2861
- 'export { getFarmRedirectError, isFarmNotFoundError, isFarmRedirectError, notFound, permanentRedirect, redirect } from "@farm.js/core/navigation";',
2862
- 'export { createAPIClient } from "@farm.js/core/client";',
2863
- 'export { localFont, remoteFont } from "@farm.js/core/font";'
2864
- ].join("\n");
3033
+ load: {
3034
+ filter: {
3035
+ id: exactIdPattern([
3036
+ "\0empty-module",
3037
+ "\0empty-api-route",
3038
+ "\0farm-i18n-client-bridge",
3039
+ "\0farm-client-exports"
3040
+ ])
3041
+ },
3042
+ handler(id) {
3043
+ if (id === "\0empty-module") {
3044
+ return "const emptyMiddlewareStore = new Map(); export default {}; export const getMiddlewareContext = () => emptyMiddlewareStore; export const getMiddlewareData = () => emptyMiddlewareStore; export const getMiddlewareValue = () => undefined; export const middleware = () => ({});";
3045
+ }
3046
+ if (id === "\0empty-api-route") {
3047
+ return "export const GET = () => {}; export const HEAD = () => {}; export const QUERY = () => {}; export const POST = () => {}; export const PUT = () => {}; export const DELETE = () => {}; export const PATCH = () => {}; export const OPTIONS = () => {}; export default {};";
3048
+ }
3049
+ if (id === "\0farm-i18n-client-bridge") {
3050
+ return 'export { createTranslator, format, getLocale, getLocaleSource, t } from "@farm.js/core/i18n/client";';
3051
+ }
3052
+ if (id === "\0farm-client-exports") {
3053
+ return [
3054
+ "// Farm.js Client Exports - Safe for browser bundling",
3055
+ 'export { Link } from "@farm.js/core/client";',
3056
+ 'export { useRouter } from "@farm.js/core/client";',
3057
+ 'export { usePathname, useSearchParams } from "@farm.js/core/navigation";',
3058
+ // A page that hydrates ships to the browser with its notFound()/redirect() calls.
3059
+ 'export { getFarmRedirectError, isFarmNotFoundError, isFarmRedirectError, notFound, permanentRedirect, redirect } from "@farm.js/core/navigation";',
3060
+ 'export { createAPIClient } from "@farm.js/core/client";',
3061
+ 'export { localFont, remoteFont } from "@farm.js/core/font";'
3062
+ ].join("\n");
3063
+ }
3064
+ return null;
2865
3065
  }
2866
- return null;
2867
3066
  }
2868
3067
  },
2869
3068
  farmPlugin(
@@ -2893,8 +3092,8 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2893
3092
  };
2894
3093
  await viteBuild(mergeFarmProductionViteConfig(clientViteConfig, config.vite));
2895
3094
  if (platform === "mobile") {
2896
- await fs4.rm(path11.join(outputDir, `${entryName}.css`), { force: true });
2897
- if (!await hasFarmMobileClientEntry(path11.dirname(outputDir), outputDir)) {
3095
+ await fs4.rm(path12.join(outputDir, `${entryName}.css`), { force: true });
3096
+ if (!await hasFarmMobileClientEntry(path12.dirname(outputDir), outputDir)) {
2898
3097
  throw new IncompleteClientBuildOutputError(
2899
3098
  `${FARM_MOBILE_CLIENT_ENTRY_NAME}.js is missing or empty`
2900
3099
  );
@@ -2915,12 +3114,12 @@ async function buildClient(productionVite, config, root, srcDir, outputDir, page
2915
3114
  }
2916
3115
  function toBakedMarkdownSourcePath(root, filePath) {
2917
3116
  if (!filePath) return "";
2918
- if (!path11.isAbsolute(filePath)) return filePath.split(path11.sep).join("/");
2919
- const relative = path11.relative(root, filePath);
2920
- if (!relative || relative.startsWith("..") || path11.isAbsolute(relative)) {
2921
- return path11.basename(filePath);
3117
+ if (!path12.isAbsolute(filePath)) return filePath.split(path12.sep).join("/");
3118
+ const relative = path12.relative(root, filePath);
3119
+ if (!relative || relative.startsWith("..") || path12.isAbsolute(relative)) {
3120
+ return path12.basename(filePath);
2922
3121
  }
2923
- return relative.split(path11.sep).join("/");
3122
+ return relative.split(path12.sep).join("/");
2924
3123
  }
2925
3124
  function generateUniversalRouterStateRuntime(streamNavigations = false) {
2926
3125
  return `
@@ -3011,6 +3210,14 @@ function hasAbsoluteNavigationHref(href) {
3011
3210
  }
3012
3211
  `.trim();
3013
3212
  }
3213
+ function generateClientPageDirectorySource() {
3214
+ return `function getFarmPageDirectory(pathname) {
3215
+ const path = getFarmRoutePathname(pathname);
3216
+ let matched = clientRouteMatcher.match(path);
3217
+ if (matched && matched.route.meta.docs) matched = clientPageRouteMatcher.match(path);
3218
+ return matched ? matched.route.meta.directory || matched.route.meta.pattern : null;
3219
+ }`;
3220
+ }
3014
3221
  function generateRuntimePathMatcherSource() {
3015
3222
  return `
3016
3223
  function normalizeRuntimePath(pathname) {
@@ -3170,30 +3377,35 @@ function encodeRuntimePathSegment(value) {
3170
3377
  }
3171
3378
 
3172
3379
  function interpolateRedirectDestination(destination, params) {
3173
- let result = destination;
3174
3380
  const catchAllParamSegments = params[farmCatchAllParamSegments] || {};
3381
+ const encodedParams = new Map();
3175
3382
  const orderedCaptures = [];
3176
3383
  for (const [key, value] of Object.entries(params)) {
3177
3384
  const segments = catchAllParamSegments[key];
3178
3385
  const encodedValue = Array.isArray(segments)
3179
3386
  ? segments.map(encodeRuntimePathSegment).join("/")
3180
3387
  : encodeRuntimePathSegment(value);
3388
+ encodedParams.set(key, encodedValue);
3181
3389
  orderedCaptures.push(encodedValue);
3182
- result = result.split("[[..." + key + "]]").join(encodedValue);
3183
- result = result.split("[..." + key + "]").join(encodedValue);
3184
- result = result.split("[" + key + "]").join(encodedValue);
3185
- result = result.split(":" + key + "*").join(encodedValue);
3186
- result = result.split(":" + key).join(encodedValue);
3187
- if (key === "wildcard") result = result.split("*").join(encodedValue);
3188
- }
3189
- // Numbered captures resolve after the named substitutions. Encoded values
3190
- // never contain "$", so this cannot rewrite an already-injected value. An
3191
- // out-of-range index resolves to "", matching the development path.
3192
- result = result.replace(/\\$(\\d+)/g, function(_whole, group) {
3193
- const captured = orderedCaptures[Number(group) - 1];
3194
- return captured === undefined ? "" : captured;
3195
- });
3196
- return result;
3390
+ }
3391
+ // One pass that reads each reference whole, as the development path does: ":id" never
3392
+ // consumes the start of ":idx", an unknown ":name" stays as written, and an injected value is
3393
+ // never read again. An out-of-range "$n" resolves to "", matching the development path.
3394
+ return destination.replace(
3395
+ /\\[\\[\\.\\.\\.(\\w+)\\]\\]|\\[\\.\\.\\.(\\w+)\\]|\\[(\\w+)\\]|:([A-Za-z0-9_]+)(\\*?)|\\$(\\d+)|\\*/g,
3396
+ function(whole, optionalCatchAll, catchAll, bracket, name, star, group) {
3397
+ if (group !== undefined) {
3398
+ const captured = orderedCaptures[Number(group) - 1];
3399
+ return captured === undefined ? "" : captured;
3400
+ }
3401
+ const wildcard = encodedParams.has("wildcard") ? encodedParams.get("wildcard") : "*";
3402
+ const key = optionalCatchAll || catchAll || bracket || name;
3403
+ if (key === undefined) return wildcard;
3404
+ if (encodedParams.has(key)) return encodedParams.get(key);
3405
+ if (name === undefined) return whole;
3406
+ return ":" + name + (star ? wildcard : "");
3407
+ },
3408
+ );
3197
3409
  }
3198
3410
  `.trim();
3199
3411
  }
@@ -3522,8 +3734,10 @@ ${streamNavigations ? ` // A streamed navigation swaps in the page's shell; its
3522
3734
  const record = recover ? null : { valid: true, deploymentId, promise: null };
3523
3735
  // A navigation (not a prefetch) streams when the router supports it: the page goes in as
3524
3736
  // soon as its shell arrives, and its Suspense content follows (takeNavigationStream). A page
3525
- // whose layouts hydrate, or one rendered in this page's React root, arrives whole.
3526
- const streamShell = ${streamNavigations ? `recover && !interceptFrom && !partialHeaders["F-Render"] &&
3737
+ // whose layouts hydrate, or one rendered in this page's React root, arrives whole. So does a
3738
+ // refresh, which renders every layout again (no layout chain): like a transition, it keeps
3739
+ // the page on screen until the new one is ready, so the islands it keeps are all in it.
3740
+ const streamShell = ${streamNavigations ? `recover && layoutChain && !interceptFrom && !partialHeaders["F-Render"] &&
3527
3741
  !hasHydratableLayout(new URL(url, window.location.href).pathname)` : "false"};
3528
3742
  const request = async () => {
3529
3743
  const response = await fetchFarmNavigationDocument(url, {
@@ -3535,7 +3749,7 @@ ${streamNavigations ? ` // A streamed navigation swaps in the page's shell; its
3535
3749
  ...partialHeaders,
3536
3750
  ...(streamShell ? { "F-Stream": "flush" } : {}),
3537
3751
  }, recover, signal);
3538
- if (!response.ok) throw new Error("Failed to fetch page");
3752
+ if (!response.ok) throw new Error("Failed to fetch page: " + response.status);
3539
3753
  const store = (html) => {
3540
3754
  if (cacheResult && !signal?.aborted && generation === this.prefetchGeneration &&
3541
3755
  deploymentId === window.__FARM_DEPLOYMENT_ID__ && (!record || record.valid)) {
@@ -3950,7 +4164,7 @@ __farmConfigureApp(__farmAppSetup);` : `import React, { createRoot, hydrateRoot
3950
4164
  root,
3951
4165
  renderer.componentExtensions ?? []
3952
4166
  );
3953
- const globalsCssPath = path11.join(root, srcDir, "app", "globals.css");
4167
+ const globalsCssPath = path12.join(root, srcDir, "app", "globals.css");
3954
4168
  const serverStyleModules = [];
3955
4169
  const cssImport = [
3956
4170
  ...existsSync2(globalsCssPath) ? [globalsCssPath] : [],
@@ -4066,6 +4280,8 @@ mountFarmDocsSearch();
4066
4280
 
4067
4281
  ${generateUniversalRouterStateRuntime()}
4068
4282
 
4283
+ ${FARM_NAVIGATION_SCRIPT_SOURCE}
4284
+
4069
4285
  // SPA Router for server-rendered pages (HTML swap)
4070
4286
  const spaRouter = {
4071
4287
  ${generateUniversalRouterStateProperties()}
@@ -4236,12 +4452,7 @@ ${generateUniversalRouterStateProperties()}
4236
4452
 
4237
4453
  setTimeout(function() {
4238
4454
  Array.from(document.querySelectorAll("script")).forEach(function(script) {
4239
- const freshScript = document.createElement("script");
4240
- Array.from(script.attributes).forEach(function(attr) {
4241
- freshScript.setAttribute(attr.name, attr.value);
4242
- });
4243
- freshScript.textContent = script.textContent || "";
4244
- script.replaceWith(freshScript);
4455
+ script.replaceWith(createFarmNavigationScript(script));
4245
4456
  });
4246
4457
  }, 0);
4247
4458
 
@@ -4348,7 +4559,7 @@ document.addEventListener("click", function(e) {
4348
4559
  routeEntries.push(` {
4349
4560
  pattern: ${JSON.stringify(page.pattern)},${page.directory ? `
4350
4561
  directory: ${JSON.stringify(page.directory)},` : ""}
4351
- pageShouldHydrate: ${JSON.stringify(page.pageShouldHydrate)},
4562
+ pageShouldHydrate: ${JSON.stringify(page.pageShouldHydrate)},${page.docs ? "\n docs: true," : ""}
4352
4563
  ${page.hasIsolatedClientBoundaries ? "hasIsolatedClientBoundaries: true," : ""}
4353
4564
  islandStrategy: ${JSON.stringify(page.islandStrategy)},
4354
4565
  navigation: "html-fragment",
@@ -4449,6 +4660,12 @@ ${routeEntries.join(",\n")}
4449
4660
  const clientRouteMatcher = createFarmRouter(clientRoutes.map(function(route) {
4450
4661
  return { path: route.pattern, meta: route };
4451
4662
  }));
4663
+ ${clientPages.some((page) => page.docs) ? `const clientPageRouteMatcher = createFarmRouter(clientRoutes.filter(function(route) {
4664
+ return !route.docs;
4665
+ }).map(function(route) {
4666
+ return { path: route.pattern, meta: route };
4667
+ }));` : "const clientPageRouteMatcher = clientRouteMatcher;"}
4668
+ ${generateClientPageDirectorySource()}
4452
4669
 
4453
4670
  ${isolatedHydrationRuntime}
4454
4671
  ${routeClientGraphRuntime}
@@ -4474,10 +4691,7 @@ function getApplicableLayouts(pathname) {
4474
4691
  const urlPattern = layout.urlPattern || layout.pattern;
4475
4692
  if (urlPattern !== '/' && !isFarmRouteActive(urlPattern, normalizedPath, { exact: false })) continue;
4476
4693
  if (layout.groupScope) {
4477
- if (directory === undefined) {
4478
- const matched = matchRoute(pathname);
4479
- directory = matched ? matched.route.directory || matched.route.pattern : null;
4480
- }
4694
+ if (directory === undefined) directory = getFarmPageDirectory(pathname);
4481
4695
  if (
4482
4696
  typeof directory !== 'string' ||
4483
4697
  (directory !== layout.groupScope && !directory.startsWith(layout.groupScope + '/'))
@@ -5050,10 +5264,12 @@ async function hydrate() {
5050
5264
  }
5051
5265
  },
5052
5266
  });
5053
- ${isolatedHydrationEnabled ? `const isolatedHydration =
5267
+ ${isolatedHydrationEnabled ? `// Not cancelled with the page: a navigation disposes the islands it removes, and one in a
5268
+ // layout it keeps still waits for its trigger, as on a page of islands only.
5269
+ const isolatedHydration =
5054
5270
  !hasHydratableLayout(pathname) &&
5055
5271
  document.querySelector('f-island[src]')
5056
- ? hydrateFarmIsolatedClientBoundaries(document, hydrationController.signal)
5272
+ ? hydrateFarmIsolatedClientBoundaries(document)
5057
5273
  : Promise.resolve();
5058
5274
  await Promise.all([pageHydration, isolatedHydration]);` : "await pageHydration;"}
5059
5275
  } finally {
@@ -5099,14 +5315,11 @@ function fitsSegmentResponse(currentRoot, nextRoot) {
5099
5315
  return true;
5100
5316
  }` : ""}
5101
5317
 
5318
+ ${FARM_NAVIGATION_SCRIPT_SOURCE}
5319
+
5102
5320
  function activateNavigationScripts(root) {
5103
5321
  for (const script of Array.from(root?.querySelectorAll?.("script") || [])) {
5104
- const freshScript = document.createElement("script");
5105
- for (const attribute of Array.from(script.attributes)) {
5106
- freshScript.setAttribute(attribute.name, attribute.value);
5107
- }
5108
- freshScript.textContent = script.textContent || "";
5109
- script.replaceWith(freshScript);
5322
+ script.replaceWith(createFarmNavigationScript(script));
5110
5323
  }
5111
5324
  }
5112
5325
 
@@ -5180,8 +5393,8 @@ function removeSuspenseContent(root) {
5180
5393
  }
5181
5394
  }
5182
5395
 
5183
- // A layout's own server output, without what it wraps and without its islands, whose live DOM
5184
- // always differs from fresh HTML.
5396
+ // A layout's own server output, without what it wraps and without its islands' DOM, which live
5397
+ // always differs from fresh HTML. It keeps each island's props, so new props count as a change.
5185
5398
  function getLayoutShell(root, patterns, index) {
5186
5399
  const shell = findLayoutBoundary(root, patterns[index])?.cloneNode(true);
5187
5400
  if (!shell) return null;
@@ -5190,7 +5403,12 @@ function getLayoutShell(root, patterns, index) {
5190
5403
  : shell.querySelector("#__farm_page__");
5191
5404
  inner?.replaceChildren();
5192
5405
  removeSuspenseContent(shell);
5193
- shell.querySelectorAll("script").forEach(function(script) { script.remove(); });
5406
+ shell.querySelectorAll("script").forEach(function(script) {
5407
+ if (script.type !== "f/props") return script.remove();
5408
+ Array.from(script.attributes).forEach(function(attribute) {
5409
+ if (attribute.name !== "type") script.removeAttribute(attribute.name);
5410
+ });
5411
+ });
5194
5412
  shell.querySelectorAll("f-island").forEach(function(island) {
5195
5413
  island.replaceChildren();
5196
5414
  Array.from(island.attributes).forEach(function(attribute) {
@@ -5200,7 +5418,9 @@ function getLayoutShell(root, patterns, index) {
5200
5418
  return shell.innerHTML;
5201
5419
  }
5202
5420
 
5203
- function replaceSharedLayoutBoundary(currentRoot, nextRoot, refresh = false) {
5421
+ ${islandValues ? FARM_REFRESH_FIELDS_SOURCE : ""}function replaceSharedLayoutBoundary(currentRoot, nextRoot, refresh = false) {
5422
+ // A refresh keeps the islands still on the page: the ones in streamed Suspense content too.
5423
+ if (refresh) revealFarmStreamedContent(nextRoot);
5204
5424
  const currentPatterns = getLayoutPatterns(currentRoot);
5205
5425
  const nextPatterns = getLayoutPatterns(nextRoot);
5206
5426
  let sharedCount = 0;
@@ -5224,11 +5444,13 @@ function replaceSharedLayoutBoundary(currentRoot, nextRoot, refresh = false) {
5224
5444
  ? findLayoutBoundary(nextRoot, nextPatterns[sharedCount])
5225
5445
  : nextRoot.querySelector("#__farm_page__");
5226
5446
 
5227
- if (!currentTarget || !nextTarget) return false;
5447
+ if (!currentTarget || !nextTarget) return false;${islandValues ? `
5448
+ // A refresh renders the same layouts again: their fields keep what was typed, and the focus.
5449
+ const fields = refresh ? captureFarmServerFields(currentTarget) : null;` : ""}
5228
5450
  ${isolatedHydrationEnabled ? `${islandValues ? `// A refresh keeps the islands still on the page, with their state and new props.
5229
5451
  if (refresh) farmIsolatedHydrationRuntime.carryOver(currentTarget, nextTarget);
5230
5452
  ` : ""}disposeFarmIsolatedClientBoundaries(currentTarget);` : ""}
5231
- currentTarget.replaceWith(nextTarget);
5453
+ currentTarget.replaceWith(nextTarget);${islandValues ? "\n if (fields) restoreFarmServerFields(fields, nextTarget);" : ""}
5232
5454
  activateNavigationScripts(nextTarget);
5233
5455
  if (nextTreeRoot && nextTreeRoot !== nextTarget) nextTreeRoot.remove();
5234
5456
 
@@ -5236,7 +5458,17 @@ function replaceSharedLayoutBoundary(currentRoot, nextRoot, refresh = false) {
5236
5458
  const support = document.createElement("div");
5237
5459
  support.hidden = true;
5238
5460
  support.dataset.farmFragmentSupport = "true";
5239
- while (nextRoot.firstChild) support.appendChild(nextRoot.firstChild);
5461
+ while (nextRoot.firstChild) {
5462
+ const node = nextRoot.firstChild;
5463
+ // React's staged Suspense content stays in the root, where a later flush of a streamed
5464
+ // navigation reveals it; React removes it then.
5465
+ if (node.nodeType === 1 && node.matches('div[hidden][id^="S:"]')) {
5466
+ currentRoot.appendChild(node);
5467
+ activateNavigationScripts(node);
5468
+ } else {
5469
+ support.appendChild(node);
5470
+ }
5471
+ }
5240
5472
  document.body.appendChild(support);
5241
5473
  activateNavigationScripts(support);
5242
5474
  setTimeout(function() { support.remove(); }, 0);
@@ -5661,12 +5893,7 @@ ${islandValues ? ` // Islands mode: navigations name the layouts on screen, and
5661
5893
 
5662
5894
  setTimeout(function() {
5663
5895
  Array.from(document.querySelectorAll("script")).forEach(function(script) {
5664
- const freshScript = document.createElement("script");
5665
- Array.from(script.attributes).forEach(function(attr) {
5666
- freshScript.setAttribute(attr.name, attr.value);
5667
- });
5668
- freshScript.textContent = script.textContent || "";
5669
- script.replaceWith(freshScript);
5896
+ script.replaceWith(createFarmNavigationScript(script));
5670
5897
  });
5671
5898
  }, 0);
5672
5899
 
@@ -5789,9 +6016,9 @@ async function buildSSRInMemory(productionVite, config, root, routeManager, apiR
5789
6016
  buildLifetime: rendererBuildLifetime
5790
6017
  });
5791
6018
  if (!hasScopedPostcssConfig) {
5792
- postcssConfigDir = await fs4.mkdtemp(path11.join(os.tmpdir(), "farm-postcss-"));
6019
+ postcssConfigDir = await fs4.mkdtemp(path12.join(os.tmpdir(), "farm-postcss-"));
5793
6020
  await fs4.writeFile(
5794
- path11.join(postcssConfigDir, "postcss.config.cjs"),
6021
+ path12.join(postcssConfigDir, "postcss.config.cjs"),
5795
6022
  "module.exports = { plugins: [] };\n"
5796
6023
  );
5797
6024
  tailwindVitePlugin = await loadTailwindVitePlugin({
@@ -5893,7 +6120,13 @@ async function buildSSRInMemory(productionVite, config, root, routeManager, apiR
5893
6120
  specRoute: config.openapi.specRoute || null
5894
6121
  };
5895
6122
  }
5896
- const middlewareRoutes = await discoverMiddlewareRoutes(appDirs);
6123
+ const discoveredMiddlewareRoutes = await discoverMiddlewareRoutes(appDirs);
6124
+ const middlewareRoutes = farmTargetRunsEdgeMiddleware(preset) ? await Promise.all(
6125
+ discoveredMiddlewareRoutes.map(async (route) => ({
6126
+ ...route,
6127
+ config: await readMiddlewareFileConfig(route.filePath)
6128
+ }))
6129
+ ) : discoveredMiddlewareRoutes;
5897
6130
  const instrumentationPath = resolveFarmInstrumentationFile(root, config.srcDir || "src");
5898
6131
  const notFoundPath = resolveFarmNotFoundComponentPath(config, appDirs);
5899
6132
  if (notFoundPath) logger.info(`\u{1F4CB} Found custom 404 page: ${notFoundPath}`);
@@ -5919,7 +6152,7 @@ async function buildSSRInMemory(productionVite, config, root, routeManager, apiR
5919
6152
  const hasMdxComponentConfig = Boolean(config.mdx?.components);
5920
6153
  const hasMiddlewareConfig = hasFarmMiddlewareConfig(config.middleware);
5921
6154
  const hasRouteContextConfig = hasCustomFarmRouteContext(config);
5922
- const hasServerRuntimePlugins = hasFarmServerRuntimePlugins(config);
6155
+ const hasServerRuntimePlugins = hasFarmServerRuntimePlugins(config.plugins);
5923
6156
  const hasPluginRoutes = hasFarmPluginRoutes(config);
5924
6157
  const hasServerCacheConfig = hasFarmServerCacheConfig(config.cache);
5925
6158
  const configModulePath = hasServerRuntimeIntegrations || hasObservabilityHandler || hasMdxComponentConfig || hasMiddlewareConfig || hasRouteContextConfig || hasServerRuntimePlugins || hasPluginRoutes || hasServerCacheConfig || hasFarmServerStorageConfig(config.storage) || hasIntegrationProviders ? await findFarmConfigPath(root) : null;
@@ -5933,7 +6166,8 @@ async function buildSSRInMemory(productionVite, config, root, routeManager, apiR
5933
6166
  assertFarmDocsAdapterServesNoGuardedPages(
5934
6167
  config.docs,
5935
6168
  { root, srcDir: config.srcDir },
5936
- (pathname) => adapterGuardedPaths.has(pathname)
6169
+ (pathname) => adapterGuardedPaths.has(pathname),
6170
+ getFarmPresetRuntime(preset) === "edge" ? "edge" : "node"
5937
6171
  );
5938
6172
  }
5939
6173
  const farmDocsCspNonceMarker = createFarmCspNonce(config.security);
@@ -6138,17 +6372,23 @@ async function buildSSRInMemory(productionVite, config, root, routeManager, apiR
6138
6372
  ] : [],
6139
6373
  {
6140
6374
  name: "farm-virtual-ssr-entry",
6141
- resolveId(id) {
6142
- if (id === virtualEntryId || id === "\0virtual:farm-ssr-entry") {
6143
- return virtualEntryId;
6375
+ resolveId: {
6376
+ filter: { id: exactIdPattern([virtualEntryId, "\0virtual:farm-ssr-entry"]) },
6377
+ handler(id) {
6378
+ if (id === virtualEntryId || id === "\0virtual:farm-ssr-entry") {
6379
+ return virtualEntryId;
6380
+ }
6381
+ return null;
6144
6382
  }
6145
- return null;
6146
6383
  },
6147
- load(id) {
6148
- if (id === virtualEntryId) {
6149
- return virtualEntryCode;
6384
+ load: {
6385
+ filter: { id: exactIdPattern([virtualEntryId]) },
6386
+ handler(id) {
6387
+ if (id === virtualEntryId) {
6388
+ return virtualEntryCode;
6389
+ }
6390
+ return null;
6150
6391
  }
6151
- return null;
6152
6392
  }
6153
6393
  },
6154
6394
  {
@@ -6199,7 +6439,7 @@ async function buildSSRInMemory(productionVite, config, root, routeManager, apiR
6199
6439
  }
6200
6440
  function readFarmAppPackageIdentity(root) {
6201
6441
  try {
6202
- return JSON.parse(readFileSync(path11.join(root, "package.json"), "utf8"));
6442
+ return JSON.parse(readFileSync(path12.join(root, "package.json"), "utf8"));
6203
6443
  } catch {
6204
6444
  return {};
6205
6445
  }
@@ -6690,6 +6930,7 @@ function renderFarmServerTreeLayout(Layout, props, outlets) {
6690
6930
  const hasGeneratedMetadataImages = metadataImageRoutes.some(
6691
6931
  (image) => image.sourceType === "module"
6692
6932
  );
6933
+ const edgeMiddlewareFilePaths = farmTargetRunsEdgeMiddleware(preset) ? middlewareRoutes.filter(isFarmEdgeMiddlewareRoute).map((route) => route.filePath) : [];
6693
6934
  const hasMiddlewareRuntime = middlewareRoutes.length > 0 || hasFarmMiddlewareConfig(config.middleware);
6694
6935
  const farmDocsFontAssets = config.docs?.enabled ? toFarmDocsPublicFontAssets(resolveFarmDocsFontAssets(config.root)) : [];
6695
6936
  const integrationProviders = getIntegrationProviders(config.integrations);
@@ -7034,6 +7275,7 @@ function renderFarmServerTreeLayout(Layout, props, outlets) {
7034
7275
  createFarmApiCatalogResponse,
7035
7276
  createFarmAppManifestResponse,
7036
7277
  farmPathGuardCoversEndpoint,
7278
+ farmPathGuardCoversPage,
7037
7279
  collectFarmLlmsTxtPages,
7038
7280
  createFarmDefaultLlmsTxt,
7039
7281
  createFarmLlmsMarkdownReader,
@@ -7144,13 +7386,15 @@ function resolveFarmMobileShellRender(request, route, routePathname) {
7144
7386
  }
7145
7387
  return loading.route.module.default;
7146
7388
  }` : ""}${farmIslandsMode ? `
7147
- import { getSharedLayoutPrefixLength, handleFarmFormActionRequest, ignoreFarmHeldValues, installFarmIslandValues, parseFarmLayoutChainHeader } from "@farm.js/core/internal/production-runtime";
7389
+ import { getFarmFormState as farmFormState, getSharedLayoutPrefixLength, handleFarmFormActionRequest, ignoreFarmHeldValues, installFarmIslandValues, parseFarmLayoutChainHeader, renderFarmFormStateScript as farmFormStateScript } from "@farm.js/core/internal/production-runtime";
7148
7390
  import { installFarmIslandsServer } from "@farm.js/core/internal/islands-server";
7149
7391
  installFarmIslandsServer();
7150
7392
  const farmFormActionsConfig = ${JSON.stringify(resolveServerActionsConfig(config.serverActions))};
7151
7393
  installFarmIslandValues();
7152
7394
  ${islandsActionKeyCode()}
7153
- ${FARM_SEGMENT_NAVIGATION_SERVER_RUNTIME}` : ""}`;
7395
+ ${FARM_SEGMENT_NAVIGATION_SERVER_RUNTIME}` : `
7396
+ function farmFormState() { return undefined; }
7397
+ function farmFormStateScript() { return ""; }`}`;
7154
7398
  const productionSiteTelemetryImport = config.telemetry ? `import { createFarmProductionSiteReporter } from "@farm.js/core/internal/product-telemetry-runtime";` : "";
7155
7399
  const metadataImageRuntimeImport = hasGeneratedMetadataImages ? `import { createFarmMetadataImageResponse } from "@farm.js/core/internal/metadata-image-runtime";` : "";
7156
7400
  const pluginRuntimeImport = hasPluginRuntime ? `import { PluginManager } from "@farm.js/core/plugin";` : "";
@@ -7175,7 +7419,7 @@ import { fileURLToPath as farmDocsFileURLToPath } from "node:url";` : "";
7175
7419
  const markdownHandlerImport = config.md?.enabled ? `import { applyMarkdownNegotiationHeaders, createMarkdownMirrorResponse, getFarmMarkdownAlternatePath } from "@farm.js/core/markdown";` : "";
7176
7420
  const appMarkdownImport = hasMarkdownPages ? `import { FARM_MARKDOWN_ANONYMOUS_CLIENT_ADDRESS, createFarmMarkdownRouteModule, createFarmMarkdownSourceResponse, isFarmMarkdownPublicSourceResponse } from "@farm.js/core/internal/app-markdown-runtime";` : "const createFarmMarkdownSourceResponse = null;\nconst isFarmMarkdownPublicSourceResponse = null;";
7177
7421
  const markdownErrorImport = `import { FARM_MARKDOWN_CONTENT_TYPE, FARM_MARKDOWN_PAGE_CHECK_HEADER, _isFarmMarkdownPageCheck, createFarmMarkdownErrorBody, farmRequestWantsMarkdown } from "@farm.js/core/markdown";`;
7178
- const mdxComponentsPath = typeof config.mdx?.components === "string" ? path11.isAbsolute(config.mdx.components) ? config.mdx.components : path11.join(config.root, config.mdx.components) : null;
7422
+ const mdxComponentsPath = typeof config.mdx?.components === "string" ? path12.isAbsolute(config.mdx.components) ? config.mdx.components : path12.join(config.root, config.mdx.components) : null;
7179
7423
  const mdxComponentsImport = mdxComponentsPath ? `import * as FarmMdxComponentsModule from ${toVirtualEntryImportSpecifier(mdxComponentsPath)};` : "";
7180
7424
  const layerConfigPaths = (config.layers || []).map((layer) => layer.configFile).filter((configFile) => Boolean(configFile)).filter((configFile) => configFile !== configModulePath);
7181
7425
  const layerConfigImports = layerConfigPaths.map(
@@ -7678,6 +7922,19 @@ const farmDocsHandler = ${config.docs?.enabled ? hasPrecompiledDocs ? "farmDocsP
7678
7922
  loadReactModule: async () => FarmDocsAdapterReact,
7679
7923
  // Lists the docs MCP endpoint in /.well-known/ai-catalog.json for the server's lifetime.
7680
7924
  registerMCPServer: registerFarmMCPServer,
7925
+ // A page built with this keeps its HTML string, so the preload budget and the response
7926
+ // writer use it instead of reading and re-encoding the body. Older adapters ignore it.
7927
+ createHtmlResponse: farmOwnedHtmlResponse,${farmDocsAdapterServesGuardedPages(config.docs) ? `
7928
+ // The adapter keeps pages a path guard covers off search, llms.txt, the sitemap and MCP. It
7929
+ // asks about any path its own content lists, so the guards decide here, not a page list.
7930
+ isPathGuarded: (pathname) =>
7931
+ farmPathGuardCoversPage(
7932
+ {
7933
+ config: { middleware: farmMiddlewareConfig, integrations: serverRuntimeIntegrations },
7934
+ middlewareRoutes: fileMiddlewareModules,
7935
+ },
7936
+ pathname,
7937
+ ),` : ""}
7681
7938
  })` : `createFarmDocsHandler(farmDocsResolvedConfig, {
7682
7939
  root: farmDocsRuntimeRoot,
7683
7940
  srcDir: ${JSON.stringify(config.srcDir)},
@@ -7697,7 +7954,7 @@ const farmDocsAPIHandler = ${config.docs?.enabled ? hasPrecompiledDocs ? "farmDo
7697
7954
 
7698
7955
  // API routes bundled at build time
7699
7956
  const apiRoutes = ${apiRoutes.length > 0 ? "mergePluginAPIRoutes(" : ""}[${apiRegistrations.join(",")}
7700
- ]${apiRoutes.length > 0 ? `, configuredPlugins, ${JSON.stringify(apiRoutes.map(({ path: path13, methods }) => ({ path: path13, methods })))}, { bodySizeLimit: ${JSON.stringify(config.server.bodySizeLimit)}, dispatch: dispatchFarmPluginAPIRequest })` : ""};
7957
+ ]${apiRoutes.length > 0 ? `, configuredPlugins, ${JSON.stringify(apiRoutes.map(({ path: path14, methods }) => ({ path: path14, methods })))}, { bodySizeLimit: ${JSON.stringify(config.server.bodySizeLimit)}, dispatch: dispatchFarmPluginAPIRequest })` : ""};
7701
7958
  // A plugin calling an app endpoint (an MCP tool, say) goes through the whole
7702
7959
  // pipeline, so the endpoint's middleware and integration guards run for it.
7703
7960
  function dispatchFarmPluginAPIRequest(request) {
@@ -7839,7 +8096,7 @@ function renderFarmClientBootstrapScript(canonicalPath, selectedRouteSlots, page
7839
8096
  }
7840
8097
  return '<script id="__farm_route_slots_data__" type="application/json">' +
7841
8098
  serializedRouteSlots +
7842
- '</script>' + stampFarmCspNonce('<script>' + source + '</script>');
8099
+ '</script>' + stampFarmCspNonce('<script>' + source + '</script>') + farmFormStateScript();
7843
8100
  }
7844
8101
 
7845
8102
  // The settled defer() values the bootstrap script's props refer to, as development writes them.
@@ -7980,6 +8237,7 @@ async function renderFarmElement(ReactDOMServer, element, routeKey, flushToken =
7980
8237
  typeof ReactDOMServer.renderToReadableStream === "function") {
7981
8238
  const stream = await ReactDOMServer.renderToReadableStream(element, {
7982
8239
  nonce: _resolveCurrentCspNonce(),
8240
+ formState: farmFormState(),
7983
8241
  onError(error) {
7984
8242
  // redirect()/notFound() are control flow, not render failures: the
7985
8243
  // request handler must still receive them to map the response status,
@@ -8142,6 +8400,7 @@ async function renderFarmElement(ReactDOMServer, element, routeKey, flushToken =
8142
8400
  };
8143
8401
  pipeableStream = ReactDOMServer.renderToPipeableStream(element, {
8144
8402
  nonce: _resolveCurrentCspNonce(),
8403
+ formState: farmFormState(),
8145
8404
  onShellReady() {
8146
8405
  try {
8147
8406
  pipeableStream.pipe(destination);
@@ -8257,6 +8516,12 @@ function rememberFarmSyncRender(routeKey, streamedHtml) {
8257
8516
 
8258
8517
  function renderFarmElementSync(ReactDOMServer, element, routeKey) {
8259
8518
  if (!farmReactSyncRender) return undefined;
8519
+ // renderToString takes no form state: the page a useActionState form posted to streams.
8520
+ if (farmFormState() !== undefined) return undefined;
8521
+ // renderToString takes no nonce, so the scripts React adds itself (the form replay script of a
8522
+ // form with a function action) would go out without one, and a nonce policy blocks them. A
8523
+ // response with a nonce renders with the stream, which gives them the nonce.
8524
+ if (_resolveCurrentCspNonce()) return undefined;
8260
8525
  const addsDoctype = routeKey === undefined ? undefined : farmSyncRenderRoutes.get(routeKey);
8261
8526
  if (addsDoctype === undefined) return undefined;
8262
8527
  if (typeof ReactDOMServer.renderToString !== "function") return undefined;
@@ -8670,12 +8935,8 @@ function withFarmDocsRequestCache(response, request, farmLocaleResolution, middl
8670
8935
  ) {
8671
8936
  return response;
8672
8937
  }
8673
- const headers = new Headers(response.headers);
8674
- headers.set("Cache-Control", "private, no-store");
8675
- return farmOwnedResponse(response.body, {
8676
- status: response.status,
8677
- statusText: response.statusText,
8678
- headers,
8938
+ return farmPreloadHeadersResponse(response, (headers) => {
8939
+ headers.set("Cache-Control", "private, no-store");
8679
8940
  });
8680
8941
  }
8681
8942
 
@@ -9133,13 +9394,18 @@ function matchRewriteRoute(pathname, locale) {
9133
9394
  return null;
9134
9395
  }
9135
9396
 
9397
+ // The URL the browser asked for, for a request a configured rewrite replaced.
9398
+ const farmRequestedUrls = new WeakMap();
9399
+
9136
9400
  function createRewrittenRequest(request, destination) {
9137
9401
  const sourceUrl = new URL(request.url);
9138
9402
  const destinationUrl = new URL(destination, sourceUrl);
9139
9403
  if (!destinationUrl.search && sourceUrl.search) {
9140
9404
  destinationUrl.search = sourceUrl.search;
9141
9405
  }
9142
- return new Request(destinationUrl, request);
9406
+ const rewritten = new Request(destinationUrl, request);
9407
+ farmRequestedUrls.set(rewritten, farmRequestedUrls.get(request) || request.url);
9408
+ return rewritten;
9143
9409
  }
9144
9410
 
9145
9411
  ${generateConfiguredResponseHeadersRuntimeSource()}
@@ -9147,10 +9413,17 @@ ${generateConfiguredResponseHeadersRuntimeSource()}
9147
9413
  // App middleware files bundled at build time (sorted by depth, root first)
9148
9414
  const fileMiddlewareModules = [${middlewareRegistrations.join(",")}
9149
9415
  ];
9150
-
9416
+ ${edgeMiddlewareFilePaths.length > 0 ? `
9417
+ // \`runtime: "edge"\` middleware runs as Vercel routing middleware in front of the pages the build
9418
+ // prerendered for it, so the build's own requests for those pages skip it. A page any other
9419
+ // middleware guards is never prerendered. Read once: Nitro's prerender worker sets the variable.
9420
+ const farmEdgeMiddlewareFiles = new Set(${JSON.stringify(edgeMiddlewareFilePaths)});
9421
+ const farmPrerendering =
9422
+ typeof process !== "undefined" && process.env?.${FARM_PRERENDER_ENV} === "1";
9423
+ ` : ""}
9151
9424
  const farmMiddlewareRunner = ${hasMiddlewareRuntime ? `createProductionMiddlewareRunner({
9152
9425
  config: farmMiddlewareConfig,
9153
- modules: fileMiddlewareModules,
9426
+ modules: ${edgeMiddlewareFilePaths.length > 0 ? "farmPrerendering ? fileMiddlewareModules.filter((entry) => !farmEdgeMiddlewareFiles.has(entry.filePath)) : fileMiddlewareModules" : "fileMiddlewareModules"},
9154
9427
  i18n: farmI18nConfig,
9155
9428
  server: farmServerConfig,
9156
9429
  apiBasePath: farmLocalAPIBasePath,
@@ -9763,6 +10036,8 @@ async function resolveFarmRequestInContext(
9763
10036
  let url = requestUrl;
9764
10037
  let pathname = url.pathname;
9765
10038
  let routePathname = getFarmRoutePathname(pathname);
10039
+ // Before middleware: a ctx.rewrite() replaces the request below.
10040
+ const farmRequestedUrl = farmRequestedUrls.get(request) || request.url;
9766
10041
 
9767
10042
  // Redirects have precedence over local routes. Configured rewrites use
9768
10043
  // after-files semantics so emitted page, API, integration, docs, image, and
@@ -9993,13 +10268,11 @@ ${hasServerRuntimeIntegrations ? `
9993
10268
  middlewareData,
9994
10269
  middlewareContext,
9995
10270
  );
9996
- const docsHeaders = new Headers(wrappedDocsResponse.headers);
9997
- docsHeaders.set("x-farm-preload-buffered", "1");
9998
- return applyProductionMiddlewareHeaders(farmOwnedResponse(wrappedDocsResponse.body, {
9999
- status: wrappedDocsResponse.status,
10000
- statusText: wrappedDocsResponse.statusText,
10001
- headers: docsHeaders,
10002
- }), middlewareHeaders);
10271
+ // In place for a page the adapter built with createHtmlResponse, so its HTML string stays.
10272
+ const bufferedDocsResponse = farmPreloadHeadersResponse(wrappedDocsResponse, (headers) => {
10273
+ headers.set("x-farm-preload-buffered", "1");
10274
+ });
10275
+ return applyProductionMiddlewareHeaders(bufferedDocsResponse, middlewareHeaders);
10003
10276
  }
10004
10277
  }
10005
10278
  ` : ""}
@@ -10263,7 +10536,7 @@ ${hasServerRuntimeIntegrations ? `
10263
10536
  if (matchedRoute && request.method === "POST") {
10264
10537
  const actionResponse = await _runWithMiddlewareData(middlewareData || {}, () =>
10265
10538
  _runWithMiddlewareContext(middlewareContext || {}, () =>
10266
- handleFarmFormActionRequest(request, farmFormActionsConfig)
10539
+ handleFarmFormActionRequest(request, farmFormActionsConfig, farmRequestedUrl)
10267
10540
  )
10268
10541
  );
10269
10542
  if (actionResponse) return applyProductionMiddlewareHeaders(actionResponse, middlewareHeaders);
@@ -11795,6 +12068,16 @@ function getEffectiveRouteRule(config, pathname) {
11795
12068
  function getManifestPageEntry(manifest, pathname) {
11796
12069
  return manifest.routes.filter((entry) => entry.kind === "page" && middlewarePatternMatches(entry.pattern, pathname)).sort((left, right) => compareRoutePatternSpecificity(left.pattern, right.pattern))[0];
11797
12070
  }
12071
+ function withFarmEdgeGuardedPrerenderHeaders(headers, edgeGuarded) {
12072
+ if (!edgeGuarded) return headers;
12073
+ const cacheHeaders = /* @__PURE__ */ new Set(["cache-control", ...CDN_CACHE_CONTROL_HEADERS]);
12074
+ return {
12075
+ ...Object.fromEntries(
12076
+ Object.entries(headers).filter(([name]) => !cacheHeaders.has(name.toLowerCase()))
12077
+ ),
12078
+ "cache-control": "private, no-store"
12079
+ };
12080
+ }
11798
12081
  function getPhysicalPrerenderBypassReason(options) {
11799
12082
  const {
11800
12083
  config,
@@ -11831,18 +12114,30 @@ function getPhysicalPrerenderBypassReason(options) {
11831
12114
  }
11832
12115
  async function getFarmDocsPrerenderPages(config, root, preset) {
11833
12116
  if (!config.docs?.enabled || !config.docs.prerender) return [];
11834
- if (!isReactRenderer(config.renderer) || !hasFarmDocsRuntimeAdapter(config.docs)) {
11835
- logger.warn(
11836
- "docs.prerender needs a docs adapter such as @farming-labs/farmjs; Farm's built-in docs renderer keeps rendering docs pages on request."
11837
- );
11838
- return [];
11839
- }
11840
12117
  if (getFarmPresetRuntime(preset) === "edge") {
11841
12118
  logger.info(
11842
12119
  `\u21AA Keeping docs pages in the edge docs snapshot: docs.prerender writes static files on Node and serverless targets, not "${preset}".`
11843
12120
  );
11844
12121
  return [];
11845
12122
  }
12123
+ if (!hasFarmDocsRuntimeAdapter(config.docs)) {
12124
+ const { pages: pages2, originDependent } = listFarmDocsBuiltInPrerenderPages(config.docs, {
12125
+ root,
12126
+ srcDir: config.srcDir
12127
+ });
12128
+ if (originDependent.length > 0) {
12129
+ logger.info(
12130
+ `\u21AA Keeping ${originDependent.length} docs page(s) rendering on request: their social image metadata is an absolute URL built from the request's origin. Set docs.socialImage.baseUrl to prerender them.`
12131
+ );
12132
+ }
12133
+ return pages2;
12134
+ }
12135
+ if (!isReactRenderer(config.renderer)) {
12136
+ logger.warn(
12137
+ `The docs adapter ${JSON.stringify(config.docs.adapter.id)} renders with React; docs.prerender keeps its pages rendering on request with the "${config.renderer.name}" renderer.`
12138
+ );
12139
+ return [];
12140
+ }
11846
12141
  const pages = await listFarmDocsAdapterPages(config.docs, { root, srcDir: config.srcDir });
11847
12142
  if (!pages) {
11848
12143
  logger.warn(
@@ -11870,8 +12165,8 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
11870
12165
  const isVercel = preset === "vercel";
11871
12166
  const isCloudflareWorker = preset === "cloudflare-module";
11872
12167
  const outputDir = resolveDeployOutputPath(root, config.deploy.outputDir);
11873
- const runtimeServerOutputDir = isVercel ? path11.join(outputDir, "functions", "__nitro.func") : path11.join(outputDir, "server");
11874
- const ssrOutputDir = path11.join(root, distDir, "ssr");
12168
+ const runtimeServerOutputDir = isVercel ? path12.join(outputDir, "functions", "__nitro.func") : path12.join(outputDir, "server");
12169
+ const ssrOutputDir = path12.join(root, distDir, "ssr");
11875
12170
  const imageRuntime = resolveFarmImageServerRuntime(config.images, preset);
11876
12171
  const hasGeneratedMetadataImages = Array.from(routeManager.getMetadataImages().values()).some(
11877
12172
  (image) => image.sourceType === "module"
@@ -11886,7 +12181,10 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
11886
12181
  ...imageRuntime === "node" ? ["sharp"] : [],
11887
12182
  ...useExternalMetadataImageRuntime ? ["@vercel/og"] : []
11888
12183
  ]);
11889
- const isPrebuiltSSRCandidate = preset === "node-server" && [...ssrExternalPackages].every((packageName) => copiedRuntimePackages.has(packageName));
12184
+ const ssrExternalsArePackaged = [...ssrExternalPackages].every(
12185
+ (packageName) => copiedRuntimePackages.has(packageName)
12186
+ );
12187
+ const isPrebuiltSSRCandidate = preset === "node-server" && ssrExternalsArePackaged;
11890
12188
  logger.info(`\u{1F4E6} Nitro output directory: ${outputDir}`);
11891
12189
  logger.info(`\u{1F4E6} SSR entry file: ${ssrEntryFile}`);
11892
12190
  logger.info(`\u{1F4E6} Preset: ${preset}`);
@@ -11920,12 +12218,21 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
11920
12218
  config: await readMiddlewareFileConfig(route.filePath)
11921
12219
  }))
11922
12220
  ) : middlewareRoutes;
12221
+ const edgeMiddlewareRoutes = farmTargetRunsEdgeMiddleware(preset) ? middlewareRoutesWithConfig.filter(isFarmEdgeMiddlewareRoute) : [];
12222
+ const serverMiddlewareRoutes = edgeMiddlewareRoutes.length > 0 ? middlewareRoutesWithConfig.filter((route) => !isFarmEdgeMiddlewareRoute(route)) : middlewareRoutesWithConfig;
12223
+ const edgeGuardedPrerenderRoutes = [];
12224
+ const addPrerenderRoute = (pathname) => {
12225
+ prerenderRoutes.push(pathname);
12226
+ if (appMiddlewareMayHandlePath(edgeMiddlewareRoutes, pathname)) {
12227
+ edgeGuardedPrerenderRoutes.push(pathname);
12228
+ }
12229
+ };
11923
12230
  for (const page of ssgPages) {
11924
12231
  if (page.revalidate !== void 0) continue;
11925
12232
  if (prerenderRoutes.includes(page.urlPath)) continue;
11926
12233
  const reason = getPhysicalPrerenderBypassReason({
11927
12234
  config,
11928
- middlewareRoutes: middlewareRoutesWithConfig,
12235
+ middlewareRoutes: serverMiddlewareRoutes,
11929
12236
  routeRuntimeManifest,
11930
12237
  redirectSources,
11931
12238
  rewriteSources,
@@ -11935,7 +12242,7 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
11935
12242
  skippedPrerenderRoutes.push({ pathname: page.urlPath, reason });
11936
12243
  continue;
11937
12244
  }
11938
- prerenderRoutes.push(page.urlPath);
12245
+ addPrerenderRoute(page.urlPath);
11939
12246
  }
11940
12247
  const docsRouteRuntimeManifest = {
11941
12248
  ...routeRuntimeManifest,
@@ -11945,7 +12252,7 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
11945
12252
  if (prerenderRoutes.includes(pathname)) continue;
11946
12253
  const reason = getPhysicalPrerenderBypassReason({
11947
12254
  config,
11948
- middlewareRoutes: middlewareRoutesWithConfig,
12255
+ middlewareRoutes: serverMiddlewareRoutes,
11949
12256
  routeRuntimeManifest: docsRouteRuntimeManifest,
11950
12257
  redirectSources,
11951
12258
  rewriteSources,
@@ -11955,7 +12262,7 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
11955
12262
  skippedPrerenderRoutes.push({ pathname, reason });
11956
12263
  continue;
11957
12264
  }
11958
- prerenderRoutes.push(pathname);
12265
+ addPrerenderRoute(pathname);
11959
12266
  }
11960
12267
  for (const skipped of skippedPrerenderRoutes) {
11961
12268
  logger.info(`\u21AA Keeping SSG route ${skipped.pathname} server-handled (${skipped.reason})`);
@@ -11981,15 +12288,15 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
11981
12288
  resolveHashedClientCssHref(clientOutputDir),
11982
12289
  resolveHashedClientJsSrc(clientOutputDir),
11983
12290
  resolveClientBootSrc(clientOutputDir),
11984
- readFarmDocsModulePreloads(path11.join(root, distDir)),
11985
- readFarmClientModulePreloads(path11.join(root, distDir))
12291
+ readFarmDocsModulePreloads(path12.join(root, distDir)),
12292
+ readFarmClientModulePreloads(path12.join(root, distDir))
11986
12293
  ]);
11987
12294
  let nativeStylesheets;
11988
12295
  const encodedDocsModulePreloads = encodeFarmDocsModulePreloads(docsModulePreloads);
11989
12296
  const encodedClientModulePreloads = encodeFarmClientModulePreloads(clientModulePreloads);
11990
12297
  const encodedMobileShellClient = shouldBuildFarmMobileClient(config) ? encodeFarmMobileShellClient(
11991
12298
  await finalizeFarmMobileClient({
11992
- buildDir: path11.join(root, distDir),
12299
+ buildDir: path12.join(root, distDir),
11993
12300
  clientOutputDir,
11994
12301
  webEntry: clientJsSrc,
11995
12302
  webBoot: clientBootSrc,
@@ -12028,12 +12335,12 @@ async function buildNitroUniversal(config, routeManager, apiRouteManager, server
12028
12335
  await fs4.mkdir(ssrOutputDir, { recursive: true });
12029
12336
  await Promise.all(
12030
12337
  Object.entries(ssrBundle).map(async ([fileName, output]) => {
12031
- const filePath = path11.join(ssrOutputDir, fileName);
12032
- await fs4.mkdir(path11.dirname(filePath), { recursive: true });
12338
+ const filePath = path12.join(ssrOutputDir, fileName);
12339
+ await fs4.mkdir(path12.dirname(filePath), { recursive: true });
12033
12340
  await fs4.writeFile(filePath, output.type === "chunk" ? output.code : output.source);
12034
12341
  })
12035
12342
  );
12036
- const nitroEntryPath = path11.join(ssrOutputDir, "nitro-entry.mjs");
12343
+ const nitroEntryPath = path12.join(ssrOutputDir, "nitro-entry.mjs");
12037
12344
  const nodeAdapterModule = preset === "node-server" ? resolveNitroRuntimeDependency(root, "srvx/node") : null;
12038
12345
  const hasNitroCacheRouteRules = hasFarmNitroCacheRouteRule(config.routeRules);
12039
12346
  const nitroEntryCode = `
@@ -12241,20 +12548,20 @@ function toFarmNodeResponse(request, response) {
12241
12548
  );
12242
12549
  }
12243
12550
  await fs4.writeFile(
12244
- path11.join(ssrOutputDir, FARM_DESKTOP_ENV_MODULE_FILE),
12551
+ path12.join(ssrOutputDir, FARM_DESKTOP_ENV_MODULE_FILE),
12245
12552
  FARM_DESKTOP_ENV_MODULE_SOURCE
12246
12553
  );
12247
12554
  }
12248
- const farmNodeServerEntryPath = preset === "node-server" ? path11.join(ssrOutputDir, "farm-node-server-entry.mjs") : null;
12555
+ const farmNodeServerEntryPath = preset === "node-server" ? path12.join(ssrOutputDir, "farm-node-server-entry.mjs") : null;
12249
12556
  if (farmNodeServerEntryPath && nodeAdapterModule) {
12250
12557
  await fs4.writeFile(
12251
- path11.join(ssrOutputDir, FARM_NODE_ENV_MODULE_FILE),
12558
+ path12.join(ssrOutputDir, FARM_NODE_ENV_MODULE_FILE),
12252
12559
  FARM_NODE_ENV_MODULE_SOURCE
12253
12560
  );
12254
12561
  await fs4.writeFile(
12255
12562
  farmNodeServerEntryPath,
12256
12563
  createFarmNodeServerEntry({
12257
- nitroEntryFile: path11.basename(nitroEntryPath),
12564
+ nitroEntryFile: path12.basename(nitroEntryPath),
12258
12565
  nodeAdapterModule,
12259
12566
  server: config.server,
12260
12567
  websocketAdapterModule: resolveNitroRuntimeDependency(root, "crossws/adapters/node"),
@@ -12262,12 +12569,12 @@ function toFarmNodeResponse(request, response) {
12262
12569
  })
12263
12570
  );
12264
12571
  }
12265
- const farmBunServerEntryPath = preset === "bun" ? path11.join(ssrOutputDir, "farm-bun-server-entry.mjs") : null;
12572
+ const farmBunServerEntryPath = preset === "bun" ? path12.join(ssrOutputDir, "farm-bun-server-entry.mjs") : null;
12266
12573
  if (farmBunServerEntryPath) {
12267
12574
  await fs4.writeFile(
12268
12575
  farmBunServerEntryPath,
12269
12576
  createFarmBunServerEntry({
12270
- nitroEntryFile: path11.basename(nitroEntryPath),
12577
+ nitroEntryFile: path12.basename(nitroEntryPath),
12271
12578
  bunAdapterModule: resolveNitroRuntimeDependency(root, "srvx/bun"),
12272
12579
  server: config.server,
12273
12580
  websocketAdapterModule: resolveNitroRuntimeDependency(root, "crossws/adapters/bun"),
@@ -12275,7 +12582,7 @@ function toFarmNodeResponse(request, response) {
12275
12582
  })
12276
12583
  );
12277
12584
  }
12278
- const farmNetlifyEntryPath = preset === "netlify" ? path11.join(ssrOutputDir, "farm-netlify-entry.mjs") : null;
12585
+ const farmNetlifyEntryPath = preset === "netlify" ? path12.join(ssrOutputDir, "farm-netlify-entry.mjs") : null;
12279
12586
  if (farmNetlifyEntryPath) {
12280
12587
  await fs4.writeFile(
12281
12588
  farmNetlifyEntryPath,
@@ -12284,7 +12591,7 @@ function toFarmNodeResponse(request, response) {
12284
12591
  })
12285
12592
  );
12286
12593
  }
12287
- const farmCloudflareEnvPath = preset === "cloudflare-pages" ? path11.join(ssrOutputDir, "farm-cloudflare-env.mjs") : null;
12594
+ const farmCloudflareEnvPath = preset === "cloudflare-pages" ? path12.join(ssrOutputDir, "farm-cloudflare-env.mjs") : null;
12288
12595
  if (farmCloudflareEnvPath) {
12289
12596
  await fs4.writeFile(
12290
12597
  farmCloudflareEnvPath,
@@ -12300,19 +12607,30 @@ function toFarmNodeResponse(request, response) {
12300
12607
  ssrOutputDir,
12301
12608
  ssrEntryFile
12302
12609
  );
12303
- const configuredNitroRouteRules = shouldBuildFarmMobileClient(config) ? varyFarmNitroCacheRulesByShell(routeRulesToNitroRouteRules(config.routeRules)) : routeRulesToNitroRouteRules(config.routeRules);
12610
+ const configuredNitroRouteRules = nitroRouteRulesBelowBasePath(
12611
+ shouldBuildFarmMobileClient(config) ? varyFarmNitroCacheRulesByShell(routeRulesToNitroRouteRules(config.routeRules)) : routeRulesToNitroRouteRules(config.routeRules),
12612
+ config.basePath,
12613
+ resolveFarmAPIServerBasePath(config.api)
12614
+ );
12615
+ const toPrerenderPublicPath = (route) => normalizeFarmTrailingSlashPathname(
12616
+ applyFarmBasePath(route, config.basePath),
12617
+ config.trailingSlash === true
12618
+ );
12304
12619
  const prerenderNitroRouteRules = Object.fromEntries(
12305
12620
  prerenderRoutes.map((route) => {
12306
12621
  const configuredRule = configuredNitroRouteRules[route] || {};
12307
12622
  return [
12308
- route,
12623
+ toPrerenderPublicPath(route),
12309
12624
  {
12310
12625
  ...configuredRule,
12311
12626
  prerender: true,
12312
- headers: {
12313
- ...getPrerenderRouteHeaders(route, configuredHeaderRoutes),
12314
- ...configuredRule.headers
12315
- }
12627
+ headers: withFarmEdgeGuardedPrerenderHeaders(
12628
+ {
12629
+ ...getPrerenderRouteHeaders(route, configuredHeaderRoutes),
12630
+ ...configuredRule.headers
12631
+ },
12632
+ edgeGuardedPrerenderRoutes.includes(route)
12633
+ )
12316
12634
  }
12317
12635
  ];
12318
12636
  })
@@ -12331,7 +12649,7 @@ function toFarmNodeResponse(request, response) {
12331
12649
  // `src` directory), as Nitro handlers outside Farm's aliases.
12332
12650
  serverDir: false,
12333
12651
  serverEntry: false,
12334
- buildDir: path11.join(root, distDir, ".nitro"),
12652
+ buildDir: path12.join(root, distDir, ".nitro"),
12335
12653
  alias: resolveNitroInternalRuntimeAliases(root),
12336
12654
  compatibilityDate: "2024-12-01",
12337
12655
  output: resolveFarmNitroOutputConfig(preset, outputDir),
@@ -12359,7 +12677,7 @@ function toFarmNodeResponse(request, response) {
12359
12677
  // answered independently, as by the production server, so keeping several
12360
12678
  // in flight overlaps the worker's rendering with this thread's per-route work.
12361
12679
  concurrency: Math.min(os.availableParallelism(), 8),
12362
- routes: prerenderRoutes
12680
+ routes: prerenderRoutes.map(toPrerenderPublicPath)
12363
12681
  }
12364
12682
  } : {},
12365
12683
  experimental: {
@@ -12423,7 +12741,7 @@ function toFarmNodeResponse(request, response) {
12423
12741
  if (pluginManager) {
12424
12742
  nitroConfig = await pluginManager.runHookSerial("beforeNitroBuild", nitroConfig);
12425
12743
  }
12426
- const expectedServerDir = path11.join(outputDir, "server");
12744
+ const expectedServerDir = path12.join(outputDir, "server");
12427
12745
  const customRollupKeys = Object.keys(nitroConfig.rollupConfig || {}).filter(
12428
12746
  (key) => key !== "external" && key !== "plugins"
12429
12747
  );
@@ -12436,11 +12754,13 @@ function toFarmNodeResponse(request, response) {
12436
12754
  snapshotSSRRebundleOptions(nitroConfig)
12437
12755
  );
12438
12756
  const requestedBuilder = nitroConfig.builder ?? process.env.NITRO_BUILDER;
12439
- const canReusePrebuiltSSR = isPrebuiltSSRCandidate && nitroConfig.preset === "node-server" && (requestedBuilder === void 0 || requestedBuilder === "rollup" || requestedBuilder === "rolldown") && nitroConfig.sourcemap === false && !hasCustomOxcOptions && !hasLateBuildMutationConfig && !hasUnsupportedSSRRebundleOverrides && nitroConfig.rollupConfig?.external === nitroRollupExternal && !hasRollupPlugins(nitroConfig.rollupConfig?.plugins) && customRollupKeys.length === 0 && path11.resolve(nitroConfig.output?.serverDir || "") === path11.resolve(expectedServerDir) && Boolean(
12757
+ const nitroBuildIsFarms = (requestedBuilder === void 0 || requestedBuilder === "rollup" || requestedBuilder === "rolldown") && nitroConfig.sourcemap === false && !hasCustomOxcOptions && !hasLateBuildMutationConfig && !hasUnsupportedSSRRebundleOverrides && nitroConfig.rollupConfig?.external === nitroRollupExternal && !hasRollupPlugins(nitroConfig.rollupConfig?.plugins) && customRollupKeys.length === 0 && Boolean(
12440
12758
  nitroConfig.handlers?.some(
12441
- (handler) => path11.resolve(handler?.handler || "") === nitroEntryPath
12759
+ (handler) => path12.resolve(handler?.handler || "") === nitroEntryPath
12442
12760
  )
12443
12761
  );
12762
+ const canReusePrebuiltSSR = isPrebuiltSSRCandidate && nitroConfig.preset === "node-server" && nitroBuildIsFarms && path12.resolve(nitroConfig.output?.serverDir || "") === path12.resolve(expectedServerDir);
12763
+ const prerenderReusesPrebuiltSSR = prerenderRoutes.length > 0 && ssrExternalsArePackaged && nitroBuildIsFarms;
12444
12764
  const selectRolldownBuilder = canReusePrebuiltSSR && requestedBuilder === void 0 && await canUseRolldownBuilder();
12445
12765
  if (selectRolldownBuilder) nitroConfig.builder = "rolldown";
12446
12766
  const useRolldownBuilder = canReusePrebuiltSSR && (nitroConfig.builder ?? process.env.NITRO_BUILDER) === "rolldown";
@@ -12535,7 +12855,24 @@ function toFarmNodeResponse(request, response) {
12535
12855
  });
12536
12856
  await nitroBuilder.prepare(nitroInstance);
12537
12857
  await nitroBuilder.copyPublicAssets(nitroInstance);
12538
- if (prerenderRoutes.length > 0 && canReusePrebuiltSSR) {
12858
+ if (prerenderReusesPrebuiltSSR && !canReusePrebuiltSSR) {
12859
+ nitroInstance.hooks.hook("prerender:config", (prerendererConfig) => {
12860
+ const configuredPlugins = prerendererConfig.rollupConfig?.plugins;
12861
+ const plugins = Array.isArray(configuredPlugins) ? configuredPlugins : configuredPlugins ? [configuredPlugins] : [];
12862
+ prerendererConfig.rollupConfig = {
12863
+ ...prerendererConfig.rollupConfig,
12864
+ plugins: [...plugins.filter((plugin) => plugin !== ssrRollupPlugin), prebuiltSSRPlugin]
12865
+ };
12866
+ prerendererConfig.output = {
12867
+ ...prerendererConfig.output,
12868
+ serverDir: path12.join(
12869
+ prerendererConfig.buildDir ?? path12.join(root, distDir, ".nitro"),
12870
+ "prerender"
12871
+ )
12872
+ };
12873
+ });
12874
+ }
12875
+ if (prerenderReusesPrebuiltSSR) {
12539
12876
  nitroInstance.hooks.hook("prerender:init", (prerenderer) => {
12540
12877
  if (useRolldownBuilder) {
12541
12878
  prerenderer.hooks.hook("rollup:before", (_nitro, rollupConfig) => {
@@ -12545,10 +12882,10 @@ function toFarmNodeResponse(request, response) {
12545
12882
  });
12546
12883
  }
12547
12884
  prerenderer.hooks.hook("compiled", async () => {
12548
- const prerenderServerDir = path11.join(outputDir, "server");
12885
+ const prerenderServerDir = prerenderer.options.output.serverDir;
12549
12886
  await copyPrebuiltSSRBundle(
12550
12887
  ssrBundle,
12551
- path11.join(prerenderServerDir, FARM_SSR_OUTPUT_DIR),
12888
+ path12.join(prerenderServerDir, FARM_SSR_OUTPUT_DIR),
12552
12889
  null,
12553
12890
  fs4
12554
12891
  );
@@ -12624,7 +12961,7 @@ function toFarmNodeResponse(request, response) {
12624
12961
  const copyResults = await Promise.allSettled([
12625
12962
  prebuiltSSRFilesResult.value ? writeSSRBundleFiles(
12626
12963
  prebuiltSSRFilesResult.value,
12627
- path11.join(outputDir, "server", FARM_SSR_OUTPUT_DIR),
12964
+ path12.join(outputDir, "server", FARM_SSR_OUTPUT_DIR),
12628
12965
  fs4
12629
12966
  ) : Promise.resolve(),
12630
12967
  runtimeCopyPromise
@@ -12634,14 +12971,14 @@ function toFarmNodeResponse(request, response) {
12634
12971
  );
12635
12972
  if (failedCopy) throw failedCopy.reason;
12636
12973
  if (canReusePrebuiltSSR) {
12637
- await registerPrebuiltSSRPackageImport(path11.join(outputDir, "server"), ssrEntryFile, fs4);
12974
+ await registerPrebuiltSSRPackageImport(path12.join(outputDir, "server"), ssrEntryFile, fs4);
12638
12975
  logger.info("\u26A1 Reused Farm's prebuilt SSR bundle for the Node output");
12639
12976
  }
12640
12977
  if (useRolldownBuilder) {
12641
12978
  logger.info("\u26A1 Built the Node adapter with Rolldown");
12642
12979
  }
12643
12980
  if (preset === "node-server" && !desktopServerEntry) {
12644
- await installFarmCompileCacheLauncher(path11.join(outputDir, "server"), fs4);
12981
+ await installFarmCompileCacheLauncher(path12.join(outputDir, "server"), fs4);
12645
12982
  }
12646
12983
  if (preset.startsWith("cloudflare")) {
12647
12984
  await populateCloudflareProcessEnv(nitroInstance.options.output.serverDir, fs4);
@@ -12662,7 +12999,12 @@ function toFarmNodeResponse(request, response) {
12662
12999
  config,
12663
13000
  farmWorkflows,
12664
13001
  routeRuntimeManifest,
12665
- farmCron.provider === "host" ? farmCron.jobs : []
13002
+ farmCron.provider === "host" ? farmCron.jobs : [],
13003
+ {
13004
+ buildDir: path12.join(root, distDir),
13005
+ middlewareRoutes: edgeMiddlewareRoutes,
13006
+ guardedPages: edgeGuardedPrerenderRoutes
13007
+ }
12666
13008
  );
12667
13009
  }
12668
13010
  logger.success(`\u2705 Nitro build completed with preset: ${preset}`);
@@ -12672,29 +13014,16 @@ function resolveFarmNitroOutputConfig(preset, outputDir) {
12672
13014
  return {
12673
13015
  dir: outputDir,
12674
13016
  ...preset === "node-server" ? {
12675
- serverDir: path11.join(outputDir, "server"),
12676
- publicDir: path11.join(outputDir, "public")
13017
+ serverDir: path12.join(outputDir, "server"),
13018
+ publicDir: path12.join(outputDir, "public")
12677
13019
  } : isVercel ? {
12678
- serverDir: path11.join(outputDir, "functions", "__nitro.func"),
12679
- publicDir: path11.join(outputDir, "static")
13020
+ serverDir: path12.join(outputDir, "functions", "__nitro.func"),
13021
+ publicDir: path12.join(outputDir, "static")
12680
13022
  } : {}
12681
13023
  };
12682
13024
  }
12683
- var CLOUDFLARE_POPULATE_PROCESS_ENV_FLAG = "nodejs_compat_populate_process_env";
12684
- var CLOUDFLARE_DO_NOT_POPULATE_PROCESS_ENV_FLAG = "nodejs_compat_do_not_populate_process_env";
12685
- var CLOUDFLARE_POPULATE_PROCESS_ENV_DATE = "2025-04-01";
12686
- function resolveCloudflareProcessEnvFlags(wrangler) {
12687
- const date = wrangler.compatibility_date;
12688
- const flags = wrangler.compatibility_flags;
12689
- if (typeof date !== "string" || date >= CLOUDFLARE_POPULATE_PROCESS_ENV_DATE) return void 0;
12690
- if (!Array.isArray(flags) || !flags.includes("nodejs_compat")) return void 0;
12691
- if (flags.includes(CLOUDFLARE_POPULATE_PROCESS_ENV_FLAG) || flags.includes(CLOUDFLARE_DO_NOT_POPULATE_PROCESS_ENV_FLAG)) {
12692
- return void 0;
12693
- }
12694
- return [...flags, CLOUDFLARE_POPULATE_PROCESS_ENV_FLAG];
12695
- }
12696
13025
  async function populateCloudflareProcessEnv(serverDir, fs4) {
12697
- const wranglerPath = path11.join(serverDir, "wrangler.json");
13026
+ const wranglerPath = path12.join(serverDir, "wrangler.json");
12698
13027
  let source;
12699
13028
  try {
12700
13029
  source = await fs4.readFile(wranglerPath, "utf8");
@@ -12722,8 +13051,8 @@ async function writeSSRBundleFiles(files, targetDir, fs4) {
12722
13051
  await fs4.rm(targetDir, { recursive: true, force: true });
12723
13052
  await Promise.all(
12724
13053
  files.map(async ({ fileName, contents }) => {
12725
- const targetPath = path11.join(targetDir, fileName);
12726
- await fs4.mkdir(path11.dirname(targetPath), { recursive: true });
13054
+ const targetPath = path12.join(targetDir, fileName);
13055
+ await fs4.mkdir(path12.dirname(targetPath), { recursive: true });
12727
13056
  await fs4.writeFile(targetPath, contents);
12728
13057
  })
12729
13058
  );
@@ -12732,8 +13061,8 @@ async function copyPrebuiltSSRBundle(ssrBundle, targetDir, minifyOptions, fs4) {
12732
13061
  await writeSSRBundleFiles(await prepareSSRBundleFiles(ssrBundle, minifyOptions), targetDir, fs4);
12733
13062
  }
12734
13063
  async function installFarmCompileCacheLauncher(serverDir, fs4) {
12735
- const entryPath = path11.join(serverDir, "index.mjs");
12736
- const serverPath = path11.join(serverDir, FARM_SERVER_MODULE_FILE);
13064
+ const entryPath = path12.join(serverDir, "index.mjs");
13065
+ const serverPath = path12.join(serverDir, FARM_SERVER_MODULE_FILE);
12737
13066
  const entry = await fs4.readFile(entryPath, "utf8").catch((error) => {
12738
13067
  if (error.code === "ENOENT") return null;
12739
13068
  throw error;
@@ -12742,11 +13071,11 @@ async function installFarmCompileCacheLauncher(serverDir, fs4) {
12742
13071
  if (entry.includes(`./${FARM_SERVER_MODULE_FILE}`)) return false;
12743
13072
  await fs4.rename(entryPath, serverPath);
12744
13073
  await fs4.writeFile(entryPath, createFarmCompileCacheLauncher(FARM_SERVER_MODULE_FILE));
12745
- await fs4.rm(path11.join(serverDir, FARM_COMPILE_CACHE_DIR), { recursive: true, force: true });
13074
+ await fs4.rm(path12.join(serverDir, FARM_COMPILE_CACHE_DIR), { recursive: true, force: true });
12746
13075
  return true;
12747
13076
  }
12748
13077
  async function registerPrebuiltSSRPackageImport(serverDir, ssrEntryFile, fs4) {
12749
- const packagePath = path11.join(serverDir, "package.json");
13078
+ const packagePath = path12.join(serverDir, "package.json");
12750
13079
  const packageJSON = await fs4.readFile(packagePath, "utf8").then((contents) => JSON.parse(contents)).catch((error) => {
12751
13080
  if (error.code === "ENOENT") return { type: "module" };
12752
13081
  throw error;
@@ -12774,19 +13103,19 @@ async function moveVercelOutputPath(src, dest, fs4) {
12774
13103
  await fs4.cp(src, dest, { recursive: true, force: true });
12775
13104
  await fs4.rm(src, { recursive: true, force: true });
12776
13105
  }
12777
- async function postProcessVercelOutput(root, outputDir, fs4, config, farmWorkflows, routeRuntimeManifest, cronJobs) {
12778
- const serverDir = path11.join(outputDir, "server");
12779
- const functionsDir = path11.join(outputDir, "functions");
12780
- const nitroFuncDir = path11.join(functionsDir, "__nitro.func");
12781
- const staticDir = path11.join(outputDir, "static");
12782
- const publicDir = path11.join(outputDir, "public");
13106
+ async function postProcessVercelOutput(root, outputDir, fs4, config, farmWorkflows, routeRuntimeManifest, cronJobs, edgeMiddleware) {
13107
+ const serverDir = path12.join(outputDir, "server");
13108
+ const functionsDir = path12.join(outputDir, "functions");
13109
+ const nitroFuncDir = path12.join(functionsDir, "__nitro.func");
13110
+ const staticDir = path12.join(outputDir, "static");
13111
+ const publicDir = path12.join(outputDir, "public");
12783
13112
  await fs4.mkdir(nitroFuncDir, { recursive: true });
12784
13113
  const serverContents = await fs4.readdir(serverDir).catch((error) => {
12785
13114
  if (error.code === "ENOENT") return [];
12786
13115
  throw error;
12787
13116
  });
12788
13117
  for (const file of serverContents) {
12789
- await moveVercelOutputPath(path11.join(serverDir, file), path11.join(nitroFuncDir, file), fs4);
13118
+ await moveVercelOutputPath(path12.join(serverDir, file), path12.join(nitroFuncDir, file), fs4);
12790
13119
  }
12791
13120
  if (serverContents.length > 0) await fs4.rm(serverDir, { recursive: true, force: true });
12792
13121
  try {
@@ -12796,7 +13125,7 @@ async function postProcessVercelOutput(root, outputDir, fs4, config, farmWorkflo
12796
13125
  }
12797
13126
  await copyFarmDocsContentForVercel(config, root, nitroFuncDir, fs4);
12798
13127
  await copyPrismaClientForVercel(root, nitroFuncDir, fs4);
12799
- const configPath = path11.join(outputDir, "config.json");
13128
+ const configPath = path12.join(outputDir, "config.json");
12800
13129
  const configContent = await fs4.readFile(configPath, "utf-8");
12801
13130
  const vercelConfig = JSON.parse(configContent);
12802
13131
  const runtimeRoutes = await createFarmVercelRouteRuntimeFunctions(
@@ -12805,9 +13134,24 @@ async function postProcessVercelOutput(root, outputDir, fs4, config, farmWorkflo
12805
13134
  fs4,
12806
13135
  config.basePath
12807
13136
  );
13137
+ const edgeMiddlewareRoutes = edgeMiddleware.middlewareRoutes.filter(
13138
+ (route) => edgeMiddleware.guardedPages.some((pathname) => appMiddlewareMayHandlePath([route], pathname))
13139
+ );
13140
+ if (edgeMiddlewareRoutes.length > 0) {
13141
+ await writeFarmVercelEdgeMiddlewareFunction({
13142
+ root,
13143
+ outputDir,
13144
+ buildDir: edgeMiddleware.buildDir,
13145
+ config,
13146
+ routes: edgeMiddlewareRoutes,
13147
+ guardedPages: edgeMiddleware.guardedPages,
13148
+ fs: fs4
13149
+ });
13150
+ }
12808
13151
  vercelConfig.routes = buildFarmVercelRoutes({
12809
13152
  presetRoutes: Array.isArray(vercelConfig.routes) ? vercelConfig.routes : [],
12810
- runtimeRoutes
13153
+ runtimeRoutes,
13154
+ middlewareRoutes: edgeMiddlewareRoutes.length > 0 ? [createFarmVercelEdgeMiddlewareRoute(edgeMiddleware.guardedPages, config.basePath)] : []
12811
13155
  });
12812
13156
  const vercelConfigWithWorkflowCrons = applyFarmWorkflowVercelCrons(
12813
13157
  vercelConfig,
@@ -12824,7 +13168,7 @@ async function copyFarmDocsContentForVercel(config, root, nitroFuncDir, fs4) {
12824
13168
  mainRoot,
12825
13169
  root,
12826
13170
  config.srcDir,
12827
- path11.join(nitroFuncDir, "farm-docs-content"),
13171
+ path12.join(nitroFuncDir, "farm-docs-content"),
12828
13172
  fs4
12829
13173
  );
12830
13174
  for (const [index, docsRoot] of extraRoots.entries()) {
@@ -12832,7 +13176,7 @@ async function copyFarmDocsContentForVercel(config, root, nitroFuncDir, fs4) {
12832
13176
  docsRoot,
12833
13177
  root,
12834
13178
  config.srcDir,
12835
- path11.join(nitroFuncDir, "farm-docs-roots", String(index)),
13179
+ path12.join(nitroFuncDir, "farm-docs-roots", String(index)),
12836
13180
  fs4
12837
13181
  );
12838
13182
  }
@@ -12850,17 +13194,17 @@ async function copyFarmDocsRootContent(docs, root, srcDir, bundledContentDir, fs
12850
13194
  );
12851
13195
  }
12852
13196
  await fs4.rm(bundledContentDir, { recursive: true, force: true });
12853
- await fs4.mkdir(path11.dirname(bundledContentDir), { recursive: true });
13197
+ await fs4.mkdir(path12.dirname(bundledContentDir), { recursive: true });
12854
13198
  await fs4.cp(docsContentDir, bundledContentDir, {
12855
13199
  recursive: true,
12856
13200
  force: true
12857
13201
  });
12858
13202
  await fs4.writeFile(
12859
- path11.join(bundledContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST),
13203
+ path12.join(bundledContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST),
12860
13204
  `${JSON.stringify(lastModifiedManifest, null, 2)}
12861
13205
  `
12862
13206
  );
12863
- logger.info(`\u{1F4DA} Bundled docs content for Vercel: ${path11.relative(root, docsContentDir)}`);
13207
+ logger.info(`\u{1F4DA} Bundled docs content for Vercel: ${path12.relative(root, docsContentDir)}`);
12864
13208
  }
12865
13209
  function resolveServerFunctionPlatform(preset) {
12866
13210
  return preset === "vercel" || preset === "netlify" ? { os: "linux", cpu: "x64", libc: "glibc" } : null;
@@ -12877,20 +13221,20 @@ function platformFieldAllows(field, value) {
12877
13221
  }
12878
13222
  async function stageSharpRuntime(config, root, distDir, fs4, preset) {
12879
13223
  const functionPlatform = resolveServerFunctionPlatform(preset);
12880
- const projectRequire = createRequire(path11.join(root, "package.json"));
13224
+ const projectRequire = createRequire2(path12.join(root, "package.json"));
12881
13225
  let sharpRequire = projectRequire;
12882
13226
  if (!resolvePackageJson(projectRequire, "sharp")) {
12883
13227
  try {
12884
- sharpRequire = createRequire(projectRequire.resolve("@farm.js/core"));
13228
+ sharpRequire = createRequire2(projectRequire.resolve("@farm.js/core"));
12885
13229
  } catch {
12886
13230
  }
12887
13231
  }
12888
13232
  const copiedPackages = /* @__PURE__ */ new Map();
12889
13233
  const packageCopies = /* @__PURE__ */ new Map();
12890
- const stageRoot = path11.join(root, distDir, "tmp");
13234
+ const stageRoot = path12.join(root, distDir, "tmp");
12891
13235
  await fs4.mkdir(stageRoot, { recursive: true });
12892
- const stageDir = await fs4.mkdtemp(path11.join(stageRoot, "sharp-runtime-"));
12893
- const targetNodeModules = path11.join(stageDir, "node_modules");
13236
+ const stageDir = await fs4.mkdtemp(path12.join(stageRoot, "sharp-runtime-"));
13237
+ const targetNodeModules = path12.join(stageDir, "node_modules");
12894
13238
  function copyPackage(packageName, parentRequire) {
12895
13239
  const activeCopy = packageCopies.get(packageName);
12896
13240
  if (activeCopy) return activeCopy;
@@ -12903,11 +13247,11 @@ async function stageSharpRuntime(config, root, distDir, fs4, preset) {
12903
13247
  if (!packageJsonPath) return;
12904
13248
  const packageJson = JSON.parse(await fs4.readFile(packageJsonPath, "utf8"));
12905
13249
  if (functionPlatform && !packageSupportsPlatform(packageJson, functionPlatform)) return;
12906
- const packageDir = path11.dirname(packageJsonPath);
12907
- const targetDir = path11.join(targetNodeModules, ...packageName.split("/"));
13250
+ const packageDir = path12.dirname(packageJsonPath);
13251
+ const targetDir = path12.join(targetNodeModules, ...packageName.split("/"));
12908
13252
  copiedPackages.set(packageName, String(packageJson.version || "*"));
12909
- await fs4.mkdir(path11.dirname(targetDir), { recursive: true });
12910
- const packageRequire = createRequire(packageJsonPath);
13253
+ await fs4.mkdir(path12.dirname(targetDir), { recursive: true });
13254
+ const packageRequire = createRequire2(packageJsonPath);
12911
13255
  const dependencies = {
12912
13256
  ...packageJson.dependencies,
12913
13257
  ...packageJson.optionalDependencies
@@ -12941,8 +13285,8 @@ async function stageSharpRuntime(config, root, distDir, fs4, preset) {
12941
13285
  };
12942
13286
  }
12943
13287
  async function installStagedSharpRuntime(staged, nitroFuncDir, fs4) {
12944
- const stagedNodeModules = path11.join(staged.stageDir, "node_modules");
12945
- const targetNodeModules = path11.join(nitroFuncDir, "node_modules");
13288
+ const stagedNodeModules = path12.join(staged.stageDir, "node_modules");
13289
+ const targetNodeModules = path12.join(nitroFuncDir, "node_modules");
12946
13290
  try {
12947
13291
  await mergeStagedDirectory(stagedNodeModules, targetNodeModules, fs4);
12948
13292
  const functionPackage = await readNitroOutputPackage(nitroFuncDir, fs4);
@@ -12970,8 +13314,8 @@ async function mergeStagedDirectory(sourceDir, targetDir, fs4) {
12970
13314
  const entries = await fs4.readdir(sourceDir, { withFileTypes: true });
12971
13315
  await settleAllOrThrow(
12972
13316
  entries.map(async (entry) => {
12973
- const sourcePath = path11.join(sourceDir, entry.name);
12974
- const targetPath = path11.join(targetDir, entry.name);
13317
+ const sourcePath = path12.join(sourceDir, entry.name);
13318
+ const targetPath = path12.join(targetDir, entry.name);
12975
13319
  try {
12976
13320
  await fs4.rename(sourcePath, targetPath);
12977
13321
  return;
@@ -12998,17 +13342,17 @@ async function mergeStagedDirectory(sourceDir, targetDir, fs4) {
12998
13342
  function assertMetadataImageRuntimeInstalled(root, metadataImageRoutes) {
12999
13343
  const generated = metadataImageRoutes.find((image) => image.sourceType === "module");
13000
13344
  if (!generated || resolveMetadataImageRuntimePackageJson(root)) return;
13001
- const file = generated.modulePath ? toPosixPath(path11.relative(root, generated.modulePath)) : "";
13345
+ const file = generated.modulePath ? toPosixPath(path12.relative(root, generated.modulePath)) : "";
13002
13346
  throw new Error(
13003
13347
  `${file || "A generated metadata image"} renders with @vercel/og, which is not installed. ${VERCEL_OG_INSTALL_HINT}`
13004
13348
  );
13005
13349
  }
13006
13350
  function resolveMetadataImageRuntimePackageJson(root) {
13007
- const projectRequire = createRequire(path11.join(root, "package.json"));
13351
+ const projectRequire = createRequire2(path12.join(root, "package.json"));
13008
13352
  const packageJsonPath = resolvePackageJson(projectRequire, "@vercel/og");
13009
13353
  if (packageJsonPath) return packageJsonPath;
13010
13354
  try {
13011
- return resolvePackageJson(createRequire(projectRequire.resolve("@farm.js/core")), "@vercel/og");
13355
+ return resolvePackageJson(createRequire2(projectRequire.resolve("@farm.js/core")), "@vercel/og");
13012
13356
  } catch {
13013
13357
  return null;
13014
13358
  }
@@ -13017,9 +13361,9 @@ async function copyMetadataImageRuntime(root, nitroFuncDir, fs4) {
13017
13361
  const packageJsonPath = resolveMetadataImageRuntimePackageJson(root);
13018
13362
  if (!packageJsonPath) return;
13019
13363
  const packageJson = JSON.parse(await fs4.readFile(packageJsonPath, "utf8"));
13020
- const packageDir = path11.dirname(packageJsonPath);
13021
- const targetDir = path11.join(nitroFuncDir, "node_modules", "@vercel", "og");
13022
- await fs4.mkdir(path11.dirname(targetDir), { recursive: true });
13364
+ const packageDir = path12.dirname(packageJsonPath);
13365
+ const targetDir = path12.join(nitroFuncDir, "node_modules", "@vercel", "og");
13366
+ await fs4.mkdir(path12.dirname(targetDir), { recursive: true });
13023
13367
  await fs4.cp(packageDir, targetDir, {
13024
13368
  recursive: true,
13025
13369
  force: true,
@@ -13035,7 +13379,7 @@ async function copyMetadataImageRuntime(root, nitroFuncDir, fs4) {
13035
13379
  logger.info("\u{1F5BC}\uFE0F Bundled generated metadata image runtime");
13036
13380
  }
13037
13381
  async function readNitroOutputPackage(outputDir, fs4) {
13038
- const packagePath = path11.join(outputDir, "package.json");
13382
+ const packagePath = path12.join(outputDir, "package.json");
13039
13383
  return fs4.readFile(packagePath, "utf8").then((contents) => JSON.parse(contents)).catch((error) => {
13040
13384
  if (error.code === "ENOENT") return {};
13041
13385
  throw error;
@@ -13044,7 +13388,7 @@ async function readNitroOutputPackage(outputDir, fs4) {
13044
13388
  async function writeNitroOutputPackage(outputDir, packageJson, fs4) {
13045
13389
  await fs4.mkdir(outputDir, { recursive: true });
13046
13390
  await fs4.writeFile(
13047
- path11.join(outputDir, "package.json"),
13391
+ path12.join(outputDir, "package.json"),
13048
13392
  `${JSON.stringify(packageJson, null, 2)}
13049
13393
  `
13050
13394
  );
@@ -13060,9 +13404,9 @@ function resolvePackageJson(parentRequire, packageName) {
13060
13404
  }
13061
13405
  }
13062
13406
  try {
13063
- let directory = path11.dirname(metadataModule ?? parentRequire.resolve(packageName));
13064
- while (directory !== path11.dirname(directory)) {
13065
- const candidate = path11.join(directory, "package.json");
13407
+ let directory = path12.dirname(metadataModule ?? parentRequire.resolve(packageName));
13408
+ while (directory !== path12.dirname(directory)) {
13409
+ const candidate = path12.join(directory, "package.json");
13066
13410
  if (existsSync2(candidate)) {
13067
13411
  try {
13068
13412
  const manifest = JSON.parse(readFileSync(candidate, "utf8"));
@@ -13070,31 +13414,40 @@ function resolvePackageJson(parentRequire, packageName) {
13070
13414
  } catch {
13071
13415
  }
13072
13416
  }
13073
- if (path11.basename(directory) === "node_modules") break;
13074
- directory = path11.dirname(directory);
13417
+ if (path12.basename(directory) === "node_modules") break;
13418
+ directory = path12.dirname(directory);
13075
13419
  }
13076
13420
  } catch {
13077
13421
  }
13078
13422
  return null;
13079
13423
  }
13080
- async function copyPrismaClientForVercel(root, nitroFuncDir, fs4) {
13081
- const projectRequire = createRequire(path11.join(root, "package.json"));
13082
- let prismaClientDir;
13083
- try {
13084
- prismaClientDir = path11.dirname(projectRequire.resolve("@prisma/client/default.js"));
13085
- } catch {
13086
- return;
13424
+ async function resolveProjectInstalledPackageDir(root, packageName, fs4) {
13425
+ let directory = path12.resolve(root);
13426
+ while (true) {
13427
+ const candidate = path12.join(directory, "node_modules", ...packageName.split("/"));
13428
+ try {
13429
+ const packageDir = await fs4.realpath(candidate);
13430
+ if ((await fs4.stat(path12.join(packageDir, "package.json"))).isFile()) return packageDir;
13431
+ } catch {
13432
+ }
13433
+ const parent = path12.dirname(directory);
13434
+ if (parent === directory) return null;
13435
+ directory = parent;
13087
13436
  }
13088
- const generatedClientDir = path11.join(prismaClientDir, "..", "..", ".prisma", "client");
13437
+ }
13438
+ async function copyPrismaClientForVercel(root, nitroFuncDir, fs4) {
13439
+ const prismaClientDir = await resolveProjectInstalledPackageDir(root, "@prisma/client", fs4);
13440
+ if (!prismaClientDir) return;
13441
+ const generatedClientDir = path12.join(prismaClientDir, "..", "..", ".prisma", "client");
13089
13442
  try {
13090
13443
  await fs4.access(generatedClientDir);
13091
13444
  } catch {
13092
13445
  return;
13093
13446
  }
13094
- const targetNodeModules = path11.join(nitroFuncDir, "node_modules");
13095
- const targetPrismaScopeDir = path11.join(targetNodeModules, "@prisma");
13096
- const targetGeneratedDir = path11.join(targetNodeModules, ".prisma", "client");
13097
- const targetClientDir = path11.join(targetPrismaScopeDir, "client");
13447
+ const targetNodeModules = path12.join(nitroFuncDir, "node_modules");
13448
+ const targetPrismaScopeDir = path12.join(targetNodeModules, "@prisma");
13449
+ const targetGeneratedDir = path12.join(targetNodeModules, ".prisma", "client");
13450
+ const targetClientDir = path12.join(targetPrismaScopeDir, "client");
13098
13451
  await fs4.mkdir(targetPrismaScopeDir, { recursive: true });
13099
13452
  await fs4.cp(prismaClientDir, targetClientDir, {
13100
13453
  recursive: true,
@@ -13104,7 +13457,7 @@ async function copyPrismaClientForVercel(root, nitroFuncDir, fs4) {
13104
13457
  recursive: true,
13105
13458
  force: true
13106
13459
  });
13107
- const clientPackagePath = path11.join(prismaClientDir, "package.json");
13460
+ const clientPackagePath = path12.join(prismaClientDir, "package.json");
13108
13461
  const [functionPackage, clientPackageContent] = await Promise.all([
13109
13462
  readNitroOutputPackage(nitroFuncDir, fs4),
13110
13463
  fs4.readFile(clientPackagePath, "utf-8")
@@ -13290,9 +13643,9 @@ async function buildWithProductionNodeEnv(inputConfig, options) {
13290
13643
  } else {
13291
13644
  const { build: legacyViteBuild } = await import("vite");
13292
13645
  logger.info("\u{1F4E6} Building client bundle...");
13293
- await buildClient2(legacyViteBuild, config, root, srcDir, path12.join(root, distDir, "client"));
13646
+ await buildClient2(legacyViteBuild, config, root, srcDir, path13.join(root, distDir, "client"));
13294
13647
  logger.info("\u{1F4E6} Building SSR bundle...");
13295
- await buildSSR(legacyViteBuild, config, root, srcDir, path12.join(root, distDir, "server"));
13648
+ await buildSSR(legacyViteBuild, config, root, srcDir, path13.join(root, distDir, "server"));
13296
13649
  logger.info(`\u{1F680} Building server with Nitro (preset: ${preset})...`);
13297
13650
  await buildNitro(
13298
13651
  config,
@@ -13369,8 +13722,10 @@ async function createProjectModuleServer(createViteServer, config, root, buildLi
13369
13722
  }),
13370
13723
  farmEnvironmentFunctionsPlugin(),
13371
13724
  // Route modules load here at build time (rendering config, prerendering): `server-only`
13372
- // resolves as it does in the server build.
13373
- farmServerOnlyEntriesPlugin()
13725
+ // resolves as it does in the server build. Module-entry packages load pre-bundled, as in
13726
+ // `farm dev`: unbundled, lucide-react alone is ~1,750 modules through the module runner,
13727
+ // which a docs build waited on after its bundles.
13728
+ farmServerOnlyEntriesPlugin({ prebundleServerPackages: true })
13374
13729
  ],
13375
13730
  server: {
13376
13731
  middlewareMode: true,
@@ -13390,6 +13745,12 @@ async function createProjectModuleServer(createViteServer, config, root, buildLi
13390
13745
  return createViteServer({
13391
13746
  ...viteConfig,
13392
13747
  root,
13748
+ // Vite keys its pre-bundled dependencies on the config, mode included, so this server and
13749
+ // `farm dev` sharing one cache would each rebuild it after the other ran.
13750
+ cacheDir: path13.join(
13751
+ path13.resolve(root, viteConfig.cacheDir ?? path13.join("node_modules", ".vite")),
13752
+ "farm-build"
13753
+ ),
13393
13754
  configFile: false,
13394
13755
  appType: "custom",
13395
13756
  mode: "production",
@@ -13480,16 +13841,16 @@ async function buildSSR(viteBuild, config, root, srcDir, outputDir) {
13480
13841
  });
13481
13842
  }
13482
13843
  function resolveLegacyPageEntry(config, root, srcDir) {
13483
- const appDir = path12.join(root, srcDir, "app");
13844
+ const appDir = path13.join(root, srcDir, "app");
13484
13845
  for (const extension of getFarmRendererComponentExtensions(config.renderer)) {
13485
- const candidate = path12.join(appDir, `page${extension}`);
13846
+ const candidate = path13.join(appDir, `page${extension}`);
13486
13847
  if (existsSync3(candidate)) return candidate;
13487
13848
  }
13488
- return path12.join(appDir, "page.tsx");
13849
+ return path13.join(appDir, "page.tsx");
13489
13850
  }
13490
13851
  async function buildNitro(config, routeManager, apiRouteManager, serverRenderer, preset, root, distDir, pluginManager) {
13491
13852
  const [{ createNitroConfig }, { createNitro, build: nitroBuild }] = await Promise.all([
13492
- import("./nitro-55YOZWRA.mjs"),
13853
+ import("./nitro-NSTXT7LB.mjs"),
13493
13854
  import("nitro/builder")
13494
13855
  ]);
13495
13856
  let nitroConfig = await createNitroConfig(
@@ -13503,18 +13864,18 @@ async function buildNitro(config, routeManager, apiRouteManager, serverRenderer,
13503
13864
  nitroConfig = await pluginManager.runHookSerial("beforeNitroBuild", nitroConfig);
13504
13865
  }
13505
13866
  const outputDir = resolveDeployOutputPath(root, config.deploy.outputDir);
13506
- const serverOutputDir = path12.join(outputDir, "server");
13507
- const publicOutputDir = path12.join(outputDir, "public");
13867
+ const serverOutputDir = path13.join(outputDir, "server");
13868
+ const publicOutputDir = path13.join(outputDir, "public");
13508
13869
  const { mkdir, cp } = await import("fs/promises");
13509
13870
  await mkdir(serverOutputDir, { recursive: true });
13510
13871
  await mkdir(publicOutputDir, { recursive: true });
13511
- const clientDir = path12.join(root, distDir, "client");
13872
+ const clientDir = path13.join(root, distDir, "client");
13512
13873
  try {
13513
13874
  await mkdir(publicOutputDir, { recursive: true });
13514
13875
  await cp(clientDir, publicOutputDir, { recursive: true });
13515
13876
  logger.info("\u{1F4E6} Copied client assets to public directory");
13516
- const manifestPath = path12.join(publicOutputDir, "farm-client-manifest.json");
13517
- const assetsDir = path12.join(publicOutputDir, "assets");
13877
+ const manifestPath = path13.join(publicOutputDir, "farm-client-manifest.json");
13878
+ const assetsDir = path13.join(publicOutputDir, "assets");
13518
13879
  const manifestExists = await import("fs/promises").then(
13519
13880
  (fs4) => fs4.access(manifestPath).then(() => true).catch(() => false)
13520
13881
  );
@@ -13530,8 +13891,8 @@ async function buildNitro(config, routeManager, apiRouteManager, serverRenderer,
13530
13891
  logger.error(`\u274C Failed to copy client assets: ${error}`);
13531
13892
  throw error;
13532
13893
  }
13533
- const serverDir = path12.join(root, distDir, "server");
13534
- const nitroServerDir = path12.join(root, distDir, ".nitro", "server", "farm");
13894
+ const serverDir = path13.join(root, distDir, "server");
13895
+ const nitroServerDir = path13.join(root, distDir, ".nitro", "server", "farm");
13535
13896
  try {
13536
13897
  await mkdir(nitroServerDir, { recursive: true });
13537
13898
  await cp(serverDir, nitroServerDir, { recursive: true });
@@ -13540,7 +13901,7 @@ async function buildNitro(config, routeManager, apiRouteManager, serverRenderer,
13540
13901
  logger.warn(`Could not copy SSR bundles: ${error}`);
13541
13902
  }
13542
13903
  const nitro = await createNitro(nitroConfig);
13543
- const registryPath = path12.join(root, distDir, ".nitro", "server", "farm-registry.ts");
13904
+ const registryPath = path13.join(root, distDir, ".nitro", "server", "farm-registry.ts");
13544
13905
  try {
13545
13906
  const { farmRegistry } = await import(
13546
13907
  /* @vite-ignore */
@@ -13557,7 +13918,7 @@ async function buildNitro(config, routeManager, apiRouteManager, serverRenderer,
13557
13918
  }
13558
13919
  farmRegistry.routePaths = routePaths;
13559
13920
  try {
13560
- const clientManifestPath = path12.join(root, distDir, "client", "farm-client-manifest.json");
13921
+ const clientManifestPath = path13.join(root, distDir, "client", "farm-client-manifest.json");
13561
13922
  const { readFile } = await import("fs/promises");
13562
13923
  const manifestContent = await readFile(clientManifestPath, "utf-8");
13563
13924
  farmRegistry.clientManifest = JSON.parse(manifestContent);