@farm.js/core 0.1.65 → 0.1.67

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 (439) 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-BFu9xHAi.d.ts} +1 -1
  4. package/dist/{agent-mcp.d-CO_ABmNK.d.mts → agent-mcp.d-DWyWkTSy.d.mts} +1 -1
  5. package/dist/agent-runtime.cjs +6 -5
  6. package/dist/agent-runtime.d.mts +6 -6
  7. package/dist/agent-runtime.d.ts +6 -6
  8. package/dist/agent-runtime.mjs +5 -4
  9. package/dist/analyzer-KVZGVY5Q.cjs +16 -0
  10. package/dist/{analyzer-PE33SK5W.mjs → analyzer-TTIIXXMQ.mjs} +3 -3
  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 +59 -0
  21. package/dist/api/node.d.ts +59 -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 +10 -9
  25. package/dist/api/route-manager.d.ts +10 -9
  26. package/dist/api/route-manager.mjs +10 -10
  27. package/dist/api/runtime.cjs +11 -7
  28. package/dist/api/runtime.d.mts +7 -7
  29. package/dist/api/runtime.d.ts +7 -7
  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 +11 -10
  35. package/dist/api.d.ts +11 -10
  36. package/dist/api.mjs +16 -12
  37. package/dist/{app-manifest.d-BpKxiU_E.d.mts → app-manifest.d-CRmjN5j9.d.mts} +1 -1
  38. package/dist/{app-manifest.d-DDmNkYQQ.d.ts → app-manifest.d-CwfhGrVR.d.ts} +1 -1
  39. package/dist/app-markdown.cjs +5 -5
  40. package/dist/app-markdown.d.mts +7 -7
  41. package/dist/app-markdown.d.ts +7 -7
  42. package/dist/app-markdown.mjs +4 -4
  43. package/dist/{app.d-x68Cwr0_.d.ts → app.d-BX9LVTiP.d.ts} +50 -9
  44. package/dist/{app.d-kuoVWhWM.d.mts → app.d-uBBUxwyV.d.mts} +50 -9
  45. package/dist/{chunk-V56632LA.cjs → chunk-22IWL4YD.cjs} +19 -5
  46. package/dist/{chunk-CZF4XIRZ.cjs → chunk-23PVOIPT.cjs} +3 -3
  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-RVGSVQWT.mjs → chunk-3T5TLFCQ.mjs} +10 -5
  51. package/dist/{chunk-XBSKPLHF.cjs → chunk-3T7ALZJF.cjs} +2 -2
  52. package/dist/{chunk-JCEFKP5M.mjs → chunk-423SSBYQ.mjs} +6 -0
  53. package/dist/{chunk-7QVRWGBL.cjs → chunk-4DRINDGN.cjs} +319 -138
  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-JGAE5XPL.cjs → chunk-4JX3M4C6.cjs} +2 -1
  57. package/dist/{chunk-CJNAUEVC.mjs → chunk-4QENVMG7.mjs} +1 -1
  58. package/dist/{chunk-IMK32ERL.cjs → chunk-556H7JCE.cjs} +65 -48
  59. package/dist/{chunk-OLIGNTWU.cjs → chunk-5NFQ6AZI.cjs} +7 -7
  60. package/dist/{chunk-6HRAK7I5.mjs → chunk-5OFNUETM.mjs} +8 -2
  61. package/dist/{chunk-TZVUF5JJ.mjs → chunk-5TA63JD3.mjs} +4 -4
  62. package/dist/{chunk-RD623KW4.cjs → chunk-67MZTLTF.cjs} +21 -3
  63. package/dist/chunk-6I4BFRE7.cjs +51 -0
  64. package/dist/{chunk-OSFIUSYK.cjs → chunk-6R53ZWX2.cjs} +7 -7
  65. package/dist/{chunk-MGKW5XZE.cjs → chunk-6SQZXRJ2.cjs} +7 -7
  66. package/dist/{chunk-WNXVWXG3.cjs → chunk-6V5YWI4W.cjs} +2 -2
  67. package/dist/{chunk-BM2LH2JM.mjs → chunk-6YBYX4K4.mjs} +13 -12
  68. package/dist/{chunk-X3XUZWRB.mjs → chunk-724MGMIL.mjs} +17 -3
  69. package/dist/{chunk-K5EW7GUU.mjs → chunk-7BIW7VCW.mjs} +13 -5
  70. package/dist/{chunk-HPP2II4Z.mjs → chunk-7PJARAQQ.mjs} +1 -1
  71. package/dist/{chunk-LEJDW34D.cjs → chunk-7PPLTD3P.cjs} +3 -3
  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-ZEXE4TGY.mjs → chunk-AQDLVHNF.mjs} +230 -110
  76. package/dist/{chunk-NKRZLQUK.mjs → chunk-AQIO3RNL.mjs} +1 -1
  77. package/dist/chunk-AQIRXBBY.cjs +26 -0
  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-V727H3RI.cjs → chunk-CCAUIBIS.cjs} +6 -0
  84. package/dist/{chunk-YN6BHOYY.cjs → chunk-CL52PD6D.cjs} +10 -3
  85. package/dist/{chunk-ZX2JHEWW.mjs → chunk-CO3YMZFD.mjs} +20 -9
  86. package/dist/{chunk-XURDCXNH.cjs → chunk-CSLHNBPS.cjs} +6 -6
  87. package/dist/{chunk-CNNBFGL5.cjs → chunk-DB2HSHQA.cjs} +14 -14
  88. package/dist/{chunk-XQSYOVCW.cjs → chunk-DBYNZIIQ.cjs} +13 -5
  89. package/dist/{chunk-32RPJAAS.cjs → chunk-DCXSIEFE.cjs} +40 -41
  90. package/dist/{chunk-D4MRNBVF.cjs → chunk-DGOFR7D5.cjs} +2 -2
  91. package/dist/{chunk-QTD6EMN2.mjs → chunk-DQ2DI3Y7.mjs} +11 -4
  92. package/dist/chunk-DXZ57EPE.mjs +375 -0
  93. package/dist/{chunk-SA7MLSP4.mjs → chunk-E3HDJCWF.mjs} +3 -3
  94. package/dist/{chunk-EFZGB7JC.cjs → chunk-E5UN4OWX.cjs} +1 -0
  95. package/dist/{chunk-HKNYNSOK.mjs → chunk-E6CD45JK.mjs} +30 -31
  96. package/dist/{chunk-752XUZIM.cjs → chunk-EGIY4A7V.cjs} +6 -6
  97. package/dist/chunk-EIVGPQN5.mjs +51 -0
  98. package/dist/{chunk-KPAJWD3N.mjs → chunk-EYPSKXO4.mjs} +1 -1
  99. package/dist/{chunk-E552H232.cjs → chunk-F43OG25P.cjs} +1 -1
  100. package/dist/{chunk-UAQD67HM.mjs → chunk-F7JKVHU2.mjs} +1 -1
  101. package/dist/{chunk-QISW423S.cjs → chunk-FPBOAG6N.cjs} +2 -2
  102. package/dist/{chunk-2C5L5RPM.cjs → chunk-FT6KJHS3.cjs} +71 -38
  103. package/dist/{chunk-ES2LD2YD.mjs → chunk-GCRT6GJG.mjs} +18 -0
  104. package/dist/{chunk-5OJVKXFV.cjs → chunk-GDM3ZD2O.cjs} +10 -8
  105. package/dist/{chunk-EMDGXYUD.mjs → chunk-GJ7QVFAG.mjs} +16 -7
  106. package/dist/{chunk-TGSEVBPO.mjs → chunk-GJEC5S4V.mjs} +11 -0
  107. package/dist/{chunk-ZAUOOGER.mjs → chunk-GTV2ABO7.mjs} +218 -37
  108. package/dist/{chunk-72JSHQQQ.mjs → chunk-H37MDCPR.mjs} +1 -1
  109. package/dist/{chunk-HNAISJFD.cjs → chunk-HDPT6OYE.cjs} +9 -3
  110. package/dist/{chunk-25T5VXOE.mjs → chunk-HFHJJXSV.mjs} +106 -19
  111. package/dist/{chunk-ZNH6NR3H.cjs → chunk-HJZZSBVK.cjs} +2 -2
  112. package/dist/{chunk-A3G5IY2W.cjs → chunk-HM7AGSKU.cjs} +1 -1
  113. package/dist/{chunk-GL7N5UHF.cjs → chunk-HNVAZGQD.cjs} +20 -9
  114. package/dist/{chunk-GRBJ7VKH.mjs → chunk-HP2DQGQH.mjs} +1 -1
  115. package/dist/{chunk-E2TSYUHV.mjs → chunk-HRPTMX5C.mjs} +4 -4
  116. package/dist/{chunk-K7OZAVOI.mjs → chunk-IFR74W6S.mjs} +46 -13
  117. package/dist/{chunk-5A77OEIG.cjs → chunk-IHTDLCDJ.cjs} +5 -5
  118. package/dist/{chunk-VQJHT2ND.mjs → chunk-IRA2CZAY.mjs} +2 -2
  119. package/dist/{chunk-OYZXVBZP.cjs → chunk-IUKBPBM7.cjs} +2 -1
  120. package/dist/chunk-J6TZRYCO.cjs +22 -0
  121. package/dist/{chunk-WYAXRIYP.cjs → chunk-J7JHVCWA.cjs} +8 -8
  122. package/dist/chunk-JSOCDYER.cjs +375 -0
  123. package/dist/{chunk-YUW7F6SK.mjs → chunk-JVM3DKZE.mjs} +3 -3
  124. package/dist/{chunk-UPYIFH2H.cjs → chunk-JWLRBDDC.cjs} +2 -2
  125. package/dist/{chunk-BQWBHWEW.mjs → chunk-JWSI5WO4.mjs} +1 -1
  126. package/dist/{chunk-OLGQZRW6.mjs → chunk-JZBU7V4D.mjs} +37 -17
  127. package/dist/{chunk-ONG4RDW3.mjs → chunk-JZGL2PIH.mjs} +13 -3
  128. package/dist/chunk-K63OWRY2.mjs +22 -0
  129. package/dist/{chunk-TUPKMMXT.mjs → chunk-K6HIIWUB.mjs} +1 -1
  130. package/dist/{chunk-MESQF2JC.mjs → chunk-K6SXMVXO.mjs} +2 -2
  131. package/dist/{chunk-L2JG337G.cjs → chunk-K6VFYFOY.cjs} +33 -31
  132. package/dist/{chunk-3CCAICF7.cjs → chunk-KCY52OUQ.cjs} +4 -4
  133. package/dist/{chunk-EZ34EHQP.mjs → chunk-KI3MU7B5.mjs} +1 -1
  134. package/dist/{chunk-GHNW564E.mjs → chunk-KSZK34HU.mjs} +30 -10
  135. package/dist/{chunk-RFKTJTWZ.mjs → chunk-KWFNUODD.mjs} +2 -1
  136. package/dist/{chunk-ECKQFEX2.mjs → chunk-LENKRGBV.mjs} +8 -6
  137. package/dist/{chunk-C7DCMGC4.cjs → chunk-LPIZMU7D.cjs} +12 -12
  138. package/dist/{chunk-HEPJIKKQ.cjs → chunk-MCSRMEQV.cjs} +2 -2
  139. package/dist/{chunk-DQF3QLOH.mjs → chunk-ME7RVELR.mjs} +3 -2
  140. package/dist/{chunk-3KJPIO5D.cjs → chunk-N5DQMOAG.cjs} +589 -678
  141. package/dist/{chunk-O4F3JUST.mjs → chunk-NDDRTFN4.mjs} +4 -0
  142. package/dist/{chunk-CBOEJ5Z4.cjs → chunk-OB3IFUK6.cjs} +133 -46
  143. package/dist/{chunk-R62SF5R4.mjs → chunk-OB45EAQL.mjs} +6 -1
  144. package/dist/{chunk-SYXPWJ7N.cjs → chunk-OFBLGH6V.cjs} +17 -18
  145. package/dist/{chunk-VQ4NWOWO.mjs → chunk-OGVTUGMU.mjs} +5 -13
  146. package/dist/{chunk-3UZVPO72.mjs → chunk-OIOPQ25L.mjs} +6 -7
  147. package/dist/{chunk-2XGBJSDV.cjs → chunk-OO7DYIJD.cjs} +73 -24
  148. package/dist/{chunk-IP2KHSGF.mjs → chunk-P2NBQ5JI.mjs} +57 -4
  149. package/dist/{chunk-ZQQK4U66.cjs → chunk-PDFFYZAT.cjs} +72 -19
  150. package/dist/{chunk-GSVJ3IIF.cjs → chunk-PHCJJJZV.cjs} +2 -2
  151. package/dist/{chunk-EVMXPJCB.mjs → chunk-PKMUQ7LM.mjs} +2 -1
  152. package/dist/{chunk-YD4J37RN.cjs → chunk-PL6RTBDE.cjs} +30 -19
  153. package/dist/{chunk-OAJOQU5J.mjs → chunk-PLJKJJ2H.mjs} +82 -63
  154. package/dist/{chunk-WMTBBQHY.cjs → chunk-PPX7UOFY.cjs} +271 -151
  155. package/dist/{chunk-6XQSPIN6.cjs → chunk-PWKAX5MS.cjs} +13 -3
  156. package/dist/{chunk-7XGWBPQQ.cjs → chunk-Q37INCXG.cjs} +13 -8
  157. package/dist/{chunk-T4M52BA5.cjs → chunk-Q5UX55YA.cjs} +1457 -612
  158. package/dist/{chunk-53ZCZ46B.cjs → chunk-QGQP6QKO.cjs} +4 -3
  159. package/dist/{chunk-TZOGZKI7.cjs → chunk-QITSS4TD.cjs} +1381 -626
  160. package/dist/{chunk-4ZJ5C7UJ.cjs → chunk-QIXEU2WV.cjs} +19 -10
  161. package/dist/{chunk-HCGWDRZO.mjs → chunk-QJVW76JG.mjs} +17 -6
  162. package/dist/{chunk-FJWN7RV4.cjs → chunk-QO43L7Z4.cjs} +38 -8
  163. package/dist/{chunk-ZIHWAN55.cjs → chunk-RE5E2G5S.cjs} +1 -1
  164. package/dist/chunk-RWR7SMD7.cjs +50 -0
  165. package/dist/{chunk-7PTISZSQ.cjs → chunk-S7MWSFFP.cjs} +4 -0
  166. package/dist/chunk-SD6JGJOM.mjs +50 -0
  167. package/dist/{chunk-7H4SVNC4.cjs → chunk-SPP3EZTJ.cjs} +46 -26
  168. package/dist/{chunk-E4RDMG3K.mjs → chunk-TEG6HJVF.mjs} +4 -4
  169. package/dist/{chunk-WAY6LOQH.mjs → chunk-TEJ67GD2.mjs} +1 -1
  170. package/dist/{chunk-ZNXTU4YH.mjs → chunk-TM2E623I.mjs} +1 -0
  171. package/dist/{chunk-IFTGERT3.mjs → chunk-TTXIITYA.mjs} +49 -0
  172. package/dist/{chunk-ZFWYCVKS.mjs → chunk-TY5KCYDE.mjs} +22 -4
  173. package/dist/{chunk-W2ZXMMHA.mjs → chunk-UHE5JUKB.mjs} +1 -1
  174. package/dist/{chunk-6X5NKNBE.mjs → chunk-UHNSY2PQ.mjs} +1304 -459
  175. package/dist/{chunk-UJ3R2AH2.cjs → chunk-UPOYKX4S.cjs} +5 -5
  176. package/dist/{chunk-2DLGV2ZG.mjs → chunk-UTUS6JUH.mjs} +1 -21
  177. package/dist/{chunk-Q75QPLBA.mjs → chunk-V5MQMQ2P.mjs} +1 -1
  178. package/dist/{chunk-TRIDJQ6A.cjs → chunk-V5RTHYJB.cjs} +30 -10
  179. package/dist/{chunk-QHRCR44V.mjs → chunk-VK54PDQ6.mjs} +25 -5
  180. package/dist/{chunk-LQNW3ABP.cjs → chunk-VX2HZGC7.cjs} +14 -14
  181. package/dist/{chunk-2L54YV25.mjs → chunk-WDD5CTZW.mjs} +49 -32
  182. package/dist/{chunk-7GYCZRTH.mjs → chunk-WGHY3OL5.mjs} +355 -444
  183. package/dist/{chunk-A2MN5PQJ.mjs → chunk-WMLSZAKN.mjs} +9 -9
  184. package/dist/{chunk-3EEET2Q5.cjs → chunk-WUTFJOV7.cjs} +32 -12
  185. package/dist/chunk-WVQNXXNE.cjs +28 -0
  186. package/dist/{chunk-Y5TOT5F6.cjs → chunk-X3MHKLCO.cjs} +5 -5
  187. package/dist/{chunk-Z7P2BTZ3.cjs → chunk-XGTFLG73.cjs} +30 -12
  188. package/dist/{chunk-VHHLKIDZ.mjs → chunk-XNZWMXCF.mjs} +1090 -335
  189. package/dist/{chunk-FIR62CR3.mjs → chunk-XUES6OET.mjs} +1 -1
  190. package/dist/{chunk-XCXHQBMM.mjs → chunk-Y2LU4LE5.mjs} +1 -1
  191. package/dist/{chunk-5J45H65F.mjs → chunk-Y5LEPEVH.mjs} +1 -1
  192. package/dist/{chunk-BT4SEFLC.cjs → chunk-YAEN3L2F.cjs} +3 -2
  193. package/dist/chunk-YFTGIHNC.mjs +26 -0
  194. package/dist/{chunk-KL7SHLQB.mjs → chunk-YGJ5P3TJ.mjs} +31 -1
  195. package/dist/{chunk-UYRI6U3P.mjs → chunk-YQYTQJZN.mjs} +3 -2
  196. package/dist/{chunk-X4K7TYN6.cjs → chunk-YVTS3S3F.cjs} +24 -23
  197. package/dist/{chunk-72KABRWN.mjs → chunk-ZJGFAW5U.mjs} +5 -3
  198. package/dist/{chunk-TNBJ4LZG.mjs → chunk-ZPKJPM7K.mjs} +4 -4
  199. package/dist/client/lifecycle.cjs +2 -2
  200. package/dist/client/lifecycle.d.mts +1 -1
  201. package/dist/client/lifecycle.d.ts +1 -1
  202. package/dist/client/lifecycle.mjs +1 -1
  203. package/dist/{client-component.d-D74pqdea.d.mts → client-component.d-CDRvRmbU.d.mts} +2 -2
  204. package/dist/{client-component.d-D8VcypQA.d.ts → client-component.d-DWRKyAp5.d.ts} +2 -2
  205. package/dist/client-plugins.cjs +2 -2
  206. package/dist/{client-plugins.d-D4-6hNx7.d.mts → client-plugins.d-BNILjfX3.d.mts} +94 -140
  207. package/dist/{client-plugins.d-CXElzotB.d.ts → client-plugins.d-CrKZiNSN.d.ts} +94 -140
  208. package/dist/client-plugins.d.mts +6 -6
  209. package/dist/client-plugins.d.ts +6 -6
  210. package/dist/client-plugins.mjs +1 -1
  211. package/dist/client.cjs +11 -9
  212. package/dist/client.d.mts +13 -13
  213. package/dist/client.d.ts +13 -13
  214. package/dist/client.mjs +10 -8
  215. package/dist/{config.d-qt-mE8O5.d.mts → config.d-BKIhJtmr.d.mts} +7 -2
  216. package/dist/{config.d-qt-mE8O5.d.ts → config.d-BKIhJtmr.d.ts} +7 -2
  217. package/dist/config.d.mts +6 -6
  218. package/dist/config.d.ts +6 -6
  219. package/dist/cron.cjs +2 -2
  220. package/dist/cron.mjs +1 -1
  221. package/dist/deferred.cjs +2 -2
  222. package/dist/deferred.mjs +1 -1
  223. package/dist/deployment.cjs +2 -2
  224. package/dist/deployment.mjs +1 -1
  225. package/dist/desktop.d.mts +7 -7
  226. package/dist/desktop.d.ts +7 -7
  227. package/dist/{devtools-SGYOG36E.cjs → devtools-RZVT4JVN.cjs} +36 -32
  228. package/dist/{devtools-PUVZB3F2.mjs → devtools-UFQYT3VA.mjs} +31 -27
  229. package/dist/docs.cjs +26 -25
  230. package/dist/docs.d.mts +20 -8
  231. package/dist/docs.d.ts +20 -8
  232. package/dist/docs.mjs +25 -24
  233. package/dist/env-types.cjs +3 -3
  234. package/dist/env-types.mjs +2 -2
  235. package/dist/environment/vite.cjs +5 -5
  236. package/dist/environment/vite.mjs +4 -4
  237. package/dist/headers.cjs +3 -3
  238. package/dist/headers.mjs +2 -2
  239. package/dist/image/server.d.mts +1 -1
  240. package/dist/image/server.d.ts +1 -1
  241. package/dist/image/sharp.d.mts +1 -1
  242. package/dist/image/sharp.d.ts +1 -1
  243. package/dist/{image-config.d-CeDgNyX4.d.mts → image-config.d-ByhQ0TT7.d.mts} +3 -1
  244. package/dist/{image-config.d-CeDgNyX4.d.ts → image-config.d-ByhQ0TT7.d.ts} +3 -1
  245. package/dist/image.cjs +6 -6
  246. package/dist/image.d.mts +1 -1
  247. package/dist/image.d.ts +1 -1
  248. package/dist/image.mjs +1 -1
  249. package/dist/index.cjs +143 -128
  250. package/dist/{index.d-SSgYDv4D.d.mts → index.d-Bdm6866n.d.mts} +1 -1
  251. package/dist/{index.d-A_x10zGS.d.ts → index.d-Dey5T14f.d.ts} +1 -1
  252. package/dist/index.d.mts +31 -82
  253. package/dist/index.d.ts +31 -82
  254. package/dist/index.mjs +214 -199
  255. package/dist/{integration-orm-52GPGTHO.cjs → integrations/orm.cjs} +5 -5
  256. package/dist/integrations/orm.d.mts +33 -0
  257. package/dist/integrations/orm.d.ts +33 -0
  258. package/dist/{integration-orm-CO23MSFE.mjs → integrations/orm.mjs} +5 -5
  259. package/dist/integrations.cjs +6 -5
  260. package/dist/integrations.d.mts +6 -6
  261. package/dist/integrations.d.ts +6 -6
  262. package/dist/integrations.mjs +5 -4
  263. package/dist/internal/app-markdown-runtime.cjs +4 -4
  264. package/dist/internal/app-markdown-runtime.d.mts +17 -8
  265. package/dist/internal/app-markdown-runtime.d.ts +17 -8
  266. package/dist/internal/app-markdown-runtime.mjs +3 -3
  267. package/dist/internal/build-runtime.cjs +70 -68
  268. package/dist/internal/build-runtime.d.mts +8 -8
  269. package/dist/internal/build-runtime.d.ts +8 -8
  270. package/dist/internal/build-runtime.mjs +69 -67
  271. package/dist/internal/cli-runtime.cjs +45 -44
  272. package/dist/internal/cli-runtime.mjs +44 -43
  273. package/dist/internal/client-error-overlay.cjs +6 -6
  274. package/dist/internal/client-error-overlay.mjs +2 -2
  275. package/dist/internal/client-runtime.cjs +60 -6
  276. package/dist/internal/client-runtime.d.mts +40 -11
  277. package/dist/internal/client-runtime.d.ts +40 -11
  278. package/dist/internal/client-runtime.mjs +58 -4
  279. package/dist/internal/compression-runtime.d.mts +6 -6
  280. package/dist/internal/compression-runtime.d.ts +6 -6
  281. package/dist/internal/config-runtime.cjs +25 -24
  282. package/dist/internal/config-runtime.d.mts +9 -9
  283. package/dist/internal/config-runtime.d.ts +9 -9
  284. package/dist/internal/config-runtime.mjs +24 -23
  285. package/dist/internal/docs-precompiled-runtime.cjs +16 -5
  286. package/dist/internal/docs-precompiled-runtime.d.mts +7 -0
  287. package/dist/internal/docs-precompiled-runtime.d.ts +7 -0
  288. package/dist/internal/docs-precompiled-runtime.mjs +15 -4
  289. package/dist/internal/infra-analytics-runtime.cjs +11 -11
  290. package/dist/internal/infra-analytics-runtime.mjs +9 -9
  291. package/dist/internal/islands-runtime.cjs +33 -4
  292. package/dist/internal/islands-runtime.d.mts +1 -1
  293. package/dist/internal/islands-runtime.d.ts +1 -1
  294. package/dist/internal/islands-runtime.mjs +31 -2
  295. package/dist/internal/native-server-fns.cjs +6 -6
  296. package/dist/internal/native-server-fns.mjs +5 -5
  297. package/dist/internal/product-telemetry-runtime.cjs +3 -3
  298. package/dist/internal/product-telemetry-runtime.mjs +2 -2
  299. package/dist/internal/production-runtime.cjs +54 -40
  300. package/dist/internal/production-runtime.d.mts +23 -15
  301. package/dist/internal/production-runtime.d.ts +23 -15
  302. package/dist/internal/production-runtime.mjs +69 -55
  303. package/dist/internal/react-cache.cjs +3 -3
  304. package/dist/internal/react-cache.mjs +1 -1
  305. package/dist/{lifecycle.d-C2aLBOwu.d.ts → lifecycle.d-keQs5Swc.d.mts} +7 -1
  306. package/dist/{lifecycle.d-C2aLBOwu.d.mts → lifecycle.d-keQs5Swc.d.ts} +7 -1
  307. package/dist/{manager-H5ZM3HAM.mjs → manager-JIA66YJ2.mjs} +4 -3
  308. package/dist/manager-JOHU6BQI.cjs +15 -0
  309. package/dist/markdown.cjs +7 -3
  310. package/dist/markdown.d.mts +6 -6
  311. package/dist/markdown.d.ts +6 -6
  312. package/dist/markdown.mjs +6 -2
  313. package/dist/middleware.cjs +10 -10
  314. package/dist/middleware.d.mts +8 -8
  315. package/dist/middleware.d.ts +8 -8
  316. package/dist/middleware.mjs +9 -9
  317. package/dist/mobile.d.mts +4 -4
  318. package/dist/mobile.d.ts +4 -4
  319. package/dist/mount.d-BP0nLYQO.d.mts +38 -0
  320. package/dist/mount.d-CkiPky_F.d.ts +38 -0
  321. package/dist/{native-server-fn-handler-GLRHAYWV.mjs → native-server-fn-handler-EP5AFJYE.mjs} +5 -5
  322. package/dist/{native-server-fn-handler-J5MYRXN6.cjs → native-server-fn-handler-QRTXGZA4.cjs} +6 -6
  323. package/dist/{native-tree-HE2FLS72.cjs → native-tree-W2SSJB3Y.cjs} +5 -5
  324. package/dist/{native-tree-YF2DSPKM.mjs → native-tree-Y5YQANW7.mjs} +4 -4
  325. package/dist/{navigation-delegate.d-DQVYKoaZ.d.mts → navigation-delegate.d-CdBP-hkZ.d.mts} +1 -1
  326. package/dist/{navigation-delegate.d-GghbHJuK.d.ts → navigation-delegate.d-DchcGzAQ.d.ts} +1 -1
  327. package/dist/navigation.cjs +8 -7
  328. package/dist/navigation.d.mts +9 -9
  329. package/dist/navigation.d.ts +9 -9
  330. package/dist/navigation.mjs +7 -6
  331. package/dist/{nitro-DD4QCA66.mjs → nitro-55YOZWRA.mjs} +11 -11
  332. package/dist/{nitro-VRDX2H4M.cjs → nitro-EEX2J3KB.cjs} +13 -13
  333. package/dist/{plugin-53SY5YBS.mjs → plugin-SAS22JL7.mjs} +4 -3
  334. package/dist/{plugin-HZIBL3DW.cjs → plugin-WIU4GDD4.cjs} +5 -4
  335. package/dist/plugin.cjs +61 -59
  336. package/dist/plugin.d.mts +8 -8
  337. package/dist/plugin.d.ts +8 -8
  338. package/dist/plugin.mjs +60 -58
  339. package/dist/{port-UFUZL6RI.mjs → port-CLL4BC4O.mjs} +1 -1
  340. package/dist/{port-VTLHPZOI.cjs → port-HASZTQGY.cjs} +9 -9
  341. package/dist/{production-runtime.d-Bzns3NW9.d.ts → production-runtime.d-Dou_Htas.d.ts} +1 -1
  342. package/dist/{production-runtime.d-DiFa5vHW.d.mts → production-runtime.d-VwsBzIee.d.mts} +1 -1
  343. package/dist/query/client.cjs +9 -7
  344. package/dist/query/client.mjs +5 -3
  345. package/dist/{render-plan.d-CL_Ikfg_.d.ts → render-plan.d-D8UakAIk.d.ts} +1 -1
  346. package/dist/{render-plan.d-CcF0MeCf.d.mts → render-plan.d-LKymStDJ.d.mts} +1 -1
  347. package/dist/renderer/none/server.cjs +35 -0
  348. package/dist/renderer/none/server.d.mts +21 -0
  349. package/dist/renderer/none/server.d.ts +21 -0
  350. package/dist/renderer/none/server.mjs +35 -0
  351. package/dist/renderer/react/server.cjs +2 -2
  352. package/dist/renderer/react/server.mjs +3 -3
  353. package/dist/renderer-client.cjs +8 -6
  354. package/dist/renderer-client.d.mts +9 -9
  355. package/dist/renderer-client.d.ts +9 -9
  356. package/dist/renderer-client.mjs +5 -3
  357. package/dist/renderer.cjs +6 -2
  358. package/dist/renderer.d.mts +20 -2
  359. package/dist/renderer.d.ts +20 -2
  360. package/dist/renderer.mjs +5 -1
  361. package/dist/request.cjs +2 -2
  362. package/dist/{request.d-B1RnTLri.d.ts → request.d-B928QjWy.d.ts} +1 -1
  363. package/dist/{request.d-DarDOCk9.d.mts → request.d-KG-4d2eG.d.mts} +1 -1
  364. package/dist/request.d.mts +7 -7
  365. package/dist/request.d.ts +7 -7
  366. package/dist/request.mjs +1 -1
  367. package/dist/{route-rendering.d-BTUYCIj4.d.ts → route-rendering.d-DoEe_w9t.d.ts} +1 -1
  368. package/dist/{route-rendering.d-D_2Ual0-.d.mts → route-rendering.d-NIHQeb4m.d.mts} +1 -1
  369. package/dist/{route.d-BaVH3V0w.d.mts → route.d-DrXkpvcg.d.mts} +1 -1
  370. package/dist/{route.d-DBTEqifW.d.ts → route.d-hs-_cyHn.d.ts} +1 -1
  371. package/dist/{router.d-Cuv1jntg.d.mts → router.d-B8PkJSGp.d.mts} +1 -1
  372. package/dist/{router.d-CMANF6da.d.ts → router.d-DYnRHQwz.d.ts} +1 -1
  373. package/dist/routes.cjs +3 -3
  374. package/dist/{routes.d-c2HKfrfL.d.mts → routes.d-DgZ_jgGG.d.mts} +1 -1
  375. package/dist/{routes.d-B6yFe6jm.d.ts → routes.d-uUBZyWoK.d.ts} +1 -1
  376. package/dist/routes.d.mts +6 -6
  377. package/dist/routes.d.ts +6 -6
  378. package/dist/routes.mjs +2 -2
  379. package/dist/{rsc-pipeline-T3PWURLJ.mjs → rsc-pipeline-4OJ5ZQNZ.mjs} +26 -25
  380. package/dist/{rsc-pipeline-V4ANLRAA.cjs → rsc-pipeline-7K5H2RPH.cjs} +27 -26
  381. package/dist/{runtime-LRIQ3XH7.mjs → runtime-U7O3HZOZ.mjs} +62 -36
  382. package/dist/{runtime-5AROV2C3.cjs → runtime-X52Q7JFR.cjs} +72 -46
  383. package/dist/{runtime.d-wvh4ngU0.d.mts → runtime.d-BxQIzwfy.d.mts} +11 -3
  384. package/dist/{runtime.d-C3RQUj6_.d.ts → runtime.d-DP7mEkEF.d.ts} +11 -3
  385. package/dist/{schema-dev-notice-JMXEQWIQ.mjs → schema-dev-notice-C2JINRZI.mjs} +3 -2
  386. package/dist/{schema-dev-notice-PLBFDTOF.cjs → schema-dev-notice-X7GG7QVB.cjs} +5 -4
  387. package/dist/schema.cjs +6 -2
  388. package/dist/schema.d-Dny9pnrm.d.mts +298 -0
  389. package/dist/schema.d-Dny9pnrm.d.ts +298 -0
  390. package/dist/schema.d.mts +1 -115
  391. package/dist/schema.d.ts +1 -115
  392. package/dist/schema.mjs +5 -1
  393. package/dist/server-fn-client.d.mts +2 -2
  394. package/dist/server-fn-client.d.ts +2 -2
  395. package/dist/server-fn.cjs +5 -5
  396. package/dist/server-fn.mjs +4 -4
  397. package/dist/server-plugins.cjs +7 -7
  398. package/dist/server-plugins.d.mts +16 -10
  399. package/dist/server-plugins.d.ts +16 -10
  400. package/dist/server-plugins.mjs +8 -8
  401. package/dist/server-query.cjs +6 -6
  402. package/dist/server-query.mjs +5 -5
  403. package/dist/server.cjs +160 -120
  404. package/dist/server.d.mts +20 -14
  405. package/dist/server.d.ts +20 -14
  406. package/dist/server.mjs +138 -98
  407. package/dist/{spa-router.d-WU_qS5gJ.d.mts → spa-router.d-BgHPVMhz.d.mts} +15 -5
  408. package/dist/{spa-router.d-m8H_Kl_B.d.ts → spa-router.d-DsFDHTsv.d.ts} +15 -5
  409. package/dist/testing.cjs +17 -17
  410. package/dist/testing.d.mts +6 -6
  411. package/dist/testing.d.ts +6 -6
  412. package/dist/testing.mjs +13 -13
  413. package/dist/theme/server.cjs +3 -3
  414. package/dist/theme/server.mjs +2 -2
  415. package/dist/{utils.d-W9IiEqmW.d.mts → utils.d-BKyKDBR1.d.mts} +1 -1
  416. package/dist/{utils.d-C9dQD5Zg.d.ts → utils.d-zxAVcf_V.d.ts} +1 -1
  417. package/dist/version.cjs +2 -2
  418. package/dist/version.mjs +1 -1
  419. package/dist/vite.cjs +63 -61
  420. package/dist/vite.d.mts +32 -12
  421. package/dist/vite.d.ts +32 -12
  422. package/dist/vite.mjs +62 -60
  423. package/dist/workflows.cjs +4 -4
  424. package/dist/workflows.mjs +3 -3
  425. package/package.json +31 -1
  426. package/dist/analyzer-GHWK46LX.cjs +0 -16
  427. package/dist/chunk-5YPBFMBN.cjs +0 -19
  428. package/dist/chunk-OM7WILES.mjs +0 -100
  429. package/dist/chunk-Q5B4LNON.mjs +0 -19
  430. package/dist/chunk-QPJ4MZTO.mjs +0 -60
  431. package/dist/chunk-R53QDV6T.cjs +0 -100
  432. package/dist/chunk-UYTAP4FQ.cjs +0 -60
  433. package/dist/manager-2LUKNX2N.cjs +0 -14
  434. /package/dist/{chunk-QGOZLGVP.mjs → chunk-I6FIAWNT.mjs} +0 -0
  435. /package/dist/{chunk-XPIPMWY3.cjs → chunk-K5NI5YQR.cjs} +0 -0
  436. /package/dist/{chunk-NWUHS6GV.cjs → chunk-QEJWNXRI.cjs} +0 -0
  437. /package/dist/{chunk-FSXSQQTV.mjs → chunk-TXE4SAMV.mjs} +0 -0
  438. /package/dist/{chunk-ZXK2EYQW.cjs → chunk-UUQNJDGH.cjs} +0 -0
  439. /package/dist/{chunk-46P5KNTE.mjs → chunk-VZBAW44S.mjs} +0 -0
@@ -18,7 +18,6 @@ import {
18
18
  createFarmThemeCssPlugin,
19
19
  farmFontImportsPlugin,
20
20
  generateClientCachePersistenceCode,
21
- generateFarmClientPluginEntryCode,
22
21
  generateFarmIntegrationProviderClientCode,
23
22
  inferFarmIslandStrategy,
24
23
  isFarmDocsClientConfigModule,
@@ -28,20 +27,26 @@ import {
28
27
  resolveFarmClientCacheAdapterEntry,
29
28
  resolveFarmImageProviderForRuntime,
30
29
  resolveFarmRouteRootStrategy
31
- } from "./chunk-7GYCZRTH.mjs";
30
+ } from "./chunk-WGHY3OL5.mjs";
32
31
  import {
32
+ generateFarmClientPluginEntryCode,
33
33
  loadTailwindVitePlugin
34
- } from "./chunk-OM7WILES.mjs";
34
+ } from "./chunk-DXZ57EPE.mjs";
35
35
  import {
36
36
  FARM_NODE_RESPONSE_END_PENDING
37
- } from "./chunk-GHNW564E.mjs";
37
+ } from "./chunk-KSZK34HU.mjs";
38
+ import {
39
+ generateFarmTypeArtifacts,
40
+ resolveRouteRenderingConfig
41
+ } from "./chunk-6YBYX4K4.mjs";
38
42
  import {
39
43
  resolveFarmPlatform
40
44
  } from "./chunk-SMUW7UST.mjs";
41
45
  import {
42
- generateFarmTypeArtifacts,
43
- resolveRouteRenderingConfig
44
- } from "./chunk-BM2LH2JM.mjs";
46
+ createFarmServerFnBoundaryModule,
47
+ isFarmServerFnBoundaryId,
48
+ transformFarmServerFns
49
+ } from "./chunk-GNZIAJGB.mjs";
45
50
  import {
46
51
  createFarmRouteRenderPlan,
47
52
  farmPathGuardCoversEndpoint,
@@ -52,7 +57,7 @@ import {
52
57
  parseFarmLayoutChainHeader,
53
58
  renderFarmLocaleAlternateLinks,
54
59
  stripRouteGroups
55
- } from "./chunk-TNBJ4LZG.mjs";
60
+ } from "./chunk-ZPKJPM7K.mjs";
56
61
  import {
57
62
  FARM_NATIVE_TREE_CONTENT_TYPE
58
63
  } from "./chunk-LLZSYFOM.mjs";
@@ -70,25 +75,21 @@ import {
70
75
  resolveFarmMCPRouteLabel,
71
76
  resolveFarmMarkdownRouteLabel,
72
77
  setFarmRouteLabel
73
- } from "./chunk-E2TSYUHV.mjs";
78
+ } from "./chunk-HRPTMX5C.mjs";
74
79
  import {
75
80
  FARM_DEFAULT_MCP_PATH
76
- } from "./chunk-MESQF2JC.mjs";
81
+ } from "./chunk-K6SXMVXO.mjs";
77
82
  import {
78
83
  isFarmPreviewDeploymentEnvironment
79
- } from "./chunk-Q75QPLBA.mjs";
80
- import {
81
- createFarmServerFnBoundaryModule,
82
- isFarmServerFnBoundaryId,
83
- transformFarmServerFns
84
- } from "./chunk-GNZIAJGB.mjs";
84
+ } from "./chunk-V5MQMQ2P.mjs";
85
85
  import {
86
86
  resolveFarmLayoutFonts
87
87
  } from "./chunk-HZOMT5DY.mjs";
88
88
  import {
89
89
  FARM_CLIENT_REFERENCE_DIRECTORY,
90
90
  FARM_CLIENT_REFERENCE_PRAGMA,
91
- collectFarmServerBundledPackages,
91
+ collectFarmServerBundledPackageInfo,
92
+ ensureFarmInternalClientReference,
92
93
  ensureFarmPackageClientReference,
93
94
  farmBrowserBuiltinsOptimizerPlugin,
94
95
  farmEnvironmentFunctionsPlugin,
@@ -107,10 +108,12 @@ import {
107
108
  resolveFarmBrowserBuiltin,
108
109
  resolveFarmIsolatedClientHydrationMode,
109
110
  resolveModuleSourcePath,
111
+ resolvePackageClientBoundaryCacheFile,
110
112
  rewriteFarmPackageClientImports,
113
+ rewriteFarmReactServerClientModuleImports,
111
114
  rewriteFarmReactServerImports,
112
115
  stripUseClientDirective
113
- } from "./chunk-ZAUOOGER.mjs";
116
+ } from "./chunk-GTV2ABO7.mjs";
114
117
  import {
115
118
  generateFarmDocsAdapterClientRuntime,
116
119
  getFarmDocsAdapterConfigModule
@@ -122,6 +125,9 @@ import {
122
125
  import {
123
126
  generateFarmDevIndicatorsClientRuntime
124
127
  } from "./chunk-TPA2PV5J.mjs";
128
+ import {
129
+ resolveRouteRuleCorsPreflightHeaders
130
+ } from "./chunk-724MGMIL.mjs";
125
131
  import {
126
132
  FARM_DEVTOOLS_LAUNCH_PARAM,
127
133
  FARM_DEVTOOLS_PATH,
@@ -131,13 +137,13 @@ import {
131
137
  FARM_PREVIEW_ROBOTS_TAG,
132
138
  resolveFarmAgentCrawlers,
133
139
  resolveFarmAgentSitemap
134
- } from "./chunk-VQ4NWOWO.mjs";
140
+ } from "./chunk-OGVTUGMU.mjs";
135
141
  import {
136
142
  resolveFarmLlmsTxtConfig
137
- } from "./chunk-KL7SHLQB.mjs";
143
+ } from "./chunk-YGJ5P3TJ.mjs";
138
144
  import {
139
145
  resolveFarmServerComponentsMode
140
- } from "./chunk-CJNAUEVC.mjs";
146
+ } from "./chunk-4QENVMG7.mjs";
141
147
  import {
142
148
  getFarmAppDirectories,
143
149
  getFarmLayerAliases,
@@ -146,16 +152,17 @@ import {
146
152
  import {
147
153
  REACT_RENDERER,
148
154
  getFarmRendererCapabilities,
155
+ isFarmRendererDisabled,
149
156
  isReactRenderer,
150
157
  loadFarmRendererVitePlugins,
151
158
  resolveFarmComponentExtensions,
152
159
  resolveFarmRenderer,
153
160
  resolveFarmRendererAppSetup
154
- } from "./chunk-ES2LD2YD.mjs";
161
+ } from "./chunk-GCRT6GJG.mjs";
155
162
  import {
156
163
  getPublicFarmImageConfig,
157
164
  resolveFarmImageConfig
158
- } from "./chunk-2NGZFOKG.mjs";
165
+ } from "./chunk-AOIUYHPH.mjs";
159
166
  import {
160
167
  createBundledEnv
161
168
  } from "./chunk-N33DLJBC.mjs";
@@ -163,30 +170,29 @@ import {
163
170
  createFarmMarkdownSourceResponse,
164
171
  isFarmMarkdownPageFile,
165
172
  normalizeFarmMarkdownRoutePath
166
- } from "./chunk-RVGSVQWT.mjs";
173
+ } from "./chunk-3T5TLFCQ.mjs";
167
174
  import {
168
175
  FARM_MARKDOWN_CONTENT_TYPE,
169
176
  createFarmMarkdownErrorBody,
170
177
  createMarkdownMirrorResponse,
171
178
  farmRequestWantsMarkdown,
172
179
  getFarmMarkdownAlternatePath,
173
- getFarmMarkdownMirrorPath,
174
180
  resolveMarkdownMirrorTarget
175
- } from "./chunk-K7OZAVOI.mjs";
176
- import {
177
- resolveFarmRouteContext,
178
- withFarmRouteContext
179
- } from "./chunk-BMQAPZXD.mjs";
181
+ } from "./chunk-IFR74W6S.mjs";
180
182
  import {
181
183
  dispatchIntegrationRequest,
182
184
  getFarmIntegrationPluginOwner,
183
185
  getIntegrationDocumentNavigationMatchers,
184
186
  getIntegrationProviders,
185
187
  matchIntegrationRoute
186
- } from "./chunk-TGULJSHD.mjs";
188
+ } from "./chunk-AJNBTOVQ.mjs";
189
+ import {
190
+ resolveFarmRouteContext,
191
+ withFarmRouteContext
192
+ } from "./chunk-BMQAPZXD.mjs";
187
193
  import {
188
194
  MiddlewareManager
189
- } from "./chunk-A2MN5PQJ.mjs";
195
+ } from "./chunk-WMLSZAKN.mjs";
190
196
  import {
191
197
  _runWithMiddlewareContext,
192
198
  _runWithMiddlewareData
@@ -202,7 +208,7 @@ import {
202
208
  } from "./chunk-IYEY3JWJ.mjs";
203
209
  import {
204
210
  APIRouteManager
205
- } from "./chunk-3UZVPO72.mjs";
211
+ } from "./chunk-OIOPQ25L.mjs";
206
212
  import {
207
213
  getFarmI18nClientSnapshot
208
214
  } from "./chunk-CV6MFQ4Y.mjs";
@@ -211,8 +217,10 @@ import {
211
217
  isOptionalPeerInstalled
212
218
  } from "./chunk-NR63PD3P.mjs";
213
219
  import {
220
+ FARM_INTERNAL_SERVER_ERROR_BODY,
221
+ createFarmInternalServerErrorResponse,
214
222
  isFarmAPIPathname
215
- } from "./chunk-ZFWYCVKS.mjs";
223
+ } from "./chunk-TY5KCYDE.mjs";
216
224
  import {
217
225
  registerFarmMCPServer
218
226
  } from "./chunk-C7GJDVN4.mjs";
@@ -224,6 +232,11 @@ import {
224
232
  import {
225
233
  createCliColors
226
234
  } from "./chunk-IGL6CO6M.mjs";
235
+ import {
236
+ applyWebResponseHeaders,
237
+ fetchFarmExternalRewrite,
238
+ sendWebResponse
239
+ } from "./chunk-CO6UYM2D.mjs";
227
240
  import {
228
241
  invalidateFailedFarmDevModules,
229
242
  invalidateFarmDevDependents,
@@ -238,19 +251,6 @@ import {
238
251
  toPosixPath,
239
252
  toViteModuleId
240
253
  } 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
254
  import {
255
255
  resolveFarmAPIServerBasePath
256
256
  } from "./chunk-2I6PUKWJ.mjs";
@@ -261,12 +261,24 @@ import {
261
261
  readNodeRequestBody,
262
262
  resolveFarmServerConfig
263
263
  } from "./chunk-QDWMCFTH.mjs";
264
+ import {
265
+ createFarmSearchParams,
266
+ searchParamsToObject
267
+ } from "./chunk-H3ASZDT7.mjs";
268
+ import {
269
+ emitFarmEvent,
270
+ runWithFarmRequestSpan
271
+ } from "./chunk-2DA7CLY7.mjs";
264
272
  import {
265
273
  FARM_VERSION
266
- } from "./chunk-72JSHQQQ.mjs";
274
+ } from "./chunk-H37MDCPR.mjs";
267
275
  import {
268
276
  DEFAULT_FARM_API_BASE_PATH
269
277
  } from "./chunk-W6QLRQ3V.mjs";
278
+ import {
279
+ createFarmPageDataRedirectResponse,
280
+ getFarmPageDataRedirectFromResponse
281
+ } from "./chunk-SD6JGJOM.mjs";
270
282
  import {
271
283
  addMetadataMarkdownAlternate,
272
284
  mergeMetadata,
@@ -275,20 +287,25 @@ import {
275
287
  import {
276
288
  FARM_DEPLOYMENT_ID_HEADER,
277
289
  createFarmDeploymentMismatchResponse,
278
- getFarmDeploymentMismatch
279
- } from "./chunk-UAQD67HM.mjs";
290
+ getFarmDeploymentMismatch,
291
+ withFarmDeploymentResponse
292
+ } from "./chunk-F7JKVHU2.mjs";
280
293
  import {
281
294
  createDeferredDataResponse
282
- } from "./chunk-K5EW7GUU.mjs";
295
+ } from "./chunk-7BIW7VCW.mjs";
283
296
  import {
284
- FARM_CONFIG_REWRITES_PLUGIN_NAME
285
- } from "./chunk-QPJ4MZTO.mjs";
297
+ FARM_CONFIG_HEADERS_PLUGIN_NAME,
298
+ FARM_CONFIG_REDIRECTS_PLUGIN_NAME,
299
+ FARM_CONFIG_REWRITES_PLUGIN_NAME,
300
+ getConfigRedirectMatcher
301
+ } from "./chunk-PLJKJJ2H.mjs";
302
+ import {
303
+ parseFarmRequestTarget,
304
+ resolveFarmRequestURL
305
+ } from "./chunk-5OFNUETM.mjs";
286
306
  import {
287
307
  isFarmNotFoundError
288
308
  } from "./chunk-JNYFXL7X.mjs";
289
- import {
290
- resolveFarmRequestURL
291
- } from "./chunk-6HRAK7I5.mjs";
292
309
  import {
293
310
  applyFarmBasePath,
294
311
  stripFarmBasePath
@@ -318,6 +335,7 @@ function transformFarmFormActionModule(options) {
318
335
 
319
336
  // src/vite.ts
320
337
  import { parseSync } from "vite";
338
+ import { AsyncLocalStorage } from "async_hooks";
321
339
  import { isBuiltin } from "module";
322
340
 
323
341
  // src/dev-preview-guard.ts
@@ -393,8 +411,7 @@ async function isAllowedPreviewRequest(server, options, req) {
393
411
  if (server.config.publicDir && isInside(await realpathOr(server.config.publicDir), file)) {
394
412
  return true;
395
413
  }
396
- const isModuleOrAsset = MODULE_EXTENSION.test(file) || ASSET_EXTENSION.test(file) || query.has("import");
397
- if (!isModuleOrAsset) return false;
414
+ if (!MODULE_EXTENSION.test(file) && !ASSET_EXTENSION.test(file)) return false;
398
415
  for (const source of options.getSourceRoots()) {
399
416
  const sourceRoot = await realpathOr(source.root);
400
417
  const sourceDir = await realpathOr(path2.resolve(source.root, source.srcDir));
@@ -436,8 +453,40 @@ async function realpathOr(directory) {
436
453
  }
437
454
  }
438
455
  function isInside(directory, file) {
439
- const relative2 = path2.relative(directory, file);
440
- return relative2 !== "" && relative2 !== ".." && !relative2.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative2);
456
+ const relative3 = path2.relative(directory, file);
457
+ return relative3 !== "" && relative3 !== ".." && !relative3.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative3);
458
+ }
459
+
460
+ // src/server/dev-cors.ts
461
+ var VITE_DEFAULT_CORS_ORIGIN = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
462
+ var VITE_DEFAULT_CORS_METHODS = "GET,HEAD,PUT,PATCH,POST,DELETE";
463
+ function appendVary(res, value) {
464
+ const current = res.getHeader("Vary");
465
+ const values = String(current ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
466
+ if (values.includes("*") || values.some((entry) => entry.toLowerCase() === value.toLowerCase())) {
467
+ return;
468
+ }
469
+ res.setHeader("Vary", [...values, value].join(", "));
470
+ }
471
+ function createFarmDevViteCorsMiddleware() {
472
+ return function farmDevViteCors(req, res, next) {
473
+ const origin = req.headers.origin;
474
+ if (typeof origin === "string" && VITE_DEFAULT_CORS_ORIGIN.test(origin) && !res.hasHeader("Access-Control-Allow-Origin")) {
475
+ res.setHeader("Access-Control-Allow-Origin", origin);
476
+ }
477
+ appendVary(res, "Origin");
478
+ if (req.method?.toUpperCase() !== "OPTIONS") {
479
+ next();
480
+ return;
481
+ }
482
+ res.setHeader("Access-Control-Allow-Methods", VITE_DEFAULT_CORS_METHODS);
483
+ appendVary(res, "Access-Control-Request-Headers");
484
+ const requestHeaders = req.headers["access-control-request-headers"];
485
+ if (requestHeaders) res.setHeader("Access-Control-Allow-Headers", requestHeaders);
486
+ res.statusCode = 204;
487
+ res.setHeader("Content-Length", "0");
488
+ res.end();
489
+ };
441
490
  }
442
491
 
443
492
  // src/vite.ts
@@ -448,13 +497,87 @@ import { pathToFileURL } from "url";
448
497
  // src/dev-static.ts
449
498
  import * as fs from "fs";
450
499
  import * as path3 from "path";
451
- function shouldBypassFarmRouterForDottedPath(pathname, routeManager, baseDirs, generatedPaths = []) {
500
+ function shouldBypassFarmRouterForDottedPath(pathname, routeManager, baseDirs, generatedPaths = [], method = "GET") {
452
501
  if (!pathname.includes(".") || pathname.endsWith(".html")) return false;
453
502
  const matchesAppRoute = Boolean(
454
503
  routeManager?.matchRoute(pathname)?.route || routeManager?.matchMetadataRoute(pathname) || routeManager?.matchMetadataImage(pathname) || generatedPaths.includes(pathname)
455
504
  );
505
+ if (method !== "GET" && method !== "HEAD") {
506
+ return !matchesAppRoute && !devServableFileExists(pathname, baseDirs);
507
+ }
456
508
  return !matchesAppRoute || devServableFileExists(pathname, baseDirs);
457
509
  }
510
+ function isMalformedFarmRequestPathname(pathname) {
511
+ if (!pathname.includes("%")) return false;
512
+ try {
513
+ decodeURI(pathname);
514
+ return false;
515
+ } catch {
516
+ return true;
517
+ }
518
+ }
519
+ var FARM_MALFORMED_REQUEST_BODY = JSON.stringify(
520
+ { error: true, status: 400, message: "Bad Request" },
521
+ null,
522
+ 2
523
+ );
524
+ function resolveFarmPublicFilePath(pathname, publicFiles) {
525
+ if (publicFiles.size === 0) return null;
526
+ let id = pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
527
+ if (id.includes("%")) {
528
+ const escaped = id.replace(/%2f/gi, "%252F");
529
+ try {
530
+ id = decodeURIComponent(escaped);
531
+ } catch {
532
+ id = escaped;
533
+ }
534
+ }
535
+ if (publicFiles.has(id)) return id;
536
+ const index = `${id === "/" ? "" : id}/index.html`;
537
+ return publicFiles.has(index) ? index : null;
538
+ }
539
+ function createFarmPublicFileIndex(getPublicDir) {
540
+ const none = /* @__PURE__ */ new Set();
541
+ let listing;
542
+ return {
543
+ get() {
544
+ const configured = getPublicDir();
545
+ if (typeof configured !== "string" || configured.length === 0) return none;
546
+ if (listing?.configured === configured) return listing.files;
547
+ const dir = path3.resolve(configured);
548
+ listing = { configured, dir, files: listFarmPublicFiles(dir) };
549
+ return listing.files;
550
+ },
551
+ invalidate(file) {
552
+ if (!listing) return;
553
+ const resolved = path3.resolve(file);
554
+ if (resolved === listing.dir || resolved.startsWith(listing.dir + path3.sep)) {
555
+ listing = void 0;
556
+ }
557
+ }
558
+ };
559
+ }
560
+ function listFarmPublicFiles(dir) {
561
+ const files = /* @__PURE__ */ new Set();
562
+ let entries;
563
+ try {
564
+ entries = fs.readdirSync(dir, { recursive: true, withFileTypes: true });
565
+ } catch {
566
+ return files;
567
+ }
568
+ for (const entry of entries) {
569
+ const filePath = path3.join(entry.parentPath, entry.name);
570
+ let isFile = entry.isFile();
571
+ if (!isFile && entry.isSymbolicLink()) {
572
+ try {
573
+ isFile = fs.statSync(filePath).isFile();
574
+ } catch {
575
+ }
576
+ }
577
+ if (isFile) files.add(`/${path3.relative(dir, filePath).split(path3.sep).join("/")}`);
578
+ }
579
+ return files;
580
+ }
458
581
  var VITE_MODULE_QUERY_FLAGS = [
459
582
  "import",
460
583
  "raw",
@@ -470,13 +593,28 @@ function isViteModuleRequest(url, headers) {
470
593
  const value = Array.isArray(destination) ? destination[0] : destination;
471
594
  return value !== void 0 && SCRIPT_FETCH_DESTINATIONS.has(value.toLowerCase());
472
595
  }
596
+ var VITE_CLIENT_QUERY_FLAGS = ["t", "v", "direct", "html-proxy", "worker_file"];
597
+ var NAVIGATION_FETCH_DESTINATIONS = /* @__PURE__ */ new Set(["document", "iframe", "frame", "embed", "object"]);
598
+ function isViteDevClientRequest(url, headers) {
599
+ if (isViteModuleRequest(url, headers)) return true;
600
+ if (VITE_CLIENT_QUERY_FLAGS.some((flag) => url.searchParams.has(flag))) return true;
601
+ const destination = firstHeaderValue(headers["sec-fetch-dest"]);
602
+ if (destination !== void 0) {
603
+ return !NAVIGATION_FETCH_DESTINATIONS.has(destination.toLowerCase());
604
+ }
605
+ return firstHeaderValue(headers.referer) !== void 0 && !(firstHeaderValue(headers.accept) ?? "").includes("text/html");
606
+ }
607
+ function firstHeaderValue(value) {
608
+ return Array.isArray(value) ? value[0] : value;
609
+ }
473
610
  var DOCS_ENGINE_APP_OWNABLE_PATHS = /* @__PURE__ */ new Set([
474
611
  "/llms.txt",
475
612
  "/llms-full.txt",
476
613
  "/sitemap.xml",
477
614
  "/robots.txt"
478
615
  ]);
479
- function farmAppOwnsDocsEnginePath(pathname, options) {
616
+ function farmAppOwnsDocsEnginePath(routePathname, options) {
617
+ const pathname = routePathname.length > 1 ? routePathname.replace(/\/+$/, "") : routePathname;
480
618
  if (!DOCS_ENGINE_APP_OWNABLE_PATHS.has(pathname)) return false;
481
619
  return options.generatedPaths.includes(pathname) || Boolean(options.routeManager?.matchMetadataRoute(pathname)) || devServableFileExists(pathname, [options.publicDir]);
482
620
  }
@@ -696,6 +834,42 @@ async function createBlurDataURL(bytes) {
696
834
  }
697
835
  }
698
836
 
837
+ // src/dev/deferred-setup.ts
838
+ function createFarmDeferredMiddleware(ready) {
839
+ const stack = [];
840
+ const run = (req, res, next) => {
841
+ let index = 0;
842
+ const step = (error) => {
843
+ if (error !== void 0 && error !== null) return next(error);
844
+ const layer = stack[index++];
845
+ if (!layer) return next();
846
+ try {
847
+ layer.handle(req, res, step);
848
+ } catch (thrown) {
849
+ next(thrown ?? new Error("Middleware threw a nullish value"));
850
+ }
851
+ };
852
+ step();
853
+ };
854
+ return {
855
+ handle(req, res, next) {
856
+ const pending = ready();
857
+ if (!pending) return run(req, res, next);
858
+ pending.then(
859
+ () => run(req, res, next),
860
+ (error) => next(error ?? new Error("Farm dev server setup failed"))
861
+ );
862
+ },
863
+ target: {
864
+ stack,
865
+ use(handle) {
866
+ stack.push({ route: "", handle });
867
+ return this;
868
+ }
869
+ }
870
+ };
871
+ }
872
+
699
873
  // src/vite.ts
700
874
  import { rewriteFormStatusImports } from "@farm.js/islx/compiler";
701
875
 
@@ -880,13 +1054,13 @@ function loadFarmDocsSearchDevRuntime() {
880
1054
  return import("./search-client-OXH6GBNO.mjs");
881
1055
  }
882
1056
  function loadFarmOpenAPIDevRuntime() {
883
- return import("./manager-H5ZM3HAM.mjs");
1057
+ return import("./manager-JIA66YJ2.mjs");
884
1058
  }
885
1059
  function loadFarmWorkflowsDevRuntime() {
886
1060
  return import("./workflows.mjs");
887
1061
  }
888
1062
  function loadFarmDevtoolsSnapshotRuntime() {
889
- return import("./devtools-PUVZB3F2.mjs");
1063
+ return import("./devtools-UFQYT3VA.mjs");
890
1064
  }
891
1065
  function loadFarmDevtoolsUIRuntime() {
892
1066
  return import("./devtools-ui-CYBVFLPH.mjs");
@@ -923,6 +1097,18 @@ export function appDataDir() {
923
1097
  }
924
1098
  `;
925
1099
  }
1100
+ function createFarmServerPrebundleConfig(bundledPackages) {
1101
+ const include = bundledPackages.filter(({ prebundle }) => prebundle).map(({ name }) => name);
1102
+ if (include.length === 0) return {};
1103
+ const isBare = (id) => /^(?![a-zA-Z]:)[\w@]/.test(id) && !id.includes(":");
1104
+ const isIncluded = (id) => include.some((name) => id === name || id.startsWith(`${name}/`));
1105
+ return {
1106
+ optimizeDeps: {
1107
+ include,
1108
+ rolldownOptions: { external: (id) => isBare(id) && !isIncluded(id) }
1109
+ }
1110
+ };
1111
+ }
926
1112
  function farmServerOnlyEntriesPlugin(options = {}) {
927
1113
  let root = process.cwd();
928
1114
  let vercelOgInstalled = false;
@@ -930,6 +1116,9 @@ function farmServerOnlyEntriesPlugin(options = {}) {
930
1116
  name: "farm:server-only-entries",
931
1117
  enforce: "pre",
932
1118
  config(config) {
1119
+ const bundledPackages = collectFarmServerBundledPackageInfo(
1120
+ path6.resolve(config.root ?? process.cwd())
1121
+ );
933
1122
  return {
934
1123
  optimizeDeps: { rolldownOptions: { plugins: [farmBrowserBuiltinsOptimizerPlugin()] } },
935
1124
  ssr: {
@@ -937,8 +1126,9 @@ function farmServerOnlyEntriesPlugin(options = {}) {
937
1126
  // Resolve `server-only` here rather than in Node, which would load its throwing build.
938
1127
  SERVER_ONLY_PACKAGE,
939
1128
  // Packages Node cannot load as a bundler does (stylesheet imports, `module`-only ESM).
940
- ...collectFarmServerBundledPackages(path6.resolve(config.root ?? process.cwd()))
941
- ]
1129
+ ...bundledPackages.map(({ name }) => name)
1130
+ ],
1131
+ ...options.prebundleServerPackages ? createFarmServerPrebundleConfig(bundledPackages) : {}
942
1132
  }
943
1133
  };
944
1134
  },
@@ -1057,10 +1247,36 @@ function withFarmRequestTracing(handler, apiRuntime, resolveTraceUrl = (request)
1057
1247
  }
1058
1248
  res.statusCode = 500;
1059
1249
  res.setHeader("Content-Type", "application/json");
1060
- res.end(JSON.stringify({ error: "Internal server error" }));
1250
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
1061
1251
  });
1062
1252
  };
1063
1253
  }
1254
+ function sendFarmDevErrorJSON(res) {
1255
+ res.statusCode = 500;
1256
+ res.setHeader("Content-Type", "application/json");
1257
+ res.setHeader("Cache-Control", "private, no-store");
1258
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
1259
+ }
1260
+ function createFarmDevMiddlewareErrorResponse() {
1261
+ return new Response(FARM_INTERNAL_SERVER_ERROR_BODY, {
1262
+ status: 500,
1263
+ headers: { "Content-Type": "application/json", "Cache-Control": "private, no-store" }
1264
+ });
1265
+ }
1266
+ function sendFarmDevRuntimeHookError(res, json) {
1267
+ res.statusCode = 500;
1268
+ res.setHeader("Content-Type", json ? "application/json" : "text/plain; charset=utf-8");
1269
+ res.end(json ? FARM_INTERNAL_SERVER_ERROR_BODY : "Internal Server Error");
1270
+ }
1271
+ var FARM_CONFIG_ROUTE_PLUGIN_NAMES = /* @__PURE__ */ new Set([
1272
+ FARM_CONFIG_HEADERS_PLUGIN_NAME,
1273
+ FARM_CONFIG_REDIRECTS_PLUGIN_NAME,
1274
+ FARM_CONFIG_REWRITES_PLUGIN_NAME
1275
+ ]);
1276
+ function isFarmConfigRoutePlugin(plugin) {
1277
+ return FARM_CONFIG_ROUTE_PLUGIN_NAMES.has(plugin.name);
1278
+ }
1279
+ var FARM_DEV_CONFIG_REWRITE_SOURCE = /* @__PURE__ */ Symbol.for("farm.devConfigRewriteSource");
1064
1280
  async function proxyFarmExternalRewrite(req, res, bodySizeLimit) {
1065
1281
  const destination = req.url;
1066
1282
  if (!destination || !/^https?:\/\//i.test(destination)) return false;
@@ -1158,6 +1374,32 @@ function interceptFarmDevPageResponse(options) {
1158
1374
  const originalFlushHeaders = res.flushHeaders?.bind(res);
1159
1375
  let afterResponseCalled = false;
1160
1376
  let interceptedEnd = false;
1377
+ const restore = () => {
1378
+ res.write = originalWrite;
1379
+ res.end = originalEnd;
1380
+ res.writeHead = originalWriteHead;
1381
+ if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;
1382
+ delete res[FARM_NODE_RESPONSE_END_PENDING];
1383
+ };
1384
+ let runtimeHookFailed = false;
1385
+ const endRuntimeRequest = (response) => pm.endRuntimeRequest(runtimeSession, response).catch((error) => {
1386
+ runtimeHookFailed = true;
1387
+ throw error;
1388
+ });
1389
+ const reportFailure = (error) => {
1390
+ if (!runtimeHookFailed) void options.emitError(error);
1391
+ console.error("Error in afterResponse hook:", error);
1392
+ };
1393
+ const writeRuntimeHookFailure = () => {
1394
+ res.statusCode = 500;
1395
+ res.removeHeader("Content-Length");
1396
+ res.setHeader(
1397
+ "Content-Type",
1398
+ options.jsonError ? "application/json" : "text/plain; charset=utf-8"
1399
+ );
1400
+ originalWriteHead(500);
1401
+ originalWrite(options.jsonError ? FARM_INTERNAL_SERVER_ERROR_BODY : "Internal Server Error");
1402
+ };
1161
1403
  const htmlChunks = [];
1162
1404
  const responseChunks = [];
1163
1405
  let didStreamHtml = false;
@@ -1188,8 +1430,7 @@ function interceptFarmDevPageResponse(options) {
1188
1430
  const status = res.statusCode || 200;
1189
1431
  const canHaveBody = method !== "HEAD" && status !== 204 && status !== 205 && status !== 304;
1190
1432
  pm.copyRequestContext(req, runtimeSession.request);
1191
- const done = pm.endRuntimeRequest(
1192
- runtimeSession,
1433
+ const done = endRuntimeRequest(
1193
1434
  new Response(canHaveBody ? body : null, {
1194
1435
  status,
1195
1436
  headers: createHeadersFromNodeResponse(res)
@@ -1273,13 +1514,6 @@ function interceptFarmDevPageResponse(options) {
1273
1514
  options.logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, "PAGE");
1274
1515
  const originalEndArgs = [...args];
1275
1516
  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
1517
  if (streamsThroughRuntime()) {
1284
1518
  const stream = startRuntimeStream();
1285
1519
  streamRuntimeChunk(toNodeResponseBuffer(args[0], args[1]));
@@ -1290,15 +1524,8 @@ function interceptFarmDevPageResponse(options) {
1290
1524
  stream.done.then(
1291
1525
  () => hasAfterResponseHook ? pm.runHookParallel("afterResponse", req, res) : void 0
1292
1526
  ).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
- }
1527
+ reportFailure(error);
1528
+ if (!res.headersSent) writeRuntimeHookFailure();
1302
1529
  }).finally(() => {
1303
1530
  restore();
1304
1531
  if (callback) originalEnd(callback);
@@ -1317,15 +1544,23 @@ function interceptFarmDevPageResponse(options) {
1317
1544
  Promise.resolve().then(async () => {
1318
1545
  if (isHtmlResponse) {
1319
1546
  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);
1547
+ try {
1548
+ if (!didStreamHtml || bufferPluginResponse) {
1549
+ let html = await pm.runHookSerial("transformHTML", fullHtml);
1550
+ html = await pm.runHookSerial("afterRender", html, renderPayload);
1551
+ originalEndArgs.length = 0;
1552
+ originalEndArgs.push(html);
1553
+ if (callback) originalEndArgs.push(callback);
1554
+ } else {
1555
+ await pm.runHookSerial("transformHTML", fullHtml);
1556
+ await pm.runHookSerial("afterRender", fullHtml, renderPayload);
1557
+ }
1558
+ } catch (error) {
1559
+ if (runtimeSession) {
1560
+ runtimeHookFailed = true;
1561
+ await pm.failRuntimeRequest(runtimeSession, error);
1562
+ }
1563
+ throw error;
1329
1564
  }
1330
1565
  }
1331
1566
  if (runtimeSession) {
@@ -1334,8 +1569,7 @@ function interceptFarmDevPageResponse(options) {
1334
1569
  const canHaveBody = method !== "HEAD" && status !== 204 && status !== 205 && status !== 304;
1335
1570
  const firstArg = originalEndArgs[0];
1336
1571
  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,
1572
+ const runtimeResponse = await endRuntimeRequest(
1339
1573
  new Response(responseBody ? toRequestBody(responseBody) : responseBody, {
1340
1574
  status,
1341
1575
  headers: createHeadersFromNodeResponse(res)
@@ -1360,8 +1594,13 @@ function interceptFarmDevPageResponse(options) {
1360
1594
  delete res[FARM_NODE_RESPONSE_END_PENDING];
1361
1595
  originalEnd(...originalEndArgs);
1362
1596
  }).catch((error) => {
1363
- void options.emitError(error);
1364
- console.error("Error in afterResponse hook:", error);
1597
+ reportFailure(error);
1598
+ if (runtimeHookFailed && !res.headersSent) {
1599
+ restore();
1600
+ writeRuntimeHookFailure();
1601
+ originalEnd(callback);
1602
+ return;
1603
+ }
1365
1604
  const shouldBufferResponse = isHtmlResponse ? bufferPluginResponse : Boolean(runtimeSession && hasRuntimeAfterHook);
1366
1605
  if (shouldBufferResponse) {
1367
1606
  const body = Buffer.concat(isHtmlResponse ? htmlChunks : responseChunks);
@@ -1383,7 +1622,10 @@ function interceptFarmDevPageResponse(options) {
1383
1622
  return res;
1384
1623
  });
1385
1624
  return {
1386
- isEnded: () => interceptedEnd || res.writableEnded
1625
+ isEnded: () => interceptedEnd || res.writableEnded,
1626
+ release() {
1627
+ if (!interceptedEnd) restore();
1628
+ }
1387
1629
  };
1388
1630
  }
1389
1631
  function getFullEnvDefine(config) {
@@ -1401,7 +1643,12 @@ function getEnvDefines(config, configEnv) {
1401
1643
  __FARM_API_BASE_URL__: JSON.stringify(getFarmAPIBaseURLDefine(config)),
1402
1644
  __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),
1403
1645
  __FARM_IMAGE_CONFIG__: JSON.stringify(
1404
- getPublicFarmImageConfig(resolveFarmImageConfig(config.images))
1646
+ getPublicFarmImageConfig(
1647
+ resolveFarmImageConfig(
1648
+ config.images,
1649
+ isFarmRendererDisabled(config.renderer) ? "none" : void 0
1650
+ )
1651
+ )
1405
1652
  )
1406
1653
  };
1407
1654
  if (configEnv?.isSsrBuild) {
@@ -1590,7 +1837,7 @@ function transformIsolatedClientBoundaryModule(options) {
1590
1837
  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {
1591
1838
  output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);
1592
1839
  }
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";
1840
+ const runtimeImport = options.slots ? options.browser ? "const __farm_islx_island__ = (component) => component;" : `import { createIsland as __farm_islx_island__ } from "@farm.js/core/internal/islx-react";` : `import * as __farm_isolated_react__ from "react";
1594
1841
  import { createFarmIsolatedClientBoundary as __farm_create_isolated_boundary__ } from "@farm.js/core/internal/isolated-boundary";`;
1595
1842
  return `${runtimeImport}
1596
1843
  ${output}
@@ -1622,8 +1869,8 @@ function isFarmModuleAstNode(value) {
1622
1869
  function isFarmConfigFile(file, root) {
1623
1870
  const normalized = file.replace(/\\/g, "/");
1624
1871
  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);
1872
+ const relative3 = normalized.startsWith(`${rootSlug}/`) ? normalized.slice(rootSlug.length + 1) : normalized;
1873
+ return FARM_CONFIG_FILENAMES.has(relative3);
1627
1874
  }
1628
1875
  var warnedClientBoundaryIds = /* @__PURE__ */ new Set();
1629
1876
  function warnClientBoundaryOnce(context, id, code, config) {
@@ -1652,7 +1899,8 @@ function hasViteAlias(alias, find) {
1652
1899
  (entry) => typeof entry.find === "string" ? entry.find === find : entry.find.test(`${find}/`)
1653
1900
  );
1654
1901
  }
1655
- function farmPlugin(options = {}, initialPluginManager) {
1902
+ function farmPlugin(options = {}, initialPluginManager, deferredSetup) {
1903
+ const rendererDisabled = isFarmRendererDisabled(options.renderer);
1656
1904
  const imageImports = farmImageImportsPlugin();
1657
1905
  const fontImports = farmFontImportsPlugin({
1658
1906
  root: options.root,
@@ -1667,12 +1915,16 @@ function farmPlugin(options = {}, initialPluginManager) {
1667
1915
  };
1668
1916
  let reactRefreshActive = false;
1669
1917
  let server;
1918
+ let deferredGates;
1919
+ let pendingClientSetup = null;
1920
+ const farmSetupContext = new AsyncLocalStorage();
1670
1921
  let apiRouteManager;
1671
1922
  let openAPIManager = null;
1672
1923
  let middlewareManager;
1673
1924
  let refreshRouteDiscovery = null;
1674
1925
  let workflowHandler = null;
1675
1926
  let isBuild = false;
1927
+ let farmOwnsDevCors = false;
1676
1928
  const docsMCPServerDisposers = /* @__PURE__ */ new Set();
1677
1929
  const releaseDocsMCPServers = () => {
1678
1930
  for (const dispose of docsMCPServerDisposers) dispose();
@@ -1689,7 +1941,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1689
1941
  console.log(log);
1690
1942
  };
1691
1943
  const getProgrammaticClientRoutes = () => options.programmaticClientRoutes ?? farmApp?.getRouteManager().getProgrammaticClientRoutes();
1692
- return {
1944
+ const plugin = {
1693
1945
  name: "farm",
1694
1946
  api: { getProgrammaticClientRoutes },
1695
1947
  config(userConfig, configEnv) {
@@ -1697,6 +1949,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1697
1949
  const layerAliases = getFarmLayerAliases(options.layers);
1698
1950
  const sourceAlias = hasViteAlias(userConfig.resolve?.alias, "@") ? {} : createFarmSourceAlias(options.root || process.cwd(), options.srcDir);
1699
1951
  const layerRoots = (options.layers ?? []).map((layer) => layer.root);
1952
+ farmOwnsDevCors = !isBuild && userConfig.server?.cors === void 0;
1700
1953
  return {
1701
1954
  // Honor Farm's publicDir so the dev server serves the same static
1702
1955
  // directory the production client build emits.
@@ -1709,6 +1962,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1709
1962
  alias: { ...layerAliases, ...sourceAlias }
1710
1963
  },
1711
1964
  server: {
1965
+ ...farmOwnsDevCors ? { cors: false } : {},
1712
1966
  fs: {
1713
1967
  ...layerRoots.length ? { allow: [path6.resolve(options.root || process.cwd()), ...layerRoots] } : {},
1714
1968
  deny: getFarmDevFsDeny(userConfig.server?.fs?.deny, options)
@@ -1721,7 +1975,7 @@ function farmPlugin(options = {}, initialPluginManager) {
1721
1975
  await fontImports.configResolved.call(this, config);
1722
1976
  }
1723
1977
  serverFnTransformActive = config.plugins.some(
1724
- (plugin) => plugin.name === SERVER_FN_TRANSFORM_PLUGIN
1978
+ (plugin2) => plugin2.name === SERVER_FN_TRANSFORM_PLUGIN
1725
1979
  );
1726
1980
  reactRefreshActive = isFarmReactRefreshActive(config);
1727
1981
  if (options.experimental?.serverActions === true && !serverFnTransformActive && !islandsServerFns()) {
@@ -1740,7 +1994,16 @@ function farmPlugin(options = {}, initialPluginManager) {
1740
1994
  await fontImports.configureServer.call(this, viteServer);
1741
1995
  }
1742
1996
  server = viteServer;
1997
+ const farmMiddlewares = deferredGates?.pre.target ?? viteServer.middlewares;
1998
+ const farmPostMiddlewares = deferredGates?.post.target ?? viteServer.middlewares;
1743
1999
  const pm = initialPluginManager;
2000
+ const configRoutePlugins = new Set(
2001
+ pm?.getPlugins().filter(isFarmConfigRoutePlugin).map((plugin2) => plugin2.name)
2002
+ );
2003
+ const configRedirectMatchers = (pm?.getPlugins() ?? []).flatMap((plugin2) => {
2004
+ const matcher = getConfigRedirectMatcher(plugin2);
2005
+ return matcher ? [matcher] : [];
2006
+ });
1744
2007
  const emitPluginError = async (phase, error, meta) => {
1745
2008
  if (!pm) return;
1746
2009
  try {
@@ -1755,11 +2018,17 @@ function farmPlugin(options = {}, initialPluginManager) {
1755
2018
  },
1756
2019
  server
1757
2020
  );
2021
+ farmApp.getRouteManager().usePackageClientBoundaryCacheFile(
2022
+ resolvePackageClientBoundaryCacheFile(
2023
+ farmApp.getConfig().root,
2024
+ options.distDir || ".farm"
2025
+ )
2026
+ );
1758
2027
  await farmApp.initialize();
1759
2028
  const farmConfig = farmApp.getConfig();
1760
2029
  let farmAppPackages;
1761
2030
  if (farmConfig.agent?.noindexPreviews) {
1762
- server.middlewares.use((_req, res, next) => {
2031
+ farmMiddlewares.use((_req, res, next) => {
1763
2032
  if (isFarmPreviewDeploymentEnvironment(process.env)) {
1764
2033
  res.setHeader("X-Robots-Tag", FARM_PREVIEW_ROBOTS_TAG);
1765
2034
  }
@@ -2068,7 +2337,8 @@ function farmPlugin(options = {}, initialPluginManager) {
2068
2337
  const { OpenAPIManager } = await loadFarmOpenAPIDevRuntime();
2069
2338
  openAPIManager = new OpenAPIManager(appDirs, options.openapi, {
2070
2339
  mode: "development",
2071
- apiBaseURL: typeof options.api?.baseURL === "string" ? options.api.baseURL : void 0
2340
+ apiBaseURL: typeof options.api?.baseURL === "string" ? options.api.baseURL : void 0,
2341
+ loadModule: (filePath) => apiRouteManager.loadModule(filePath)
2072
2342
  });
2073
2343
  const spec = await openAPIManager.generateSpec();
2074
2344
  reportOpenAPIDevGenerationResult(spec);
@@ -2117,9 +2387,10 @@ function farmPlugin(options = {}, initialPluginManager) {
2117
2387
  loadModule: async (specifier) => {
2118
2388
  const resolved = await server.environments.ssr.pluginContainer.resolveId(specifier);
2119
2389
  if (specifier === farmConfig.docs.adapter?.server && resolved?.id) {
2390
+ const file = resolved.id.split("?", 1)[0];
2120
2391
  return import(
2121
2392
  /* @vite-ignore */
2122
- pathToFileURL(resolved.id).href
2393
+ pathToFileURL(file).href
2123
2394
  );
2124
2395
  }
2125
2396
  return loadFarmDevModule(server, resolved?.id ?? specifier);
@@ -2144,7 +2415,8 @@ function farmPlugin(options = {}, initialPluginManager) {
2144
2415
  farmConfig.root,
2145
2416
  farmConfig.srcDir
2146
2417
  ),
2147
- isPathGuarded: isFarmDocsPathGuarded
2418
+ isPathGuarded: isFarmDocsPathGuarded,
2419
+ basePath: farmConfig.basePath
2148
2420
  }) : null;
2149
2421
  const wrapFarmDocsResponseWithLayouts = async (request, response) => {
2150
2422
  if (request.method === "HEAD" || response.headers.has("x-farm-docs-adapter") || !response.headers.get("content-type")?.toLowerCase().includes("text/html")) {
@@ -2253,7 +2525,8 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2253
2525
  srcDir: farmConfig.srcDir,
2254
2526
  docs: farmConfig.docs,
2255
2527
  diagnostics: true,
2256
- isPathGuarded: isFarmDocsPathGuarded
2528
+ isPathGuarded: isFarmDocsPathGuarded,
2529
+ basePath: farmConfig.basePath
2257
2530
  }) : null;
2258
2531
  const farmDocsFontAssets = new Map(
2259
2532
  farmDocsFontAssetList.map(({ url, sourcePath }) => [url, sourcePath])
@@ -2300,8 +2573,13 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2300
2573
  });
2301
2574
  }
2302
2575
  );
2303
- server.middlewares.use(
2304
- withAPIRequestTracing(async (req, res, next) => {
2576
+ const publicFileIndex = createFarmPublicFileIndex(() => server.config.publicDir);
2577
+ for (const event of ["add", "unlink", "addDir", "unlinkDir"]) {
2578
+ server.watcher.on(event, (file) => publicFileIndex.invalidate(file));
2579
+ }
2580
+ const deferredDottedRequests = /* @__PURE__ */ new WeakMap();
2581
+ farmMiddlewares.use(
2582
+ withAPIRequestTracing(async function handleFarmDevRequest(req, res, next) {
2305
2583
  const requestUrl = req.url || "/";
2306
2584
  const requestMethod = req.method || "GET";
2307
2585
  const currentConfig = farmApp?.getConfig() ?? options;
@@ -2311,6 +2589,32 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2311
2589
  });
2312
2590
  const fullUrl = parsedRequestUrl.toString();
2313
2591
  const requestPathname = parsedRequestUrl.pathname;
2592
+ if (isMalformedFarmRequestPathname(requestPathname)) {
2593
+ res.statusCode = 400;
2594
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
2595
+ res.end(requestMethod === "HEAD" ? void 0 : FARM_MALFORMED_REQUEST_BODY);
2596
+ return;
2597
+ }
2598
+ if ((requestMethod === "GET" || requestMethod === "HEAD") && req[FARM_DEV_CONFIG_REWRITE_SOURCE] === void 0 && !isViteModuleRequest(parsedRequestUrl, req.headers)) {
2599
+ const publicFile = resolveFarmPublicFilePath(requestPathname, publicFileIndex.get());
2600
+ if (publicFile) {
2601
+ if (publicFile !== requestPathname) {
2602
+ req.url = `${encodeURI(publicFile)}${parsedRequestUrl.search}`;
2603
+ }
2604
+ return next();
2605
+ }
2606
+ }
2607
+ if (requestMethod === "OPTIONS" && req.headers.origin && req.headers["access-control-request-method"]) {
2608
+ const preflightHeaders = resolveRouteRuleCorsPreflightHeaders(
2609
+ currentConfig.routeRules,
2610
+ requestPathname
2611
+ );
2612
+ if (preflightHeaders) {
2613
+ res.writeHead(204, preflightHeaders);
2614
+ res.end();
2615
+ return;
2616
+ }
2617
+ }
2314
2618
  if (imageHandler && requestPathname === farmConfig.images.path) {
2315
2619
  const imageResponse = await imageHandler(
2316
2620
  createRequestFromNodeRequest(req, new URL(fullUrl))
@@ -2337,7 +2641,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2337
2641
  res.end("Farm DevTools are disabled.");
2338
2642
  return;
2339
2643
  }
2340
- if (requestPathname === FARM_DEVTOOLS_PATH && parsedRequestUrl.searchParams.get("embedded") !== "1") {
2644
+ if (requestPathname === FARM_DEVTOOLS_PATH && parsedRequestUrl.searchParams.get("embedded") !== "1" && !rendererDisabled) {
2341
2645
  let launchUrl = new URL(farmConfig.basePath || "/", parsedRequestUrl.origin);
2342
2646
  const referrer = req.headers.referer;
2343
2647
  if (referrer) {
@@ -2394,6 +2698,57 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2394
2698
  }
2395
2699
  return;
2396
2700
  }
2701
+ 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]));
2702
+ const configRewriteSource = req[FARM_DEV_CONFIG_REWRITE_SOURCE];
2703
+ const runtimeHookErrorAnswersJSON = rendererDisabled || isFarmAPIPathname(requestPathname, apiServerBasePath);
2704
+ if (pm && configRewriteSource === void 0 && !deferredDottedRequests.has(req) && (configRoutePlugins.has(FARM_CONFIG_HEADERS_PLUGIN_NAME) || configRedirectMatchers.length > 0) && !isViteOwnedRequest()) {
2705
+ let redirect = null;
2706
+ try {
2707
+ await pm.runHookParallelFiltered(
2708
+ "beforeRequest",
2709
+ (plugin2) => plugin2.name === FARM_CONFIG_HEADERS_PLUGIN_NAME,
2710
+ req,
2711
+ res
2712
+ );
2713
+ for (const matchRedirect of configRedirectMatchers) {
2714
+ redirect ?? (redirect = matchRedirect(parsedRequestUrl));
2715
+ }
2716
+ } catch (error) {
2717
+ await emitPluginError("before-request", error, { urlPath: requestUrl });
2718
+ if (!res.headersSent) {
2719
+ res.statusCode = 500;
2720
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
2721
+ }
2722
+ res.end("Internal Server Error");
2723
+ return;
2724
+ }
2725
+ if (redirect) {
2726
+ let response = new Response(`Redirecting to ${redirect.destination}`, {
2727
+ status: redirect.statusCode,
2728
+ headers: { Location: redirect.destination }
2729
+ });
2730
+ if (pm.hasRuntimeRequestHooks()) {
2731
+ const redirectResponse = response;
2732
+ try {
2733
+ response = await pm.runRuntimeRequest(
2734
+ createRequestFromNodeRequest(req, parsedRequestUrl),
2735
+ () => redirectResponse,
2736
+ {
2737
+ kind: isFarmAPIPathname(requestPathname, apiServerBasePath) ? "api" : requestMethod === "GET" || requestMethod === "HEAD" ? "page" : "request",
2738
+ route: { pathname: requestPathname }
2739
+ }
2740
+ );
2741
+ } catch {
2742
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2743
+ logResponse(requestMethod, requestUrl, 500, 0, "PAGE");
2744
+ return;
2745
+ }
2746
+ }
2747
+ await sendWebResponse(res, response);
2748
+ logResponse(requestMethod, requestUrl, res.statusCode, 0, "PAGE");
2749
+ return;
2750
+ }
2751
+ }
2397
2752
  const runAppMiddlewareForContentRoute = async () => {
2398
2753
  if (!middlewareManager?.hasMiddleware()) return false;
2399
2754
  const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));
@@ -2405,6 +2760,40 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2405
2760
  () => middlewareManager.execute(req, res)
2406
2761
  );
2407
2762
  };
2763
+ const runAppMiddlewareInRuntimeSession = async (runtimeSession2, logResponse2) => {
2764
+ const interceptor = runtimeSession2 && pm?.hasRuntimeHook("after") && middlewareManager?.hasMiddleware() ? interceptFarmDevPageResponse({
2765
+ req,
2766
+ res,
2767
+ pm,
2768
+ runtimeSession: runtimeSession2,
2769
+ hasRuntimeAfterHook: true,
2770
+ hasAfterResponseHook: false,
2771
+ hasHTMLTransformHook: false,
2772
+ renderPayload: {},
2773
+ method: requestMethod,
2774
+ urlPath: requestUrl,
2775
+ pathname: requestPathname,
2776
+ startTime: Date.now(),
2777
+ logResponse: (_method, _path, status) => logResponse2?.(status),
2778
+ // The runtime reports a runtime.after failure itself.
2779
+ emitError: async () => {
2780
+ },
2781
+ jsonError: runtimeHookErrorAnswersJSON
2782
+ }) : void 0;
2783
+ let handled;
2784
+ try {
2785
+ handled = await runAppMiddlewareForContentRoute();
2786
+ } catch (error) {
2787
+ interceptor?.release();
2788
+ throw error;
2789
+ }
2790
+ if (!handled) {
2791
+ interceptor?.release();
2792
+ return false;
2793
+ }
2794
+ if (!interceptor?.isEnded()) logResponse2?.(res.statusCode || 200);
2795
+ return true;
2796
+ };
2408
2797
  const serveBuiltInRoute = async (respond, {
2409
2798
  kind = requestMethod === "GET" || requestMethod === "HEAD" ? "page" : "request",
2410
2799
  computed,
@@ -2414,6 +2803,16 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2414
2803
  await computed?.body?.cancel().catch(() => {
2415
2804
  });
2416
2805
  };
2806
+ const sendRuntimeResponse = async (runtimeSession3, response2) => {
2807
+ let runtimeResponse;
2808
+ try {
2809
+ runtimeResponse = await pm.endRuntimeRequest(runtimeSession3, response2);
2810
+ } catch {
2811
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2812
+ return;
2813
+ }
2814
+ await sendWebResponse(res, runtimeResponse);
2815
+ };
2417
2816
  let runtimeSession2;
2418
2817
  if (pm?.hasRuntimeRequestHooks()) {
2419
2818
  try {
@@ -2426,43 +2825,40 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2426
2825
  createRequestFromNodeRequest(req, new URL(fullUrl)),
2427
2826
  { kind, route }
2428
2827
  );
2429
- } catch (error) {
2828
+ } catch {
2430
2829
  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");
2830
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2435
2831
  return;
2436
2832
  }
2437
2833
  if (runtimeSession2.response) {
2438
2834
  await discard();
2439
- await sendWebResponse(
2440
- res,
2441
- await pm.endRuntimeRequest(runtimeSession2, runtimeSession2.response)
2442
- );
2835
+ await sendRuntimeResponse(runtimeSession2, runtimeSession2.response);
2443
2836
  return;
2444
2837
  }
2445
2838
  pm.copyRequestContext(runtimeSession2.request, req);
2446
2839
  applyWebRequestToNodeRequest(runtimeSession2.request, req);
2447
2840
  }
2448
- if (await runAppMiddlewareForContentRoute()) {
2449
- await discard();
2450
- return;
2451
- }
2452
2841
  let response;
2842
+ let responding = false;
2453
2843
  try {
2844
+ if (await runAppMiddlewareInRuntimeSession(runtimeSession2)) {
2845
+ await discard();
2846
+ return;
2847
+ }
2848
+ responding = true;
2454
2849
  response = await respond(
2455
2850
  runtimeSession2?.request ?? createRequestFromNodeRequest(req, new URL(fullUrl))
2456
2851
  );
2457
2852
  } catch (error) {
2458
2853
  if (runtimeSession2) await pm.failRuntimeRequest(runtimeSession2, error);
2459
- throw error;
2854
+ if (!runtimeSession2 || !responding || res.headersSent) throw error;
2855
+ console.error("[FARM] Built-in route error:", error);
2856
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
2857
+ return;
2460
2858
  }
2461
2859
  if (!response) return;
2462
- await sendWebResponse(
2463
- res,
2464
- runtimeSession2 ? await pm.endRuntimeRequest(runtimeSession2, response) : response
2465
- );
2860
+ if (runtimeSession2) await sendRuntimeResponse(runtimeSession2, response);
2861
+ else await sendWebResponse(res, response);
2466
2862
  };
2467
2863
  const openAPIRequestPathname = openAPIManager ? stripFarmBasePath(requestPathname, farmConfig.basePath) : requestPathname;
2468
2864
  if (openAPIManager && options.openapi?.specRoute && openAPIRequestPathname === options.openapi.specRoute) {
@@ -2549,7 +2945,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2549
2945
  }
2550
2946
  }),
2551
2947
  {
2552
- basePath: farmConfig.basePath,
2948
+ basePath: farmApp.getConfig().basePath,
2553
2949
  apiServerBasePath,
2554
2950
  defaultMCP: () => farmApp.getServerRenderer().getDefaultMCPServer()
2555
2951
  }
@@ -2566,11 +2962,15 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2566
2962
  }
2567
2963
  }
2568
2964
  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
- });
2965
+ const toRoutePathname = (pathname2) => farmApp.getRouteManager().toRoutePathname(pathname2);
2966
+ const appOwnsDocsEnginePath = farmAppOwnsDocsEnginePath(
2967
+ toRoutePathname(requestPathname),
2968
+ {
2969
+ generatedPaths: farmAgentGeneratedPaths(farmConfig),
2970
+ routeManager: farmApp.getRouteManager(),
2971
+ publicDir: server.config.publicDir
2972
+ }
2973
+ );
2574
2974
  if (farmDocsHandler && !appOwnsDocsEnginePath && !viteModuleRequest) {
2575
2975
  const docsRequest = new Request(fullUrl, {
2576
2976
  method: requestMethod,
@@ -2597,7 +2997,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2597
2997
  }
2598
2998
  }
2599
2999
  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-YF2DSPKM.mjs");
3000
+ const { createFarmNativeTreeResponse } = await import("./native-tree-Y5YQANW7.mjs");
2601
3001
  const treeBodyInit = requestMethod === "POST" ? { body: createFarmNodeRequestBodyStream(req), duplex: "half" } : {};
2602
3002
  const treeResponse = await createFarmNativeTreeResponse({
2603
3003
  request: new Request(fullUrl, {
@@ -2618,9 +3018,12 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2618
3018
  });
2619
3019
  return;
2620
3020
  }
2621
- const markdownRouteLabel = () => resolveFarmMarkdownRouteLabel(
2622
- stripFarmBasePath(requestPathname, farmConfig.basePath),
2623
- (page) => farmApp.getRouteManager().matchRoute(page).route?.pattern
3021
+ const markdownRouteLabel = () => (
3022
+ // On the route path, as production labels it: /fr/index.md is /index.md.
3023
+ resolveFarmMarkdownRouteLabel(
3024
+ toRoutePathname(requestPathname),
3025
+ (page) => farmApp.getRouteManager().matchRoute(page).route?.pattern
3026
+ )
2624
3027
  );
2625
3028
  const markdownSourceResponse = viteModuleRequest ? null : await createFarmMarkdownSourceResponse({
2626
3029
  request: new Request(fullUrl, {
@@ -2628,6 +3031,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2628
3031
  headers: docsHeaders
2629
3032
  }),
2630
3033
  config: farmApp.getConfig().mdx,
3034
+ routePathname: toRoutePathname,
2631
3035
  resolveSource: async (pathname2) => {
2632
3036
  const match = farmApp.getRouteManager().matchRoute(pathname2);
2633
3037
  const sourcePath = match.route?.markdownSourcePath || (match.route && isFarmMarkdownPageFile(match.route.modulePath) ? match.route.modulePath : null);
@@ -2661,6 +3065,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2661
3065
  headers: docsHeaders
2662
3066
  }),
2663
3067
  config: farmApp.getConfig().md,
3068
+ routePathname: toRoutePathname,
2664
3069
  routeExists: (pathname2) => Boolean(farmApp.getRouteManager().matchRoute(pathname2).route),
2665
3070
  // The page is rendered by this server's own listener, never the host the
2666
3071
  // caller's Host names. Redirects are not followed, so the mirror answers with
@@ -2687,7 +3092,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2687
3092
  return;
2688
3093
  }
2689
3094
  if (!viteModuleRequest && farmRequestWantsMarkdown(requestPathname, req.headers.accept)) {
2690
- const markdownRoute = farmApp.getRouteManager().matchRoute(normalizeFarmMarkdownRoutePath(requestPathname));
3095
+ const markdownRoute = farmApp.getRouteManager().matchRoute(normalizeFarmMarkdownRoutePath(requestPathname, toRoutePathname));
2691
3096
  if (!markdownRoute.route) {
2692
3097
  await serveBuiltInRoute(
2693
3098
  () => new Response(
@@ -2709,7 +3114,8 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2709
3114
  farmApp.getConfig().md,
2710
3115
  requestPathname,
2711
3116
  {
2712
- accept: "text/markdown"
3117
+ accept: "text/markdown",
3118
+ routePathname: toRoutePathname
2713
3119
  }
2714
3120
  );
2715
3121
  if (markdownPageTarget && farmApp.getRouteManager().matchRoute(markdownPageTarget.pathname).route) {
@@ -2718,8 +3124,7 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2718
3124
  if (!varyValues.some((value) => value.toLowerCase() === "accept")) {
2719
3125
  res.setHeader("Vary", [...varyValues, "Accept"].join(", "));
2720
3126
  }
2721
- const alternatePath = getFarmMarkdownMirrorPath(markdownPageTarget.pathname);
2722
- const alternateLink = `<${alternatePath}>; rel="alternate"; type="text/markdown"`;
3127
+ const alternateLink = `<${markdownPageTarget.markdownPath}>; rel="alternate"; type="text/markdown"`;
2723
3128
  const currentLink = res.getHeader("Link");
2724
3129
  res.setHeader(
2725
3130
  "Link",
@@ -2764,13 +3169,14 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2764
3169
  return false;
2765
3170
  }
2766
3171
  const startTime2 = Date.now();
3172
+ let runtimeReportsErrors = false;
2767
3173
  try {
2768
3174
  if (pm) {
2769
3175
  await pm.runHookParallelFiltered(
2770
3176
  "beforeRequest",
2771
- (plugin) => {
2772
- const owner = getFarmIntegrationPluginOwner(plugin);
2773
- return plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME && (owner?.source !== "lifecycle" || owner.key !== matchedRoute.key);
3177
+ (plugin2) => {
3178
+ const owner = getFarmIntegrationPluginOwner(plugin2);
3179
+ return !isFarmConfigRoutePlugin(plugin2) && (owner?.source !== "lifecycle" || owner.key !== matchedRoute.key);
2774
3180
  },
2775
3181
  req,
2776
3182
  res
@@ -2797,22 +3203,29 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2797
3203
  body: toRequestBody(body),
2798
3204
  signal: createFarmNodeRequestAbortSignal(req, res)
2799
3205
  });
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`);
3206
+ const dispatchIntegration = async (request, runtime) => {
3207
+ try {
3208
+ const result = await dispatchIntegrationRequest(
3209
+ {
3210
+ integration: matchedRoute.integration,
3211
+ config: currentConfig,
3212
+ isDev: true,
3213
+ isProd: false
3214
+ },
3215
+ request,
3216
+ { clientAddress: req.socket?.remoteAddress }
3217
+ );
3218
+ if (!result) {
3219
+ throw new Error(`Matched integration route did not return a response`);
3220
+ }
3221
+ return result;
3222
+ } catch (error) {
3223
+ logger.error(`Integration route error: ${error}`);
3224
+ await runtime?.reportError(error);
3225
+ return createFarmInternalServerErrorResponse();
2813
3226
  }
2814
- return result;
2815
3227
  };
3228
+ runtimeReportsErrors = Boolean(pm);
2816
3229
  const response = pm ? await pm.runRuntimeRequest(integrationRequest, dispatchIntegration, {
2817
3230
  kind: "integration",
2818
3231
  route: {
@@ -2835,21 +3248,59 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2835
3248
  }
2836
3249
  const duration = Date.now() - startTime2;
2837
3250
  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
- });
3251
+ if (!runtimeReportsErrors) {
3252
+ await emitPluginError("integration-handler", error, {
3253
+ pathname: requestPathname,
3254
+ routePath: requestUrl,
3255
+ method: requestMethod,
3256
+ integration: matchedRoute.key
3257
+ });
3258
+ }
2844
3259
  logger.error(`Integration route error: ${error}`);
2845
3260
  if (!res.writableEnded) {
2846
3261
  res.statusCode = 500;
2847
3262
  res.setHeader("Content-Type", "application/json");
2848
- res.end(JSON.stringify({ error: "Internal server error" }));
3263
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
2849
3264
  }
2850
3265
  return true;
2851
3266
  }
2852
3267
  };
3268
+ if (pm && configRewriteSource === void 0 && configRoutePlugins.has(FARM_CONFIG_REWRITES_PLUGIN_NAME)) {
3269
+ const hasLocalDevRoute = () => {
3270
+ const routeManager3 = farmApp.getRouteManager();
3271
+ return Boolean(
3272
+ matchIntegrationRoute(configuredIntegrations, {
3273
+ pathname: requestPathname,
3274
+ method: requestMethod
3275
+ }) || routeManager3.matchRedirect(requestPathname) || apiRouteManager.matchRoute(requestPathname) || farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(requestPathname) || routeManager3.matchRoute(requestPathname).route || routeManager3.matchMetadataRoute(requestPathname) || routeManager3.matchMetadataImage(requestPathname)
3276
+ );
3277
+ };
3278
+ try {
3279
+ await pm.runHookParallelFiltered(
3280
+ "beforeRequest",
3281
+ (plugin2) => plugin2.name === FARM_CONFIG_REWRITES_PLUGIN_NAME,
3282
+ req,
3283
+ res
3284
+ );
3285
+ } catch (error) {
3286
+ await emitPluginError("before-request", error, { urlPath: requestUrl });
3287
+ res.statusCode = 500;
3288
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
3289
+ res.end("Internal Server Error");
3290
+ return;
3291
+ }
3292
+ if (req.url !== requestUrl) {
3293
+ if (isViteOwnedRequest() || hasLocalDevRoute()) {
3294
+ req.url = requestUrl;
3295
+ } else {
3296
+ if (await proxyFarmExternalRewrite(req, res, currentServerConfig.bodySizeLimit)) {
3297
+ return;
3298
+ }
3299
+ req[FARM_DEV_CONFIG_REWRITE_SOURCE] = fullUrl;
3300
+ return handleFarmDevRequest(req, res, next);
3301
+ }
3302
+ }
3303
+ }
2853
3304
  if (await tryConfiguredIntegrationRoute()) {
2854
3305
  return;
2855
3306
  }
@@ -2869,25 +3320,18 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2869
3320
  const pathname2 = resolveFarmRequestURL(req, {
2870
3321
  trustProxy: currentServerConfig.trustProxy
2871
3322
  }).pathname;
2872
- const servesLocalApiRoute = hasMatchedApiRoute || Boolean(
2873
- farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(requestPathname)
2874
- );
2875
3323
  try {
2876
3324
  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
- }
3325
+ await pm.runHookParallelFiltered(
3326
+ "beforeRequest",
3327
+ (plugin2) => !isFarmConfigRoutePlugin(plugin2),
3328
+ req,
3329
+ res
3330
+ );
2887
3331
  }
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");
3332
+ if (res.writableEnded) {
3333
+ const duration = Date.now() - startTime2;
3334
+ logResponse(method2, urlPath2, res.statusCode || 200, duration, "API");
2891
3335
  return;
2892
3336
  }
2893
3337
  } catch (error) {
@@ -2898,14 +3342,129 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2898
3342
  logger.error(`Request hook error: ${error}`);
2899
3343
  res.statusCode = 500;
2900
3344
  res.setHeader("Content-Type", "application/json");
2901
- res.end(JSON.stringify({ error: "Internal server error" }));
3345
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
2902
3346
  return;
2903
3347
  }
2904
- if (await runAppMiddlewareForContentRoute()) {
2905
- const duration2 = Date.now() - startTime2;
2906
- logResponse(method2, urlPath2, res.statusCode || 200, duration2, "API");
3348
+ const createAPIRequest = async () => {
3349
+ const headers = new Headers();
3350
+ for (const [key, value] of Object.entries(req.headers)) {
3351
+ if (value) {
3352
+ headers.set(key, Array.isArray(value) ? value.join(", ") : value);
3353
+ }
3354
+ }
3355
+ let body;
3356
+ if (req.method !== "GET" && req.method !== "HEAD") {
3357
+ body = await readNodeRequestBody(req, currentServerConfig.bodySizeLimit);
3358
+ }
3359
+ return new Request(`http://${req.headers.host || "localhost:3000"}${req.url}`, {
3360
+ method: req.method,
3361
+ headers,
3362
+ body: toRequestBody(body),
3363
+ signal: createFarmNodeRequestAbortSignal(req, res)
3364
+ });
3365
+ };
3366
+ const isDocsAPIRequest = Boolean(
3367
+ farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname2)
3368
+ );
3369
+ const docsRuntimeOptions = () => ({
3370
+ kind: "docs",
3371
+ route: setFarmRouteLabel(
3372
+ { pathname: pathname2, pattern: urlPath2 },
3373
+ resolveFarmDocsRouteLabel(pathname2, {
3374
+ path: farmConfig.docs?.entry || "/docs",
3375
+ roots: farmConfig.docs?.roots?.map((root) => root.entry)
3376
+ })
3377
+ )
3378
+ });
3379
+ let runtimeSession2;
3380
+ let sessionRequestUrl;
3381
+ if (pm?.hasRuntimeRequestHooks()) {
3382
+ try {
3383
+ runtimeSession2 = await pm.beginRuntimeRequest(
3384
+ await createAPIRequest(),
3385
+ !hasMatchedApiRoute && isDocsAPIRequest ? docsRuntimeOptions() : {
3386
+ kind: "api",
3387
+ route: matchedApiRoute ? { pathname: pathname2, pattern: matchedApiRoute.route.path } : { pathname: pathname2 }
3388
+ }
3389
+ );
3390
+ if (runtimeSession2.response) {
3391
+ const response = await pm.endRuntimeRequest(
3392
+ runtimeSession2,
3393
+ runtimeSession2.response
3394
+ );
3395
+ logResponse(method2, urlPath2, response.status, Date.now() - startTime2, "API");
3396
+ await sendWebResponse(res, response);
3397
+ return;
3398
+ }
3399
+ } catch (error) {
3400
+ const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);
3401
+ if (bodyErrorResponse) {
3402
+ logResponse(
3403
+ method2,
3404
+ urlPath2,
3405
+ bodyErrorResponse.status,
3406
+ Date.now() - startTime2,
3407
+ "API"
3408
+ );
3409
+ await sendWebResponse(res, bodyErrorResponse);
3410
+ return;
3411
+ }
3412
+ logger.error(`API route error: ${error}`);
3413
+ res.statusCode = 500;
3414
+ res.setHeader("Content-Type", "application/json");
3415
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3416
+ return;
3417
+ }
3418
+ pm.copyRequestContext(runtimeSession2.request, req);
3419
+ applyWebRequestToNodeRequest(runtimeSession2.request, req);
3420
+ sessionRequestUrl = req.url;
3421
+ }
3422
+ try {
3423
+ if (await runAppMiddlewareInRuntimeSession(
3424
+ runtimeSession2,
3425
+ (status) => logResponse(method2, urlPath2, status, Date.now() - startTime2, "API")
3426
+ )) {
3427
+ return;
3428
+ }
3429
+ } catch (error) {
3430
+ if (res.headersSent) {
3431
+ if (runtimeSession2) await pm.failRuntimeRequest(runtimeSession2, error);
3432
+ throw error;
3433
+ }
3434
+ logger.error(`Middleware error: ${error}`);
3435
+ let response = createFarmDevMiddlewareErrorResponse();
3436
+ if (runtimeSession2) {
3437
+ const errorResponse = response;
3438
+ try {
3439
+ response = await pm.completeRuntimeRequest(
3440
+ runtimeSession2,
3441
+ async (_request, runtime) => {
3442
+ await runtime.reportError(error);
3443
+ return errorResponse;
3444
+ }
3445
+ );
3446
+ } catch {
3447
+ logResponse(method2, urlPath2, 500, Date.now() - startTime2, "API");
3448
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
3449
+ return;
3450
+ }
3451
+ }
3452
+ logResponse(method2, urlPath2, response.status, Date.now() - startTime2, "API");
3453
+ await sendWebResponse(res, response);
2907
3454
  return;
2908
3455
  }
3456
+ const createHandlerRequest = async () => {
3457
+ if (runtimeSession2 && req.url === sessionRequestUrl && !runtimeSession2.request.bodyUsed) {
3458
+ return runtimeSession2.request;
3459
+ }
3460
+ const request = await createAPIRequest();
3461
+ if (runtimeSession2) pm.copyRequestContext(runtimeSession2.request, request);
3462
+ return request;
3463
+ };
3464
+ const runInRuntime = (request, handler, options2) => runtimeSession2 ? pm.completeRuntimeRequest(
3465
+ runtimeSession2,
3466
+ (_request, runtime) => handler(request, runtime)
3467
+ ) : pm ? pm.runRuntimeRequest(request, handler, options2) : handler(request);
2909
3468
  const apiHandler = apiRouteManager.getHandler({ throwOnError: true });
2910
3469
  const routedPathname = resolveFarmRequestURL(req, {
2911
3470
  trustProxy: currentServerConfig.trustProxy
@@ -2928,101 +3487,85 @@ window.__FARM_MANIFEST__ = ${inlineValue({
2928
3487
  });
2929
3488
  try {
2930
3489
  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
- });
3490
+ const request = await createHandlerRequest();
2947
3491
  const apiLifecyclePayload = {
2948
3492
  pathname: new URL(url).pathname,
2949
3493
  method: method2,
2950
3494
  routePath: apiRoutePattern
2951
3495
  };
2952
- const invokeAPIHandler = async (runtimeRequest) => {
3496
+ let apiHandlerFailed = false;
3497
+ const invokeAPIHandler = async (runtimeRequest, runtime) => {
2953
3498
  const handledRequest = pm ? await pm.runHookSerial(
2954
3499
  "beforeApiHandler",
2955
3500
  runtimeRequest,
2956
3501
  apiLifecyclePayload
2957
3502
  ) : runtimeRequest;
2958
- const response = await apiHandler(handledRequest);
3503
+ let response;
3504
+ try {
3505
+ response = await apiHandler(handledRequest);
3506
+ } catch (error) {
3507
+ apiHandlerFailed = true;
3508
+ emitFarmEvent({
3509
+ type: "api.error",
3510
+ pathname: pathname2,
3511
+ route: apiRoutePattern,
3512
+ method: method2,
3513
+ durationMs: Date.now() - startTime2,
3514
+ error
3515
+ });
3516
+ logger.error(`API route error: ${error}`);
3517
+ await runtime?.reportError(error);
3518
+ response = createFarmInternalServerErrorResponse();
3519
+ }
2959
3520
  return pm ? await pm.runHookSerial("afterApiHandler", response, apiLifecyclePayload) : response;
2960
3521
  };
2961
- const handledResponse = pm ? await pm.runRuntimeRequest(request, invokeAPIHandler, {
3522
+ const handledResponse = await runInRuntime(request, invokeAPIHandler, {
2962
3523
  kind: "api",
2963
3524
  route: {
2964
3525
  pathname: apiLifecyclePayload.pathname,
2965
3526
  pattern: apiLifecyclePayload.routePath
2966
3527
  }
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
3528
  });
2977
- logResponse(method2, urlPath2, handledResponse.status, duration2, "API");
3529
+ const duration = Date.now() - startTime2;
3530
+ if (!apiHandlerFailed) {
3531
+ emitFarmEvent({
3532
+ type: "api.request.complete",
3533
+ pathname: pathname2,
3534
+ route: apiRoutePattern,
3535
+ method: method2,
3536
+ status: handledResponse.status,
3537
+ durationMs: duration
3538
+ });
3539
+ }
3540
+ logResponse(method2, urlPath2, handledResponse.status, duration, "API");
2978
3541
  await sendWebResponse(res, handledResponse);
2979
3542
  return;
2980
3543
  } catch (error) {
2981
- const duration2 = Date.now() - startTime2;
3544
+ const duration = Date.now() - startTime2;
2982
3545
  emitFarmEvent({
2983
3546
  type: "api.error",
2984
3547
  pathname: pathname2,
2985
3548
  route: apiRoutePattern,
2986
3549
  method: method2,
2987
- durationMs: duration2,
3550
+ durationMs: duration,
2988
3551
  error
2989
3552
  });
2990
3553
  const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);
2991
3554
  if (bodyErrorResponse) {
2992
- logResponse(method2, urlPath2, bodyErrorResponse.status, duration2, "API");
3555
+ logResponse(method2, urlPath2, bodyErrorResponse.status, duration, "API");
2993
3556
  await sendWebResponse(res, bodyErrorResponse);
2994
3557
  return;
2995
3558
  }
2996
- await emitPluginError("api-handler", error, {
2997
- urlPath: urlPath2,
2998
- method: method2
2999
- });
3000
3559
  logger.error(`API route error: ${error}`);
3001
3560
  res.statusCode = 500;
3002
3561
  res.setHeader("Content-Type", "application/json");
3003
- res.end(JSON.stringify({ error: "Internal server error" }));
3562
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3004
3563
  return;
3005
3564
  }
3006
3565
  }
3007
- if (farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname2)) {
3566
+ if (farmDocsAPIHandler && isDocsAPIRequest) {
3008
3567
  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
- });
3568
+ const request = await createHandlerRequest();
3026
3569
  const apiLifecyclePayload = {
3027
3570
  pathname: pathname2,
3028
3571
  method: method2,
@@ -3040,19 +3583,14 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3040
3583
  }
3041
3584
  return pm ? await pm.runHookSerial("afterApiHandler", response, apiLifecyclePayload) : response;
3042
3585
  };
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);
3586
+ const docsResponse = await runInRuntime(
3587
+ request,
3588
+ invokeDocsAPIHandler,
3589
+ docsRuntimeOptions()
3590
+ );
3053
3591
  if (docsResponse) {
3054
- const duration2 = Date.now() - startTime2;
3055
- logResponse(method2, urlPath2, docsResponse.status, duration2, "API");
3592
+ const duration = Date.now() - startTime2;
3593
+ logResponse(method2, urlPath2, docsResponse.status, duration, "API");
3056
3594
  await sendWebResponse(res, docsResponse);
3057
3595
  return;
3058
3596
  }
@@ -3062,38 +3600,56 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3062
3600
  await sendWebResponse(res, bodyErrorResponse);
3063
3601
  return;
3064
3602
  }
3065
- await emitPluginError("docs-api-handler", error, {
3066
- urlPath: urlPath2,
3067
- method: method2
3068
- });
3069
3603
  logger.error(`Docs API route error: ${error}`);
3070
3604
  res.statusCode = 500;
3071
3605
  res.setHeader("Content-Type", "application/json");
3072
- res.end(JSON.stringify({ error: "Internal server error" }));
3606
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3073
3607
  return;
3074
3608
  }
3075
3609
  }
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 }));
3610
+ const notFoundBody = JSON.stringify({ error: "API route not found", pathname: pathname2 });
3611
+ if (!runtimeSession2) {
3612
+ logResponse(method2, urlPath2, 404, Date.now() - startTime2, "API");
3613
+ res.statusCode = 404;
3614
+ res.setHeader("Content-Type", "application/json");
3615
+ res.end(notFoundBody);
3616
+ return;
3617
+ }
3618
+ try {
3619
+ const response = await pm.completeRuntimeRequest(
3620
+ runtimeSession2,
3621
+ () => new Response(notFoundBody, {
3622
+ status: 404,
3623
+ headers: { "Content-Type": "application/json" }
3624
+ })
3625
+ );
3626
+ logResponse(method2, urlPath2, response.status, Date.now() - startTime2, "API");
3627
+ await sendWebResponse(res, response);
3628
+ } catch (error) {
3629
+ logger.error(`API route error: ${error}`);
3630
+ res.statusCode = 500;
3631
+ res.setHeader("Content-Type", "application/json");
3632
+ res.end(FARM_INTERNAL_SERVER_ERROR_BODY);
3633
+ }
3081
3634
  return;
3082
3635
  }
3083
3636
  if (req.url?.startsWith("/@") || req.url?.startsWith("/node_modules")) {
3084
3637
  return next();
3085
3638
  }
3086
- if (shouldBypassFarmRouterForDottedPath(
3639
+ if (!deferredDottedRequests.has(req) && shouldBypassFarmRouterForDottedPath(
3087
3640
  requestPathname,
3088
3641
  farmApp?.getRouteManager(),
3089
3642
  [server.config.publicDir, server.config.root],
3090
- farmAgentGeneratedPaths(farmConfig)
3643
+ farmAgentGeneratedPaths(farmConfig),
3644
+ requestMethod
3091
3645
  )) {
3646
+ if (!viteModuleRequest) deferredDottedRequests.set(req, requestUrl);
3092
3647
  return next();
3093
3648
  }
3094
3649
  if (req.url?.startsWith("/__farm/page-data")) {
3095
3650
  const urlObj = parsedRequestUrl;
3096
3651
  const targetPath = urlObj.searchParams.get("path") || "/";
3652
+ let renderedRequest;
3097
3653
  try {
3098
3654
  const request = createRequestFromNodeRequest(
3099
3655
  req,
@@ -3117,17 +3673,24 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3117
3673
  headers: request.headers,
3118
3674
  signal: request.signal
3119
3675
  });
3676
+ renderedRequest = targetRequest;
3120
3677
  let middlewareMap = /* @__PURE__ */ new Map();
3121
3678
  let middlewareContext = /* @__PURE__ */ new Map();
3122
3679
  if (middlewareManager?.hasMiddleware()) {
3123
3680
  const targetNodeRequest = createPageDataMiddlewareRequest(req, targetRequestUrl);
3681
+ const targetNodeResponse = createPageDataMiddlewareResponse(res);
3124
3682
  const handled = await runFarmMiddlewareWithNavigation(
3125
3683
  farmApp.getServerRenderer(),
3126
3684
  targetRequest,
3127
3685
  targetNodeRequest,
3128
- res,
3129
- () => middlewareManager.execute(targetNodeRequest, res)
3686
+ targetNodeResponse.response,
3687
+ () => middlewareManager.execute(targetNodeRequest, targetNodeResponse.response)
3130
3688
  );
3689
+ const middlewareRedirect = targetNodeResponse.redirect();
3690
+ if (middlewareRedirect) {
3691
+ await sendFarmPageDataRedirect(res, middlewareRedirect, farmConfig.deploymentId);
3692
+ return;
3693
+ }
3131
3694
  if (handled) return;
3132
3695
  middlewareMap = targetNodeRequest.__FARM_MIDDLEWARE_DATA__ ?? middlewareMap;
3133
3696
  middlewareContext = targetNodeRequest.__FARM_MIDDLEWARE_CONTEXT__ ?? middlewareContext;
@@ -3251,7 +3814,9 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3251
3814
  mergedMetadata = await mergeModuleViewport(mergedMetadata, routeModule, routeProps);
3252
3815
  mergedMetadata = addMetadataMarkdownAlternate(
3253
3816
  mergedMetadata,
3254
- getFarmMarkdownAlternatePath(farmApp.getConfig().md, targetRequestUrl.pathname)
3817
+ getFarmMarkdownAlternatePath(farmApp.getConfig().md, targetRequestUrl.pathname, {
3818
+ routePathname: (pathname2) => routeManager3.toRoutePathname(pathname2)
3819
+ })
3255
3820
  );
3256
3821
  const routeSlots = await Promise.all(
3257
3822
  slots.map(async (slot) => {
@@ -3410,6 +3975,11 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3410
3975
  });
3411
3976
  return;
3412
3977
  } catch (error) {
3978
+ const redirect = renderedRequest ? await farmApp.getServerRenderer().resolvePageDataRedirect(renderedRequest, error) : null;
3979
+ if (redirect && !res.headersSent) {
3980
+ await sendFarmPageDataRedirect(res, redirect, farmConfig.deploymentId);
3981
+ return;
3982
+ }
3413
3983
  const failure = resolveFarmPageDataFailure(error);
3414
3984
  if (failure.status >= 500) {
3415
3985
  await emitPluginError("page-data", error, {
@@ -3447,41 +4017,43 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3447
4017
  return routePathname === FARM_DEFAULT_MCP_PATH && farmApp.getServerRenderer().getDefaultMCPServer() ? FARM_DEFAULT_MCP_PATH : null;
3448
4018
  };
3449
4019
  let runtimeSession;
4020
+ let pathname = requestedPathname;
3450
4021
  if (pm && hasRuntimeRequestHooks) {
3451
4022
  try {
4023
+ const sessionOptions = {
4024
+ kind: "page",
4025
+ route: setFarmRouteLabel(
4026
+ {
4027
+ pathname: requestedPathname,
4028
+ pattern: requestedMatch?.route?.pattern || null,
4029
+ params: requestedMatch?.params || {}
4030
+ },
4031
+ requestedMatch?.route ? null : pageBuiltInRouteLabel(requestedPathname)
4032
+ )
4033
+ };
3452
4034
  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
- }
4035
+ createRequestFromNodeRequest(req, new URL(configRewriteSource ?? fullUrl)),
4036
+ sessionOptions
3465
4037
  );
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
- );
4038
+ const routedRequest = runtimeSession.response ?? (configRewriteSource === void 0 ? runtimeSession.request : await pm.runRuntimeBeforeForRewrite(
4039
+ runtimeSession.request,
4040
+ createRequestFromNodeRequest(req, new URL(fullUrl)),
4041
+ sessionOptions
4042
+ ));
4043
+ if (routedRequest instanceof Response) {
4044
+ const response = await pm.endRuntimeRequest(runtimeSession, routedRequest);
3473
4045
  await sendWebResponse(res, response);
3474
4046
  return;
3475
4047
  }
4048
+ pm.copyRequestContext(routedRequest, req);
4049
+ applyWebRequestToNodeRequest(routedRequest, req);
4050
+ pathname = new URL(routedRequest.url).pathname;
3476
4051
  } 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");
4052
+ if (runtimeSession) await pm.failRuntimeRequest(runtimeSession, error);
4053
+ sendFarmDevRuntimeHookError(res, runtimeHookErrorAnswersJSON);
3481
4054
  return;
3482
4055
  }
3483
4056
  }
3484
- const pathname = runtimeSession ? new URL(runtimeSession.request.url).pathname : requestedPathname;
3485
4057
  const routeMatch = pathname === requestedPathname ? requestedMatch : routeManager2.matchRoute(pathname);
3486
4058
  if (pm && hasBeforeRouteMatchHook) {
3487
4059
  await pm.runHookParallel("beforeRouteMatch", {
@@ -3521,8 +4093,10 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3521
4093
  pathname,
3522
4094
  startTime,
3523
4095
  logResponse,
3524
- emitError: (error) => emitPluginError("response-end", error, { pathname })
4096
+ emitError: (error) => emitPluginError("response-end", error, { pathname }),
4097
+ jsonError: runtimeHookErrorAnswersJSON
3525
4098
  }) : void 0;
4099
+ let middlewareFailed = false;
3526
4100
  try {
3527
4101
  if (middlewareManager?.hasMiddleware()) {
3528
4102
  const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));
@@ -3532,7 +4106,10 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3532
4106
  req,
3533
4107
  res,
3534
4108
  () => middlewareManager.execute(req, res)
3535
- );
4109
+ ).catch((error) => {
4110
+ middlewareFailed = true;
4111
+ throw error;
4112
+ });
3536
4113
  if (handled) {
3537
4114
  if (!responseInterceptor?.isEnded()) {
3538
4115
  const duration = Date.now() - startTime;
@@ -3542,42 +4119,14 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3542
4119
  }
3543
4120
  }
3544
4121
  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
4122
  await pm.runHookParallelFiltered(
3552
4123
  "beforeRequest",
3553
- (plugin) => !hasLocalPageRoute || plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,
4124
+ (plugin2) => !isFarmConfigRoutePlugin(plugin2),
3554
4125
  req,
3555
4126
  res
3556
4127
  );
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
4128
  }
3580
- if (res.writableEnded || responseInterceptor?.isEnded() || await proxyFarmExternalRewrite(req, res, currentServerConfig.bodySizeLimit)) {
4129
+ if (res.writableEnded || responseInterceptor?.isEnded()) {
3581
4130
  if (!responseInterceptor?.isEnded()) {
3582
4131
  const duration = Date.now() - startTime;
3583
4132
  logResponse(method, urlPath, res.statusCode || 200, duration, "PAGE");
@@ -3598,11 +4147,41 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3598
4147
  if (pm && runtimeSession) {
3599
4148
  await pm.failRuntimeRequest(runtimeSession, error);
3600
4149
  }
3601
- await emitPluginError("render-page", error, { pathname });
4150
+ if (!(middlewareFailed && runtimeSession)) {
4151
+ await emitPluginError("render-page", error, { pathname });
4152
+ }
4153
+ if (rendererDisabled && !res.headersSent) {
4154
+ sendFarmDevErrorJSON(res);
4155
+ return;
4156
+ }
4157
+ if (!res.headersSent) {
4158
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
4159
+ res.setHeader("Cache-Control", "private, no-store");
4160
+ }
3602
4161
  next(error);
3603
4162
  }
3604
4163
  })
3605
4164
  );
4165
+ const farmRequestMiddleware = farmMiddlewares.stack.at(-1)?.handle;
4166
+ if (farmOwnsDevCors && viteServer.config.server.cors === false) {
4167
+ farmMiddlewares.use(createFarmDevViteCorsMiddleware());
4168
+ }
4169
+ return () => {
4170
+ farmPostMiddlewares.use((req, res, next) => {
4171
+ if (res.headersSent || res.writableEnded) return next();
4172
+ const deferredUrl = deferredDottedRequests.get(req);
4173
+ if (deferredUrl !== void 0) {
4174
+ req.url = deferredUrl;
4175
+ return farmRequestMiddleware(req, res, next);
4176
+ }
4177
+ if (!rendererDisabled) return next();
4178
+ const requested = req.originalUrl ?? req.url ?? "/";
4179
+ const pathname = parseFarmRequestTarget(requested, "http://localhost").pathname;
4180
+ res.statusCode = 404;
4181
+ res.setHeader("Content-Type", "application/json");
4182
+ res.end(JSON.stringify({ error: "Not found", pathname }));
4183
+ });
4184
+ };
3606
4185
  },
3607
4186
  async resolveId(id, importer, resolveOptions) {
3608
4187
  if (typeof fontImports.resolveId === "function") {
@@ -3627,6 +4206,9 @@ window.__FARM_MANIFEST__ = ${inlineValue({
3627
4206
  }
3628
4207
  },
3629
4208
  async load(id, loadOptions) {
4209
+ if (pendingClientSetup && !loadOptions?.ssr && !farmSetupContext.getStore()) {
4210
+ await pendingClientSetup;
4211
+ }
3630
4212
  if (isFarmServerFnBoundaryId(id) && islandsServerFns()) {
3631
4213
  const file = id.split("?", 1)[0];
3632
4214
  this.addWatchFile(file);
@@ -3788,6 +4370,9 @@ export const manifest = getManifest();
3788
4370
  }
3789
4371
  },
3790
4372
  async transform(code, id, transformOptions) {
4373
+ if (pendingClientSetup && !transformOptions?.ssr && !farmSetupContext.getStore()) {
4374
+ await pendingClientSetup;
4375
+ }
3791
4376
  const actionConfig = farmApp?.getConfig() ?? options;
3792
4377
  let rewrotePackageImports = false;
3793
4378
  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)) {
@@ -3812,6 +4397,15 @@ export const manifest = getManifest();
3812
4397
  code = reactServer;
3813
4398
  rewrotePackageImports = true;
3814
4399
  }
4400
+ const internal = farmReactServerFiles.has(file) ? rewriteFarmReactServerClientModuleImports({
4401
+ code,
4402
+ file,
4403
+ reference: (clientFile) => ensureFarmInternalClientReference(projectRoot, clientFile)
4404
+ }) : null;
4405
+ if (internal !== null) {
4406
+ code = internal;
4407
+ rewrotePackageImports = true;
4408
+ }
3815
4409
  }
3816
4410
  const referenced = rewriteFarmPackageClientImports({
3817
4411
  code,
@@ -3934,6 +4528,7 @@ export const manifest = getManifest();
3934
4528
  islandStrategy: explicitStrategy ?? "load",
3935
4529
  parse: (source) => this.parse(source),
3936
4530
  slots: islandsMode,
4531
+ browser: transformOptions?.ssr !== true,
3937
4532
  inferredInteraction: inference?.strategy === "interaction"
3938
4533
  });
3939
4534
  if (!transformedBoundary) {
@@ -3999,6 +4594,7 @@ if (import.meta.hot) {
3999
4594
  if (typeof fontImports.generateBundle === "function") {
4000
4595
  await fontImports.generateBundle.call(this, options2, bundle, false);
4001
4596
  }
4597
+ if (rendererDisabled) return;
4002
4598
  const clientManifest = generateClientManifest(bundle);
4003
4599
  this.emitFile({
4004
4600
  type: "asset",
@@ -4105,6 +4701,7 @@ if (import.meta.hot) {
4105
4701
  invalidateFarmClientOnlyScan();
4106
4702
  },
4107
4703
  async handleHotUpdate(ctx) {
4704
+ if (pendingClientSetup && !farmSetupContext.getStore()) await pendingClientSetup;
4108
4705
  const { file, server: server2, modules } = ctx;
4109
4706
  if (initialPluginManager) {
4110
4707
  try {
@@ -4249,6 +4846,40 @@ if (import.meta.hot) {
4249
4846
  return modules;
4250
4847
  }
4251
4848
  };
4849
+ if (!deferredSetup) return plugin;
4850
+ const setUpDevServer = plugin.configureServer;
4851
+ let deferred = false;
4852
+ plugin.configureServer = function(viteServer) {
4853
+ if (deferred) {
4854
+ deferredGates = void 0;
4855
+ return setUpDevServer.call(this, viteServer);
4856
+ }
4857
+ deferred = true;
4858
+ const ready = () => deferredSetup.ready;
4859
+ deferredGates = {
4860
+ pre: createFarmDeferredMiddleware(ready),
4861
+ post: createFarmDeferredMiddleware(ready)
4862
+ };
4863
+ const setup = farmSetupContext.run(true, () => setUpDevServer.call(this, viteServer)).then((registerPostMiddleware) => {
4864
+ registerPostMiddleware();
4865
+ });
4866
+ viteServer.middlewares.use(deferredGates.pre.handle);
4867
+ deferredSetup.setup = setup;
4868
+ deferredSetup.ready = setup;
4869
+ pendingClientSetup = setup.then(
4870
+ () => {
4871
+ pendingClientSetup = null;
4872
+ },
4873
+ () => {
4874
+ pendingClientSetup = null;
4875
+ }
4876
+ );
4877
+ const post = deferredGates.post.handle;
4878
+ return () => {
4879
+ viteServer.middlewares.use(post);
4880
+ };
4881
+ };
4882
+ return plugin;
4252
4883
  }
4253
4884
  function runFarmMiddlewareWithNavigation(renderer, middlewareRequest, req, res, execute) {
4254
4885
  return renderer.runWithRequestContext(middlewareRequest, async () => {
@@ -4267,6 +4898,75 @@ function createPageDataMiddlewareRequest(req, target) {
4267
4898
  targetNodeRequest.method = "GET";
4268
4899
  return targetNodeRequest;
4269
4900
  }
4901
+ function createPageDataMiddlewareResponse(res) {
4902
+ let redirect = null;
4903
+ let passthrough = false;
4904
+ const captures = (status, location) => {
4905
+ if (redirect) return true;
4906
+ if (passthrough) return false;
4907
+ redirect = getFarmPageDataRedirectFromResponse(
4908
+ status,
4909
+ Array.isArray(location) ? location[0] : typeof location === "string" ? location : null
4910
+ );
4911
+ passthrough = !redirect;
4912
+ return !passthrough;
4913
+ };
4914
+ const response = new Proxy(res, {
4915
+ get(target, property) {
4916
+ if (property === "writeHead") {
4917
+ return (status, ...args) => {
4918
+ const headers = args.find((arg) => arg && typeof arg === "object");
4919
+ if (captures(status, readWriteHeadLocation(headers) ?? target.getHeader("location"))) {
4920
+ return response;
4921
+ }
4922
+ return target.writeHead(
4923
+ status,
4924
+ ...args
4925
+ );
4926
+ };
4927
+ }
4928
+ if (property === "write" || property === "end") {
4929
+ return (...args) => {
4930
+ if (captures(target.statusCode, target.getHeader("location"))) {
4931
+ const callback = args.find((arg) => typeof arg === "function");
4932
+ callback?.();
4933
+ return property === "write" ? true : response;
4934
+ }
4935
+ return target[property](...args);
4936
+ };
4937
+ }
4938
+ if (redirect && (property === "headersSent" || property === "writableEnded" || property === "finished")) {
4939
+ return true;
4940
+ }
4941
+ const value = Reflect.get(target, property, target);
4942
+ return typeof value === "function" ? value.bind(target) : value;
4943
+ },
4944
+ set(target, property, value) {
4945
+ return Reflect.set(target, property, value, target);
4946
+ }
4947
+ });
4948
+ return { response, redirect: () => redirect };
4949
+ }
4950
+ function readWriteHeadLocation(headers) {
4951
+ if (Array.isArray(headers)) {
4952
+ for (let index = 0; index + 1 < headers.length; index += 2) {
4953
+ if (String(headers[index]).toLowerCase() === "location") return headers[index + 1];
4954
+ }
4955
+ return void 0;
4956
+ }
4957
+ if (!headers || typeof headers !== "object") return void 0;
4958
+ for (const [name, value] of Object.entries(headers)) {
4959
+ if (name.toLowerCase() === "location") return value;
4960
+ }
4961
+ return void 0;
4962
+ }
4963
+ async function sendFarmPageDataRedirect(res, redirect, deploymentId) {
4964
+ for (const name of ["location", "content-length", "content-type"]) res.removeHeader(name);
4965
+ await sendWebResponse(
4966
+ res,
4967
+ withFarmDeploymentResponse(createFarmPageDataRedirectResponse(redirect), deploymentId)
4968
+ );
4969
+ }
4270
4970
  function resolveDevelopmentRoot(farmRoot, viteRoot) {
4271
4971
  if (!farmRoot) return viteRoot;
4272
4972
  if (path6.resolve(farmRoot) === path6.resolve(viteRoot)) return farmRoot;
@@ -5825,6 +6525,45 @@ function parseNavigationFragment(html) {
5825
6525
  return template.content;
5826
6526
  }
5827
6527
 
6528
+ // Suspense content streams, so a fresh response holds its fallback where the live DOM holds the
6529
+ // result. Compare without it.
6530
+ function removeSuspenseContent(root) {
6531
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
6532
+ const comments = [];
6533
+ while (walker.nextNode()) comments.push(walker.currentNode);
6534
+ let depth = 0;
6535
+ let start = null;
6536
+ for (const comment of comments) {
6537
+ if (comment.data === "$" || comment.data === "$?" || comment.data === "$!") {
6538
+ if (depth++ === 0) start = comment;
6539
+ } else if (comment.data === "/$" && depth > 0 && --depth === 0) {
6540
+ const range = document.createRange();
6541
+ range.setStartAfter(start);
6542
+ range.setEndBefore(comment);
6543
+ range.deleteContents();
6544
+ start.data = "$";
6545
+ }
6546
+ }
6547
+ }
6548
+
6549
+ // A layout's own server output, without what it wraps and without its islands, whose live DOM
6550
+ // always differs from fresh HTML.
6551
+ function getLayoutShell(root, patterns, index, find) {
6552
+ const shell = find(root, patterns[index])?.cloneNode(true);
6553
+ if (!shell) return null;
6554
+ const inner = index + 1 < patterns.length
6555
+ ? find(shell, patterns[index + 1])
6556
+ : shell.querySelector('#__farm_page__');
6557
+ inner?.replaceChildren();
6558
+ removeSuspenseContent(shell);
6559
+ shell.querySelectorAll('script').forEach((script) => script.remove());
6560
+ shell.querySelectorAll('f-island').forEach((island) => {
6561
+ island.replaceChildren();
6562
+ Array.from(island.attributes).forEach((attribute) => island.removeAttribute(attribute.name));
6563
+ });
6564
+ return shell.innerHTML;
6565
+ }
6566
+
5828
6567
  function replaceNavigationBoundary(
5829
6568
  container,
5830
6569
  fragment,
@@ -5837,7 +6576,11 @@ function replaceNavigationBoundary(
5837
6576
  while (
5838
6577
  sharedCount < currentPatterns.length &&
5839
6578
  sharedCount < nextPatterns.length &&
5840
- currentPatterns[sharedCount] === nextPatterns[sharedCount]
6579
+ currentPatterns[sharedCount] === nextPatterns[sharedCount] &&
6580
+ // A refresh renders every layout again: start at the first one whose output changed.
6581
+ (!refresh ||
6582
+ getLayoutShell(container, currentPatterns, sharedCount, find) ===
6583
+ getLayoutShell(fragment, nextPatterns, sharedCount, find))
5841
6584
  ) {
5842
6585
  sharedCount++;
5843
6586
  }
@@ -5938,7 +6681,8 @@ function farmDocumentNavigationRoute(pathname) {
5938
6681
  }
5939
6682
 
5940
6683
  async function fetchFarmNavigationDocument(path, context) {
5941
- farmNavigationStreamGeneration++;
6684
+ // A prefetch reads the page whole for the router's cache, and leaves a page that streams alone.
6685
+ if (!context.prefetch) farmNavigationStreamGeneration++;
5942
6686
  const url = new URL(path, window.location.href);
5943
6687
  const match = farmDocumentNavigationRoute(url.pathname);
5944
6688
  const container = document.getElementById('root');
@@ -5956,9 +6700,11 @@ async function fetchFarmNavigationDocument(path, context) {
5956
6700
  redirect: 'manual',
5957
6701
  headers: createFarmDeploymentRequestHeaders(deploymentId, {
5958
6702
  Accept: 'text/html',
5959
- 'F-Stream': 'flush',
6703
+ ...(context.prefetch ? {} : { 'F-Stream': 'flush' }),
5960
6704
  ...getFarmIslandValueHeaders(),
5961
- ...(identities.length ? { 'F-Layouts': JSON.stringify(identities) } : {}),
6705
+ // A prefetch names its layouts even when it keeps none: that marks it as a navigation,
6706
+ // which the server answers without loading.tsx.
6707
+ ...(identities.length || context.prefetch ? { 'F-Layouts': JSON.stringify(identities) } : {}),
5962
6708
  }),
5963
6709
  });
5964
6710
  if (isFarmDeploymentMismatchResponse(response, deploymentId)) {
@@ -5966,7 +6712,9 @@ async function fetchFarmNavigationDocument(path, context) {
5966
6712
  window.dispatchEvent(new CustomEvent('farm:deployment-mismatch', { detail: error }));
5967
6713
  throw error;
5968
6714
  }
5969
- // A redirect, an error or anything but HTML: the router loads the document instead.
6715
+ // A manual redirect hides its target, so page data answers this navigation and follows it.
6716
+ if (response.type === 'opaqueredirect') return null;
6717
+ // An error or anything but HTML: the router loads the document instead.
5970
6718
  if (
5971
6719
  !response.ok ||
5972
6720
  !response.body ||
@@ -5979,10 +6727,11 @@ async function fetchFarmNavigationDocument(path, context) {
5979
6727
  return { stream, doc, nextRoot: doc.getElementById('root') };
5980
6728
  };
5981
6729
  let result = await request(true);
5982
- if (result.nextRoot && !fitsFarmSegment(container, result.nextRoot)) {
6730
+ if (result && result.nextRoot && !fitsFarmSegment(container, result.nextRoot)) {
5983
6731
  result.stream.cancel?.();
5984
6732
  result = await request(false);
5985
6733
  }
6734
+ if (!result) return null;
5986
6735
  if (!result.nextRoot) {
5987
6736
  result.stream.cancel?.();
5988
6737
  throw new Error('The page has no #root');
@@ -6342,7 +7091,13 @@ function farmIslandsOnlyDocument() {
6342
7091
  // Islands mode hydrates the document, as production does, so islx also watches the islands
6343
7092
  // that stream in after this runs. Not cancelled by a navigation: an island it removes is
6344
7093
  // disposed with its DOM, and one in a layout it keeps still waits for its trigger.
7094
+ const hydrationSession = await farmClientRuntime.beginHydration({
7095
+ container: rootContainer || document.body,
7096
+ mode: 'hydrate',
7097
+ });
7098
+ // Each island reports and recovers its own failure, so this resolves once they are live.
6345
7099
  await hydrateFarmIsolatedClientBoundaries(${islandValues ? "document" : "rootContainer"});
7100
+ await farmClientRuntime.completeHydration(hydrationSession);
6346
7101
  // The rest of the document is static server HTML with nothing to hydrate, so
6347
7102
  // stop holding its clicks and submits once the load-strategy islands are live.
6348
7103
  // Deferred islands capture their own interactions, and held targets outside an