@farm.js/core 0.1.17 → 0.1.18

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 (249) hide show
  1. package/dist/after.cjs +12 -225
  2. package/dist/agent-runtime.cjs +83 -2800
  3. package/dist/api/client.cjs +17 -4060
  4. package/dist/api/route-manager.cjs +34 -4354
  5. package/dist/api/runtime.cjs +29 -2696
  6. package/dist/api.cjs +88 -8434
  7. package/dist/app-markdown.cjs +39 -280
  8. package/dist/cache.cjs +38 -1560
  9. package/dist/chunk-22GUSVNJ.cjs +351 -0
  10. package/dist/chunk-2CQ74SP6.cjs +13 -0
  11. package/dist/chunk-2SJ4RQ6P.cjs +57 -0
  12. package/dist/chunk-3376ZTRC.cjs +1 -0
  13. package/dist/{chunk-YD4J4XCI.mjs → chunk-3XG26Z3J.mjs} +1 -1
  14. package/dist/chunk-4PNUXIVU.cjs +472 -0
  15. package/dist/chunk-4PPEPOZZ.cjs +21 -0
  16. package/dist/chunk-4ZFL5GFN.cjs +520 -0
  17. package/dist/chunk-5OVTOKGH.cjs +65 -0
  18. package/dist/chunk-5QIKR7RR.cjs +224 -0
  19. package/dist/chunk-5ZSWG4UX.cjs +127 -0
  20. package/dist/chunk-62YJ2IEB.cjs +238 -0
  21. package/dist/chunk-6EODJYCX.cjs +183 -0
  22. package/dist/chunk-6EXBPJ24.cjs +434 -0
  23. package/dist/chunk-6QQDAAAZ.cjs +38 -0
  24. package/dist/chunk-6V4TDWEC.cjs +455 -0
  25. package/dist/chunk-72ADZ6GQ.cjs +19 -0
  26. package/dist/chunk-75BRBIFP.cjs +172 -0
  27. package/dist/chunk-7W3CPVXS.cjs +24 -0
  28. package/dist/chunk-A6WIQH5Z.cjs +31 -0
  29. package/dist/chunk-AFOD3LYZ.cjs +377 -0
  30. package/dist/chunk-AMDMVWMI.cjs +39 -0
  31. package/dist/chunk-AORPIPNB.cjs +552 -0
  32. package/dist/chunk-ARJWXNQL.cjs +256 -0
  33. package/dist/chunk-AWRISO2H.cjs +2199 -0
  34. package/dist/chunk-AYJR42WX.cjs +711 -0
  35. package/dist/chunk-B4CH33IG.cjs +644 -0
  36. package/dist/chunk-BIDYX3SL.cjs +91 -0
  37. package/dist/chunk-BSTRERPP.cjs +40 -0
  38. package/dist/chunk-BYODCJD6.cjs +663 -0
  39. package/dist/chunk-C3VRMB6H.cjs +85 -0
  40. package/dist/chunk-C5GUTBZK.cjs +173 -0
  41. package/dist/chunk-CIAGU2X4.cjs +337 -0
  42. package/dist/chunk-CMGMGHUZ.cjs +27 -0
  43. package/dist/chunk-CXP5U3RW.cjs +54 -0
  44. package/dist/chunk-D2ULAULS.cjs +166 -0
  45. package/dist/chunk-D7JTOLFK.cjs +285 -0
  46. package/dist/chunk-DVM4FKZL.cjs +169 -0
  47. package/dist/chunk-DYEJQTDN.cjs +49 -0
  48. package/dist/chunk-E2BMSZ2W.cjs +151 -0
  49. package/dist/chunk-E3UK5IIB.cjs +593 -0
  50. package/dist/chunk-EM6SBQKM.cjs +470 -0
  51. package/dist/chunk-FJSWYIR7.cjs +482 -0
  52. package/dist/chunk-FK6GO24V.cjs +54 -0
  53. package/dist/chunk-FXUUWYAX.cjs +654 -0
  54. package/dist/chunk-G3HRIVEY.cjs +395 -0
  55. package/dist/chunk-G643DQCH.cjs +13 -0
  56. package/dist/chunk-G7HXGLEC.cjs +175 -0
  57. package/dist/chunk-GDSHDTJ4.cjs +152 -0
  58. package/dist/chunk-GNEO2XOF.cjs +2040 -0
  59. package/dist/{chunk-56DAX2BE.mjs → chunk-GYKJCFTS.mjs} +1 -1
  60. package/dist/chunk-H6G5INWM.cjs +1094 -0
  61. package/dist/chunk-HBTUGXHS.cjs +180 -0
  62. package/dist/chunk-HREOKQWT.cjs +45 -0
  63. package/dist/chunk-I4J452B7.cjs +435 -0
  64. package/dist/chunk-I57LW5VZ.cjs +94 -0
  65. package/dist/chunk-I7PUUDGY.cjs +389 -0
  66. package/dist/chunk-IAMRBF3Z.cjs +86 -0
  67. package/dist/chunk-IKNRN4VS.cjs +14214 -0
  68. package/dist/chunk-IQXFRNY2.cjs +169 -0
  69. package/dist/chunk-IXTFU4PL.cjs +2355 -0
  70. package/dist/chunk-J2OP5GG3.cjs +725 -0
  71. package/dist/chunk-J3LOGE4T.cjs +42 -0
  72. package/dist/chunk-J7FSKED3.cjs +93 -0
  73. package/dist/chunk-JDNHKPTD.cjs +22 -0
  74. package/dist/chunk-JSROZYYO.cjs +164 -0
  75. package/dist/chunk-K6FNHVDR.cjs +696 -0
  76. package/dist/chunk-KGZIORNL.cjs +43 -0
  77. package/dist/{chunk-MVIWBEJF.mjs → chunk-KPNVGRBL.mjs} +1 -1
  78. package/dist/chunk-KR6CKSXT.cjs +15 -0
  79. package/dist/chunk-KROWKCUH.cjs +185 -0
  80. package/dist/chunk-KVFPGF2M.cjs +46 -0
  81. package/dist/chunk-LCCBO7PJ.cjs +46 -0
  82. package/dist/chunk-LIUGYUX3.cjs +22 -0
  83. package/dist/chunk-LTNGXMQ6.cjs +55 -0
  84. package/dist/chunk-M2L4MYDQ.cjs +14 -0
  85. package/dist/chunk-MCJLA63J.cjs +1 -0
  86. package/dist/chunk-MKB2EGIR.cjs +148 -0
  87. package/dist/chunk-MQ3H6LT5.cjs +202 -0
  88. package/dist/chunk-MT763TDW.cjs +43 -0
  89. package/dist/chunk-MWSK6C4J.cjs +18 -0
  90. package/dist/chunk-MWWVKDW3.cjs +169 -0
  91. package/dist/chunk-NO3WWW3N.cjs +192 -0
  92. package/dist/chunk-NV3A5DXM.cjs +862 -0
  93. package/dist/chunk-NWOD6NIT.cjs +9 -0
  94. package/dist/chunk-NZKJGRB3.cjs +230 -0
  95. package/dist/chunk-OAVTUMJP.cjs +1496 -0
  96. package/dist/chunk-OHY2ZWUG.cjs +25 -0
  97. package/dist/chunk-OI6CMLWX.cjs +47 -0
  98. package/dist/chunk-OIEOCXKG.cjs +453 -0
  99. package/dist/chunk-OWOUTKIJ.cjs +558 -0
  100. package/dist/chunk-OX6O6WVA.cjs +74 -0
  101. package/dist/chunk-OXSIH4D6.cjs +476 -0
  102. package/dist/chunk-OYEUREB6.cjs +35 -0
  103. package/dist/chunk-PCOTGFSM.cjs +139 -0
  104. package/dist/chunk-PZYCPSCC.cjs +35 -0
  105. package/dist/chunk-QBK2AA4U.cjs +445 -0
  106. package/dist/chunk-QBPXNZGV.cjs +487 -0
  107. package/dist/chunk-QNPEUFHQ.cjs +27 -0
  108. package/dist/chunk-QZRVZSPN.cjs +236 -0
  109. package/dist/chunk-R5A5KNVX.cjs +20 -0
  110. package/dist/chunk-R5JIFR6B.cjs +42 -0
  111. package/dist/chunk-R6AIILII.cjs +193 -0
  112. package/dist/chunk-RG3ZOTG5.cjs +34 -0
  113. package/dist/chunk-ROUTX2E5.cjs +390 -0
  114. package/dist/chunk-RTHIVJ2G.cjs +54 -0
  115. package/dist/chunk-S3A45T7F.cjs +166 -0
  116. package/dist/chunk-S3JO3N4H.cjs +17 -0
  117. package/dist/chunk-SK35NQKK.cjs +27 -0
  118. package/dist/chunk-SU7MH53P.cjs +180 -0
  119. package/dist/chunk-SVRTJOUF.cjs +113 -0
  120. package/dist/chunk-SWN467MP.cjs +18 -0
  121. package/dist/chunk-SYQ3MOWW.cjs +73 -0
  122. package/dist/chunk-T5CERMEH.cjs +417 -0
  123. package/dist/chunk-TFAXUHWX.cjs +206 -0
  124. package/dist/chunk-TIWHTW3Q.cjs +24 -0
  125. package/dist/chunk-TKJZFIML.cjs +20 -0
  126. package/dist/chunk-TKNSDBBN.cjs +193 -0
  127. package/dist/chunk-TWGMSEHX.cjs +525 -0
  128. package/dist/chunk-TYQUSXUG.cjs +1357 -0
  129. package/dist/chunk-U4KT7QP3.cjs +23 -0
  130. package/dist/chunk-UJ2C4ICS.cjs +277 -0
  131. package/dist/chunk-UN5GHC5V.cjs +10244 -0
  132. package/dist/chunk-UQZ4AYTH.cjs +168 -0
  133. package/dist/chunk-US2QVW3E.cjs +36 -0
  134. package/dist/chunk-VB6UCX3V.cjs +421 -0
  135. package/dist/chunk-VEKFLAQM.cjs +300 -0
  136. package/dist/chunk-VQDBNVOO.cjs +14 -0
  137. package/dist/chunk-W4E7WMXE.cjs +71 -0
  138. package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
  139. package/dist/chunk-WMAPPDMM.cjs +28 -0
  140. package/dist/chunk-WMOGFOUJ.cjs +223 -0
  141. package/dist/chunk-WPYFSQKK.cjs +37 -0
  142. package/dist/chunk-WZMNW2IW.cjs +1415 -0
  143. package/dist/chunk-XGC343EY.cjs +443 -0
  144. package/dist/chunk-XSKZORAS.cjs +727 -0
  145. package/dist/chunk-XWAWFQFS.cjs +82 -0
  146. package/dist/chunk-Y4YMF2NQ.cjs +460 -0
  147. package/dist/chunk-Y4YWHNKU.cjs +250 -0
  148. package/dist/chunk-Y53ZSFN6.cjs +504 -0
  149. package/dist/chunk-YA6LLTIJ.cjs +411 -0
  150. package/dist/chunk-YFPGHF5F.cjs +202 -0
  151. package/dist/chunk-YJRZR7VU.cjs +28 -0
  152. package/dist/chunk-YTAABQEV.cjs +1 -0
  153. package/dist/chunk-YX3DBN4M.cjs +18 -0
  154. package/dist/chunk-YZTASLPQ.cjs +64 -0
  155. package/dist/chunk-Z5HIWVDP.cjs +2173 -0
  156. package/dist/chunk-ZEG3OPIB.cjs +93 -0
  157. package/dist/chunk-ZMN3H73H.cjs +155 -0
  158. package/dist/client/lifecycle.cjs +6 -35
  159. package/dist/client-plugins.cjs +7 -448
  160. package/dist/client.cjs +171 -9808
  161. package/dist/config.cjs +8 -36
  162. package/dist/cron.cjs +24 -491
  163. package/dist/deferred.cjs +26 -475
  164. package/dist/deployment.cjs +39 -210
  165. package/dist/devtools-OUIPHVV6.cjs +388 -0
  166. package/dist/devtools-client-4WAPJY5L.cjs +254 -0
  167. package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
  168. package/dist/docs.cjs +46 -5657
  169. package/dist/env-types.cjs +5 -226
  170. package/dist/env.cjs +21 -338
  171. package/dist/environment/vite.cjs +8 -372
  172. package/dist/environment.cjs +12 -94
  173. package/dist/font.cjs +13 -63
  174. package/dist/headers.cjs +7 -123
  175. package/dist/i18n/client.cjs +55 -294
  176. package/dist/i18n/index.cjs +22 -209
  177. package/dist/i18n/server.cjs +22 -745
  178. package/dist/image/server.cjs +13 -729
  179. package/dist/image/sharp.cjs +33 -171
  180. package/dist/image.cjs +41 -85
  181. package/dist/index.cjs +1151 -68080
  182. package/dist/index.mjs +3 -3
  183. package/dist/instrumentation.cjs +12 -138
  184. package/dist/integration-orm-55F7CII5.cjs +13 -0
  185. package/dist/integrations.cjs +55 -4090
  186. package/dist/internal/app-markdown-runtime.cjs +27 -224
  187. package/dist/internal/build-runtime.cjs +120 -52259
  188. package/dist/internal/build-runtime.mjs +3 -3
  189. package/dist/internal/cli-runtime.cjs +67 -13811
  190. package/dist/internal/client-error-overlay.cjs +80 -733
  191. package/dist/internal/client-error-overlay.mjs +1 -1
  192. package/dist/internal/client-runtime.cjs +81 -913
  193. package/dist/internal/compression-runtime.cjs +8 -214
  194. package/dist/internal/config-runtime.cjs +42 -6547
  195. package/dist/internal/docs-precompiled-runtime.cjs +26 -46
  196. package/dist/internal/infra-analytics-runtime.cjs +10 -536
  197. package/dist/internal/isolated-boundary.cjs +14 -414
  198. package/dist/internal/metadata-image-runtime.cjs +7 -285
  199. package/dist/internal/product-telemetry-runtime.cjs +42 -97
  200. package/dist/internal/product-telemetry-runtime.mjs +1 -1
  201. package/dist/internal/production-node-env.cjs +6 -63
  202. package/dist/internal/production-runtime.cjs +418 -7133
  203. package/dist/internal/request-cookies.cjs +6 -54
  204. package/dist/json-ld.cjs +24 -50
  205. package/dist/layers-E4WPJNY5.cjs +17 -0
  206. package/dist/manager-G4B2IPYE.cjs +14 -0
  207. package/dist/markdown.cjs +21 -547
  208. package/dist/middleware.cjs +36 -2995
  209. package/dist/navigation.cjs +22 -2588
  210. package/dist/nitro-4I2MYLY2.cjs +652 -0
  211. package/dist/observability.cjs +22 -614
  212. package/dist/og.cjs +5 -28
  213. package/dist/plugin.cjs +106 -37442
  214. package/dist/plugin.mjs +2 -2
  215. package/dist/query/client.cjs +113 -449
  216. package/dist/query/index.cjs +26 -288
  217. package/dist/query/parsers.cjs +23 -247
  218. package/dist/query/server.cjs +36 -298
  219. package/dist/renderer/react/client.cjs +9 -43
  220. package/dist/renderer/react/server.cjs +40 -103
  221. package/dist/renderer/react/vite.cjs +7 -29
  222. package/dist/renderer-client.cjs +126 -4295
  223. package/dist/renderer.cjs +31 -249
  224. package/dist/request.cjs +5 -68
  225. package/dist/router.cjs +11 -474
  226. package/dist/routes.cjs +42 -2461
  227. package/dist/schema-dev-notice-MXSZMVDG.cjs +56 -0
  228. package/dist/schema.cjs +6 -33
  229. package/dist/search-client-G3RICOFU.cjs +13 -0
  230. package/dist/server-action-security.cjs +25 -541
  231. package/dist/server-fn-client.cjs +6 -337
  232. package/dist/server-fn.cjs +32 -1841
  233. package/dist/server-plugins.cjs +15 -884
  234. package/dist/server-query-client.cjs +15 -1883
  235. package/dist/server-query.cjs +16 -1838
  236. package/dist/server.cjs +296 -44681
  237. package/dist/server.mjs +2 -2
  238. package/dist/storage.cjs +57 -576
  239. package/dist/testing.cjs +89 -3186
  240. package/dist/theme/client.cjs +13 -108
  241. package/dist/theme/index.cjs +6 -68
  242. package/dist/theme/runtime.cjs +13 -78
  243. package/dist/theme/server.cjs +10 -179
  244. package/dist/version.cjs +4 -32
  245. package/dist/version.mjs +1 -1
  246. package/dist/vite.cjs +119 -37773
  247. package/dist/vite.mjs +2 -2
  248. package/dist/workflows.cjs +19 -1040
  249. package/package.json +1 -1
@@ -0,0 +1,552 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunk4PPEPOZZcjs = require('./chunk-4PPEPOZZ.cjs');
4
+
5
+
6
+ var _chunkMQ3H6LT5cjs = require('./chunk-MQ3H6LT5.cjs');
7
+
8
+
9
+ var _chunkAFOD3LYZcjs = require('./chunk-AFOD3LYZ.cjs');
10
+
11
+
12
+ var _chunkIAMRBF3Zcjs = require('./chunk-IAMRBF3Z.cjs');
13
+
14
+
15
+ var _chunk2CQ74SP6cjs = require('./chunk-2CQ74SP6.cjs');
16
+
17
+
18
+
19
+
20
+
21
+
22
+ var _chunk4PNUXIVUcjs = require('./chunk-4PNUXIVU.cjs');
23
+
24
+
25
+ var _chunk6V4TDWECcjs = require('./chunk-6V4TDWEC.cjs');
26
+
27
+
28
+
29
+
30
+ var _chunkEM6SBQKMcjs = require('./chunk-EM6SBQKM.cjs');
31
+
32
+
33
+ var _chunkM2L4MYDQcjs = require('./chunk-M2L4MYDQ.cjs');
34
+
35
+
36
+
37
+ var _chunk5QIKR7RRcjs = require('./chunk-5QIKR7RR.cjs');
38
+
39
+
40
+ var _chunkUQZ4AYTHcjs = require('./chunk-UQZ4AYTH.cjs');
41
+
42
+
43
+ var _chunk5ZSWG4UXcjs = require('./chunk-5ZSWG4UX.cjs');
44
+
45
+
46
+
47
+
48
+ var _chunkNO3WWW3Ncjs = require('./chunk-NO3WWW3N.cjs');
49
+
50
+
51
+ var _chunkS3JO3N4Hcjs = require('./chunk-S3JO3N4H.cjs');
52
+
53
+ // src/api/vite-plugin.ts
54
+ function farmApiPlugin(options = {}) {
55
+ const srcDir = _nullishCoalesce(options.srcDir, () => ( "src"));
56
+ const debug = _nullishCoalesce(options.debug, () => ( false));
57
+ const bodySizeLimit = _chunkEM6SBQKMcjs.resolveFarmServerConfig.call(void 0, {
58
+ bodySizeLimit: options.bodySizeLimit
59
+ }).bodySizeLimit;
60
+ const basePath = options.basePath;
61
+ let apiRoutesCache = /* @__PURE__ */ new Map();
62
+ let apiRouterHandler = null;
63
+ let discoveryComplete = false;
64
+ let discoveryPromise = null;
65
+ let discoveryError;
66
+ let recoverFailedDiscovery;
67
+ const endpointSources = /* @__PURE__ */ new Map();
68
+ const routeShapes = /* @__PURE__ */ new Map();
69
+ const log = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (_message) => {
70
+ }, "log");
71
+ const logResponse = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (method, urlPath, status, duration) => {
72
+ const pc = _chunkM2L4MYDQcjs.createCliColors.call(void 0, );
73
+ let statusColor = pc.green;
74
+ if (status >= 500) statusColor = pc.red;
75
+ else if (status >= 400) statusColor = pc.yellow;
76
+ else if (status >= 300) statusColor = pc.cyan;
77
+ const logMsg = [
78
+ pc.dim("[") + pc.bold(pc.blue("FARM")) + pc.dim("]"),
79
+ pc.dim("[") + pc.bold(pc.cyan("API")) + pc.dim("]"),
80
+ pc.dim("[") + pc.bold(pc.white(method.padEnd(3))) + pc.dim("]"),
81
+ pc.gray(urlPath),
82
+ pc.dim("-"),
83
+ statusColor(status.toString()),
84
+ pc.dim(`(${duration}ms)`)
85
+ ].join(" ");
86
+ console.log(logMsg);
87
+ }, "logResponse");
88
+ const registerRouteShape = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (routePath, filePath) => {
89
+ _chunkNO3WWW3Ncjs.assertUniqueRouteParameters.call(void 0, routePath, "api");
90
+ const shape = _chunkNO3WWW3Ncjs.getRoutePatternShape.call(void 0, routePath, "api");
91
+ const existing = routeShapes.get(shape);
92
+ if (existing && existing.routePath !== routePath) {
93
+ throw new (0, _chunkNO3WWW3Ncjs.AmbiguousRouteError)(
94
+ `Ambiguous API routes "${existing.routePath}" and "${routePath}" match the same URLs. Found ${existing.filePath} and ${filePath}. Keep only one route for this URL shape.`
95
+ );
96
+ }
97
+ routeShapes.set(shape, { routePath, filePath });
98
+ }, "registerRouteShape");
99
+ const addEndpoint = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (routePath, filePath, method, endpoint) => {
100
+ registerRouteShape(routePath, filePath);
101
+ const normalizedMethod = method.toUpperCase();
102
+ const existing = apiRoutesCache.get(routePath);
103
+ const existingFile = _optionalChain([endpointSources, 'access', _ => _.get, 'call', _2 => _2(routePath), 'optionalAccess', _3 => _3.get, 'call', _4 => _4(normalizedMethod)]);
104
+ if (existingFile) {
105
+ throw new (0, _chunkAFOD3LYZcjs.APIRouteConflictError)(routePath, normalizedMethod, existingFile, filePath);
106
+ }
107
+ if (existing) {
108
+ if (!existing.methods.includes(normalizedMethod)) {
109
+ existing.methods.push(normalizedMethod);
110
+ }
111
+ existing.endpoints[normalizedMethod] = endpoint;
112
+ const sources = _nullishCoalesce(endpointSources.get(routePath), () => ( /* @__PURE__ */ new Map()));
113
+ sources.set(normalizedMethod, filePath);
114
+ endpointSources.set(routePath, sources);
115
+ return;
116
+ }
117
+ apiRoutesCache.set(routePath, {
118
+ path: routePath,
119
+ filePath,
120
+ methods: [normalizedMethod],
121
+ endpoints: { [normalizedMethod]: endpoint }
122
+ });
123
+ endpointSources.set(routePath, /* @__PURE__ */ new Map([[normalizedMethod, filePath]]));
124
+ }, "addEndpoint");
125
+ const removeEndpointsFromFile = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (filePath) => {
126
+ for (const [routePath, sources] of endpointSources) {
127
+ const route = apiRoutesCache.get(routePath);
128
+ if (!route) continue;
129
+ for (const [method, sourceFile] of sources) {
130
+ if (sourceFile !== filePath) continue;
131
+ sources.delete(method);
132
+ route.methods = route.methods.filter((candidate) => candidate !== method);
133
+ delete route.endpoints[method];
134
+ }
135
+ if (route.methods.length === 0) {
136
+ apiRoutesCache.delete(routePath);
137
+ endpointSources.delete(routePath);
138
+ routeShapes.delete(_chunkNO3WWW3Ncjs.getRoutePatternShape.call(void 0, routePath, "api"));
139
+ } else {
140
+ const currentSource = sources.values().next().value;
141
+ if (route.filePath === filePath && currentSource) {
142
+ route.filePath = currentSource;
143
+ }
144
+ routeShapes.set(_chunkNO3WWW3Ncjs.getRoutePatternShape.call(void 0, routePath, "api"), {
145
+ routePath,
146
+ filePath: _nullishCoalesce(currentSource, () => ( route.filePath))
147
+ });
148
+ }
149
+ }
150
+ }, "removeEndpointsFromFile");
151
+ const snapshotRouteState = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => ({
152
+ routes: new Map(
153
+ [...apiRoutesCache].map(([routePath, route]) => [
154
+ routePath,
155
+ {
156
+ ...route,
157
+ methods: [...route.methods],
158
+ endpoints: { ...route.endpoints }
159
+ }
160
+ ])
161
+ ),
162
+ sources: new Map(
163
+ [...endpointSources].map(([routePath, sources]) => [routePath, new Map(sources)])
164
+ ),
165
+ shapes: new Map(routeShapes)
166
+ }), "snapshotRouteState");
167
+ const restoreRouteState = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (snapshot) => {
168
+ apiRoutesCache = snapshot.routes;
169
+ endpointSources.clear();
170
+ for (const [routePath, sources] of snapshot.sources) {
171
+ endpointSources.set(routePath, sources);
172
+ }
173
+ routeShapes.clear();
174
+ for (const [shape, route] of snapshot.shapes) {
175
+ routeShapes.set(shape, route);
176
+ }
177
+ }, "restoreRouteState");
178
+ const createRouter = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
179
+ const totalEndpoints = Array.from(apiRoutesCache.values()).reduce(
180
+ (sum, route) => sum + route.methods.length,
181
+ 0
182
+ );
183
+ apiRouterHandler = null;
184
+ if (totalEndpoints > 0) {
185
+ apiRouterHandler = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (request) => {
186
+ const url = new URL(request.url);
187
+ const method = request.method.toUpperCase();
188
+ const pathname = url.pathname;
189
+ const match = _chunk4PNUXIVUcjs.matchAPIRouteAtBasePath.call(void 0, apiRoutesCache, pathname, basePath);
190
+ if (!match) {
191
+ return new Response(JSON.stringify({ error: "Not Found" }), {
192
+ status: 404,
193
+ headers: { "Content-Type": "application/json" }
194
+ });
195
+ }
196
+ const { route, params } = match;
197
+ const endpoint = _chunk4PNUXIVUcjs.resolveAPIRouteEndpoint.call(void 0, route, method);
198
+ if (!endpoint) {
199
+ return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
200
+ status: 405,
201
+ headers: {
202
+ Allow: _chunk4PNUXIVUcjs.getAllowedAPIRouteMethods.call(void 0, route).join(", "),
203
+ "Content-Type": "application/json"
204
+ }
205
+ });
206
+ }
207
+ try {
208
+ return await _chunk4PNUXIVUcjs.invokeAPIRouteEndpoint.call(void 0, endpoint, request, params, bodySizeLimit);
209
+ } catch (error) {
210
+ return new Response(JSON.stringify({ error: error.message || "Internal Server Error" }), {
211
+ status: 500,
212
+ headers: { "Content-Type": "application/json" }
213
+ });
214
+ }
215
+ }, "apiRouterHandler");
216
+ log(`API router created with ${totalEndpoints} endpoints`);
217
+ }
218
+ }, "createRouter");
219
+ return {
220
+ name: "@farm.js/core:api",
221
+ enforce: "pre",
222
+ configureServer(server) {
223
+ const discoverFileRoutes = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (apiDir) => {
224
+ const fs = await import("fs");
225
+ const path = await import("path");
226
+ if (!fs.existsSync(apiDir)) {
227
+ log("No api directory found");
228
+ return;
229
+ }
230
+ const findRouteFiles = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (dir) => {
231
+ const files = [];
232
+ if (!fs.existsSync(dir)) return files;
233
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
234
+ for (const entry of entries) {
235
+ const fullPath = path.join(dir, entry.name);
236
+ if (entry.isDirectory()) {
237
+ files.push(...findRouteFiles(fullPath));
238
+ } else if (_chunk2CQ74SP6cjs.isFarmAPIRouteFileName.call(void 0, entry.name)) {
239
+ files.push(fullPath);
240
+ }
241
+ }
242
+ return files;
243
+ }, "findRouteFiles");
244
+ const routeFiles = findRouteFiles(apiDir);
245
+ apiRoutesCache.clear();
246
+ endpointSources.clear();
247
+ routeShapes.clear();
248
+ for (const filePath of routeFiles) {
249
+ try {
250
+ const relativePath = path.relative(apiDir, path.dirname(filePath));
251
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
252
+ const routeModule = await server.ssrLoadModule(filePath);
253
+ const endpoints = {};
254
+ const availableMethods = [];
255
+ for (const method of _chunk4PNUXIVUcjs.API_ROUTE_METHODS) {
256
+ if (routeModule[method]) {
257
+ availableMethods.push(method);
258
+ endpoints[method] = routeModule[method];
259
+ }
260
+ }
261
+ if (availableMethods.length > 0) {
262
+ for (const method of availableMethods) {
263
+ addEndpoint(routePath, filePath, method, endpoints[method]);
264
+ }
265
+ log(`API route discovered: ${availableMethods.join(", ")} ${routePath}`);
266
+ }
267
+ } catch (e) {
268
+ if (e instanceof _chunkAFOD3LYZcjs.APIRouteConflictError || e instanceof _chunkNO3WWW3Ncjs.AmbiguousRouteError) throw e;
269
+ log(`API route load failed at ${filePath}: ${e.message}`);
270
+ }
271
+ }
272
+ }, "discoverFileRoutes");
273
+ const discoverRootRoutes = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
274
+ const fs = await import("fs");
275
+ const path = await import("path");
276
+ const routesFiles = [
277
+ path.join(server.config.root, srcDir, "routes.ts"),
278
+ path.join(server.config.root, srcDir, "routes.tsx"),
279
+ path.join(server.config.root, srcDir, "routes.js")
280
+ ];
281
+ for (const routesFile of routesFiles) {
282
+ if (fs.existsSync(routesFile)) {
283
+ try {
284
+ const routesModule = await server.ssrLoadModule(routesFile);
285
+ for (const [exportName, exportValue] of Object.entries(routesModule)) {
286
+ const endpoint = exportValue;
287
+ if (endpoint && endpoint.__path) {
288
+ const routePath = endpoint.__path;
289
+ const method = String(endpoint.__method || "GET").toUpperCase();
290
+ addEndpoint(routePath, routesFile, method, endpoint);
291
+ log(`Root route discovered: ${method} ${routePath}`);
292
+ }
293
+ }
294
+ } catch (e) {
295
+ if (e instanceof _chunkAFOD3LYZcjs.APIRouteConflictError || e instanceof _chunkNO3WWW3Ncjs.AmbiguousRouteError) throw e;
296
+ log(`Root routes.ts load failed: ${e.message}`);
297
+ }
298
+ break;
299
+ }
300
+ }
301
+ }, "discoverRootRoutes");
302
+ const discoverProgrammaticRoutes = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
303
+ const path = await import("path");
304
+ const srcRoot = path.join(server.config.root, srcDir);
305
+ const routeFiles = _chunkIAMRBF3Zcjs.findProgrammaticRouteFilesInDir.call(void 0, srcRoot);
306
+ if (routeFiles.length === 0) return;
307
+ const { getProgrammaticRouteManifest } = await import("./routes.cjs");
308
+ for (const routeFile of routeFiles) {
309
+ try {
310
+ const routesModule = await server.ssrLoadModule(
311
+ _chunk5QIKR7RRcjs.toViteModuleId.call(void 0, routeFile, server.config.root)
312
+ );
313
+ const manifest = getProgrammaticRouteManifest(routesModule);
314
+ if (!manifest) continue;
315
+ for (const definition of manifest.routes) {
316
+ if (definition.kind !== "api") continue;
317
+ for (const [method, endpoint] of Object.entries(definition.methods)) {
318
+ if (endpoint) {
319
+ addEndpoint(definition.path, routeFile, method, endpoint);
320
+ log(`Programmatic route discovered: ${method} ${definition.path}`);
321
+ }
322
+ }
323
+ }
324
+ } catch (e) {
325
+ if (e instanceof _chunkAFOD3LYZcjs.APIRouteConflictError || e instanceof _chunkNO3WWW3Ncjs.AmbiguousRouteError) throw e;
326
+ log(`Programmatic routes file load failed at ${routeFile}: ${e.message}`);
327
+ }
328
+ }
329
+ }, "discoverProgrammaticRoutes");
330
+ const initializeDiscovery = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
331
+ const path = await import("path");
332
+ const apiDir = path.join(server.config.root, srcDir, "api");
333
+ log(`Discovering API routes in: ${apiDir}`);
334
+ await discoverFileRoutes(apiDir);
335
+ await discoverRootRoutes();
336
+ await discoverProgrammaticRoutes();
337
+ await createRouter();
338
+ discoveryComplete = true;
339
+ log(`API discovery complete: ${apiRoutesCache.size} routes found`);
340
+ }, "initializeDiscovery");
341
+ discoveryPromise = initializeDiscovery().catch((e) => {
342
+ discoveryError = e;
343
+ console.error("[FARM] API discovery error:", e);
344
+ });
345
+ const waitForDiscovery = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
346
+ await discoveryPromise;
347
+ if (discoveryError) throw discoveryError;
348
+ }, "waitForDiscovery");
349
+ recoverFailedDiscovery = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
350
+ if (!discoveryError) return false;
351
+ const previousState = snapshotRouteState();
352
+ try {
353
+ await initializeDiscovery();
354
+ discoveryError = void 0;
355
+ discoveryPromise = Promise.resolve();
356
+ } catch (error) {
357
+ restoreRouteState(previousState);
358
+ discoveryError = error;
359
+ discoveryComplete = false;
360
+ discoveryPromise = Promise.resolve();
361
+ throw error;
362
+ }
363
+ return true;
364
+ }, "recoverFailedDiscovery");
365
+ server.__farmApi__ = {
366
+ getHandler: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => apiRouterHandler, "getHandler"),
367
+ getRoutes: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => apiRoutesCache, "getRoutes"),
368
+ isReady: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => discoveryComplete, "isReady"),
369
+ waitForDiscovery
370
+ };
371
+ return () => {
372
+ const apiMiddleware = _chunkMQ3H6LT5cjs._withAfterNodeMiddleware.call(void 0, async (req, res, next) => {
373
+ const url = req.url || "/";
374
+ const pathname = url.split("?")[0];
375
+ const method = req.method || "GET";
376
+ if (discoveryPromise) await waitForDiscovery();
377
+ if (!_chunk4PNUXIVUcjs.matchAPIRouteAtBasePath.call(void 0, apiRoutesCache, pathname, basePath)) {
378
+ return next();
379
+ }
380
+ if (!apiRouterHandler) {
381
+ return next();
382
+ }
383
+ const startTime = Date.now();
384
+ try {
385
+ const farmMiddleware = server.__farmMiddleware__;
386
+ if (farmMiddleware) {
387
+ await _optionalChain([farmMiddleware, 'access', _5 => _5.waitForDiscovery, 'optionalCall', _6 => _6()]);
388
+ const middlewareData = /* @__PURE__ */ new Map();
389
+ const handled = await farmMiddleware.execute(req, res, pathname, middlewareData);
390
+ if (handled) {
391
+ const duration2 = Date.now() - startTime;
392
+ logResponse(method, pathname, res.statusCode || 200, duration2);
393
+ return;
394
+ }
395
+ }
396
+ const currentUrl = req.url || url;
397
+ const currentPathname = currentUrl.split("?")[0];
398
+ if (currentPathname !== pathname && !_chunk4PNUXIVUcjs.matchAPIRouteAtBasePath.call(void 0, apiRoutesCache, currentPathname, basePath)) {
399
+ return next();
400
+ }
401
+ const fullUrl = _chunk5ZSWG4UXcjs.resolveFarmRequestURL.call(void 0, req);
402
+ const headers = new Headers();
403
+ for (const [key, value] of Object.entries(req.headers)) {
404
+ if (value) {
405
+ headers.set(key, Array.isArray(value) ? value.join(", ") : value);
406
+ }
407
+ }
408
+ let body;
409
+ if (method !== "GET" && method !== "HEAD") {
410
+ body = await _chunkEM6SBQKMcjs.readNodeRequestBody.call(void 0, req, bodySizeLimit);
411
+ }
412
+ const request = new Request(fullUrl, {
413
+ method,
414
+ headers,
415
+ body: body ? body.buffer.slice(
416
+ body.byteOffset,
417
+ body.byteOffset + body.byteLength
418
+ ) : void 0
419
+ });
420
+ const response = await apiRouterHandler(request);
421
+ const duration = Date.now() - startTime;
422
+ logResponse(method, currentPathname, response.status, duration);
423
+ await _chunkUQZ4AYTHcjs.sendWebResponse.call(void 0, res, response);
424
+ } catch (error) {
425
+ const bodyErrorResponse = _chunkEM6SBQKMcjs.createFarmRequestBodyErrorResponse.call(void 0, error);
426
+ if (bodyErrorResponse) {
427
+ await _chunkUQZ4AYTHcjs.sendWebResponse.call(void 0, res, bodyErrorResponse);
428
+ return;
429
+ }
430
+ const duration = Date.now() - startTime;
431
+ logResponse(method, pathname, 500, duration);
432
+ console.error("[FARM] API error:", error);
433
+ res.statusCode = 500;
434
+ res.setHeader("Content-Type", "application/json");
435
+ res.end(JSON.stringify({ error: "Internal server error" }));
436
+ }
437
+ });
438
+ server.middlewares.use((req, res, next) => {
439
+ const result = _chunk4PPEPOZZcjs._runWithAPIRequestRuntime.call(void 0,
440
+ {
441
+ basePath: _nullishCoalesce(basePath, () => ( "/api")),
442
+ dispatch: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (request) => apiRouterHandler ? apiRouterHandler(request) : Response.json({ error: "Not Found" }, { status: 404 }), "dispatch")
443
+ },
444
+ () => apiMiddleware(req, res, next)
445
+ );
446
+ return Promise.resolve(result).catch((error) => {
447
+ console.error(
448
+ `[FARM] Unhandled API error while handling ${req.method || "GET"} ${req.url || "/"}:`,
449
+ error
450
+ );
451
+ if (res.writableEnded) return;
452
+ if (res.headersSent) {
453
+ _optionalChain([res, 'access', _7 => _7.destroy, 'optionalCall', _8 => _8(error instanceof Error ? error : new Error(String(error)))]);
454
+ return;
455
+ }
456
+ res.statusCode = 500;
457
+ res.setHeader("Content-Type", "application/json");
458
+ res.end(JSON.stringify({ error: "Internal server error" }));
459
+ });
460
+ });
461
+ };
462
+ },
463
+ async handleHotUpdate({ file, server, modules }) {
464
+ const normalizedFile = _chunk5QIKR7RRcjs.toPosixPath.call(void 0, file);
465
+ const fileName = normalizedFile.split("/").pop() || "";
466
+ if (fileName === "routes.ts" || fileName === "routes.tsx" || fileName === "routes.js" || _chunk6V4TDWECcjs.isProgrammaticRoutesFileName.call(void 0, fileName)) {
467
+ log(`Root routes file updated: ${fileName}`);
468
+ for (const mod of modules) {
469
+ server.moduleGraph.invalidateModule(mod);
470
+ }
471
+ if (await _optionalChain([recoverFailedDiscovery, 'optionalCall', _9 => _9()])) return [];
472
+ const previousState = snapshotRouteState();
473
+ try {
474
+ const routesModule = await server.ssrLoadModule(file);
475
+ removeEndpointsFromFile(file);
476
+ for (const [exportName, exportValue] of Object.entries(routesModule)) {
477
+ const endpoint = exportValue;
478
+ if (endpoint && endpoint.__path) {
479
+ const routePath = endpoint.__path;
480
+ const method = String(endpoint.__method || "GET").toUpperCase();
481
+ addEndpoint(routePath, file, method, endpoint);
482
+ log(`Root route reloaded: ${method} ${routePath}`);
483
+ }
484
+ }
485
+ const { getProgrammaticRouteManifest } = await import("./routes.cjs");
486
+ const manifest = getProgrammaticRouteManifest(routesModule);
487
+ if (manifest) {
488
+ for (const definition of manifest.routes) {
489
+ if (definition.kind !== "api") continue;
490
+ for (const [method, endpoint] of Object.entries(definition.methods)) {
491
+ if (endpoint) {
492
+ addEndpoint(definition.path, file, method, endpoint);
493
+ log(`Programmatic route reloaded: ${method} ${definition.path}`);
494
+ }
495
+ }
496
+ }
497
+ }
498
+ await createRouter();
499
+ log(`API router recreated`);
500
+ } catch (e) {
501
+ restoreRouteState(previousState);
502
+ if (e instanceof _chunkAFOD3LYZcjs.APIRouteConflictError || e instanceof _chunkNO3WWW3Ncjs.AmbiguousRouteError) throw e;
503
+ log(`Root routes.ts HMR failed: ${e.message}`);
504
+ }
505
+ return [];
506
+ }
507
+ if (normalizedFile.includes("/api/") && fileName.startsWith("route.")) {
508
+ const shortPath = normalizedFile.split("/api/")[1] || normalizedFile;
509
+ log(`API route updated: ${shortPath}`);
510
+ for (const mod of modules) {
511
+ server.moduleGraph.invalidateModule(mod);
512
+ }
513
+ if (await _optionalChain([recoverFailedDiscovery, 'optionalCall', _10 => _10()])) return [];
514
+ const previousState = snapshotRouteState();
515
+ try {
516
+ const path = await import("path");
517
+ const apiDir = path.join(server.config.root, srcDir, "api");
518
+ const relativePath = path.relative(apiDir, path.dirname(file));
519
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
520
+ const fs = await import("fs");
521
+ if (!fs.existsSync(file)) {
522
+ removeEndpointsFromFile(file);
523
+ await createRouter();
524
+ log(`API route file removed: ${routePath}`);
525
+ return [];
526
+ }
527
+ const routeModule = await server.ssrLoadModule(file);
528
+ removeEndpointsFromFile(file);
529
+ const availableMethods = [];
530
+ for (const method of _chunk4PNUXIVUcjs.API_ROUTE_METHODS) {
531
+ if (!routeModule[method]) continue;
532
+ availableMethods.push(method);
533
+ addEndpoint(routePath, file, method, routeModule[method]);
534
+ }
535
+ await createRouter();
536
+ log(`API route reloaded: ${availableMethods.join(", ")} ${routePath}`);
537
+ log(`API router recreated`);
538
+ } catch (e) {
539
+ restoreRouteState(previousState);
540
+ if (e instanceof _chunkAFOD3LYZcjs.APIRouteConflictError || e instanceof _chunkNO3WWW3Ncjs.AmbiguousRouteError) throw e;
541
+ log(`API route HMR failed: ${e.message}`);
542
+ }
543
+ return [];
544
+ }
545
+ }
546
+ };
547
+ }
548
+ _chunkS3JO3N4Hcjs.__name.call(void 0, farmApiPlugin, "farmApiPlugin");
549
+
550
+
551
+
552
+ exports.farmApiPlugin = farmApiPlugin;