@farm.js/core 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (549) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +11 -0
  3. package/dist/after.cjs +227 -0
  4. package/dist/after.cjs.map +1 -0
  5. package/dist/after.d.mts +25 -0
  6. package/dist/after.d.ts +25 -0
  7. package/dist/after.mjs +14 -0
  8. package/dist/after.mjs.map +1 -0
  9. package/dist/agent-runtime.cjs +2379 -0
  10. package/dist/agent-runtime.cjs.map +1 -0
  11. package/dist/agent-runtime.d.mts +93 -0
  12. package/dist/agent-runtime.d.ts +93 -0
  13. package/dist/agent-runtime.mjs +479 -0
  14. package/dist/agent-runtime.mjs.map +1 -0
  15. package/dist/api/route-manager.cjs +1196 -0
  16. package/dist/api/route-manager.cjs.map +1 -0
  17. package/dist/api/route-manager.d.mts +64 -0
  18. package/dist/api/route-manager.d.ts +64 -0
  19. package/dist/api/route-manager.mjs +34 -0
  20. package/dist/api/route-manager.mjs.map +1 -0
  21. package/dist/api/runtime.cjs +272 -0
  22. package/dist/api/runtime.cjs.map +1 -0
  23. package/dist/api/runtime.d.mts +16 -0
  24. package/dist/api/runtime.d.ts +16 -0
  25. package/dist/api/runtime.mjs +16 -0
  26. package/dist/api/runtime.mjs.map +1 -0
  27. package/dist/api.cjs +3199 -0
  28. package/dist/api.cjs.map +1 -0
  29. package/dist/api.d.mts +190 -0
  30. package/dist/api.d.ts +190 -0
  31. package/dist/api.mjs +63 -0
  32. package/dist/api.mjs.map +1 -0
  33. package/dist/app-BiX4qb-d.d.mts +265 -0
  34. package/dist/app-CFRNJXP1.d.ts +265 -0
  35. package/dist/app-markdown.cjs +220 -0
  36. package/dist/app-markdown.cjs.map +1 -0
  37. package/dist/app-markdown.d.mts +21 -0
  38. package/dist/app-markdown.d.ts +21 -0
  39. package/dist/app-markdown.mjs +26 -0
  40. package/dist/app-markdown.mjs.map +1 -0
  41. package/dist/cache.cjs +543 -0
  42. package/dist/cache.cjs.map +1 -0
  43. package/dist/cache.d.mts +78 -0
  44. package/dist/cache.d.ts +78 -0
  45. package/dist/cache.mjs +38 -0
  46. package/dist/cache.mjs.map +1 -0
  47. package/dist/chunk-25D7G34K.mjs +142 -0
  48. package/dist/chunk-25D7G34K.mjs.map +1 -0
  49. package/dist/chunk-3QJO55ZF.mjs +3548 -0
  50. package/dist/chunk-3QJO55ZF.mjs.map +1 -0
  51. package/dist/chunk-3XNTL3FQ.mjs +452 -0
  52. package/dist/chunk-3XNTL3FQ.mjs.map +1 -0
  53. package/dist/chunk-44ZCFSKE.mjs +84 -0
  54. package/dist/chunk-44ZCFSKE.mjs.map +1 -0
  55. package/dist/chunk-4PTK6KT4.mjs +364 -0
  56. package/dist/chunk-4PTK6KT4.mjs.map +1 -0
  57. package/dist/chunk-4S3ORGFA.mjs +44 -0
  58. package/dist/chunk-4S3ORGFA.mjs.map +1 -0
  59. package/dist/chunk-5BY76U2M.mjs +1 -0
  60. package/dist/chunk-5BY76U2M.mjs.map +1 -0
  61. package/dist/chunk-5ZGPRGWV.mjs +136 -0
  62. package/dist/chunk-5ZGPRGWV.mjs.map +1 -0
  63. package/dist/chunk-6XDUHOEM.mjs +157 -0
  64. package/dist/chunk-6XDUHOEM.mjs.map +1 -0
  65. package/dist/chunk-74YTBPTY.mjs +450 -0
  66. package/dist/chunk-74YTBPTY.mjs.map +1 -0
  67. package/dist/chunk-7HO6AEOP.mjs +74 -0
  68. package/dist/chunk-7HO6AEOP.mjs.map +1 -0
  69. package/dist/chunk-7MABZJIM.mjs +29 -0
  70. package/dist/chunk-7MABZJIM.mjs.map +1 -0
  71. package/dist/chunk-7ZY5AIJO.mjs +161 -0
  72. package/dist/chunk-7ZY5AIJO.mjs.map +1 -0
  73. package/dist/chunk-AGS7UJ52.mjs +446 -0
  74. package/dist/chunk-AGS7UJ52.mjs.map +1 -0
  75. package/dist/chunk-AZ7YUVNR.mjs +65 -0
  76. package/dist/chunk-AZ7YUVNR.mjs.map +1 -0
  77. package/dist/chunk-B232I2GP.mjs +163 -0
  78. package/dist/chunk-B232I2GP.mjs.map +1 -0
  79. package/dist/chunk-B6N4ZB2H.mjs +718 -0
  80. package/dist/chunk-B6N4ZB2H.mjs.map +1 -0
  81. package/dist/chunk-BHG3LVHH.mjs +176 -0
  82. package/dist/chunk-BHG3LVHH.mjs.map +1 -0
  83. package/dist/chunk-C3DLZMBU.mjs +597 -0
  84. package/dist/chunk-C3DLZMBU.mjs.map +1 -0
  85. package/dist/chunk-CGILA3WO.mjs +14 -0
  86. package/dist/chunk-CGILA3WO.mjs.map +1 -0
  87. package/dist/chunk-CHFHNEMO.mjs +7088 -0
  88. package/dist/chunk-CHFHNEMO.mjs.map +1 -0
  89. package/dist/chunk-E2MPIBRE.mjs +149 -0
  90. package/dist/chunk-E2MPIBRE.mjs.map +1 -0
  91. package/dist/chunk-E6EPN5BT.mjs +203 -0
  92. package/dist/chunk-E6EPN5BT.mjs.map +1 -0
  93. package/dist/chunk-EVGBEZDF.mjs +215 -0
  94. package/dist/chunk-EVGBEZDF.mjs.map +1 -0
  95. package/dist/chunk-FQYDHKKU.mjs +128 -0
  96. package/dist/chunk-FQYDHKKU.mjs.map +1 -0
  97. package/dist/chunk-G3B5BRDY.mjs +5763 -0
  98. package/dist/chunk-G3B5BRDY.mjs.map +1 -0
  99. package/dist/chunk-GN72QAIH.mjs +146 -0
  100. package/dist/chunk-GN72QAIH.mjs.map +1 -0
  101. package/dist/chunk-GS6K5OCM.mjs +407 -0
  102. package/dist/chunk-GS6K5OCM.mjs.map +1 -0
  103. package/dist/chunk-GY2STC2S.mjs +180 -0
  104. package/dist/chunk-GY2STC2S.mjs.map +1 -0
  105. package/dist/chunk-GZP5W4K3.mjs +158 -0
  106. package/dist/chunk-GZP5W4K3.mjs.map +1 -0
  107. package/dist/chunk-H2FA2SBS.mjs +51 -0
  108. package/dist/chunk-H2FA2SBS.mjs.map +1 -0
  109. package/dist/chunk-HXP3ZSPC.mjs +211 -0
  110. package/dist/chunk-HXP3ZSPC.mjs.map +1 -0
  111. package/dist/chunk-ITN462YM.mjs +98 -0
  112. package/dist/chunk-ITN462YM.mjs.map +1 -0
  113. package/dist/chunk-J23HNLFY.mjs +72 -0
  114. package/dist/chunk-J23HNLFY.mjs.map +1 -0
  115. package/dist/chunk-J4FNJ5IU.mjs +179 -0
  116. package/dist/chunk-J4FNJ5IU.mjs.map +1 -0
  117. package/dist/chunk-JK25YEN6.mjs +219 -0
  118. package/dist/chunk-JK25YEN6.mjs.map +1 -0
  119. package/dist/chunk-JLWMCADZ.mjs +204 -0
  120. package/dist/chunk-JLWMCADZ.mjs.map +1 -0
  121. package/dist/chunk-JN3UU635.mjs +622 -0
  122. package/dist/chunk-JN3UU635.mjs.map +1 -0
  123. package/dist/chunk-K4667E2Q.mjs +1916 -0
  124. package/dist/chunk-K4667E2Q.mjs.map +1 -0
  125. package/dist/chunk-LGHEOHBU.mjs +218 -0
  126. package/dist/chunk-LGHEOHBU.mjs.map +1 -0
  127. package/dist/chunk-LLC7BNXW.mjs +275 -0
  128. package/dist/chunk-LLC7BNXW.mjs.map +1 -0
  129. package/dist/chunk-LM2YNO4U.mjs +24 -0
  130. package/dist/chunk-LM2YNO4U.mjs.map +1 -0
  131. package/dist/chunk-NNLCAVB6.mjs +391 -0
  132. package/dist/chunk-NNLCAVB6.mjs.map +1 -0
  133. package/dist/chunk-O3HADRW6.mjs +639 -0
  134. package/dist/chunk-O3HADRW6.mjs.map +1 -0
  135. package/dist/chunk-OYXO65LI.mjs +119 -0
  136. package/dist/chunk-OYXO65LI.mjs.map +1 -0
  137. package/dist/chunk-P7QDS5AT.mjs +191 -0
  138. package/dist/chunk-P7QDS5AT.mjs.map +1 -0
  139. package/dist/chunk-PRNYWD7K.mjs +599 -0
  140. package/dist/chunk-PRNYWD7K.mjs.map +1 -0
  141. package/dist/chunk-QF4PHCMA.mjs +422 -0
  142. package/dist/chunk-QF4PHCMA.mjs.map +1 -0
  143. package/dist/chunk-QFQRHRZS.mjs +1224 -0
  144. package/dist/chunk-QFQRHRZS.mjs.map +1 -0
  145. package/dist/chunk-QGOHVJ6J.mjs +63 -0
  146. package/dist/chunk-QGOHVJ6J.mjs.map +1 -0
  147. package/dist/chunk-QKVUNGAH.mjs +39 -0
  148. package/dist/chunk-QKVUNGAH.mjs.map +1 -0
  149. package/dist/chunk-QM6VV26B.mjs +149 -0
  150. package/dist/chunk-QM6VV26B.mjs.map +1 -0
  151. package/dist/chunk-RHIFZZUI.mjs +69 -0
  152. package/dist/chunk-RHIFZZUI.mjs.map +1 -0
  153. package/dist/chunk-RKI6TN3A.mjs +49 -0
  154. package/dist/chunk-RKI6TN3A.mjs.map +1 -0
  155. package/dist/chunk-RSKVYESE.mjs +187 -0
  156. package/dist/chunk-RSKVYESE.mjs.map +1 -0
  157. package/dist/chunk-S2XHZS7W.mjs +180 -0
  158. package/dist/chunk-S2XHZS7W.mjs.map +1 -0
  159. package/dist/chunk-SCFX4UTD.mjs +28 -0
  160. package/dist/chunk-SCFX4UTD.mjs.map +1 -0
  161. package/dist/chunk-SL6HTIOK.mjs +66 -0
  162. package/dist/chunk-SL6HTIOK.mjs.map +1 -0
  163. package/dist/chunk-SOU3Q3ZA.mjs +173 -0
  164. package/dist/chunk-SOU3Q3ZA.mjs.map +1 -0
  165. package/dist/chunk-SPBBQLXI.mjs +207 -0
  166. package/dist/chunk-SPBBQLXI.mjs.map +1 -0
  167. package/dist/chunk-SXZTEK3V.mjs +396 -0
  168. package/dist/chunk-SXZTEK3V.mjs.map +1 -0
  169. package/dist/chunk-T4QJQK76.mjs +459 -0
  170. package/dist/chunk-T4QJQK76.mjs.map +1 -0
  171. package/dist/chunk-TRORP7E4.mjs +41 -0
  172. package/dist/chunk-TRORP7E4.mjs.map +1 -0
  173. package/dist/chunk-TU4YJICB.mjs +728 -0
  174. package/dist/chunk-TU4YJICB.mjs.map +1 -0
  175. package/dist/chunk-TXCFGOHW.mjs +42 -0
  176. package/dist/chunk-TXCFGOHW.mjs.map +1 -0
  177. package/dist/chunk-UHE2TTLK.mjs +466 -0
  178. package/dist/chunk-UHE2TTLK.mjs.map +1 -0
  179. package/dist/chunk-UREJA4GZ.mjs +364 -0
  180. package/dist/chunk-UREJA4GZ.mjs.map +1 -0
  181. package/dist/chunk-USWZZUEH.mjs +25 -0
  182. package/dist/chunk-USWZZUEH.mjs.map +1 -0
  183. package/dist/chunk-UVCIEUJC.mjs +16 -0
  184. package/dist/chunk-UVCIEUJC.mjs.map +1 -0
  185. package/dist/chunk-V6WE6JSZ.mjs +352 -0
  186. package/dist/chunk-V6WE6JSZ.mjs.map +1 -0
  187. package/dist/chunk-V7RBCSDJ.mjs +170 -0
  188. package/dist/chunk-V7RBCSDJ.mjs.map +1 -0
  189. package/dist/chunk-VCANOYFI.mjs +588 -0
  190. package/dist/chunk-VCANOYFI.mjs.map +1 -0
  191. package/dist/chunk-WZ5QFROO.mjs +23 -0
  192. package/dist/chunk-WZ5QFROO.mjs.map +1 -0
  193. package/dist/chunk-Y2OJJD7R.mjs +543 -0
  194. package/dist/chunk-Y2OJJD7R.mjs.map +1 -0
  195. package/dist/chunk-Y7A27276.mjs +538 -0
  196. package/dist/chunk-Y7A27276.mjs.map +1 -0
  197. package/dist/chunk-YHU7SS6L.mjs +365 -0
  198. package/dist/chunk-YHU7SS6L.mjs.map +1 -0
  199. package/dist/chunk-ZBE6MLHL.mjs +230 -0
  200. package/dist/chunk-ZBE6MLHL.mjs.map +1 -0
  201. package/dist/chunk-ZJQNATYV.mjs +299 -0
  202. package/dist/chunk-ZJQNATYV.mjs.map +1 -0
  203. package/dist/client-D_yUjVhe.d.mts +402 -0
  204. package/dist/client-Dkc03WP8.d.ts +402 -0
  205. package/dist/client-cache-CIlyBlmx.d.ts +6 -0
  206. package/dist/client-cache-D-EZ7XVW.d.mts +6 -0
  207. package/dist/client-plugins-BZnpeTGA.d.ts +1848 -0
  208. package/dist/client-plugins-g4bzuCmo.d.mts +1848 -0
  209. package/dist/client-plugins.cjs +415 -0
  210. package/dist/client-plugins.cjs.map +1 -0
  211. package/dist/client-plugins.d.mts +21 -0
  212. package/dist/client-plugins.d.ts +21 -0
  213. package/dist/client-plugins.mjs +10 -0
  214. package/dist/client-plugins.mjs.map +1 -0
  215. package/dist/client.cjs +4571 -0
  216. package/dist/client.cjs.map +1 -0
  217. package/dist/client.d.mts +329 -0
  218. package/dist/client.d.ts +329 -0
  219. package/dist/client.mjs +103 -0
  220. package/dist/client.mjs.map +1 -0
  221. package/dist/config.cjs +38 -0
  222. package/dist/config.cjs.map +1 -0
  223. package/dist/config.d.mts +28 -0
  224. package/dist/config.d.ts +28 -0
  225. package/dist/config.mjs +10 -0
  226. package/dist/config.mjs.map +1 -0
  227. package/dist/cron.cjs +406 -0
  228. package/dist/cron.cjs.map +1 -0
  229. package/dist/cron.d.mts +78 -0
  230. package/dist/cron.d.ts +78 -0
  231. package/dist/cron.mjs +30 -0
  232. package/dist/cron.mjs.map +1 -0
  233. package/dist/deferred.cjs +438 -0
  234. package/dist/deferred.cjs.map +1 -0
  235. package/dist/deferred.d.mts +42 -0
  236. package/dist/deferred.d.ts +42 -0
  237. package/dist/deferred.mjs +28 -0
  238. package/dist/deferred.mjs.map +1 -0
  239. package/dist/deployment.cjs +199 -0
  240. package/dist/deployment.cjs.map +1 -0
  241. package/dist/deployment.d.mts +34 -0
  242. package/dist/deployment.d.ts +34 -0
  243. package/dist/deployment.mjs +38 -0
  244. package/dist/deployment.mjs.map +1 -0
  245. package/dist/devtools-AE4RVXCM.mjs +370 -0
  246. package/dist/devtools-AE4RVXCM.mjs.map +1 -0
  247. package/dist/devtools-client-6WPY2AQU.mjs +225 -0
  248. package/dist/devtools-client-6WPY2AQU.mjs.map +1 -0
  249. package/dist/devtools-ui-NJKFORTG.mjs +1349 -0
  250. package/dist/devtools-ui-NJKFORTG.mjs.map +1 -0
  251. package/dist/docs.cjs +5541 -0
  252. package/dist/docs.cjs.map +1 -0
  253. package/dist/docs.d.mts +69 -0
  254. package/dist/docs.d.ts +69 -0
  255. package/dist/docs.mjs +46 -0
  256. package/dist/docs.mjs.map +1 -0
  257. package/dist/env-types.cjs +223 -0
  258. package/dist/env-types.cjs.map +1 -0
  259. package/dist/env-types.d.mts +11 -0
  260. package/dist/env-types.d.ts +11 -0
  261. package/dist/env-types.mjs +9 -0
  262. package/dist/env-types.mjs.map +1 -0
  263. package/dist/env.cjs +215 -0
  264. package/dist/env.cjs.map +1 -0
  265. package/dist/env.d.mts +45 -0
  266. package/dist/env.d.ts +45 -0
  267. package/dist/env.mjs +22 -0
  268. package/dist/env.mjs.map +1 -0
  269. package/dist/environment/vite.cjs +374 -0
  270. package/dist/environment/vite.cjs.map +1 -0
  271. package/dist/environment/vite.d.mts +22 -0
  272. package/dist/environment/vite.d.ts +22 -0
  273. package/dist/environment/vite.mjs +10 -0
  274. package/dist/environment/vite.mjs.map +1 -0
  275. package/dist/environment.cjs +96 -0
  276. package/dist/environment.cjs.map +1 -0
  277. package/dist/environment.d.mts +18 -0
  278. package/dist/environment.d.ts +18 -0
  279. package/dist/environment.mjs +14 -0
  280. package/dist/environment.mjs.map +1 -0
  281. package/dist/headers.cjs +126 -0
  282. package/dist/headers.cjs.map +1 -0
  283. package/dist/headers.d.mts +22 -0
  284. package/dist/headers.d.ts +22 -0
  285. package/dist/headers.mjs +12 -0
  286. package/dist/headers.mjs.map +1 -0
  287. package/dist/i18n/client.cjs +283 -0
  288. package/dist/i18n/client.cjs.map +1 -0
  289. package/dist/i18n/client.d.mts +32 -0
  290. package/dist/i18n/client.d.ts +32 -0
  291. package/dist/i18n/client.mjs +121 -0
  292. package/dist/i18n/client.mjs.map +1 -0
  293. package/dist/i18n/index.cjs +130 -0
  294. package/dist/i18n/index.cjs.map +1 -0
  295. package/dist/i18n/index.d.mts +20 -0
  296. package/dist/i18n/index.d.ts +20 -0
  297. package/dist/i18n/index.mjs +22 -0
  298. package/dist/i18n/index.mjs.map +1 -0
  299. package/dist/i18n/server.cjs +637 -0
  300. package/dist/i18n/server.cjs.map +1 -0
  301. package/dist/i18n/server.d.mts +30 -0
  302. package/dist/i18n/server.d.ts +30 -0
  303. package/dist/i18n/server.mjs +32 -0
  304. package/dist/i18n/server.mjs.map +1 -0
  305. package/dist/image/server.cjs +477 -0
  306. package/dist/image/server.cjs.map +1 -0
  307. package/dist/image/server.d.mts +37 -0
  308. package/dist/image/server.d.ts +37 -0
  309. package/dist/image/server.mjs +16 -0
  310. package/dist/image/server.mjs.map +1 -0
  311. package/dist/image/sharp.cjs +135 -0
  312. package/dist/image/sharp.cjs.map +1 -0
  313. package/dist/image/sharp.d.mts +7 -0
  314. package/dist/image/sharp.d.ts +7 -0
  315. package/dist/image/sharp.mjs +75 -0
  316. package/dist/image/sharp.mjs.map +1 -0
  317. package/dist/image-config-Duob7wER.d.mts +50 -0
  318. package/dist/image-config-Duob7wER.d.ts +50 -0
  319. package/dist/image.cjs +209 -0
  320. package/dist/image.cjs.map +1 -0
  321. package/dist/image.d.mts +39 -0
  322. package/dist/image.d.ts +39 -0
  323. package/dist/image.mjs +165 -0
  324. package/dist/image.mjs.map +1 -0
  325. package/dist/index.cjs +39433 -0
  326. package/dist/index.cjs.map +1 -0
  327. package/dist/index.d.mts +451 -0
  328. package/dist/index.d.ts +451 -0
  329. package/dist/index.mjs +930 -0
  330. package/dist/index.mjs.map +1 -0
  331. package/dist/integration-api-CHT2OKAf.d.mts +93 -0
  332. package/dist/integration-api-CHT2OKAf.d.ts +93 -0
  333. package/dist/integration-orm-GQLGU66X.mjs +13 -0
  334. package/dist/integration-orm-GQLGU66X.mjs.map +1 -0
  335. package/dist/integrations.cjs +2820 -0
  336. package/dist/integrations.cjs.map +1 -0
  337. package/dist/integrations.d.mts +21 -0
  338. package/dist/integrations.d.ts +21 -0
  339. package/dist/integrations.mjs +51 -0
  340. package/dist/integrations.mjs.map +1 -0
  341. package/dist/internal/build-runtime.cjs +31340 -0
  342. package/dist/internal/build-runtime.cjs.map +1 -0
  343. package/dist/internal/build-runtime.d.mts +38 -0
  344. package/dist/internal/build-runtime.d.ts +38 -0
  345. package/dist/internal/build-runtime.mjs +73 -0
  346. package/dist/internal/build-runtime.mjs.map +1 -0
  347. package/dist/internal/client-runtime.cjs +579 -0
  348. package/dist/internal/client-runtime.cjs.map +1 -0
  349. package/dist/internal/client-runtime.d.mts +2 -0
  350. package/dist/internal/client-runtime.d.ts +2 -0
  351. package/dist/internal/client-runtime.mjs +12 -0
  352. package/dist/internal/client-runtime.mjs.map +1 -0
  353. package/dist/internal/config-runtime.cjs +4172 -0
  354. package/dist/internal/config-runtime.cjs.map +1 -0
  355. package/dist/internal/config-runtime.d.mts +38 -0
  356. package/dist/internal/config-runtime.d.ts +38 -0
  357. package/dist/internal/config-runtime.mjs +38 -0
  358. package/dist/internal/config-runtime.mjs.map +1 -0
  359. package/dist/internal/production-node-env.cjs +65 -0
  360. package/dist/internal/production-node-env.cjs.map +1 -0
  361. package/dist/internal/production-node-env.d.mts +12 -0
  362. package/dist/internal/production-node-env.d.ts +12 -0
  363. package/dist/internal/production-node-env.mjs +8 -0
  364. package/dist/internal/production-node-env.mjs.map +1 -0
  365. package/dist/internal/production-runtime.cjs +1896 -0
  366. package/dist/internal/production-runtime.cjs.map +1 -0
  367. package/dist/internal/production-runtime.d.mts +39 -0
  368. package/dist/internal/production-runtime.d.ts +39 -0
  369. package/dist/internal/production-runtime.mjs +79 -0
  370. package/dist/internal/production-runtime.mjs.map +1 -0
  371. package/dist/layers-VWVDTPUZ.mjs +16 -0
  372. package/dist/layers-VWVDTPUZ.mjs.map +1 -0
  373. package/dist/manager-THKFTOFE.mjs +10 -0
  374. package/dist/manager-THKFTOFE.mjs.map +1 -0
  375. package/dist/markdown.cjs +299 -0
  376. package/dist/markdown.cjs.map +1 -0
  377. package/dist/markdown.d.mts +43 -0
  378. package/dist/markdown.d.ts +43 -0
  379. package/dist/markdown.mjs +14 -0
  380. package/dist/markdown.mjs.map +1 -0
  381. package/dist/metadata-C9NZxMDW.d.mts +22 -0
  382. package/dist/metadata-DAXRaOHx.d.ts +22 -0
  383. package/dist/middleware.cjs +2148 -0
  384. package/dist/middleware.cjs.map +1 -0
  385. package/dist/middleware.d.mts +163 -0
  386. package/dist/middleware.d.ts +163 -0
  387. package/dist/middleware.mjs +49 -0
  388. package/dist/middleware.mjs.map +1 -0
  389. package/dist/navigation-errors-Dvwpzaer.d.mts +13 -0
  390. package/dist/navigation-errors-Dvwpzaer.d.ts +13 -0
  391. package/dist/navigation.cjs +1304 -0
  392. package/dist/navigation.cjs.map +1 -0
  393. package/dist/navigation.d.mts +14 -0
  394. package/dist/navigation.d.ts +14 -0
  395. package/dist/navigation.mjs +33 -0
  396. package/dist/navigation.mjs.map +1 -0
  397. package/dist/nitro-KME62MWG.mjs +691 -0
  398. package/dist/nitro-KME62MWG.mjs.map +1 -0
  399. package/dist/observability.cjs +186 -0
  400. package/dist/observability.cjs.map +1 -0
  401. package/dist/observability.d.mts +335 -0
  402. package/dist/observability.d.ts +335 -0
  403. package/dist/observability.mjs +16 -0
  404. package/dist/observability.mjs.map +1 -0
  405. package/dist/params-BALtrRim.d.ts +15 -0
  406. package/dist/params-ry-lxqmy.d.mts +15 -0
  407. package/dist/plugin-BJDf43dc.d.mts +165 -0
  408. package/dist/plugin-BJDf43dc.d.ts +165 -0
  409. package/dist/plugin.cjs +22285 -0
  410. package/dist/plugin.cjs.map +1 -0
  411. package/dist/plugin.d.mts +21 -0
  412. package/dist/plugin.d.ts +21 -0
  413. package/dist/plugin.mjs +60 -0
  414. package/dist/plugin.mjs.map +1 -0
  415. package/dist/production-runtime-C_B79w2P.d.mts +28 -0
  416. package/dist/production-runtime-DDEM1D2q.d.ts +28 -0
  417. package/dist/production-runtime-DRkCHUvJ.d.ts +79 -0
  418. package/dist/production-runtime-flrjp_nC.d.mts +79 -0
  419. package/dist/query/client.cjs +560 -0
  420. package/dist/query/client.cjs.map +1 -0
  421. package/dist/query/client.d.mts +61 -0
  422. package/dist/query/client.d.ts +61 -0
  423. package/dist/query/client.mjs +364 -0
  424. package/dist/query/client.mjs.map +1 -0
  425. package/dist/query/index.cjs +226 -0
  426. package/dist/query/index.cjs.map +1 -0
  427. package/dist/query/index.d.mts +90 -0
  428. package/dist/query/index.d.ts +90 -0
  429. package/dist/query/index.mjs +31 -0
  430. package/dist/query/index.mjs.map +1 -0
  431. package/dist/query/parsers.cjs +178 -0
  432. package/dist/query/parsers.cjs.map +1 -0
  433. package/dist/query/parsers.d.mts +25 -0
  434. package/dist/query/parsers.d.ts +25 -0
  435. package/dist/query/parsers.mjs +24 -0
  436. package/dist/query/parsers.mjs.map +1 -0
  437. package/dist/query/server.cjs +301 -0
  438. package/dist/query/server.cjs.map +1 -0
  439. package/dist/query/server.d.mts +55 -0
  440. package/dist/query/server.d.ts +55 -0
  441. package/dist/query/server.mjs +105 -0
  442. package/dist/query/server.mjs.map +1 -0
  443. package/dist/request-BrFBuc8G.d.mts +6 -0
  444. package/dist/request-BslSZIRz.d.ts +6 -0
  445. package/dist/request.cjs +71 -0
  446. package/dist/request.cjs.map +1 -0
  447. package/dist/request.d.mts +2 -0
  448. package/dist/request.d.ts +2 -0
  449. package/dist/request.mjs +9 -0
  450. package/dist/request.mjs.map +1 -0
  451. package/dist/resolver-C6iecsDV.d.ts +14 -0
  452. package/dist/resolver-DlOPpjkB.d.mts +14 -0
  453. package/dist/route-runtime-DoOHzCAD.d.mts +38 -0
  454. package/dist/route-runtime-DoOHzCAD.d.ts +38 -0
  455. package/dist/router.cjs +254 -0
  456. package/dist/router.cjs.map +1 -0
  457. package/dist/router.d.mts +36 -0
  458. package/dist/router.d.ts +36 -0
  459. package/dist/router.mjs +14 -0
  460. package/dist/router.mjs.map +1 -0
  461. package/dist/routes.cjs +1213 -0
  462. package/dist/routes.cjs.map +1 -0
  463. package/dist/routes.d.mts +224 -0
  464. package/dist/routes.d.ts +224 -0
  465. package/dist/routes.mjs +52 -0
  466. package/dist/routes.mjs.map +1 -0
  467. package/dist/runtime-B6GvwDS1.d.ts +27 -0
  468. package/dist/runtime-DeAAZ6gO.d.mts +27 -0
  469. package/dist/search-client-6OXIBNYQ.mjs +14 -0
  470. package/dist/search-client-6OXIBNYQ.mjs.map +1 -0
  471. package/dist/server-action-security.cjs +492 -0
  472. package/dist/server-action-security.cjs.map +1 -0
  473. package/dist/server-action-security.d.mts +42 -0
  474. package/dist/server-action-security.d.ts +42 -0
  475. package/dist/server-action-security.mjs +29 -0
  476. package/dist/server-action-security.mjs.map +1 -0
  477. package/dist/server-fn-client.cjs +180 -0
  478. package/dist/server-fn-client.cjs.map +1 -0
  479. package/dist/server-fn-client.d.mts +31 -0
  480. package/dist/server-fn-client.d.ts +31 -0
  481. package/dist/server-fn-client.mjs +9 -0
  482. package/dist/server-fn-client.mjs.map +1 -0
  483. package/dist/server-fn.cjs +284 -0
  484. package/dist/server-fn.cjs.map +1 -0
  485. package/dist/server-fn.d.mts +84 -0
  486. package/dist/server-fn.d.ts +84 -0
  487. package/dist/server-fn.mjs +17 -0
  488. package/dist/server-fn.mjs.map +1 -0
  489. package/dist/server-plugins.cjs +235 -0
  490. package/dist/server-plugins.cjs.map +1 -0
  491. package/dist/server-plugins.d.mts +54 -0
  492. package/dist/server-plugins.d.ts +54 -0
  493. package/dist/server-plugins.mjs +18 -0
  494. package/dist/server-plugins.mjs.map +1 -0
  495. package/dist/server-query-client.cjs +792 -0
  496. package/dist/server-query-client.cjs.map +1 -0
  497. package/dist/server-query-client.d.mts +50 -0
  498. package/dist/server-query-client.d.ts +50 -0
  499. package/dist/server-query-client.mjs +23 -0
  500. package/dist/server-query-client.mjs.map +1 -0
  501. package/dist/server-query.cjs +804 -0
  502. package/dist/server-query.cjs.map +1 -0
  503. package/dist/server-query.d.mts +36 -0
  504. package/dist/server-query.d.ts +36 -0
  505. package/dist/server-query.mjs +18 -0
  506. package/dist/server-query.mjs.map +1 -0
  507. package/dist/server.cjs +25739 -0
  508. package/dist/server.cjs.map +1 -0
  509. package/dist/server.d.mts +47 -0
  510. package/dist/server.d.ts +47 -0
  511. package/dist/server.mjs +511 -0
  512. package/dist/server.mjs.map +1 -0
  513. package/dist/storage.cjs +515 -0
  514. package/dist/storage.cjs.map +1 -0
  515. package/dist/storage.d.mts +52 -0
  516. package/dist/storage.d.ts +52 -0
  517. package/dist/storage.mjs +58 -0
  518. package/dist/storage.mjs.map +1 -0
  519. package/dist/testing.cjs +1882 -0
  520. package/dist/testing.cjs.map +1 -0
  521. package/dist/testing.d.mts +100 -0
  522. package/dist/testing.d.ts +100 -0
  523. package/dist/testing.mjs +324 -0
  524. package/dist/testing.mjs.map +1 -0
  525. package/dist/types-BH1lhg5G.d.mts +81 -0
  526. package/dist/types-BH1lhg5G.d.ts +81 -0
  527. package/dist/types-C9N-nk5R.d.mts +53 -0
  528. package/dist/types-C9N-nk5R.d.ts +53 -0
  529. package/dist/types-D1A6-XvH.d.mts +73 -0
  530. package/dist/types-D1A6-XvH.d.ts +73 -0
  531. package/dist/utils-DA1yo54_.d.ts +23 -0
  532. package/dist/utils-DOXXivjL.d.mts +23 -0
  533. package/dist/vite.cjs +22684 -0
  534. package/dist/vite.cjs.map +1 -0
  535. package/dist/vite.d.mts +21 -0
  536. package/dist/vite.d.ts +21 -0
  537. package/dist/vite.mjs +59 -0
  538. package/dist/vite.mjs.map +1 -0
  539. package/dist/workflows.cjs +586 -0
  540. package/dist/workflows.cjs.map +1 -0
  541. package/dist/workflows.d.mts +110 -0
  542. package/dist/workflows.d.ts +110 -0
  543. package/dist/workflows.mjs +32 -0
  544. package/dist/workflows.mjs.map +1 -0
  545. package/package.json +523 -0
  546. package/types/api.d.ts +88 -0
  547. package/types/client.d.ts +1171 -0
  548. package/types/index.d.ts +17 -0
  549. package/types/middleware.d.ts +266 -0
package/dist/api.cjs ADDED
@@ -0,0 +1,3199 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/api/index.ts
32
+ var api_exports = {};
33
+ __export(api_exports, {
34
+ APIRouteManager: () => APIRouteManager,
35
+ API_ROUTE_METHODS: () => API_ROUTE_METHODS,
36
+ DELETE: () => DELETE,
37
+ GET: () => GET,
38
+ HEAD: () => HEAD,
39
+ OPTIONS: () => OPTIONS,
40
+ PATCH: () => PATCH,
41
+ POST: () => POST,
42
+ PUT: () => PUT,
43
+ createAPIClient: () => createAPIClient,
44
+ createEndpoint: () => createEndpoint,
45
+ createServerAPIClient: () => createServerAPIClient,
46
+ farmApiPlugin: () => farmApiPlugin,
47
+ invokeAPIRouteEndpoint: () => invokeAPIRouteEndpoint,
48
+ isWebResponse: () => isWebResponse,
49
+ matchAPIRoute: () => matchAPIRoute,
50
+ normalizeRouteResponse: () => normalizeRouteResponse
51
+ });
52
+ module.exports = __toCommonJS(api_exports);
53
+
54
+ // src/api/endpoint.ts
55
+ var import_better_call = require("better-call");
56
+ function createEndpoint(pathOrOptions, optionsOrHandler, maybeHandler) {
57
+ let path4;
58
+ let options;
59
+ let handler;
60
+ if (typeof pathOrOptions === "string") {
61
+ path4 = pathOrOptions;
62
+ options = optionsOrHandler;
63
+ handler = maybeHandler;
64
+ } else {
65
+ path4 = "";
66
+ options = pathOrOptions;
67
+ handler = optionsOrHandler;
68
+ }
69
+ if (typeof handler !== "function") {
70
+ throw new TypeError("createEndpoint requires a handler function");
71
+ }
72
+ const middleware = normalizeEndpointMiddleware(options.middleware);
73
+ const wrappedHandler = /* @__PURE__ */ __name(((ctx) => runEndpointMiddleware(middleware, ctx, handler)), "wrappedHandler");
74
+ const { middleware: _middleware, ...betterCallOptions } = options;
75
+ const endpoint = (0, import_better_call.createEndpoint)(
76
+ path4 || "/__farm_auto_path__",
77
+ betterCallOptions,
78
+ wrappedHandler
79
+ );
80
+ endpoint.__path = path4 || void 0;
81
+ endpoint.__method = options.method || "GET";
82
+ endpoint.__autoPath = !path4;
83
+ endpoint.__handler = wrappedHandler;
84
+ endpoint.__middleware = middleware;
85
+ endpoint.__sourceHandler = handler;
86
+ endpoint.__types = {
87
+ body: options.body,
88
+ query: options.query,
89
+ headers: options.headers,
90
+ response: null
91
+ };
92
+ return endpoint;
93
+ }
94
+ __name(createEndpoint, "createEndpoint");
95
+ var EMPTY_ENDPOINT_MIDDLEWARE = Object.freeze([]);
96
+ var EMPTY_ENDPOINT_CONTEXT = Object.freeze(/* @__PURE__ */ Object.create(null));
97
+ var UNSAFE_ENDPOINT_CONTEXT_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
98
+ function normalizeEndpointMiddleware(middleware) {
99
+ if (middleware === void 0) return EMPTY_ENDPOINT_MIDDLEWARE;
100
+ if (!Array.isArray(middleware)) {
101
+ throw new TypeError("createEndpoint middleware must be an array of functions");
102
+ }
103
+ const normalized = [...middleware];
104
+ for (const entry of normalized) {
105
+ if (typeof entry !== "function") {
106
+ throw new TypeError("createEndpoint middleware entries must be functions");
107
+ }
108
+ }
109
+ return Object.freeze(normalized);
110
+ }
111
+ __name(normalizeEndpointMiddleware, "normalizeEndpointMiddleware");
112
+ async function runEndpointMiddleware(middleware, handlerContext, handler) {
113
+ let context = createInitialEndpointContext(handlerContext.context);
114
+ for (let index = 0; index < middleware.length; index++) {
115
+ const result = await middleware[index]({ ...handlerContext, context });
116
+ if (isEndpointResponse(result)) return result;
117
+ if (result === false) return forbiddenEndpointResponse();
118
+ if (result === true) continue;
119
+ if (!isPlainEndpointContext(result)) {
120
+ throw new TypeError(
121
+ `Endpoint middleware ${index + 1} must return an object, true, false, or a Response`
122
+ );
123
+ }
124
+ context = mergeEndpointContext(context, result, index);
125
+ }
126
+ return handler({ ...handlerContext, context });
127
+ }
128
+ __name(runEndpointMiddleware, "runEndpointMiddleware");
129
+ function createInitialEndpointContext(value) {
130
+ if (value === void 0 || value === null) return EMPTY_ENDPOINT_CONTEXT;
131
+ if (!isPlainEndpointContext(value)) {
132
+ throw new TypeError("Endpoint context must be a plain object");
133
+ }
134
+ return mergeEndpointContext(EMPTY_ENDPOINT_CONTEXT, value);
135
+ }
136
+ __name(createInitialEndpointContext, "createInitialEndpointContext");
137
+ function mergeEndpointContext(current, added, middlewareIndex) {
138
+ const next = Object.assign(/* @__PURE__ */ Object.create(null), current);
139
+ for (const key of Reflect.ownKeys(added)) {
140
+ if (!Object.prototype.propertyIsEnumerable.call(added, key)) continue;
141
+ if (typeof key === "string" && UNSAFE_ENDPOINT_CONTEXT_KEYS.has(key)) {
142
+ throw new TypeError(`Endpoint middleware cannot provide the unsafe context key "${key}"`);
143
+ }
144
+ if (Object.prototype.hasOwnProperty.call(current, key)) {
145
+ const source = middlewareIndex === void 0 ? "Endpoint context" : `Endpoint middleware ${middlewareIndex + 1}`;
146
+ throw new TypeError(`${source} cannot replace the existing context key "${String(key)}"`);
147
+ }
148
+ next[key] = added[key];
149
+ }
150
+ return Object.freeze(next);
151
+ }
152
+ __name(mergeEndpointContext, "mergeEndpointContext");
153
+ function isPlainEndpointContext(value) {
154
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
155
+ const prototype = Object.getPrototypeOf(value);
156
+ return prototype === Object.prototype || prototype === null;
157
+ }
158
+ __name(isPlainEndpointContext, "isPlainEndpointContext");
159
+ function isEndpointResponse(value) {
160
+ return value instanceof Response || typeof value === "object" && value !== null && "headers" in value && "status" in value && typeof value.arrayBuffer === "function";
161
+ }
162
+ __name(isEndpointResponse, "isEndpointResponse");
163
+ function forbiddenEndpointResponse() {
164
+ return new Response(JSON.stringify({ error: "Forbidden" }), {
165
+ status: 403,
166
+ headers: { "Content-Type": "application/json" }
167
+ });
168
+ }
169
+ __name(forbiddenEndpointResponse, "forbiddenEndpointResponse");
170
+ function GET(...args) {
171
+ if (args.length === 1) {
172
+ return createEndpoint("", { method: "GET" }, args[0]);
173
+ }
174
+ return createEndpoint("", { ...args[0], method: "GET" }, args[1]);
175
+ }
176
+ __name(GET, "GET");
177
+ function HEAD(...args) {
178
+ if (args.length === 1) {
179
+ return createEndpoint("", { method: "HEAD" }, args[0]);
180
+ }
181
+ return createEndpoint("", { ...args[0], method: "HEAD" }, args[1]);
182
+ }
183
+ __name(HEAD, "HEAD");
184
+ function POST(...args) {
185
+ if (args.length === 1) {
186
+ return createEndpoint("", { method: "POST" }, args[0]);
187
+ }
188
+ return createEndpoint("", { ...args[0], method: "POST" }, args[1]);
189
+ }
190
+ __name(POST, "POST");
191
+ function PUT(...args) {
192
+ if (args.length === 1) {
193
+ return createEndpoint("", { method: "PUT" }, args[0]);
194
+ }
195
+ return createEndpoint("", { ...args[0], method: "PUT" }, args[1]);
196
+ }
197
+ __name(PUT, "PUT");
198
+ function DELETE(...args) {
199
+ if (args.length === 1) {
200
+ return createEndpoint("", { method: "DELETE" }, args[0]);
201
+ }
202
+ return createEndpoint("", { ...args[0], method: "DELETE" }, args[1]);
203
+ }
204
+ __name(DELETE, "DELETE");
205
+ function PATCH(...args) {
206
+ if (args.length === 1) {
207
+ return createEndpoint("", { method: "PATCH" }, args[0]);
208
+ }
209
+ return createEndpoint("", { ...args[0], method: "PATCH" }, args[1]);
210
+ }
211
+ __name(PATCH, "PATCH");
212
+ function OPTIONS(...args) {
213
+ if (args.length === 1) {
214
+ return createEndpoint("", { method: "OPTIONS" }, args[0]);
215
+ }
216
+ return createEndpoint("", { ...args[0], method: "OPTIONS" }, args[1]);
217
+ }
218
+ __name(OPTIONS, "OPTIONS");
219
+
220
+ // src/api/route-manager.ts
221
+ var fs = __toESM(require("fs"));
222
+ var path3 = __toESM(require("path"));
223
+
224
+ // src/utils.ts
225
+ var import_path = __toESM(require("path"));
226
+ function toViteModuleId(filePath, root) {
227
+ if (!import_path.default.isAbsolute(filePath)) return filePath;
228
+ const relativePath = import_path.default.relative(root, filePath);
229
+ if (relativePath && !relativePath.startsWith("..") && !import_path.default.isAbsolute(relativePath)) {
230
+ return `/${relativePath.split(import_path.default.sep).join("/")}`;
231
+ }
232
+ const normalizedPath = filePath.replace(/\\/g, "/");
233
+ return normalizedPath.startsWith("/") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;
234
+ }
235
+ __name(toViteModuleId, "toViteModuleId");
236
+ var logger = {
237
+ info: /* @__PURE__ */ __name((message) => console.log(`[info] ${message}`), "info"),
238
+ success: /* @__PURE__ */ __name((message) => console.log(`[success] ${message}`), "success"),
239
+ warn: /* @__PURE__ */ __name((message) => console.warn(`\u26A0\uFE0F ${message}`), "warn"),
240
+ error: /* @__PURE__ */ __name((message) => console.error(`\u274C ${message}`), "error"),
241
+ ready: /* @__PURE__ */ __name((message) => console.log(`${message}`), "ready"),
242
+ event: /* @__PURE__ */ __name((message) => console.log(` ${message}`), "event")
243
+ };
244
+
245
+ // src/routes.ts
246
+ var import_react = require("react");
247
+
248
+ // src/observability.ts
249
+ var runtimeHandlers = /* @__PURE__ */ new Set();
250
+ var observabilityState = {
251
+ logs: false,
252
+ handlers: []
253
+ };
254
+ function emitFarmEvent(input) {
255
+ const event = {
256
+ timestamp: Date.now(),
257
+ level: inferFarmEventLevel(input.type),
258
+ ...input
259
+ };
260
+ if (!shouldEmitFarmEvent(event)) {
261
+ return event;
262
+ }
263
+ if (observabilityState.logs) {
264
+ logFarmEvent(event);
265
+ }
266
+ for (const handler of [...observabilityState.handlers, ...runtimeHandlers]) {
267
+ try {
268
+ Promise.resolve(handler(event)).catch((error) => {
269
+ console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
270
+ });
271
+ } catch (error) {
272
+ console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
273
+ }
274
+ }
275
+ return event;
276
+ }
277
+ __name(emitFarmEvent, "emitFarmEvent");
278
+ function shouldEmitFarmEvent(event) {
279
+ if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
280
+ return false;
281
+ }
282
+ if (observabilityState.events && !observabilityState.events.has(event.type)) {
283
+ return false;
284
+ }
285
+ return true;
286
+ }
287
+ __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
288
+ function inferFarmEventLevel(type) {
289
+ if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
290
+ return "error";
291
+ }
292
+ if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
293
+ return "warn";
294
+ }
295
+ if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
296
+ return "debug";
297
+ }
298
+ return "info";
299
+ }
300
+ __name(inferFarmEventLevel, "inferFarmEventLevel");
301
+ function logFarmEvent(event) {
302
+ const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
303
+ switch (event.level) {
304
+ case "error":
305
+ console.error(message);
306
+ break;
307
+ case "warn":
308
+ console.warn(message);
309
+ break;
310
+ default:
311
+ console.log(message);
312
+ break;
313
+ }
314
+ }
315
+ __name(logFarmEvent, "logFarmEvent");
316
+ function formatFarmEventDetails(event) {
317
+ const details = [];
318
+ const record = event;
319
+ for (const key of [
320
+ "route",
321
+ "pathname",
322
+ "method",
323
+ "status",
324
+ "key",
325
+ "tag",
326
+ "path",
327
+ "reason",
328
+ "durationMs",
329
+ "integration",
330
+ "operation",
331
+ "plugin",
332
+ "hook",
333
+ "target",
334
+ "count"
335
+ ]) {
336
+ const value = record[key];
337
+ if (value !== void 0) {
338
+ details.push(`${key}=${formatDetailValue(value)}`);
339
+ }
340
+ }
341
+ return details.length > 0 ? ` ${details.join(" ")}` : "";
342
+ }
343
+ __name(formatFarmEventDetails, "formatFarmEventDetails");
344
+ function formatDetailValue(value) {
345
+ if (typeof value === "string") {
346
+ return value;
347
+ }
348
+ if (typeof value === "number" || typeof value === "boolean") {
349
+ return String(value);
350
+ }
351
+ try {
352
+ return JSON.stringify(value);
353
+ } catch {
354
+ return String(value);
355
+ }
356
+ }
357
+ __name(formatDetailValue, "formatDetailValue");
358
+ function formatError(error) {
359
+ return error instanceof Error ? error.message : String(error);
360
+ }
361
+ __name(formatError, "formatError");
362
+
363
+ // src/cache-invalidation.ts
364
+ var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
365
+ var globalState = globalThis;
366
+ function getFarmCacheInvalidationState() {
367
+ return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
368
+ listeners: /* @__PURE__ */ new Set()
369
+ });
370
+ }
371
+ __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
372
+ function subscribeFarmCacheInvalidation(listener) {
373
+ const state = getFarmCacheInvalidationState();
374
+ state.listeners.add(listener);
375
+ return () => state.listeners.delete(listener);
376
+ }
377
+ __name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
378
+
379
+ // src/i18n/bridge.ts
380
+ var FARM_I18N_SNAPSHOT_RESOLVER = /* @__PURE__ */ Symbol.for("farm.i18n.snapshotResolver");
381
+ function _setFarmI18nSnapshotResolver(resolver) {
382
+ globalThis[FARM_I18N_SNAPSHOT_RESOLVER] = resolver;
383
+ }
384
+ __name(_setFarmI18nSnapshotResolver, "_setFarmI18nSnapshotResolver");
385
+
386
+ // src/cache.ts
387
+ var _FarmDataCache = class _FarmDataCache {
388
+ constructor() {
389
+ this.entries = /* @__PURE__ */ new Map();
390
+ this.inflight = /* @__PURE__ */ new Map();
391
+ this.invalidatedTagVersions = /* @__PURE__ */ new Map();
392
+ this.version = 0;
393
+ }
394
+ get size() {
395
+ return this.entries.size;
396
+ }
397
+ get(key, options = {}) {
398
+ return this.getEntry(key, options)?.value;
399
+ }
400
+ getEntry(key, options = {}) {
401
+ const entry = this.entries.get(key);
402
+ if (!entry) {
403
+ emitFarmEvent({ type: "cache.miss", key });
404
+ return void 0;
405
+ }
406
+ const stale = this.isStale(entry, options.now);
407
+ if (stale) {
408
+ emitFarmEvent({
409
+ type: "cache.stale",
410
+ key,
411
+ tags: Array.from(entry.tags),
412
+ revalidate: entry.revalidate
413
+ });
414
+ }
415
+ if (!options.allowStale && stale) {
416
+ emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
417
+ return void 0;
418
+ }
419
+ emitFarmEvent({
420
+ type: "cache.hit",
421
+ key,
422
+ tags: Array.from(entry.tags),
423
+ revalidate: entry.revalidate,
424
+ stale
425
+ });
426
+ return this.toPublicEntry(entry);
427
+ }
428
+ set(key, value, options = {}) {
429
+ const tags = /* @__PURE__ */ new Set();
430
+ for (const tag of options.tags ?? []) {
431
+ tags.add(normalizeCacheTag(tag));
432
+ }
433
+ for (const routePath of options.paths ?? []) {
434
+ tags.add(createPathCacheTag(routePath));
435
+ }
436
+ const entry = {
437
+ key,
438
+ value,
439
+ tags,
440
+ createdAt: options.createdAt ?? Date.now(),
441
+ createdVersion: ++this.version,
442
+ revalidate: normalizeRevalidate(options.revalidate)
443
+ };
444
+ this.entries.set(key, entry);
445
+ emitFarmEvent({
446
+ type: "cache.set",
447
+ key,
448
+ tags: Array.from(tags),
449
+ revalidate: entry.revalidate
450
+ });
451
+ return this.toPublicEntry(entry);
452
+ }
453
+ delete(key) {
454
+ const deleted = this.entries.delete(key);
455
+ emitFarmEvent({ type: "cache.delete", key, deleted });
456
+ return deleted;
457
+ }
458
+ clear() {
459
+ const count = this.entries.size;
460
+ this.entries.clear();
461
+ this.inflight.clear();
462
+ this.invalidatedTagVersions.clear();
463
+ this.version = 0;
464
+ emitFarmEvent({ type: "cache.clear", count });
465
+ }
466
+ isStale(entry, now = Date.now()) {
467
+ if (typeof entry.revalidate === "number" && entry.revalidate > 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
468
+ return true;
469
+ }
470
+ for (const tag of entry.tags) {
471
+ const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
472
+ if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
473
+ return true;
474
+ }
475
+ }
476
+ return false;
477
+ }
478
+ revalidateTag(tag, options = {}) {
479
+ const normalized = normalizeCacheTag(tag);
480
+ const count = this.invalidateTag(normalized);
481
+ emitFarmEvent(
482
+ options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
483
+ );
484
+ return count;
485
+ }
486
+ revalidatePath(routePath) {
487
+ const normalizedPath = normalizeRevalidatePath(routePath);
488
+ const pathTag = createPathCacheTag(normalizedPath);
489
+ const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
490
+ const count = this.invalidateTag(pathTag);
491
+ emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
492
+ if (pprCount > 0) {
493
+ emitFarmEvent({
494
+ type: "ppr.shell.invalidated",
495
+ route: normalizedPath,
496
+ reason: "revalidatePath",
497
+ count: pprCount
498
+ });
499
+ }
500
+ return count;
501
+ }
502
+ async getOrSet(key, producer, options = {}) {
503
+ const cached = this.getEntry(key);
504
+ if (cached) {
505
+ return cached.value;
506
+ }
507
+ const inflight = this.inflight.get(key);
508
+ if (inflight) {
509
+ emitFarmEvent({ type: "cache.dedupe", key });
510
+ return inflight;
511
+ }
512
+ const promise = Promise.resolve().then(producer).then((value) => {
513
+ this.set(key, value, options);
514
+ return value;
515
+ }).catch((error) => {
516
+ emitFarmEvent({ type: "cache.error", key, operation: "set", error });
517
+ throw error;
518
+ }).finally(() => {
519
+ this.inflight.delete(key);
520
+ });
521
+ this.inflight.set(key, promise);
522
+ return promise;
523
+ }
524
+ countEntriesForTag(tag) {
525
+ let count = 0;
526
+ for (const entry of this.entries.values()) {
527
+ if (entry.tags.has(tag)) {
528
+ count++;
529
+ }
530
+ }
531
+ return count;
532
+ }
533
+ countEntriesForTags(tags) {
534
+ let count = 0;
535
+ for (const entry of this.entries.values()) {
536
+ if (tags.every((tag) => entry.tags.has(tag))) {
537
+ count++;
538
+ }
539
+ }
540
+ return count;
541
+ }
542
+ invalidateTag(normalizedTag) {
543
+ this.invalidatedTagVersions.set(normalizedTag, ++this.version);
544
+ return this.countEntriesForTag(normalizedTag);
545
+ }
546
+ toPublicEntry(entry) {
547
+ return {
548
+ key: entry.key,
549
+ value: entry.value,
550
+ tags: Array.from(entry.tags),
551
+ createdAt: entry.createdAt,
552
+ createdVersion: entry.createdVersion,
553
+ revalidate: entry.revalidate
554
+ };
555
+ }
556
+ };
557
+ __name(_FarmDataCache, "FarmDataCache");
558
+ var FarmDataCache = _FarmDataCache;
559
+ var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
560
+ var farmDataCacheGlobal = globalThis;
561
+ var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
562
+ var functionIds = /* @__PURE__ */ new WeakMap();
563
+ var nextFunctionId = 0;
564
+ function createPathCacheTag(routePath) {
565
+ return `path:${normalizeRevalidatePath(routePath)}`;
566
+ }
567
+ __name(createPathCacheTag, "createPathCacheTag");
568
+ function createRouteDataCacheKey(key) {
569
+ return createFarmCacheKey(Array.isArray(key) ? key : [key]);
570
+ }
571
+ __name(createRouteDataCacheKey, "createRouteDataCacheKey");
572
+ function normalizeRevalidatePath(routePath) {
573
+ if (typeof routePath !== "string") {
574
+ throw new TypeError("revalidatePath expects a path string.");
575
+ }
576
+ let normalized = routePath.trim();
577
+ if (!normalized) {
578
+ throw new Error("revalidatePath expects a non-empty path.");
579
+ }
580
+ try {
581
+ if (/^https?:\/\//.test(normalized)) {
582
+ normalized = new URL(normalized).pathname;
583
+ }
584
+ } catch {
585
+ }
586
+ normalized = normalized.split("?")[0] ?? normalized;
587
+ normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
588
+ normalized = normalized.replace(/\/{2,}/g, "/");
589
+ if (normalized.length > 1) {
590
+ normalized = normalized.replace(/\/+$/, "");
591
+ }
592
+ return normalized || "/";
593
+ }
594
+ __name(normalizeRevalidatePath, "normalizeRevalidatePath");
595
+ function createFarmCacheKey(parts) {
596
+ return stableSerialize(parts);
597
+ }
598
+ __name(createFarmCacheKey, "createFarmCacheKey");
599
+ function normalizeRevalidate(revalidate) {
600
+ if (revalidate === false || revalidate === void 0) {
601
+ return revalidate;
602
+ }
603
+ if (!Number.isFinite(revalidate) || revalidate <= 0) {
604
+ return void 0;
605
+ }
606
+ return revalidate;
607
+ }
608
+ __name(normalizeRevalidate, "normalizeRevalidate");
609
+ function normalizeCacheTag(tag) {
610
+ if (typeof tag !== "string") {
611
+ throw new TypeError("Cache tags must be strings.");
612
+ }
613
+ const normalized = tag.trim();
614
+ if (!normalized) {
615
+ throw new Error("Cache tags cannot be empty.");
616
+ }
617
+ return normalized;
618
+ }
619
+ __name(normalizeCacheTag, "normalizeCacheTag");
620
+ function getFunctionCacheIdentity(fn) {
621
+ if (fn.name) {
622
+ return `name:${fn.name}`;
623
+ }
624
+ let id = functionIds.get(fn);
625
+ if (!id) {
626
+ id = ++nextFunctionId;
627
+ functionIds.set(fn, id);
628
+ }
629
+ return `anonymous:${id}`;
630
+ }
631
+ __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
632
+ function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
633
+ if (value === null) return "null";
634
+ if (value === void 0) return "undefined";
635
+ const valueType = typeof value;
636
+ if (valueType === "string") return JSON.stringify(value);
637
+ if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
638
+ return `${valueType}:${String(value)}`;
639
+ }
640
+ if (valueType === "symbol") {
641
+ return `symbol:${String(value)}`;
642
+ }
643
+ if (valueType === "function") {
644
+ return `function:${getFunctionCacheIdentity(value)}`;
645
+ }
646
+ if (value instanceof Date) {
647
+ return `date:${value.toISOString()}`;
648
+ }
649
+ if (value instanceof URL) {
650
+ return `url:${value.toString()}`;
651
+ }
652
+ if (value instanceof RegExp) {
653
+ return `regexp:${value.toString()}`;
654
+ }
655
+ if (Array.isArray(value)) {
656
+ return `[${value.map((item) => stableSerialize(item, seen)).join(",")}]`;
657
+ }
658
+ if (value && typeof value === "object") {
659
+ if (seen.has(value)) {
660
+ return "[Circular]";
661
+ }
662
+ seen.add(value);
663
+ const entries = Object.entries(value).sort(
664
+ ([a], [b]) => a.localeCompare(b)
665
+ );
666
+ const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
667
+ seen.delete(value);
668
+ return `{${serialized}}`;
669
+ }
670
+ return String(value);
671
+ }
672
+ __name(stableSerialize, "stableSerialize");
673
+
674
+ // src/route-runtime.ts
675
+ function normalizeFarmRouteRuntimeConfig(value, source = "Route configuration") {
676
+ if (!value) return {};
677
+ const normalized = {};
678
+ if (value.runtime !== void 0) {
679
+ if (value.runtime !== "auto" && value.runtime !== "node" && value.runtime !== "edge") {
680
+ throw new TypeError(`${source} runtime must be "auto", "node", or "edge"`);
681
+ }
682
+ normalized.runtime = value.runtime;
683
+ }
684
+ if (value.regions !== void 0) {
685
+ if (value.regions === "auto") {
686
+ normalized.regions = "auto";
687
+ } else {
688
+ if (!Array.isArray(value.regions) || value.regions.length === 0) {
689
+ throw new TypeError(`${source} regions must be "auto" or a non-empty string array`);
690
+ }
691
+ const regions = Array.from(
692
+ new Set(
693
+ value.regions.map((region) => {
694
+ if (typeof region !== "string" || !region.trim() || /[\u0000-\u001f\u007f]/.test(region)) {
695
+ throw new TypeError(`${source} regions must contain non-empty region identifiers`);
696
+ }
697
+ return region.trim();
698
+ })
699
+ )
700
+ );
701
+ normalized.regions = regions;
702
+ }
703
+ }
704
+ if (value.maxDuration !== void 0) {
705
+ if (value.maxDuration === "auto") {
706
+ normalized.maxDuration = "auto";
707
+ } else if (typeof value.maxDuration !== "number" || !Number.isInteger(value.maxDuration) || value.maxDuration <= 0) {
708
+ throw new TypeError(`${source} maxDuration must be "auto" or a positive integer in seconds`);
709
+ } else {
710
+ normalized.maxDuration = value.maxDuration;
711
+ }
712
+ }
713
+ return normalized;
714
+ }
715
+ __name(normalizeFarmRouteRuntimeConfig, "normalizeFarmRouteRuntimeConfig");
716
+ function getFarmRouteRuntimeConfig(value) {
717
+ if (!value || typeof value !== "object") return {};
718
+ const route = value;
719
+ return {
720
+ ...route.runtime !== void 0 ? { runtime: route.runtime } : {},
721
+ ...route.regions !== void 0 ? { regions: route.regions } : {},
722
+ ...route.maxDuration !== void 0 ? { maxDuration: route.maxDuration } : {}
723
+ };
724
+ }
725
+ __name(getFarmRouteRuntimeConfig, "getFarmRouteRuntimeConfig");
726
+
727
+ // src/routes.ts
728
+ var FARM_ROUTES_BRAND = /* @__PURE__ */ Symbol.for("farm.routes");
729
+ var PROGRAMMATIC_ROUTE_FILE_NAMES = [
730
+ "farm.route.ts",
731
+ "farm.route.tsx",
732
+ "farm.route.js",
733
+ "farm.route.jsx",
734
+ "farm.routes.ts",
735
+ "farm.routes.tsx",
736
+ "farm.routes.js",
737
+ "farm.routes.jsx",
738
+ "routes.ts",
739
+ "routes.tsx",
740
+ "routes.js",
741
+ "routes.jsx"
742
+ ];
743
+ function defineRoutes(input) {
744
+ const routes = typeof input === "function" ? input(routesBuilder) : input;
745
+ const manifest = {
746
+ __farmRoutes: true,
747
+ routes: routes.map(normalizeProgrammaticRoute)
748
+ };
749
+ Object.defineProperty(manifest, FARM_ROUTES_BRAND, {
750
+ value: true,
751
+ enumerable: false
752
+ });
753
+ return manifest;
754
+ }
755
+ __name(defineRoutes, "defineRoutes");
756
+ var routesBuilder = {
757
+ page(path4, options) {
758
+ return normalizeProgrammaticRoute({
759
+ kind: "page",
760
+ path: path4,
761
+ ...options
762
+ });
763
+ },
764
+ layout(path4, options) {
765
+ return normalizeProgrammaticRoute({
766
+ kind: "layout",
767
+ path: path4,
768
+ ...options
769
+ });
770
+ },
771
+ api(path4, options) {
772
+ const { render, runtime, regions, maxDuration, ...methods } = options;
773
+ return normalizeProgrammaticRoute({
774
+ kind: "api",
775
+ path: path4,
776
+ render,
777
+ runtime,
778
+ regions,
779
+ maxDuration,
780
+ methods: normalizeApiMethods(methods)
781
+ });
782
+ },
783
+ redirect(source, destination, options = {}) {
784
+ return normalizeProgrammaticRoute({
785
+ kind: "redirect",
786
+ source,
787
+ destination,
788
+ ...options
789
+ });
790
+ }
791
+ };
792
+ var page = routesBuilder.page;
793
+ var layout = routesBuilder.layout;
794
+ var api = routesBuilder.api;
795
+ var redirect = routesBuilder.redirect;
796
+ function isProgrammaticRoutesFileName(fileName) {
797
+ const normalized = fileName.replace(/\\/g, "/");
798
+ const baseName = normalized.split("/").pop() || normalized;
799
+ return PROGRAMMATIC_ROUTE_FILE_NAMES.includes(baseName);
800
+ }
801
+ __name(isProgrammaticRoutesFileName, "isProgrammaticRoutesFileName");
802
+ function getProgrammaticRouteManifest(mod) {
803
+ if (!mod) return null;
804
+ const candidates = [mod.default, mod.routes, mod.Route];
805
+ for (const candidate of candidates) {
806
+ if (isProgrammaticRouteManifest(candidate)) {
807
+ return candidate;
808
+ }
809
+ if (isProgrammaticRouteDefinition(candidate)) {
810
+ return defineRoutes([candidate]);
811
+ }
812
+ if (Array.isArray(candidate)) {
813
+ return defineRoutes(candidate);
814
+ }
815
+ }
816
+ const routeDefinitions = Object.values(mod).filter(isProgrammaticRouteDefinition);
817
+ if (routeDefinitions.length > 0) {
818
+ return defineRoutes(routeDefinitions);
819
+ }
820
+ return null;
821
+ }
822
+ __name(getProgrammaticRouteManifest, "getProgrammaticRouteManifest");
823
+ function isProgrammaticRouteManifest(value) {
824
+ return !!value && typeof value === "object" && value.__farmRoutes === true && Array.isArray(value.routes);
825
+ }
826
+ __name(isProgrammaticRouteManifest, "isProgrammaticRouteManifest");
827
+ function isProgrammaticRouteDefinition(value) {
828
+ if (!value || typeof value !== "object") {
829
+ return false;
830
+ }
831
+ const kind = value.kind;
832
+ return kind === "page" || kind === "layout" || kind === "api" || kind === "redirect";
833
+ }
834
+ __name(isProgrammaticRouteDefinition, "isProgrammaticRouteDefinition");
835
+ function createProgrammaticRouteModuleId(filePath, kind, routePath) {
836
+ return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeRoutePath(routePath))}`;
837
+ }
838
+ __name(createProgrammaticRouteModuleId, "createProgrammaticRouteModuleId");
839
+ function normalizeProgrammaticRoute(route) {
840
+ if (route.kind === "redirect") {
841
+ return {
842
+ ...route,
843
+ source: normalizeRoutePath(route.source)
844
+ };
845
+ }
846
+ if (route.kind === "api") {
847
+ return {
848
+ ...route,
849
+ ...normalizeFarmRouteRuntimeConfig(route, `API route "${route.path}"`),
850
+ path: normalizeRoutePath(route.path),
851
+ methods: normalizeApiMethods(route.methods)
852
+ };
853
+ }
854
+ return {
855
+ ...route,
856
+ ...normalizeFarmRouteRuntimeConfig(
857
+ route,
858
+ `${route.kind === "layout" ? "Layout" : "Route"} "${route.path}"`
859
+ ),
860
+ path: normalizeRoutePath(route.path)
861
+ };
862
+ }
863
+ __name(normalizeProgrammaticRoute, "normalizeProgrammaticRoute");
864
+ function normalizeRoutePath(routePath) {
865
+ const withSlash = routePath.startsWith("/") ? routePath : `/${routePath}`;
866
+ const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
867
+ return withoutTrailing || "/";
868
+ }
869
+ __name(normalizeRoutePath, "normalizeRoutePath");
870
+ function normalizeApiMethods(methods) {
871
+ const normalized = {};
872
+ for (const [method, handler] of Object.entries(methods)) {
873
+ const normalizedMethod = method.toUpperCase();
874
+ if (handler && isProgrammaticRouteMethod(normalizedMethod)) {
875
+ normalized[normalizedMethod] = handler;
876
+ }
877
+ }
878
+ return normalized;
879
+ }
880
+ __name(normalizeApiMethods, "normalizeApiMethods");
881
+ function isProgrammaticRouteMethod(method) {
882
+ return method === "GET" || method === "HEAD" || method === "POST" || method === "PUT" || method === "DELETE" || method === "PATCH" || method === "OPTIONS";
883
+ }
884
+ __name(isProgrammaticRouteMethod, "isProgrammaticRouteMethod");
885
+
886
+ // src/routes.server.ts
887
+ var import_fs = require("fs");
888
+ var import_path2 = require("path");
889
+ function findProgrammaticRouteFilesInDir(srcRoot) {
890
+ const files = [];
891
+ for (const fileName of PROGRAMMATIC_ROUTE_FILE_NAMES) {
892
+ const filePath = (0, import_path2.join)(srcRoot, fileName);
893
+ if ((0, import_fs.existsSync)(filePath)) {
894
+ files.push(filePath);
895
+ }
896
+ }
897
+ return files;
898
+ }
899
+ __name(findProgrammaticRouteFilesInDir, "findProgrammaticRouteFilesInDir");
900
+
901
+ // src/i18n/server.ts
902
+ var import_node_async_hooks = require("async_hooks");
903
+
904
+ // src/i18n/runtime.ts
905
+ var import_intl_messageformat = __toESM(require("intl-messageformat"));
906
+
907
+ // src/i18n/catalog.ts
908
+ var import_promises = require("fs/promises");
909
+ var import_icu_messageformat_parser = require("@formatjs/icu-messageformat-parser");
910
+
911
+ // src/i18n/config.ts
912
+ var import_node_path = __toESM(require("path"));
913
+ var DEFAULT_FARM_I18N_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
914
+
915
+ // src/i18n/server.ts
916
+ var FARM_I18N_REQUEST_STORE = /* @__PURE__ */ Symbol.for("farm.i18n.requestStore");
917
+ function getRequestStore() {
918
+ const state = globalThis;
919
+ return state[FARM_I18N_REQUEST_STORE] ?? (state[FARM_I18N_REQUEST_STORE] = new import_node_async_hooks.AsyncLocalStorage());
920
+ }
921
+ __name(getRequestStore, "getRequestStore");
922
+ function getState() {
923
+ const state = getRequestStore().getStore();
924
+ if (!state) {
925
+ throw new Error(
926
+ "No Farm i18n request context is active. Use this API while rendering, inside an API route, or use createTranslator(locale)."
927
+ );
928
+ }
929
+ return state;
930
+ }
931
+ __name(getState, "getState");
932
+ async function _runWithFarmI18nRequest(runtime, request, fn, options = {}) {
933
+ const resolution = runtime.resolveRequest(request, options);
934
+ const state = {
935
+ runtime,
936
+ resolution,
937
+ snapshot: runtime.getClientSnapshot(resolution)
938
+ };
939
+ return getRequestStore().run(state, () => fn(resolution));
940
+ }
941
+ __name(_runWithFarmI18nRequest, "_runWithFarmI18nRequest");
942
+ var t = createTranslatorFromState(() => getState());
943
+ function getFarmI18nClientSnapshot() {
944
+ return getRequestStore().getStore()?.snapshot;
945
+ }
946
+ __name(getFarmI18nClientSnapshot, "getFarmI18nClientSnapshot");
947
+ function createTranslatorFromState(resolveState) {
948
+ const translator = /* @__PURE__ */ __name(((key, values) => {
949
+ const state = resolveState();
950
+ return state.runtime.translate(state.resolution.locale, key, values);
951
+ }), "translator");
952
+ translator.rich = (key, values) => {
953
+ const state = resolveState();
954
+ return state.runtime.translateRich(state.resolution.locale, key, values);
955
+ };
956
+ translator.raw = (key) => {
957
+ const state = resolveState();
958
+ return state.runtime.getRawMessage(state.resolution.locale, key);
959
+ };
960
+ translator.has = (key) => {
961
+ const state = resolveState();
962
+ return state.runtime.hasMessage(state.resolution.locale, key);
963
+ };
964
+ return translator;
965
+ }
966
+ __name(createTranslatorFromState, "createTranslatorFromState");
967
+ _setFarmI18nSnapshotResolver(() => getFarmI18nClientSnapshot());
968
+
969
+ // src/server/request.ts
970
+ var import_node_async_hooks2 = require("async_hooks");
971
+
972
+ // src/server/request-bridge.ts
973
+ var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
974
+ function getGlobalState() {
975
+ return globalThis;
976
+ }
977
+ __name(getGlobalState, "getGlobalState");
978
+ function _setCurrentRequestResolver(resolver) {
979
+ getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;
980
+ }
981
+ __name(_setCurrentRequestResolver, "_setCurrentRequestResolver");
982
+
983
+ // src/server/request.ts
984
+ var REQUEST_STORAGE_KEY = /* @__PURE__ */ Symbol.for("@farm.js/core/request-storage");
985
+ function getRequestStore2() {
986
+ const runtime = globalThis;
987
+ const existing = runtime[REQUEST_STORAGE_KEY];
988
+ if (existing instanceof import_node_async_hooks2.AsyncLocalStorage) {
989
+ return existing;
990
+ }
991
+ const storage = new import_node_async_hooks2.AsyncLocalStorage();
992
+ runtime[REQUEST_STORAGE_KEY] = storage;
993
+ return storage;
994
+ }
995
+ __name(getRequestStore2, "getRequestStore");
996
+ var requestStore = getRequestStore2();
997
+ _setCurrentRequestResolver(() => requestStore.getStore());
998
+ async function _runWithCurrentRequest(request, fn) {
999
+ return requestStore.run(request, fn);
1000
+ }
1001
+ __name(_runWithCurrentRequest, "_runWithCurrentRequest");
1002
+
1003
+ // src/api/runtime.ts
1004
+ function matchAPIRoute(routes, pathname) {
1005
+ const exactRoute = routes.get(pathname);
1006
+ if (exactRoute) {
1007
+ return { route: exactRoute, params: {} };
1008
+ }
1009
+ const normalizedPathname = normalizePathname(pathname);
1010
+ if (normalizedPathname !== pathname) {
1011
+ const normalizedRoute = routes.get(normalizedPathname);
1012
+ if (normalizedRoute) {
1013
+ return { route: normalizedRoute, params: {} };
1014
+ }
1015
+ }
1016
+ for (const route of routes.values()) {
1017
+ const params = matchRoutePath(route.path, pathname);
1018
+ if (params) {
1019
+ return { route, params };
1020
+ }
1021
+ }
1022
+ return null;
1023
+ }
1024
+ __name(matchAPIRoute, "matchAPIRoute");
1025
+ async function invokeAPIRouteEndpoint(endpoint, request, params = {}) {
1026
+ return _runWithCurrentRequest(
1027
+ request,
1028
+ () => invokeAPIRouteEndpointInContext(endpoint, request, params)
1029
+ );
1030
+ }
1031
+ __name(invokeAPIRouteEndpoint, "invokeAPIRouteEndpoint");
1032
+ async function invokeAPIRouteEndpointInContext(endpoint, request, params) {
1033
+ const farmHandler = endpoint.__handler || (isFarmContextHandler(endpoint) ? endpoint : null);
1034
+ if (!farmHandler) {
1035
+ const result2 = await endpoint(request, {
1036
+ params: Promise.resolve(params)
1037
+ });
1038
+ return normalizeRouteResponse(result2);
1039
+ }
1040
+ const url = new URL(request.url);
1041
+ const query = {};
1042
+ url.searchParams.forEach((value, key) => {
1043
+ query[key] = value;
1044
+ });
1045
+ let body = void 0;
1046
+ if (request.method.toUpperCase() !== "GET" && request.method.toUpperCase() !== "HEAD") {
1047
+ body = await readJSONBody(request);
1048
+ }
1049
+ const headers = Object.fromEntries(request.headers.entries());
1050
+ const types = endpoint.__types || {};
1051
+ const queryValidation = validateInput(types.query, query, "Invalid query parameters");
1052
+ if (queryValidation instanceof Response) {
1053
+ return queryValidation;
1054
+ }
1055
+ const bodyValidation = validateInput(types.body, body, "Invalid request body");
1056
+ if (bodyValidation instanceof Response) {
1057
+ return bodyValidation;
1058
+ }
1059
+ const headersValidation = validateInput(types.headers, headers, "Invalid request headers");
1060
+ if (headersValidation instanceof Response) {
1061
+ return headersValidation;
1062
+ }
1063
+ const result = await farmHandler({
1064
+ query: queryValidation,
1065
+ body: bodyValidation,
1066
+ headers: headersValidation,
1067
+ request,
1068
+ context: {},
1069
+ params
1070
+ });
1071
+ return normalizeRouteResponse(result);
1072
+ }
1073
+ __name(invokeAPIRouteEndpointInContext, "invokeAPIRouteEndpointInContext");
1074
+ function normalizeRouteResponse(result) {
1075
+ if (isWebResponse(result)) {
1076
+ return result;
1077
+ }
1078
+ if (result === void 0) {
1079
+ return new Response(null, { status: 204 });
1080
+ }
1081
+ return new Response(JSON.stringify(result), {
1082
+ status: 200,
1083
+ headers: { "Content-Type": "application/json" }
1084
+ });
1085
+ }
1086
+ __name(normalizeRouteResponse, "normalizeRouteResponse");
1087
+ function isWebResponse(value) {
1088
+ return value instanceof Response || typeof value === "object" && value !== null && "headers" in value && "status" in value && typeof value.arrayBuffer === "function";
1089
+ }
1090
+ __name(isWebResponse, "isWebResponse");
1091
+ function isFarmContextHandler(endpoint) {
1092
+ if (typeof endpoint !== "function") {
1093
+ return false;
1094
+ }
1095
+ const source = Function.prototype.toString.call(endpoint).trim();
1096
+ const arrowMatch = source.match(/^(?:async\s*)?(?:\(([^)]*)\)|([A-Za-z_$][\w$]*))\s*=>/);
1097
+ const functionMatch = source.match(/^(?:async\s*)?function[^(]*\(([^)]*)\)/);
1098
+ const firstParameter = (arrowMatch?.[1] || arrowMatch?.[2] || functionMatch?.[1] || "").split(",")[0].trim();
1099
+ return firstParameter === "ctx" || firstParameter === "context" || firstParameter.startsWith("{");
1100
+ }
1101
+ __name(isFarmContextHandler, "isFarmContextHandler");
1102
+ async function readJSONBody(request) {
1103
+ try {
1104
+ const text = await request.clone().text();
1105
+ if (text) {
1106
+ return JSON.parse(text);
1107
+ }
1108
+ } catch {
1109
+ }
1110
+ return void 0;
1111
+ }
1112
+ __name(readJSONBody, "readJSONBody");
1113
+ function validateInput(schema, value, error) {
1114
+ if (!schema || typeof schema.parse !== "function") {
1115
+ return value;
1116
+ }
1117
+ try {
1118
+ return schema.parse(value);
1119
+ } catch (validationError) {
1120
+ return new Response(
1121
+ JSON.stringify({
1122
+ error,
1123
+ details: validationError.errors || validationError.issues || validationError.message
1124
+ }),
1125
+ {
1126
+ status: 400,
1127
+ headers: { "Content-Type": "application/json" }
1128
+ }
1129
+ );
1130
+ }
1131
+ }
1132
+ __name(validateInput, "validateInput");
1133
+ function matchRoutePath(routePath, pathname) {
1134
+ const routeSegments = getPathSegments(routePath);
1135
+ const pathnameSegments = getPathSegments(pathname);
1136
+ const params = {};
1137
+ let pathIndex = 0;
1138
+ for (const routeSegment of routeSegments) {
1139
+ const dynamicSegment = parseDynamicSegment(routeSegment);
1140
+ if (dynamicSegment?.catchAll) {
1141
+ const remainingSegments = pathnameSegments.slice(pathIndex).map(decodePathSegment);
1142
+ if (remainingSegments.length === 0 && !dynamicSegment.optional) {
1143
+ return null;
1144
+ }
1145
+ if (remainingSegments.length > 0) {
1146
+ params[dynamicSegment.name] = remainingSegments;
1147
+ }
1148
+ pathIndex = pathnameSegments.length;
1149
+ continue;
1150
+ }
1151
+ const pathnameSegment = pathnameSegments[pathIndex];
1152
+ if (pathnameSegment === void 0) {
1153
+ return null;
1154
+ }
1155
+ if (dynamicSegment) {
1156
+ params[dynamicSegment.name] = decodePathSegment(pathnameSegment);
1157
+ pathIndex++;
1158
+ continue;
1159
+ }
1160
+ if (routeSegment !== pathnameSegment) {
1161
+ return null;
1162
+ }
1163
+ pathIndex++;
1164
+ }
1165
+ return pathIndex === pathnameSegments.length ? params : null;
1166
+ }
1167
+ __name(matchRoutePath, "matchRoutePath");
1168
+ function getPathSegments(pathname) {
1169
+ return normalizePathname(pathname).split("/").filter((segment) => segment.length > 0);
1170
+ }
1171
+ __name(getPathSegments, "getPathSegments");
1172
+ function normalizePathname(pathname) {
1173
+ if (pathname.length > 1 && pathname.endsWith("/")) {
1174
+ return pathname.replace(/\/+$/, "");
1175
+ }
1176
+ return pathname;
1177
+ }
1178
+ __name(normalizePathname, "normalizePathname");
1179
+ function parseDynamicSegment(segment) {
1180
+ const optionalCatchAll = segment.match(/^\[\[\.\.\.(.+)\]\]$/);
1181
+ if (optionalCatchAll?.[1]) {
1182
+ return { name: optionalCatchAll[1], catchAll: true, optional: true };
1183
+ }
1184
+ const catchAll = segment.match(/^\[\.\.\.(.+)\]$/);
1185
+ if (catchAll?.[1]) {
1186
+ return { name: catchAll[1], catchAll: true, optional: false };
1187
+ }
1188
+ const dynamic = segment.match(/^\[(.+)\]$/);
1189
+ if (dynamic?.[1]) {
1190
+ return { name: dynamic[1], catchAll: false, optional: false };
1191
+ }
1192
+ return null;
1193
+ }
1194
+ __name(parseDynamicSegment, "parseDynamicSegment");
1195
+ function decodePathSegment(segment) {
1196
+ try {
1197
+ return decodeURIComponent(segment);
1198
+ } catch {
1199
+ return segment;
1200
+ }
1201
+ }
1202
+ __name(decodePathSegment, "decodePathSegment");
1203
+
1204
+ // src/api/route-manager.ts
1205
+ var API_ROUTE_METHODS = [
1206
+ "GET",
1207
+ "HEAD",
1208
+ "POST",
1209
+ "PUT",
1210
+ "DELETE",
1211
+ "PATCH",
1212
+ "OPTIONS"
1213
+ ];
1214
+ var _APIRouteManager = class _APIRouteManager {
1215
+ constructor(appDir, viteServer, options = {}) {
1216
+ this.routes = /* @__PURE__ */ new Map();
1217
+ this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir];
1218
+ this.viteServer = viteServer;
1219
+ this.throwOnLoadError = options.throwOnLoadError === true;
1220
+ this.i18n = options.i18n;
1221
+ }
1222
+ /**
1223
+ * Discover route.ts files in /app/api and explicit endpoints in root routes.ts
1224
+ */
1225
+ async discoverRoutes() {
1226
+ this.routes.clear();
1227
+ for (const appDir of this.appDirs) {
1228
+ const apiDir = path3.join(appDir, "api");
1229
+ let routeFiles = [];
1230
+ if (fs.existsSync(apiDir)) {
1231
+ routeFiles = this.findRouteFiles(apiDir);
1232
+ }
1233
+ for (const filePath of routeFiles) {
1234
+ await this.loadRoute(filePath, appDir);
1235
+ }
1236
+ await this.loadRootRoutes(appDir);
1237
+ await this.loadProgrammaticApiRoutes(appDir);
1238
+ }
1239
+ if (process.env.FARM_VERBOSE) {
1240
+ logger.success(`Discovered ${this.routes.size} API routes`);
1241
+ for (const [routePath, route] of this.routes) {
1242
+ logger.info(` ${route.methods.join(", ")} ${routePath}`);
1243
+ }
1244
+ }
1245
+ }
1246
+ /**
1247
+ * Recursively find all route.ts files
1248
+ */
1249
+ findRouteFiles(dir) {
1250
+ const files = [];
1251
+ if (!fs.existsSync(dir)) {
1252
+ return files;
1253
+ }
1254
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
1255
+ for (const entry of entries) {
1256
+ const fullPath = path3.join(dir, entry.name);
1257
+ if (entry.isDirectory()) {
1258
+ files.push(...this.findRouteFiles(fullPath));
1259
+ } else if (entry.name === "route.ts" || entry.name === "route.tsx" || entry.name === "route.js") {
1260
+ files.push(fullPath);
1261
+ }
1262
+ }
1263
+ return files;
1264
+ }
1265
+ /**
1266
+ * Load a route.ts file and extract HTTP method exports
1267
+ */
1268
+ async loadRoute(filePath, appDir) {
1269
+ try {
1270
+ const apiDir = path3.join(appDir, "api");
1271
+ const relativePath = path3.relative(apiDir, path3.dirname(filePath));
1272
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
1273
+ const routeModule = await this.loadModule(filePath);
1274
+ const endpoints = {};
1275
+ const availableMethods = [];
1276
+ for (const method of API_ROUTE_METHODS) {
1277
+ if (routeModule[method]) {
1278
+ endpoints[method] = routeModule[method];
1279
+ availableMethods.push(method);
1280
+ }
1281
+ }
1282
+ if (availableMethods.length > 0) {
1283
+ const runtimeConfig = normalizeFarmRouteRuntimeConfig(
1284
+ getFarmRouteRuntimeConfig(routeModule),
1285
+ `API route "${routePath}"`
1286
+ );
1287
+ this.routes.set(routePath, {
1288
+ path: routePath,
1289
+ filePath,
1290
+ methods: availableMethods,
1291
+ endpoints,
1292
+ ...runtimeConfig
1293
+ });
1294
+ }
1295
+ } catch (error) {
1296
+ this.handleLoadError(`Error loading route ${filePath}`, error);
1297
+ }
1298
+ }
1299
+ /**
1300
+ * Load explicit-path endpoints from src/routes.ts-style files.
1301
+ */
1302
+ async loadRootRoutes(appDir) {
1303
+ const routesFile = this.findRootRoutesFile(appDir);
1304
+ if (!routesFile) {
1305
+ return;
1306
+ }
1307
+ try {
1308
+ const routesModule = await this.loadModule(routesFile);
1309
+ for (const exportValue of Object.values(routesModule)) {
1310
+ const endpoint = exportValue;
1311
+ if (!endpoint?.__path) {
1312
+ continue;
1313
+ }
1314
+ const method = String(endpoint.__method || "GET").toUpperCase();
1315
+ this.addEndpoint(endpoint.__path, routesFile, method, endpoint);
1316
+ }
1317
+ } catch (error) {
1318
+ this.handleLoadError(`Error loading root API routes ${routesFile}`, error);
1319
+ }
1320
+ }
1321
+ async loadProgrammaticApiRoutes(appDir) {
1322
+ const candidateRoots = [path3.dirname(appDir), appDir];
1323
+ const routeFiles = Array.from(
1324
+ new Set(candidateRoots.flatMap((srcRoot) => findProgrammaticRouteFilesInDir(srcRoot)))
1325
+ );
1326
+ for (const routeFile of routeFiles) {
1327
+ try {
1328
+ const routesModule = await this.loadModule(routeFile);
1329
+ const manifest = getProgrammaticRouteManifest(routesModule);
1330
+ if (!manifest) continue;
1331
+ for (const definition of manifest.routes) {
1332
+ if (definition.kind !== "api") continue;
1333
+ this.addProgrammaticApiRoute(routeFile, definition);
1334
+ }
1335
+ } catch (error) {
1336
+ this.handleLoadError(`Error loading programmatic API routes ${routeFile}`, error);
1337
+ }
1338
+ }
1339
+ }
1340
+ handleLoadError(message, error) {
1341
+ logger.error(`${message}: ${error}`);
1342
+ if (this.throwOnLoadError) {
1343
+ throw error;
1344
+ }
1345
+ }
1346
+ findRootRoutesFile(appDir) {
1347
+ const routeNames = ["routes.ts", "routes.tsx", "routes.js"];
1348
+ const candidateDirs = [path3.dirname(appDir), appDir];
1349
+ const seen = /* @__PURE__ */ new Set();
1350
+ for (const dir of candidateDirs) {
1351
+ for (const routeName of routeNames) {
1352
+ const routesFile = path3.join(dir, routeName);
1353
+ if (seen.has(routesFile)) {
1354
+ continue;
1355
+ }
1356
+ seen.add(routesFile);
1357
+ if (fs.existsSync(routesFile)) {
1358
+ return routesFile;
1359
+ }
1360
+ }
1361
+ }
1362
+ return null;
1363
+ }
1364
+ async loadModule(filePath) {
1365
+ if (this.viteServer) {
1366
+ return await this.viteServer.ssrLoadModule(filePath);
1367
+ }
1368
+ const fileUrl = `file://${filePath}`;
1369
+ return await import(
1370
+ /* @vite-ignore */
1371
+ fileUrl
1372
+ );
1373
+ }
1374
+ addEndpoint(routePath, filePath, method, endpoint, runtimeConfig = {}) {
1375
+ const normalizedMethod = method.toUpperCase();
1376
+ const existingRoute = this.routes.get(routePath);
1377
+ if (existingRoute) {
1378
+ if (!existingRoute.methods.includes(normalizedMethod)) {
1379
+ existingRoute.methods.push(normalizedMethod);
1380
+ }
1381
+ existingRoute.endpoints[normalizedMethod] = endpoint;
1382
+ Object.assign(existingRoute, runtimeConfig);
1383
+ return;
1384
+ }
1385
+ this.routes.set(routePath, {
1386
+ path: routePath,
1387
+ filePath,
1388
+ methods: [normalizedMethod],
1389
+ endpoints: { [normalizedMethod]: endpoint },
1390
+ ...runtimeConfig
1391
+ });
1392
+ }
1393
+ addProgrammaticApiRoute(filePath, route) {
1394
+ const modulePath = createProgrammaticRouteModuleId(filePath, "api", route.path);
1395
+ const runtimeConfig = normalizeFarmRouteRuntimeConfig(route, `API route "${route.path}"`);
1396
+ for (const [method, endpoint] of Object.entries(route.methods)) {
1397
+ if (endpoint) {
1398
+ this.addEndpoint(route.path, modulePath, method, endpoint, runtimeConfig);
1399
+ }
1400
+ }
1401
+ }
1402
+ /**
1403
+ * Get the handler that directly invokes endpoint handlers
1404
+ */
1405
+ getHandler() {
1406
+ if (this.routes.size === 0) {
1407
+ return null;
1408
+ }
1409
+ return async (request) => {
1410
+ const url = new URL(request.url);
1411
+ const pathname = url.pathname;
1412
+ const method = request.method.toUpperCase();
1413
+ const match = matchAPIRoute(this.routes, pathname);
1414
+ if (!match) {
1415
+ return new Response(JSON.stringify({ error: "Not Found" }), {
1416
+ status: 404,
1417
+ headers: { "Content-Type": "application/json" }
1418
+ });
1419
+ }
1420
+ const { route, params } = match;
1421
+ const endpoint = route.endpoints[method];
1422
+ if (!endpoint) {
1423
+ return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
1424
+ status: 405,
1425
+ headers: { "Content-Type": "application/json" }
1426
+ });
1427
+ }
1428
+ const invoke = /* @__PURE__ */ __name(async () => {
1429
+ try {
1430
+ return await invokeAPIRouteEndpoint(endpoint, request, params);
1431
+ } catch (error) {
1432
+ console.error(`[API Error] ${pathname}:`, error);
1433
+ return new Response(JSON.stringify({ error: "Internal Server Error" }), {
1434
+ status: 500,
1435
+ headers: { "Content-Type": "application/json" }
1436
+ });
1437
+ }
1438
+ }, "invoke");
1439
+ return this.i18n?.config.enabled ? _runWithFarmI18nRequest(this.i18n, request, invoke, {
1440
+ redirect: false
1441
+ }) : invoke();
1442
+ };
1443
+ }
1444
+ /**
1445
+ * Check if a path is an API route
1446
+ */
1447
+ isAPIRoute(pathname) {
1448
+ return Boolean(this.matchRoute(pathname));
1449
+ }
1450
+ matchRoute(pathname) {
1451
+ return matchAPIRoute(this.routes, pathname);
1452
+ }
1453
+ /**
1454
+ * Get all routes for client type generation
1455
+ */
1456
+ getRoutes() {
1457
+ return this.routes;
1458
+ }
1459
+ };
1460
+ __name(_APIRouteManager, "APIRouteManager");
1461
+ var APIRouteManager = _APIRouteManager;
1462
+
1463
+ // src/integration-client.ts
1464
+ var _IntegrationClientError = class _IntegrationClientError extends Error {
1465
+ constructor(message, response, data) {
1466
+ super(message);
1467
+ this.name = "IntegrationClientError";
1468
+ this.status = response.status;
1469
+ this.response = response;
1470
+ this.data = data;
1471
+ }
1472
+ };
1473
+ __name(_IntegrationClientError, "IntegrationClientError");
1474
+ var IntegrationClientError = _IntegrationClientError;
1475
+ var INTEGRATION_RUNTIME_REGISTRY_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRuntimeRegistry");
1476
+ var CURRENT_REQUEST_RESOLVER_KEY2 = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
1477
+ var INTEGRATION_REQUEST_DISPATCHER_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRequestDispatcher");
1478
+ function isOperation(value) {
1479
+ return !!value && typeof value === "object" && value.kind === "farm-integration-api-operation";
1480
+ }
1481
+ __name(isOperation, "isOperation");
1482
+ function tryResolveSourceAPI(source) {
1483
+ if ("kind" in source && source.kind === "farm-integration") {
1484
+ if (!source.api) {
1485
+ return null;
1486
+ }
1487
+ return source.api;
1488
+ }
1489
+ return source;
1490
+ }
1491
+ __name(tryResolveSourceAPI, "tryResolveSourceAPI");
1492
+ function getIntegrationRuntimeRegistry() {
1493
+ const globalState2 = globalThis;
1494
+ return globalState2[INTEGRATION_RUNTIME_REGISTRY_KEY] || /* @__PURE__ */ new Map();
1495
+ }
1496
+ __name(getIntegrationRuntimeRegistry, "getIntegrationRuntimeRegistry");
1497
+ function getRegisteredIntegrationRuntimeLocal(key) {
1498
+ return getIntegrationRuntimeRegistry().get(key);
1499
+ }
1500
+ __name(getRegisteredIntegrationRuntimeLocal, "getRegisteredIntegrationRuntimeLocal");
1501
+ function getRegisteredIntegrationsLocal() {
1502
+ return Object.fromEntries(
1503
+ Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [
1504
+ key,
1505
+ runtime.integration
1506
+ ])
1507
+ );
1508
+ }
1509
+ __name(getRegisteredIntegrationsLocal, "getRegisteredIntegrationsLocal");
1510
+ function resolveCurrentRequestLocal() {
1511
+ const globalState2 = globalThis;
1512
+ return globalState2[CURRENT_REQUEST_RESOLVER_KEY2]?.();
1513
+ }
1514
+ __name(resolveCurrentRequestLocal, "resolveCurrentRequestLocal");
1515
+ function resolveIntegrationRequestDispatcherLocal() {
1516
+ const globalState2 = globalThis;
1517
+ return globalState2[INTEGRATION_REQUEST_DISPATCHER_KEY];
1518
+ }
1519
+ __name(resolveIntegrationRequestDispatcherLocal, "resolveIntegrationRequestDispatcherLocal");
1520
+ var INTEGRATION_DATA_HEADER = "x-farm-integration-data";
1521
+ var INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;
1522
+ var BLOCKED_INTEGRATION_DATA_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1523
+ function isIntegrationClientData(value) {
1524
+ return !!value && typeof value === "object" && !Array.isArray(value);
1525
+ }
1526
+ __name(isIntegrationClientData, "isIntegrationClientData");
1527
+ function isPlainIntegrationDataObject(value) {
1528
+ if (!isIntegrationClientData(value)) {
1529
+ return false;
1530
+ }
1531
+ const prototype = Object.getPrototypeOf(value);
1532
+ return prototype === Object.prototype || prototype === null;
1533
+ }
1534
+ __name(isPlainIntegrationDataObject, "isPlainIntegrationDataObject");
1535
+ function sanitizeIntegrationClientDataValue(value) {
1536
+ if (Array.isArray(value)) {
1537
+ return value.map((item) => sanitizeIntegrationClientDataValue(item));
1538
+ }
1539
+ if (!isPlainIntegrationDataObject(value)) {
1540
+ return value;
1541
+ }
1542
+ const sanitized = {};
1543
+ for (const [key, item] of Object.entries(value)) {
1544
+ if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {
1545
+ continue;
1546
+ }
1547
+ sanitized[key] = sanitizeIntegrationClientDataValue(item);
1548
+ }
1549
+ return sanitized;
1550
+ }
1551
+ __name(sanitizeIntegrationClientDataValue, "sanitizeIntegrationClientDataValue");
1552
+ function normalizeIntegrationClientData(value) {
1553
+ if (!isIntegrationClientData(value)) {
1554
+ return void 0;
1555
+ }
1556
+ const sanitized = sanitizeIntegrationClientDataValue(value);
1557
+ return isIntegrationClientData(sanitized) && Object.keys(sanitized).length > 0 ? sanitized : void 0;
1558
+ }
1559
+ __name(normalizeIntegrationClientData, "normalizeIntegrationClientData");
1560
+ function getIntegrationDataHeaderByteLength(value) {
1561
+ return new TextEncoder().encode(value).byteLength;
1562
+ }
1563
+ __name(getIntegrationDataHeaderByteLength, "getIntegrationDataHeaderByteLength");
1564
+ function mergeIntegrationClientData(...values) {
1565
+ let merged;
1566
+ for (const value of values) {
1567
+ const data = normalizeIntegrationClientData(value);
1568
+ if (!data) {
1569
+ continue;
1570
+ }
1571
+ merged = {
1572
+ ...merged || {},
1573
+ ...data
1574
+ };
1575
+ }
1576
+ return merged && Object.keys(merged).length > 0 ? merged : void 0;
1577
+ }
1578
+ __name(mergeIntegrationClientData, "mergeIntegrationClientData");
1579
+ function serializeIntegrationClientData(data) {
1580
+ const serialized = JSON.stringify(data);
1581
+ if (getIntegrationDataHeaderByteLength(serialized) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {
1582
+ throw new Error(
1583
+ `Integration client data must be smaller than ${INTEGRATION_DATA_HEADER_MAX_LENGTH} bytes when sent over HTTP headers.`
1584
+ );
1585
+ }
1586
+ return serialized;
1587
+ }
1588
+ __name(serializeIntegrationClientData, "serializeIntegrationClientData");
1589
+ function appendIntegrationClientDataHeader(headers, data) {
1590
+ if (!data) {
1591
+ return;
1592
+ }
1593
+ headers.set(INTEGRATION_DATA_HEADER, serializeIntegrationClientData(data));
1594
+ }
1595
+ __name(appendIntegrationClientDataHeader, "appendIntegrationClientDataHeader");
1596
+ function resolveAutomaticClientNamespaces() {
1597
+ const globalState2 = globalThis;
1598
+ const manifest = globalState2.window?.__FARM_INTEGRATION_API_MANIFEST__ || globalState2.__FARM_INTEGRATION_API_MANIFEST__ || {};
1599
+ return Object.entries(manifest).map(([key, api2]) => [key, api2, api2]);
1600
+ }
1601
+ __name(resolveAutomaticClientNamespaces, "resolveAutomaticClientNamespaces");
1602
+ function resolveAutomaticServerNamespaces() {
1603
+ return Object.entries(getRegisteredIntegrationsLocal()).flatMap(([key, source]) => {
1604
+ const api2 = tryResolveSourceAPI(source);
1605
+ return api2 ? [[key, api2, source]] : [];
1606
+ });
1607
+ }
1608
+ __name(resolveAutomaticServerNamespaces, "resolveAutomaticServerNamespaces");
1609
+ function appendQuery(url, query) {
1610
+ if (!query) {
1611
+ return;
1612
+ }
1613
+ for (const [key, value] of Object.entries(query)) {
1614
+ if (value == null) {
1615
+ continue;
1616
+ }
1617
+ if (Array.isArray(value)) {
1618
+ for (const item of value) {
1619
+ if (item != null) {
1620
+ url.searchParams.append(key, String(item));
1621
+ }
1622
+ }
1623
+ continue;
1624
+ }
1625
+ url.searchParams.set(key, String(value));
1626
+ }
1627
+ }
1628
+ __name(appendQuery, "appendQuery");
1629
+ function appendHeaders(target, source) {
1630
+ if (!source) {
1631
+ return;
1632
+ }
1633
+ const headers = new Headers(source);
1634
+ headers.forEach((value, key) => {
1635
+ target.set(key, value);
1636
+ });
1637
+ }
1638
+ __name(appendHeaders, "appendHeaders");
1639
+ var DEFAULT_FORWARDED_HEADERS = [
1640
+ "authorization",
1641
+ "cookie",
1642
+ "x-client-ip",
1643
+ "x-forwarded-for",
1644
+ "x-forwarded-host",
1645
+ "x-forwarded-proto",
1646
+ "x-real-ip"
1647
+ ];
1648
+ function resolveRequestLike(request) {
1649
+ if (!request) {
1650
+ return void 0;
1651
+ }
1652
+ if (request instanceof Request) {
1653
+ return {
1654
+ url: request.url,
1655
+ headers: request.headers
1656
+ };
1657
+ }
1658
+ return {
1659
+ url: request.url,
1660
+ headers: request.headers ? new Headers(request.headers) : void 0
1661
+ };
1662
+ }
1663
+ __name(resolveRequestLike, "resolveRequestLike");
1664
+ function resolveServerBaseURL(explicitBaseURL, request) {
1665
+ if (explicitBaseURL) {
1666
+ return explicitBaseURL;
1667
+ }
1668
+ if (request?.url) {
1669
+ try {
1670
+ return new URL(request.url).origin;
1671
+ } catch {
1672
+ }
1673
+ }
1674
+ const headers = request?.headers;
1675
+ const host = headers?.get("x-forwarded-host") || headers?.get("host");
1676
+ if (host) {
1677
+ const proto = headers?.get("x-forwarded-proto") || "http";
1678
+ return `${proto}://${host}`;
1679
+ }
1680
+ return "http://localhost:3000";
1681
+ }
1682
+ __name(resolveServerBaseURL, "resolveServerBaseURL");
1683
+ function resolveForwardHeaders(request, forwardHeaders) {
1684
+ if (!request?.headers || forwardHeaders === false) {
1685
+ return new Headers();
1686
+ }
1687
+ const allowed = Array.isArray(forwardHeaders) && forwardHeaders.length > 0 ? new Set(forwardHeaders.map((item) => item.toLowerCase())) : new Set(DEFAULT_FORWARDED_HEADERS);
1688
+ const headers = new Headers();
1689
+ request.headers.forEach((value, key) => {
1690
+ if (allowed.has(key.toLowerCase())) {
1691
+ headers.set(key, value);
1692
+ }
1693
+ });
1694
+ return headers;
1695
+ }
1696
+ __name(resolveForwardHeaders, "resolveForwardHeaders");
1697
+ function createBody(format, body, headers) {
1698
+ if (body == null || format === "none") {
1699
+ return void 0;
1700
+ }
1701
+ if (format === "form") {
1702
+ if (body instanceof FormData || body instanceof URLSearchParams) {
1703
+ return body;
1704
+ }
1705
+ const form = new URLSearchParams();
1706
+ for (const [key, value] of Object.entries(body)) {
1707
+ if (value == null) {
1708
+ continue;
1709
+ }
1710
+ if (Array.isArray(value)) {
1711
+ for (const item of value) {
1712
+ if (item != null) {
1713
+ form.append(key, String(item));
1714
+ }
1715
+ }
1716
+ continue;
1717
+ }
1718
+ form.set(key, String(value));
1719
+ }
1720
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
1721
+ return form;
1722
+ }
1723
+ headers.set("content-type", "application/json");
1724
+ return JSON.stringify(body);
1725
+ }
1726
+ __name(createBody, "createBody");
1727
+ async function parseResponseData(response) {
1728
+ if (response.status === 204 || response.status === 205) {
1729
+ return void 0;
1730
+ }
1731
+ const contentType = response.headers.get("content-type") || "";
1732
+ if (contentType.includes("application/json")) {
1733
+ return await response.json();
1734
+ }
1735
+ return await response.text();
1736
+ }
1737
+ __name(parseResponseData, "parseResponseData");
1738
+ async function safeParseResponseData(response) {
1739
+ try {
1740
+ return await parseResponseData(response);
1741
+ } catch {
1742
+ return void 0;
1743
+ }
1744
+ }
1745
+ __name(safeParseResponseData, "safeParseResponseData");
1746
+ function createResponseError(response, errorData) {
1747
+ const message = typeof errorData === "string" ? errorData : typeof errorData === "object" && errorData ? String(
1748
+ errorData.error || errorData.message || response.statusText
1749
+ ) : response.statusText || "Integration request failed.";
1750
+ return new IntegrationClientError(message, response, errorData);
1751
+ }
1752
+ __name(createResponseError, "createResponseError");
1753
+ function normalizeExecutionError(error) {
1754
+ if (error instanceof Error) {
1755
+ return error;
1756
+ }
1757
+ if (typeof error === "string" && error.length > 0) {
1758
+ return new Error(error);
1759
+ }
1760
+ return new Error("Integration request failed.");
1761
+ }
1762
+ __name(normalizeExecutionError, "normalizeExecutionError");
1763
+ async function finalizeOperationResponse(operation, response) {
1764
+ if (!response.ok) {
1765
+ const errorData = await safeParseResponseData(response);
1766
+ return {
1767
+ data: null,
1768
+ error: createResponseError(response, errorData)
1769
+ };
1770
+ }
1771
+ if (operation.responseFormat === "response") {
1772
+ return {
1773
+ data: response,
1774
+ error: null
1775
+ };
1776
+ }
1777
+ return {
1778
+ data: await parseResponseData(response),
1779
+ error: null
1780
+ };
1781
+ }
1782
+ __name(finalizeOperationResponse, "finalizeOperationResponse");
1783
+ async function executeClientOperation(operation, input, options, requestOptions) {
1784
+ try {
1785
+ if (!operation.path) {
1786
+ return {
1787
+ data: null,
1788
+ error: new Error(
1789
+ "Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
1790
+ )
1791
+ };
1792
+ }
1793
+ const baseURL = options.baseURL || (typeof window !== "undefined" ? window.location.origin : "http://localhost:3000");
1794
+ const url = new URL(operation.path, baseURL);
1795
+ appendQuery(url, input.query);
1796
+ const headers = new Headers({
1797
+ "x-farm-integration-client": "1",
1798
+ ...options.headers,
1799
+ ...operation.headers,
1800
+ ...requestOptions?.headers
1801
+ });
1802
+ if (operation.responseFormat !== "response") {
1803
+ headers.set("accept", "application/json");
1804
+ }
1805
+ appendIntegrationClientDataHeader(
1806
+ headers,
1807
+ mergeIntegrationClientData(options.data, requestOptions?.data)
1808
+ );
1809
+ const response = await fetch(url.toString(), {
1810
+ method: operation.method,
1811
+ headers,
1812
+ body: createBody(operation.bodyFormat, input.body, headers),
1813
+ credentials: requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? "include",
1814
+ signal: requestOptions?.signal
1815
+ });
1816
+ if (!response.ok) {
1817
+ const errorData = await safeParseResponseData(response);
1818
+ return {
1819
+ data: null,
1820
+ error: createResponseError(response, errorData)
1821
+ };
1822
+ }
1823
+ if (operation.responseFormat === "response") {
1824
+ return {
1825
+ data: response,
1826
+ error: null
1827
+ };
1828
+ }
1829
+ return {
1830
+ data: await parseResponseData(response),
1831
+ error: null
1832
+ };
1833
+ } catch (error) {
1834
+ return {
1835
+ data: null,
1836
+ error: normalizeExecutionError(error)
1837
+ };
1838
+ }
1839
+ }
1840
+ __name(executeClientOperation, "executeClientOperation");
1841
+ async function executeServerOperation(operation, input, options, requestOptions, integrationKey, source) {
1842
+ try {
1843
+ if (!operation.path) {
1844
+ return {
1845
+ data: null,
1846
+ error: new Error(
1847
+ "Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
1848
+ )
1849
+ };
1850
+ }
1851
+ const serverRequestOptions = requestOptions && ("request" in requestOptions || "baseURL" in requestOptions || "forwardHeaders" in requestOptions) ? requestOptions : void 0;
1852
+ const currentRequest = serverRequestOptions?.request instanceof Request ? serverRequestOptions.request : options.request instanceof Request ? options.request : resolveCurrentRequestLocal();
1853
+ const request = resolveRequestLike(
1854
+ serverRequestOptions?.request ?? options.request ?? currentRequest
1855
+ );
1856
+ const baseURL = resolveServerBaseURL(serverRequestOptions?.baseURL ?? options.baseURL, request);
1857
+ const url = new URL(operation.path, baseURL);
1858
+ appendQuery(url, input.query);
1859
+ const headers = new Headers();
1860
+ appendHeaders(
1861
+ headers,
1862
+ resolveForwardHeaders(
1863
+ request,
1864
+ serverRequestOptions?.forwardHeaders ?? options.forwardHeaders
1865
+ )
1866
+ );
1867
+ appendHeaders(headers, options.headers);
1868
+ appendHeaders(headers, operation.headers);
1869
+ appendHeaders(headers, requestOptions?.headers);
1870
+ headers.set("x-farm-integration-client", "1");
1871
+ if (operation.responseFormat !== "response") {
1872
+ headers.set("accept", "application/json");
1873
+ }
1874
+ const data = mergeIntegrationClientData(options.data, requestOptions?.data);
1875
+ if (integrationKey) {
1876
+ const runtime = "kind" in (source || {}) && source.kind === "farm-integration" ? getRegisteredIntegrationRuntimeLocal(integrationKey) || {
1877
+ integration: source,
1878
+ config: {},
1879
+ isDev: process.env.NODE_ENV !== "production",
1880
+ isProd: process.env.NODE_ENV === "production"
1881
+ } : getRegisteredIntegrationRuntimeLocal(integrationKey);
1882
+ if (runtime) {
1883
+ const dispatchIntegrationRequest = resolveIntegrationRequestDispatcherLocal();
1884
+ const directResponse = dispatchIntegrationRequest ? await dispatchIntegrationRequest(
1885
+ runtime,
1886
+ new Request(url.toString(), {
1887
+ method: operation.method,
1888
+ headers,
1889
+ body: createBody(operation.bodyFormat, input.body, headers)
1890
+ }),
1891
+ {
1892
+ currentRequest,
1893
+ data,
1894
+ internal: true
1895
+ }
1896
+ ) : null;
1897
+ if (directResponse) {
1898
+ return await finalizeOperationResponse(operation, directResponse);
1899
+ }
1900
+ }
1901
+ }
1902
+ appendIntegrationClientDataHeader(headers, data);
1903
+ const response = await fetch(url.toString(), {
1904
+ method: operation.method,
1905
+ headers,
1906
+ body: createBody(operation.bodyFormat, input.body, headers),
1907
+ credentials: requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? "include",
1908
+ signal: requestOptions?.signal
1909
+ });
1910
+ return await finalizeOperationResponse(operation, response);
1911
+ } catch (error) {
1912
+ return {
1913
+ data: null,
1914
+ error: normalizeExecutionError(error)
1915
+ };
1916
+ }
1917
+ }
1918
+ __name(executeServerOperation, "executeServerOperation");
1919
+ function createAutomaticIntegrationAliases(isServer, options = {}) {
1920
+ const cache = isServer ? /* @__PURE__ */ new Map() : null;
1921
+ const integrationNamespaces = new Proxy(
1922
+ {},
1923
+ {
1924
+ get(_target, property) {
1925
+ if (typeof property !== "string") {
1926
+ return void 0;
1927
+ }
1928
+ if (property === "integrations") {
1929
+ return integrationNamespaces;
1930
+ }
1931
+ if (cache?.has(property)) {
1932
+ return cache.get(property);
1933
+ }
1934
+ const namespaces = isServer ? resolveAutomaticServerNamespaces() : resolveAutomaticClientNamespaces();
1935
+ const match = namespaces.find(([key]) => key === property);
1936
+ if (!match) {
1937
+ return void 0;
1938
+ }
1939
+ const namespace = isServer ? createServerNamespaceProxy(
1940
+ match[0],
1941
+ match[2],
1942
+ match[1],
1943
+ options
1944
+ ) : createNamespaceProxy(match[1], options);
1945
+ cache?.set(property, namespace);
1946
+ return namespace;
1947
+ }
1948
+ }
1949
+ );
1950
+ Object.defineProperty(integrationNamespaces, "integrations", {
1951
+ value: integrationNamespaces,
1952
+ enumerable: false,
1953
+ configurable: false,
1954
+ writable: false
1955
+ });
1956
+ return integrationNamespaces;
1957
+ }
1958
+ __name(createAutomaticIntegrationAliases, "createAutomaticIntegrationAliases");
1959
+ function integrationsClient(options = {}) {
1960
+ return createAutomaticIntegrationAliases(
1961
+ false,
1962
+ options
1963
+ );
1964
+ }
1965
+ __name(integrationsClient, "integrationsClient");
1966
+ function integrationsServer(options = {}) {
1967
+ return createAutomaticIntegrationAliases(true, {
1968
+ ...options,
1969
+ isServer: true
1970
+ });
1971
+ }
1972
+ __name(integrationsServer, "integrationsServer");
1973
+ function resolveSingleNamespaceOperation(api2) {
1974
+ const entries = Object.entries(api2);
1975
+ if (entries.length !== 1) {
1976
+ return null;
1977
+ }
1978
+ const [, value] = entries[0];
1979
+ return isOperation(value) ? value : null;
1980
+ }
1981
+ __name(resolveSingleNamespaceOperation, "resolveSingleNamespaceOperation");
1982
+ function createClientOperationCaller(operation, property, options) {
1983
+ if (operation.isServer === true) {
1984
+ return async () => {
1985
+ throw new Error(
1986
+ `Integration method "${property}" is registered with isServer: true and is only available from a server integration client.`
1987
+ );
1988
+ };
1989
+ }
1990
+ return async (input = {}, requestOptions) => {
1991
+ if (typeof window === "undefined") {
1992
+ throw new Error(
1993
+ "Client integration API cannot be called on the server. Pass { isServer: true } to createIntegrationClient(...) during server rendering, or provide { isServer: true, request } outside it."
1994
+ );
1995
+ }
1996
+ return executeClientOperation(operation, input, options, requestOptions);
1997
+ };
1998
+ }
1999
+ __name(createClientOperationCaller, "createClientOperationCaller");
2000
+ function createServerOperationCaller(operation, options, integrationKey, source) {
2001
+ return async (input = {}, requestOptions) => {
2002
+ if (typeof window !== "undefined") {
2003
+ throw new Error(
2004
+ "Server integration API cannot be called in the browser. Remove { isServer: true } and create a client integration API instead."
2005
+ );
2006
+ }
2007
+ return executeServerOperation(
2008
+ operation,
2009
+ input,
2010
+ options,
2011
+ requestOptions,
2012
+ integrationKey,
2013
+ source
2014
+ );
2015
+ };
2016
+ }
2017
+ __name(createServerOperationCaller, "createServerOperationCaller");
2018
+ function createNamespaceProxy(api2, options) {
2019
+ const cache = /* @__PURE__ */ new Map();
2020
+ const directOperation = resolveSingleNamespaceOperation(api2);
2021
+ const target = directOperation ? createClientOperationCaller(directOperation, directOperation.method.toLowerCase(), options) : {};
2022
+ return new Proxy(target, {
2023
+ get(targetObject, property, receiver) {
2024
+ if (typeof property !== "string") {
2025
+ return Reflect.get(targetObject, property, receiver);
2026
+ }
2027
+ if (cache.has(property)) {
2028
+ return cache.get(property);
2029
+ }
2030
+ const value = api2[property];
2031
+ if (!value) {
2032
+ return Reflect.get(targetObject, property, receiver);
2033
+ }
2034
+ if (isOperation(value)) {
2035
+ const caller = createClientOperationCaller(value, property, options);
2036
+ cache.set(property, caller);
2037
+ return caller;
2038
+ }
2039
+ const namespace = createNamespaceProxy(value, options);
2040
+ cache.set(property, namespace);
2041
+ return namespace;
2042
+ }
2043
+ });
2044
+ }
2045
+ __name(createNamespaceProxy, "createNamespaceProxy");
2046
+ function createServerNamespaceProxy(integrationKey, source, api2, options) {
2047
+ const cache = /* @__PURE__ */ new Map();
2048
+ const directOperation = resolveSingleNamespaceOperation(api2);
2049
+ const target = directOperation ? createServerOperationCaller(directOperation, options, integrationKey, source) : {};
2050
+ return new Proxy(target, {
2051
+ get(targetObject, property, receiver) {
2052
+ if (typeof property !== "string") {
2053
+ return Reflect.get(targetObject, property, receiver);
2054
+ }
2055
+ if (cache.has(property)) {
2056
+ return cache.get(property);
2057
+ }
2058
+ const value = api2[property];
2059
+ if (!value) {
2060
+ return Reflect.get(targetObject, property, receiver);
2061
+ }
2062
+ if (isOperation(value)) {
2063
+ const caller = createServerOperationCaller(value, options, integrationKey, source);
2064
+ cache.set(property, caller);
2065
+ return caller;
2066
+ }
2067
+ const namespace = createServerNamespaceProxy(
2068
+ integrationKey,
2069
+ source,
2070
+ value,
2071
+ options
2072
+ );
2073
+ cache.set(property, namespace);
2074
+ return namespace;
2075
+ }
2076
+ });
2077
+ }
2078
+ __name(createServerNamespaceProxy, "createServerNamespaceProxy");
2079
+
2080
+ // src/client-cache.ts
2081
+ var _FarmClientDataCache = class _FarmClientDataCache {
2082
+ constructor() {
2083
+ this.entries = /* @__PURE__ */ new Map();
2084
+ this.aliases = /* @__PURE__ */ new Map();
2085
+ this.invalidatedAt = /* @__PURE__ */ new Map();
2086
+ this.listeners = /* @__PURE__ */ new Map();
2087
+ this.inflight = /* @__PURE__ */ new Map();
2088
+ subscribeFarmCacheInvalidation((key) => this.invalidate(key));
2089
+ }
2090
+ get size() {
2091
+ return this.entries.size;
2092
+ }
2093
+ resolveKey(key) {
2094
+ let resolved = key;
2095
+ const seen = /* @__PURE__ */ new Set();
2096
+ while (this.aliases.has(resolved) && !seen.has(resolved)) {
2097
+ seen.add(resolved);
2098
+ resolved = this.aliases.get(resolved);
2099
+ }
2100
+ return resolved;
2101
+ }
2102
+ get(key, now = Date.now()) {
2103
+ const resolved = this.resolveKey(key);
2104
+ const entry = this.entries.get(resolved);
2105
+ if (!entry) return void 0;
2106
+ if (entry.gcAt !== void 0 && now >= entry.gcAt) {
2107
+ this.entries.delete(resolved);
2108
+ this.emit(resolved);
2109
+ return void 0;
2110
+ }
2111
+ return entry;
2112
+ }
2113
+ set(key, entry) {
2114
+ const resolved = this.resolveKey(key);
2115
+ const invalidatedAt = this.invalidatedAt.get(resolved);
2116
+ const nextEntry = invalidatedAt !== void 0 && invalidatedAt > entry.updatedAt ? { ...entry, staleAt: 0, invalidatedAt } : { ...entry, invalidatedAt: void 0 };
2117
+ if (invalidatedAt === void 0 || entry.updatedAt >= invalidatedAt) {
2118
+ this.invalidatedAt.delete(resolved);
2119
+ }
2120
+ this.entries.set(resolved, nextEntry);
2121
+ this.emit(resolved);
2122
+ return this;
2123
+ }
2124
+ delete(key) {
2125
+ const resolved = this.resolveKey(key);
2126
+ const deleted = this.entries.delete(resolved);
2127
+ this.inflight.delete(resolved);
2128
+ this.emit(resolved);
2129
+ return deleted;
2130
+ }
2131
+ clear() {
2132
+ const keys = /* @__PURE__ */ new Set([...this.entries.keys(), ...this.listeners.keys()]);
2133
+ this.entries.clear();
2134
+ this.aliases.clear();
2135
+ this.invalidatedAt.clear();
2136
+ this.inflight.clear();
2137
+ for (const key of keys) this.emit(key);
2138
+ }
2139
+ isStale(key, now = Date.now()) {
2140
+ const entry = this.get(key, now);
2141
+ return !entry || entry.invalidatedAt !== void 0 || now >= entry.staleAt;
2142
+ }
2143
+ invalidate(key, now = Date.now()) {
2144
+ const resolved = this.resolveKey(key);
2145
+ this.invalidatedAt.set(resolved, now);
2146
+ const entry = this.entries.get(resolved);
2147
+ if (entry) {
2148
+ this.entries.set(resolved, {
2149
+ ...entry,
2150
+ staleAt: 0,
2151
+ invalidatedAt: now
2152
+ });
2153
+ }
2154
+ this.emit(resolved);
2155
+ }
2156
+ alias(alias, key) {
2157
+ const resolved = this.resolveKey(key);
2158
+ if (alias === resolved) return;
2159
+ const aliasEntry = this.entries.get(alias);
2160
+ if (aliasEntry && !this.entries.has(resolved)) {
2161
+ this.entries.set(resolved, aliasEntry);
2162
+ }
2163
+ this.entries.delete(alias);
2164
+ const aliasInflight = this.inflight.get(alias);
2165
+ if (aliasInflight && !this.inflight.has(resolved)) {
2166
+ this.inflight.set(resolved, aliasInflight);
2167
+ }
2168
+ this.inflight.delete(alias);
2169
+ this.aliases.set(alias, resolved);
2170
+ this.emit(alias);
2171
+ this.emit(resolved);
2172
+ }
2173
+ subscribe(key, listener) {
2174
+ let listeners = this.listeners.get(key);
2175
+ if (!listeners) {
2176
+ listeners = /* @__PURE__ */ new Set();
2177
+ this.listeners.set(key, listeners);
2178
+ }
2179
+ listeners.add(listener);
2180
+ return () => {
2181
+ listeners.delete(listener);
2182
+ if (listeners.size === 0) this.listeners.delete(key);
2183
+ };
2184
+ }
2185
+ getInflight(key) {
2186
+ return this.inflight.get(this.resolveKey(key));
2187
+ }
2188
+ setInflight(key, promise) {
2189
+ this.inflight.set(this.resolveKey(key), promise);
2190
+ }
2191
+ deleteInflight(key) {
2192
+ this.inflight.delete(this.resolveKey(key));
2193
+ }
2194
+ emit(key) {
2195
+ this.notifyListeners(key);
2196
+ for (const [alias, target] of this.aliases) {
2197
+ if (this.resolveKey(target) === key) {
2198
+ this.notifyListeners(alias);
2199
+ }
2200
+ }
2201
+ }
2202
+ notifyListeners(key) {
2203
+ for (const listener of this.listeners.get(key) ?? []) {
2204
+ listener();
2205
+ }
2206
+ }
2207
+ };
2208
+ __name(_FarmClientDataCache, "FarmClientDataCache");
2209
+ var FarmClientDataCache = _FarmClientDataCache;
2210
+ var FARM_CLIENT_DATA_CACHE = /* @__PURE__ */ Symbol.for("farm.clientDataCache");
2211
+ var clientCacheGlobal = globalThis;
2212
+ var sharedFarmClientDataCache = clientCacheGlobal[FARM_CLIENT_DATA_CACHE] ?? (clientCacheGlobal[FARM_CLIENT_DATA_CACHE] = new FarmClientDataCache());
2213
+ function getFarmClientDataCache() {
2214
+ return sharedFarmClientDataCache;
2215
+ }
2216
+ __name(getFarmClientDataCache, "getFarmClientDataCache");
2217
+ function normalizeFarmClientCacheKey(key) {
2218
+ return typeof key === "string" ? key : createRouteDataCacheKey(key);
2219
+ }
2220
+ __name(normalizeFarmClientCacheKey, "normalizeFarmClientCacheKey");
2221
+
2222
+ // src/api/client.ts
2223
+ function createAPIClient(options = {}) {
2224
+ options ?? (options = {});
2225
+ const baseURL = options.baseURL || (typeof window !== "undefined" ? window.location.origin : "http://localhost:3000");
2226
+ const integrationOptions = options.integrations === false ? false : {
2227
+ baseURL: options.baseURL,
2228
+ headers: options.headers,
2229
+ credentials: options.credentials,
2230
+ ...typeof options.integrations === "object" ? options.integrations : {}
2231
+ };
2232
+ const rootAliases = integrationOptions === false ? void 0 : {
2233
+ integrations: integrationsClient(integrationOptions)
2234
+ };
2235
+ const cacheState = getFarmClientDataCache();
2236
+ const inflightState = /* @__PURE__ */ new Map();
2237
+ const routeMeta = /* @__PURE__ */ new WeakMap();
2238
+ let requestCounter = 0;
2239
+ const fetchClient = /* @__PURE__ */ __name(async (path4, requestOptions = {}) => {
2240
+ const url = new URL(path4, baseURL);
2241
+ if (requestOptions.query) {
2242
+ Object.entries(requestOptions.query).forEach(([key, value]) => {
2243
+ if (value !== void 0 && value !== null) {
2244
+ url.searchParams.set(key, String(value));
2245
+ }
2246
+ });
2247
+ }
2248
+ const fetchOptions = {
2249
+ method: requestOptions.method || "GET",
2250
+ headers: {
2251
+ "Content-Type": "application/json",
2252
+ ...options.headers,
2253
+ ...requestOptions.headers
2254
+ }
2255
+ };
2256
+ if (requestOptions.body) {
2257
+ fetchOptions.body = JSON.stringify(requestOptions.body);
2258
+ }
2259
+ const response = await fetch(url.toString(), fetchOptions);
2260
+ let data = void 0;
2261
+ if (response.status !== 204 && response.status !== 205) {
2262
+ data = await response.json();
2263
+ }
2264
+ return { response, data };
2265
+ }, "fetchClient");
2266
+ const request = /* @__PURE__ */ __name(async (path4, method, input = {}, clientOptions) => {
2267
+ const methodUpper = method.toUpperCase();
2268
+ const requestId = `${Date.now()}-${++requestCounter}`;
2269
+ const cacheOptions = clientOptions?.cache ? {
2270
+ ...options.cacheDefaults,
2271
+ ...clientOptions.cache
2272
+ } : void 0;
2273
+ const configuredCacheKey = clientOptions?.key ?? cacheOptions?.key;
2274
+ const cacheKey = normalizeFarmClientCacheKey(
2275
+ configuredCacheKey ?? buildCacheKey(methodUpper, path4, input, baseURL)
2276
+ );
2277
+ const now = Date.now();
2278
+ const emitStatus = /* @__PURE__ */ __name((phase, payload) => {
2279
+ clientOptions?.onStatus?.({
2280
+ phase,
2281
+ requestId,
2282
+ method: methodUpper,
2283
+ key: cacheKey,
2284
+ input,
2285
+ timestamp: Date.now(),
2286
+ ...payload
2287
+ });
2288
+ }, "emitStatus");
2289
+ const entry = getValidCacheEntry(cacheState, cacheKey, now);
2290
+ const policy = cacheOptions?.policy ?? (cacheOptions ? "cache-first" : "network-only");
2291
+ const staleTime = cacheOptions?.staleTime ?? 0;
2292
+ const isCacheEnabled = Boolean(cacheOptions) && methodUpper === "GET";
2293
+ const isStale = entry ? isEntryStale(entry, now) : true;
2294
+ const applyOptimisticUpdates = /* @__PURE__ */ __name(() => {
2295
+ if (!clientOptions?.optimistic?.update?.length) return [];
2296
+ const snapshots = [];
2297
+ for (const update of clientOptions.optimistic.update) {
2298
+ const [target, targetInput, updater] = update.length === 2 ? [update[0], void 0, update[1]] : [update[0], update[1], update[2]];
2299
+ const targetKey = resolveTargetKey(routeMeta, target, targetInput, baseURL);
2300
+ if (!targetKey) continue;
2301
+ const targetEntry = getValidCacheEntry(cacheState, targetKey, now);
2302
+ const previousEntry = targetEntry ? { ...targetEntry } : void 0;
2303
+ const previousData = targetEntry?.data;
2304
+ const nextData = updater(previousData);
2305
+ cacheState.set(targetKey, {
2306
+ data: nextData,
2307
+ updatedAt: now,
2308
+ staleAt: targetEntry?.staleAt ?? now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),
2309
+ gcAt: targetEntry?.gcAt ?? getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime),
2310
+ invalidatedAt: targetEntry?.invalidatedAt
2311
+ });
2312
+ snapshots.push({ key: targetKey, entry: previousEntry });
2313
+ }
2314
+ return snapshots;
2315
+ }, "applyOptimisticUpdates");
2316
+ const rollbackOptimisticUpdates = /* @__PURE__ */ __name((snapshots) => {
2317
+ if (!clientOptions?.optimistic?.rollbackOnError) return;
2318
+ for (const snapshot of snapshots) {
2319
+ if (!snapshot.entry) {
2320
+ cacheState.delete(snapshot.key);
2321
+ continue;
2322
+ }
2323
+ cacheState.set(snapshot.key, { ...snapshot.entry });
2324
+ }
2325
+ }, "rollbackOptimisticUpdates");
2326
+ const executeNetwork = /* @__PURE__ */ __name(async (opts) => {
2327
+ const dedupeMs = cacheOptions?.dedupeMs ?? 0;
2328
+ const inflight = inflightState.get(cacheKey);
2329
+ const allowDedupe = isCacheEnabled && dedupeMs > 0;
2330
+ if (allowDedupe && inflight && now - inflight.startedAt < dedupeMs) {
2331
+ emitStatus("pending", { isBackground: opts?.isBackground, data: entry?.data });
2332
+ const result2 = await inflight.promise;
2333
+ if (result2.error) {
2334
+ emitStatus("error", { error: result2.error, isBackground: opts?.isBackground });
2335
+ if (opts?.callCallbacks !== false) {
2336
+ clientOptions?.onError?.(result2.error);
2337
+ }
2338
+ } else {
2339
+ emitStatus("success", { data: result2.data, isBackground: opts?.isBackground });
2340
+ if (opts?.callCallbacks !== false) {
2341
+ clientOptions?.onSuccess?.(result2.data);
2342
+ }
2343
+ }
2344
+ return result2;
2345
+ }
2346
+ emitStatus(opts?.isBackground ? "revalidating" : "pending", {
2347
+ isBackground: opts?.isBackground
2348
+ });
2349
+ const promise = (async () => {
2350
+ const maxRetries = Math.max(0, clientOptions?.retry?.count ?? 0);
2351
+ let attempt = 0;
2352
+ while (true) {
2353
+ clientOptions?.onRequest?.({
2354
+ requestId,
2355
+ method: methodUpper,
2356
+ key: cacheKey,
2357
+ path: path4,
2358
+ input,
2359
+ attempt,
2360
+ timestamp: Date.now()
2361
+ });
2362
+ try {
2363
+ const { response, data } = await fetchClient(path4, {
2364
+ ...input,
2365
+ method: methodUpper
2366
+ });
2367
+ const error = response.ok ? null : createResponseError2(response, data);
2368
+ const responseEvent = {
2369
+ requestId,
2370
+ method: methodUpper,
2371
+ key: cacheKey,
2372
+ path: path4,
2373
+ input,
2374
+ attempt,
2375
+ timestamp: Date.now(),
2376
+ response,
2377
+ data: response.ok ? data : void 0,
2378
+ error: error ?? void 0,
2379
+ ok: response.ok,
2380
+ status: response.status
2381
+ };
2382
+ clientOptions?.onResponse?.(response.ok ? data : void 0, error, responseEvent);
2383
+ if (!error) {
2384
+ return { data, error: null, key: cacheKey };
2385
+ }
2386
+ if (attempt >= maxRetries) {
2387
+ return { data: void 0, error, key: cacheKey };
2388
+ }
2389
+ } catch (err) {
2390
+ const error = normalizeError(err);
2391
+ const responseEvent = {
2392
+ requestId,
2393
+ method: methodUpper,
2394
+ key: cacheKey,
2395
+ path: path4,
2396
+ input,
2397
+ attempt,
2398
+ timestamp: Date.now(),
2399
+ error,
2400
+ ok: false
2401
+ };
2402
+ clientOptions?.onResponse?.(void 0, error, responseEvent);
2403
+ if (attempt >= maxRetries) {
2404
+ return { data: void 0, error, key: cacheKey };
2405
+ }
2406
+ }
2407
+ attempt += 1;
2408
+ const delay = typeof clientOptions?.retry?.delay === "function" ? clientOptions.retry.delay(attempt) : clientOptions?.retry?.delay ?? 0;
2409
+ if (delay > 0) {
2410
+ await new Promise((resolve) => setTimeout(resolve, delay));
2411
+ }
2412
+ }
2413
+ })();
2414
+ inflightState.set(cacheKey, { promise, startedAt: now });
2415
+ try {
2416
+ const result2 = await promise;
2417
+ if (!result2.error && isCacheEnabled) {
2418
+ const updatedAt = Date.now();
2419
+ cacheState.set(cacheKey, {
2420
+ data: result2.data,
2421
+ updatedAt,
2422
+ staleAt: updatedAt + staleTime,
2423
+ gcAt: getGcAt(updatedAt, cacheOptions?.gcTime),
2424
+ invalidatedAt: void 0
2425
+ });
2426
+ }
2427
+ if (result2.error) {
2428
+ emitStatus("error", { error: result2.error, isBackground: opts?.isBackground });
2429
+ if (opts?.callCallbacks !== false) {
2430
+ clientOptions?.onError?.(result2.error);
2431
+ }
2432
+ } else {
2433
+ emitStatus("success", { data: result2.data, isBackground: opts?.isBackground });
2434
+ if (opts?.callCallbacks !== false) {
2435
+ clientOptions?.onSuccess?.(result2.data);
2436
+ }
2437
+ }
2438
+ return result2;
2439
+ } finally {
2440
+ inflightState.delete(cacheKey);
2441
+ }
2442
+ }, "executeNetwork");
2443
+ const invalidateTargets = /* @__PURE__ */ __name(async () => {
2444
+ if (!clientOptions?.invalidate) return;
2445
+ const invalidateOptions = Array.isArray(clientOptions.invalidate) ? { targets: clientOptions.invalidate, refetch: false } : {
2446
+ targets: clientOptions.invalidate.targets,
2447
+ refetch: clientOptions.invalidate.refetch ?? false
2448
+ };
2449
+ for (const target of invalidateOptions.targets) {
2450
+ const targetKey = resolveTargetKey(routeMeta, target, void 0, baseURL);
2451
+ if (!targetKey) continue;
2452
+ const existing = cacheState.get(targetKey);
2453
+ if (existing) {
2454
+ cacheState.set(targetKey, {
2455
+ ...existing,
2456
+ staleAt: 0,
2457
+ invalidatedAt: Date.now()
2458
+ });
2459
+ }
2460
+ emitStatus("invalidated", { key: targetKey });
2461
+ if (invalidateOptions.refetch && existing && targetKey === cacheKey) {
2462
+ void executeNetwork({ isBackground: true, callCallbacks: false });
2463
+ }
2464
+ }
2465
+ }, "invalidateTargets");
2466
+ const optimisticSnapshots = applyOptimisticUpdates();
2467
+ if (isCacheEnabled) {
2468
+ if (entry && !isStale && policy !== "network-only") {
2469
+ emitStatus("success", { data: entry.data });
2470
+ clientOptions?.onSuccess?.(entry.data);
2471
+ clientOptions?.onSettled?.(entry.data, null);
2472
+ return { data: entry.data, error: null, key: cacheKey };
2473
+ }
2474
+ if (entry && isStale && policy === "stale-while-revalidate") {
2475
+ emitStatus("success", { data: entry.data });
2476
+ clientOptions?.onSuccess?.(entry.data);
2477
+ clientOptions?.onSettled?.(entry.data, null);
2478
+ void executeNetwork({ isBackground: true, callCallbacks: false });
2479
+ return { data: entry.data, error: null, key: cacheKey };
2480
+ }
2481
+ }
2482
+ const result = await executeNetwork();
2483
+ if (result.error) {
2484
+ rollbackOptimisticUpdates(optimisticSnapshots);
2485
+ }
2486
+ await invalidateTargets();
2487
+ clientOptions?.onSettled?.(result.data, result.error);
2488
+ return result;
2489
+ }, "request");
2490
+ return createNestedProxy([], request, routeMeta, baseURL, rootAliases);
2491
+ }
2492
+ __name(createAPIClient, "createAPIClient");
2493
+ function createNestedProxy(path4, client, routeMeta, baseURL, rootAliases) {
2494
+ const target = /* @__PURE__ */ __name(() => {
2495
+ }, "target");
2496
+ const proxy = new Proxy(target, {
2497
+ // When accessing a property (api.hello)
2498
+ get(_target, prop) {
2499
+ if (path4.length === 0 && typeof prop === "string" && rootAliases && prop in rootAliases) {
2500
+ return rootAliases[prop];
2501
+ }
2502
+ return createNestedProxy([...path4, prop], client, routeMeta, baseURL, rootAliases);
2503
+ },
2504
+ // When calling as a function
2505
+ apply(_target, _thisArg, args) {
2506
+ const lastPart = path4[path4.length - 1];
2507
+ const httpMethods = ["get", "post", "put", "delete", "patch", "options", "head"];
2508
+ if (httpMethods.includes(lastPart)) {
2509
+ const routePath = "/api/" + path4.slice(0, -1).join("/");
2510
+ const method = lastPart.toUpperCase();
2511
+ const [options, clientOptions] = args;
2512
+ return client(routePath, method, options, clientOptions);
2513
+ } else {
2514
+ const routePath = "/api/" + path4.join("/");
2515
+ const [options, clientOptions] = args;
2516
+ return client(routePath, options?.method || "GET", options, clientOptions);
2517
+ }
2518
+ }
2519
+ });
2520
+ routeMeta.set(proxy, { path: [...path4], baseURL });
2521
+ return proxy;
2522
+ }
2523
+ __name(createNestedProxy, "createNestedProxy");
2524
+ function createServerAPIClient(endpoints, options = {}) {
2525
+ if (options.integrations === false || Object.prototype.hasOwnProperty.call(endpoints, "integrations")) {
2526
+ return endpoints;
2527
+ }
2528
+ Object.defineProperty(endpoints, "integrations", {
2529
+ get() {
2530
+ return integrationsServer(
2531
+ typeof options.integrations === "object" ? options.integrations : {}
2532
+ );
2533
+ },
2534
+ enumerable: false,
2535
+ configurable: true
2536
+ });
2537
+ return endpoints;
2538
+ }
2539
+ __name(createServerAPIClient, "createServerAPIClient");
2540
+ function buildCacheKey(method, path4, input, baseURL) {
2541
+ const keyInput = input && typeof input === "object" ? { query: input.query, body: input.body } : input;
2542
+ const url = new URL(path4, baseURL);
2543
+ return `${method}:${url.origin}${url.pathname}:${stableStringify(keyInput ?? {})}`;
2544
+ }
2545
+ __name(buildCacheKey, "buildCacheKey");
2546
+ function stableStringify(value) {
2547
+ if (value === null || value === void 0) return String(value);
2548
+ if (value instanceof Date) return value.toISOString();
2549
+ if (typeof value !== "object") return JSON.stringify(value);
2550
+ if (Array.isArray(value)) {
2551
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
2552
+ }
2553
+ const keys = Object.keys(value).sort();
2554
+ const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
2555
+ return `{${entries.join(",")}}`;
2556
+ }
2557
+ __name(stableStringify, "stableStringify");
2558
+ function getGcAt(now, gcTime) {
2559
+ if (gcTime === void 0) return void 0;
2560
+ if (!Number.isFinite(gcTime) || gcTime <= 0) return now;
2561
+ return now + gcTime;
2562
+ }
2563
+ __name(getGcAt, "getGcAt");
2564
+ function getValidCacheEntry(cacheState, key, now) {
2565
+ const entry = cacheState.get(key);
2566
+ if (!entry) return void 0;
2567
+ if (entry.gcAt !== void 0 && now >= entry.gcAt) {
2568
+ cacheState.delete(key);
2569
+ return void 0;
2570
+ }
2571
+ return entry;
2572
+ }
2573
+ __name(getValidCacheEntry, "getValidCacheEntry");
2574
+ function isEntryStale(entry, now) {
2575
+ if (entry.invalidatedAt !== void 0) return true;
2576
+ return now >= entry.staleAt;
2577
+ }
2578
+ __name(isEntryStale, "isEntryStale");
2579
+ function resolveTargetKey(routeMeta, target, input, baseURL = "http://localhost:3000") {
2580
+ if (!target) return null;
2581
+ if (typeof target === "string") return target;
2582
+ if (typeof target === "function") {
2583
+ const meta = routeMeta.get(target);
2584
+ if (!meta) return null;
2585
+ const { method, routePath } = resolveRouteMeta(meta);
2586
+ return buildCacheKey(method, routePath, input ?? {}, meta.baseURL);
2587
+ }
2588
+ if (Array.isArray(target)) {
2589
+ const [route, routeInput] = target;
2590
+ return resolveTargetKey(routeMeta, route, routeInput, baseURL);
2591
+ }
2592
+ if ("key" in target) return normalizeFarmClientCacheKey(target.key);
2593
+ if ("path" in target) {
2594
+ const method = target.method ?? "GET";
2595
+ return buildCacheKey(method, target.path, target.input ?? {}, baseURL);
2596
+ }
2597
+ return null;
2598
+ }
2599
+ __name(resolveTargetKey, "resolveTargetKey");
2600
+ function resolveRouteMeta(meta) {
2601
+ const httpMethods = ["get", "post", "put", "delete", "patch", "options", "head"];
2602
+ const lastPart = meta.path[meta.path.length - 1];
2603
+ if (lastPart && httpMethods.includes(lastPart)) {
2604
+ return {
2605
+ routePath: "/api/" + meta.path.slice(0, -1).join("/"),
2606
+ method: lastPart.toUpperCase()
2607
+ };
2608
+ }
2609
+ return {
2610
+ routePath: "/api/" + meta.path.join("/"),
2611
+ method: "GET"
2612
+ };
2613
+ }
2614
+ __name(resolveRouteMeta, "resolveRouteMeta");
2615
+ function normalizeError(error) {
2616
+ if (error instanceof Error) return error;
2617
+ return new Error(typeof error === "string" ? error : "Unknown error");
2618
+ }
2619
+ __name(normalizeError, "normalizeError");
2620
+ function createResponseError2(response, data) {
2621
+ const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
2622
+ error.status = response.status;
2623
+ error.response = response;
2624
+ error.data = data;
2625
+ return error;
2626
+ }
2627
+ __name(createResponseError2, "createResponseError");
2628
+
2629
+ // src/server/response.ts
2630
+ var import_node_events = require("events");
2631
+ async function sendWebResponse(res, response) {
2632
+ res.statusCode = response.status;
2633
+ const responseHeaders = response.headers;
2634
+ const setCookies = responseHeaders.getSetCookie?.() || [];
2635
+ if (setCookies.length > 0) {
2636
+ res.setHeader("Set-Cookie", setCookies);
2637
+ }
2638
+ response.headers.forEach((value, key) => {
2639
+ if (key.toLowerCase() === "set-cookie" && setCookies.length > 0) {
2640
+ return;
2641
+ }
2642
+ res.setHeader(key, value);
2643
+ });
2644
+ if (!response.body) {
2645
+ res.end();
2646
+ return;
2647
+ }
2648
+ if (typeof res.write !== "function") {
2649
+ const body = await response.arrayBuffer();
2650
+ res.end(Buffer.from(body));
2651
+ return;
2652
+ }
2653
+ const reader = response.body.getReader();
2654
+ try {
2655
+ while (true) {
2656
+ const { done, value } = await reader.read();
2657
+ if (done) {
2658
+ break;
2659
+ }
2660
+ if (!value || value.byteLength === 0) {
2661
+ continue;
2662
+ }
2663
+ if (!res.write(value)) {
2664
+ await (0, import_node_events.once)(res, "drain");
2665
+ }
2666
+ }
2667
+ res.end();
2668
+ } catch (error) {
2669
+ if (!res.writableEnded) {
2670
+ const responseError = error instanceof Error ? error : new Error(String(error));
2671
+ if (typeof res.destroy === "function") {
2672
+ res.destroy(responseError);
2673
+ } else {
2674
+ res.end();
2675
+ }
2676
+ }
2677
+ throw error;
2678
+ } finally {
2679
+ reader.releaseLock();
2680
+ }
2681
+ }
2682
+ __name(sendWebResponse, "sendWebResponse");
2683
+
2684
+ // src/after.ts
2685
+ var import_node_async_hooks3 = require("async_hooks");
2686
+ var AFTER_STORAGE = /* @__PURE__ */ Symbol.for("@farm.js/core/after-storage");
2687
+ function getAfterStorage() {
2688
+ const runtime = globalThis;
2689
+ const existing = runtime[AFTER_STORAGE];
2690
+ if (existing instanceof import_node_async_hooks3.AsyncLocalStorage) {
2691
+ return existing;
2692
+ }
2693
+ const storage = new import_node_async_hooks3.AsyncLocalStorage();
2694
+ runtime[AFTER_STORAGE] = storage;
2695
+ return storage;
2696
+ }
2697
+ __name(getAfterStorage, "getAfterStorage");
2698
+ var afterStorage = getAfterStorage();
2699
+ function defaultAfterErrorReporter(error) {
2700
+ console.error("[Farm.js] after() callback failed:", error);
2701
+ }
2702
+ __name(defaultAfterErrorReporter, "defaultAfterErrorReporter");
2703
+ function reportAfterError(state, error) {
2704
+ try {
2705
+ state.reportError(error);
2706
+ } catch {
2707
+ }
2708
+ }
2709
+ __name(reportAfterError, "reportAfterError");
2710
+ function createAfterRequestState(reportError = defaultAfterErrorReporter) {
2711
+ let resolveResponseFinished;
2712
+ let responseFinished = false;
2713
+ const responseFinishedPromise = new Promise((resolve) => {
2714
+ resolveResponseFinished = resolve;
2715
+ });
2716
+ const state = {
2717
+ completion: Promise.resolve(),
2718
+ finishResponse: /* @__PURE__ */ __name(() => {
2719
+ if (responseFinished) return;
2720
+ responseFinished = true;
2721
+ resolveResponseFinished();
2722
+ }, "finishResponse"),
2723
+ phase: "open",
2724
+ reportError,
2725
+ tasks: []
2726
+ };
2727
+ state.completion = responseFinishedPromise.then(
2728
+ () => afterStorage.run(state, async () => {
2729
+ state.phase = "running";
2730
+ for (let index = 0; index < state.tasks.length; index++) {
2731
+ const task = state.tasks[index];
2732
+ task.start();
2733
+ try {
2734
+ await task.result;
2735
+ } catch (error) {
2736
+ reportAfterError(state, error);
2737
+ }
2738
+ }
2739
+ state.phase = "closed";
2740
+ })
2741
+ );
2742
+ return state;
2743
+ }
2744
+ __name(createAfterRequestState, "createAfterRequestState");
2745
+ function registerPlatformLifetime(state, context) {
2746
+ if (!context?.waitUntil) return;
2747
+ try {
2748
+ context.waitUntil(state.completion);
2749
+ } catch (error) {
2750
+ reportAfterError(state, error);
2751
+ }
2752
+ }
2753
+ __name(registerPlatformLifetime, "registerPlatformLifetime");
2754
+ function finishSoon(state) {
2755
+ setTimeout(state.finishResponse, 0);
2756
+ }
2757
+ __name(finishSoon, "finishSoon");
2758
+ async function _runWithAfterNodeResponse(response, handler, context) {
2759
+ if (afterStorage.getStore()) {
2760
+ return await handler();
2761
+ }
2762
+ const state = createAfterRequestState();
2763
+ let finished = false;
2764
+ const finish = /* @__PURE__ */ __name(() => {
2765
+ if (finished) return;
2766
+ finished = true;
2767
+ response.off("finish", finish);
2768
+ response.off("close", finish);
2769
+ state.finishResponse();
2770
+ }, "finish");
2771
+ response.once("finish", finish);
2772
+ response.once("close", finish);
2773
+ if (response.writableEnded) finishSoon(state);
2774
+ registerPlatformLifetime(state, context);
2775
+ return await afterStorage.run(state, handler);
2776
+ }
2777
+ __name(_runWithAfterNodeResponse, "_runWithAfterNodeResponse");
2778
+ function _withAfterNodeMiddleware(handler) {
2779
+ return async (request, response, next) => {
2780
+ await _runWithAfterNodeResponse(response, () => handler(request, response, next));
2781
+ };
2782
+ }
2783
+ __name(_withAfterNodeMiddleware, "_withAfterNodeMiddleware");
2784
+
2785
+ // src/api/vite-plugin.ts
2786
+ function farmApiPlugin(options = {}) {
2787
+ const srcDir = options.srcDir ?? "src";
2788
+ const debug = options.debug ?? false;
2789
+ let apiRoutesCache = /* @__PURE__ */ new Map();
2790
+ let apiRouterHandler = null;
2791
+ let discoveryComplete = false;
2792
+ let discoveryPromise = null;
2793
+ const log = /* @__PURE__ */ __name((_message) => {
2794
+ }, "log");
2795
+ const logResponse = /* @__PURE__ */ __name((method, urlPath, status, duration) => {
2796
+ try {
2797
+ const pc = require("picocolors");
2798
+ let statusColor = pc.green;
2799
+ if (status >= 500) statusColor = pc.red;
2800
+ else if (status >= 400) statusColor = pc.yellow;
2801
+ else if (status >= 300) statusColor = pc.cyan;
2802
+ const logMsg = [
2803
+ pc.dim("[") + pc.bold(pc.blue("FARM")) + pc.dim("]"),
2804
+ pc.dim("[") + pc.bold(pc.cyan("API")) + pc.dim("]"),
2805
+ pc.dim("[") + pc.bold(pc.white(method.padEnd(3))) + pc.dim("]"),
2806
+ pc.gray(urlPath),
2807
+ pc.dim("-"),
2808
+ statusColor(status.toString()),
2809
+ pc.dim(`(${duration}ms)`)
2810
+ ].join(" ");
2811
+ console.log(logMsg);
2812
+ } catch {
2813
+ console.log(`[FARM] [API] [${method}] ${urlPath} - ${status} (${duration}ms)`);
2814
+ }
2815
+ }, "logResponse");
2816
+ const addEndpoint = /* @__PURE__ */ __name((routePath, filePath, method, endpoint) => {
2817
+ const normalizedMethod = method.toUpperCase();
2818
+ const existing = apiRoutesCache.get(routePath);
2819
+ if (existing) {
2820
+ if (!existing.methods.includes(normalizedMethod)) {
2821
+ existing.methods.push(normalizedMethod);
2822
+ }
2823
+ existing.endpoints[normalizedMethod] = endpoint;
2824
+ return;
2825
+ }
2826
+ apiRoutesCache.set(routePath, {
2827
+ path: routePath,
2828
+ filePath,
2829
+ methods: [normalizedMethod],
2830
+ endpoints: { [normalizedMethod]: endpoint }
2831
+ });
2832
+ }, "addEndpoint");
2833
+ const createRouter = /* @__PURE__ */ __name(async () => {
2834
+ const totalEndpoints = Array.from(apiRoutesCache.values()).reduce(
2835
+ (sum, route) => sum + route.methods.length,
2836
+ 0
2837
+ );
2838
+ apiRouterHandler = null;
2839
+ if (totalEndpoints > 0) {
2840
+ apiRouterHandler = /* @__PURE__ */ __name(async (request) => {
2841
+ const url = new URL(request.url);
2842
+ const method = request.method.toUpperCase();
2843
+ const pathname = url.pathname;
2844
+ const match = matchAPIRoute(apiRoutesCache, pathname);
2845
+ if (!match) {
2846
+ return new Response(JSON.stringify({ error: "Not Found" }), {
2847
+ status: 404,
2848
+ headers: { "Content-Type": "application/json" }
2849
+ });
2850
+ }
2851
+ const { route, params } = match;
2852
+ const endpoint = route.endpoints[method];
2853
+ if (!endpoint) {
2854
+ return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
2855
+ status: 405,
2856
+ headers: { "Content-Type": "application/json" }
2857
+ });
2858
+ }
2859
+ try {
2860
+ return await invokeAPIRouteEndpoint(endpoint, request, params);
2861
+ } catch (error) {
2862
+ return new Response(JSON.stringify({ error: error.message || "Internal Server Error" }), {
2863
+ status: 500,
2864
+ headers: { "Content-Type": "application/json" }
2865
+ });
2866
+ }
2867
+ }, "apiRouterHandler");
2868
+ log(`API router created with ${totalEndpoints} endpoints`);
2869
+ }
2870
+ }, "createRouter");
2871
+ return {
2872
+ name: "@farm.js/core:api",
2873
+ enforce: "pre",
2874
+ configureServer(server) {
2875
+ const discoverFileRoutes = /* @__PURE__ */ __name(async (apiDir) => {
2876
+ const fs2 = await import("fs");
2877
+ const path4 = await import("path");
2878
+ if (!fs2.existsSync(apiDir)) {
2879
+ log("No api directory found");
2880
+ return;
2881
+ }
2882
+ const findRouteFiles = /* @__PURE__ */ __name((dir) => {
2883
+ const files = [];
2884
+ if (!fs2.existsSync(dir)) return files;
2885
+ const entries = fs2.readdirSync(dir, { withFileTypes: true });
2886
+ for (const entry of entries) {
2887
+ const fullPath = path4.join(dir, entry.name);
2888
+ if (entry.isDirectory()) {
2889
+ files.push(...findRouteFiles(fullPath));
2890
+ } else if (entry.name === "route.ts" || entry.name === "route.tsx" || entry.name === "route.js") {
2891
+ files.push(fullPath);
2892
+ }
2893
+ }
2894
+ return files;
2895
+ }, "findRouteFiles");
2896
+ const routeFiles = findRouteFiles(apiDir);
2897
+ apiRoutesCache.clear();
2898
+ for (const filePath of routeFiles) {
2899
+ try {
2900
+ const relativePath = path4.relative(apiDir, path4.dirname(filePath));
2901
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
2902
+ const routeModule = await server.ssrLoadModule(filePath);
2903
+ const endpoints = {};
2904
+ const availableMethods = [];
2905
+ for (const method of API_ROUTE_METHODS) {
2906
+ if (routeModule[method]) {
2907
+ availableMethods.push(method);
2908
+ endpoints[method] = routeModule[method];
2909
+ }
2910
+ }
2911
+ if (availableMethods.length > 0) {
2912
+ apiRoutesCache.set(routePath, {
2913
+ path: routePath,
2914
+ filePath,
2915
+ methods: availableMethods,
2916
+ endpoints
2917
+ });
2918
+ log(`API route discovered: ${availableMethods.join(", ")} ${routePath}`);
2919
+ }
2920
+ } catch (e) {
2921
+ log(`API route load failed at ${filePath}: ${e.message}`);
2922
+ }
2923
+ }
2924
+ }, "discoverFileRoutes");
2925
+ const discoverRootRoutes = /* @__PURE__ */ __name(async () => {
2926
+ const fs2 = await import("fs");
2927
+ const path4 = await import("path");
2928
+ const routesFiles = [
2929
+ path4.join(server.config.root, srcDir, "routes.ts"),
2930
+ path4.join(server.config.root, srcDir, "routes.tsx"),
2931
+ path4.join(server.config.root, srcDir, "routes.js")
2932
+ ];
2933
+ for (const routesFile of routesFiles) {
2934
+ if (fs2.existsSync(routesFile)) {
2935
+ try {
2936
+ const routesModule = await server.ssrLoadModule(routesFile);
2937
+ for (const [exportName, exportValue] of Object.entries(routesModule)) {
2938
+ const endpoint = exportValue;
2939
+ if (endpoint && endpoint.__path) {
2940
+ const routePath = endpoint.__path;
2941
+ const method = String(endpoint.__method || "GET").toUpperCase();
2942
+ addEndpoint(routePath, routesFile, method, endpoint);
2943
+ log(`Root route discovered: ${method} ${routePath}`);
2944
+ }
2945
+ }
2946
+ } catch (e) {
2947
+ log(`Root routes.ts load failed: ${e.message}`);
2948
+ }
2949
+ break;
2950
+ }
2951
+ }
2952
+ }, "discoverRootRoutes");
2953
+ const discoverProgrammaticRoutes = /* @__PURE__ */ __name(async () => {
2954
+ const path4 = await import("path");
2955
+ const srcRoot = path4.join(server.config.root, srcDir);
2956
+ const routeFiles = findProgrammaticRouteFilesInDir(srcRoot);
2957
+ for (const routeFile of routeFiles) {
2958
+ try {
2959
+ const routesModule = await server.ssrLoadModule(
2960
+ toViteModuleId(routeFile, server.config.root)
2961
+ );
2962
+ const manifest = getProgrammaticRouteManifest(routesModule);
2963
+ if (!manifest) continue;
2964
+ for (const definition of manifest.routes) {
2965
+ if (definition.kind !== "api") continue;
2966
+ for (const [method, endpoint] of Object.entries(definition.methods)) {
2967
+ if (endpoint) {
2968
+ addEndpoint(definition.path, routeFile, method, endpoint);
2969
+ log(`Programmatic route discovered: ${method} ${definition.path}`);
2970
+ }
2971
+ }
2972
+ }
2973
+ } catch (e) {
2974
+ log(`Programmatic routes file load failed at ${routeFile}: ${e.message}`);
2975
+ }
2976
+ }
2977
+ }, "discoverProgrammaticRoutes");
2978
+ const initializeDiscovery = /* @__PURE__ */ __name(async () => {
2979
+ const path4 = await import("path");
2980
+ const apiDir = path4.join(server.config.root, srcDir, "api");
2981
+ log(`Discovering API routes in: ${apiDir}`);
2982
+ await discoverFileRoutes(apiDir);
2983
+ await discoverRootRoutes();
2984
+ await discoverProgrammaticRoutes();
2985
+ await createRouter();
2986
+ discoveryComplete = true;
2987
+ log(`API discovery complete: ${apiRoutesCache.size} routes found`);
2988
+ }, "initializeDiscovery");
2989
+ discoveryPromise = initializeDiscovery().catch((e) => {
2990
+ console.error("[FARM] API discovery error:", e);
2991
+ });
2992
+ server.__farmApi__ = {
2993
+ getHandler: /* @__PURE__ */ __name(() => apiRouterHandler, "getHandler"),
2994
+ getRoutes: /* @__PURE__ */ __name(() => apiRoutesCache, "getRoutes"),
2995
+ isReady: /* @__PURE__ */ __name(() => discoveryComplete, "isReady"),
2996
+ waitForDiscovery: /* @__PURE__ */ __name(() => discoveryPromise, "waitForDiscovery")
2997
+ };
2998
+ return () => {
2999
+ server.middlewares.use(_withAfterNodeMiddleware(async (req, res, next) => {
3000
+ const url = req.url || "/";
3001
+ const pathname = url.split("?")[0];
3002
+ const method = req.method || "GET";
3003
+ if (discoveryPromise && !discoveryComplete) {
3004
+ await discoveryPromise;
3005
+ }
3006
+ if (!matchAPIRoute(apiRoutesCache, pathname)) {
3007
+ return next();
3008
+ }
3009
+ if (!apiRouterHandler) {
3010
+ return next();
3011
+ }
3012
+ const startTime = Date.now();
3013
+ try {
3014
+ const farmMiddleware = server.__farmMiddleware__;
3015
+ if (farmMiddleware) {
3016
+ await farmMiddleware.waitForDiscovery?.();
3017
+ const middlewareData = /* @__PURE__ */ new Map();
3018
+ const handled = await farmMiddleware.execute(req, res, pathname, middlewareData);
3019
+ if (handled) {
3020
+ const duration2 = Date.now() - startTime;
3021
+ logResponse(method, pathname, res.statusCode || 200, duration2);
3022
+ return;
3023
+ }
3024
+ }
3025
+ const fullUrl = `http://${req.headers.host || "localhost:3000"}${url}`;
3026
+ const headers = new Headers();
3027
+ for (const [key, value] of Object.entries(req.headers)) {
3028
+ if (value) {
3029
+ headers.set(key, Array.isArray(value) ? value.join(", ") : value);
3030
+ }
3031
+ }
3032
+ let body;
3033
+ if (method !== "GET" && method !== "HEAD") {
3034
+ body = await new Promise((resolve) => {
3035
+ let data = "";
3036
+ req.on("data", (chunk) => {
3037
+ data += chunk;
3038
+ });
3039
+ req.on("end", () => {
3040
+ resolve(data);
3041
+ });
3042
+ });
3043
+ }
3044
+ const request = new Request(fullUrl, {
3045
+ method,
3046
+ headers,
3047
+ body: body || void 0
3048
+ });
3049
+ const response = await apiRouterHandler(request);
3050
+ const duration = Date.now() - startTime;
3051
+ logResponse(method, pathname, response.status, duration);
3052
+ await sendWebResponse(res, response);
3053
+ } catch (error) {
3054
+ const duration = Date.now() - startTime;
3055
+ logResponse(method, pathname, 500, duration);
3056
+ console.error("[FARM] API error:", error);
3057
+ res.statusCode = 500;
3058
+ res.setHeader("Content-Type", "application/json");
3059
+ res.end(JSON.stringify({ error: "Internal server error" }));
3060
+ }
3061
+ }));
3062
+ };
3063
+ },
3064
+ async handleHotUpdate({ file, server, modules }) {
3065
+ const fileName = file.split("/").pop() || "";
3066
+ if (fileName === "routes.ts" || fileName === "routes.tsx" || fileName === "routes.js" || isProgrammaticRoutesFileName(fileName)) {
3067
+ log(`Root routes file updated: ${fileName}`);
3068
+ for (const mod of modules) {
3069
+ server.moduleGraph.invalidateModule(mod);
3070
+ }
3071
+ for (const [routePath, route] of apiRoutesCache) {
3072
+ if (route.filePath === file) {
3073
+ apiRoutesCache.delete(routePath);
3074
+ }
3075
+ }
3076
+ try {
3077
+ const routesModule = await server.ssrLoadModule(file);
3078
+ for (const [exportName, exportValue] of Object.entries(routesModule)) {
3079
+ const endpoint = exportValue;
3080
+ if (endpoint && endpoint.__path) {
3081
+ const routePath = endpoint.__path;
3082
+ const method = String(endpoint.__method || "GET").toUpperCase();
3083
+ addEndpoint(routePath, file, method, endpoint);
3084
+ log(`Root route reloaded: ${method} ${routePath}`);
3085
+ }
3086
+ }
3087
+ const manifest = getProgrammaticRouteManifest(routesModule);
3088
+ if (manifest) {
3089
+ for (const definition of manifest.routes) {
3090
+ if (definition.kind !== "api") continue;
3091
+ for (const [method, endpoint] of Object.entries(definition.methods)) {
3092
+ if (endpoint) {
3093
+ addEndpoint(definition.path, file, method, endpoint);
3094
+ log(`Programmatic route reloaded: ${method} ${definition.path}`);
3095
+ }
3096
+ }
3097
+ }
3098
+ }
3099
+ await createRouter();
3100
+ log(`API router recreated`);
3101
+ } catch (e) {
3102
+ log(`Root routes.ts HMR failed: ${e.message}`);
3103
+ }
3104
+ return [];
3105
+ }
3106
+ if (file.includes("/api/") && fileName.startsWith("route.")) {
3107
+ const shortPath = file.split("/api/")[1] || file;
3108
+ log(`API route updated: ${shortPath}`);
3109
+ for (const mod of modules) {
3110
+ server.moduleGraph.invalidateModule(mod);
3111
+ }
3112
+ let routePathToUpdate = null;
3113
+ for (const [routePath, route] of apiRoutesCache) {
3114
+ if (route.filePath === file) {
3115
+ routePathToUpdate = routePath;
3116
+ break;
3117
+ }
3118
+ }
3119
+ if (routePathToUpdate) {
3120
+ try {
3121
+ const routeModule = await server.ssrLoadModule(file);
3122
+ const endpoints = {};
3123
+ const availableMethods = [];
3124
+ for (const method of API_ROUTE_METHODS) {
3125
+ if (routeModule[method]) {
3126
+ availableMethods.push(method);
3127
+ endpoints[method] = routeModule[method];
3128
+ }
3129
+ }
3130
+ if (availableMethods.length > 0) {
3131
+ apiRoutesCache.set(routePathToUpdate, {
3132
+ path: routePathToUpdate,
3133
+ filePath: file,
3134
+ methods: availableMethods,
3135
+ endpoints
3136
+ });
3137
+ log(`API route reloaded: ${routePathToUpdate}`);
3138
+ await createRouter();
3139
+ log(`API router recreated`);
3140
+ }
3141
+ } catch (e) {
3142
+ log(`API route HMR failed: ${e.message}`);
3143
+ }
3144
+ } else {
3145
+ try {
3146
+ const path4 = await import("path");
3147
+ const apiDir = path4.join(server.config.root, srcDir, "api");
3148
+ const relativePath = path4.relative(apiDir, path4.dirname(file));
3149
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
3150
+ const routeModule = await server.ssrLoadModule(file);
3151
+ const endpoints = {};
3152
+ const availableMethods = [];
3153
+ for (const method of API_ROUTE_METHODS) {
3154
+ if (routeModule[method]) {
3155
+ availableMethods.push(method);
3156
+ endpoints[method] = routeModule[method];
3157
+ }
3158
+ }
3159
+ if (availableMethods.length > 0) {
3160
+ apiRoutesCache.set(routePath, {
3161
+ path: routePath,
3162
+ filePath: file,
3163
+ methods: availableMethods,
3164
+ endpoints
3165
+ });
3166
+ log(`New API route discovered: ${routePath}`);
3167
+ await createRouter();
3168
+ }
3169
+ } catch (e) {
3170
+ log(`New API route load failed: ${e.message}`);
3171
+ }
3172
+ }
3173
+ return [];
3174
+ }
3175
+ }
3176
+ };
3177
+ }
3178
+ __name(farmApiPlugin, "farmApiPlugin");
3179
+ // Annotate the CommonJS export names for ESM import in node:
3180
+ 0 && (module.exports = {
3181
+ APIRouteManager,
3182
+ API_ROUTE_METHODS,
3183
+ DELETE,
3184
+ GET,
3185
+ HEAD,
3186
+ OPTIONS,
3187
+ PATCH,
3188
+ POST,
3189
+ PUT,
3190
+ createAPIClient,
3191
+ createEndpoint,
3192
+ createServerAPIClient,
3193
+ farmApiPlugin,
3194
+ invokeAPIRouteEndpoint,
3195
+ isWebResponse,
3196
+ matchAPIRoute,
3197
+ normalizeRouteResponse
3198
+ });
3199
+ //# sourceMappingURL=api.cjs.map