@farm.js/core 0.1.66 → 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 (494) hide show
  1. package/dist/{agent-mcp-handler-QLFDDTYN.mjs → agent-mcp-handler-AZ7QW4UP.mjs} +5 -5
  2. package/dist/{agent-mcp-handler-OXT73ZBY.cjs → agent-mcp-handler-FER4MQDF.cjs} +6 -6
  3. package/dist/{agent-mcp.d-QD2WZ9BS.d.ts → agent-mcp.d-Uh5xr7aX.d.ts} +1 -1
  4. package/dist/{agent-mcp.d-CO_ABmNK.d.mts → agent-mcp.d-wkVPK1GA.d.mts} +1 -1
  5. package/dist/agent-runtime.cjs +6 -5
  6. package/dist/agent-runtime.d.mts +10 -8
  7. package/dist/agent-runtime.d.ts +10 -8
  8. package/dist/agent-runtime.mjs +5 -4
  9. package/dist/{analyzer-4UFP4HVP.mjs → analyzer-CQDU7E3Y.mjs} +2 -2
  10. package/dist/analyzer-PPAHM4AW.cjs +16 -0
  11. package/dist/api/client.cjs +12 -2
  12. package/dist/api/client.d.mts +4 -4
  13. package/dist/api/client.d.ts +4 -4
  14. package/dist/api/client.mjs +12 -2
  15. package/dist/api/client.native.cjs +12 -2
  16. package/dist/api/client.native.d.mts +5 -5
  17. package/dist/api/client.native.d.ts +5 -5
  18. package/dist/api/client.native.mjs +12 -2
  19. package/dist/api/node.cjs +223 -0
  20. package/dist/api/node.d.mts +61 -0
  21. package/dist/api/node.d.ts +61 -0
  22. package/dist/api/node.mjs +223 -0
  23. package/dist/api/route-manager.cjs +11 -11
  24. package/dist/api/route-manager.d.mts +14 -11
  25. package/dist/api/route-manager.d.ts +14 -11
  26. package/dist/api/route-manager.mjs +10 -10
  27. package/dist/api/runtime.cjs +11 -7
  28. package/dist/api/runtime.d.mts +11 -9
  29. package/dist/api/runtime.d.ts +11 -9
  30. package/dist/api/runtime.mjs +10 -6
  31. package/dist/{api-client.d-BNLXNCXJ.d.mts → api-client.d-Bp35zMqR.d.mts} +1 -1
  32. package/dist/{api-client.d-ddQBNGtu.d.ts → api-client.d-CFI_xL0V.d.ts} +1 -1
  33. package/dist/api.cjs +17 -13
  34. package/dist/api.d.mts +15 -12
  35. package/dist/api.d.ts +15 -12
  36. package/dist/api.mjs +16 -12
  37. package/dist/{app-manifest.d-DDmNkYQQ.d.ts → app-manifest.d-BT5i2F-o.d.ts} +1 -1
  38. package/dist/{app-manifest.d-BpKxiU_E.d.mts → app-manifest.d-Dd4q5CFx.d.mts} +1 -1
  39. package/dist/app-markdown.cjs +5 -5
  40. package/dist/app-markdown.d.mts +15 -15
  41. package/dist/app-markdown.d.ts +15 -15
  42. package/dist/app-markdown.mjs +4 -4
  43. package/dist/{app.d-x68Cwr0_.d.ts → app.d-BVOpL_f2.d.ts} +52 -11
  44. package/dist/{app.d-kuoVWhWM.d.mts → app.d-BhiDXex_.d.mts} +52 -11
  45. package/dist/{chunk-RY4ABNPE.cjs → chunk-225APHKC.cjs} +3 -3
  46. package/dist/{chunk-JGAE5XPL.cjs → chunk-23VJEGKC.cjs} +4 -2
  47. package/dist/{chunk-5C7XMKQ4.cjs → chunk-2AFW7673.cjs} +6 -1
  48. package/dist/{chunk-SYW346ZN.cjs → chunk-2LHZD3OP.cjs} +1 -21
  49. package/dist/{chunk-ZZI56IUY.mjs → chunk-2ZOYOYEE.mjs} +13 -13
  50. package/dist/{chunk-7XGWBPQQ.cjs → chunk-3EEINK7G.cjs} +24 -10
  51. package/dist/{chunk-BRWIVOV4.cjs → chunk-3GNHJ3RN.cjs} +10 -8
  52. package/dist/{chunk-HCGWDRZO.mjs → chunk-3Y52TWYU.mjs} +18 -7
  53. package/dist/{chunk-CBOEJ5Z4.cjs → chunk-437QZIC2.cjs} +133 -46
  54. package/dist/{chunk-O6L3YYPM.cjs → chunk-4E57QHPW.cjs} +8 -16
  55. package/dist/{chunk-WKPBIT5Q.cjs → chunk-4HGLJOXZ.cjs} +6 -6
  56. package/dist/{chunk-CJNAUEVC.mjs → chunk-4QENVMG7.mjs} +1 -1
  57. package/dist/{chunk-EMNKZGF4.mjs → chunk-4UAQB5LB.mjs} +556 -462
  58. package/dist/{chunk-BQWBHWEW.mjs → chunk-4ZXKYCYK.mjs} +1 -1
  59. package/dist/{chunk-N35YPV4N.mjs → chunk-57QAQU4F.mjs} +9 -7
  60. package/dist/{chunk-ZEXE4TGY.mjs → chunk-5FBZJJGA.mjs} +247 -110
  61. package/dist/{chunk-4OSOLDPL.cjs → chunk-5JKDFRTK.cjs} +2 -2
  62. package/dist/{chunk-OLIGNTWU.cjs → chunk-5NFQ6AZI.cjs} +7 -7
  63. package/dist/{chunk-6HRAK7I5.mjs → chunk-5OFNUETM.mjs} +8 -2
  64. package/dist/{chunk-RD623KW4.cjs → chunk-67MZTLTF.cjs} +21 -3
  65. package/dist/chunk-6I4BFRE7.cjs +51 -0
  66. package/dist/{chunk-UBMHQVWN.mjs → chunk-6OFOIMNS.mjs} +1 -1
  67. package/dist/{chunk-K5EW7GUU.mjs → chunk-7BIW7VCW.mjs} +13 -5
  68. package/dist/{chunk-CHYTADNK.cjs → chunk-7LK5CTUM.cjs} +70 -53
  69. package/dist/{chunk-HPP2II4Z.mjs → chunk-7PJARAQQ.mjs} +1 -1
  70. package/dist/{chunk-LEJDW34D.cjs → chunk-7PPLTD3P.cjs} +3 -3
  71. package/dist/{chunk-BYRZ5VTH.mjs → chunk-A3T445WK.mjs} +47 -34
  72. package/dist/{chunk-TGULJSHD.mjs → chunk-AJNBTOVQ.mjs} +20 -9
  73. package/dist/{chunk-FBEBSAVI.cjs → chunk-AKIQ54FK.cjs} +82 -63
  74. package/dist/{chunk-2NGZFOKG.mjs → chunk-AOIUYHPH.mjs} +2 -2
  75. package/dist/{chunk-NKRZLQUK.mjs → chunk-AQIO3RNL.mjs} +1 -1
  76. package/dist/chunk-AQIRXBBY.cjs +26 -0
  77. package/dist/{chunk-DQJ2CIH7.cjs → chunk-ASYOWPSR.cjs} +2 -1
  78. package/dist/chunk-AZ6IW6SF.mjs +28 -0
  79. package/dist/{chunk-QMDU6QHN.mjs → chunk-B6RBJJ5G.mjs} +1 -1
  80. package/dist/{chunk-I32V5CZL.cjs → chunk-BDYM2TN3.cjs} +28 -17
  81. package/dist/{chunk-JLDNXURZ.cjs → chunk-BZWTBELF.cjs} +32 -32
  82. package/dist/{chunk-ITV4QQL2.cjs → chunk-C6CUUBY5.cjs} +14 -3
  83. package/dist/{chunk-QGJ4FI2G.mjs → chunk-C6HGUTXB.mjs} +113 -29
  84. package/dist/{chunk-YN6BHOYY.cjs → chunk-CL52PD6D.cjs} +10 -3
  85. package/dist/{chunk-VQJHT2ND.mjs → chunk-CRVSYDHV.mjs} +2 -2
  86. package/dist/{chunk-XURDCXNH.cjs → chunk-CSLHNBPS.cjs} +6 -6
  87. package/dist/{chunk-XQSYOVCW.cjs → chunk-DBYNZIIQ.cjs} +13 -5
  88. package/dist/{chunk-AZUUKA66.mjs → chunk-DIXFKAPM.mjs} +1251 -389
  89. package/dist/{chunk-QTD6EMN2.mjs → chunk-DQ2DI3Y7.mjs} +11 -4
  90. package/dist/{chunk-NHQM2Q4I.cjs → chunk-DWLNLU55.cjs} +2 -2
  91. package/dist/chunk-DXZ57EPE.mjs +375 -0
  92. package/dist/{chunk-SA7MLSP4.mjs → chunk-E3HDJCWF.mjs} +3 -3
  93. package/dist/{chunk-52Y3C3HG.mjs → chunk-E7VF3LQ5.mjs} +3 -2
  94. package/dist/{chunk-752XUZIM.cjs → chunk-EGIY4A7V.cjs} +6 -6
  95. package/dist/chunk-EIVGPQN5.mjs +51 -0
  96. package/dist/{chunk-KPAJWD3N.mjs → chunk-EYPSKXO4.mjs} +1 -1
  97. package/dist/{chunk-E4UDLFWR.cjs → chunk-F36LS2C7.cjs} +796 -702
  98. package/dist/{chunk-MPIGW42F.mjs → chunk-F6CMGWAL.mjs} +1 -1
  99. package/dist/{chunk-GL7N5UHF.cjs → chunk-FJMC24KG.cjs} +21 -10
  100. package/dist/{chunk-QISW423S.cjs → chunk-FPBOAG6N.cjs} +2 -2
  101. package/dist/{chunk-3CCAICF7.cjs → chunk-FSODPZRT.cjs} +5 -5
  102. package/dist/{chunk-2C5L5RPM.cjs → chunk-FT6KJHS3.cjs} +71 -38
  103. package/dist/{chunk-WMTBBQHY.cjs → chunk-FVYBEMOD.cjs} +288 -151
  104. package/dist/{chunk-BM2LH2JM.mjs → chunk-G7NBPP7H.mjs} +14 -13
  105. package/dist/{chunk-ES2LD2YD.mjs → chunk-GCRT6GJG.mjs} +18 -0
  106. package/dist/{chunk-5OJVKXFV.cjs → chunk-GDM3ZD2O.cjs} +10 -8
  107. package/dist/{chunk-25T5VXOE.mjs → chunk-GFPS7MNE.mjs} +106 -19
  108. package/dist/{chunk-EMDGXYUD.mjs → chunk-GJ7QVFAG.mjs} +16 -7
  109. package/dist/{chunk-TGSEVBPO.mjs → chunk-GJEC5S4V.mjs} +11 -0
  110. package/dist/{chunk-HNAISJFD.cjs → chunk-HDPT6OYE.cjs} +9 -3
  111. package/dist/{chunk-RVGSVQWT.mjs → chunk-HEJM46HQ.mjs} +21 -7
  112. package/dist/chunk-HHLEYA4B.cjs +17 -0
  113. package/dist/{chunk-ZNH6NR3H.cjs → chunk-HJZZSBVK.cjs} +2 -2
  114. package/dist/{chunk-E552H232.cjs → chunk-I7J5RLGO.cjs} +16 -2
  115. package/dist/chunk-ICFPTHXM.mjs +97 -0
  116. package/dist/{chunk-K7OZAVOI.mjs → chunk-IFR74W6S.mjs} +46 -13
  117. package/dist/{chunk-MPJEIHW2.cjs → chunk-IGDYL2IA.cjs} +2 -2
  118. package/dist/{chunk-5A77OEIG.cjs → chunk-IHTDLCDJ.cjs} +5 -5
  119. package/dist/{chunk-OYZXVBZP.cjs → chunk-IUKBPBM7.cjs} +2 -1
  120. package/dist/chunk-J6TZRYCO.cjs +22 -0
  121. package/dist/{chunk-E4RDMG3K.mjs → chunk-JL2YW5KX.mjs} +5 -4
  122. package/dist/chunk-JSOCDYER.cjs +375 -0
  123. package/dist/{chunk-UPYIFH2H.cjs → chunk-JWLRBDDC.cjs} +2 -2
  124. package/dist/{chunk-OLGQZRW6.mjs → chunk-JZBU7V4D.mjs} +37 -17
  125. package/dist/{chunk-ONG4RDW3.mjs → chunk-JZGL2PIH.mjs} +13 -3
  126. package/dist/chunk-K63OWRY2.mjs +22 -0
  127. package/dist/{chunk-TUPKMMXT.mjs → chunk-K6HIIWUB.mjs} +1 -1
  128. package/dist/{chunk-MESQF2JC.mjs → chunk-K6SXMVXO.mjs} +2 -2
  129. package/dist/{chunk-L2JG337G.cjs → chunk-K6VFYFOY.cjs} +33 -31
  130. package/dist/{chunk-TKK5QHKZ.mjs → chunk-KDO6T6OB.mjs} +3 -3
  131. package/dist/{chunk-EZ34EHQP.mjs → chunk-KI3MU7B5.mjs} +1 -1
  132. package/dist/{chunk-GHNW564E.mjs → chunk-KSZK34HU.mjs} +30 -10
  133. package/dist/{chunk-IT6WRNGB.cjs → chunk-KWCZKJYU.cjs} +1541 -679
  134. package/dist/{chunk-DVKH2RVN.cjs → chunk-LDEXTX4I.cjs} +70 -57
  135. package/dist/{chunk-ECKQFEX2.mjs → chunk-LENKRGBV.mjs} +8 -6
  136. package/dist/{chunk-XBSKPLHF.cjs → chunk-LR4KP3I7.cjs} +2 -2
  137. package/dist/{chunk-HEPJIKKQ.cjs → chunk-MCSRMEQV.cjs} +2 -2
  138. package/dist/{chunk-DQF3QLOH.mjs → chunk-ME7RVELR.mjs} +3 -2
  139. package/dist/{chunk-VFXE6NWR.mjs → chunk-MGKWYPE3.mjs} +2 -1
  140. package/dist/{chunk-TZVUF5JJ.mjs → chunk-MGZVDX4R.mjs} +5 -5
  141. package/dist/{chunk-MGKW5XZE.cjs → chunk-MMDKYJ5V.cjs} +7 -7
  142. package/dist/{chunk-SK7QSNWE.mjs → chunk-MNJDNTGO.mjs} +1 -1
  143. package/dist/{chunk-5Y2P454O.cjs → chunk-MTBDJ326.cjs} +6 -5
  144. package/dist/{chunk-FIR62CR3.mjs → chunk-MV7NWU23.mjs} +1 -1
  145. package/dist/{chunk-7ONGIFYX.cjs → chunk-MZ4CRSY7.cjs} +481 -171
  146. package/dist/{chunk-O4F3JUST.mjs → chunk-NDDRTFN4.mjs} +4 -0
  147. package/dist/{chunk-4IHMHFQB.cjs → chunk-NG2EZ6QS.cjs} +28 -1
  148. package/dist/{chunk-XBSLKXBL.mjs → chunk-NT4W4H52.mjs} +52 -35
  149. package/dist/{chunk-UAQD67HM.mjs → chunk-NVOMQLI2.mjs} +16 -2
  150. package/dist/{chunk-R62SF5R4.mjs → chunk-OB45EAQL.mjs} +6 -1
  151. package/dist/{chunk-V56632LA.cjs → chunk-OCNV4CI2.cjs} +39 -6
  152. package/dist/{chunk-SYXPWJ7N.cjs → chunk-OFBLGH6V.cjs} +17 -18
  153. package/dist/{chunk-VQ4NWOWO.mjs → chunk-OGVTUGMU.mjs} +5 -13
  154. package/dist/{chunk-3UZVPO72.mjs → chunk-OIOPQ25L.mjs} +6 -7
  155. package/dist/{chunk-2XGBJSDV.cjs → chunk-OO7DYIJD.cjs} +73 -24
  156. package/dist/{chunk-27FPUFWR.mjs → chunk-P2NBQ5JI.mjs} +1 -1
  157. package/dist/{chunk-HZPKJRYA.cjs → chunk-PDFFYZAT.cjs} +2 -2
  158. package/dist/{chunk-GSVJ3IIF.cjs → chunk-PHCJJJZV.cjs} +2 -2
  159. package/dist/{chunk-EVMXPJCB.mjs → chunk-PKMUQ7LM.mjs} +2 -1
  160. package/dist/{chunk-OAJOQU5J.mjs → chunk-PLJKJJ2H.mjs} +82 -63
  161. package/dist/{chunk-72KCTHLV.cjs → chunk-PRL7FXG4.cjs} +113 -29
  162. package/dist/{chunk-6XQSPIN6.cjs → chunk-PWKAX5MS.cjs} +13 -3
  163. package/dist/{chunk-4ZJ5C7UJ.cjs → chunk-QIXEU2WV.cjs} +19 -10
  164. package/dist/{chunk-FJWN7RV4.cjs → chunk-QO43L7Z4.cjs} +38 -8
  165. package/dist/{chunk-X4K7TYN6.cjs → chunk-QOGIZKSO.cjs} +26 -25
  166. package/dist/{chunk-CNNBFGL5.cjs → chunk-QSUYB3RH.cjs} +14 -14
  167. package/dist/chunk-QYNZ3CTI.mjs +17 -0
  168. package/dist/{chunk-X3XUZWRB.mjs → chunk-R2ZHU37O.mjs} +36 -3
  169. package/dist/{chunk-ZIHWAN55.cjs → chunk-RE5E2G5S.cjs} +1 -1
  170. package/dist/{chunk-O75GQVUK.mjs → chunk-RLH5AH2M.mjs} +1 -1
  171. package/dist/chunk-RWR7SMD7.cjs +50 -0
  172. package/dist/{chunk-7PTISZSQ.cjs → chunk-S7MWSFFP.cjs} +4 -0
  173. package/dist/chunk-SD6JGJOM.mjs +50 -0
  174. package/dist/{chunk-7H4SVNC4.cjs → chunk-SPP3EZTJ.cjs} +46 -26
  175. package/dist/{chunk-BIF5MLTH.cjs → chunk-SQ6IWJ3H.cjs} +1 -1
  176. package/dist/{chunk-WVYRLP5E.mjs → chunk-T5XFZQCL.mjs} +1 -1
  177. package/dist/{chunk-WAY6LOQH.mjs → chunk-TEJ67GD2.mjs} +1 -1
  178. package/dist/{chunk-OP7LHY4Y.cjs → chunk-TNK2TVRS.cjs} +2005 -800
  179. package/dist/{chunk-IFTGERT3.mjs → chunk-TTXIITYA.mjs} +49 -0
  180. package/dist/{chunk-ZFWYCVKS.mjs → chunk-TY5KCYDE.mjs} +22 -4
  181. package/dist/{chunk-WYAXRIYP.cjs → chunk-UKZ6AWKZ.cjs} +10 -9
  182. package/dist/{chunk-UJ3R2AH2.cjs → chunk-UPOYKX4S.cjs} +5 -5
  183. package/dist/{chunk-VBCQ5WOI.cjs → chunk-URN7VFO7.cjs} +105 -16
  184. package/dist/{chunk-2DLGV2ZG.mjs → chunk-UTUS6JUH.mjs} +1 -21
  185. package/dist/{chunk-435QJNC2.mjs → chunk-VFNAK6A5.mjs} +4 -4
  186. package/dist/{chunk-WFWFECDW.mjs → chunk-VRGY3X2I.mjs} +100 -11
  187. package/dist/{chunk-LQNW3ABP.cjs → chunk-VX2HZGC7.cjs} +14 -14
  188. package/dist/chunk-W44X6IC2.cjs +97 -0
  189. package/dist/{chunk-A2MN5PQJ.mjs → chunk-WMLSZAKN.mjs} +9 -9
  190. package/dist/{chunk-672ISQIG.mjs → chunk-WPB67LE5.mjs} +379 -69
  191. package/dist/{chunk-3EEET2Q5.cjs → chunk-WUTFJOV7.cjs} +32 -12
  192. package/dist/chunk-WVQNXXNE.cjs +28 -0
  193. package/dist/{chunk-Y5TOT5F6.cjs → chunk-X3MHKLCO.cjs} +5 -5
  194. package/dist/{chunk-W2ZXMMHA.mjs → chunk-XCAQTCGK.mjs} +1 -1
  195. package/dist/{chunk-Z7P2BTZ3.cjs → chunk-XGTFLG73.cjs} +30 -12
  196. package/dist/{chunk-XCXHQBMM.mjs → chunk-Y2LU4LE5.mjs} +1 -1
  197. package/dist/{chunk-5J45H65F.mjs → chunk-Y5LEPEVH.mjs} +1 -1
  198. package/dist/{chunk-D4MRNBVF.cjs → chunk-Y6KHPJDB.cjs} +2 -2
  199. package/dist/{chunk-BT4SEFLC.cjs → chunk-YAEN3L2F.cjs} +3 -2
  200. package/dist/chunk-YFTGIHNC.mjs +26 -0
  201. package/dist/{chunk-KL7SHLQB.mjs → chunk-YGJ5P3TJ.mjs} +31 -1
  202. package/dist/{chunk-752IHQTD.cjs → chunk-YTNBCXCW.cjs} +12 -12
  203. package/dist/{chunk-RFKTJTWZ.mjs → chunk-YVPX5PI5.mjs} +3 -1
  204. package/dist/{chunk-4TVPYN32.cjs → chunk-Z3PW3DIR.cjs} +7 -7
  205. package/dist/{chunk-OB7VKCUZ.mjs → chunk-Z6SOXHAD.mjs} +1851 -646
  206. package/dist/{chunk-72KABRWN.mjs → chunk-ZJGFAW5U.mjs} +5 -3
  207. package/dist/{chunk-TNBJ4LZG.mjs → chunk-ZPKJPM7K.mjs} +4 -4
  208. package/dist/{chunk-5FE5YT2N.mjs → chunk-ZZGQD3LL.mjs} +28 -1
  209. package/dist/client/lifecycle.cjs +2 -2
  210. package/dist/client/lifecycle.d.mts +1 -1
  211. package/dist/client/lifecycle.d.ts +1 -1
  212. package/dist/client/lifecycle.mjs +1 -1
  213. package/dist/{client-component.d-D74pqdea.d.mts → client-component.d-BvQOxSqh.d.mts} +2 -2
  214. package/dist/{client-component.d-D8VcypQA.d.ts → client-component.d-DNVSLEPi.d.ts} +2 -2
  215. package/dist/client-plugins.cjs +2 -2
  216. package/dist/{client-plugins.d-D4-6hNx7.d.mts → client-plugins.d-CE1lVK2R.d.mts} +116 -373
  217. package/dist/{client-plugins.d-CXElzotB.d.ts → client-plugins.d-CNDqcAuf.d.ts} +116 -373
  218. package/dist/client-plugins.d.mts +10 -8
  219. package/dist/client-plugins.d.ts +10 -8
  220. package/dist/client-plugins.mjs +1 -1
  221. package/dist/client.cjs +11 -9
  222. package/dist/client.d.mts +17 -15
  223. package/dist/client.d.ts +17 -15
  224. package/dist/client.mjs +10 -8
  225. package/dist/{config.d-qt-mE8O5.d.mts → config.d-BKIhJtmr.d.mts} +7 -2
  226. package/dist/{config.d-qt-mE8O5.d.ts → config.d-BKIhJtmr.d.ts} +7 -2
  227. package/dist/config.d.mts +10 -8
  228. package/dist/config.d.ts +10 -8
  229. package/dist/cron.cjs +2 -2
  230. package/dist/cron.mjs +1 -1
  231. package/dist/deferred.cjs +2 -2
  232. package/dist/deferred.mjs +1 -1
  233. package/dist/deployment.cjs +4 -2
  234. package/dist/deployment.d.mts +15 -1
  235. package/dist/deployment.d.ts +15 -1
  236. package/dist/deployment.mjs +3 -1
  237. package/dist/desktop.d.mts +11 -9
  238. package/dist/desktop.d.ts +11 -9
  239. package/dist/{devtools-NZUVNUP3.mjs → devtools-2A2GPC7B.mjs} +33 -29
  240. package/dist/{devtools-N2JQCMXB.cjs → devtools-R27T3BRY.cjs} +38 -34
  241. package/dist/docs.cjs +28 -27
  242. package/dist/docs.d.mts +24 -10
  243. package/dist/docs.d.ts +24 -10
  244. package/dist/docs.mjs +27 -26
  245. package/dist/env-types.cjs +3 -3
  246. package/dist/env-types.mjs +2 -2
  247. package/dist/environment/vite.cjs +7 -7
  248. package/dist/environment/vite.d.mts +1 -1
  249. package/dist/environment/vite.d.ts +1 -1
  250. package/dist/environment/vite.mjs +6 -6
  251. package/dist/{generate-route-types.d-BL2pq6xC.d.ts → generate-route-types.d-B76M5R11.d.ts} +1 -1
  252. package/dist/{generate-route-types.d-BoVDU8qX.d.mts → generate-route-types.d-CaGMIaNI.d.mts} +1 -1
  253. package/dist/headers.cjs +3 -3
  254. package/dist/headers.mjs +2 -2
  255. package/dist/image/server.d.mts +1 -1
  256. package/dist/image/server.d.ts +1 -1
  257. package/dist/image/sharp.d.mts +1 -1
  258. package/dist/image/sharp.d.ts +1 -1
  259. package/dist/{image-config.d-CeDgNyX4.d.mts → image-config.d-ByhQ0TT7.d.mts} +3 -1
  260. package/dist/{image-config.d-CeDgNyX4.d.ts → image-config.d-ByhQ0TT7.d.ts} +3 -1
  261. package/dist/image.cjs +6 -6
  262. package/dist/image.d.mts +1 -1
  263. package/dist/image.d.ts +1 -1
  264. package/dist/image.mjs +1 -1
  265. package/dist/index.cjs +148 -128
  266. package/dist/{index.d-SSgYDv4D.d.mts → index.d-Bt3kl19W.d.mts} +1 -1
  267. package/dist/{index.d-A_x10zGS.d.ts → index.d-Cx_-DaKV.d.ts} +1 -1
  268. package/dist/index.d.mts +39 -87
  269. package/dist/index.d.ts +39 -87
  270. package/dist/index.mjs +224 -204
  271. package/dist/instrumentation.cjs +3 -3
  272. package/dist/instrumentation.mjs +2 -2
  273. package/dist/{integration-orm-52GPGTHO.cjs → integrations/orm.cjs} +5 -5
  274. package/dist/integrations/orm.d.mts +35 -0
  275. package/dist/integrations/orm.d.ts +35 -0
  276. package/dist/{integration-orm-CO23MSFE.mjs → integrations/orm.mjs} +5 -5
  277. package/dist/integrations.cjs +6 -5
  278. package/dist/integrations.d.mts +10 -8
  279. package/dist/integrations.d.ts +10 -8
  280. package/dist/integrations.mjs +5 -4
  281. package/dist/internal/app-markdown-runtime.cjs +4 -4
  282. package/dist/internal/app-markdown-runtime.d.mts +27 -11
  283. package/dist/internal/app-markdown-runtime.d.ts +27 -11
  284. package/dist/internal/app-markdown-runtime.mjs +3 -3
  285. package/dist/internal/build-runtime.cjs +76 -71
  286. package/dist/internal/build-runtime.d.mts +12 -10
  287. package/dist/internal/build-runtime.d.ts +12 -10
  288. package/dist/internal/build-runtime.mjs +75 -70
  289. package/dist/internal/cli-runtime.cjs +47 -46
  290. package/dist/internal/cli-runtime.mjs +46 -45
  291. package/dist/internal/client-error-overlay.cjs +6 -6
  292. package/dist/internal/client-error-overlay.mjs +2 -2
  293. package/dist/internal/client-runtime.cjs +85 -36
  294. package/dist/internal/client-runtime.d.mts +44 -13
  295. package/dist/internal/client-runtime.d.ts +44 -13
  296. package/dist/internal/client-runtime.mjs +79 -30
  297. package/dist/internal/compression-runtime.d.mts +10 -8
  298. package/dist/internal/compression-runtime.d.ts +10 -8
  299. package/dist/internal/config-runtime.cjs +27 -26
  300. package/dist/internal/config-runtime.d.mts +14 -12
  301. package/dist/internal/config-runtime.d.ts +14 -12
  302. package/dist/internal/config-runtime.mjs +26 -25
  303. package/dist/internal/docs-precompiled-runtime.cjs +16 -5
  304. package/dist/internal/docs-precompiled-runtime.d.mts +7 -0
  305. package/dist/internal/docs-precompiled-runtime.d.ts +7 -0
  306. package/dist/internal/docs-precompiled-runtime.mjs +15 -4
  307. package/dist/internal/form-actions.cjs +7 -2
  308. package/dist/internal/form-actions.d.mts +10 -3
  309. package/dist/internal/form-actions.d.ts +10 -3
  310. package/dist/internal/form-actions.mjs +8 -3
  311. package/dist/internal/infra-analytics-runtime.cjs +11 -11
  312. package/dist/internal/infra-analytics-runtime.mjs +9 -9
  313. package/dist/internal/islands-boot.cjs +6 -1
  314. package/dist/internal/islands-boot.mjs +6 -1
  315. package/dist/internal/islands-runtime.cjs +33 -4
  316. package/dist/internal/islands-runtime.d.mts +1 -1
  317. package/dist/internal/islands-runtime.d.ts +1 -1
  318. package/dist/internal/islands-runtime.mjs +31 -2
  319. package/dist/internal/native-server-fns.cjs +5 -5
  320. package/dist/internal/native-server-fns.mjs +4 -4
  321. package/dist/internal/product-telemetry-runtime.cjs +3 -3
  322. package/dist/internal/product-telemetry-runtime.mjs +2 -2
  323. package/dist/internal/production-node-env.cjs +4 -2
  324. package/dist/internal/production-node-env.d.mts +22 -1
  325. package/dist/internal/production-node-env.d.ts +22 -1
  326. package/dist/internal/production-node-env.mjs +3 -1
  327. package/dist/internal/production-runtime.cjs +57 -39
  328. package/dist/internal/production-runtime.d.mts +27 -21
  329. package/dist/internal/production-runtime.d.ts +27 -21
  330. package/dist/internal/production-runtime.mjs +72 -54
  331. package/dist/internal/react-cache.cjs +3 -3
  332. package/dist/internal/react-cache.mjs +1 -1
  333. package/dist/internal/server-tree.cjs +2 -2
  334. package/dist/internal/server-tree.d.mts +0 -5
  335. package/dist/internal/server-tree.d.ts +0 -5
  336. package/dist/internal/server-tree.mjs +1 -1
  337. package/dist/internal/vercel-edge-middleware.cjs +87 -0
  338. package/dist/internal/vercel-edge-middleware.d.mts +39 -0
  339. package/dist/internal/vercel-edge-middleware.d.ts +39 -0
  340. package/dist/internal/vercel-edge-middleware.mjs +87 -0
  341. package/dist/layers-7P4RLKVX.cjs +20 -0
  342. package/dist/{layers-T55SA47E.mjs → layers-XQ7VFMWO.mjs} +4 -2
  343. package/dist/{layers.d-CcS42OGR.d.mts → layers.d-CH0bC4QL.d.mts} +2 -1
  344. package/dist/{layers.d-CcS42OGR.d.ts → layers.d-CH0bC4QL.d.ts} +2 -1
  345. package/dist/{lifecycle.d-C2aLBOwu.d.ts → lifecycle.d-keQs5Swc.d.mts} +7 -1
  346. package/dist/{lifecycle.d-C2aLBOwu.d.mts → lifecycle.d-keQs5Swc.d.ts} +7 -1
  347. package/dist/{manager-H5ZM3HAM.mjs → manager-JIA66YJ2.mjs} +4 -3
  348. package/dist/manager-JOHU6BQI.cjs +15 -0
  349. package/dist/markdown.cjs +7 -3
  350. package/dist/markdown.d.mts +10 -8
  351. package/dist/markdown.d.ts +10 -8
  352. package/dist/markdown.mjs +6 -2
  353. package/dist/middleware.cjs +11 -11
  354. package/dist/middleware.d.mts +13 -10
  355. package/dist/middleware.d.ts +13 -10
  356. package/dist/middleware.mjs +13 -13
  357. package/dist/mobile.d.mts +6 -6
  358. package/dist/mobile.d.ts +6 -6
  359. package/dist/mount.d-Bki4pOaJ.d.mts +38 -0
  360. package/dist/mount.d-DjR5aerM.d.ts +38 -0
  361. package/dist/{native-server-fn-handler-GLRHAYWV.mjs → native-server-fn-handler-EP5AFJYE.mjs} +5 -5
  362. package/dist/{native-server-fn-handler-J5MYRXN6.cjs → native-server-fn-handler-QRTXGZA4.cjs} +6 -6
  363. package/dist/{native-tree-7LPH57Z4.cjs → native-tree-W2SSJB3Y.cjs} +4 -4
  364. package/dist/{native-tree-VV6WN3GX.mjs → native-tree-Y5YQANW7.mjs} +3 -3
  365. package/dist/{navigation-delegate.d-GghbHJuK.d.ts → navigation-delegate.d-CtghaSP3.d.ts} +1 -1
  366. package/dist/{navigation-delegate.d-DQVYKoaZ.d.mts → navigation-delegate.d-VDkziXTK.d.mts} +1 -1
  367. package/dist/navigation.cjs +8 -7
  368. package/dist/navigation.d.mts +13 -11
  369. package/dist/navigation.d.ts +13 -11
  370. package/dist/navigation.mjs +7 -6
  371. package/dist/{nitro-DD4QCA66.mjs → nitro-NSTXT7LB.mjs} +11 -11
  372. package/dist/{nitro-VRDX2H4M.cjs → nitro-Y3LGITW3.cjs} +13 -13
  373. package/dist/node-module-bundle-LIZ2KMVW.cjs +13 -0
  374. package/dist/node-module-bundle-VR6NV6AI.mjs +13 -0
  375. package/dist/{plugin-53SY5YBS.mjs → plugin-SAS22JL7.mjs} +4 -3
  376. package/dist/{plugin-HZIBL3DW.cjs → plugin-WIU4GDD4.cjs} +5 -4
  377. package/dist/plugin.cjs +65 -63
  378. package/dist/plugin.d.mts +12 -10
  379. package/dist/plugin.d.ts +12 -10
  380. package/dist/plugin.mjs +64 -62
  381. package/dist/{production-runtime.d-Bzns3NW9.d.ts → production-runtime.d-BMyyLGBB.d.ts} +3 -57
  382. package/dist/{production-runtime.d-DiFa5vHW.d.mts → production-runtime.d-DMZY3OgV.d.mts} +3 -57
  383. package/dist/query/client.cjs +9 -7
  384. package/dist/query/client.mjs +5 -3
  385. package/dist/{render-plan.d-CcF0MeCf.d.mts → render-plan.d-BSwV8PE4.d.mts} +1 -1
  386. package/dist/{render-plan.d-CL_Ikfg_.d.ts → render-plan.d-i9sI4tc9.d.ts} +1 -1
  387. package/dist/renderer/none/server.cjs +35 -0
  388. package/dist/renderer/none/server.d.mts +21 -0
  389. package/dist/renderer/none/server.d.ts +21 -0
  390. package/dist/renderer/none/server.mjs +35 -0
  391. package/dist/renderer/react/server.cjs +3 -3
  392. package/dist/renderer/react/server.mjs +3 -3
  393. package/dist/renderer-client.cjs +8 -6
  394. package/dist/renderer-client.d.mts +13 -11
  395. package/dist/renderer-client.d.ts +13 -11
  396. package/dist/renderer-client.mjs +5 -3
  397. package/dist/renderer.cjs +6 -2
  398. package/dist/renderer.d.mts +25 -2
  399. package/dist/renderer.d.ts +25 -2
  400. package/dist/renderer.mjs +5 -1
  401. package/dist/request.cjs +2 -2
  402. package/dist/{request.d-DarDOCk9.d.mts → request.d-C24FNQ_7.d.mts} +1 -1
  403. package/dist/{request.d-B1RnTLri.d.ts → request.d-Dgln8tuI.d.ts} +1 -1
  404. package/dist/request.d.mts +11 -9
  405. package/dist/request.d.ts +11 -9
  406. package/dist/request.mjs +1 -1
  407. package/dist/{route-rendering.d-BTUYCIj4.d.ts → route-rendering.d-CUylZKJA.d.ts} +1 -1
  408. package/dist/{route-rendering.d-D_2Ual0-.d.mts → route-rendering.d-Ds0BfwQi.d.mts} +1 -1
  409. package/dist/{route.d-BaVH3V0w.d.mts → route.d-DrXkpvcg.d.mts} +1 -1
  410. package/dist/{route.d-DBTEqifW.d.ts → route.d-hs-_cyHn.d.ts} +1 -1
  411. package/dist/{router.d-CMANF6da.d.ts → router.d-B56rMOFm.d.ts} +1 -1
  412. package/dist/{router.d-Cuv1jntg.d.mts → router.d-CFPcbqzc.d.mts} +1 -1
  413. package/dist/routes.cjs +3 -3
  414. package/dist/{routes.d-B6yFe6jm.d.ts → routes.d-9GFFNioh.d.ts} +2 -2
  415. package/dist/{routes.d-c2HKfrfL.d.mts → routes.d-CrEy0lJS.d.mts} +2 -2
  416. package/dist/routes.d.mts +10 -8
  417. package/dist/routes.d.ts +10 -8
  418. package/dist/routes.mjs +2 -2
  419. package/dist/{rsc-pipeline-Z7QBZOIJ.cjs → rsc-pipeline-3T7V6OUT.cjs} +30 -28
  420. package/dist/{rsc-pipeline-7PNVJSTR.mjs → rsc-pipeline-GA4AQWZI.mjs} +29 -27
  421. package/dist/{runtime-FKFCUHSK.cjs → runtime-REUTNTI5.cjs} +72 -46
  422. package/dist/{runtime-QQHX4BP3.mjs → runtime-ZYCKKY7L.mjs} +60 -34
  423. package/dist/{runtime.d-wvh4ngU0.d.mts → runtime.d-DLRO-ExG.d.mts} +11 -3
  424. package/dist/{runtime.d-C3RQUj6_.d.ts → runtime.d-H7k9hOQE.d.ts} +11 -3
  425. package/dist/{schema-dev-notice-JMXEQWIQ.mjs → schema-dev-notice-C2JINRZI.mjs} +3 -2
  426. package/dist/{schema-dev-notice-PLBFDTOF.cjs → schema-dev-notice-X7GG7QVB.cjs} +5 -4
  427. package/dist/schema.cjs +6 -2
  428. package/dist/schema.d-Dny9pnrm.d.mts +298 -0
  429. package/dist/schema.d-Dny9pnrm.d.ts +298 -0
  430. package/dist/schema.d.mts +1 -115
  431. package/dist/schema.d.ts +1 -115
  432. package/dist/schema.mjs +5 -1
  433. package/dist/server-fn-client.d.mts +2 -2
  434. package/dist/server-fn-client.d.ts +2 -2
  435. package/dist/server-fn.cjs +5 -5
  436. package/dist/server-fn.mjs +4 -4
  437. package/dist/server-http.d-rAe7lAQc.d.mts +70 -0
  438. package/dist/server-http.d-rAe7lAQc.d.ts +70 -0
  439. package/dist/server-plugins.cjs +7 -7
  440. package/dist/server-plugins.d.mts +20 -12
  441. package/dist/server-plugins.d.ts +20 -12
  442. package/dist/server-plugins.mjs +8 -8
  443. package/dist/server-query.cjs +6 -6
  444. package/dist/server-query.mjs +5 -5
  445. package/dist/server.cjs +168 -126
  446. package/dist/server.d-C5FFrZAo.d.ts +57 -0
  447. package/dist/server.d-DgC8xew5.d.mts +57 -0
  448. package/dist/server.d.mts +24 -16
  449. package/dist/server.d.ts +24 -16
  450. package/dist/server.mjs +144 -102
  451. package/dist/{spa-router.d-m8H_Kl_B.d.ts → spa-router.d-Dr7oanhl.d.ts} +15 -5
  452. package/dist/{spa-router.d-WU_qS5gJ.d.mts → spa-router.d-g4CzhEH1.d.mts} +15 -5
  453. package/dist/testing.cjs +17 -17
  454. package/dist/testing.d.mts +10 -8
  455. package/dist/testing.d.ts +10 -8
  456. package/dist/testing.mjs +13 -13
  457. package/dist/theme/server.cjs +3 -3
  458. package/dist/theme/server.mjs +2 -2
  459. package/dist/types.d-xCIhyjOq.d.mts +233 -0
  460. package/dist/types.d-xCIhyjOq.d.ts +233 -0
  461. package/dist/{utils.d-C9dQD5Zg.d.ts → utils.d-BxxyDEb8.d.ts} +1 -1
  462. package/dist/{utils.d-W9IiEqmW.d.mts → utils.d-HIla3pD_.d.mts} +1 -1
  463. package/dist/version.cjs +2 -2
  464. package/dist/version.mjs +1 -1
  465. package/dist/vite.cjs +65 -63
  466. package/dist/vite.d.mts +36 -14
  467. package/dist/vite.d.ts +36 -14
  468. package/dist/vite.mjs +64 -62
  469. package/dist/workflows.cjs +4 -4
  470. package/dist/workflows.d.mts +121 -1
  471. package/dist/workflows.d.ts +121 -1
  472. package/dist/workflows.mjs +3 -3
  473. package/package.json +37 -2
  474. package/dist/analyzer-H7SIX6BJ.cjs +0 -16
  475. package/dist/chunk-5YPBFMBN.cjs +0 -19
  476. package/dist/chunk-CLFEQGET.cjs +0 -60
  477. package/dist/chunk-MK5E44WP.mjs +0 -60
  478. package/dist/chunk-OM7WILES.mjs +0 -100
  479. package/dist/chunk-Q5B4LNON.mjs +0 -19
  480. package/dist/chunk-QPJ4MZTO.mjs +0 -60
  481. package/dist/chunk-R53QDV6T.cjs +0 -100
  482. package/dist/chunk-UYTAP4FQ.cjs +0 -60
  483. package/dist/layers-DMRXRL7F.cjs +0 -18
  484. package/dist/manager-2LUKNX2N.cjs +0 -14
  485. package/dist/node-module-bundle-7JHPPF6B.mjs +0 -11
  486. package/dist/node-module-bundle-YJGYBOGK.cjs +0 -11
  487. package/dist/workflows.d-CRMzQZ3k.d.mts +0 -188
  488. package/dist/workflows.d-CRMzQZ3k.d.ts +0 -188
  489. /package/dist/{chunk-QGOZLGVP.mjs → chunk-I6FIAWNT.mjs} +0 -0
  490. /package/dist/{chunk-XPIPMWY3.cjs → chunk-K5NI5YQR.cjs} +0 -0
  491. /package/dist/{chunk-NWUHS6GV.cjs → chunk-QEJWNXRI.cjs} +0 -0
  492. /package/dist/{chunk-FSXSQQTV.mjs → chunk-TXE4SAMV.mjs} +0 -0
  493. /package/dist/{chunk-ZXK2EYQW.cjs → chunk-UUQNJDGH.cjs} +0 -0
  494. /package/dist/{chunk-46P5KNTE.mjs → chunk-VZBAW44S.mjs} +0 -0
@@ -8,7 +8,9 @@ import {
8
8
  } from "./chunk-3TXKFRSO.mjs";
9
9
  import {
10
10
  FARM_LAYOUT_ELEMENT_CLIENT_SOURCE,
11
+ FARM_NAVIGATION_SCRIPT_SOURCE,
11
12
  FARM_NAVIGATION_STREAM_READER_SOURCE,
13
+ FARM_REFRESH_FIELDS_SOURCE,
12
14
  FARM_SERVER_TREE_LAYOUT_CLIENT_SOURCE,
13
15
  FarmApp,
14
16
  collectFarmWebMCPTools,
@@ -16,9 +18,9 @@ import {
16
18
  createFarmClientOptimizeDepsEntries,
17
19
  createFarmSourceAlias,
18
20
  createFarmThemeCssPlugin,
21
+ exactIdPattern,
19
22
  farmFontImportsPlugin,
20
23
  generateClientCachePersistenceCode,
21
- generateFarmClientPluginEntryCode,
22
24
  generateFarmIntegrationProviderClientCode,
23
25
  inferFarmIslandStrategy,
24
26
  isFarmDocsClientConfigModule,
@@ -28,20 +30,26 @@ import {
28
30
  resolveFarmClientCacheAdapterEntry,
29
31
  resolveFarmImageProviderForRuntime,
30
32
  resolveFarmRouteRootStrategy
31
- } from "./chunk-EMNKZGF4.mjs";
33
+ } from "./chunk-4UAQB5LB.mjs";
32
34
  import {
35
+ generateFarmClientPluginEntryCode,
33
36
  loadTailwindVitePlugin
34
- } from "./chunk-OM7WILES.mjs";
37
+ } from "./chunk-DXZ57EPE.mjs";
35
38
  import {
36
39
  FARM_NODE_RESPONSE_END_PENDING
37
- } from "./chunk-GHNW564E.mjs";
40
+ } from "./chunk-KSZK34HU.mjs";
38
41
  import {
39
42
  resolveFarmPlatform
40
43
  } from "./chunk-SMUW7UST.mjs";
41
44
  import {
42
45
  generateFarmTypeArtifacts,
43
46
  resolveRouteRenderingConfig
44
- } from "./chunk-BM2LH2JM.mjs";
47
+ } from "./chunk-G7NBPP7H.mjs";
48
+ import {
49
+ createFarmServerFnBoundaryModule,
50
+ isFarmServerFnBoundaryId,
51
+ transformFarmServerFns
52
+ } from "./chunk-GNZIAJGB.mjs";
45
53
  import {
46
54
  createFarmRouteRenderPlan,
47
55
  farmPathGuardCoversEndpoint,
@@ -52,7 +60,7 @@ import {
52
60
  parseFarmLayoutChainHeader,
53
61
  renderFarmLocaleAlternateLinks,
54
62
  stripRouteGroups
55
- } from "./chunk-TNBJ4LZG.mjs";
63
+ } from "./chunk-ZPKJPM7K.mjs";
56
64
  import {
57
65
  FARM_NATIVE_TREE_CONTENT_TYPE
58
66
  } from "./chunk-LLZSYFOM.mjs";
@@ -70,25 +78,23 @@ import {
70
78
  resolveFarmMCPRouteLabel,
71
79
  resolveFarmMarkdownRouteLabel,
72
80
  setFarmRouteLabel
73
- } from "./chunk-435QJNC2.mjs";
81
+ } from "./chunk-VFNAK6A5.mjs";
74
82
  import {
75
83
  FARM_DEFAULT_MCP_PATH
76
- } from "./chunk-MESQF2JC.mjs";
84
+ } from "./chunk-K6SXMVXO.mjs";
77
85
  import {
78
86
  isFarmPreviewDeploymentEnvironment
79
- } from "./chunk-WVYRLP5E.mjs";
80
- import {
81
- createFarmServerFnBoundaryModule,
82
- isFarmServerFnBoundaryId,
83
- transformFarmServerFns
84
- } from "./chunk-GNZIAJGB.mjs";
87
+ } from "./chunk-T5XFZQCL.mjs";
85
88
  import {
86
89
  resolveFarmLayoutFonts
87
90
  } from "./chunk-HZOMT5DY.mjs";
88
91
  import {
92
+ FARM_BROWSER_BUILTIN_PREFIX,
89
93
  FARM_CLIENT_REFERENCE_DIRECTORY,
90
94
  FARM_CLIENT_REFERENCE_PRAGMA,
91
- collectFarmServerBundledPackages,
95
+ FARM_RESOLVE_FROM_PREFIX,
96
+ collectFarmServerBundledPackageInfo,
97
+ ensureFarmInternalClientReference,
92
98
  ensureFarmPackageClientReference,
93
99
  farmBrowserBuiltinsOptimizerPlugin,
94
100
  farmEnvironmentFunctionsPlugin,
@@ -103,14 +109,17 @@ import {
103
109
  isFarmPackageClientBoundary,
104
110
  isIsolatableClientBoundarySource,
105
111
  loadFarmBrowserBuiltin,
112
+ parseFarmResolveFrom,
106
113
  programmaticClientRouteKey,
107
114
  resolveFarmBrowserBuiltin,
108
115
  resolveFarmIsolatedClientHydrationMode,
109
116
  resolveModuleSourcePath,
117
+ resolvePackageClientBoundaryCacheFile,
110
118
  rewriteFarmPackageClientImports,
119
+ rewriteFarmReactServerClientModuleImports,
111
120
  rewriteFarmReactServerImports,
112
121
  stripUseClientDirective
113
- } from "./chunk-672ISQIG.mjs";
122
+ } from "./chunk-WPB67LE5.mjs";
114
123
  import {
115
124
  generateFarmDocsAdapterClientRuntime,
116
125
  getFarmDocsAdapterConfigModule
@@ -122,6 +131,9 @@ import {
122
131
  import {
123
132
  generateFarmDevIndicatorsClientRuntime
124
133
  } from "./chunk-TPA2PV5J.mjs";
134
+ import {
135
+ resolveRouteRuleCorsPreflightHeaders
136
+ } from "./chunk-R2ZHU37O.mjs";
125
137
  import {
126
138
  FARM_DEVTOOLS_LAUNCH_PARAM,
127
139
  FARM_DEVTOOLS_PATH,
@@ -131,31 +143,32 @@ import {
131
143
  FARM_PREVIEW_ROBOTS_TAG,
132
144
  resolveFarmAgentCrawlers,
133
145
  resolveFarmAgentSitemap
134
- } from "./chunk-VQ4NWOWO.mjs";
146
+ } from "./chunk-OGVTUGMU.mjs";
135
147
  import {
136
148
  resolveFarmLlmsTxtConfig
137
- } from "./chunk-KL7SHLQB.mjs";
149
+ } from "./chunk-YGJ5P3TJ.mjs";
138
150
  import {
139
151
  resolveFarmServerComponentsMode
140
- } from "./chunk-CJNAUEVC.mjs";
152
+ } from "./chunk-4QENVMG7.mjs";
141
153
  import {
142
154
  getFarmAppDirectories,
143
155
  getFarmLayerAliases,
144
156
  getFarmSourceRoots
145
- } from "./chunk-52Y3C3HG.mjs";
157
+ } from "./chunk-E7VF3LQ5.mjs";
146
158
  import {
147
159
  REACT_RENDERER,
148
160
  getFarmRendererCapabilities,
161
+ isFarmRendererDisabled,
149
162
  isReactRenderer,
150
163
  loadFarmRendererVitePlugins,
151
164
  resolveFarmComponentExtensions,
152
165
  resolveFarmRenderer,
153
166
  resolveFarmRendererAppSetup
154
- } from "./chunk-ES2LD2YD.mjs";
167
+ } from "./chunk-GCRT6GJG.mjs";
155
168
  import {
156
169
  getPublicFarmImageConfig,
157
170
  resolveFarmImageConfig
158
- } from "./chunk-2NGZFOKG.mjs";
171
+ } from "./chunk-AOIUYHPH.mjs";
159
172
  import {
160
173
  createBundledEnv
161
174
  } from "./chunk-N33DLJBC.mjs";
@@ -163,30 +176,29 @@ import {
163
176
  createFarmMarkdownSourceResponse,
164
177
  isFarmMarkdownPageFile,
165
178
  normalizeFarmMarkdownRoutePath
166
- } from "./chunk-RVGSVQWT.mjs";
179
+ } from "./chunk-HEJM46HQ.mjs";
167
180
  import {
168
181
  FARM_MARKDOWN_CONTENT_TYPE,
169
182
  createFarmMarkdownErrorBody,
170
183
  createMarkdownMirrorResponse,
171
184
  farmRequestWantsMarkdown,
172
185
  getFarmMarkdownAlternatePath,
173
- getFarmMarkdownMirrorPath,
174
186
  resolveMarkdownMirrorTarget
175
- } from "./chunk-K7OZAVOI.mjs";
176
- import {
177
- resolveFarmRouteContext,
178
- withFarmRouteContext
179
- } from "./chunk-BMQAPZXD.mjs";
187
+ } from "./chunk-IFR74W6S.mjs";
180
188
  import {
181
189
  dispatchIntegrationRequest,
182
190
  getFarmIntegrationPluginOwner,
183
191
  getIntegrationDocumentNavigationMatchers,
184
192
  getIntegrationProviders,
185
193
  matchIntegrationRoute
186
- } from "./chunk-TGULJSHD.mjs";
194
+ } from "./chunk-AJNBTOVQ.mjs";
195
+ import {
196
+ resolveFarmRouteContext,
197
+ withFarmRouteContext
198
+ } from "./chunk-BMQAPZXD.mjs";
187
199
  import {
188
200
  MiddlewareManager
189
- } from "./chunk-A2MN5PQJ.mjs";
201
+ } from "./chunk-WMLSZAKN.mjs";
190
202
  import {
191
203
  _runWithMiddlewareContext,
192
204
  _runWithMiddlewareData
@@ -202,7 +214,7 @@ import {
202
214
  } from "./chunk-IYEY3JWJ.mjs";
203
215
  import {
204
216
  APIRouteManager
205
- } from "./chunk-3UZVPO72.mjs";
217
+ } from "./chunk-OIOPQ25L.mjs";
206
218
  import {
207
219
  getFarmI18nClientSnapshot
208
220
  } from "./chunk-CV6MFQ4Y.mjs";
@@ -211,8 +223,10 @@ import {
211
223
  isOptionalPeerInstalled
212
224
  } from "./chunk-NR63PD3P.mjs";
213
225
  import {
226
+ FARM_INTERNAL_SERVER_ERROR_BODY,
227
+ createFarmInternalServerErrorResponse,
214
228
  isFarmAPIPathname
215
- } from "./chunk-ZFWYCVKS.mjs";
229
+ } from "./chunk-TY5KCYDE.mjs";
216
230
  import {
217
231
  registerFarmMCPServer
218
232
  } from "./chunk-C7GJDVN4.mjs";
@@ -224,6 +238,11 @@ import {
224
238
  import {
225
239
  createCliColors
226
240
  } from "./chunk-IGL6CO6M.mjs";
241
+ import {
242
+ applyWebResponseHeaders,
243
+ fetchFarmExternalRewrite,
244
+ sendWebResponse
245
+ } from "./chunk-CO6UYM2D.mjs";
227
246
  import {
228
247
  invalidateFailedFarmDevModules,
229
248
  invalidateFarmDevDependents,
@@ -238,19 +257,6 @@ import {
238
257
  toPosixPath,
239
258
  toViteModuleId
240
259
  } from "./chunk-JSDV2NUN.mjs";
241
- import {
242
- createFarmSearchParams,
243
- searchParamsToObject
244
- } from "./chunk-H3ASZDT7.mjs";
245
- import {
246
- emitFarmEvent,
247
- runWithFarmRequestSpan
248
- } from "./chunk-2DA7CLY7.mjs";
249
- import {
250
- applyWebResponseHeaders,
251
- fetchFarmExternalRewrite,
252
- sendWebResponse
253
- } from "./chunk-CO6UYM2D.mjs";
254
260
  import {
255
261
  resolveFarmAPIServerBasePath
256
262
  } from "./chunk-2I6PUKWJ.mjs";
@@ -261,12 +267,24 @@ import {
261
267
  readNodeRequestBody,
262
268
  resolveFarmServerConfig
263
269
  } from "./chunk-QDWMCFTH.mjs";
270
+ import {
271
+ createFarmSearchParams,
272
+ searchParamsToObject
273
+ } from "./chunk-H3ASZDT7.mjs";
274
+ import {
275
+ emitFarmEvent,
276
+ runWithFarmRequestSpan
277
+ } from "./chunk-2DA7CLY7.mjs";
264
278
  import {
265
279
  FARM_VERSION
266
- } from "./chunk-MPIGW42F.mjs";
280
+ } from "./chunk-F6CMGWAL.mjs";
267
281
  import {
268
282
  DEFAULT_FARM_API_BASE_PATH
269
283
  } from "./chunk-W6QLRQ3V.mjs";
284
+ import {
285
+ createFarmPageDataRedirectResponse,
286
+ getFarmPageDataRedirectFromResponse
287
+ } from "./chunk-SD6JGJOM.mjs";
270
288
  import {
271
289
  addMetadataMarkdownAlternate,
272
290
  mergeMetadata,
@@ -275,20 +293,25 @@ import {
275
293
  import {
276
294
  FARM_DEPLOYMENT_ID_HEADER,
277
295
  createFarmDeploymentMismatchResponse,
278
- getFarmDeploymentMismatch
279
- } from "./chunk-UAQD67HM.mjs";
296
+ getFarmDeploymentMismatch,
297
+ withFarmDeploymentResponse
298
+ } from "./chunk-NVOMQLI2.mjs";
280
299
  import {
281
300
  createDeferredDataResponse
282
- } from "./chunk-K5EW7GUU.mjs";
301
+ } from "./chunk-7BIW7VCW.mjs";
283
302
  import {
284
- FARM_CONFIG_REWRITES_PLUGIN_NAME
285
- } from "./chunk-QPJ4MZTO.mjs";
303
+ FARM_CONFIG_HEADERS_PLUGIN_NAME,
304
+ FARM_CONFIG_REDIRECTS_PLUGIN_NAME,
305
+ FARM_CONFIG_REWRITES_PLUGIN_NAME,
306
+ getConfigRedirectMatcher
307
+ } from "./chunk-PLJKJJ2H.mjs";
308
+ import {
309
+ parseFarmRequestTarget,
310
+ resolveFarmRequestURL
311
+ } from "./chunk-5OFNUETM.mjs";
286
312
  import {
287
313
  isFarmNotFoundError
288
314
  } from "./chunk-JNYFXL7X.mjs";
289
- import {
290
- resolveFarmRequestURL
291
- } from "./chunk-6HRAK7I5.mjs";
292
315
  import {
293
316
  applyFarmBasePath,
294
317
  stripFarmBasePath
@@ -318,7 +341,9 @@ function transformFarmFormActionModule(options) {
318
341
 
319
342
  // src/vite.ts
320
343
  import { parseSync } from "vite";
321
- import { isBuiltin } from "module";
344
+ import { initSync as initModuleLexer, parse as lexModule } from "es-module-lexer";
345
+ import { AsyncLocalStorage } from "async_hooks";
346
+ import { builtinModules, isBuiltin } from "module";
322
347
 
323
348
  // src/dev-preview-guard.ts
324
349
  import { promises as fsp } from "fs";
@@ -393,8 +418,7 @@ async function isAllowedPreviewRequest(server, options, req) {
393
418
  if (server.config.publicDir && isInside(await realpathOr(server.config.publicDir), file)) {
394
419
  return true;
395
420
  }
396
- const isModuleOrAsset = MODULE_EXTENSION.test(file) || ASSET_EXTENSION.test(file) || query.has("import");
397
- if (!isModuleOrAsset) return false;
421
+ if (!MODULE_EXTENSION.test(file) && !ASSET_EXTENSION.test(file)) return false;
398
422
  for (const source of options.getSourceRoots()) {
399
423
  const sourceRoot = await realpathOr(source.root);
400
424
  const sourceDir = await realpathOr(path2.resolve(source.root, source.srcDir));
@@ -436,8 +460,40 @@ async function realpathOr(directory) {
436
460
  }
437
461
  }
438
462
  function isInside(directory, file) {
439
- const relative2 = path2.relative(directory, file);
440
- return relative2 !== "" && relative2 !== ".." && !relative2.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative2);
463
+ const relative4 = path2.relative(directory, file);
464
+ return relative4 !== "" && relative4 !== ".." && !relative4.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative4);
465
+ }
466
+
467
+ // src/server/dev-cors.ts
468
+ var VITE_DEFAULT_CORS_ORIGIN = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
469
+ var VITE_DEFAULT_CORS_METHODS = "GET,HEAD,PUT,PATCH,POST,DELETE";
470
+ function appendVary(res, value) {
471
+ const current = res.getHeader("Vary");
472
+ const values = String(current ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
473
+ if (values.includes("*") || values.some((entry) => entry.toLowerCase() === value.toLowerCase())) {
474
+ return;
475
+ }
476
+ res.setHeader("Vary", [...values, value].join(", "));
477
+ }
478
+ function createFarmDevViteCorsMiddleware() {
479
+ return function farmDevViteCors(req, res, next) {
480
+ const origin = req.headers.origin;
481
+ if (typeof origin === "string" && VITE_DEFAULT_CORS_ORIGIN.test(origin) && !res.hasHeader("Access-Control-Allow-Origin")) {
482
+ res.setHeader("Access-Control-Allow-Origin", origin);
483
+ }
484
+ appendVary(res, "Origin");
485
+ if (req.method?.toUpperCase() !== "OPTIONS") {
486
+ next();
487
+ return;
488
+ }
489
+ res.setHeader("Access-Control-Allow-Methods", VITE_DEFAULT_CORS_METHODS);
490
+ appendVary(res, "Access-Control-Request-Headers");
491
+ const requestHeaders = req.headers["access-control-request-headers"];
492
+ if (requestHeaders) res.setHeader("Access-Control-Allow-Headers", requestHeaders);
493
+ res.statusCode = 204;
494
+ res.setHeader("Content-Length", "0");
495
+ res.end();
496
+ };
441
497
  }
442
498
 
443
499
  // src/vite.ts
@@ -448,13 +504,87 @@ import { pathToFileURL } from "url";
448
504
  // src/dev-static.ts
449
505
  import * as fs from "fs";
450
506
  import * as path3 from "path";
451
- function shouldBypassFarmRouterForDottedPath(pathname, routeManager, baseDirs, generatedPaths = []) {
507
+ function shouldBypassFarmRouterForDottedPath(pathname, routeManager, baseDirs, generatedPaths = [], method = "GET") {
452
508
  if (!pathname.includes(".") || pathname.endsWith(".html")) return false;
453
509
  const matchesAppRoute = Boolean(
454
510
  routeManager?.matchRoute(pathname)?.route || routeManager?.matchMetadataRoute(pathname) || routeManager?.matchMetadataImage(pathname) || generatedPaths.includes(pathname)
455
511
  );
512
+ if (method !== "GET" && method !== "HEAD") {
513
+ return !matchesAppRoute && !devServableFileExists(pathname, baseDirs);
514
+ }
456
515
  return !matchesAppRoute || devServableFileExists(pathname, baseDirs);
457
516
  }
517
+ function isMalformedFarmRequestPathname(pathname) {
518
+ if (!pathname.includes("%")) return false;
519
+ try {
520
+ decodeURI(pathname);
521
+ return false;
522
+ } catch {
523
+ return true;
524
+ }
525
+ }
526
+ var FARM_MALFORMED_REQUEST_BODY = JSON.stringify(
527
+ { error: true, status: 400, message: "Bad Request" },
528
+ null,
529
+ 2
530
+ );
531
+ function resolveFarmPublicFilePath(pathname, publicFiles) {
532
+ if (publicFiles.size === 0) return null;
533
+ let id = pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
534
+ if (id.includes("%")) {
535
+ const escaped = id.replace(/%2f/gi, "%252F");
536
+ try {
537
+ id = decodeURIComponent(escaped);
538
+ } catch {
539
+ id = escaped;
540
+ }
541
+ }
542
+ if (publicFiles.has(id)) return id;
543
+ const index = `${id === "/" ? "" : id}/index.html`;
544
+ return publicFiles.has(index) ? index : null;
545
+ }
546
+ function createFarmPublicFileIndex(getPublicDir) {
547
+ const none = /* @__PURE__ */ new Set();
548
+ let listing;
549
+ return {
550
+ get() {
551
+ const configured = getPublicDir();
552
+ if (typeof configured !== "string" || configured.length === 0) return none;
553
+ if (listing?.configured === configured) return listing.files;
554
+ const dir = path3.resolve(configured);
555
+ listing = { configured, dir, files: listFarmPublicFiles(dir) };
556
+ return listing.files;
557
+ },
558
+ invalidate(file) {
559
+ if (!listing) return;
560
+ const resolved = path3.resolve(file);
561
+ if (resolved === listing.dir || resolved.startsWith(listing.dir + path3.sep)) {
562
+ listing = void 0;
563
+ }
564
+ }
565
+ };
566
+ }
567
+ function listFarmPublicFiles(dir) {
568
+ const files = /* @__PURE__ */ new Set();
569
+ let entries;
570
+ try {
571
+ entries = fs.readdirSync(dir, { recursive: true, withFileTypes: true });
572
+ } catch {
573
+ return files;
574
+ }
575
+ for (const entry of entries) {
576
+ const filePath = path3.join(entry.parentPath, entry.name);
577
+ let isFile = entry.isFile();
578
+ if (!isFile && entry.isSymbolicLink()) {
579
+ try {
580
+ isFile = fs.statSync(filePath).isFile();
581
+ } catch {
582
+ }
583
+ }
584
+ if (isFile) files.add(`/${path3.relative(dir, filePath).split(path3.sep).join("/")}`);
585
+ }
586
+ return files;
587
+ }
458
588
  var VITE_MODULE_QUERY_FLAGS = [
459
589
  "import",
460
590
  "raw",
@@ -470,13 +600,28 @@ function isViteModuleRequest(url, headers) {
470
600
  const value = Array.isArray(destination) ? destination[0] : destination;
471
601
  return value !== void 0 && SCRIPT_FETCH_DESTINATIONS.has(value.toLowerCase());
472
602
  }
603
+ var VITE_CLIENT_QUERY_FLAGS = ["t", "v", "direct", "html-proxy", "worker_file"];
604
+ var NAVIGATION_FETCH_DESTINATIONS = /* @__PURE__ */ new Set(["document", "iframe", "frame", "embed", "object"]);
605
+ function isViteDevClientRequest(url, headers) {
606
+ if (isViteModuleRequest(url, headers)) return true;
607
+ if (VITE_CLIENT_QUERY_FLAGS.some((flag) => url.searchParams.has(flag))) return true;
608
+ const destination = firstHeaderValue(headers["sec-fetch-dest"]);
609
+ if (destination !== void 0) {
610
+ return !NAVIGATION_FETCH_DESTINATIONS.has(destination.toLowerCase());
611
+ }
612
+ return firstHeaderValue(headers.referer) !== void 0 && !(firstHeaderValue(headers.accept) ?? "").includes("text/html");
613
+ }
614
+ function firstHeaderValue(value) {
615
+ return Array.isArray(value) ? value[0] : value;
616
+ }
473
617
  var DOCS_ENGINE_APP_OWNABLE_PATHS = /* @__PURE__ */ new Set([
474
618
  "/llms.txt",
475
619
  "/llms-full.txt",
476
620
  "/sitemap.xml",
477
621
  "/robots.txt"
478
622
  ]);
479
- function farmAppOwnsDocsEnginePath(pathname, options) {
623
+ function farmAppOwnsDocsEnginePath(routePathname, options) {
624
+ const pathname = routePathname.length > 1 ? routePathname.replace(/\/+$/, "") : routePathname;
480
625
  if (!DOCS_ENGINE_APP_OWNABLE_PATHS.has(pathname)) return false;
481
626
  return options.generatedPaths.includes(pathname) || Boolean(options.routeManager?.matchMetadataRoute(pathname)) || devServableFileExists(pathname, [options.publicDir]);
482
627
  }
@@ -696,6 +841,42 @@ async function createBlurDataURL(bytes) {
696
841
  }
697
842
  }
698
843
 
844
+ // src/dev/deferred-setup.ts
845
+ function createFarmDeferredMiddleware(ready) {
846
+ const stack = [];
847
+ const run = (req, res, next) => {
848
+ let index = 0;
849
+ const step = (error) => {
850
+ if (error !== void 0 && error !== null) return next(error);
851
+ const layer = stack[index++];
852
+ if (!layer) return next();
853
+ try {
854
+ layer.handle(req, res, step);
855
+ } catch (thrown) {
856
+ next(thrown ?? new Error("Middleware threw a nullish value"));
857
+ }
858
+ };
859
+ step();
860
+ };
861
+ return {
862
+ handle(req, res, next) {
863
+ const pending = ready();
864
+ if (!pending) return run(req, res, next);
865
+ pending.then(
866
+ () => run(req, res, next),
867
+ (error) => next(error ?? new Error("Farm dev server setup failed"))
868
+ );
869
+ },
870
+ target: {
871
+ stack,
872
+ use(handle) {
873
+ stack.push({ route: "", handle });
874
+ return this;
875
+ }
876
+ }
877
+ };
878
+ }
879
+
699
880
  // src/vite.ts
700
881
  import { rewriteFormStatusImports } from "@farm.js/islx/compiler";
701
882
 
@@ -880,13 +1061,13 @@ function loadFarmDocsSearchDevRuntime() {
880
1061
  return import("./search-client-OXH6GBNO.mjs");
881
1062
  }
882
1063
  function loadFarmOpenAPIDevRuntime() {
883
- return import("./manager-H5ZM3HAM.mjs");
1064
+ return import("./manager-JIA66YJ2.mjs");
884
1065
  }
885
1066
  function loadFarmWorkflowsDevRuntime() {
886
1067
  return import("./workflows.mjs");
887
1068
  }
888
1069
  function loadFarmDevtoolsSnapshotRuntime() {
889
- return import("./devtools-NZUVNUP3.mjs");
1070
+ return import("./devtools-2A2GPC7B.mjs");
890
1071
  }
891
1072
  function loadFarmDevtoolsUIRuntime() {
892
1073
  return import("./devtools-ui-CYBVFLPH.mjs");
@@ -916,6 +1097,18 @@ var farmReactServerFiles = /* @__PURE__ */ new Set();
916
1097
  var FARM_SERVER_ONLY_PACKAGE_ID = "\0farm:server-only";
917
1098
  var FARM_PLATFORM_ENTRY = "@farm.js/core/platform";
918
1099
  var FARM_PLATFORM_CLIENT_ID = "\0farm:platform-client";
1100
+ var FARM_SERVER_ONLY_ENTRIES_RESOLVE_FILTER = [
1101
+ exactIdPattern([FARM_PLATFORM_ENTRY, SERVER_ONLY_PACKAGE, ...FARM_SERVER_ONLY_ENTRIES]),
1102
+ new RegExp(`^${FARM_RESOLVE_FROM_PREFIX}`),
1103
+ // What isBuiltin() accepts: `node:` ids and the builtin names, subpaths such as fs/promises
1104
+ // included.
1105
+ /^node:/,
1106
+ exactIdPattern(builtinModules)
1107
+ ];
1108
+ var FARM_SERVER_ONLY_ENTRIES_LOAD_FILTER = [
1109
+ exactIdPattern([FARM_SERVER_ONLY_PACKAGE_ID, FARM_PLATFORM_CLIENT_ID]),
1110
+ new RegExp(`^${FARM_BROWSER_BUILTIN_PREFIX}`)
1111
+ ];
919
1112
  function createFarmPlatformClientModule(platform) {
920
1113
  return `export function platform() { return ${JSON.stringify(platform)}; }
921
1114
  export function appDataDir() {
@@ -923,6 +1116,18 @@ export function appDataDir() {
923
1116
  }
924
1117
  `;
925
1118
  }
1119
+ function createFarmServerPrebundleConfig(bundledPackages) {
1120
+ const include = bundledPackages.filter(({ prebundle }) => prebundle).map(({ name }) => name);
1121
+ if (include.length === 0) return {};
1122
+ const isBare = (id) => /^(?![a-zA-Z]:)[\w@]/.test(id) && !id.includes(":");
1123
+ const isIncluded = (id) => include.some((name) => id === name || id.startsWith(`${name}/`));
1124
+ return {
1125
+ optimizeDeps: {
1126
+ include,
1127
+ rolldownOptions: { external: (id) => isBare(id) && !isIncluded(id) }
1128
+ }
1129
+ };
1130
+ }
926
1131
  function farmServerOnlyEntriesPlugin(options = {}) {
927
1132
  let root = process.cwd();
928
1133
  let vercelOgInstalled = false;
@@ -930,6 +1135,9 @@ function farmServerOnlyEntriesPlugin(options = {}) {
930
1135
  name: "farm:server-only-entries",
931
1136
  enforce: "pre",
932
1137
  config(config) {
1138
+ const bundledPackages = collectFarmServerBundledPackageInfo(
1139
+ path6.resolve(config.root ?? process.cwd())
1140
+ );
933
1141
  return {
934
1142
  optimizeDeps: { rolldownOptions: { plugins: [farmBrowserBuiltinsOptimizerPlugin()] } },
935
1143
  ssr: {
@@ -937,48 +1145,68 @@ function farmServerOnlyEntriesPlugin(options = {}) {
937
1145
  // Resolve `server-only` here rather than in Node, which would load its throwing build.
938
1146
  SERVER_ONLY_PACKAGE,
939
1147
  // Packages Node cannot load as a bundler does (stylesheet imports, `module`-only ESM).
940
- ...collectFarmServerBundledPackages(path6.resolve(config.root ?? process.cwd()))
941
- ]
1148
+ ...bundledPackages.map(({ name }) => name)
1149
+ ],
1150
+ ...options.prebundleServerPackages ? createFarmServerPrebundleConfig(bundledPackages) : {}
942
1151
  }
943
1152
  };
944
1153
  },
945
1154
  configResolved(config) {
946
1155
  root = config.root;
947
1156
  },
948
- resolveId(id, importer, options2) {
949
- if (id === FARM_PLATFORM_ENTRY) return options2?.ssr ? null : FARM_PLATFORM_CLIENT_ID;
950
- if (id === SERVER_ONLY_PACKAGE) {
951
- if (options2?.ssr || options2?.scan) {
952
- return FARM_SERVER_ONLY_PACKAGE_ID;
1157
+ resolveId: {
1158
+ filter: { id: FARM_SERVER_ONLY_ENTRIES_RESOLVE_FILTER },
1159
+ handler(id, importer, options2) {
1160
+ if (id === FARM_PLATFORM_ENTRY) return options2?.ssr ? null : FARM_PLATFORM_CLIENT_ID;
1161
+ if (id === SERVER_ONLY_PACKAGE) {
1162
+ if (options2?.ssr || options2?.scan) {
1163
+ return FARM_SERVER_ONLY_PACKAGE_ID;
1164
+ }
1165
+ this.error(
1166
+ `${importer ?? "A module"} imports "server-only", so it must not reach the browser, but client code imports it. Move what the client needs out of that module, or call it from a server component, server function or API route.`
1167
+ );
953
1168
  }
954
- this.error(
955
- `${importer ?? "A module"} imports "server-only", so it must not reach the browser, but client code imports it. Move what the client needs out of that module, or call it from a server component, server function or API route.`
956
- );
957
- }
958
- if (!options2?.ssr && isBuiltin(id)) {
959
- return resolveFarmBrowserBuiltin(this, id, importer, options2);
960
- }
961
- if (!FARM_SERVER_ONLY_ENTRIES.has(id)) return null;
962
- const importedBy = importer ? ` (imported by ${importer})` : "";
963
- if (!options2?.ssr) {
964
- this.error(
965
- `${id} is server-only and cannot be imported into client code${importedBy}. Use it from an API route or another server module.`
966
- );
967
- }
968
- vercelOgInstalled || (vercelOgInstalled = isOptionalPeerInstalled(root, "@vercel/og"));
969
- if (!vercelOgInstalled) {
970
- this.error(
971
- `${id} needs @vercel/og, which is not installed${importedBy}. ${VERCEL_OG_INSTALL_HINT}`
972
- );
1169
+ if (!options2?.ssr && isBuiltin(id)) {
1170
+ return resolveFarmBrowserBuiltin(this, id, importer, options2);
1171
+ }
1172
+ const resolveFrom = importer ? parseFarmResolveFrom(id, importer.split("?", 1)[0]) : null;
1173
+ if (resolveFrom) {
1174
+ const directory = path6.dirname(resolveFrom.importer);
1175
+ return this.resolve(resolveFrom.specifier, resolveFrom.importer, {
1176
+ ...options2,
1177
+ skipSelf: true
1178
+ }).then((resolved) => {
1179
+ if (resolved) return resolved;
1180
+ return this.error(
1181
+ `Could not resolve "${resolveFrom.specifier}" from ${directory}, the package whose server component renders it. Install it in that package, or run your package manager's install again.`
1182
+ );
1183
+ });
1184
+ }
1185
+ if (!FARM_SERVER_ONLY_ENTRIES.has(id)) return null;
1186
+ const importedBy = importer ? ` (imported by ${importer})` : "";
1187
+ if (!options2?.ssr) {
1188
+ this.error(
1189
+ `${id} is server-only and cannot be imported into client code${importedBy}. Use it from an API route or another server module.`
1190
+ );
1191
+ }
1192
+ vercelOgInstalled || (vercelOgInstalled = isOptionalPeerInstalled(root, "@vercel/og"));
1193
+ if (!vercelOgInstalled) {
1194
+ this.error(
1195
+ `${id} needs @vercel/og, which is not installed${importedBy}. ${VERCEL_OG_INSTALL_HINT}`
1196
+ );
1197
+ }
1198
+ return null;
973
1199
  }
974
- return null;
975
1200
  },
976
- load(id) {
977
- if (id === FARM_SERVER_ONLY_PACKAGE_ID) return "export {};";
978
- if (id === FARM_PLATFORM_CLIENT_ID) {
979
- return createFarmPlatformClientModule(options.platform ?? resolveFarmPlatform());
1201
+ load: {
1202
+ filter: { id: FARM_SERVER_ONLY_ENTRIES_LOAD_FILTER },
1203
+ handler(id) {
1204
+ if (id === FARM_SERVER_ONLY_PACKAGE_ID) return "export {};";
1205
+ if (id === FARM_PLATFORM_CLIENT_ID) {
1206
+ return createFarmPlatformClientModule(options.platform ?? resolveFarmPlatform());
1207
+ }
1208
+ return loadFarmBrowserBuiltin(id) ?? null;
980
1209
  }
981
- return loadFarmBrowserBuiltin(id) ?? null;
982
1210
  }
983
1211
  };
984
1212
  }
@@ -1057,10 +1285,36 @@ function withFarmRequestTracing(handler, apiRuntime, resolveTraceUrl = (request)
1057
1285
  }
1058
1286
  res.statusCode = 500;
1059
1287
  res.setHeader("Content-Type", "application/json");
1060
- res.end(JSON.stringify({ error: "Internal server error" }));
1288
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
1061
1289
  });
1062
1290
  };
1063
1291
  }
1292
+ function sendFarmDevErrorJSON(res) {
1293
+ res.statusCode = 500;
1294
+ res.setHeader("Content-Type", "application/json");
1295
+ res.setHeader("Cache-Control", "private, no-store");
1296
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
1297
+ }
1298
+ function createFarmDevMiddlewareErrorResponse() {
1299
+ return new Response(FARM_INTERNAL_SERVER_ERROR_BODY, {
1300
+ status: 500,
1301
+ headers: { "Content-Type": "application/json", "Cache-Control": "private, no-store" }
1302
+ });
1303
+ }
1304
+ function sendFarmDevRuntimeHookError(res, json) {
1305
+ res.statusCode = 500;
1306
+ res.setHeader("Content-Type", json ? "application/json" : "text/plain; charset=utf-8");
1307
+ res.end(json ? FARM_INTERNAL_SERVER_ERROR_BODY : "Internal Server Error");
1308
+ }
1309
+ var FARM_CONFIG_ROUTE_PLUGIN_NAMES = /* @__PURE__ */ new Set([
1310
+ FARM_CONFIG_HEADERS_PLUGIN_NAME,
1311
+ FARM_CONFIG_REDIRECTS_PLUGIN_NAME,
1312
+ FARM_CONFIG_REWRITES_PLUGIN_NAME
1313
+ ]);
1314
+ function isFarmConfigRoutePlugin(plugin) {
1315
+ return FARM_CONFIG_ROUTE_PLUGIN_NAMES.has(plugin.name);
1316
+ }
1317
+ var FARM_DEV_CONFIG_REWRITE_SOURCE = /* @__PURE__ */ Symbol.for("farm.devConfigRewriteSource");
1064
1318
  async function proxyFarmExternalRewrite(req, res, bodySizeLimit) {
1065
1319
  const destination = req.url;
1066
1320
  if (!destination || !/^https?:\/\//i.test(destination)) return false;
@@ -1158,6 +1412,32 @@ function interceptFarmDevPageResponse(options) {
1158
1412
  const originalFlushHeaders = res.flushHeaders?.bind(res);
1159
1413
  let afterResponseCalled = false;
1160
1414
  let interceptedEnd = false;
1415
+ const restore = () => {
1416
+ res.write = originalWrite;
1417
+ res.end = originalEnd;
1418
+ res.writeHead = originalWriteHead;
1419
+ if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;
1420
+ delete res[FARM_NODE_RESPONSE_END_PENDING];
1421
+ };
1422
+ let runtimeHookFailed = false;
1423
+ const endRuntimeRequest = (response) => pm.endRuntimeRequest(runtimeSession, response).catch((error) => {
1424
+ runtimeHookFailed = true;
1425
+ throw error;
1426
+ });
1427
+ const reportFailure = (error) => {
1428
+ if (!runtimeHookFailed) void options.emitError(error);
1429
+ console.error("Error in afterResponse hook:", error);
1430
+ };
1431
+ const writeRuntimeHookFailure = () => {
1432
+ res.statusCode = 500;
1433
+ res.removeHeader("Content-Length");
1434
+ res.setHeader(
1435
+ "Content-Type",
1436
+ options.jsonError ? "application/json" : "text/plain; charset=utf-8"
1437
+ );
1438
+ originalWriteHead(500);
1439
+ originalWrite(options.jsonError ? FARM_INTERNAL_SERVER_ERROR_BODY : "Internal Server Error");
1440
+ };
1161
1441
  const htmlChunks = [];
1162
1442
  const responseChunks = [];
1163
1443
  let didStreamHtml = false;
@@ -1188,8 +1468,7 @@ function interceptFarmDevPageResponse(options) {
1188
1468
  const status = res.statusCode || 200;
1189
1469
  const canHaveBody = method !== "HEAD" && status !== 204 && status !== 205 && status !== 304;
1190
1470
  pm.copyRequestContext(req, runtimeSession.request);
1191
- const done = pm.endRuntimeRequest(
1192
- runtimeSession,
1471
+ const done = endRuntimeRequest(
1193
1472
  new Response(canHaveBody ? body : null, {
1194
1473
  status,
1195
1474
  headers: createHeadersFromNodeResponse(res)
@@ -1273,13 +1552,6 @@ function interceptFarmDevPageResponse(options) {
1273
1552
  options.logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, "PAGE");
1274
1553
  const originalEndArgs = [...args];
1275
1554
  const callback = typeof originalEndArgs[originalEndArgs.length - 1] === "function" ? originalEndArgs[originalEndArgs.length - 1] : void 0;
1276
- const restore = () => {
1277
- res.write = originalWrite;
1278
- res.end = originalEnd;
1279
- res.writeHead = originalWriteHead;
1280
- if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;
1281
- delete res[FARM_NODE_RESPONSE_END_PENDING];
1282
- };
1283
1555
  if (streamsThroughRuntime()) {
1284
1556
  const stream = startRuntimeStream();
1285
1557
  streamRuntimeChunk(toNodeResponseBuffer(args[0], args[1]));
@@ -1290,15 +1562,8 @@ function interceptFarmDevPageResponse(options) {
1290
1562
  stream.done.then(
1291
1563
  () => hasAfterResponseHook ? pm.runHookParallel("afterResponse", req, res) : void 0
1292
1564
  ).catch((error) => {
1293
- void options.emitError(error);
1294
- console.error("Error in afterResponse hook:", error);
1295
- if (!res.headersSent) {
1296
- res.statusCode = 500;
1297
- res.removeHeader("Content-Length");
1298
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
1299
- originalWriteHead(500);
1300
- originalWrite("Internal Server Error");
1301
- }
1565
+ reportFailure(error);
1566
+ if (!res.headersSent) writeRuntimeHookFailure();
1302
1567
  }).finally(() => {
1303
1568
  restore();
1304
1569
  if (callback) originalEnd(callback);
@@ -1317,15 +1582,23 @@ function interceptFarmDevPageResponse(options) {
1317
1582
  Promise.resolve().then(async () => {
1318
1583
  if (isHtmlResponse) {
1319
1584
  const fullHtml = Buffer.concat(htmlChunks).toString("utf8");
1320
- if (!didStreamHtml || bufferPluginResponse) {
1321
- let html = await pm.runHookSerial("transformHTML", fullHtml);
1322
- html = await pm.runHookSerial("afterRender", html, renderPayload);
1323
- originalEndArgs.length = 0;
1324
- originalEndArgs.push(html);
1325
- if (callback) originalEndArgs.push(callback);
1326
- } else {
1327
- await pm.runHookSerial("transformHTML", fullHtml);
1328
- await pm.runHookSerial("afterRender", fullHtml, renderPayload);
1585
+ try {
1586
+ if (!didStreamHtml || bufferPluginResponse) {
1587
+ let html = await pm.runHookSerial("transformHTML", fullHtml);
1588
+ html = await pm.runHookSerial("afterRender", html, renderPayload);
1589
+ originalEndArgs.length = 0;
1590
+ originalEndArgs.push(html);
1591
+ if (callback) originalEndArgs.push(callback);
1592
+ } else {
1593
+ await pm.runHookSerial("transformHTML", fullHtml);
1594
+ await pm.runHookSerial("afterRender", fullHtml, renderPayload);
1595
+ }
1596
+ } catch (error) {
1597
+ if (runtimeSession) {
1598
+ runtimeHookFailed = true;
1599
+ await pm.failRuntimeRequest(runtimeSession, error);
1600
+ }
1601
+ throw error;
1329
1602
  }
1330
1603
  }
1331
1604
  if (runtimeSession) {
@@ -1334,8 +1607,7 @@ function interceptFarmDevPageResponse(options) {
1334
1607
  const canHaveBody = method !== "HEAD" && status !== 204 && status !== 205 && status !== 304;
1335
1608
  const firstArg = originalEndArgs[0];
1336
1609
  const responseBody = canHaveBody ? isHtmlResponse ? didStreamHtml && !bufferPluginResponse ? Buffer.concat(htmlChunks) : toNodeResponseBuffer(firstArg, originalEndArgs[1]) : hasRuntimeAfterHook ? Buffer.concat(responseChunks) : toNodeResponseBuffer(firstArg, originalEndArgs[1]) : null;
1337
- const runtimeResponse = await pm.endRuntimeRequest(
1338
- runtimeSession,
1610
+ const runtimeResponse = await endRuntimeRequest(
1339
1611
  new Response(responseBody ? toRequestBody(responseBody) : responseBody, {
1340
1612
  status,
1341
1613
  headers: createHeadersFromNodeResponse(res)
@@ -1360,8 +1632,13 @@ function interceptFarmDevPageResponse(options) {
1360
1632
  delete res[FARM_NODE_RESPONSE_END_PENDING];
1361
1633
  originalEnd(...originalEndArgs);
1362
1634
  }).catch((error) => {
1363
- void options.emitError(error);
1364
- console.error("Error in afterResponse hook:", error);
1635
+ reportFailure(error);
1636
+ if (runtimeHookFailed && !res.headersSent) {
1637
+ restore();
1638
+ writeRuntimeHookFailure();
1639
+ originalEnd(callback);
1640
+ return;
1641
+ }
1365
1642
  const shouldBufferResponse = isHtmlResponse ? bufferPluginResponse : Boolean(runtimeSession && hasRuntimeAfterHook);
1366
1643
  if (shouldBufferResponse) {
1367
1644
  const body = Buffer.concat(isHtmlResponse ? htmlChunks : responseChunks);
@@ -1383,7 +1660,10 @@ function interceptFarmDevPageResponse(options) {
1383
1660
  return res;
1384
1661
  });
1385
1662
  return {
1386
- isEnded: () => interceptedEnd || res.writableEnded
1663
+ isEnded: () => interceptedEnd || res.writableEnded,
1664
+ release() {
1665
+ if (!interceptedEnd) restore();
1666
+ }
1387
1667
  };
1388
1668
  }
1389
1669
  function getFullEnvDefine(config) {
@@ -1401,7 +1681,12 @@ function getEnvDefines(config, configEnv) {
1401
1681
  __FARM_API_BASE_URL__: JSON.stringify(getFarmAPIBaseURLDefine(config)),
1402
1682
  __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),
1403
1683
  __FARM_IMAGE_CONFIG__: JSON.stringify(
1404
- getPublicFarmImageConfig(resolveFarmImageConfig(config.images))
1684
+ getPublicFarmImageConfig(
1685
+ resolveFarmImageConfig(
1686
+ config.images,
1687
+ isFarmRendererDisabled(config.renderer) ? "none" : void 0
1688
+ )
1689
+ )
1405
1690
  )
1406
1691
  };
1407
1692
  if (configEnv?.isSsrBuild) {
@@ -1434,25 +1719,57 @@ function fileContainsProgrammaticPageRoute(file) {
1434
1719
  return false;
1435
1720
  }
1436
1721
  }
1437
- function rewriteEarlySsrRelativeImports(options) {
1438
- const cleanId = options.id.split("?", 1)[0];
1439
- if (!path6.isAbsolute(cleanId) || cleanId.replace(/\\/g, "/").includes("/node_modules/")) {
1722
+ var moduleLexerReady = false;
1723
+ function lexModuleSpecifiers(code) {
1724
+ if (!moduleLexerReady) {
1725
+ initModuleLexer();
1726
+ moduleLexerReady = true;
1727
+ }
1728
+ let imports;
1729
+ try {
1730
+ [imports] = lexModule(code);
1731
+ } catch {
1440
1732
  return null;
1441
1733
  }
1442
- const replacements = [];
1734
+ const specifiers = [];
1735
+ for (const entry of imports) {
1736
+ if (entry.n === void 0 || entry.d === -2) continue;
1737
+ const start = entry.d === -1 ? entry.s - 1 : entry.s;
1738
+ const end = entry.d === -1 ? entry.e + 1 : entry.e;
1739
+ const quote = code[start];
1740
+ if (quote !== '"' && quote !== "'" || code[end - 1] !== quote) continue;
1741
+ specifiers.push({ value: entry.n, start, end });
1742
+ }
1743
+ return specifiers;
1744
+ }
1745
+ function parseModuleSpecifiers(options) {
1443
1746
  let ast;
1444
1747
  try {
1445
1748
  ast = options.parse(options.code);
1446
1749
  } catch {
1447
1750
  return null;
1448
1751
  }
1752
+ const specifiers = [];
1449
1753
  walkModuleAst(ast, (node) => {
1450
1754
  if (node.type !== "ImportDeclaration" && node.type !== "ExportNamedDeclaration" && node.type !== "ExportAllDeclaration" && node.type !== "ImportExpression") {
1451
1755
  return;
1452
1756
  }
1453
1757
  const source = node.source;
1454
1758
  if (!isFarmModuleAstNode(source) || typeof source.value !== "string") return;
1455
- if (!source.value.startsWith(".")) return;
1759
+ specifiers.push({ value: source.value, start: source.start, end: source.end });
1760
+ });
1761
+ return specifiers;
1762
+ }
1763
+ function rewriteEarlySsrRelativeImports(options) {
1764
+ const cleanId = options.id.split("?", 1)[0];
1765
+ if (!path6.isAbsolute(cleanId) || cleanId.replace(/\\/g, "/").includes("/node_modules/")) {
1766
+ return null;
1767
+ }
1768
+ const sources = lexModuleSpecifiers(options.code) ?? parseModuleSpecifiers(options);
1769
+ if (!sources) return null;
1770
+ const replacements = [];
1771
+ for (const source of sources) {
1772
+ if (!source.value.startsWith(".")) continue;
1456
1773
  const suffixIndex = source.value.search(/[?#]/);
1457
1774
  const sourcePath = suffixIndex === -1 ? source.value : source.value.slice(0, suffixIndex);
1458
1775
  const suffix = suffixIndex === -1 ? "" : source.value.slice(suffixIndex);
@@ -1464,13 +1781,15 @@ function rewriteEarlySsrRelativeImports(options) {
1464
1781
  end: source.end,
1465
1782
  code: JSON.stringify(`${specifier}${suffix}`)
1466
1783
  });
1467
- });
1784
+ }
1468
1785
  if (replacements.length === 0) return null;
1469
- let output = options.code;
1470
- for (const replacement of replacements.sort((left, right) => right.start - left.start)) {
1471
- output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);
1786
+ let output = "";
1787
+ let copied = 0;
1788
+ for (const replacement of replacements.sort((left, right) => left.start - right.start)) {
1789
+ output += options.code.slice(copied, replacement.start) + replacement.code;
1790
+ copied = replacement.end;
1472
1791
  }
1473
- return output;
1792
+ return output + options.code.slice(copied);
1474
1793
  }
1475
1794
  function transformIsolatedClientBoundaryModule(options) {
1476
1795
  if (options.slots) {
@@ -1590,8 +1909,13 @@ function transformIsolatedClientBoundaryModule(options) {
1590
1909
  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {
1591
1910
  output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);
1592
1911
  }
1593
- const runtimeImport = options.slots ? `import { createIsland as __farm_islx_island__ } from "@farm.js/core/internal/islx-react";` : `import * as __farm_isolated_react__ from "react";
1594
- import { createFarmIsolatedClientBoundary as __farm_create_isolated_boundary__ } from "@farm.js/core/internal/isolated-boundary";`;
1912
+ const isComponent = `(value) => typeof value === "function" || (typeof value === "object" && value !== null && [Symbol.for("react.memo"), Symbol.for("react.forward_ref"), Symbol.for("react.lazy")].includes(value.$$typeof))`;
1913
+ const runtimeImport = options.slots ? options.browser ? "const __farm_islx_island__ = (component) => component;" : `import { createIsland as __farm_islx_create_island__ } from "@farm.js/core/internal/islx-react";
1914
+ const __farm_is_component__ = ${isComponent};
1915
+ const __farm_islx_island__ = (component, ...rest) => __farm_is_component__(component) ? __farm_islx_create_island__(component, ...rest) : component;` : `import * as __farm_isolated_react__ from "react";
1916
+ import { createFarmIsolatedClientBoundary as __farm_create_boundary__ } from "@farm.js/core/internal/isolated-boundary";
1917
+ const __farm_is_component__ = ${isComponent};
1918
+ const __farm_create_isolated_boundary__ = (react, component, ...rest) => __farm_is_component__(component) ? __farm_create_boundary__(react, component, ...rest) : component;`;
1595
1919
  return `${runtimeImport}
1596
1920
  ${output}
1597
1921
  ${wrapperStatements.join("\n")}
@@ -1622,8 +1946,8 @@ function isFarmModuleAstNode(value) {
1622
1946
  function isFarmConfigFile(file, root) {
1623
1947
  const normalized = file.replace(/\\/g, "/");
1624
1948
  const rootSlug = root.replace(/\\/g, "/").replace(/\/+$/, "");
1625
- const relative2 = normalized.startsWith(`${rootSlug}/`) ? normalized.slice(rootSlug.length + 1) : normalized;
1626
- return FARM_CONFIG_FILENAMES.has(relative2);
1949
+ const relative4 = normalized.startsWith(`${rootSlug}/`) ? normalized.slice(rootSlug.length + 1) : normalized;
1950
+ return FARM_CONFIG_FILENAMES.has(relative4);
1627
1951
  }
1628
1952
  var warnedClientBoundaryIds = /* @__PURE__ */ new Set();
1629
1953
  function warnClientBoundaryOnce(context, id, code, config) {
@@ -1652,7 +1976,8 @@ function hasViteAlias(alias, find) {
1652
1976
  (entry) => typeof entry.find === "string" ? entry.find === find : entry.find.test(`${find}/`)
1653
1977
  );
1654
1978
  }
1655
- function farmPlugin(options = {}, initialPluginManager) {
1979
+ function farmPlugin(options = {}, initialPluginManager, deferredSetup) {
1980
+ const rendererDisabled = isFarmRendererDisabled(options.renderer);
1656
1981
  const imageImports = farmImageImportsPlugin();
1657
1982
  const fontImports = farmFontImportsPlugin({
1658
1983
  root: options.root,
@@ -1667,12 +1992,16 @@ function farmPlugin(options = {}, initialPluginManager) {
1667
1992
  };
1668
1993
  let reactRefreshActive = false;
1669
1994
  let server;
1995
+ let deferredGates;
1996
+ let pendingClientSetup = null;
1997
+ const farmSetupContext = new AsyncLocalStorage();
1670
1998
  let apiRouteManager;
1671
1999
  let openAPIManager = null;
1672
2000
  let middlewareManager;
1673
2001
  let refreshRouteDiscovery = null;
1674
2002
  let workflowHandler = null;
1675
2003
  let isBuild = false;
2004
+ let farmOwnsDevCors = false;
1676
2005
  const docsMCPServerDisposers = /* @__PURE__ */ new Set();
1677
2006
  const releaseDocsMCPServers = () => {
1678
2007
  for (const dispose of docsMCPServerDisposers) dispose();
@@ -1689,7 +2018,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1689
2018
  console.log(log);
1690
2019
  };
1691
2020
  const getProgrammaticClientRoutes = () => options.programmaticClientRoutes ?? farmApp?.getRouteManager().getProgrammaticClientRoutes();
1692
- return {
2021
+ const plugin = {
1693
2022
  name: "farm",
1694
2023
  api: { getProgrammaticClientRoutes },
1695
2024
  config(userConfig, configEnv) {
@@ -1697,6 +2026,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1697
2026
  const layerAliases = getFarmLayerAliases(options.layers);
1698
2027
  const sourceAlias = hasViteAlias(userConfig.resolve?.alias, "@") ? {} : createFarmSourceAlias(options.root || process.cwd(), options.srcDir);
1699
2028
  const layerRoots = (options.layers ?? []).map((layer) => layer.root);
2029
+ farmOwnsDevCors = !isBuild && userConfig.server?.cors === void 0;
1700
2030
  return {
1701
2031
  // Honor Farm's publicDir so the dev server serves the same static
1702
2032
  // directory the production client build emits.
@@ -1709,6 +2039,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1709
2039
  alias: { ...layerAliases, ...sourceAlias }
1710
2040
  },
1711
2041
  server: {
2042
+ ...farmOwnsDevCors ? { cors: false } : {},
1712
2043
  fs: {
1713
2044
  ...layerRoots.length ? { allow: [path6.resolve(options.root || process.cwd()), ...layerRoots] } : {},
1714
2045
  deny: getFarmDevFsDeny(userConfig.server?.fs?.deny, options)
@@ -1721,7 +2052,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1721
2052
  await fontImports.configResolved.call(this, config);
1722
2053
  }
1723
2054
  serverFnTransformActive = config.plugins.some(
1724
- (plugin) => plugin.name === SERVER_FN_TRANSFORM_PLUGIN
2055
+ (plugin2) => plugin2.name === SERVER_FN_TRANSFORM_PLUGIN
1725
2056
  );
1726
2057
  reactRefreshActive = isFarmReactRefreshActive(config);
1727
2058
  if (options.experimental?.serverActions === true && !serverFnTransformActive && !islandsServerFns()) {
@@ -1740,7 +2071,16 @@ function farmPlugin(options = {}, initialPluginManager) {
1740
2071
  await fontImports.configureServer.call(this, viteServer);
1741
2072
  }
1742
2073
  server = viteServer;
2074
+ const farmMiddlewares = deferredGates?.pre.target ?? viteServer.middlewares;
2075
+ const farmPostMiddlewares = deferredGates?.post.target ?? viteServer.middlewares;
1743
2076
  const pm = initialPluginManager;
2077
+ const configRoutePlugins = new Set(
2078
+ pm?.getPlugins().filter(isFarmConfigRoutePlugin).map((plugin2) => plugin2.name)
2079
+ );
2080
+ const configRedirectMatchers = (pm?.getPlugins() ?? []).flatMap((plugin2) => {
2081
+ const matcher = getConfigRedirectMatcher(plugin2);
2082
+ return matcher ? [matcher] : [];
2083
+ });
1744
2084
  const emitPluginError = async (phase, error, meta) => {
1745
2085
  if (!pm) return;
1746
2086
  try {
@@ -1755,11 +2095,17 @@ function farmPlugin(options = {}, initialPluginManager) {
1755
2095
  },
1756
2096
  server
1757
2097
  );
2098
+ farmApp.getRouteManager().usePackageClientBoundaryCacheFile(
2099
+ resolvePackageClientBoundaryCacheFile(
2100
+ farmApp.getConfig().root,
2101
+ options.distDir || ".farm"
2102
+ )
2103
+ );
1758
2104
  await farmApp.initialize();
1759
2105
  const farmConfig = farmApp.getConfig();
1760
2106
  let farmAppPackages;
1761
2107
  if (farmConfig.agent?.noindexPreviews) {
1762
- server.middlewares.use((_req, res, next) => {
2108
+ farmMiddlewares.use((_req, res, next) => {
1763
2109
  if (isFarmPreviewDeploymentEnvironment(process.env)) {
1764
2110
  res.setHeader("X-Robots-Tag", FARM_PREVIEW_ROBOTS_TAG);
1765
2111
  }
@@ -2068,7 +2414,8 @@ function farmPlugin(options = {}, initialPluginManager) {
2068
2414
  const { OpenAPIManager } = await loadFarmOpenAPIDevRuntime();
2069
2415
  openAPIManager = new OpenAPIManager(appDirs, options.openapi, {
2070
2416
  mode: "development",
2071
- apiBaseURL: typeof options.api?.baseURL === "string" ? options.api.baseURL : void 0
2417
+ apiBaseURL: typeof options.api?.baseURL === "string" ? options.api.baseURL : void 0,
2418
+ loadModule: (filePath) => apiRouteManager.loadModule(filePath)
2072
2419
  });
2073
2420
  const spec = await openAPIManager.generateSpec();
2074
2421
  reportOpenAPIDevGenerationResult(spec);
@@ -2117,9 +2464,10 @@ function farmPlugin(options = {}, initialPluginManager) {
2117
2464
  loadModule: async (specifier) => {
2118
2465
  const resolved = await server.environments.ssr.pluginContainer.resolveId(specifier);
2119
2466
  if (specifier === farmConfig.docs.adapter?.server && resolved?.id) {
2467
+ const file = resolved.id.split("?", 1)[0];
2120
2468
  return import(
2121
2469
  /* @vite-ignore */
2122
- pathToFileURL(resolved.id).href
2470
+ pathToFileURL(file).href
2123
2471
  );
2124
2472
  }
2125
2473
  return loadFarmDevModule(server, resolved?.id ?? specifier);
@@ -2144,7 +2492,8 @@ function farmPlugin(options = {}, initialPluginManager) {
2144
2492
  farmConfig.root,
2145
2493
  farmConfig.srcDir
2146
2494
  ),
2147
- isPathGuarded: isFarmDocsPathGuarded
2495
+ isPathGuarded: isFarmDocsPathGuarded,
2496
+ basePath: farmConfig.basePath
2148
2497
  }) : null;
2149
2498
  const wrapFarmDocsResponseWithLayouts = async (request, response) => {
2150
2499
  if (request.method === "HEAD" || response.headers.has("x-farm-docs-adapter") || !response.headers.get("content-type")?.toLowerCase().includes("text/html")) {
@@ -2253,7 +2602,8 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2253
2602
  srcDir: farmConfig.srcDir,
2254
2603
  docs: farmConfig.docs,
2255
2604
  diagnostics: true,
2256
- isPathGuarded: isFarmDocsPathGuarded
2605
+ isPathGuarded: isFarmDocsPathGuarded,
2606
+ basePath: farmConfig.basePath
2257
2607
  }) : null;
2258
2608
  const farmDocsFontAssets = new Map(
2259
2609
  farmDocsFontAssetList.map(({ url, sourcePath }) => [url, sourcePath])
@@ -2300,8 +2650,13 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2300
2650
  });
2301
2651
  }
2302
2652
  );
2303
- server.middlewares.use(
2304
- withAPIRequestTracing(async (req, res, next) => {
2653
+ const publicFileIndex = createFarmPublicFileIndex(() => server.config.publicDir);
2654
+ for (const event of ["add", "unlink", "addDir", "unlinkDir"]) {
2655
+ server.watcher.on(event, (file) => publicFileIndex.invalidate(file));
2656
+ }
2657
+ const deferredDottedRequests = /* @__PURE__ */ new WeakMap();
2658
+ farmMiddlewares.use(
2659
+ withAPIRequestTracing(async function handleFarmDevRequest(req, res, next) {
2305
2660
  const requestUrl = req.url || "/";
2306
2661
  const requestMethod = req.method || "GET";
2307
2662
  const currentConfig = farmApp?.getConfig() ?? options;
@@ -2311,6 +2666,32 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2311
2666
  });
2312
2667
  const fullUrl = parsedRequestUrl.toString();
2313
2668
  const requestPathname = parsedRequestUrl.pathname;
2669
+ if (isMalformedFarmRequestPathname(requestPathname)) {
2670
+ res.statusCode = 400;
2671
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
2672
+ res.end(requestMethod === "HEAD" ? void 0 : FARM_MALFORMED_REQUEST_BODY);
2673
+ return;
2674
+ }
2675
+ if ((requestMethod === "GET" || requestMethod === "HEAD") && req[FARM_DEV_CONFIG_REWRITE_SOURCE] === void 0 && !isViteModuleRequest(parsedRequestUrl, req.headers)) {
2676
+ const publicFile = resolveFarmPublicFilePath(requestPathname, publicFileIndex.get());
2677
+ if (publicFile) {
2678
+ if (publicFile !== requestPathname) {
2679
+ req.url = `${encodeURI(publicFile)}${parsedRequestUrl.search}`;
2680
+ }
2681
+ return next();
2682
+ }
2683
+ }
2684
+ if (requestMethod === "OPTIONS" && req.headers.origin && req.headers["access-control-request-method"]) {
2685
+ const preflightHeaders = resolveRouteRuleCorsPreflightHeaders(
2686
+ currentConfig.routeRules,
2687
+ requestPathname
2688
+ );
2689
+ if (preflightHeaders) {
2690
+ res.writeHead(204, preflightHeaders);
2691
+ res.end();
2692
+ return;
2693
+ }
2694
+ }
2314
2695
  if (imageHandler && requestPathname === farmConfig.images.path) {
2315
2696
  const imageResponse = await imageHandler(
2316
2697
  createRequestFromNodeRequest(req, new URL(fullUrl))
@@ -2337,7 +2718,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2337
2718
  res.end("Farm DevTools are disabled.");
2338
2719
  return;
2339
2720
  }
2340
- if (requestPathname === FARM_DEVTOOLS_PATH && parsedRequestUrl.searchParams.get("embedded") !== "1") {
2721
+ if (requestPathname === FARM_DEVTOOLS_PATH && parsedRequestUrl.searchParams.get("embedded") !== "1" && !rendererDisabled) {
2341
2722
  let launchUrl = new URL(farmConfig.basePath || "/", parsedRequestUrl.origin);
2342
2723
  const referrer = req.headers.referer;
2343
2724
  if (referrer) {
@@ -2394,6 +2775,57 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2394
2775
  }
2395
2776
  return;
2396
2777
  }
2778
+ const isViteOwnedRequest = () => requestUrl.startsWith("/@") || requestUrl.startsWith("/node_modules/") || requestUrl.startsWith("/__farm/") || isViteModuleRequest(parsedRequestUrl, req.headers) || (requestMethod === "GET" || requestMethod === "HEAD") && requestPathname.includes(".") && (devServableFileExists(requestPathname, [server.config.publicDir]) || isViteDevClientRequest(parsedRequestUrl, req.headers) && devServableFileExists(requestPathname, [server.config.root]));
2779
+ const configRewriteSource = req[FARM_DEV_CONFIG_REWRITE_SOURCE];
2780
+ const runtimeHookErrorAnswersJSON = rendererDisabled || isFarmAPIPathname(requestPathname, apiServerBasePath);
2781
+ if (pm && configRewriteSource === void 0 && !deferredDottedRequests.has(req) && (configRoutePlugins.has(FARM_CONFIG_HEADERS_PLUGIN_NAME) || configRedirectMatchers.length > 0) && !isViteOwnedRequest()) {
2782
+ let redirect = null;
2783
+ try {
2784
+ await pm.runHookParallelFiltered(
2785
+ "beforeRequest",
2786
+ (plugin2) => plugin2.name === FARM_CONFIG_HEADERS_PLUGIN_NAME,
2787
+ req,
2788
+ res
2789
+ );
2790
+ for (const matchRedirect of configRedirectMatchers) {
2791
+ redirect ?? (redirect = matchRedirect(parsedRequestUrl));
2792
+ }
2793
+ } catch (error) {
2794
+ await emitPluginError("before-request", error, { urlPath: requestUrl });
2795
+ if (!res.headersSent) {
2796
+ res.statusCode = 500;
2797
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
2798
+ }
2799
+ res.end("Internal Server Error");
2800
+ return;
2801
+ }
2802
+ if (redirect) {
2803
+ let response = new Response(`Redirecting to ${redirect.destination}`, {
2804
+ status: redirect.statusCode,
2805
+ headers: { Location: redirect.destination }
2806
+ });
2807
+ if (pm.hasRuntimeRequestHooks()) {
2808
+ const redirectResponse = response;
2809
+ try {
2810
+ response = await pm.runRuntimeRequest(
2811
+ createRequestFromNodeRequest(req, parsedRequestUrl),
2812
+ () => redirectResponse,
2813
+ {
2814
+ kind: isFarmAPIPathname(requestPathname, apiServerBasePath) ? "api" : requestMethod === "GET" || requestMethod === "HEAD" ? "page" : "request",
2815
+ route: { pathname: requestPathname }
2816
+ }
2817
+ );
2818
+ } catch {
2819
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2820
+ logResponse(requestMethod, requestUrl, 500, 0, "PAGE");
2821
+ return;
2822
+ }
2823
+ }
2824
+ await sendWebResponse(res, response);
2825
+ logResponse(requestMethod, requestUrl, res.statusCode, 0, "PAGE");
2826
+ return;
2827
+ }
2828
+ }
2397
2829
  const runAppMiddlewareForContentRoute = async () => {
2398
2830
  if (!middlewareManager?.hasMiddleware()) return false;
2399
2831
  const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));
@@ -2405,6 +2837,40 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2405
2837
  () => middlewareManager.execute(req, res)
2406
2838
  );
2407
2839
  };
2840
+ const runAppMiddlewareInRuntimeSession = async (runtimeSession2, logResponse2) => {
2841
+ const interceptor = runtimeSession2 && pm?.hasRuntimeHook("after") && middlewareManager?.hasMiddleware() ? interceptFarmDevPageResponse({
2842
+ req,
2843
+ res,
2844
+ pm,
2845
+ runtimeSession: runtimeSession2,
2846
+ hasRuntimeAfterHook: true,
2847
+ hasAfterResponseHook: false,
2848
+ hasHTMLTransformHook: false,
2849
+ renderPayload: {},
2850
+ method: requestMethod,
2851
+ urlPath: requestUrl,
2852
+ pathname: requestPathname,
2853
+ startTime: Date.now(),
2854
+ logResponse: (_method, _path, status) => logResponse2?.(status),
2855
+ // The runtime reports a runtime.after failure itself.
2856
+ emitError: async () => {
2857
+ },
2858
+ jsonError: runtimeHookErrorAnswersJSON
2859
+ }) : void 0;
2860
+ let handled;
2861
+ try {
2862
+ handled = await runAppMiddlewareForContentRoute();
2863
+ } catch (error) {
2864
+ interceptor?.release();
2865
+ throw error;
2866
+ }
2867
+ if (!handled) {
2868
+ interceptor?.release();
2869
+ return false;
2870
+ }
2871
+ if (!interceptor?.isEnded()) logResponse2?.(res.statusCode || 200);
2872
+ return true;
2873
+ };
2408
2874
  const serveBuiltInRoute = async (respond, {
2409
2875
  kind = requestMethod === "GET" || requestMethod === "HEAD" ? "page" : "request",
2410
2876
  computed,
@@ -2414,6 +2880,16 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2414
2880
  await computed?.body?.cancel().catch(() => {
2415
2881
  });
2416
2882
  };
2883
+ const sendRuntimeResponse = async (runtimeSession3, response2) => {
2884
+ let runtimeResponse;
2885
+ try {
2886
+ runtimeResponse = await pm.endRuntimeRequest(runtimeSession3, response2);
2887
+ } catch {
2888
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2889
+ return;
2890
+ }
2891
+ await sendWebResponse(res, runtimeResponse);
2892
+ };
2417
2893
  let runtimeSession2;
2418
2894
  if (pm?.hasRuntimeRequestHooks()) {
2419
2895
  try {
@@ -2426,43 +2902,40 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2426
2902
  createRequestFromNodeRequest(req, new URL(fullUrl)),
2427
2903
  { kind, route }
2428
2904
  );
2429
- } catch (error) {
2905
+ } catch {
2430
2906
  await discard();
2431
- await emitPluginError("runtime-before", error, { pathname: requestPathname });
2432
- res.statusCode = 500;
2433
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
2434
- res.end("Internal Server Error");
2907
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2435
2908
  return;
2436
2909
  }
2437
2910
  if (runtimeSession2.response) {
2438
2911
  await discard();
2439
- await sendWebResponse(
2440
- res,
2441
- await pm.endRuntimeRequest(runtimeSession2, runtimeSession2.response)
2442
- );
2912
+ await sendRuntimeResponse(runtimeSession2, runtimeSession2.response);
2443
2913
  return;
2444
2914
  }
2445
2915
  pm.copyRequestContext(runtimeSession2.request, req);
2446
2916
  applyWebRequestToNodeRequest(runtimeSession2.request, req);
2447
2917
  }
2448
- if (await runAppMiddlewareForContentRoute()) {
2449
- await discard();
2450
- return;
2451
- }
2452
2918
  let response;
2919
+ let responding = false;
2453
2920
  try {
2921
+ if (await runAppMiddlewareInRuntimeSession(runtimeSession2)) {
2922
+ await discard();
2923
+ return;
2924
+ }
2925
+ responding = true;
2454
2926
  response = await respond(
2455
2927
  runtimeSession2?.request ?? createRequestFromNodeRequest(req, new URL(fullUrl))
2456
2928
  );
2457
2929
  } catch (error) {
2458
2930
  if (runtimeSession2) await pm.failRuntimeRequest(runtimeSession2, error);
2459
- throw error;
2931
+ if (!runtimeSession2 || !responding || res.headersSent) throw error;
2932
+ console.error("[FARM] Built-in route error:", error);
2933
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2934
+ return;
2460
2935
  }
2461
2936
  if (!response) return;
2462
- await sendWebResponse(
2463
- res,
2464
- runtimeSession2 ? await pm.endRuntimeRequest(runtimeSession2, response) : response
2465
- );
2937
+ if (runtimeSession2) await sendRuntimeResponse(runtimeSession2, response);
2938
+ else await sendWebResponse(res, response);
2466
2939
  };
2467
2940
  const openAPIRequestPathname = openAPIManager ? stripFarmBasePath(requestPathname, farmConfig.basePath) : requestPathname;
2468
2941
  if (openAPIManager && options.openapi?.specRoute && openAPIRequestPathname === options.openapi.specRoute) {
@@ -2549,7 +3022,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2549
3022
  }
2550
3023
  }),
2551
3024
  {
2552
- basePath: farmConfig.basePath,
3025
+ basePath: farmApp.getConfig().basePath,
2553
3026
  apiServerBasePath,
2554
3027
  defaultMCP: () => farmApp.getServerRenderer().getDefaultMCPServer()
2555
3028
  }
@@ -2566,11 +3039,15 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2566
3039
  }
2567
3040
  }
2568
3041
  const viteModuleRequest = isViteModuleRequest(parsedRequestUrl, req.headers);
2569
- const appOwnsDocsEnginePath = farmAppOwnsDocsEnginePath(requestPathname, {
2570
- generatedPaths: farmAgentGeneratedPaths(farmConfig),
2571
- routeManager: farmApp.getRouteManager(),
2572
- publicDir: server.config.publicDir
2573
- });
3042
+ const toRoutePathname = (pathname2) => farmApp.getRouteManager().toRoutePathname(pathname2);
3043
+ const appOwnsDocsEnginePath = farmAppOwnsDocsEnginePath(
3044
+ toRoutePathname(requestPathname),
3045
+ {
3046
+ generatedPaths: farmAgentGeneratedPaths(farmConfig),
3047
+ routeManager: farmApp.getRouteManager(),
3048
+ publicDir: server.config.publicDir
3049
+ }
3050
+ );
2574
3051
  if (farmDocsHandler && !appOwnsDocsEnginePath && !viteModuleRequest) {
2575
3052
  const docsRequest = new Request(fullUrl, {
2576
3053
  method: requestMethod,
@@ -2597,7 +3074,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2597
3074
  }
2598
3075
  }
2599
3076
  if (options.mobileClient && !viteModuleRequest && (requestMethod === "GET" || requestMethod === "HEAD" || requestMethod === "POST") && req.headers.accept?.includes(FARM_NATIVE_TREE_CONTENT_TYPE)) {
2600
- const { createFarmNativeTreeResponse } = await import("./native-tree-VV6WN3GX.mjs");
3077
+ const { createFarmNativeTreeResponse } = await import("./native-tree-Y5YQANW7.mjs");
2601
3078
  const treeBodyInit = requestMethod === "POST" ? { body: createFarmNodeRequestBodyStream(req), duplex: "half" } : {};
2602
3079
  const treeResponse = await createFarmNativeTreeResponse({
2603
3080
  request: new Request(fullUrl, {
@@ -2618,9 +3095,12 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2618
3095
  });
2619
3096
  return;
2620
3097
  }
2621
- const markdownRouteLabel = () => resolveFarmMarkdownRouteLabel(
2622
- stripFarmBasePath(requestPathname, farmConfig.basePath),
2623
- (page) => farmApp.getRouteManager().matchRoute(page).route?.pattern
3098
+ const markdownRouteLabel = () => (
3099
+ // On the route path, as production labels it: /fr/index.md is /index.md.
3100
+ resolveFarmMarkdownRouteLabel(
3101
+ toRoutePathname(requestPathname),
3102
+ (page) => farmApp.getRouteManager().matchRoute(page).route?.pattern
3103
+ )
2624
3104
  );
2625
3105
  const markdownSourceResponse = viteModuleRequest ? null : await createFarmMarkdownSourceResponse({
2626
3106
  request: new Request(fullUrl, {
@@ -2628,6 +3108,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2628
3108
  headers: docsHeaders
2629
3109
  }),
2630
3110
  config: farmApp.getConfig().mdx,
3111
+ routePathname: toRoutePathname,
2631
3112
  resolveSource: async (pathname2) => {
2632
3113
  const match = farmApp.getRouteManager().matchRoute(pathname2);
2633
3114
  const sourcePath = match.route?.markdownSourcePath || (match.route && isFarmMarkdownPageFile(match.route.modulePath) ? match.route.modulePath : null);
@@ -2661,6 +3142,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2661
3142
  headers: docsHeaders
2662
3143
  }),
2663
3144
  config: farmApp.getConfig().md,
3145
+ routePathname: toRoutePathname,
2664
3146
  routeExists: (pathname2) => Boolean(farmApp.getRouteManager().matchRoute(pathname2).route),
2665
3147
  // The page is rendered by this server's own listener, never the host the
2666
3148
  // caller's Host names. Redirects are not followed, so the mirror answers with
@@ -2687,7 +3169,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2687
3169
  return;
2688
3170
  }
2689
3171
  if (!viteModuleRequest && farmRequestWantsMarkdown(requestPathname, req.headers.accept)) {
2690
- const markdownRoute = farmApp.getRouteManager().matchRoute(normalizeFarmMarkdownRoutePath(requestPathname));
3172
+ const markdownRoute = farmApp.getRouteManager().matchRoute(normalizeFarmMarkdownRoutePath(requestPathname, toRoutePathname));
2691
3173
  if (!markdownRoute.route) {
2692
3174
  await serveBuiltInRoute(
2693
3175
  () => new Response(
@@ -2709,7 +3191,8 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2709
3191
  farmApp.getConfig().md,
2710
3192
  requestPathname,
2711
3193
  {
2712
- accept: "text/markdown"
3194
+ accept: "text/markdown",
3195
+ routePathname: toRoutePathname
2713
3196
  }
2714
3197
  );
2715
3198
  if (markdownPageTarget && farmApp.getRouteManager().matchRoute(markdownPageTarget.pathname).route) {
@@ -2718,8 +3201,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2718
3201
  if (!varyValues.some((value) => value.toLowerCase() === "accept")) {
2719
3202
  res.setHeader("Vary", [...varyValues, "Accept"].join(", "));
2720
3203
  }
2721
- const alternatePath = getFarmMarkdownMirrorPath(markdownPageTarget.pathname);
2722
- const alternateLink = `<${alternatePath}>; rel="alternate"; type="text/markdown"`;
3204
+ const alternateLink = `<${markdownPageTarget.markdownPath}>; rel="alternate"; type="text/markdown"`;
2723
3205
  const currentLink = res.getHeader("Link");
2724
3206
  res.setHeader(
2725
3207
  "Link",
@@ -2764,13 +3246,14 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2764
3246
  return false;
2765
3247
  }
2766
3248
  const startTime2 = Date.now();
3249
+ let runtimeReportsErrors = false;
2767
3250
  try {
2768
3251
  if (pm) {
2769
3252
  await pm.runHookParallelFiltered(
2770
3253
  "beforeRequest",
2771
- (plugin) => {
2772
- const owner = getFarmIntegrationPluginOwner(plugin);
2773
- return plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME && (owner?.source !== "lifecycle" || owner.key !== matchedRoute.key);
3254
+ (plugin2) => {
3255
+ const owner = getFarmIntegrationPluginOwner(plugin2);
3256
+ return !isFarmConfigRoutePlugin(plugin2) && (owner?.source !== "lifecycle" || owner.key !== matchedRoute.key);
2774
3257
  },
2775
3258
  req,
2776
3259
  res
@@ -2797,22 +3280,29 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2797
3280
  body: toRequestBody(body),
2798
3281
  signal: createFarmNodeRequestAbortSignal(req, res)
2799
3282
  });
2800
- const dispatchIntegration = async (request) => {
2801
- const result = await dispatchIntegrationRequest(
2802
- {
2803
- integration: matchedRoute.integration,
2804
- config: currentConfig,
2805
- isDev: true,
2806
- isProd: false
2807
- },
2808
- request,
2809
- { clientAddress: req.socket?.remoteAddress }
2810
- );
2811
- if (!result) {
2812
- throw new Error(`Matched integration route did not return a response`);
3283
+ const dispatchIntegration = async (request, runtime) => {
3284
+ try {
3285
+ const result = await dispatchIntegrationRequest(
3286
+ {
3287
+ integration: matchedRoute.integration,
3288
+ config: currentConfig,
3289
+ isDev: true,
3290
+ isProd: false
3291
+ },
3292
+ request,
3293
+ { clientAddress: req.socket?.remoteAddress }
3294
+ );
3295
+ if (!result) {
3296
+ throw new Error(`Matched integration route did not return a response`);
3297
+ }
3298
+ return result;
3299
+ } catch (error) {
3300
+ logger.error(`Integration route error: ${error}`);
3301
+ await runtime?.reportError(error);
3302
+ return createFarmInternalServerErrorResponse();
2813
3303
  }
2814
- return result;
2815
3304
  };
3305
+ runtimeReportsErrors = Boolean(pm);
2816
3306
  const response = pm ? await pm.runRuntimeRequest(integrationRequest, dispatchIntegration, {
2817
3307
  kind: "integration",
2818
3308
  route: {
@@ -2835,21 +3325,59 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2835
3325
  }
2836
3326
  const duration = Date.now() - startTime2;
2837
3327
  logResponse(requestMethod, requestUrl, 500, duration, "API");
2838
- await emitPluginError("integration-handler", error, {
2839
- pathname: requestPathname,
2840
- routePath: requestUrl,
2841
- method: requestMethod,
2842
- integration: matchedRoute.key
2843
- });
3328
+ if (!runtimeReportsErrors) {
3329
+ await emitPluginError("integration-handler", error, {
3330
+ pathname: requestPathname,
3331
+ routePath: requestUrl,
3332
+ method: requestMethod,
3333
+ integration: matchedRoute.key
3334
+ });
3335
+ }
2844
3336
  logger.error(`Integration route error: ${error}`);
2845
3337
  if (!res.writableEnded) {
2846
3338
  res.statusCode = 500;
2847
3339
  res.setHeader("Content-Type", "application/json");
2848
- res.end(JSON.stringify({ error: "Internal server error" }));
3340
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
2849
3341
  }
2850
3342
  return true;
2851
3343
  }
2852
3344
  };
3345
+ if (pm && configRewriteSource === void 0 && configRoutePlugins.has(FARM_CONFIG_REWRITES_PLUGIN_NAME)) {
3346
+ const hasLocalDevRoute = () => {
3347
+ const routeManager3 = farmApp.getRouteManager();
3348
+ return Boolean(
3349
+ matchIntegrationRoute(configuredIntegrations, {
3350
+ pathname: requestPathname,
3351
+ method: requestMethod
3352
+ }) || routeManager3.matchRedirect(requestPathname) || apiRouteManager.matchRoute(requestPathname) || farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(requestPathname) || routeManager3.matchRoute(requestPathname).route || routeManager3.matchMetadataRoute(requestPathname) || routeManager3.matchMetadataImage(requestPathname)
3353
+ );
3354
+ };
3355
+ try {
3356
+ await pm.runHookParallelFiltered(
3357
+ "beforeRequest",
3358
+ (plugin2) => plugin2.name === FARM_CONFIG_REWRITES_PLUGIN_NAME,
3359
+ req,
3360
+ res
3361
+ );
3362
+ } catch (error) {
3363
+ await emitPluginError("before-request", error, { urlPath: requestUrl });
3364
+ res.statusCode = 500;
3365
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
3366
+ res.end("Internal Server Error");
3367
+ return;
3368
+ }
3369
+ if (req.url !== requestUrl) {
3370
+ if (isViteOwnedRequest() || hasLocalDevRoute()) {
3371
+ req.url = requestUrl;
3372
+ } else {
3373
+ if (await proxyFarmExternalRewrite(req, res, currentServerConfig.bodySizeLimit)) {
3374
+ return;
3375
+ }
3376
+ req[FARM_DEV_CONFIG_REWRITE_SOURCE] = fullUrl;
3377
+ return handleFarmDevRequest(req, res, next);
3378
+ }
3379
+ }
3380
+ }
2853
3381
  if (await tryConfiguredIntegrationRoute()) {
2854
3382
  return;
2855
3383
  }
@@ -2869,25 +3397,18 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2869
3397
  const pathname2 = resolveFarmRequestURL(req, {
2870
3398
  trustProxy: currentServerConfig.trustProxy
2871
3399
  }).pathname;
2872
- const servesLocalApiRoute = hasMatchedApiRoute || Boolean(
2873
- farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(requestPathname)
2874
- );
2875
3400
  try {
2876
3401
  if (pm) {
2877
- if (servesLocalApiRoute) {
2878
- await pm.runHookParallelFiltered(
2879
- "beforeRequest",
2880
- (plugin) => plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,
2881
- req,
2882
- res
2883
- );
2884
- } else {
2885
- await pm.runHookParallel("beforeRequest", req, res);
2886
- }
3402
+ await pm.runHookParallelFiltered(
3403
+ "beforeRequest",
3404
+ (plugin2) => !isFarmConfigRoutePlugin(plugin2),
3405
+ req,
3406
+ res
3407
+ );
2887
3408
  }
2888
- if (res.writableEnded || await proxyFarmExternalRewrite(req, res, currentServerConfig.bodySizeLimit)) {
2889
- const duration2 = Date.now() - startTime2;
2890
- logResponse(method2, urlPath2, res.statusCode || 200, duration2, "API");
3409
+ if (res.writableEnded) {
3410
+ const duration = Date.now() - startTime2;
3411
+ logResponse(method2, urlPath2, res.statusCode || 200, duration, "API");
2891
3412
  return;
2892
3413
  }
2893
3414
  } catch (error) {
@@ -2898,14 +3419,129 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2898
3419
  logger.error(`Request hook error: ${error}`);
2899
3420
  res.statusCode = 500;
2900
3421
  res.setHeader("Content-Type", "application/json");
2901
- res.end(JSON.stringify({ error: "Internal server error" }));
3422
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
2902
3423
  return;
2903
3424
  }
2904
- if (await runAppMiddlewareForContentRoute()) {
2905
- const duration2 = Date.now() - startTime2;
2906
- logResponse(method2, urlPath2, res.statusCode || 200, duration2, "API");
3425
+ const createAPIRequest = async () => {
3426
+ const headers = new Headers();
3427
+ for (const [key, value] of Object.entries(req.headers)) {
3428
+ if (value) {
3429
+ headers.set(key, Array.isArray(value) ? value.join(", ") : value);
3430
+ }
3431
+ }
3432
+ let body;
3433
+ if (req.method !== "GET" && req.method !== "HEAD") {
3434
+ body = await readNodeRequestBody(req, currentServerConfig.bodySizeLimit);
3435
+ }
3436
+ return new Request(`http://${req.headers.host || "localhost:3000"}${req.url}`, {
3437
+ method: req.method,
3438
+ headers,
3439
+ body: toRequestBody(body),
3440
+ signal: createFarmNodeRequestAbortSignal(req, res)
3441
+ });
3442
+ };
3443
+ const isDocsAPIRequest = Boolean(
3444
+ farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname2)
3445
+ );
3446
+ const docsRuntimeOptions = () => ({
3447
+ kind: "docs",
3448
+ route: setFarmRouteLabel(
3449
+ { pathname: pathname2, pattern: urlPath2 },
3450
+ resolveFarmDocsRouteLabel(pathname2, {
3451
+ path: farmConfig.docs?.entry || "/docs",
3452
+ roots: farmConfig.docs?.roots?.map((root) => root.entry)
3453
+ })
3454
+ )
3455
+ });
3456
+ let runtimeSession2;
3457
+ let sessionRequestUrl;
3458
+ if (pm?.hasRuntimeRequestHooks()) {
3459
+ try {
3460
+ runtimeSession2 = await pm.beginRuntimeRequest(
3461
+ await createAPIRequest(),
3462
+ !hasMatchedApiRoute && isDocsAPIRequest ? docsRuntimeOptions() : {
3463
+ kind: "api",
3464
+ route: matchedApiRoute ? { pathname: pathname2, pattern: matchedApiRoute.route.path } : { pathname: pathname2 }
3465
+ }
3466
+ );
3467
+ if (runtimeSession2.response) {
3468
+ const response = await pm.endRuntimeRequest(
3469
+ runtimeSession2,
3470
+ runtimeSession2.response
3471
+ );
3472
+ logResponse(method2, urlPath2, response.status, Date.now() - startTime2, "API");
3473
+ await sendWebResponse(res, response);
3474
+ return;
3475
+ }
3476
+ } catch (error) {
3477
+ const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);
3478
+ if (bodyErrorResponse) {
3479
+ logResponse(
3480
+ method2,
3481
+ urlPath2,
3482
+ bodyErrorResponse.status,
3483
+ Date.now() - startTime2,
3484
+ "API"
3485
+ );
3486
+ await sendWebResponse(res, bodyErrorResponse);
3487
+ return;
3488
+ }
3489
+ logger.error(`API route error: ${error}`);
3490
+ res.statusCode = 500;
3491
+ res.setHeader("Content-Type", "application/json");
3492
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3493
+ return;
3494
+ }
3495
+ pm.copyRequestContext(runtimeSession2.request, req);
3496
+ applyWebRequestToNodeRequest(runtimeSession2.request, req);
3497
+ sessionRequestUrl = req.url;
3498
+ }
3499
+ try {
3500
+ if (await runAppMiddlewareInRuntimeSession(
3501
+ runtimeSession2,
3502
+ (status) => logResponse(method2, urlPath2, status, Date.now() - startTime2, "API")
3503
+ )) {
3504
+ return;
3505
+ }
3506
+ } catch (error) {
3507
+ if (res.headersSent) {
3508
+ if (runtimeSession2) await pm.failRuntimeRequest(runtimeSession2, error);
3509
+ throw error;
3510
+ }
3511
+ logger.error(`Middleware error: ${error}`);
3512
+ let response = createFarmDevMiddlewareErrorResponse();
3513
+ if (runtimeSession2) {
3514
+ const errorResponse = response;
3515
+ try {
3516
+ response = await pm.completeRuntimeRequest(
3517
+ runtimeSession2,
3518
+ async (_request, runtime) => {
3519
+ await runtime.reportError(error);
3520
+ return errorResponse;
3521
+ }
3522
+ );
3523
+ } catch {
3524
+ logResponse(method2, urlPath2, 500, Date.now() - startTime2, "API");
3525
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
3526
+ return;
3527
+ }
3528
+ }
3529
+ logResponse(method2, urlPath2, response.status, Date.now() - startTime2, "API");
3530
+ await sendWebResponse(res, response);
2907
3531
  return;
2908
3532
  }
3533
+ const createHandlerRequest = async () => {
3534
+ if (runtimeSession2 && req.url === sessionRequestUrl && !runtimeSession2.request.bodyUsed) {
3535
+ return runtimeSession2.request;
3536
+ }
3537
+ const request = await createAPIRequest();
3538
+ if (runtimeSession2) pm.copyRequestContext(runtimeSession2.request, request);
3539
+ return request;
3540
+ };
3541
+ const runInRuntime = (request, handler, options2) => runtimeSession2 ? pm.completeRuntimeRequest(
3542
+ runtimeSession2,
3543
+ (_request, runtime) => handler(request, runtime)
3544
+ ) : pm ? pm.runRuntimeRequest(request, handler, options2) : handler(request);
2909
3545
  const apiHandler = apiRouteManager.getHandler({ throwOnError: true });
2910
3546
  const routedPathname = resolveFarmRequestURL(req, {
2911
3547
  trustProxy: currentServerConfig.trustProxy
@@ -2928,101 +3564,85 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2928
3564
  });
2929
3565
  try {
2930
3566
  const url = `http://${req.headers.host || "localhost:3000"}${req.url}`;
2931
- const headers = new Headers();
2932
- for (const [key, value] of Object.entries(req.headers)) {
2933
- if (value) {
2934
- headers.set(key, Array.isArray(value) ? value.join(", ") : value);
2935
- }
2936
- }
2937
- let body;
2938
- if (req.method !== "GET" && req.method !== "HEAD") {
2939
- body = await readNodeRequestBody(req, currentServerConfig.bodySizeLimit);
2940
- }
2941
- const request = new Request(url, {
2942
- method: req.method,
2943
- headers,
2944
- body: toRequestBody(body),
2945
- signal: createFarmNodeRequestAbortSignal(req, res)
2946
- });
3567
+ const request = await createHandlerRequest();
2947
3568
  const apiLifecyclePayload = {
2948
3569
  pathname: new URL(url).pathname,
2949
3570
  method: method2,
2950
3571
  routePath: apiRoutePattern
2951
3572
  };
2952
- const invokeAPIHandler = async (runtimeRequest) => {
3573
+ let apiHandlerFailed = false;
3574
+ const invokeAPIHandler = async (runtimeRequest, runtime) => {
2953
3575
  const handledRequest = pm ? await pm.runHookSerial(
2954
3576
  "beforeApiHandler",
2955
3577
  runtimeRequest,
2956
3578
  apiLifecyclePayload
2957
3579
  ) : runtimeRequest;
2958
- const response = await apiHandler(handledRequest);
3580
+ let response;
3581
+ try {
3582
+ response = await apiHandler(handledRequest);
3583
+ } catch (error) {
3584
+ apiHandlerFailed = true;
3585
+ emitFarmEvent({
3586
+ type: "api.error",
3587
+ pathname: pathname2,
3588
+ route: apiRoutePattern,
3589
+ method: method2,
3590
+ durationMs: Date.now() - startTime2,
3591
+ error
3592
+ });
3593
+ logger.error(`API route error: ${error}`);
3594
+ await runtime?.reportError(error);
3595
+ response = createFarmInternalServerErrorResponse();
3596
+ }
2959
3597
  return pm ? await pm.runHookSerial("afterApiHandler", response, apiLifecyclePayload) : response;
2960
3598
  };
2961
- const handledResponse = pm ? await pm.runRuntimeRequest(request, invokeAPIHandler, {
3599
+ const handledResponse = await runInRuntime(request, invokeAPIHandler, {
2962
3600
  kind: "api",
2963
3601
  route: {
2964
3602
  pathname: apiLifecyclePayload.pathname,
2965
3603
  pattern: apiLifecyclePayload.routePath
2966
3604
  }
2967
- }) : await invokeAPIHandler(request);
2968
- const duration2 = Date.now() - startTime2;
2969
- emitFarmEvent({
2970
- type: "api.request.complete",
2971
- pathname: pathname2,
2972
- route: apiRoutePattern,
2973
- method: method2,
2974
- status: handledResponse.status,
2975
- durationMs: duration2
2976
3605
  });
2977
- logResponse(method2, urlPath2, handledResponse.status, duration2, "API");
3606
+ const duration = Date.now() - startTime2;
3607
+ if (!apiHandlerFailed) {
3608
+ emitFarmEvent({
3609
+ type: "api.request.complete",
3610
+ pathname: pathname2,
3611
+ route: apiRoutePattern,
3612
+ method: method2,
3613
+ status: handledResponse.status,
3614
+ durationMs: duration
3615
+ });
3616
+ }
3617
+ logResponse(method2, urlPath2, handledResponse.status, duration, "API");
2978
3618
  await sendWebResponse(res, handledResponse);
2979
3619
  return;
2980
3620
  } catch (error) {
2981
- const duration2 = Date.now() - startTime2;
3621
+ const duration = Date.now() - startTime2;
2982
3622
  emitFarmEvent({
2983
3623
  type: "api.error",
2984
3624
  pathname: pathname2,
2985
3625
  route: apiRoutePattern,
2986
3626
  method: method2,
2987
- durationMs: duration2,
3627
+ durationMs: duration,
2988
3628
  error
2989
3629
  });
2990
3630
  const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);
2991
3631
  if (bodyErrorResponse) {
2992
- logResponse(method2, urlPath2, bodyErrorResponse.status, duration2, "API");
3632
+ logResponse(method2, urlPath2, bodyErrorResponse.status, duration, "API");
2993
3633
  await sendWebResponse(res, bodyErrorResponse);
2994
3634
  return;
2995
3635
  }
2996
- await emitPluginError("api-handler", error, {
2997
- urlPath: urlPath2,
2998
- method: method2
2999
- });
3000
3636
  logger.error(`API route error: ${error}`);
3001
3637
  res.statusCode = 500;
3002
3638
  res.setHeader("Content-Type", "application/json");
3003
- res.end(JSON.stringify({ error: "Internal server error" }));
3639
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3004
3640
  return;
3005
3641
  }
3006
3642
  }
3007
- if (farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname2)) {
3643
+ if (farmDocsAPIHandler && isDocsAPIRequest) {
3008
3644
  try {
3009
- const url = `http://${req.headers.host || "localhost:3000"}${req.url}`;
3010
- const headers = new Headers();
3011
- for (const [key, value] of Object.entries(req.headers)) {
3012
- if (value) {
3013
- headers.set(key, Array.isArray(value) ? value.join(", ") : value);
3014
- }
3015
- }
3016
- let body;
3017
- if (req.method !== "GET" && req.method !== "HEAD") {
3018
- body = await readNodeRequestBody(req, currentServerConfig.bodySizeLimit);
3019
- }
3020
- const request = new Request(url, {
3021
- method: req.method,
3022
- headers,
3023
- body: toRequestBody(body),
3024
- signal: createFarmNodeRequestAbortSignal(req, res)
3025
- });
3645
+ const request = await createHandlerRequest();
3026
3646
  const apiLifecyclePayload = {
3027
3647
  pathname: pathname2,
3028
3648
  method: method2,
@@ -3040,19 +3660,14 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3040
3660
  }
3041
3661
  return pm ? await pm.runHookSerial("afterApiHandler", response, apiLifecyclePayload) : response;
3042
3662
  };
3043
- const docsResponse = pm ? await pm.runRuntimeRequest(request, invokeDocsAPIHandler, {
3044
- kind: "docs",
3045
- route: setFarmRouteLabel(
3046
- { pathname: pathname2, pattern: apiLifecyclePayload.routePath },
3047
- resolveFarmDocsRouteLabel(pathname2, {
3048
- path: farmConfig.docs?.entry || "/docs",
3049
- roots: farmConfig.docs?.roots?.map((root) => root.entry)
3050
- })
3051
- )
3052
- }) : await invokeDocsAPIHandler(request);
3663
+ const docsResponse = await runInRuntime(
3664
+ request,
3665
+ invokeDocsAPIHandler,
3666
+ docsRuntimeOptions()
3667
+ );
3053
3668
  if (docsResponse) {
3054
- const duration2 = Date.now() - startTime2;
3055
- logResponse(method2, urlPath2, docsResponse.status, duration2, "API");
3669
+ const duration = Date.now() - startTime2;
3670
+ logResponse(method2, urlPath2, docsResponse.status, duration, "API");
3056
3671
  await sendWebResponse(res, docsResponse);
3057
3672
  return;
3058
3673
  }
@@ -3062,38 +3677,56 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3062
3677
  await sendWebResponse(res, bodyErrorResponse);
3063
3678
  return;
3064
3679
  }
3065
- await emitPluginError("docs-api-handler", error, {
3066
- urlPath: urlPath2,
3067
- method: method2
3068
- });
3069
3680
  logger.error(`Docs API route error: ${error}`);
3070
3681
  res.statusCode = 500;
3071
3682
  res.setHeader("Content-Type", "application/json");
3072
- res.end(JSON.stringify({ error: "Internal server error" }));
3683
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3073
3684
  return;
3074
3685
  }
3075
3686
  }
3076
- const duration = Date.now() - startTime2;
3077
- logResponse(method2, urlPath2, 404, duration, "API");
3078
- res.statusCode = 404;
3079
- res.setHeader("Content-Type", "application/json");
3080
- res.end(JSON.stringify({ error: "API route not found", pathname: pathname2 }));
3687
+ const notFoundBody = JSON.stringify({ error: "API route not found", pathname: pathname2 });
3688
+ if (!runtimeSession2) {
3689
+ logResponse(method2, urlPath2, 404, Date.now() - startTime2, "API");
3690
+ res.statusCode = 404;
3691
+ res.setHeader("Content-Type", "application/json");
3692
+ res.end(notFoundBody);
3693
+ return;
3694
+ }
3695
+ try {
3696
+ const response = await pm.completeRuntimeRequest(
3697
+ runtimeSession2,
3698
+ () => new Response(notFoundBody, {
3699
+ status: 404,
3700
+ headers: { "Content-Type": "application/json" }
3701
+ })
3702
+ );
3703
+ logResponse(method2, urlPath2, response.status, Date.now() - startTime2, "API");
3704
+ await sendWebResponse(res, response);
3705
+ } catch (error) {
3706
+ logger.error(`API route error: ${error}`);
3707
+ res.statusCode = 500;
3708
+ res.setHeader("Content-Type", "application/json");
3709
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3710
+ }
3081
3711
  return;
3082
3712
  }
3083
3713
  if (req.url?.startsWith("/@") || req.url?.startsWith("/node_modules")) {
3084
3714
  return next();
3085
3715
  }
3086
- if (shouldBypassFarmRouterForDottedPath(
3716
+ if (!deferredDottedRequests.has(req) && shouldBypassFarmRouterForDottedPath(
3087
3717
  requestPathname,
3088
3718
  farmApp?.getRouteManager(),
3089
3719
  [server.config.publicDir, server.config.root],
3090
- farmAgentGeneratedPaths(farmConfig)
3720
+ farmAgentGeneratedPaths(farmConfig),
3721
+ requestMethod
3091
3722
  )) {
3723
+ if (!viteModuleRequest) deferredDottedRequests.set(req, requestUrl);
3092
3724
  return next();
3093
3725
  }
3094
3726
  if (req.url?.startsWith("/__farm/page-data")) {
3095
3727
  const urlObj = parsedRequestUrl;
3096
3728
  const targetPath = urlObj.searchParams.get("path") || "/";
3729
+ let renderedRequest;
3097
3730
  try {
3098
3731
  const request = createRequestFromNodeRequest(
3099
3732
  req,
@@ -3117,17 +3750,24 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3117
3750
  headers: request.headers,
3118
3751
  signal: request.signal
3119
3752
  });
3753
+ renderedRequest = targetRequest;
3120
3754
  let middlewareMap = /* @__PURE__ */ new Map();
3121
3755
  let middlewareContext = /* @__PURE__ */ new Map();
3122
3756
  if (middlewareManager?.hasMiddleware()) {
3123
3757
  const targetNodeRequest = createPageDataMiddlewareRequest(req, targetRequestUrl);
3758
+ const targetNodeResponse = createPageDataMiddlewareResponse(res);
3124
3759
  const handled = await runFarmMiddlewareWithNavigation(
3125
3760
  farmApp.getServerRenderer(),
3126
3761
  targetRequest,
3127
3762
  targetNodeRequest,
3128
- res,
3129
- () => middlewareManager.execute(targetNodeRequest, res)
3763
+ targetNodeResponse.response,
3764
+ () => middlewareManager.execute(targetNodeRequest, targetNodeResponse.response)
3130
3765
  );
3766
+ const middlewareRedirect = targetNodeResponse.redirect();
3767
+ if (middlewareRedirect) {
3768
+ await sendFarmPageDataRedirect(res, middlewareRedirect, farmConfig.deploymentId);
3769
+ return;
3770
+ }
3131
3771
  if (handled) return;
3132
3772
  middlewareMap = targetNodeRequest.__FARM_MIDDLEWARE_DATA__ ?? middlewareMap;
3133
3773
  middlewareContext = targetNodeRequest.__FARM_MIDDLEWARE_CONTEXT__ ?? middlewareContext;
@@ -3251,7 +3891,9 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3251
3891
  mergedMetadata = await mergeModuleViewport(mergedMetadata, routeModule, routeProps);
3252
3892
  mergedMetadata = addMetadataMarkdownAlternate(
3253
3893
  mergedMetadata,
3254
- getFarmMarkdownAlternatePath(farmApp.getConfig().md, targetRequestUrl.pathname)
3894
+ getFarmMarkdownAlternatePath(farmApp.getConfig().md, targetRequestUrl.pathname, {
3895
+ routePathname: (pathname2) => routeManager3.toRoutePathname(pathname2)
3896
+ })
3255
3897
  );
3256
3898
  const routeSlots = await Promise.all(
3257
3899
  slots.map(async (slot) => {
@@ -3410,6 +4052,11 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3410
4052
  });
3411
4053
  return;
3412
4054
  } catch (error) {
4055
+ const redirect = renderedRequest ? await farmApp.getServerRenderer().resolvePageDataRedirect(renderedRequest, error) : null;
4056
+ if (redirect && !res.headersSent) {
4057
+ await sendFarmPageDataRedirect(res, redirect, farmConfig.deploymentId);
4058
+ return;
4059
+ }
3413
4060
  const failure = resolveFarmPageDataFailure(error);
3414
4061
  if (failure.status >= 500) {
3415
4062
  await emitPluginError("page-data", error, {
@@ -3447,41 +4094,43 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3447
4094
  return routePathname === FARM_DEFAULT_MCP_PATH && farmApp.getServerRenderer().getDefaultMCPServer() ? FARM_DEFAULT_MCP_PATH : null;
3448
4095
  };
3449
4096
  let runtimeSession;
4097
+ let pathname = requestedPathname;
3450
4098
  if (pm && hasRuntimeRequestHooks) {
3451
4099
  try {
4100
+ const sessionOptions = {
4101
+ kind: "page",
4102
+ route: setFarmRouteLabel(
4103
+ {
4104
+ pathname: requestedPathname,
4105
+ pattern: requestedMatch?.route?.pattern || null,
4106
+ params: requestedMatch?.params || {}
4107
+ },
4108
+ requestedMatch?.route ? null : pageBuiltInRouteLabel(requestedPathname)
4109
+ )
4110
+ };
3452
4111
  runtimeSession = await pm.beginRuntimeRequest(
3453
- createRequestFromNodeRequest(req, new URL(fullUrl)),
3454
- {
3455
- kind: "page",
3456
- route: setFarmRouteLabel(
3457
- {
3458
- pathname: requestedPathname,
3459
- pattern: requestedMatch?.route?.pattern || null,
3460
- params: requestedMatch?.params || {}
3461
- },
3462
- requestedMatch?.route ? null : pageBuiltInRouteLabel(requestedPathname)
3463
- )
3464
- }
4112
+ createRequestFromNodeRequest(req, new URL(configRewriteSource ?? fullUrl)),
4113
+ sessionOptions
3465
4114
  );
3466
- pm.copyRequestContext(runtimeSession.request, req);
3467
- applyWebRequestToNodeRequest(runtimeSession.request, req);
3468
- if (runtimeSession.response) {
3469
- const response = await pm.endRuntimeRequest(
3470
- runtimeSession,
3471
- runtimeSession.response
3472
- );
4115
+ const routedRequest = runtimeSession.response ?? (configRewriteSource === void 0 ? runtimeSession.request : await pm.runRuntimeBeforeForRewrite(
4116
+ runtimeSession.request,
4117
+ createRequestFromNodeRequest(req, new URL(fullUrl)),
4118
+ sessionOptions
4119
+ ));
4120
+ if (routedRequest instanceof Response) {
4121
+ const response = await pm.endRuntimeRequest(runtimeSession, routedRequest);
3473
4122
  await sendWebResponse(res, response);
3474
4123
  return;
3475
4124
  }
4125
+ pm.copyRequestContext(routedRequest, req);
4126
+ applyWebRequestToNodeRequest(routedRequest, req);
4127
+ pathname = new URL(routedRequest.url).pathname;
3476
4128
  } catch (error) {
3477
- await emitPluginError("runtime-before", error, { pathname: requestedPathname });
3478
- res.statusCode = 500;
3479
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
3480
- res.end("Internal Server Error");
4129
+ if (runtimeSession) await pm.failRuntimeRequest(runtimeSession, error);
4130
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
3481
4131
  return;
3482
4132
  }
3483
4133
  }
3484
- const pathname = runtimeSession ? new URL(runtimeSession.request.url).pathname : requestedPathname;
3485
4134
  const routeMatch = pathname === requestedPathname ? requestedMatch : routeManager2.matchRoute(pathname);
3486
4135
  if (pm && hasBeforeRouteMatchHook) {
3487
4136
  await pm.runHookParallel("beforeRouteMatch", {
@@ -3521,8 +4170,10 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3521
4170
  pathname,
3522
4171
  startTime,
3523
4172
  logResponse,
3524
- emitError: (error) => emitPluginError("response-end", error, { pathname })
4173
+ emitError: (error) => emitPluginError("response-end", error, { pathname }),
4174
+ jsonError: runtimeHookErrorAnswersJSON
3525
4175
  }) : void 0;
4176
+ let middlewareFailed = false;
3526
4177
  try {
3527
4178
  if (middlewareManager?.hasMiddleware()) {
3528
4179
  const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));
@@ -3532,7 +4183,10 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3532
4183
  req,
3533
4184
  res,
3534
4185
  () => middlewareManager.execute(req, res)
3535
- );
4186
+ ).catch((error) => {
4187
+ middlewareFailed = true;
4188
+ throw error;
4189
+ });
3536
4190
  if (handled) {
3537
4191
  if (!responseInterceptor?.isEnded()) {
3538
4192
  const duration = Date.now() - startTime;
@@ -3542,42 +4196,14 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3542
4196
  }
3543
4197
  }
3544
4198
  if (pm && hasBeforeRequestHook) {
3545
- const urlBeforeRequestHooks = req.url;
3546
- const currentPathname = new URL(
3547
- req.url || "/",
3548
- `http://${req.headers.host || "localhost:3000"}`
3549
- ).pathname;
3550
- const hasLocalPageRoute = Boolean(routeManager2.matchRoute(currentPathname)?.route);
3551
4199
  await pm.runHookParallelFiltered(
3552
4200
  "beforeRequest",
3553
- (plugin) => !hasLocalPageRoute || plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,
4201
+ (plugin2) => !isFarmConfigRoutePlugin(plugin2),
3554
4202
  req,
3555
4203
  res
3556
4204
  );
3557
- if (runtimeSession && req.url !== urlBeforeRequestHooks && req.url?.startsWith("/") && !res.writableEnded) {
3558
- const destinationUrl = new URL(req.url, fullUrl);
3559
- const destinationMatch = routeManager2.matchRoute(destinationUrl.pathname);
3560
- const guarded = await pm.runRuntimeBeforeForRewrite(
3561
- runtimeSession.request,
3562
- createRequestFromNodeRequest(req, destinationUrl),
3563
- {
3564
- kind: "page",
3565
- route: {
3566
- pathname: destinationUrl.pathname,
3567
- pattern: destinationMatch?.route?.pattern || null,
3568
- params: destinationMatch?.params || {}
3569
- }
3570
- }
3571
- );
3572
- if (guarded instanceof Response) {
3573
- await sendWebResponse(res, guarded);
3574
- } else {
3575
- pm.copyRequestContext(guarded, req);
3576
- applyWebRequestToNodeRequest(guarded, req);
3577
- }
3578
- }
3579
4205
  }
3580
- if (res.writableEnded || responseInterceptor?.isEnded() || await proxyFarmExternalRewrite(req, res, currentServerConfig.bodySizeLimit)) {
4206
+ if (res.writableEnded || responseInterceptor?.isEnded()) {
3581
4207
  if (!responseInterceptor?.isEnded()) {
3582
4208
  const duration = Date.now() - startTime;
3583
4209
  logResponse(method, urlPath, res.statusCode || 200, duration, "PAGE");
@@ -3598,13 +4224,53 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3598
4224
  if (pm && runtimeSession) {
3599
4225
  await pm.failRuntimeRequest(runtimeSession, error);
3600
4226
  }
3601
- await emitPluginError("render-page", error, { pathname });
4227
+ if (!(middlewareFailed && runtimeSession)) {
4228
+ await emitPluginError("render-page", error, { pathname });
4229
+ }
4230
+ if (rendererDisabled && !res.headersSent) {
4231
+ sendFarmDevErrorJSON(res);
4232
+ return;
4233
+ }
4234
+ if (!res.headersSent) {
4235
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
4236
+ res.setHeader("Cache-Control", "private, no-store");
4237
+ }
3602
4238
  next(error);
3603
4239
  }
3604
4240
  })
3605
4241
  );
4242
+ const farmRequestMiddleware = farmMiddlewares.stack.at(-1)?.handle;
4243
+ if (farmOwnsDevCors && viteServer.config.server.cors === false) {
4244
+ farmMiddlewares.use(createFarmDevViteCorsMiddleware());
4245
+ }
4246
+ return () => {
4247
+ farmPostMiddlewares.use((req, res, next) => {
4248
+ if (res.headersSent || res.writableEnded) return next();
4249
+ const deferredUrl = deferredDottedRequests.get(req);
4250
+ if (deferredUrl !== void 0) {
4251
+ req.url = deferredUrl;
4252
+ return farmRequestMiddleware(req, res, next);
4253
+ }
4254
+ if (!rendererDisabled) return next();
4255
+ const requested = req.originalUrl ?? req.url ?? "/";
4256
+ const pathname = parseFarmRequestTarget(requested, "http://localhost").pathname;
4257
+ res.statusCode = 404;
4258
+ res.setHeader("Content-Type", "application/json");
4259
+ res.end(JSON.stringify({ error: "Not found", pathname }));
4260
+ });
4261
+ };
3606
4262
  },
3607
4263
  async resolveId(id, importer, resolveOptions) {
4264
+ if (id.startsWith("@farm.js/core/internal/") && importer) {
4265
+ const root = farmApp?.getConfig().root || server?.config.root || options.root;
4266
+ const relative4 = root ? path6.relative(root, importer.split("?", 1)[0]) : "";
4267
+ if (root && (relative4.startsWith("..") || path6.isAbsolute(relative4))) {
4268
+ return this.resolve(id, path6.join(root, "package.json"), {
4269
+ ...resolveOptions,
4270
+ skipSelf: true
4271
+ });
4272
+ }
4273
+ }
3608
4274
  if (typeof fontImports.resolveId === "function") {
3609
4275
  const fontId = await fontImports.resolveId.call(this, id, importer, resolveOptions);
3610
4276
  if (fontId) return fontId;
@@ -3627,6 +4293,9 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3627
4293
  }
3628
4294
  },
3629
4295
  async load(id, loadOptions) {
4296
+ if (pendingClientSetup && !loadOptions?.ssr && !farmSetupContext.getStore()) {
4297
+ await pendingClientSetup;
4298
+ }
3630
4299
  if (isFarmServerFnBoundaryId(id) && islandsServerFns()) {
3631
4300
  const file = id.split("?", 1)[0];
3632
4301
  this.addWatchFile(file);
@@ -3788,6 +4457,9 @@ export const manifest = getManifest();
3788
4457
  }
3789
4458
  },
3790
4459
  async transform(code, id, transformOptions) {
4460
+ if (pendingClientSetup && !transformOptions?.ssr && !farmSetupContext.getStore()) {
4461
+ await pendingClientSetup;
4462
+ }
3791
4463
  const actionConfig = farmApp?.getConfig() ?? options;
3792
4464
  let rewrotePackageImports = false;
3793
4465
  if (resolveFarmServerComponentsMode(actionConfig.experimental?.serverComponents) === "islands" && (!id.includes("/node_modules/") || transformOptions?.ssr === true && farmReactServerFiles.has(id.split("?", 1)[0])) && !id.startsWith("\0") && /\.[cm]?[jt]sx?(?:$|\?)/.test(id) && !hasUseClientDirective(code)) {
@@ -3805,13 +4477,22 @@ export const manifest = getManifest();
3805
4477
  const reactServer = !serverModule ? null : rewriteFarmReactServerImports({
3806
4478
  code,
3807
4479
  file,
3808
- reference: (specifier, exportName) => ensureFarmPackageClientReference(projectRoot, specifier, exportName),
4480
+ reference: (specifier, exportName) => ensureFarmPackageClientReference(projectRoot, specifier, exportName, file),
3809
4481
  onServerFile: (serverFile) => farmReactServerFiles.add(serverFile)
3810
4482
  });
3811
4483
  if (reactServer !== null) {
3812
4484
  code = reactServer;
3813
4485
  rewrotePackageImports = true;
3814
4486
  }
4487
+ const internal = farmReactServerFiles.has(file) ? rewriteFarmReactServerClientModuleImports({
4488
+ code,
4489
+ file,
4490
+ reference: (clientFile) => ensureFarmInternalClientReference(projectRoot, clientFile)
4491
+ }) : null;
4492
+ if (internal !== null) {
4493
+ code = internal;
4494
+ rewrotePackageImports = true;
4495
+ }
3815
4496
  }
3816
4497
  const referenced = rewriteFarmPackageClientImports({
3817
4498
  code,
@@ -3934,6 +4615,7 @@ export const manifest = getManifest();
3934
4615
  islandStrategy: explicitStrategy ?? "load",
3935
4616
  parse: (source) => this.parse(source),
3936
4617
  slots: islandsMode,
4618
+ browser: transformOptions?.ssr !== true,
3937
4619
  inferredInteraction: inference?.strategy === "interaction"
3938
4620
  });
3939
4621
  if (!transformedBoundary) {
@@ -3999,6 +4681,7 @@ if (import.meta.hot) {
3999
4681
  if (typeof fontImports.generateBundle === "function") {
4000
4682
  await fontImports.generateBundle.call(this, options2, bundle, false);
4001
4683
  }
4684
+ if (rendererDisabled) return;
4002
4685
  const clientManifest = generateClientManifest(bundle);
4003
4686
  this.emitFile({
4004
4687
  type: "asset",
@@ -4105,6 +4788,7 @@ if (import.meta.hot) {
4105
4788
  invalidateFarmClientOnlyScan();
4106
4789
  },
4107
4790
  async handleHotUpdate(ctx) {
4791
+ if (pendingClientSetup && !farmSetupContext.getStore()) await pendingClientSetup;
4108
4792
  const { file, server: server2, modules } = ctx;
4109
4793
  if (initialPluginManager) {
4110
4794
  try {
@@ -4169,6 +4853,7 @@ if (import.meta.hot) {
4169
4853
  const planRouteManager = farmApp?.getRouteManager();
4170
4854
  const isHydrationPlanSource = currentSrcRoot !== null && normalizedFile.startsWith(`${currentSrcRoot}/`) && /\.[cm]?[jt]sx?$/.test(normalizedFile);
4171
4855
  const tracksAsyncOwnerIslands = isReactRenderer(currentFarmConfig?.renderer) && planRouteManager !== void 0;
4856
+ let clientPlanCurrent = false;
4172
4857
  if (isHydrationPlanSource && (isolatedHydrationMode === "enabled" || isolatedHydrationMode === "analyze" || tracksAsyncOwnerIslands)) {
4173
4858
  const routeManager = planRouteManager;
4174
4859
  if (routeManager) {
@@ -4203,6 +4888,7 @@ if (import.meta.hot) {
4203
4888
  server2.ws.send({ type: "full-reload", path: "*" });
4204
4889
  return [];
4205
4890
  }
4891
+ clientPlanCurrent = true;
4206
4892
  } catch (error) {
4207
4893
  logger.warn(
4208
4894
  `[Farm.js] Could not refresh the client hydration plan after ${file}: ${error instanceof Error ? error.message : String(error)}`
@@ -4228,7 +4914,7 @@ if (import.meta.hot) {
4228
4914
  }
4229
4915
  return [];
4230
4916
  }
4231
- farmApp?.getRouteManager().invalidateClientManifest();
4917
+ if (!clientPlanCurrent) farmApp?.getRouteManager().invalidateClientManifest();
4232
4918
  const manifestModule = server2.moduleGraph.getModuleById("/@farm/manifest");
4233
4919
  if (manifestModule) {
4234
4920
  server2.moduleGraph.invalidateModule(manifestModule);
@@ -4249,6 +4935,40 @@ if (import.meta.hot) {
4249
4935
  return modules;
4250
4936
  }
4251
4937
  };
4938
+ if (!deferredSetup) return plugin;
4939
+ const setUpDevServer = plugin.configureServer;
4940
+ let deferred = false;
4941
+ plugin.configureServer = function(viteServer) {
4942
+ if (deferred) {
4943
+ deferredGates = void 0;
4944
+ return setUpDevServer.call(this, viteServer);
4945
+ }
4946
+ deferred = true;
4947
+ const ready = () => deferredSetup.ready;
4948
+ deferredGates = {
4949
+ pre: createFarmDeferredMiddleware(ready),
4950
+ post: createFarmDeferredMiddleware(ready)
4951
+ };
4952
+ const setup = farmSetupContext.run(true, () => setUpDevServer.call(this, viteServer)).then((registerPostMiddleware) => {
4953
+ registerPostMiddleware();
4954
+ });
4955
+ viteServer.middlewares.use(deferredGates.pre.handle);
4956
+ deferredSetup.setup = setup;
4957
+ deferredSetup.ready = setup;
4958
+ pendingClientSetup = setup.then(
4959
+ () => {
4960
+ pendingClientSetup = null;
4961
+ },
4962
+ () => {
4963
+ pendingClientSetup = null;
4964
+ }
4965
+ );
4966
+ const post = deferredGates.post.handle;
4967
+ return () => {
4968
+ viteServer.middlewares.use(post);
4969
+ };
4970
+ };
4971
+ return plugin;
4252
4972
  }
4253
4973
  function runFarmMiddlewareWithNavigation(renderer, middlewareRequest, req, res, execute) {
4254
4974
  return renderer.runWithRequestContext(middlewareRequest, async () => {
@@ -4267,6 +4987,75 @@ function createPageDataMiddlewareRequest(req, target) {
4267
4987
  targetNodeRequest.method = "GET";
4268
4988
  return targetNodeRequest;
4269
4989
  }
4990
+ function createPageDataMiddlewareResponse(res) {
4991
+ let redirect = null;
4992
+ let passthrough = false;
4993
+ const captures = (status, location) => {
4994
+ if (redirect) return true;
4995
+ if (passthrough) return false;
4996
+ redirect = getFarmPageDataRedirectFromResponse(
4997
+ status,
4998
+ Array.isArray(location) ? location[0] : typeof location === "string" ? location : null
4999
+ );
5000
+ passthrough = !redirect;
5001
+ return !passthrough;
5002
+ };
5003
+ const response = new Proxy(res, {
5004
+ get(target, property) {
5005
+ if (property === "writeHead") {
5006
+ return (status, ...args) => {
5007
+ const headers = args.find((arg) => arg && typeof arg === "object");
5008
+ if (captures(status, readWriteHeadLocation(headers) ?? target.getHeader("location"))) {
5009
+ return response;
5010
+ }
5011
+ return target.writeHead(
5012
+ status,
5013
+ ...args
5014
+ );
5015
+ };
5016
+ }
5017
+ if (property === "write" || property === "end") {
5018
+ return (...args) => {
5019
+ if (captures(target.statusCode, target.getHeader("location"))) {
5020
+ const callback = args.find((arg) => typeof arg === "function");
5021
+ callback?.();
5022
+ return property === "write" ? true : response;
5023
+ }
5024
+ return target[property](...args);
5025
+ };
5026
+ }
5027
+ if (redirect && (property === "headersSent" || property === "writableEnded" || property === "finished")) {
5028
+ return true;
5029
+ }
5030
+ const value = Reflect.get(target, property, target);
5031
+ return typeof value === "function" ? value.bind(target) : value;
5032
+ },
5033
+ set(target, property, value) {
5034
+ return Reflect.set(target, property, value, target);
5035
+ }
5036
+ });
5037
+ return { response, redirect: () => redirect };
5038
+ }
5039
+ function readWriteHeadLocation(headers) {
5040
+ if (Array.isArray(headers)) {
5041
+ for (let index = 0; index + 1 < headers.length; index += 2) {
5042
+ if (String(headers[index]).toLowerCase() === "location") return headers[index + 1];
5043
+ }
5044
+ return void 0;
5045
+ }
5046
+ if (!headers || typeof headers !== "object") return void 0;
5047
+ for (const [name, value] of Object.entries(headers)) {
5048
+ if (name.toLowerCase() === "location") return value;
5049
+ }
5050
+ return void 0;
5051
+ }
5052
+ async function sendFarmPageDataRedirect(res, redirect, deploymentId) {
5053
+ for (const name of ["location", "content-length", "content-type"]) res.removeHeader(name);
5054
+ await sendWebResponse(
5055
+ res,
5056
+ withFarmDeploymentResponse(createFarmPageDataRedirectResponse(redirect), deploymentId)
5057
+ );
5058
+ }
4270
5059
  function resolveDevelopmentRoot(farmRoot, viteRoot) {
4271
5060
  if (!farmRoot) return viteRoot;
4272
5061
  if (path6.resolve(farmRoot) === path6.resolve(viteRoot)) return farmRoot;
@@ -5808,14 +6597,11 @@ function readActiveLayoutPatterns() {
5808
6597
  .filter(Boolean);
5809
6598
  }
5810
6599
 
6600
+ ${FARM_NAVIGATION_SCRIPT_SOURCE}
6601
+
5811
6602
  function activateFragmentScripts(root) {
5812
6603
  for (const script of Array.from(root.querySelectorAll?.('script') || [])) {
5813
- const freshScript = document.createElement('script');
5814
- for (const attribute of Array.from(script.attributes)) {
5815
- freshScript.setAttribute(attribute.name, attribute.value);
5816
- }
5817
- freshScript.textContent = script.textContent || '';
5818
- script.replaceWith(freshScript);
6604
+ script.replaceWith(createFarmNavigationScript(script));
5819
6605
  }
5820
6606
  }
5821
6607
 
@@ -5825,7 +6611,52 @@ function parseNavigationFragment(html) {
5825
6611
  return template.content;
5826
6612
  }
5827
6613
 
5828
- function replaceNavigationBoundary(
6614
+ // Suspense content streams, so a fresh response holds its fallback where the live DOM holds the
6615
+ // result. Compare without it.
6616
+ function removeSuspenseContent(root) {
6617
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
6618
+ const comments = [];
6619
+ while (walker.nextNode()) comments.push(walker.currentNode);
6620
+ let depth = 0;
6621
+ let start = null;
6622
+ for (const comment of comments) {
6623
+ if (comment.data === "$" || comment.data === "$?" || comment.data === "$!") {
6624
+ if (depth++ === 0) start = comment;
6625
+ } else if (comment.data === "/$" && depth > 0 && --depth === 0) {
6626
+ const range = document.createRange();
6627
+ range.setStartAfter(start);
6628
+ range.setEndBefore(comment);
6629
+ range.deleteContents();
6630
+ start.data = "$";
6631
+ }
6632
+ }
6633
+ }
6634
+
6635
+ // A layout's own server output, without what it wraps and without its islands, whose live DOM
6636
+ // always differs from fresh HTML.
6637
+ function getLayoutShell(root, patterns, index, find) {
6638
+ const shell = find(root, patterns[index])?.cloneNode(true);
6639
+ if (!shell) return null;
6640
+ const inner = index + 1 < patterns.length
6641
+ ? find(shell, patterns[index + 1])
6642
+ : shell.querySelector('#__farm_page__');
6643
+ inner?.replaceChildren();
6644
+ removeSuspenseContent(shell);
6645
+ // Each island's props stay, without its id, so new props count as a change.
6646
+ shell.querySelectorAll('script').forEach((script) => {
6647
+ if (script.type !== 'f/props') return script.remove();
6648
+ Array.from(script.attributes).forEach((attribute) => {
6649
+ if (attribute.name !== 'type') script.removeAttribute(attribute.name);
6650
+ });
6651
+ });
6652
+ shell.querySelectorAll('f-island').forEach((island) => {
6653
+ island.replaceChildren();
6654
+ Array.from(island.attributes).forEach((attribute) => island.removeAttribute(attribute.name));
6655
+ });
6656
+ return shell.innerHTML;
6657
+ }
6658
+
6659
+ ${islandValues ? FARM_REFRESH_FIELDS_SOURCE : ""}function replaceNavigationBoundary(
5829
6660
  container,
5830
6661
  fragment,
5831
6662
  currentPatterns,
@@ -5833,11 +6664,17 @@ function replaceNavigationBoundary(
5833
6664
  refresh = false,
5834
6665
  find = findLayoutBoundary,
5835
6666
  ) {
6667
+ // A refresh keeps the islands still on the page: the ones in streamed Suspense content too.
6668
+ if (refresh) revealFarmStreamedContent(fragment);
5836
6669
  let sharedCount = 0;
5837
6670
  while (
5838
6671
  sharedCount < currentPatterns.length &&
5839
6672
  sharedCount < nextPatterns.length &&
5840
- currentPatterns[sharedCount] === nextPatterns[sharedCount]
6673
+ currentPatterns[sharedCount] === nextPatterns[sharedCount] &&
6674
+ // A refresh renders every layout again: start at the first one whose output changed.
6675
+ (!refresh ||
6676
+ getLayoutShell(container, currentPatterns, sharedCount, find) ===
6677
+ getLayoutShell(fragment, nextPatterns, sharedCount, find))
5841
6678
  ) {
5842
6679
  sharedCount++;
5843
6680
  }
@@ -5858,11 +6695,13 @@ function replaceNavigationBoundary(
5858
6695
  activateFragmentScripts(container);
5859
6696
  return container;
5860
6697
  }
5861
-
6698
+ ${islandValues ? `
6699
+ // A refresh renders the same layouts again: their fields keep what was typed, and the focus.
6700
+ const fields = refresh ? captureFarmServerFields(currentTarget) : null;` : ""}
5862
6701
  ${isolatedHydrationEnabled ? `${islandValues ? `// A refresh keeps the islands still on the page, with their state and new props.
5863
6702
  if (refresh) farmIsolatedHydrationRuntime.carryOver(currentTarget, nextTarget);
5864
6703
  ` : ""}disposeFarmIsolatedClientBoundaries(currentTarget);` : ""}
5865
- currentTarget.replaceWith(nextTarget);
6704
+ currentTarget.replaceWith(nextTarget);${islandValues ? "\n if (fields) restoreFarmServerFields(fields, nextTarget);" : ""}
5866
6705
  activateFragmentScripts(nextTarget);
5867
6706
  if (fragmentTreeRoot && fragmentTreeRoot !== nextTarget) fragmentTreeRoot.remove();
5868
6707
 
@@ -5872,7 +6711,17 @@ function replaceNavigationBoundary(
5872
6711
  const support = document.createElement('div');
5873
6712
  support.hidden = true;
5874
6713
  support.dataset.farmFragmentSupport = 'true';
5875
- support.append(fragment);
6714
+ while (fragment.firstChild) {
6715
+ const node = fragment.firstChild;
6716
+ // React's staged Suspense content stays in the root, where a later flush of a streamed
6717
+ // navigation reveals it; React removes it then.
6718
+ if (node.nodeType === 1 && node.matches('div[hidden][id^="S:"]')) {
6719
+ container.appendChild(node);
6720
+ activateFragmentScripts(node);
6721
+ } else {
6722
+ support.appendChild(node);
6723
+ }
6724
+ }
5876
6725
  document.body.appendChild(support);
5877
6726
  activateFragmentScripts(support);
5878
6727
  setTimeout(() => support.remove(), 0);
@@ -5938,7 +6787,8 @@ function farmDocumentNavigationRoute(pathname) {
5938
6787
  }
5939
6788
 
5940
6789
  async function fetchFarmNavigationDocument(path, context) {
5941
- farmNavigationStreamGeneration++;
6790
+ // A prefetch reads the page whole for the router's cache, and leaves a page that streams alone.
6791
+ if (!context.prefetch) farmNavigationStreamGeneration++;
5942
6792
  const url = new URL(path, window.location.href);
5943
6793
  const match = farmDocumentNavigationRoute(url.pathname);
5944
6794
  const container = document.getElementById('root');
@@ -5956,9 +6806,12 @@ async function fetchFarmNavigationDocument(path, context) {
5956
6806
  redirect: 'manual',
5957
6807
  headers: createFarmDeploymentRequestHeaders(deploymentId, {
5958
6808
  Accept: 'text/html',
5959
- 'F-Stream': 'flush',
6809
+ // A refresh arrives whole, like a transition: the islands it keeps are all in it.
6810
+ ...(context.prefetch || context.refresh ? {} : { 'F-Stream': 'flush' }),
5960
6811
  ...getFarmIslandValueHeaders(),
5961
- ...(identities.length ? { 'F-Layouts': JSON.stringify(identities) } : {}),
6812
+ // A prefetch names its layouts even when it keeps none: that marks it as a navigation,
6813
+ // which the server answers without loading.tsx.
6814
+ ...(identities.length || context.prefetch ? { 'F-Layouts': JSON.stringify(identities) } : {}),
5962
6815
  }),
5963
6816
  });
5964
6817
  if (isFarmDeploymentMismatchResponse(response, deploymentId)) {
@@ -5966,7 +6819,9 @@ async function fetchFarmNavigationDocument(path, context) {
5966
6819
  window.dispatchEvent(new CustomEvent('farm:deployment-mismatch', { detail: error }));
5967
6820
  throw error;
5968
6821
  }
5969
- // A redirect, an error or anything but HTML: the router loads the document instead.
6822
+ // A manual redirect hides its target, so page data answers this navigation and follows it.
6823
+ if (response.type === 'opaqueredirect') return null;
6824
+ // An error or anything but HTML: the router loads the document instead.
5970
6825
  if (
5971
6826
  !response.ok ||
5972
6827
  !response.body ||
@@ -5979,10 +6834,11 @@ async function fetchFarmNavigationDocument(path, context) {
5979
6834
  return { stream, doc, nextRoot: doc.getElementById('root') };
5980
6835
  };
5981
6836
  let result = await request(true);
5982
- if (result.nextRoot && !fitsFarmSegment(container, result.nextRoot)) {
6837
+ if (result && result.nextRoot && !fitsFarmSegment(container, result.nextRoot)) {
5983
6838
  result.stream.cancel?.();
5984
6839
  result = await request(false);
5985
6840
  }
6841
+ if (!result) return null;
5986
6842
  if (!result.nextRoot) {
5987
6843
  result.stream.cancel?.();
5988
6844
  throw new Error('The page has no #root');
@@ -6342,7 +7198,13 @@ function farmIslandsOnlyDocument() {
6342
7198
  // Islands mode hydrates the document, as production does, so islx also watches the islands
6343
7199
  // that stream in after this runs. Not cancelled by a navigation: an island it removes is
6344
7200
  // disposed with its DOM, and one in a layout it keeps still waits for its trigger.
7201
+ const hydrationSession = await farmClientRuntime.beginHydration({
7202
+ container: rootContainer || document.body,
7203
+ mode: 'hydrate',
7204
+ });
7205
+ // Each island reports and recovers its own failure, so this resolves once they are live.
6345
7206
  await hydrateFarmIsolatedClientBoundaries(${islandValues ? "document" : "rootContainer"});
7207
+ await farmClientRuntime.completeHydration(hydrationSession);
6346
7208
  // The rest of the document is static server HTML with nothing to hydrate, so
6347
7209
  // stop holding its clicks and submits once the load-strategy islands are live.
6348
7210
  // Deferred islands capture their own interactions, and held targets outside an
@@ -6565,7 +7427,7 @@ async function defineConfig(config = {}) {
6565
7427
  const tailwindVitePlugin = await loadTailwindVitePlugin();
6566
7428
  const appRoot = path6.resolve(config.root || process.cwd());
6567
7429
  if (config.extends?.length) {
6568
- const { config: layeredConfig } = await import("./layers-T55SA47E.mjs").then(
7430
+ const { config: layeredConfig } = await import("./layers-XQ7VFMWO.mjs").then(
6569
7431
  ({ resolveFarmLayers }) => resolveFarmLayers(config, {
6570
7432
  root: appRoot,
6571
7433
  mode: process.env.NODE_ENV === "production" ? "production" : "development"