@farm.js/core 0.1.17 → 0.1.19

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 (269) 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/app-markdown.mjs +3 -3
  9. package/dist/cache.cjs +38 -1560
  10. package/dist/chunk-22GUSVNJ.cjs +351 -0
  11. package/dist/{chunk-EN7WTEAY.mjs → chunk-2ANEVVF7.mjs} +1 -1
  12. package/dist/chunk-2CQ74SP6.cjs +13 -0
  13. package/dist/{chunk-YD4J4XCI.mjs → chunk-2GNATDDE.mjs} +1 -1
  14. package/dist/chunk-2SJ4RQ6P.cjs +57 -0
  15. package/dist/chunk-3376ZTRC.cjs +1 -0
  16. package/dist/chunk-4PNUXIVU.cjs +472 -0
  17. package/dist/chunk-4PPEPOZZ.cjs +21 -0
  18. package/dist/chunk-4ZFL5GFN.cjs +520 -0
  19. package/dist/chunk-5OVTOKGH.cjs +65 -0
  20. package/dist/chunk-5QIKR7RR.cjs +224 -0
  21. package/dist/chunk-5ZSWG4UX.cjs +127 -0
  22. package/dist/chunk-62YJ2IEB.cjs +238 -0
  23. package/dist/chunk-6EODJYCX.cjs +183 -0
  24. package/dist/chunk-6EXBPJ24.cjs +434 -0
  25. package/dist/chunk-6QQDAAAZ.cjs +38 -0
  26. package/dist/chunk-6V4TDWEC.cjs +455 -0
  27. package/dist/chunk-72ADZ6GQ.cjs +19 -0
  28. package/dist/chunk-75BRBIFP.cjs +172 -0
  29. package/dist/{chunk-ZCNJKLA2.mjs → chunk-7BC6GAL7.mjs} +1 -1
  30. package/dist/chunk-7W3CPVXS.cjs +24 -0
  31. package/dist/chunk-A6WIQH5Z.cjs +31 -0
  32. package/dist/chunk-A777V5WU.cjs +725 -0
  33. package/dist/chunk-AFOD3LYZ.cjs +377 -0
  34. package/dist/chunk-AH7HOAQ3.cjs +151 -0
  35. package/dist/chunk-AMDMVWMI.cjs +39 -0
  36. package/dist/chunk-AORPIPNB.cjs +552 -0
  37. package/dist/chunk-ARJWXNQL.cjs +256 -0
  38. package/dist/chunk-AYJR42WX.cjs +711 -0
  39. package/dist/chunk-BBVSJVBZ.cjs +600 -0
  40. package/dist/chunk-BIDYX3SL.cjs +91 -0
  41. package/dist/chunk-BYODCJD6.cjs +663 -0
  42. package/dist/chunk-C3VRMB6H.cjs +85 -0
  43. package/dist/chunk-C5GUTBZK.cjs +173 -0
  44. package/dist/chunk-CIAGU2X4.cjs +337 -0
  45. package/dist/chunk-CMGMGHUZ.cjs +27 -0
  46. package/dist/chunk-CXP5U3RW.cjs +54 -0
  47. package/dist/chunk-D2ULAULS.cjs +166 -0
  48. package/dist/chunk-D7JTOLFK.cjs +285 -0
  49. package/dist/chunk-DVM4FKZL.cjs +169 -0
  50. package/dist/chunk-DYEJQTDN.cjs +49 -0
  51. package/dist/chunk-E2ROOWQC.cjs +2225 -0
  52. package/dist/chunk-E3UK5IIB.cjs +593 -0
  53. package/dist/chunk-EM6SBQKM.cjs +470 -0
  54. package/dist/chunk-FJSWYIR7.cjs +482 -0
  55. package/dist/chunk-FK6GO24V.cjs +54 -0
  56. package/dist/{chunk-MVIWBEJF.mjs → chunk-FVZGEVTO.mjs} +7 -7
  57. package/dist/chunk-FXUUWYAX.cjs +654 -0
  58. package/dist/chunk-G3HRIVEY.cjs +395 -0
  59. package/dist/chunk-G643DQCH.cjs +13 -0
  60. package/dist/chunk-G7HXGLEC.cjs +175 -0
  61. package/dist/chunk-GDSHDTJ4.cjs +152 -0
  62. package/dist/chunk-GPVTX3HT.cjs +1415 -0
  63. package/dist/chunk-H6G5INWM.cjs +1094 -0
  64. package/dist/{chunk-DHDVMXYK.mjs → chunk-HALDNTIV.mjs} +30 -4
  65. package/dist/chunk-HBTUGXHS.cjs +180 -0
  66. package/dist/chunk-HREOKQWT.cjs +45 -0
  67. package/dist/{chunk-5QOEPUYE.mjs → chunk-HSDL2AUR.mjs} +1 -1
  68. package/dist/chunk-I4J452B7.cjs +435 -0
  69. package/dist/chunk-I57LW5VZ.cjs +94 -0
  70. package/dist/chunk-I5YBCWQ6.cjs +40 -0
  71. package/dist/chunk-I7PUUDGY.cjs +389 -0
  72. package/dist/chunk-IAMRBF3Z.cjs +86 -0
  73. package/dist/chunk-IQXFRNY2.cjs +169 -0
  74. package/dist/chunk-ISTFC3MZ.cjs +1357 -0
  75. package/dist/chunk-IXTFU4PL.cjs +2355 -0
  76. package/dist/chunk-J3LOGE4T.cjs +42 -0
  77. package/dist/chunk-J7FSKED3.cjs +93 -0
  78. package/dist/chunk-JDNHKPTD.cjs +22 -0
  79. package/dist/chunk-JSROZYYO.cjs +164 -0
  80. package/dist/chunk-K6FNHVDR.cjs +696 -0
  81. package/dist/chunk-KGZIORNL.cjs +43 -0
  82. package/dist/chunk-KR6CKSXT.cjs +15 -0
  83. package/dist/chunk-KROWKCUH.cjs +185 -0
  84. package/dist/chunk-KVFPGF2M.cjs +46 -0
  85. package/dist/{chunk-TNBAYAWO.mjs → chunk-L4DVIHOC.mjs} +1 -1
  86. package/dist/chunk-LCCBO7PJ.cjs +46 -0
  87. package/dist/chunk-LIUGYUX3.cjs +22 -0
  88. package/dist/chunk-LTNGXMQ6.cjs +55 -0
  89. package/dist/chunk-M2L4MYDQ.cjs +14 -0
  90. package/dist/chunk-MCJLA63J.cjs +1 -0
  91. package/dist/chunk-MKB2EGIR.cjs +148 -0
  92. package/dist/chunk-MQ3H6LT5.cjs +202 -0
  93. package/dist/chunk-MT763TDW.cjs +43 -0
  94. package/dist/{chunk-XWAYMDLB.mjs → chunk-MVUREHPN.mjs} +1 -1
  95. package/dist/chunk-MWSK6C4J.cjs +18 -0
  96. package/dist/chunk-MWWVKDW3.cjs +169 -0
  97. package/dist/{chunk-6VQIKZZO.mjs → chunk-N255VYFP.mjs} +1 -1
  98. package/dist/chunk-NBAHDVOJ.cjs +2040 -0
  99. package/dist/chunk-NO3WWW3N.cjs +192 -0
  100. package/dist/chunk-NSFC3LHB.cjs +10244 -0
  101. package/dist/chunk-NZKJGRB3.cjs +230 -0
  102. package/dist/chunk-OAVTUMJP.cjs +1496 -0
  103. package/dist/{chunk-SXHV42UQ.mjs → chunk-OFEY6KHO.mjs} +88 -13
  104. package/dist/chunk-OHY2ZWUG.cjs +25 -0
  105. package/dist/chunk-OI6CMLWX.cjs +47 -0
  106. package/dist/chunk-OWOUTKIJ.cjs +558 -0
  107. package/dist/chunk-OX6O6WVA.cjs +74 -0
  108. package/dist/chunk-OXSIH4D6.cjs +476 -0
  109. package/dist/chunk-OYDRPBBV.cjs +453 -0
  110. package/dist/chunk-OYEUREB6.cjs +35 -0
  111. package/dist/chunk-PCOTGFSM.cjs +139 -0
  112. package/dist/{chunk-76DG3LF3.mjs → chunk-PGQBL5DN.mjs} +1 -1
  113. package/dist/chunk-PZYCPSCC.cjs +35 -0
  114. package/dist/chunk-QBK2AA4U.cjs +445 -0
  115. package/dist/{chunk-UTBVHYS3.mjs → chunk-QBPKKQTD.mjs} +2 -2
  116. package/dist/chunk-QBPXNZGV.cjs +487 -0
  117. package/dist/chunk-QNPEUFHQ.cjs +27 -0
  118. package/dist/chunk-QZRVZSPN.cjs +236 -0
  119. package/dist/chunk-R5A5KNVX.cjs +20 -0
  120. package/dist/chunk-R5JIFR6B.cjs +42 -0
  121. package/dist/chunk-R6AIILII.cjs +193 -0
  122. package/dist/chunk-RFYO7QUD.cjs +9 -0
  123. package/dist/chunk-RG3ZOTG5.cjs +34 -0
  124. package/dist/chunk-ROUTX2E5.cjs +390 -0
  125. package/dist/chunk-RTHIVJ2G.cjs +54 -0
  126. package/dist/chunk-S27FMYAM.cjs +644 -0
  127. package/dist/chunk-S3A45T7F.cjs +166 -0
  128. package/dist/chunk-S3JO3N4H.cjs +17 -0
  129. package/dist/chunk-SK35NQKK.cjs +27 -0
  130. package/dist/chunk-SU7MH53P.cjs +180 -0
  131. package/dist/chunk-SVRTJOUF.cjs +113 -0
  132. package/dist/chunk-SWN467MP.cjs +18 -0
  133. package/dist/chunk-SYQ3MOWW.cjs +73 -0
  134. package/dist/chunk-T5CERMEH.cjs +417 -0
  135. package/dist/chunk-TFAXUHWX.cjs +206 -0
  136. package/dist/chunk-TIWHTW3Q.cjs +24 -0
  137. package/dist/chunk-TKJZFIML.cjs +20 -0
  138. package/dist/chunk-TKNSDBBN.cjs +193 -0
  139. package/dist/chunk-U4KT7QP3.cjs +23 -0
  140. package/dist/chunk-U5BMPGS3.cjs +862 -0
  141. package/dist/chunk-UJ2C4ICS.cjs +277 -0
  142. package/dist/chunk-UQZ4AYTH.cjs +168 -0
  143. package/dist/chunk-US2QVW3E.cjs +36 -0
  144. package/dist/{chunk-QGVJVSNX.mjs → chunk-V4AICMQA.mjs} +2 -2
  145. package/dist/chunk-VB6UCX3V.cjs +421 -0
  146. package/dist/chunk-VEKFLAQM.cjs +300 -0
  147. package/dist/chunk-VQDBNVOO.cjs +14 -0
  148. package/dist/chunk-W4E7WMXE.cjs +71 -0
  149. package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
  150. package/dist/chunk-WMAPPDMM.cjs +28 -0
  151. package/dist/chunk-WMOGFOUJ.cjs +223 -0
  152. package/dist/chunk-WPYFSQKK.cjs +37 -0
  153. package/dist/{chunk-56DAX2BE.mjs → chunk-WZXN4R5Y.mjs} +24 -13
  154. package/dist/chunk-XDGMADQM.cjs +14225 -0
  155. package/dist/chunk-XGC343EY.cjs +443 -0
  156. package/dist/chunk-XSKZORAS.cjs +727 -0
  157. package/dist/chunk-XWAWFQFS.cjs +82 -0
  158. package/dist/chunk-Y4YMF2NQ.cjs +460 -0
  159. package/dist/chunk-Y4YWHNKU.cjs +250 -0
  160. package/dist/chunk-Y53ZSFN6.cjs +504 -0
  161. package/dist/chunk-YA6LLTIJ.cjs +411 -0
  162. package/dist/chunk-YFPGHF5F.cjs +202 -0
  163. package/dist/chunk-YJRZR7VU.cjs +28 -0
  164. package/dist/chunk-YTAABQEV.cjs +1 -0
  165. package/dist/chunk-YX3DBN4M.cjs +18 -0
  166. package/dist/chunk-YZTASLPQ.cjs +64 -0
  167. package/dist/chunk-Z5HIWVDP.cjs +2173 -0
  168. package/dist/chunk-ZEG3OPIB.cjs +93 -0
  169. package/dist/chunk-ZMN3H73H.cjs +155 -0
  170. package/dist/client/lifecycle.cjs +6 -35
  171. package/dist/client-plugins.cjs +7 -448
  172. package/dist/client.cjs +171 -9808
  173. package/dist/config.cjs +8 -36
  174. package/dist/cron.cjs +24 -491
  175. package/dist/deferred.cjs +26 -475
  176. package/dist/deployment.cjs +39 -210
  177. package/dist/devtools-5KGPDVKL.cjs +388 -0
  178. package/dist/{devtools-UFVTMQX5.mjs → devtools-FY5R7TQ4.mjs} +3 -3
  179. package/dist/devtools-client-4WAPJY5L.cjs +254 -0
  180. package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
  181. package/dist/docs.cjs +46 -5657
  182. package/dist/docs.mjs +5 -5
  183. package/dist/env-types.cjs +5 -226
  184. package/dist/env.cjs +21 -338
  185. package/dist/environment/vite.cjs +8 -372
  186. package/dist/environment.cjs +12 -94
  187. package/dist/font.cjs +13 -63
  188. package/dist/headers.cjs +7 -123
  189. package/dist/i18n/client.cjs +55 -294
  190. package/dist/i18n/index.cjs +22 -209
  191. package/dist/i18n/server.cjs +22 -745
  192. package/dist/image/server.cjs +13 -729
  193. package/dist/image/sharp.cjs +33 -171
  194. package/dist/image.cjs +41 -85
  195. package/dist/index.cjs +1151 -68080
  196. package/dist/index.mjs +14 -14
  197. package/dist/instrumentation.cjs +12 -138
  198. package/dist/integration-orm-55F7CII5.cjs +13 -0
  199. package/dist/integrations.cjs +55 -4090
  200. package/dist/internal/app-markdown-runtime.cjs +27 -224
  201. package/dist/internal/app-markdown-runtime.mjs +2 -2
  202. package/dist/internal/build-runtime.cjs +120 -52259
  203. package/dist/internal/build-runtime.mjs +13 -13
  204. package/dist/internal/cli-runtime.cjs +67 -13811
  205. package/dist/internal/cli-runtime.mjs +7 -7
  206. package/dist/internal/client-error-overlay.cjs +80 -733
  207. package/dist/internal/client-error-overlay.mjs +1 -1
  208. package/dist/internal/client-runtime.cjs +81 -913
  209. package/dist/internal/compression-runtime.cjs +8 -214
  210. package/dist/internal/config-runtime.cjs +42 -6547
  211. package/dist/internal/config-runtime.mjs +3 -3
  212. package/dist/internal/docs-precompiled-runtime.cjs +26 -46
  213. package/dist/internal/infra-analytics-runtime.cjs +10 -536
  214. package/dist/internal/isolated-boundary.cjs +14 -414
  215. package/dist/internal/metadata-image-runtime.cjs +7 -285
  216. package/dist/internal/product-telemetry-runtime.cjs +42 -97
  217. package/dist/internal/product-telemetry-runtime.mjs +1 -1
  218. package/dist/internal/production-node-env.cjs +6 -63
  219. package/dist/internal/production-runtime.cjs +418 -7133
  220. package/dist/internal/production-runtime.mjs +3 -3
  221. package/dist/internal/request-cookies.cjs +6 -54
  222. package/dist/json-ld.cjs +24 -50
  223. package/dist/layers-E4WPJNY5.cjs +17 -0
  224. package/dist/manager-G4B2IPYE.cjs +14 -0
  225. package/dist/markdown.cjs +21 -547
  226. package/dist/markdown.mjs +1 -1
  227. package/dist/middleware.cjs +36 -2995
  228. package/dist/navigation.cjs +22 -2588
  229. package/dist/nitro-4I2MYLY2.cjs +652 -0
  230. package/dist/observability.cjs +22 -614
  231. package/dist/og.cjs +5 -28
  232. package/dist/plugin.cjs +106 -37442
  233. package/dist/plugin.mjs +9 -9
  234. package/dist/query/client.cjs +113 -449
  235. package/dist/query/index.cjs +26 -288
  236. package/dist/query/parsers.cjs +23 -247
  237. package/dist/query/server.cjs +36 -298
  238. package/dist/renderer/react/client.cjs +9 -43
  239. package/dist/renderer/react/server.cjs +40 -103
  240. package/dist/renderer/react/vite.cjs +7 -29
  241. package/dist/renderer-client.cjs +126 -4295
  242. package/dist/renderer.cjs +31 -249
  243. package/dist/request.cjs +5 -68
  244. package/dist/router.cjs +11 -474
  245. package/dist/routes.cjs +42 -2461
  246. package/dist/{schema-dev-notice-2IE2F2XI.mjs → schema-dev-notice-O67CPXJ6.mjs} +1 -1
  247. package/dist/schema-dev-notice-Y7MQEFGN.cjs +56 -0
  248. package/dist/schema.cjs +6 -33
  249. package/dist/search-client-G3RICOFU.cjs +13 -0
  250. package/dist/server-action-security.cjs +25 -541
  251. package/dist/server-fn-client.cjs +6 -337
  252. package/dist/server-fn.cjs +32 -1841
  253. package/dist/server-plugins.cjs +15 -884
  254. package/dist/server-query-client.cjs +15 -1883
  255. package/dist/server-query.cjs +16 -1838
  256. package/dist/server.cjs +296 -44681
  257. package/dist/server.mjs +11 -11
  258. package/dist/storage.cjs +57 -576
  259. package/dist/testing.cjs +89 -3186
  260. package/dist/theme/client.cjs +13 -108
  261. package/dist/theme/index.cjs +6 -68
  262. package/dist/theme/runtime.cjs +13 -78
  263. package/dist/theme/server.cjs +10 -179
  264. package/dist/version.cjs +4 -32
  265. package/dist/version.mjs +1 -1
  266. package/dist/vite.cjs +119 -37773
  267. package/dist/vite.mjs +9 -9
  268. package/dist/workflows.cjs +19 -1040
  269. package/package.json +1 -1
@@ -1,2742 +1,26 @@
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 __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
-
34
- // src/storage/index.ts
35
- var storage_exports = {};
36
- __export(storage_exports, {
37
- createFarmStorage: () => createFarmStorage,
38
- createStorageClient: () => createStorageClient,
39
- databaseStorage: () => databaseStorage,
40
- defineStorageClient: () => defineStorageClient,
41
- disposeStorage: () => disposeStorage,
42
- driverStorage: () => driverStorage,
43
- getStorage: () => getStorage,
44
- initStorage: () => initStorage,
45
- libsqlStorage: () => libsqlStorage,
46
- localStorage: () => localStorage,
47
- memoryStorage: () => memoryStorage,
48
- mongodbStorage: () => mongodbStorage,
49
- mysql2Storage: () => mysql2Storage,
50
- mysqlStorage: () => mysqlStorage,
51
- netlifyBlobsStorage: () => netlifyBlobsStorage,
52
- pgStorage: () => pgStorage,
53
- pgliteStorage: () => pgliteStorage,
54
- planetscaleStorage: () => planetscaleStorage,
55
- postgresStorage: () => postgresStorage,
56
- redisStorage: () => redisStorage,
57
- resolveStorageRuntimeClient: () => resolveStorageRuntimeClient,
58
- s3Storage: () => s3Storage,
59
- sqliteStorage: () => sqliteStorage,
60
- upstashStorage: () => upstashStorage,
61
- vercelBlobStorage: () => vercelBlobStorage,
62
- vercelKVStorage: () => vercelKVStorage
63
- });
64
- function createMemoryStorage() {
65
- return (0, import_unstorage.createStorage)({
66
- driver: (0, import_memory.default)()
67
- });
68
- }
69
- function readGlobalStorage() {
70
- return globalThis[GLOBAL_STORAGE_KEY];
71
- }
72
- function writeGlobalStorage(storage) {
73
- globalThis[GLOBAL_STORAGE_KEY] = storage;
74
- return storage;
75
- }
76
- function getActiveGlobalStorage() {
77
- const existing = readGlobalStorage();
78
- if (existing) {
79
- return existing;
80
- }
81
- return writeGlobalStorage(createMemoryStorage());
82
- }
83
- function normalizeMountKey(base) {
84
- return (base || "").trim().replace(/^[:/\\]+|[:/\\]+$/g, "").replace(/[\\/]+/g, ":");
85
- }
86
- function isDriverInstance(value) {
87
- return !!value && typeof value === "object" && typeof value.getItem === "function" && typeof value.getKeys === "function";
88
- }
89
- function isStorageInstance(value) {
90
- return !!value && typeof value === "object" && typeof value.mount === "function" && typeof value.getMount === "function";
91
- }
92
- function isStorageClient(value) {
93
- return !!value && typeof value === "object" && value.kind === "farm-storage-client" && typeof value.resolveDriver === "function" && typeof value.createStorage === "function";
94
- }
95
- function isDatabaseDriverName(name) {
96
- return name in DATABASE_CONNECTORS;
97
- }
98
- function extractDriverOptions(config) {
99
- const source = config;
100
- const {
101
- client: _client,
102
- driver: _driver,
103
- mounts: _mounts,
104
- options,
105
- tableName: _tableName,
106
- ...inlineOptions
107
- } = source;
108
- const hasInlineOptions = Object.keys(inlineOptions).length > 0;
109
- if (options && typeof options === "object" && !Array.isArray(options)) {
110
- return hasInlineOptions ? { ...inlineOptions, ...options } : options;
111
- }
112
- if (hasInlineOptions) {
113
- return inlineOptions;
114
- }
115
- return options;
116
- }
117
- async function loadBuiltinDriver(name, options) {
118
- const modulePath = import_unstorage.builtinDrivers[name];
119
- if (!modulePath) {
120
- throw new Error(`Unsupported storage driver "${name}".`);
121
- }
122
- const module2 = await loadModule(modulePath);
123
- return module2.default(options);
124
- }
125
- async function loadDatabaseDriver(config) {
126
- const connectorEntry = DATABASE_CONNECTORS[config.driver];
127
- const [{ createDatabase }, connectorModule, db0DriverModule] = await Promise.all([
128
- loadModule("db0"),
129
- connectorEntry.load(),
130
- loadModule("unstorage/drivers/db0")
131
- ]);
132
- const database = createDatabase(connectorModule.default(extractDriverOptions(config) || {}));
133
- const driver = db0DriverModule.default({
134
- database,
135
- tableName: config.tableName
136
- });
137
- return {
138
- ...driver,
139
- async dispose() {
140
- await database.dispose();
141
- }
142
- };
143
- }
144
- async function resolveDriver(config) {
145
- if (config && isStorageClient(config)) {
146
- return config.resolveDriver();
147
- }
148
- const driverInput = config?.driver ?? "memory";
149
- if (typeof driverInput === "function") {
150
- return await driverInput();
151
- }
152
- if (isDriverInstance(driverInput)) {
153
- return driverInput;
154
- }
155
- if (isDatabaseDriverName(driverInput)) {
156
- return loadDatabaseDriver(config);
157
- }
158
- if (driverInput === "local") {
159
- return loadBuiltinDriver("fs-lite", extractDriverOptions(config));
160
- }
161
- return loadBuiltinDriver(
162
- driverInput,
163
- extractDriverOptions(config)
164
- );
165
- }
166
- function createStorageClientFromResolver(resolveDriver2) {
167
- let driverPromise;
168
- let storagePromise;
169
- const ensureDriver = /* @__PURE__ */ __name(() => {
170
- if (driverPromise) return driverPromise;
171
- const pending = Promise.resolve().then(resolveDriver2);
172
- driverPromise = pending;
173
- void pending.catch(() => {
174
- if (driverPromise === pending) {
175
- driverPromise = void 0;
176
- storagePromise = void 0;
177
- }
178
- });
179
- return pending;
180
- }, "ensureDriver");
181
- const ensureStorage = /* @__PURE__ */ __name(() => {
182
- if (storagePromise) return storagePromise;
183
- const pending = ensureDriver().then(
184
- (driver) => (0, import_unstorage.createStorage)({
185
- driver
186
- })
187
- );
188
- storagePromise = pending;
189
- void pending.catch(() => {
190
- if (storagePromise === pending) storagePromise = void 0;
191
- });
192
- return pending;
193
- }, "ensureStorage");
194
- const target = {
195
- kind: "farm-storage-client",
196
- ready: ensureStorage,
197
- createStorage: ensureStorage,
198
- resolveDriver: ensureDriver
199
- };
200
- return new Proxy(target, {
201
- get(currentTarget, prop, receiver) {
202
- if (prop === "then") {
203
- return void 0;
204
- }
205
- if (Reflect.has(currentTarget, prop)) {
206
- return Reflect.get(currentTarget, prop, receiver);
207
- }
208
- return (...args) => ensureStorage().then(async (storage) => {
209
- const member = Reflect.get(storage, prop);
210
- if (typeof member !== "function") {
211
- return member;
212
- }
213
- const result = Reflect.apply(member, storage, args);
214
- if (prop === "dispose") {
215
- return Promise.resolve(result).finally(() => {
216
- storagePromise = void 0;
217
- driverPromise = void 0;
218
- });
219
- }
220
- return result;
221
- });
222
- }
223
- });
224
- }
225
- function defineStorageClient(resolveDriver2) {
226
- return createStorageClientFromResolver(resolveDriver2);
227
- }
228
- function createStorageClient(config) {
229
- return defineStorageClient(() => resolveDriver(config));
230
- }
231
- function driverStorage(driver) {
232
- return defineStorageClient(() => typeof driver === "function" ? driver() : driver);
233
- }
234
- function databaseStorage(database, options = {}) {
235
- return defineStorageClient(async () => {
236
- const db0DriverModule = await loadModule("unstorage/drivers/db0");
237
- const { dispose: _dispose, ...driver } = db0DriverModule.default({
238
- database,
239
- tableName: options.tableName
240
- });
241
- return driver;
242
- });
243
- }
244
- function memoryStorage() {
245
- return createStorageClient({ driver: "memory" });
246
- }
247
- function localStorage(options = {}) {
248
- return createStorageClient({
249
- driver: "local",
250
- ...options
251
- });
252
- }
253
- function sqliteStorage(options) {
254
- return createStorageClient({
255
- driver: "sqlite",
256
- ...options
257
- });
258
- }
259
- function mysqlStorage(options) {
260
- return createStorageClient({
261
- driver: "mysql",
262
- ...options
263
- });
264
- }
265
- function mysql2Storage(options) {
266
- return mysqlStorage(options);
267
- }
268
- function postgresStorage(options) {
269
- return createStorageClient({
270
- driver: "postgres",
271
- ...options
272
- });
273
- }
274
- function pgStorage(options) {
275
- return postgresStorage(options);
276
- }
277
- function pgliteStorage(options) {
278
- return createStorageClient({
279
- driver: "pglite",
280
- ...options
281
- });
282
- }
283
- function planetscaleStorage(options) {
284
- return createStorageClient({
285
- driver: "planetscale",
286
- ...options
287
- });
288
- }
289
- function libsqlStorage(options) {
290
- return createStorageClient({
291
- driver: "libsql",
292
- ...options
293
- });
294
- }
295
- function redisStorage(options) {
296
- return createStorageClient({
297
- driver: "redis",
298
- ...options
299
- });
300
- }
301
- function s3Storage(options) {
302
- return createStorageClient({
303
- driver: "s3",
304
- ...options
305
- });
306
- }
307
- function mongodbStorage(options) {
308
- return createStorageClient({
309
- driver: "mongodb",
310
- ...options
311
- });
312
- }
313
- function upstashStorage(options) {
314
- return createStorageClient({
315
- driver: "upstash",
316
- ...options
317
- });
318
- }
319
- function netlifyBlobsStorage(options) {
320
- return createStorageClient({
321
- driver: "netlify-blobs",
322
- ...options
323
- });
324
- }
325
- function vercelKVStorage(options) {
326
- return createStorageClient({
327
- driver: "vercel-kv",
328
- ...options
329
- });
330
- }
331
- function vercelBlobStorage(options) {
332
- return createStorageClient({
333
- driver: "vercel-blob",
334
- ...options
335
- });
336
- }
337
- async function mountNamespaces(storage, mounts) {
338
- if (!mounts) {
339
- return;
340
- }
341
- for (const [base, config] of Object.entries(mounts)) {
342
- storage.mount(normalizeMountKey(base), await resolveDriver(config));
343
- }
344
- }
345
- async function createFarmStorage(config = {}) {
346
- if (isStorageInstance(config)) {
347
- return config;
348
- }
349
- if (isStorageClient(config)) {
350
- return config.createStorage();
351
- }
352
- const rootConfig = isStorageClient(config.client) ? config.client : config;
353
- const storage = (0, import_unstorage.createStorage)({
354
- driver: await resolveDriver(rootConfig)
355
- });
356
- try {
357
- await mountNamespaces(storage, config.mounts);
358
- } catch (error) {
359
- await storage.dispose().catch(() => {
360
- });
361
- throw error;
362
- }
363
- return storage;
364
- }
365
- async function resolveStorageRuntimeClient(config) {
366
- if (!config || isStorageInstance(config) || isStorageClient(config)) {
367
- return void 0;
368
- }
369
- const client = config.client;
370
- if (!client || isStorageInstance(client) || isStorageClient(client)) {
371
- return void 0;
372
- }
373
- return typeof client === "function" ? await client() : client;
374
- }
375
- async function initStorage(config = {}) {
376
- globalStorage = getActiveGlobalStorage();
377
- const nextStorage = await createFarmStorage(config);
378
- const previousStorage = globalStorage;
379
- globalStorage = writeGlobalStorage(nextStorage);
380
- if (previousStorage !== nextStorage) {
381
- await previousStorage.dispose().catch(() => {
382
- });
383
- }
384
- return globalStorage;
385
- }
386
- function getStorage(namespace) {
387
- globalStorage = getActiveGlobalStorage();
388
- const base = normalizeMountKey(namespace);
389
- if (!base) {
390
- return globalStorage;
391
- }
392
- const namespaced = (0, import_unstorage.prefixStorage)(globalStorage, base);
393
- const store = globalStorage;
394
- const prefix = `${base}:`;
395
- const stripPrefix = /* @__PURE__ */ __name((key) => key.startsWith(prefix) ? key.slice(prefix.length) : key, "stripPrefix");
396
- const viewUnwatchers = /* @__PURE__ */ new Set();
397
- const releaseViewWatchers = /* @__PURE__ */ __name(async () => {
398
- const current = [...viewUnwatchers];
399
- viewUnwatchers.clear();
400
- await Promise.all(current.map((unwatch) => unwatch()));
401
- }, "releaseViewWatchers");
402
- return {
403
- ...namespaced,
404
- // Scope the wipe to the namespace instead of the whole storage, and keep
405
- // the caller's base so `clear("sessions")` cannot take unrelated keys with
406
- // it. Dropping the argument silently widens a targeted clear into a
407
- // namespace-wide delete.
408
- async clear(base2, opts) {
409
- const keys = await namespaced.getKeys(base2);
410
- await Promise.all(keys.map((key) => namespaced.removeItem(key, opts)));
411
- },
412
- async watch(callback) {
413
- const unwatch = await store.watch((event, key) => {
414
- if (key.startsWith(prefix)) callback(event, stripPrefix(key));
415
- });
416
- viewUnwatchers.add(unwatch);
417
- return async () => {
418
- viewUnwatchers.delete(unwatch);
419
- await unwatch();
420
- };
421
- },
422
- async unwatch() {
423
- await releaseViewWatchers();
424
- },
425
- async dispose() {
426
- await releaseViewWatchers();
427
- },
428
- getMount(key = "") {
429
- return store.getMount(prefix + key);
430
- },
431
- getMounts(base2 = "", options) {
432
- return store.getMounts(prefix + base2, options).map((mount) => ({ ...mount, base: stripPrefix(mount.base) }));
433
- }
434
- };
435
- }
436
- async function disposeStorage() {
437
- globalStorage = getActiveGlobalStorage();
438
- const previousStorage = globalStorage;
439
- globalStorage = writeGlobalStorage(createMemoryStorage());
440
- await previousStorage.dispose().catch(() => {
441
- });
442
- }
443
- var import_unstorage, import_memory, loadModule, DATABASE_CONNECTORS, GLOBAL_STORAGE_KEY, globalStorage;
444
- var init_storage = __esm({
445
- "src/storage/index.ts"() {
446
- "use strict";
447
- import_unstorage = require("unstorage");
448
- import_memory = __toESM(require("unstorage/drivers/memory"));
449
- loadModule = /* @__PURE__ */ __name((specifier) => import(
450
- /* @vite-ignore */
451
- specifier
452
- ), "loadModule");
453
- DATABASE_CONNECTORS = {
454
- sqlite: {
455
- connector: "node-sqlite",
456
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/node-sqlite"), "load")
457
- },
458
- "node-sqlite": {
459
- connector: "node-sqlite",
460
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/node-sqlite"), "load")
461
- },
462
- sqlite3: {
463
- connector: "sqlite3",
464
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/sqlite3"), "load")
465
- },
466
- "better-sqlite3": {
467
- connector: "better-sqlite3",
468
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/better-sqlite3"), "load")
469
- },
470
- postgres: {
471
- connector: "postgresql",
472
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/postgresql"), "load")
473
- },
474
- postgresql: {
475
- connector: "postgresql",
476
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/postgresql"), "load")
477
- },
478
- pg: {
479
- connector: "postgresql",
480
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/postgresql"), "load")
481
- },
482
- mysql: {
483
- connector: "mysql2",
484
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/mysql2"), "load")
485
- },
486
- mysql2: {
487
- connector: "mysql2",
488
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/mysql2"), "load")
489
- },
490
- pglite: {
491
- connector: "pglite",
492
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/pglite"), "load")
493
- },
494
- planetscale: {
495
- connector: "planetscale",
496
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/planetscale"), "load")
497
- },
498
- libsql: {
499
- connector: "libsql",
500
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/libsql/node"), "load")
501
- },
502
- "libsql-node": {
503
- connector: "libsql-node",
504
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/libsql/node"), "load")
505
- },
506
- "libsql-http": {
507
- connector: "libsql-http",
508
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/libsql/http"), "load")
509
- }
510
- };
511
- __name(createMemoryStorage, "createMemoryStorage");
512
- GLOBAL_STORAGE_KEY = /* @__PURE__ */ Symbol.for("farmjs.storage.global");
513
- __name(readGlobalStorage, "readGlobalStorage");
514
- __name(writeGlobalStorage, "writeGlobalStorage");
515
- __name(getActiveGlobalStorage, "getActiveGlobalStorage");
516
- globalStorage = getActiveGlobalStorage();
517
- __name(normalizeMountKey, "normalizeMountKey");
518
- __name(isDriverInstance, "isDriverInstance");
519
- __name(isStorageInstance, "isStorageInstance");
520
- __name(isStorageClient, "isStorageClient");
521
- __name(isDatabaseDriverName, "isDatabaseDriverName");
522
- __name(extractDriverOptions, "extractDriverOptions");
523
- __name(loadBuiltinDriver, "loadBuiltinDriver");
524
- __name(loadDatabaseDriver, "loadDatabaseDriver");
525
- __name(resolveDriver, "resolveDriver");
526
- __name(createStorageClientFromResolver, "createStorageClientFromResolver");
527
- __name(defineStorageClient, "defineStorageClient");
528
- __name(createStorageClient, "createStorageClient");
529
- __name(driverStorage, "driverStorage");
530
- __name(databaseStorage, "databaseStorage");
531
- __name(memoryStorage, "memoryStorage");
532
- __name(localStorage, "localStorage");
533
- __name(sqliteStorage, "sqliteStorage");
534
- __name(mysqlStorage, "mysqlStorage");
535
- __name(mysql2Storage, "mysql2Storage");
536
- __name(postgresStorage, "postgresStorage");
537
- __name(pgStorage, "pgStorage");
538
- __name(pgliteStorage, "pgliteStorage");
539
- __name(planetscaleStorage, "planetscaleStorage");
540
- __name(libsqlStorage, "libsqlStorage");
541
- __name(redisStorage, "redisStorage");
542
- __name(s3Storage, "s3Storage");
543
- __name(mongodbStorage, "mongodbStorage");
544
- __name(upstashStorage, "upstashStorage");
545
- __name(netlifyBlobsStorage, "netlifyBlobsStorage");
546
- __name(vercelKVStorage, "vercelKVStorage");
547
- __name(vercelBlobStorage, "vercelBlobStorage");
548
- __name(mountNamespaces, "mountNamespaces");
549
- __name(createFarmStorage, "createFarmStorage");
550
- __name(resolveStorageRuntimeClient, "resolveStorageRuntimeClient");
551
- __name(initStorage, "initStorage");
552
- __name(getStorage, "getStorage");
553
- __name(disposeStorage, "disposeStorage");
554
- }
555
- });
556
-
557
- // src/schema-capabilities.ts
558
- function assertNoSchemaListField(field, fieldPath, target) {
559
- if (!field.list) {
560
- return;
561
- }
562
- throw new Error(
563
- `Schema field "${fieldPath}" declares list: true, but ${target} does not support list fields. Use type: "json" for an array value or model the values in a related table.`
564
- );
565
- }
566
- var init_schema_capabilities = __esm({
567
- "src/schema-capabilities.ts"() {
568
- "use strict";
569
- __name(assertNoSchemaListField, "assertNoSchemaListField");
570
- }
571
- });
572
-
573
- // src/schema-primary-key.ts
574
- function assertSupportedPrimaryKeyField(location, field) {
575
- if (!field.primaryKey || SUPPORTED_PRIMARY_KEY_TYPES.has(field.type)) {
576
- return;
577
- }
578
- throw new Error(
579
- `Schema primary-key field "${location}" uses unsupported type "${field.type}". Supported types are id, uuid, string, and integer.`
580
- );
581
- }
582
- var SUPPORTED_PRIMARY_KEY_TYPES;
583
- var init_schema_primary_key = __esm({
584
- "src/schema-primary-key.ts"() {
585
- "use strict";
586
- SUPPORTED_PRIMARY_KEY_TYPES = /* @__PURE__ */ new Set(["id", "uuid", "string", "integer"]);
587
- __name(assertSupportedPrimaryKeyField, "assertSupportedPrimaryKeyField");
588
- }
589
- });
590
-
591
- // src/schema-reference.ts
592
- function isDatabaseEnforcedReference(reference) {
593
- return reference.enforced === void 0 || reference.enforced === "db";
594
- }
595
- var init_schema_reference = __esm({
596
- "src/schema-reference.ts"() {
597
- "use strict";
598
- __name(isDatabaseEnforcedReference, "isDatabaseEnforcedReference");
599
- }
600
- });
601
-
602
- // src/schema-resolve.ts
603
- function resolveSchemaModels(ownerKey, schema) {
604
- const models = Object.fromEntries(
605
- Object.entries(schema.models).map(([modelKey, model]) => [modelKey, cloneSchemaModel(model)])
606
- );
607
- for (const [modelKey, extension] of Object.entries(schema.extend || {})) {
608
- const existing = models[modelKey];
609
- models[modelKey] = {
610
- ...existing || { fields: {} },
611
- ...extension.name ? { name: extension.name } : {},
612
- ...extension.description ? { description: extension.description } : {},
613
- fields: {
614
- ...existing?.fields,
615
- ...extension.fields
616
- },
617
- constraints: [...existing?.constraints || [], ...extension.constraints || []],
618
- meta: {
619
- ...existing?.meta,
620
- ...extension.meta
621
- }
622
- };
623
- }
624
- for (const [modelKey, override] of Object.entries(schema.override || {})) {
625
- const existing = models[modelKey];
626
- if (!existing) {
627
- throw new Error(
628
- `Schema override for "${ownerKey}.${modelKey}" is invalid because that model does not exist.`
629
- );
630
- }
631
- const fields = {
632
- ...existing.fields
633
- };
634
- for (const [fieldKey, fieldOverride] of Object.entries(override.fields || {})) {
635
- const existingField = fields[fieldKey];
636
- if (!existingField && !fieldOverride.type) {
637
- throw new Error(
638
- `Schema override for "${ownerKey}.${modelKey}.${fieldKey}" is missing a field type.`
639
- );
640
- }
641
- fields[fieldKey] = {
642
- ...existingField,
643
- ...fieldOverride
644
- };
645
- }
646
- models[modelKey] = {
647
- ...existing,
648
- ...override.name ? { name: override.name } : {},
649
- ...override.description ? { description: override.description } : {},
650
- fields,
651
- constraints: override.constraints || existing.constraints,
652
- meta: {
653
- ...existing.meta,
654
- ...override.meta
655
- }
656
- };
657
- }
658
- const resolvedModels = {};
659
- for (const [modelKey, model] of Object.entries(models)) {
660
- const modelName = model.name || modelKey;
661
- const fieldNames = /* @__PURE__ */ new Set();
662
- const resolvedFields = {};
663
- for (const [fieldKey, field] of Object.entries(model.fields)) {
664
- const fieldName = field.name || fieldKey;
665
- assertSupportedPrimaryKeyField(`${ownerKey}.${modelKey}.${fieldKey}`, field);
666
- if (fieldNames.has(fieldName)) {
667
- throw new Error(
668
- `Schema model "${ownerKey}.${modelKey}" contains duplicate field name "${fieldName}".`
669
- );
670
- }
671
- fieldNames.add(fieldName);
672
- resolvedFields[fieldKey] = {
673
- ...field,
674
- name: fieldName
675
- };
676
- }
677
- const primaryKeyFields = Object.entries(resolvedFields).filter(([, field]) => field.primaryKey).map(([fieldKey]) => fieldKey);
678
- if (primaryKeyFields.length > 1) {
679
- throw new Error(
680
- `Schema model "${ownerKey}.${modelKey}" defines multiple primary-key fields: ${primaryKeyFields.map((fieldKey) => `"${fieldKey}"`).join(", ")}. Composite primary keys are not supported.`
681
- );
682
- }
683
- for (const constraint of model.constraints || []) {
684
- for (const fieldKey of constraint.fields) {
685
- if (!Object.prototype.hasOwnProperty.call(resolvedFields, fieldKey)) {
686
- throw new Error(
687
- `Schema ${constraint.type} constraint on "${ownerKey}.${modelKey}" references missing field "${fieldKey}".`
688
- );
689
- }
690
- }
691
- }
692
- resolvedModels[modelKey] = {
693
- ...model,
694
- name: modelName,
695
- fields: resolvedFields
696
- };
697
- }
698
- for (const [modelKey, model] of Object.entries(resolvedModels)) {
699
- for (const [fieldKey, field] of Object.entries(model.fields)) {
700
- const reference = field.reference;
701
- if (!reference || !Object.prototype.hasOwnProperty.call(resolvedModels, reference.model)) {
702
- continue;
703
- }
704
- const referencedModel = resolvedModels[reference.model];
705
- if (!Object.prototype.hasOwnProperty.call(referencedModel.fields, reference.field)) {
706
- throw new Error(
707
- `Schema reference "${ownerKey}.${modelKey}.${fieldKey}" targets missing field "${ownerKey}.${reference.model}.${reference.field}".`
708
- );
709
- }
710
- }
711
- }
712
- return resolvedModels;
713
- }
714
- function cloneSchemaModel(model) {
715
- return {
716
- ...model,
717
- fields: Object.fromEntries(
718
- Object.entries(model.fields).map(([fieldKey, field]) => [fieldKey, { ...field }])
719
- ),
720
- constraints: model.constraints ? [...model.constraints] : void 0,
721
- meta: model.meta ? { ...model.meta } : void 0
722
- };
723
- }
724
- var init_schema_resolve = __esm({
725
- "src/schema-resolve.ts"() {
726
- "use strict";
727
- init_schema_primary_key();
728
- __name(resolveSchemaModels, "resolveSchemaModels");
729
- __name(cloneSchemaModel, "cloneSchemaModel");
730
- }
731
- });
732
-
733
- // src/integration-orm.ts
734
- var integration_orm_exports = {};
735
- __export(integration_orm_exports, {
736
- createIntegrationOrm: () => createIntegrationOrm,
737
- farmIntegrationSchemaToOrmSchema: () => farmIntegrationSchemaToOrmSchema,
738
- resolveIntegrationOrmRuntimeClient: () => resolveIntegrationOrmRuntimeClient
739
- });
740
- async function createIntegrationOrm(options) {
741
- const [schema, client] = await Promise.all([
742
- farmIntegrationSchemaToOrmSchema(options.schema),
743
- resolveIntegrationOrmRuntimeClient(options)
744
- ]);
745
- if (!client) {
746
- throw new Error(
747
- "Schema-backed integration storage requires a runtime client at farm.config storage.client."
748
- );
749
- }
750
- const { createOrmFromRuntime } = await import("@farming-labs/orm-runtime");
751
- return createOrmFromRuntime({
752
- schema,
753
- client
754
- });
755
- }
756
- async function resolveIntegrationOrmRuntimeClient(options) {
757
- if (options.client !== void 0) {
758
- return typeof options.client === "function" ? await options.client() : options.client;
759
- }
760
- return resolveStorageRuntimeClient(options.storage ?? options.config?.storage);
761
- }
762
- async function farmIntegrationSchemaToOrmSchema(schema) {
763
- for (const [modelKey, modelSchema] of Object.entries(schema.models)) {
764
- for (const [fieldKey, fieldSchema] of Object.entries(modelSchema.fields)) {
765
- assertNoSchemaListField(
766
- fieldSchema,
767
- `${modelKey}.${fieldKey}`,
768
- "the Farm integration runtime ORM"
769
- );
770
- }
771
- }
772
- const orm = await import("@farming-labs/orm");
773
- const models = {};
774
- const resolvedModels = resolveSchemaModels("integration", schema);
775
- for (const [modelKey, modelSchema] of Object.entries(resolvedModels)) {
776
- models[modelKey] = orm.model({
777
- table: modelSchema.name ?? modelKey,
778
- fields: createOrmModelFields(orm, modelKey, modelSchema),
779
- constraints: createOrmModelConstraints(modelSchema),
780
- description: modelSchema.description
781
- });
782
- }
783
- return orm.defineSchema(models);
784
- }
785
- function createOrmModelFields(orm, modelKey, modelSchema) {
786
- return Object.fromEntries(
787
- Object.entries(modelSchema.fields).map(([fieldKey, fieldSchema]) => [
788
- fieldKey,
789
- createOrmField(orm, modelKey, fieldKey, fieldSchema)
790
- ])
791
- );
792
- }
793
- function createOrmField(orm, modelKey, fieldKey, field) {
794
- assertSupportedPrimaryKeyField(`integration.${modelKey}.${fieldKey}`, field);
795
- let builder = createOrmFieldBuilder(orm, fieldKey, field);
796
- if (!field.primaryKey && field.unique) {
797
- builder = builder.unique();
798
- }
799
- if (!field.primaryKey && (field.nullable || field.required === false)) {
800
- builder = builder.nullable();
801
- }
802
- if (field.default !== void 0) {
803
- builder = field.type === "datetime" && field.default === "now" ? builder.defaultNow() : builder.default(field.default);
804
- }
805
- if (field.reference && isDatabaseEnforcedReference(field.reference)) {
806
- builder = builder.references(`${field.reference.model}.${field.reference.field}`);
807
- }
808
- if (field.name && field.name !== fieldKey) {
809
- builder = builder.map(field.name);
810
- }
811
- if (field.description) {
812
- builder = builder.describe(field.description);
813
- }
814
- return builder;
815
- }
816
- function createOrmFieldBuilder(orm, fieldKey, field) {
817
- if (field.primaryKey) {
818
- if (field.type === "integer") {
819
- return orm.id({ type: "integer" });
820
- }
821
- if (field.type === "string") {
822
- return new orm.FieldBuilder({
823
- kind: "id",
824
- nullable: false,
825
- unique: true,
826
- idType: "string"
827
- });
828
- }
829
- return orm.id();
830
- }
831
- switch (field.type) {
832
- case "id":
833
- case "uuid":
834
- return orm.string();
835
- case "string":
836
- case "text":
837
- return orm.string();
838
- case "boolean":
839
- return orm.boolean();
840
- case "integer":
841
- return orm.integer();
842
- case "number":
843
- return orm.decimal();
844
- case "datetime":
845
- return orm.datetime();
846
- case "json":
847
- return orm.json();
848
- case "enum": {
849
- if (!field.values?.length) {
850
- throw new Error(`Integration schema enum field "${fieldKey}" must define values.`);
851
- }
852
- return orm.enumeration(field.values);
853
- }
854
- default:
855
- throw new Error(
856
- `Unsupported integration schema field type "${field.type}" for "${fieldKey}".`
857
- );
858
- }
859
- }
860
- function createOrmModelConstraints(modelSchema) {
861
- const unique = [];
862
- const indexes = [];
863
- for (const constraint of modelSchema.constraints ?? []) {
864
- if (!constraint.fields.length) {
865
- continue;
866
- }
867
- const fields = constraint.fields;
868
- if (constraint.type === "unique") {
869
- unique.push(fields);
870
- } else {
871
- indexes.push(fields);
872
- }
873
- }
874
- return {
875
- unique,
876
- indexes
877
- };
878
- }
879
- var init_integration_orm = __esm({
880
- "src/integration-orm.ts"() {
881
- "use strict";
882
- init_schema_capabilities();
883
- init_schema_primary_key();
884
- init_schema_reference();
885
- init_schema_resolve();
886
- init_storage();
887
- __name(createIntegrationOrm, "createIntegrationOrm");
888
- __name(resolveIntegrationOrmRuntimeClient, "resolveIntegrationOrmRuntimeClient");
889
- __name(farmIntegrationSchemaToOrmSchema, "farmIntegrationSchemaToOrmSchema");
890
- __name(createOrmModelFields, "createOrmModelFields");
891
- __name(createOrmField, "createOrmField");
892
- __name(createOrmFieldBuilder, "createOrmFieldBuilder");
893
- __name(createOrmModelConstraints, "createOrmModelConstraints");
894
- }
895
- });
896
-
897
- // src/agent-runtime.ts
898
- var agent_runtime_exports = {};
899
- __export(agent_runtime_exports, {
900
- applyAgentRuntimeViteProxy: () => applyAgentRuntimeViteProxy,
901
- createAgentRuntimeIntegration: () => createAgentRuntimeIntegration,
902
- findAvailableAgentRuntimePort: () => findAvailableAgentRuntimePort,
903
- normalizeAgentOrigin: () => normalizeAgentOrigin,
904
- normalizeAgentRoutePrefix: () => normalizeAgentRoutePrefix,
905
- proxyAgentRuntimeRequest: () => proxyAgentRuntimeRequest,
906
- resolveProjectPackageBin: () => resolveProjectPackageBin,
907
- startManagedAgentRuntime: () => startManagedAgentRuntime
908
- });
909
- module.exports = __toCommonJS(agent_runtime_exports);
910
- var import_node_child_process = require("child_process");
911
- var import_promises = require("fs/promises");
912
- var import_node_module = require("module");
913
- var import_node_net = require("net");
914
- var import_node_path = require("path");
915
-
916
- // src/routing/specificity.ts
917
- var _AmbiguousRouteError = class _AmbiguousRouteError extends Error {
918
- constructor(message) {
919
- super(message);
920
- this.name = "AmbiguousRouteError";
921
- }
922
- };
923
- __name(_AmbiguousRouteError, "AmbiguousRouteError");
924
- var AmbiguousRouteError = _AmbiguousRouteError;
925
- var _NonTerminalCatchAllRouteError = class _NonTerminalCatchAllRouteError extends TypeError {
926
- constructor(message) {
927
- super(message);
928
- this.name = "NonTerminalCatchAllRouteError";
929
- }
930
- };
931
- __name(_NonTerminalCatchAllRouteError, "NonTerminalCatchAllRouteError");
932
- var NonTerminalCatchAllRouteError = _NonTerminalCatchAllRouteError;
933
- var _DuplicateRouteParameterError = class _DuplicateRouteParameterError extends AmbiguousRouteError {
934
- constructor(message) {
935
- super(message);
936
- this.name = "DuplicateRouteParameterError";
937
- }
938
- };
939
- __name(_DuplicateRouteParameterError, "DuplicateRouteParameterError");
940
- var DuplicateRouteParameterError = _DuplicateRouteParameterError;
941
- var _ReservedRouteParameterError = class _ReservedRouteParameterError extends AmbiguousRouteError {
942
- constructor(message) {
943
- super(message);
944
- this.name = "ReservedRouteParameterError";
945
- }
946
- };
947
- __name(_ReservedRouteParameterError, "ReservedRouteParameterError");
948
- var ReservedRouteParameterError = _ReservedRouteParameterError;
949
- var _BrowserUnstableRouteError = class _BrowserUnstableRouteError extends TypeError {
950
- constructor(message) {
951
- super(message);
952
- this.name = "BrowserUnstableRouteError";
953
- }
954
- };
955
- __name(_BrowserUnstableRouteError, "BrowserUnstableRouteError");
956
- var BrowserUnstableRouteError = _BrowserUnstableRouteError;
957
- var SEGMENT_RANK = {
958
- static: 4,
959
- dynamic: 3,
960
- "catch-all": 1,
961
- "optional-catch-all": 0
962
- };
963
- var ROUTE_END_RANK = 2;
964
- function compareRouteSpecificity(left, right) {
965
- const length = Math.max(left.length, right.length);
966
- for (let index = 0; index < length; index++) {
967
- const leftRank = index < left.length ? SEGMENT_RANK[left[index]] : ROUTE_END_RANK;
968
- const rightRank = index < right.length ? SEGMENT_RANK[right[index]] : ROUTE_END_RANK;
969
- if (leftRank !== rightRank) return rightRank - leftRank;
970
- }
971
- return 0;
972
- }
973
- __name(compareRouteSpecificity, "compareRouteSpecificity");
974
- var ROUTER_PARAMETER_NAME = "[A-Za-z0-9_$-]+";
975
- var PAGE_PARAMETER_PATTERN = /^(?:\[\[\.\.\.(.+)\]\]|\[\.\.\.(.+)\]|\[(.+)\])$/;
976
- var ROUTER_PARAMETER_PATTERN = /^(?:\[\[\.\.\.([A-Za-z0-9_$-]+)\]\]|\[\.\.\.([A-Za-z0-9_$-]+)\]|\[([A-Za-z0-9_$-]+)\]|:([A-Za-z0-9_$-]+)|\*([A-Za-z0-9_$-]+)\??)$/;
977
- var RESERVED_PARAMETER_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
978
- function assertBrowserStableRoutePath(pattern) {
979
- if (pattern.includes("\\") || hasControlCharacter(pattern)) {
980
- throw new BrowserUnstableRouteError(
981
- `Route path "${pattern}" cannot contain backslashes or control characters.`
982
- );
983
- }
984
- for (const segment of pattern.split("/").filter(Boolean)) {
985
- if (segment.startsWith("(") && segment.endsWith(")") || segment.startsWith("[") && segment.endsWith("]")) {
986
- continue;
987
- }
988
- let decoded = segment;
989
- try {
990
- decoded = decodeURIComponent(segment);
991
- } catch {
992
- }
993
- if (decoded === "." || decoded === ".." || decoded.includes("/") || decoded.includes("\\") || hasControlCharacter(decoded)) {
994
- throw new BrowserUnstableRouteError(
995
- `Route path "${pattern}" contains browser-unstable segment "${segment}".`
996
- );
997
- }
998
- }
999
- }
1000
- __name(assertBrowserStableRoutePath, "assertBrowserStableRoutePath");
1001
- function hasControlCharacter(value) {
1002
- return Array.from(value).some((character) => {
1003
- const code = character.charCodeAt(0);
1004
- return code <= 31 || code >= 127 && code <= 159;
1005
- });
1006
- }
1007
- __name(hasControlCharacter, "hasControlCharacter");
1008
- function assertUniqueRouteParameters(pattern, syntax = "page") {
1009
- const parameterPattern = syntax === "router" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;
1010
- const names = /* @__PURE__ */ new Set();
1011
- for (const segment of splitRoutePattern(pattern, syntax)) {
1012
- const match = parameterPattern.exec(segment);
1013
- const name = match?.slice(1).find(Boolean);
1014
- if (!name) continue;
1015
- if (RESERVED_PARAMETER_NAMES.has(name)) {
1016
- throw new ReservedRouteParameterError(
1017
- `Route parameter "${name}" in route "${pattern}" is reserved. Use a different parameter name.`
1018
- );
1019
- }
1020
- if (names.has(name)) {
1021
- throw new DuplicateRouteParameterError(
1022
- `Duplicate route parameter "${name}" in route "${pattern}". Each dynamic segment must use a unique name.`
1023
- );
1024
- }
1025
- names.add(name);
1026
- }
1027
- }
1028
- __name(assertUniqueRouteParameters, "assertUniqueRouteParameters");
1029
- function splitRoutePattern(pattern, syntax) {
1030
- return pattern.replace(/\\/g, "/").split("/").filter(Boolean).filter(
1031
- (segment) => syntax === "api" ? true : !(segment.startsWith("(") && segment.endsWith(")"))
1032
- );
1033
- }
1034
- __name(splitRoutePattern, "splitRoutePattern");
1035
- function assertTerminalCatchAll(pattern, syntax = "page") {
1036
- const segments = splitRoutePattern(pattern, syntax);
1037
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
1038
- const catchAllPattern = new RegExp(
1039
- syntax === "router" ? `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\]|\\*${parameterName}\\??)$` : `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\])$`
1040
- );
1041
- const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));
1042
- if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {
1043
- throw new NonTerminalCatchAllRouteError(
1044
- `Catch-all segment "${segments[catchAllIndex]}" must be the final segment in route "${pattern}".`
1045
- );
1046
- }
1047
- }
1048
- __name(assertTerminalCatchAll, "assertTerminalCatchAll");
1049
- function getRoutePatternSpecificity(pattern, syntax = "page") {
1050
- assertTerminalCatchAll(pattern, syntax);
1051
- return splitRoutePattern(pattern, syntax).map(
1052
- (segment) => getPatternSegmentSpecificity(segment, syntax)
1053
- );
1054
- }
1055
- __name(getRoutePatternSpecificity, "getRoutePatternSpecificity");
1056
- function getPatternSegmentSpecificity(segment, syntax) {
1057
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
1058
- const supportsColonAndStar = syntax === "router";
1059
- if (new RegExp(`^\\[\\[\\.\\.\\.${parameterName}\\]\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}\\?$`).test(segment)) {
1060
- return "optional-catch-all";
1061
- }
1062
- if (new RegExp(`^\\[\\.\\.\\.${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}$`).test(segment)) {
1063
- return "catch-all";
1064
- }
1065
- if (new RegExp(`^\\[${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment)) {
1066
- return "dynamic";
1067
- }
1068
- return "static";
1069
- }
1070
- __name(getPatternSegmentSpecificity, "getPatternSegmentSpecificity");
1071
-
1072
- // src/utils/decode.ts
1073
- function decodeRouteSegment(segment) {
1074
- try {
1075
- return decodeURIComponent(segment);
1076
- } catch {
1077
- return segment;
1078
- }
1079
- }
1080
- __name(decodeRouteSegment, "decodeRouteSegment");
1081
- function canonicalizeRequestPathSegments(pathname) {
1082
- const segments = pathname.split("/").filter(Boolean);
1083
- if (!pathname.includes("%")) return segments;
1084
- return segments.map(decodeRouteSegment);
1085
- }
1086
- __name(canonicalizeRequestPathSegments, "canonicalizeRequestPathSegments");
1087
- function canonicalizeRequestPathname(pathname) {
1088
- const encoded = pathname.includes("%");
1089
- if (!encoded && !pathname.includes("//")) return pathname;
1090
- const collapsed = pathname.replace(/\/{2,}/g, "/");
1091
- if (!encoded) return collapsed;
1092
- return collapsed.split("/").map((segment) => {
1093
- const decoded = decodeRouteSegment(segment);
1094
- return decoded === segment ? segment : decoded.replace(/\//g, "%2F");
1095
- }).join("/");
1096
- }
1097
- __name(canonicalizeRequestPathname, "canonicalizeRequestPathname");
1098
-
1099
- // src/plugins/route-pattern.ts
1100
- function validateConfigRouteSource(source, field = "Config route source") {
1101
- if (typeof source !== "string" || source.length === 0) {
1102
- throw new TypeError(`${field} must be a non-empty pathname pattern.`);
1103
- }
1104
- if (source.trim() !== source) {
1105
- throw new Error(`${field} cannot contain leading or trailing whitespace.`);
1106
- }
1107
- if (!source.startsWith("/")) {
1108
- throw new Error(`${field} must start with "/".`);
1109
- }
1110
- if (source.includes("?") || source.includes("#")) {
1111
- throw new Error(`${field} must be a pathname without a query string or hash.`);
1112
- }
1113
- if (source.includes("\\") || Array.from(source).some((character) => {
1114
- const code = character.charCodeAt(0);
1115
- return code <= 31 || code >= 127 && code <= 159;
1116
- })) {
1117
- throw new Error(`${field} cannot contain backslashes or control characters.`);
1118
- }
1119
- assertBrowserStableRoutePath(source);
1120
- return source;
1121
- }
1122
- __name(validateConfigRouteSource, "validateConfigRouteSource");
1123
-
1124
- // src/integration-api.ts
1125
- function defineIntegrationAPIOperation(operation2) {
1126
- return {
1127
- kind: "farm-integration-api-operation",
1128
- ...operation2
1129
- };
1130
- }
1131
- __name(defineIntegrationAPIOperation, "defineIntegrationAPIOperation");
1132
- function operation(method, pathOrOptions, maybeOptions = {}) {
1133
- const hasExplicitPath = typeof pathOrOptions === "string";
1134
- const path = hasExplicitPath ? pathOrOptions : "";
1135
- const options = hasExplicitPath ? maybeOptions : {
1136
- ...maybeOptions,
1137
- ...pathOrOptions
1138
- };
1139
- return defineIntegrationAPIOperation({
1140
- path,
1141
- method,
1142
- __pathless: !hasExplicitPath,
1143
- ...options
1144
- });
1145
- }
1146
- __name(operation, "operation");
1147
- function get(pathOrOptions, maybeOptions = {}) {
1148
- return operation("GET", pathOrOptions, maybeOptions);
1149
- }
1150
- __name(get, "get");
1151
- function isOperation(value) {
1152
- return !!value && typeof value === "object" && value.kind === "farm-integration-api-operation";
1153
- }
1154
- __name(isOperation, "isOperation");
1155
- function bindRoutePath(path, api2) {
1156
- const entries = Object.entries(api2).map(([key, value]) => {
1157
- if (isOperation(value)) {
1158
- return [
1159
- key,
1160
- {
1161
- ...value,
1162
- path,
1163
- __pathless: false
1164
- }
1165
- ];
1166
- }
1167
- if (value && typeof value === "object") {
1168
- return [key, bindRoutePath(path, value)];
1169
- }
1170
- return [key, value];
1171
- });
1172
- return Object.fromEntries(entries);
1173
- }
1174
- __name(bindRoutePath, "bindRoutePath");
1175
- function route(path, definitionOrOperation, ...operations) {
1176
- if (isOperation(definitionOrOperation)) {
1177
- const allOperations = [definitionOrOperation, ...operations];
1178
- return Object.fromEntries(
1179
- allOperations.map((operation2) => [
1180
- operation2.method.toLowerCase(),
1181
- {
1182
- ...operation2,
1183
- path,
1184
- __pathless: false
1185
- }
1186
- ])
1187
- );
1188
- }
1189
- return bindRoutePath(path, definitionOrOperation);
1190
- }
1191
- __name(route, "route");
1192
- function normalizeRouteSegment(segment) {
1193
- if (!segment) {
1194
- return "index";
1195
- }
1196
- if (segment.startsWith("[...") && segment.endsWith("]")) {
1197
- return segment.slice(4, -1) || "index";
1198
- }
1199
- if (segment.startsWith("[") && segment.endsWith("]")) {
1200
- return segment.slice(1, -1) || "index";
1201
- }
1202
- const matcherIndex = segment.indexOf("(");
1203
- if (matcherIndex > 0) {
1204
- return segment.slice(0, matcherIndex);
1205
- }
1206
- return camelCaseRouteSegment(segment);
1207
- }
1208
- __name(normalizeRouteSegment, "normalizeRouteSegment");
1209
- function camelCaseRouteSegment(segment) {
1210
- return segment.replace(/-([a-zA-Z0-9])/g, (_match, value) => value.toUpperCase());
1211
- }
1212
- __name(camelCaseRouteSegment, "camelCaseRouteSegment");
1213
- function getRouteClientSegments(path) {
1214
- const segments = path.split("/").filter(Boolean);
1215
- if (segments.length === 0) {
1216
- return ["index"];
1217
- }
1218
- const stripped = segments[0] === "api" && segments.length > 2 ? segments.slice(2) : segments.length > 1 ? segments.slice(1) : [segments[segments.length - 1]];
1219
- return stripped.map(normalizeRouteSegment).filter(Boolean);
1220
- }
1221
- __name(getRouteClientSegments, "getRouteClientSegments");
1222
- function setRouteOperation(target, pathSegments, operation2) {
1223
- const [head, ...tail] = pathSegments;
1224
- if (!head) {
1225
- return;
1226
- }
1227
- if (tail.length === 0) {
1228
- const leaf = target[head] || {};
1229
- leaf[operation2.method.toLowerCase()] = {
1230
- ...operation2,
1231
- path: operation2.path,
1232
- __pathless: false
1233
- };
1234
- target[head] = leaf;
1235
- return;
1236
- }
1237
- const branch = target[head] || {};
1238
- target[head] = branch;
1239
- setRouteOperation(branch, tail, operation2);
1240
- }
1241
- __name(setRouteOperation, "setRouteOperation");
1242
- function fromRoutes(routes) {
1243
- const definition = {};
1244
- for (const route2 of routes) {
1245
- if (!isOperation(route2.__operation)) {
1246
- continue;
1247
- }
1248
- setRouteOperation(definition, getRouteClientSegments(route2.path), {
1249
- ...route2.__operation,
1250
- path: route2.path,
1251
- __pathless: false
1252
- });
1253
- }
1254
- return definition;
1255
- }
1256
- __name(fromRoutes, "fromRoutes");
1257
- var api = {
1258
- get,
1259
- route,
1260
- fromRoutes,
1261
- query(pathOrOptions, maybeOptions = {}) {
1262
- return operation("QUERY", pathOrOptions, {
1263
- bodyFormat: "json",
1264
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1265
- });
1266
- },
1267
- post(pathOrOptions, maybeOptions = {}) {
1268
- return operation("POST", pathOrOptions, {
1269
- bodyFormat: "json",
1270
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1271
- });
1272
- },
1273
- put(pathOrOptions, maybeOptions = {}) {
1274
- return operation("PUT", pathOrOptions, {
1275
- bodyFormat: "json",
1276
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1277
- });
1278
- },
1279
- patch(pathOrOptions, maybeOptions = {}) {
1280
- return operation("PATCH", pathOrOptions, {
1281
- bodyFormat: "json",
1282
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1283
- });
1284
- },
1285
- delete(pathOrOptions, maybeOptions = {}) {
1286
- return operation("DELETE", pathOrOptions, {
1287
- bodyFormat: "json",
1288
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1289
- });
1290
- },
1291
- options(pathOrOptions, maybeOptions = {}) {
1292
- return operation(
1293
- "OPTIONS",
1294
- pathOrOptions,
1295
- maybeOptions
1296
- );
1297
- },
1298
- head(pathOrOptions, maybeOptions = {}) {
1299
- return operation(
1300
- "HEAD",
1301
- pathOrOptions,
1302
- maybeOptions
1303
- );
1304
- },
1305
- form: {
1306
- query(pathOrOptions, maybeOptions = {}) {
1307
- return operation("QUERY", pathOrOptions, {
1308
- bodyFormat: "form",
1309
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1310
- });
1311
- },
1312
- post(pathOrOptions, maybeOptions = {}) {
1313
- return operation("POST", pathOrOptions, {
1314
- bodyFormat: "form",
1315
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1316
- });
1317
- },
1318
- put(pathOrOptions, maybeOptions = {}) {
1319
- return operation("PUT", pathOrOptions, {
1320
- bodyFormat: "form",
1321
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1322
- });
1323
- },
1324
- patch(pathOrOptions, maybeOptions = {}) {
1325
- return operation("PATCH", pathOrOptions, {
1326
- bodyFormat: "form",
1327
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1328
- });
1329
- },
1330
- delete(pathOrOptions, maybeOptions = {}) {
1331
- return operation("DELETE", pathOrOptions, {
1332
- bodyFormat: "form",
1333
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1334
- });
1335
- }
1336
- }
1337
- };
1338
-
1339
- // src/request-context.ts
1340
- var REQUEST_CONTEXT_STORE_KEY = /* @__PURE__ */ Symbol.for("farm.requestContextStore");
1341
- function getRequestContextStore() {
1342
- const globalState = globalThis;
1343
- if (!globalState[REQUEST_CONTEXT_STORE_KEY]) {
1344
- globalState[REQUEST_CONTEXT_STORE_KEY] = /* @__PURE__ */ new WeakMap();
1345
- }
1346
- return globalState[REQUEST_CONTEXT_STORE_KEY];
1347
- }
1348
- __name(getRequestContextStore, "getRequestContextStore");
1349
- function getBucket(target) {
1350
- const requestContextStore = getRequestContextStore();
1351
- let bucket = requestContextStore.get(target);
1352
- if (!bucket) {
1353
- bucket = {
1354
- privateData: /* @__PURE__ */ new Map(),
1355
- exposedData: /* @__PURE__ */ new Map()
1356
- };
1357
- requestContextStore.set(target, bucket);
1358
- }
1359
- return bucket;
1360
- }
1361
- __name(getBucket, "getBucket");
1362
- function setRequestContext(target, key, value, options = {}) {
1363
- const bucket = getBucket(target);
1364
- bucket.privateData.set(key, value);
1365
- if (options.exposeToPage) {
1366
- bucket.exposedData.set(key, value);
1367
- }
1368
- }
1369
- __name(setRequestContext, "setRequestContext");
1370
- function getRequestContext(target, key) {
1371
- const requestContextStore = getRequestContextStore();
1372
- const bucket = requestContextStore.get(target);
1373
- return bucket?.privateData.get(key);
1374
- }
1375
- __name(getRequestContext, "getRequestContext");
1376
- function hasRequestContext(target, key) {
1377
- const requestContextStore = getRequestContextStore();
1378
- const bucket = requestContextStore.get(target);
1379
- return bucket?.privateData.has(key) ?? false;
1380
- }
1381
- __name(hasRequestContext, "hasRequestContext");
1382
- function deleteRequestContext(target, key) {
1383
- const requestContextStore = getRequestContextStore();
1384
- const bucket = requestContextStore.get(target);
1385
- if (!bucket) return false;
1386
- const removedPrivate = bucket.privateData.delete(key);
1387
- bucket.exposedData.delete(key);
1388
- return removedPrivate;
1389
- }
1390
- __name(deleteRequestContext, "deleteRequestContext");
1391
- function clearRequestContext(target) {
1392
- const requestContextStore = getRequestContextStore();
1393
- const bucket = requestContextStore.get(target);
1394
- if (!bucket) return;
1395
- bucket.privateData.clear();
1396
- bucket.exposedData.clear();
1397
- }
1398
- __name(clearRequestContext, "clearRequestContext");
1399
- function getRequestContextSnapshot(target, options = {}) {
1400
- const requestContextStore = getRequestContextStore();
1401
- const bucket = requestContextStore.get(target);
1402
- if (!bucket) return /* @__PURE__ */ new Map();
1403
- if (options.exposedOnly) {
1404
- return new Map(bucket.exposedData);
1405
- }
1406
- return new Map(bucket.privateData);
1407
- }
1408
- __name(getRequestContextSnapshot, "getRequestContextSnapshot");
1409
- function copyRequestContext(source, target) {
1410
- const bucket = getRequestContextStore().get(source);
1411
- if (!bucket || source === target) return;
1412
- for (const [key, value] of bucket.privateData) {
1413
- setRequestContext(target, key, value, { exposeToPage: bucket.exposedData.has(key) });
1414
- }
1415
- }
1416
- __name(copyRequestContext, "copyRequestContext");
1417
-
1418
- // src/server-http.ts
1419
- var DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 1e7;
1420
- var DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 6e4;
1421
- var DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 3e5;
1422
- var DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5e3;
1423
- var DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 3e4;
1424
- var MAX_FARM_SERVER_TIMEOUT = 2147483647;
1425
- var _FarmRequestBodyError = class _FarmRequestBodyError extends Error {
1426
- constructor(code, status, message) {
1427
- super(message);
1428
- this.name = "FarmRequestBodyError";
1429
- this.code = code;
1430
- this.status = status;
1431
- }
1432
- };
1433
- __name(_FarmRequestBodyError, "FarmRequestBodyError");
1434
- var FarmRequestBodyError = _FarmRequestBodyError;
1435
- function resolveFarmServerConfig(config) {
1436
- const headersTimeout = parseFarmServerDuration(
1437
- config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,
1438
- "server.headersTimeout"
1439
- );
1440
- const requestTimeout = parseFarmServerDuration(
1441
- config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,
1442
- "server.requestTimeout"
1443
- );
1444
- if (headersTimeout > requestTimeout) {
1445
- throw new TypeError("server.headersTimeout must not exceed server.requestTimeout");
1446
- }
1447
- return Object.freeze({
1448
- bodySizeLimit: parseBodySizeLimit(
1449
- config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,
1450
- "server.bodySizeLimit"
1451
- ),
1452
- trustProxy: config?.trustProxy === true,
1453
- headersTimeout,
1454
- requestTimeout,
1455
- keepAliveTimeout: parseFarmServerDuration(
1456
- config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,
1457
- "server.keepAliveTimeout"
1458
- ),
1459
- gracefulShutdownTimeout: parseFarmServerDuration(
1460
- config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,
1461
- "server.gracefulShutdownTimeout"
1462
- ),
1463
- health: resolveFarmServerHealthConfig(config?.health)
1464
- });
1465
- }
1466
- __name(resolveFarmServerConfig, "resolveFarmServerConfig");
1467
- function parseFarmServerDuration(value, optionName = "duration") {
1468
- if (typeof value === "number") {
1469
- if (!Number.isSafeInteger(value) || value <= 0) {
1470
- throw new TypeError(`${optionName} must be a positive safe integer`);
1471
- }
1472
- if (value > MAX_FARM_SERVER_TIMEOUT) {
1473
- throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);
1474
- }
1475
- return value;
1476
- }
1477
- const match = value.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);
1478
- if (!match) {
1479
- throw new TypeError(`${optionName} must be milliseconds or a duration such as "30s" or "2m"`);
1480
- }
1481
- const amount = Number(match[1]);
1482
- const unit = match[2];
1483
- const multiplier = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : 36e5;
1484
- const milliseconds = Math.floor(amount * multiplier);
1485
- if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {
1486
- throw new TypeError(`${optionName} must resolve to a positive safe integer`);
1487
- }
1488
- if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {
1489
- throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);
1490
- }
1491
- return milliseconds;
1492
- }
1493
- __name(parseFarmServerDuration, "parseFarmServerDuration");
1494
- function resolveFarmServerHealthConfig(config) {
1495
- if (config === false || config && "enabled" in config && config.enabled === false) {
1496
- return Object.freeze({
1497
- enabled: false,
1498
- livenessPath: "/_farm/health/live",
1499
- readinessPath: "/_farm/health/ready"
1500
- });
1501
- }
1502
- const livenessPath = normalizeHealthPath(
1503
- config?.livenessPath ?? "/_farm/health/live",
1504
- "server.health.livenessPath"
1505
- );
1506
- const readinessPath = normalizeHealthPath(
1507
- config?.readinessPath ?? "/_farm/health/ready",
1508
- "server.health.readinessPath"
1509
- );
1510
- if (livenessPath === readinessPath) {
1511
- throw new TypeError("server.health livenessPath and readinessPath must be different");
1512
- }
1513
- return Object.freeze({ enabled: true, livenessPath, readinessPath });
1514
- }
1515
- __name(resolveFarmServerHealthConfig, "resolveFarmServerHealthConfig");
1516
- function normalizeHealthPath(value, optionName) {
1517
- const path = value.trim();
1518
- if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("*")) {
1519
- throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);
1520
- }
1521
- const normalized = path.length > 1 ? path.replace(/\/+$/, "") || "/" : path;
1522
- assertBrowserStableRoutePath(normalized);
1523
- return normalized;
1524
- }
1525
- __name(normalizeHealthPath, "normalizeHealthPath");
1526
- function parseBodySizeLimit(value, optionName = "bodySizeLimit") {
1527
- if (typeof value === "number") {
1528
- if (!Number.isSafeInteger(value) || value <= 0) {
1529
- throw new TypeError(`${optionName} must be a positive safe integer`);
1530
- }
1531
- return value;
1532
- }
1533
- const match = value.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|kib|mib|gib)?$/);
1534
- if (!match) {
1535
- throw new TypeError(`${optionName} must be bytes or a size string such as "500kb" or "10mb"`);
1536
- }
1537
- const amount = Number(match[1]);
1538
- const unit = match[2] ?? "b";
1539
- const multiplier = {
1540
- b: 1,
1541
- kb: 1e3,
1542
- mb: 1e6,
1543
- gb: 1e9,
1544
- kib: 1024,
1545
- mib: 1048576,
1546
- gib: 1073741824
1547
- };
1548
- const bytes = Math.floor(amount * multiplier[unit]);
1549
- if (!Number.isSafeInteger(bytes) || bytes <= 0) {
1550
- throw new TypeError(`${optionName} must resolve to a positive safe integer`);
1551
- }
1552
- return bytes;
1553
- }
1554
- __name(parseBodySizeLimit, "parseBodySizeLimit");
1555
- async function bufferFarmRequestBody(request, limit) {
1556
- if (request.method === "GET" || request.method === "HEAD" || request.body === null) {
1557
- return request;
1558
- }
1559
- const bytes = await readFarmRequestBody(request, limit);
1560
- const body = new Uint8Array(bytes.byteLength);
1561
- body.set(bytes);
1562
- const buffered = new Request(request, {
1563
- // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.
1564
- body: body.buffer
1565
- });
1566
- copyRequestContext(request, buffered);
1567
- return buffered;
1568
- }
1569
- __name(bufferFarmRequestBody, "bufferFarmRequestBody");
1570
- async function readFarmRequestBody(request, limit) {
1571
- try {
1572
- validateContentLength(request.headers.get("content-length"), limit);
1573
- } catch (error) {
1574
- void request.body?.cancel(error).catch(() => {
1575
- });
1576
- throw error;
1577
- }
1578
- throwIfAborted(request.signal);
1579
- if (!request.body) return new Uint8Array();
1580
- const reader = request.body.getReader();
1581
- const chunks = [];
1582
- let total = 0;
1583
- const cancelBodyRead = /* @__PURE__ */ __name(() => {
1584
- void reader.cancel(request.signal.reason).catch(() => {
1585
- });
1586
- }, "cancelBodyRead");
1587
- request.signal.addEventListener("abort", cancelBodyRead, { once: true });
1588
- try {
1589
- while (true) {
1590
- throwIfAborted(request.signal);
1591
- const { done, value } = await reader.read();
1592
- throwIfAborted(request.signal);
1593
- if (done) break;
1594
- if (!value) continue;
1595
- total += value.byteLength;
1596
- if (total > limit) {
1597
- const error = new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
1598
- void reader.cancel(error).catch(() => {
1599
- });
1600
- throw error;
1601
- }
1602
- chunks.push(value);
1603
- }
1604
- } catch (error) {
1605
- if (request.signal.aborted) throwIfAborted(request.signal);
1606
- throw error;
1607
- } finally {
1608
- request.signal.removeEventListener("abort", cancelBodyRead);
1609
- reader.releaseLock();
1610
- }
1611
- const body = new Uint8Array(total);
1612
- let offset = 0;
1613
- for (const chunk of chunks) {
1614
- body.set(chunk, offset);
1615
- offset += chunk.byteLength;
1616
- }
1617
- return body;
1618
- }
1619
- __name(readFarmRequestBody, "readFarmRequestBody");
1620
- function createFarmRequestBodyErrorResponse(error) {
1621
- if (!(error instanceof FarmRequestBodyError)) return null;
1622
- return new Response(error.status === 413 ? "Payload Too Large" : "Bad Request", {
1623
- status: error.status,
1624
- headers: {
1625
- "cache-control": "no-store",
1626
- "content-type": "text/plain; charset=utf-8",
1627
- "x-content-type-options": "nosniff"
1628
- }
1629
- });
1630
- }
1631
- __name(createFarmRequestBodyErrorResponse, "createFarmRequestBodyErrorResponse");
1632
- function validateContentLength(value, limit) {
1633
- const contentLength = value?.trim();
1634
- if (!contentLength) return;
1635
- if (!/^\d+$/.test(contentLength)) {
1636
- throw new FarmRequestBodyError("INVALID_CONTENT_LENGTH", 400, "Invalid content-length header");
1637
- }
1638
- if (Number(contentLength) > limit) {
1639
- throw new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
1640
- }
1641
- }
1642
- __name(validateContentLength, "validateContentLength");
1643
- function throwIfAborted(signal) {
1644
- if (!signal.aborted) return;
1645
- if (signal.reason !== void 0) throw signal.reason;
1646
- throw new DOMException("The operation was aborted", "AbortError");
1647
- }
1648
- __name(throwIfAborted, "throwIfAborted");
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkZ5HIWVDPcjs = require('./chunk-Z5HIWVDP.cjs');
4
+ require('./chunk-SVRTJOUF.cjs');
5
+ require('./chunk-G643DQCH.cjs');
6
+ require('./chunk-EM6SBQKM.cjs');
7
+ require('./chunk-UQZ4AYTH.cjs');
8
+ require('./chunk-NZKJGRB3.cjs');
9
+ require('./chunk-DVM4FKZL.cjs');
10
+ require('./chunk-US2QVW3E.cjs');
11
+ require('./chunk-BIDYX3SL.cjs');
12
+ require('./chunk-I57LW5VZ.cjs');
13
+ require('./chunk-NO3WWW3N.cjs');
1649
14
 
1650
- // src/integrations.ts
1651
- var FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY = "farm.integration.internalDispatch";
1652
- var FARM_INTEGRATION_SET_COOKIES_KEY = "farm:integration:set-cookies";
1653
- function takeForwardedIntegrationSetCookies(context) {
1654
- const cookies = context.req.get(FARM_INTEGRATION_SET_COOKIES_KEY);
1655
- if (cookies && cookies.length > 0) {
1656
- context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);
1657
- return cookies;
1658
- }
1659
- if (cookies) {
1660
- context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);
1661
- }
1662
- return [];
1663
- }
1664
- __name(takeForwardedIntegrationSetCookies, "takeForwardedIntegrationSetCookies");
1665
- function appendIntegrationForwardedCookies(response, cookies) {
1666
- if (cookies.length === 0) return response;
1667
- const headers = new Headers(response.headers);
1668
- for (const cookie of cookies) {
1669
- headers.append("set-cookie", cookie);
1670
- }
1671
- return new Response(response.body, {
1672
- status: response.status,
1673
- statusText: response.statusText,
1674
- headers
1675
- });
1676
- }
1677
- __name(appendIntegrationForwardedCookies, "appendIntegrationForwardedCookies");
1678
- function defineTypedIntegrationRoute(method, path, input) {
1679
- return {
1680
- path,
1681
- method,
1682
- middleware: input.middleware,
1683
- before: input.before,
1684
- after: input.after,
1685
- rawBody: input.rawBody,
1686
- bodyFormat: input.bodyFormat,
1687
- input: normalizeIntegrationRouteInputSchemas(input),
1688
- handler: input.handler,
1689
- __operation: defineIntegrationAPIOperation({
1690
- path,
1691
- method,
1692
- bodyFormat: input.bodyFormat,
1693
- responseFormat: input.responseFormat,
1694
- headers: input.headers,
1695
- credentials: input.credentials,
1696
- isServer: input.isServer
1697
- })
1698
- };
1699
- }
1700
- __name(defineTypedIntegrationRoute, "defineTypedIntegrationRoute");
1701
- function createIntegrationRouteFactory() {
1702
- return {
1703
- get(path, input) {
1704
- return defineTypedIntegrationRoute(
1705
- "GET",
1706
- path,
1707
- input
1708
- );
1709
- },
1710
- post(path, input) {
1711
- return defineTypedIntegrationRoute(
1712
- "POST",
1713
- path,
1714
- {
1715
- bodyFormat: "json",
1716
- ...input
1717
- }
1718
- );
1719
- },
1720
- query(path, input) {
1721
- return defineTypedIntegrationRoute("QUERY", path, {
1722
- bodyFormat: "json",
1723
- ...input
1724
- });
1725
- },
1726
- put(path, input) {
1727
- return defineTypedIntegrationRoute(
1728
- "PUT",
1729
- path,
1730
- {
1731
- bodyFormat: "json",
1732
- ...input
1733
- }
1734
- );
1735
- },
1736
- patch(path, input) {
1737
- return defineTypedIntegrationRoute("PATCH", path, {
1738
- bodyFormat: "json",
1739
- ...input
1740
- });
1741
- },
1742
- delete(path, input) {
1743
- return defineTypedIntegrationRoute("DELETE", path, {
1744
- bodyFormat: "json",
1745
- ...input
1746
- });
1747
- },
1748
- options(path, input) {
1749
- return defineTypedIntegrationRoute("OPTIONS", path, input);
1750
- },
1751
- head(path, input) {
1752
- return defineTypedIntegrationRoute(
1753
- "HEAD",
1754
- path,
1755
- input
1756
- );
1757
- }
1758
- };
1759
- }
1760
- __name(createIntegrationRouteFactory, "createIntegrationRouteFactory");
1761
- function createIntegrationRoute(_schema) {
1762
- return createIntegrationRouteFactory();
1763
- }
1764
- __name(createIntegrationRoute, "createIntegrationRoute");
1765
- var integrationRoute = createIntegrationRouteFactory();
1766
- var INTEGRATION_REQUEST_DISPATCHER_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRequestDispatcher");
1767
- function isIntegrationEndpointRoute(value) {
1768
- return !!value && typeof value === "object" && typeof value.path === "string" && typeof value.handler === "function";
1769
- }
1770
- __name(isIntegrationEndpointRoute, "isIntegrationEndpointRoute");
1771
- function flattenIntegrationEndpoints(endpoints) {
1772
- if (!endpoints) {
1773
- return [];
1774
- }
1775
- if (Array.isArray(endpoints)) {
1776
- return endpoints.flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));
1777
- }
1778
- if (isIntegrationEndpointRoute(endpoints)) {
1779
- return [endpoints];
1780
- }
1781
- if (typeof endpoints === "object") {
1782
- return Object.values(endpoints).flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));
1783
- }
1784
- return [];
1785
- }
1786
- __name(flattenIntegrationEndpoints, "flattenIntegrationEndpoints");
1787
- function defineIntegration(integration) {
1788
- const category = integration.category ?? integration.slot;
1789
- if (!category) {
1790
- throw new Error("Integration category is required.");
1791
- }
1792
- if (integration.category && integration.slot && integration.category !== integration.slot) {
1793
- throw new Error("Integration category and slot must match when both are provided.");
1794
- }
1795
- const routeFactory = createIntegrationRoute(integration.schema);
1796
- const routes = typeof integration.routes === "function" ? integration.routes({
1797
- route: routeFactory,
1798
- integrationRoute: routeFactory
1799
- }) : integration.routes;
1800
- const endpoints = typeof integration.endpoints === "function" ? integration.endpoints({
1801
- endpoint: routeFactory,
1802
- route: routeFactory,
1803
- integrationRoute: routeFactory
1804
- }) : integration.endpoints;
1805
- const endpointRoutes = flattenIntegrationEndpoints(endpoints);
1806
- const allRoutes = routes?.length || endpointRoutes.length ? [...routes || [], ...endpointRoutes] : void 0;
1807
- for (const route2 of allRoutes || []) {
1808
- assertUniqueRouteParameters(route2.path, "api");
1809
- validateConfigRouteSource(route2.path, `Integration route "${route2.path}"`);
1810
- assertTerminalCatchAll(route2.path, "api");
1811
- }
1812
- const derivedApi = integration.api || (allRoutes?.length ? api.fromRoutes(
1813
- allRoutes
1814
- ) : void 0);
1815
- return {
1816
- kind: "farm-integration",
1817
- ...integration,
1818
- endpoints,
1819
- routes: allRoutes,
1820
- api: derivedApi,
1821
- category,
1822
- slot: category
1823
- };
1824
- }
1825
- __name(defineIntegration, "defineIntegration");
1826
- async function emitIntegrationLog(integration, event) {
1827
- try {
1828
- await integration.log?.(event);
1829
- } catch {
1830
- }
1831
- }
1832
- __name(emitIntegrationLog, "emitIntegrationLog");
1833
- var INTEGRATION_DATA_HEADER = "x-farm-integration-data";
1834
- var INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;
1835
- var BLOCKED_INTEGRATION_DATA_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1836
- function isFarmIntegrationData(value) {
1837
- return !!value && typeof value === "object" && !Array.isArray(value);
1838
- }
1839
- __name(isFarmIntegrationData, "isFarmIntegrationData");
1840
- function isPlainIntegrationDataObject(value) {
1841
- if (!isFarmIntegrationData(value)) {
1842
- return false;
1843
- }
1844
- const prototype = Object.getPrototypeOf(value);
1845
- return prototype === Object.prototype || prototype === null;
1846
- }
1847
- __name(isPlainIntegrationDataObject, "isPlainIntegrationDataObject");
1848
- function sanitizeIntegrationDataValue(value) {
1849
- if (Array.isArray(value)) {
1850
- return value.map((item) => sanitizeIntegrationDataValue(item));
1851
- }
1852
- if (!isPlainIntegrationDataObject(value)) {
1853
- return value;
1854
- }
1855
- const sanitized = {};
1856
- for (const [key, item] of Object.entries(value)) {
1857
- if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {
1858
- continue;
1859
- }
1860
- sanitized[key] = sanitizeIntegrationDataValue(item);
1861
- }
1862
- return sanitized;
1863
- }
1864
- __name(sanitizeIntegrationDataValue, "sanitizeIntegrationDataValue");
1865
- function normalizeIntegrationData(value) {
1866
- if (!isFarmIntegrationData(value)) {
1867
- return {};
1868
- }
1869
- const sanitized = sanitizeIntegrationDataValue(value);
1870
- return isFarmIntegrationData(sanitized) ? sanitized : {};
1871
- }
1872
- __name(normalizeIntegrationData, "normalizeIntegrationData");
1873
- function getIntegrationDataHeaderByteLength(value) {
1874
- return new TextEncoder().encode(value).byteLength;
1875
- }
1876
- __name(getIntegrationDataHeaderByteLength, "getIntegrationDataHeaderByteLength");
1877
- function parseIntegrationDataHeader(request) {
1878
- const raw = request.headers.get(INTEGRATION_DATA_HEADER);
1879
- if (!raw) {
1880
- return {};
1881
- }
1882
- if (getIntegrationDataHeaderByteLength(raw) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {
1883
- return {};
1884
- }
1885
- try {
1886
- const value = JSON.parse(raw);
1887
- return normalizeIntegrationData(value);
1888
- } catch {
1889
- return {};
1890
- }
1891
- }
1892
- __name(parseIntegrationDataHeader, "parseIntegrationDataHeader");
1893
- function resolveIntegrationData(request, data) {
1894
- return {
1895
- ...parseIntegrationDataHeader(request),
1896
- ...normalizeIntegrationData(data)
1897
- };
1898
- }
1899
- __name(resolveIntegrationData, "resolveIntegrationData");
1900
- var INTEGRATION_ROUTE_SEGMENTS = /* @__PURE__ */ Symbol("farm.integrationRouteSegments");
1901
- var EMPTY_NORMALIZED_INTEGRATION_ROUTES = [];
1902
- var normalizedIntegrationRoutesCache = /* @__PURE__ */ new WeakMap();
1903
- function normalizeIntegrationRoutes(routes) {
1904
- if (routes.length === 0) {
1905
- return EMPTY_NORMALIZED_INTEGRATION_ROUTES;
1906
- }
1907
- const cached = normalizedIntegrationRoutesCache.get(routes);
1908
- if (cached) {
1909
- return cached;
1910
- }
1911
- const normalized = routes.map((route2, index) => {
1912
- assertUniqueRouteParameters(route2.path, "api");
1913
- return {
1914
- index,
1915
- route: {
1916
- ...route2,
1917
- methods: normalizeIntegrationRouteMethods(route2),
1918
- input: normalizeIntegrationRouteInputSchemas(route2),
1919
- [INTEGRATION_ROUTE_SEGMENTS]: splitPath(route2.path)
1920
- },
1921
- specificity: getRoutePatternSpecificity(route2.path, "api")
1922
- };
1923
- }).sort(
1924
- (left, right) => compareRouteSpecificity(left.specificity, right.specificity) || left.index - right.index
1925
- ).map(({ route: route2 }) => route2);
1926
- normalizedIntegrationRoutesCache.set(routes, normalized);
1927
- return normalized;
1928
- }
1929
- __name(normalizeIntegrationRoutes, "normalizeIntegrationRoutes");
1930
- function normalizeIntegrationRouteMethods(route2) {
1931
- const input = route2.methods && route2.methods.length > 0 ? [...route2.methods] : route2.method ? [route2.method] : ["ALL"];
1932
- return input.map((method) => String(method).toUpperCase());
1933
- }
1934
- __name(normalizeIntegrationRouteMethods, "normalizeIntegrationRouteMethods");
1935
- function normalizeIntegrationRouteInputSchemas(route2) {
1936
- const input = {
1937
- ...route2.input
1938
- };
1939
- if (route2.body) {
1940
- input.body = route2.body;
1941
- }
1942
- if (route2.query) {
1943
- input.query = route2.query;
1944
- }
1945
- return input.body || input.query ? input : void 0;
1946
- }
1947
- __name(normalizeIntegrationRouteInputSchemas, "normalizeIntegrationRouteInputSchemas");
1948
- async function validateIntegrationRouteInput(route2, request, url) {
1949
- if (request.method.toUpperCase() === "QUERY" && !request.headers.has("content-type")) {
1950
- return {
1951
- success: false,
1952
- response: Response.json(
1953
- {
1954
- error: "Invalid QUERY request",
1955
- message: "QUERY requests must include a Content-Type header."
1956
- },
1957
- { status: 400 }
1958
- )
1959
- };
1960
- }
1961
- const schemas = route2.input;
1962
- if (!schemas?.body && !schemas?.query) {
1963
- return {
1964
- success: true,
1965
- input: {}
1966
- };
1967
- }
1968
- const input = {};
1969
- const issues = [];
1970
- if (schemas.query) {
1971
- const queryResult = await parseIntegrationInputSchema(
1972
- "query",
1973
- schemas.query,
1974
- createQueryInput(url.searchParams)
1975
- );
1976
- if (queryResult.success) {
1977
- input.query = queryResult.data;
1978
- } else {
1979
- issues.push(...queryResult.issues);
1980
- }
1981
- }
1982
- if (schemas.body) {
1983
- const bodyInput = await readIntegrationValidationBody(
1984
- request,
1985
- getIntegrationRouteBodyFormat(route2)
1986
- );
1987
- if (bodyInput.success) {
1988
- const bodyResult = await parseIntegrationInputSchema("body", schemas.body, bodyInput.data);
1989
- if (bodyResult.success) {
1990
- input.body = bodyResult.data;
1991
- } else {
1992
- issues.push(...bodyResult.issues);
1993
- }
1994
- } else {
1995
- issues.push(bodyInput.issue);
1996
- }
1997
- }
1998
- if (issues.length > 0) {
1999
- return {
2000
- success: false,
2001
- response: createIntegrationValidationResponse(issues)
2002
- };
2003
- }
2004
- return {
2005
- success: true,
2006
- input
2007
- };
2008
- }
2009
- __name(validateIntegrationRouteInput, "validateIntegrationRouteInput");
2010
- async function parseIntegrationInputSchema(source, schema, value) {
2011
- const parser = schema.safeParseAsync || schema.safeParse;
2012
- if (parser) {
2013
- const result = await parser.call(schema, value);
2014
- if (result.success) {
2015
- return {
2016
- success: true,
2017
- data: result.data
2018
- };
2019
- }
2020
- return {
2021
- success: false,
2022
- issues: normalizeIntegrationValidationIssues(source, result.error)
2023
- };
2024
- }
2025
- if (schema["~standard"]?.validate) {
2026
- const result = await schema["~standard"].validate(value);
2027
- if ("value" in result) {
2028
- return {
2029
- success: true,
2030
- data: result.value
2031
- };
2032
- }
2033
- return {
2034
- success: false,
2035
- issues: normalizeIntegrationValidationIssues(source, {
2036
- issues: result.issues
2037
- })
2038
- };
2039
- }
2040
- if (schema.parse) {
2041
- try {
2042
- return {
2043
- success: true,
2044
- data: await schema.parse(value)
2045
- };
2046
- } catch (error) {
2047
- return {
2048
- success: false,
2049
- issues: normalizeIntegrationValidationIssues(
2050
- source,
2051
- normalizeIntegrationValidationError(error)
2052
- )
2053
- };
2054
- }
2055
- }
2056
- return {
2057
- success: false,
2058
- issues: [
2059
- {
2060
- source,
2061
- message: "Input schema must expose safeParse, safeParseAsync, parse, or ~standard.validate."
2062
- }
2063
- ]
2064
- };
2065
- }
2066
- __name(parseIntegrationInputSchema, "parseIntegrationInputSchema");
2067
- function createIntegrationValidationResponse(issues) {
2068
- return Response.json(
2069
- {
2070
- error: "Integration route input validation failed",
2071
- issues
2072
- },
2073
- {
2074
- status: 400
2075
- }
2076
- );
2077
- }
2078
- __name(createIntegrationValidationResponse, "createIntegrationValidationResponse");
2079
- function normalizeIntegrationValidationIssues(source, error) {
2080
- if (Array.isArray(error.issues) && error.issues.length > 0) {
2081
- return error.issues.map((issue) => ({
2082
- source,
2083
- path: normalizeIntegrationValidationPath(issue.path),
2084
- code: issue.code,
2085
- message: issue.message || "Invalid input"
2086
- }));
2087
- }
2088
- return [
2089
- {
2090
- source,
2091
- path: [],
2092
- message: error.message || "Invalid input"
2093
- }
2094
- ];
2095
- }
2096
- __name(normalizeIntegrationValidationIssues, "normalizeIntegrationValidationIssues");
2097
- function normalizeIntegrationValidationPath(path) {
2098
- return (path || []).map((segment) => {
2099
- const key = typeof segment === "object" && segment !== null && "key" in segment ? segment.key : segment;
2100
- return typeof key === "symbol" ? key.description || key.toString() : key;
2101
- });
2102
- }
2103
- __name(normalizeIntegrationValidationPath, "normalizeIntegrationValidationPath");
2104
- function normalizeIntegrationValidationError(error) {
2105
- if (error && typeof error === "object") {
2106
- return error;
2107
- }
2108
- return {
2109
- message: error instanceof Error ? error.message : String(error || "Invalid input")
2110
- };
2111
- }
2112
- __name(normalizeIntegrationValidationError, "normalizeIntegrationValidationError");
2113
- async function readIntegrationValidationBody(request, format) {
2114
- if (request.method === "GET" || request.method === "HEAD" || format === "none") {
2115
- return {
2116
- success: true,
2117
- data: void 0
2118
- };
2119
- }
2120
- try {
2121
- if (format === "form") {
2122
- return {
2123
- success: true,
2124
- data: createFormInput(await request.clone().formData())
2125
- };
2126
- }
2127
- const text = await request.clone().text();
2128
- if (text.trim().length === 0) {
2129
- return {
2130
- success: true,
2131
- data: void 0
2132
- };
2133
- }
2134
- return {
2135
- success: true,
2136
- data: JSON.parse(text)
2137
- };
2138
- } catch (error) {
2139
- return {
2140
- success: false,
2141
- issue: {
2142
- source: "body",
2143
- path: [],
2144
- message: format === "json" ? "Expected a valid JSON request body." : error instanceof Error && error.message ? error.message : "Could not parse request body."
2145
- }
2146
- };
2147
- }
2148
- }
2149
- __name(readIntegrationValidationBody, "readIntegrationValidationBody");
2150
- function getIntegrationRouteBodyFormat(route2) {
2151
- return route2.bodyFormat || route2.__operation?.bodyFormat || "json";
2152
- }
2153
- __name(getIntegrationRouteBodyFormat, "getIntegrationRouteBodyFormat");
2154
- function createIntegrationRouteArgs(input) {
2155
- let clientPromise;
2156
- let ormPromise;
2157
- const getClient = /* @__PURE__ */ __name(() => {
2158
- clientPromise ?? (clientPromise = Promise.resolve().then(() => (init_storage(), storage_exports)).then(
2159
- ({ resolveStorageRuntimeClient: resolveStorageRuntimeClient2 }) => resolveStorageRuntimeClient2(input.config.storage)
2160
- ));
2161
- return clientPromise;
2162
- }, "getClient");
2163
- const getOrm = /* @__PURE__ */ __name(() => {
2164
- if (!input.integration.schema) {
2165
- throw new Error(
2166
- `Integration "${input.integration.type}" does not define a schema for ctx.args.db.`
2167
- );
2168
- }
2169
- ormPromise ?? (ormPromise = Promise.resolve().then(() => (init_integration_orm(), integration_orm_exports)).then(
2170
- ({ createIntegrationOrm: createIntegrationOrm2 }) => createIntegrationOrm2({
2171
- schema: input.integration.schema,
2172
- config: input.config
2173
- })
2174
- ));
2175
- return ormPromise;
2176
- }, "getOrm");
2177
- return {
2178
- db: createLazyIntegrationOrmClient(getOrm),
2179
- getDb: getOrm,
2180
- storage: {
2181
- getClient,
2182
- getOrm
2183
- }
2184
- };
2185
- }
2186
- __name(createIntegrationRouteArgs, "createIntegrationRouteArgs");
2187
- function createLazyIntegrationOrmClient(resolveOrm) {
2188
- const modelProxyCache = /* @__PURE__ */ new Map();
2189
- return new Proxy(
2190
- {},
2191
- {
2192
- get(_target, prop) {
2193
- if (prop === "then") {
2194
- return void 0;
2195
- }
2196
- if (prop === "transaction" || prop === "batch") {
2197
- return async (...args) => {
2198
- const orm = await resolveOrm();
2199
- const member = orm[prop];
2200
- if (typeof member !== "function") {
2201
- throw new Error(`Integration ORM does not expose "${String(prop)}".`);
2202
- }
2203
- return member.apply(orm, args);
2204
- };
2205
- }
2206
- if (prop === "$driver") {
2207
- return void 0;
2208
- }
2209
- if (!modelProxyCache.has(prop)) {
2210
- modelProxyCache.set(prop, createLazyIntegrationOrmModel(resolveOrm, prop));
2211
- }
2212
- return modelProxyCache.get(prop);
2213
- }
2214
- }
2215
- );
2216
- }
2217
- __name(createLazyIntegrationOrmClient, "createLazyIntegrationOrmClient");
2218
- function createLazyIntegrationOrmModel(resolveOrm, modelName) {
2219
- return new Proxy(
2220
- {},
2221
- {
2222
- get(_target, prop) {
2223
- if (prop === "then") {
2224
- return void 0;
2225
- }
2226
- return async (...args) => {
2227
- const orm = await resolveOrm();
2228
- const model = orm[modelName];
2229
- const member = model?.[prop];
2230
- if (typeof member !== "function") {
2231
- throw new Error(
2232
- `Integration ORM model "${String(modelName)}" does not expose "${String(prop)}".`
2233
- );
2234
- }
2235
- return member.apply(model, args);
2236
- };
2237
- }
2238
- }
2239
- );
2240
- }
2241
- __name(createLazyIntegrationOrmModel, "createLazyIntegrationOrmModel");
2242
- async function runIntegrationRouteBeforeHooks(route2, request, context) {
2243
- const hookContext = context;
2244
- hookContext.response = void 0;
2245
- for (const hook of route2.before || []) {
2246
- const response = await hook(request, hookContext);
2247
- if (response) {
2248
- hookContext.response = response;
2249
- return response;
2250
- }
2251
- if (hookContext.response) {
2252
- return hookContext.response;
2253
- }
2254
- }
2255
- return void 0;
2256
- }
2257
- __name(runIntegrationRouteBeforeHooks, "runIntegrationRouteBeforeHooks");
2258
- async function runIntegrationRouteAfterHooks(route2, request, context, response) {
2259
- const hookContext = context;
2260
- let currentResponse = response;
2261
- for (const hook of route2.after || []) {
2262
- hookContext.response = currentResponse;
2263
- const nextResponse = await hook(request, hookContext);
2264
- currentResponse = nextResponse || hookContext.response || currentResponse;
2265
- }
2266
- hookContext.response = currentResponse;
2267
- return currentResponse;
2268
- }
2269
- __name(runIntegrationRouteAfterHooks, "runIntegrationRouteAfterHooks");
2270
- function createQueryInput(searchParams) {
2271
- const input = {};
2272
- searchParams.forEach((value, key) => {
2273
- if (key === "__proto__" || key === "constructor" || key === "prototype") return;
2274
- const existing = input[key];
2275
- if (existing === void 0) {
2276
- input[key] = value;
2277
- return;
2278
- }
2279
- input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
2280
- });
2281
- return input;
2282
- }
2283
- __name(createQueryInput, "createQueryInput");
2284
- function createFormInput(formData) {
2285
- const input = {};
2286
- formData.forEach((value, key) => {
2287
- if (key === "__proto__" || key === "constructor" || key === "prototype") return;
2288
- const existing = input[key];
2289
- if (existing === void 0) {
2290
- input[key] = value;
2291
- return;
2292
- }
2293
- input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
2294
- });
2295
- return input;
2296
- }
2297
- __name(createFormInput, "createFormInput");
2298
- async function dispatchIntegrationRequest(runtime, request, options = {}) {
2299
- try {
2300
- request = await bufferFarmRequestBody(
2301
- request,
2302
- resolveFarmServerConfig(runtime.config.server).bodySizeLimit
2303
- );
2304
- } catch (error) {
2305
- const response = createFarmRequestBodyErrorResponse(error);
2306
- if (response) return response;
2307
- throw error;
2308
- }
2309
- const integration = runtime.integration;
2310
- const url = new URL(request.url);
2311
- const pathname = url.pathname;
2312
- const requestId = request.headers.get("x-request-id") || options.currentRequest?.headers.get("x-request-id") || String(Date.now());
2313
- const routes = normalizeIntegrationRoutes(integration.routes || []);
2314
- const pathSegments = canonicalizeRequestPathSegments(pathname);
2315
- const method = normalizeIntegrationRequestMethod(request.method);
2316
- const middleware = [...integration.middleware || []];
2317
- const forwardedSetCookies = [];
2318
- for (const entry of middleware) {
2319
- const params = resolveMatcherParams(entry.matcher, pathname);
2320
- if (!params) {
2321
- continue;
2322
- }
2323
- const handlerContext = createServerIntegrationHandlerContext({
2324
- runtime,
2325
- route: {
2326
- kind: "middleware",
2327
- path: normalizeMatcher(entry.matcher),
2328
- methods: ["ALL"]
2329
- },
2330
- request,
2331
- params,
2332
- pathname,
2333
- requestId,
2334
- currentRequest: options.currentRequest,
2335
- data: options.data,
2336
- internal: options.internal === true
2337
- });
2338
- const startedAt = Date.now();
2339
- await emitIntegrationLog(integration, {
2340
- category: integration.category,
2341
- slot: integration.category,
2342
- type: integration.type,
2343
- phase: "request:start",
2344
- route: {
2345
- kind: "middleware",
2346
- path: normalizeMatcher(entry.matcher),
2347
- methods: ["ALL"]
2348
- },
2349
- request,
2350
- requestId,
2351
- context: handlerContext.req.snapshot()
2352
- });
2353
- try {
2354
- const response = await entry.handler(request, handlerContext);
2355
- forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(handlerContext));
2356
- if (response) {
2357
- await emitIntegrationLog(integration, {
2358
- category: integration.category,
2359
- slot: integration.category,
2360
- type: integration.type,
2361
- phase: "request:end",
2362
- route: {
2363
- kind: "middleware",
2364
- path: normalizeMatcher(entry.matcher),
2365
- methods: ["ALL"]
2366
- },
2367
- request,
2368
- response,
2369
- requestId,
2370
- durationMs: Date.now() - startedAt,
2371
- context: handlerContext.req.snapshot()
2372
- });
2373
- return appendIntegrationForwardedCookies(response, forwardedSetCookies);
2374
- }
2375
- await emitIntegrationLog(integration, {
2376
- category: integration.category,
2377
- slot: integration.category,
2378
- type: integration.type,
2379
- phase: "request:end",
2380
- route: {
2381
- kind: "middleware",
2382
- path: normalizeMatcher(entry.matcher),
2383
- methods: ["ALL"]
2384
- },
2385
- request,
2386
- requestId,
2387
- durationMs: Date.now() - startedAt,
2388
- context: handlerContext.req.snapshot()
2389
- });
2390
- } catch (error) {
2391
- await emitIntegrationLog(integration, {
2392
- category: integration.category,
2393
- slot: integration.category,
2394
- type: integration.type,
2395
- phase: "request:error",
2396
- route: {
2397
- kind: "middleware",
2398
- path: normalizeMatcher(entry.matcher),
2399
- methods: ["ALL"]
2400
- },
2401
- request,
2402
- requestId,
2403
- durationMs: Date.now() - startedAt,
2404
- error,
2405
- context: handlerContext.req.snapshot()
2406
- });
2407
- throw error;
2408
- }
2409
- }
2410
- for (const route2 of routes) {
2411
- const params = method && matchesMethod(route2.methods, method) ? matchPathSegments(route2[INTEGRATION_ROUTE_SEGMENTS], pathSegments) : null;
2412
- if (!params) {
2413
- continue;
2414
- }
2415
- const handlerContext = createServerIntegrationHandlerContext({
2416
- runtime,
2417
- route: {
2418
- kind: "route",
2419
- path: route2.path,
2420
- methods: route2.methods
2421
- },
2422
- request,
2423
- params,
2424
- pathname,
2425
- requestId,
2426
- currentRequest: options.currentRequest,
2427
- data: options.data,
2428
- internal: options.internal === true
2429
- });
2430
- const startedAt = Date.now();
2431
- await emitIntegrationLog(integration, {
2432
- category: integration.category,
2433
- slot: integration.category,
2434
- type: integration.type,
2435
- phase: "request:start",
2436
- route: {
2437
- kind: "route",
2438
- path: route2.path,
2439
- methods: route2.methods
2440
- },
2441
- request,
2442
- requestId,
2443
- context: handlerContext.req.snapshot()
2444
- });
2445
- try {
2446
- const validation = await validateIntegrationRouteInput(route2, request, url);
2447
- if (!validation.success) {
2448
- await emitIntegrationLog(integration, {
2449
- category: integration.category,
2450
- slot: integration.category,
2451
- type: integration.type,
2452
- phase: "request:end",
2453
- route: {
2454
- kind: "route",
2455
- path: route2.path,
2456
- methods: route2.methods
2457
- },
2458
- request,
2459
- response: validation.response,
2460
- requestId,
2461
- durationMs: Date.now() - startedAt,
2462
- context: handlerContext.req.snapshot()
2463
- });
2464
- return appendIntegrationForwardedCookies(validation.response, forwardedSetCookies);
2465
- }
2466
- handlerContext.input = validation.input;
2467
- for (const middlewareEntry of route2.middleware || []) {
2468
- const middlewareResponse = await middlewareEntry.handler(request, handlerContext);
2469
- forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(handlerContext));
2470
- if (middlewareResponse) {
2471
- await emitIntegrationLog(integration, {
2472
- category: integration.category,
2473
- slot: integration.category,
2474
- type: integration.type,
2475
- phase: "request:end",
2476
- route: {
2477
- kind: "route",
2478
- path: route2.path,
2479
- methods: route2.methods
2480
- },
2481
- request,
2482
- response: middlewareResponse,
2483
- requestId,
2484
- durationMs: Date.now() - startedAt,
2485
- context: handlerContext.req.snapshot()
2486
- });
2487
- return appendIntegrationForwardedCookies(middlewareResponse, forwardedSetCookies);
2488
- }
2489
- }
2490
- const beforeResponse = await runIntegrationRouteBeforeHooks(route2, request, handlerContext);
2491
- if (beforeResponse) {
2492
- const response2 = await runIntegrationRouteAfterHooks(
2493
- route2,
2494
- request,
2495
- handlerContext,
2496
- beforeResponse
2497
- );
2498
- await emitIntegrationLog(integration, {
2499
- category: integration.category,
2500
- slot: integration.category,
2501
- type: integration.type,
2502
- phase: "request:end",
2503
- route: {
2504
- kind: "route",
2505
- path: route2.path,
2506
- methods: route2.methods
2507
- },
2508
- request,
2509
- response: response2,
2510
- requestId,
2511
- durationMs: Date.now() - startedAt,
2512
- context: handlerContext.req.snapshot()
2513
- });
2514
- return appendIntegrationForwardedCookies(response2, forwardedSetCookies);
2515
- }
2516
- const handlerResponse = await route2.handler(request, handlerContext);
2517
- const response = await runIntegrationRouteAfterHooks(
2518
- route2,
2519
- request,
2520
- handlerContext,
2521
- handlerResponse
2522
- );
2523
- await emitIntegrationLog(integration, {
2524
- category: integration.category,
2525
- slot: integration.category,
2526
- type: integration.type,
2527
- phase: "request:end",
2528
- route: {
2529
- kind: "route",
2530
- path: route2.path,
2531
- methods: route2.methods
2532
- },
2533
- request,
2534
- response,
2535
- requestId,
2536
- durationMs: Date.now() - startedAt,
2537
- context: handlerContext.req.snapshot()
2538
- });
2539
- return appendIntegrationForwardedCookies(response, forwardedSetCookies);
2540
- } catch (error) {
2541
- await emitIntegrationLog(integration, {
2542
- category: integration.category,
2543
- slot: integration.category,
2544
- type: integration.type,
2545
- phase: "request:error",
2546
- route: {
2547
- kind: "route",
2548
- path: route2.path,
2549
- methods: route2.methods
2550
- },
2551
- request,
2552
- requestId,
2553
- durationMs: Date.now() - startedAt,
2554
- error,
2555
- context: handlerContext.req.snapshot()
2556
- });
2557
- throw error;
2558
- }
2559
- }
2560
- if (forwardedSetCookies.length > 0) {
2561
- options.onForwardedCookies?.(forwardedSetCookies);
2562
- }
2563
- return null;
2564
- }
2565
- __name(dispatchIntegrationRequest, "dispatchIntegrationRequest");
2566
- globalThis[INTEGRATION_REQUEST_DISPATCHER_KEY] = dispatchIntegrationRequest;
2567
- function createServerIntegrationHandlerContext(input) {
2568
- const req = createServerIntegrationRequestContextStore(input.request, input.currentRequest);
2569
- if (input.internal) {
2570
- req.set(FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY, true);
2571
- }
2572
- return {
2573
- request: input.request,
2574
- requestId: input.requestId,
2575
- url: new URL(input.request.url),
2576
- pathname: input.pathname,
2577
- method: input.request.method,
2578
- params: input.params,
2579
- input: {},
2580
- args: createIntegrationRouteArgs({
2581
- integration: input.runtime.integration,
2582
- config: input.runtime.config
2583
- }),
2584
- data: resolveIntegrationData(input.request, input.data),
2585
- integration: {
2586
- category: input.runtime.integration.category,
2587
- slot: input.runtime.integration.category,
2588
- type: input.runtime.integration.type,
2589
- instance: input.runtime.integration.instance
2590
- },
2591
- route: input.route,
2592
- req,
2593
- requestContext: req,
2594
- config: input.runtime.config,
2595
- isDev: input.runtime.isDev,
2596
- isProd: input.runtime.isProd
2597
- };
2598
- }
2599
- __name(createServerIntegrationHandlerContext, "createServerIntegrationHandlerContext");
2600
- function createServerIntegrationRequestContextStore(request, currentRequest) {
2601
- return {
2602
- get(key) {
2603
- const requestValue = getRequestContext(request, key);
2604
- if (requestValue !== void 0) {
2605
- return requestValue;
2606
- }
2607
- if (currentRequest) {
2608
- return getRequestContext(currentRequest, key);
2609
- }
2610
- return void 0;
2611
- },
2612
- set(key, value, options) {
2613
- setRequestContext(request, key, value, options);
2614
- if (currentRequest) {
2615
- setRequestContext(currentRequest, key, value, options);
2616
- }
2617
- },
2618
- has(key) {
2619
- return hasRequestContext(request, key) || !!currentRequest && hasRequestContext(currentRequest, key);
2620
- },
2621
- delete(key) {
2622
- const deletedRequest = deleteRequestContext(request, key);
2623
- const deletedCurrent = currentRequest ? deleteRequestContext(currentRequest, key) : false;
2624
- return deletedRequest || deletedCurrent;
2625
- },
2626
- clear() {
2627
- clearRequestContext(request);
2628
- if (currentRequest) {
2629
- clearRequestContext(currentRequest);
2630
- }
2631
- },
2632
- snapshot(options) {
2633
- const merged = currentRequest ? getRequestContextSnapshot(currentRequest, options) : /* @__PURE__ */ new Map();
2634
- const requestSnapshot = getRequestContextSnapshot(request, options);
2635
- for (const [key, value] of requestSnapshot) {
2636
- merged.set(key, value);
2637
- }
2638
- return merged;
2639
- }
2640
- };
2641
- }
2642
- __name(createServerIntegrationRequestContextStore, "createServerIntegrationRequestContextStore");
2643
- function normalizeIntegrationRequestMethod(method) {
2644
- return method ? method.toUpperCase() : void 0;
2645
- }
2646
- __name(normalizeIntegrationRequestMethod, "normalizeIntegrationRequestMethod");
2647
- function matchesMethod(methods, normalizedMethod) {
2648
- return methods.some((candidate) => candidate === "ALL" || candidate === normalizedMethod);
2649
- }
2650
- __name(matchesMethod, "matchesMethod");
2651
- function resolveMatcherParams(matcher, pathname) {
2652
- if (!matcher) {
2653
- return {};
2654
- }
2655
- const list = Array.isArray(matcher) ? matcher : [matcher];
2656
- let canonicalPathname;
2657
- let canonicalSegments;
2658
- for (const item of list) {
2659
- if (item === "/(.*)" || item === "*") {
2660
- return {};
2661
- }
2662
- if (item.endsWith("(.*)")) {
2663
- canonicalPathname ?? (canonicalPathname = canonicalizeRequestPathname(pathname));
2664
- const prefix = item.slice(0, -4);
2665
- if (canonicalPathname === prefix || canonicalPathname.startsWith(`${prefix}/`)) {
2666
- return {};
2667
- }
2668
- continue;
2669
- }
2670
- canonicalSegments ?? (canonicalSegments = canonicalizeRequestPathSegments(pathname));
2671
- const params = matchPathSegments(splitPath(item), canonicalSegments);
2672
- if (params) {
2673
- return params;
2674
- }
2675
- }
2676
- return null;
2677
- }
2678
- __name(resolveMatcherParams, "resolveMatcherParams");
2679
- function matchPathSegments(routeSegments, pathSegments) {
2680
- const params = {};
2681
- let routeIndex = 0;
2682
- let pathIndex = 0;
2683
- while (routeIndex < routeSegments.length && pathIndex < pathSegments.length) {
2684
- const routeSegment = routeSegments[routeIndex];
2685
- const pathSegment = pathSegments[pathIndex];
2686
- if (isCatchAllSegment(routeSegment)) {
2687
- params[getSegmentParamName(routeSegment)] = pathSegments.slice(pathIndex);
2688
- return params;
2689
- }
2690
- if (isDynamicSegment(routeSegment)) {
2691
- params[getSegmentParamName(routeSegment)] = pathSegment;
2692
- routeIndex += 1;
2693
- pathIndex += 1;
2694
- continue;
2695
- }
2696
- if (routeSegment !== pathSegment) {
2697
- return null;
2698
- }
2699
- routeIndex += 1;
2700
- pathIndex += 1;
2701
- }
2702
- if (routeIndex === routeSegments.length && pathIndex === pathSegments.length) {
2703
- return params;
2704
- }
2705
- if (routeIndex === routeSegments.length - 1 && isCatchAllSegment(routeSegments[routeIndex])) {
2706
- params[getSegmentParamName(routeSegments[routeIndex])] = [];
2707
- return params;
2708
- }
2709
- return null;
2710
- }
2711
- __name(matchPathSegments, "matchPathSegments");
2712
- function splitPath(value) {
2713
- return value.split("/").filter(Boolean);
2714
- }
2715
- __name(splitPath, "splitPath");
2716
- function isDynamicSegment(segment) {
2717
- return segment.startsWith("[") && segment.endsWith("]");
2718
- }
2719
- __name(isDynamicSegment, "isDynamicSegment");
2720
- function isCatchAllSegment(segment) {
2721
- return segment.startsWith("[...") && segment.endsWith("]");
2722
- }
2723
- __name(isCatchAllSegment, "isCatchAllSegment");
2724
- function getSegmentParamName(segment) {
2725
- if (isCatchAllSegment(segment)) {
2726
- return segment.slice(4, -1);
2727
- }
2728
- return segment.slice(1, -1);
2729
- }
2730
- __name(getSegmentParamName, "getSegmentParamName");
2731
- function normalizeMatcher(matcher) {
2732
- if (!matcher) {
2733
- return "/(.*)";
2734
- }
2735
- return typeof matcher === "string" ? matcher : matcher.join(", ");
2736
- }
2737
- __name(normalizeMatcher, "normalizeMatcher");
15
+
16
+ var _chunkS3JO3N4Hcjs = require('./chunk-S3JO3N4H.cjs');
2738
17
 
2739
18
  // src/agent-runtime.ts
19
+ var _child_process = require('child_process');
20
+ var _promises = require('fs/promises');
21
+ var _module = require('module');
22
+ var _net = require('net');
23
+ var _path = require('path');
2740
24
  var AGENT_RUNTIME_METHODS = [
2741
25
  "GET",
2742
26
  "HEAD",
@@ -2775,7 +59,7 @@ function createAgentRuntimeIntegration(options) {
2775
59
  provider,
2776
60
  routePrefix,
2777
61
  routePrefixes,
2778
- getOrigin: /* @__PURE__ */ __name(() => state.origin ?? resolveConfiguredOrigin(options.origin, originEnv), "getOrigin")
62
+ getOrigin: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => _nullishCoalesce(state.origin, () => ( resolveConfiguredOrigin(options.origin, originEnv))), "getOrigin")
2779
63
  };
2780
64
  const runtimePlugin = {
2781
65
  name: `farm:agent-runtime:${provider}`,
@@ -2808,7 +92,7 @@ function createAgentRuntimeIntegration(options) {
2808
92
  });
2809
93
  }
2810
94
  };
2811
- return defineIntegration({
95
+ return _chunkZ5HIWVDPcjs.defineIntegration.call(void 0, {
2812
96
  category: "agent",
2813
97
  type: provider,
2814
98
  serverRuntime: options.serverRuntime,
@@ -2826,7 +110,7 @@ function createAgentRuntimeIntegration(options) {
2826
110
  origin: state.origin
2827
111
  });
2828
112
  await context.cleanup(async () => {
2829
- await state.managed?.stop();
113
+ await _optionalChain([state, 'access', _ => _.managed, 'optionalAccess', _2 => _2.stop, 'call', _3 => _3()]);
2830
114
  state.managed = void 0;
2831
115
  state.origin = void 0;
2832
116
  });
@@ -2852,7 +136,7 @@ function createAgentRuntimeIntegration(options) {
2852
136
  plugins: [runtimePlugin, ...options.plugins || []]
2853
137
  });
2854
138
  }
2855
- __name(createAgentRuntimeIntegration, "createAgentRuntimeIntegration");
139
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createAgentRuntimeIntegration, "createAgentRuntimeIntegration");
2856
140
  function applyAgentRuntimeViteProxy(config, input) {
2857
141
  const origin = normalizeAgentOrigin(input.origin);
2858
142
  const routePrefix = normalizeAgentRoutePrefix(input.routePrefix);
@@ -2879,7 +163,7 @@ function applyAgentRuntimeViteProxy(config, input) {
2879
163
  }
2880
164
  };
2881
165
  }
2882
- __name(applyAgentRuntimeViteProxy, "applyAgentRuntimeViteProxy");
166
+ _chunkS3JO3N4Hcjs.__name.call(void 0, applyAgentRuntimeViteProxy, "applyAgentRuntimeViteProxy");
2883
167
  async function proxyAgentRuntimeRequest(request, origin, options = {}) {
2884
168
  const upstreamOrigin = normalizeAgentOrigin(origin);
2885
169
  const incomingUrl = new URL(request.url);
@@ -2900,7 +184,7 @@ async function proxyAgentRuntimeRequest(request, origin, options = {}) {
2900
184
  const upstream = await (options.fetch || globalThis.fetch)(targetUrl, init);
2901
185
  const responseHeaders = new Headers(upstream.headers);
2902
186
  removeHopByHopHeaders(responseHeaders);
2903
- const contentCodings = responseHeaders.get("content-encoding")?.toLowerCase().split(",").map((coding) => coding.trim()).filter(Boolean);
187
+ const contentCodings = _optionalChain([responseHeaders, 'access', _4 => _4.get, 'call', _5 => _5("content-encoding"), 'optionalAccess', _6 => _6.toLowerCase, 'call', _7 => _7(), 'access', _8 => _8.split, 'call', _9 => _9(","), 'access', _10 => _10.map, 'call', _11 => _11((coding) => coding.trim()), 'access', _12 => _12.filter, 'call', _13 => _13(Boolean)]);
2904
188
  let responseBody = upstream.body;
2905
189
  if (upstream.body && contentCodings && contentCodings.length) {
2906
190
  if (contentCodings.every((coding) => DECODED_CONTENT_CODINGS.includes(coding))) {
@@ -2935,15 +219,15 @@ async function proxyAgentRuntimeRequest(request, origin, options = {}) {
2935
219
  );
2936
220
  }
2937
221
  }
2938
- __name(proxyAgentRuntimeRequest, "proxyAgentRuntimeRequest");
222
+ _chunkS3JO3N4Hcjs.__name.call(void 0, proxyAgentRuntimeRequest, "proxyAgentRuntimeRequest");
2939
223
  async function startManagedAgentRuntime(options) {
2940
- const timeoutMs = options.timeoutMs ?? 3e4;
2941
- const stopTimeoutMs = options.stopTimeoutMs ?? 2e3;
224
+ const timeoutMs = _nullishCoalesce(options.timeoutMs, () => ( 3e4));
225
+ const stopTimeoutMs = _nullishCoalesce(options.stopTimeoutMs, () => ( 2e3));
2942
226
  const fixedOrigin = options.origin ? normalizeAgentOrigin(options.origin) : void 0;
2943
227
  let output = "";
2944
228
  let settled = false;
2945
229
  let checkingReadiness = false;
2946
- const child = (0, import_node_child_process.spawn)(options.command, [...options.args || []], {
230
+ const child = _child_process.spawn.call(void 0, options.command, [...options.args || []], {
2947
231
  cwd: options.cwd,
2948
232
  env: {
2949
233
  ...process.env,
@@ -2953,14 +237,14 @@ async function startManagedAgentRuntime(options) {
2953
237
  });
2954
238
  const origin = await new Promise((resolveOrigin, reject) => {
2955
239
  let timer;
2956
- const finish = /* @__PURE__ */ __name(() => {
240
+ const finish = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => {
2957
241
  if (settled) return;
2958
242
  settled = true;
2959
243
  clearTimeout(timer);
2960
244
  child.off("error", onError);
2961
245
  child.off("exit", onExit);
2962
246
  }, "finish");
2963
- const succeed = /* @__PURE__ */ __name(async (candidate) => {
247
+ const succeed = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (candidate) => {
2964
248
  if (settled || checkingReadiness) return;
2965
249
  checkingReadiness = true;
2966
250
  try {
@@ -2979,11 +263,11 @@ async function startManagedAgentRuntime(options) {
2979
263
  terminateChild(child);
2980
264
  reject(new Error(`${options.label} did not become ready within ${timeoutMs}ms.`));
2981
265
  }, timeoutMs);
2982
- const onError = /* @__PURE__ */ __name((error) => {
266
+ const onError = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (error) => {
2983
267
  finish();
2984
268
  reject(error);
2985
269
  }, "onError");
2986
- const onExit = /* @__PURE__ */ __name((code, signal) => {
270
+ const onExit = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (code, signal) => {
2987
271
  finish();
2988
272
  reject(
2989
273
  new Error(
@@ -2991,7 +275,7 @@ async function startManagedAgentRuntime(options) {
2991
275
  )
2992
276
  );
2993
277
  }, "onExit");
2994
- const onData = /* @__PURE__ */ __name((chunk, stream) => {
278
+ const onData = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (chunk, stream) => {
2995
279
  const text = chunk.toString("utf8");
2996
280
  output = `${output}${text}`.slice(-16384);
2997
281
  emitProcessOutput(text, stream, options.onOutput);
@@ -3004,8 +288,8 @@ async function startManagedAgentRuntime(options) {
3004
288
  }, "onData");
3005
289
  child.once("error", onError);
3006
290
  child.once("exit", onExit);
3007
- child.stdout?.on("data", (chunk) => onData(chunk, "stdout"));
3008
- child.stderr?.on("data", (chunk) => onData(chunk, "stderr"));
291
+ _optionalChain([child, 'access', _14 => _14.stdout, 'optionalAccess', _15 => _15.on, 'call', _16 => _16("data", (chunk) => onData(chunk, "stdout"))]);
292
+ _optionalChain([child, 'access', _17 => _17.stderr, 'optionalAccess', _18 => _18.on, 'call', _19 => _19("data", (chunk) => onData(chunk, "stderr"))]);
3009
293
  if (fixedOrigin) {
3010
294
  void succeed(fixedOrigin);
3011
295
  }
@@ -3026,10 +310,10 @@ async function startManagedAgentRuntime(options) {
3026
310
  }
3027
311
  };
3028
312
  }
3029
- __name(startManagedAgentRuntime, "startManagedAgentRuntime");
313
+ _chunkS3JO3N4Hcjs.__name.call(void 0, startManagedAgentRuntime, "startManagedAgentRuntime");
3030
314
  async function findAvailableAgentRuntimePort(host = "127.0.0.1") {
3031
315
  return await new Promise((resolvePort, reject) => {
3032
- const server = (0, import_node_net.createServer)();
316
+ const server = _net.createServer.call(void 0, );
3033
317
  server.unref();
3034
318
  server.once("error", reject);
3035
319
  server.listen(0, host, () => {
@@ -3047,33 +331,33 @@ async function findAvailableAgentRuntimePort(host = "127.0.0.1") {
3047
331
  });
3048
332
  });
3049
333
  }
3050
- __name(findAvailableAgentRuntimePort, "findAvailableAgentRuntimePort");
334
+ _chunkS3JO3N4Hcjs.__name.call(void 0, findAvailableAgentRuntimePort, "findAvailableAgentRuntimePort");
3051
335
  async function resolveProjectPackageBin(projectRoot, packageName, binName) {
3052
- const root = (0, import_node_path.resolve)(projectRoot);
3053
- const projectRequire = (0, import_node_module.createRequire)((0, import_node_path.join)(root, "package.json"));
336
+ const root = _path.resolve.call(void 0, projectRoot);
337
+ const projectRequire = _module.createRequire.call(void 0, _path.join.call(void 0, root, "package.json"));
3054
338
  let packageJsonPath;
3055
339
  try {
3056
340
  packageJsonPath = projectRequire.resolve(`${packageName}/package.json`);
3057
- } catch {
341
+ } catch (e) {
3058
342
  throw new Error(
3059
343
  `${packageName} is required by this agent integration. Install it in ${root} and try again.`
3060
344
  );
3061
345
  }
3062
- const packageJson = JSON.parse(await (0, import_promises.readFile)(packageJsonPath, "utf8"));
3063
- const bin = typeof packageJson.bin === "string" ? packageJson.bin : packageJson.bin?.[binName || packageName.split("/").at(-1) || packageName];
346
+ const packageJson = JSON.parse(await _promises.readFile.call(void 0, packageJsonPath, "utf8"));
347
+ const bin = typeof packageJson.bin === "string" ? packageJson.bin : _optionalChain([packageJson, 'access', _20 => _20.bin, 'optionalAccess', _21 => _21[binName || packageName.split("/").at(-1) || packageName]]);
3064
348
  if (!bin) {
3065
349
  throw new Error(
3066
350
  `${packageName} does not expose the expected ${binName || packageName} binary.`
3067
351
  );
3068
352
  }
3069
- const packageRoot = (0, import_node_path.dirname)(packageJsonPath);
3070
- const binaryPath = (0, import_node_path.resolve)(packageRoot, bin);
3071
- if ((0, import_node_path.relative)(packageRoot, binaryPath).startsWith("..") || (0, import_node_path.isAbsolute)((0, import_node_path.relative)(packageRoot, binaryPath))) {
353
+ const packageRoot = _path.dirname.call(void 0, packageJsonPath);
354
+ const binaryPath = _path.resolve.call(void 0, packageRoot, bin);
355
+ if (_path.relative.call(void 0, packageRoot, binaryPath).startsWith("..") || _path.isAbsolute.call(void 0, _path.relative.call(void 0, packageRoot, binaryPath))) {
3072
356
  throw new Error(`${packageName} exposes a binary outside its package root.`);
3073
357
  }
3074
358
  return binaryPath;
3075
359
  }
3076
- __name(resolveProjectPackageBin, "resolveProjectPackageBin");
360
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveProjectPackageBin, "resolveProjectPackageBin");
3077
361
  function normalizeAgentOrigin(value) {
3078
362
  const input = value.trim();
3079
363
  if (!input) {
@@ -3091,7 +375,7 @@ function normalizeAgentOrigin(value) {
3091
375
  }
3092
376
  return url.origin;
3093
377
  }
3094
- __name(normalizeAgentOrigin, "normalizeAgentOrigin");
378
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeAgentOrigin, "normalizeAgentOrigin");
3095
379
  function normalizeAgentRoutePrefix(value) {
3096
380
  const normalized = `/${value.trim()}`.replace(/\/{2,}/g, "/");
3097
381
  if (normalized === "/") {
@@ -3099,7 +383,7 @@ function normalizeAgentRoutePrefix(value) {
3099
383
  }
3100
384
  return normalized.replace(/\/$/, "");
3101
385
  }
3102
- __name(normalizeAgentRoutePrefix, "normalizeAgentRoutePrefix");
386
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeAgentRoutePrefix, "normalizeAgentRoutePrefix");
3103
387
  function normalizeProviderName(value) {
3104
388
  const provider = value.trim();
3105
389
  if (!provider || !/^[a-z0-9][a-z0-9._-]*$/i.test(provider)) {
@@ -3107,25 +391,25 @@ function normalizeProviderName(value) {
3107
391
  }
3108
392
  return provider;
3109
393
  }
3110
- __name(normalizeProviderName, "normalizeProviderName");
394
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeProviderName, "normalizeProviderName");
3111
395
  function normalizeOriginEnv(value) {
3112
396
  if (!value) return [];
3113
397
  return (Array.isArray(value) ? value : [value]).map((entry) => entry.trim()).filter(Boolean);
3114
398
  }
3115
- __name(normalizeOriginEnv, "normalizeOriginEnv");
399
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeOriginEnv, "normalizeOriginEnv");
3116
400
  function resolveConfiguredOrigin(configuredOrigin, envNames) {
3117
401
  if (configuredOrigin) {
3118
402
  return normalizeAgentOrigin(configuredOrigin);
3119
403
  }
3120
404
  for (const envName of envNames) {
3121
405
  const value = process.env[envName];
3122
- if (value?.trim()) {
406
+ if (_optionalChain([value, 'optionalAccess', _22 => _22.trim, 'call', _23 => _23()])) {
3123
407
  return normalizeAgentOrigin(value);
3124
408
  }
3125
409
  }
3126
410
  return void 0;
3127
411
  }
3128
- __name(resolveConfiguredOrigin, "resolveConfiguredOrigin");
412
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveConfiguredOrigin, "resolveConfiguredOrigin");
3129
413
  function createProxyRequestHeaders(input, incomingUrl) {
3130
414
  const headers = new Headers(input);
3131
415
  removeHopByHopHeaders(headers);
@@ -3136,9 +420,9 @@ function createProxyRequestHeaders(input, incomingUrl) {
3136
420
  headers.set("x-forwarded-proto", incomingUrl.protocol.replace(":", ""));
3137
421
  return headers;
3138
422
  }
3139
- __name(createProxyRequestHeaders, "createProxyRequestHeaders");
423
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createProxyRequestHeaders, "createProxyRequestHeaders");
3140
424
  function removeHopByHopHeaders(headers) {
3141
- const connectionOptions = headers.get("connection")?.split(",") ?? [];
425
+ const connectionOptions = _nullishCoalesce(_optionalChain([headers, 'access', _24 => _24.get, 'call', _25 => _25("connection"), 'optionalAccess', _26 => _26.split, 'call', _27 => _27(",")]), () => ( []));
3142
426
  for (const option of connectionOptions) {
3143
427
  const header = option.trim();
3144
428
  if (/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(header)) {
@@ -3149,7 +433,7 @@ function removeHopByHopHeaders(headers) {
3149
433
  headers.delete(header);
3150
434
  }
3151
435
  }
3152
- __name(removeHopByHopHeaders, "removeHopByHopHeaders");
436
+ _chunkS3JO3N4Hcjs.__name.call(void 0, removeHopByHopHeaders, "removeHopByHopHeaders");
3153
437
  async function detectZstdDecoding(body) {
3154
438
  const reader = body.getReader();
3155
439
  const consumed = [];
@@ -3162,7 +446,7 @@ async function detectZstdDecoding(body) {
3162
446
  consumed.push(value);
3163
447
  total += value.byteLength;
3164
448
  }
3165
- } catch {
449
+ } catch (e2) {
3166
450
  }
3167
451
  const lookahead = concatUint8(consumed);
3168
452
  const decoded = !startsWithZstdFrameMagic(lookahead);
@@ -3177,7 +461,7 @@ async function detectZstdDecoding(body) {
3177
461
  controller.close();
3178
462
  return;
3179
463
  }
3180
- controller.enqueue(value ?? new Uint8Array());
464
+ controller.enqueue(_nullishCoalesce(value, () => ( new Uint8Array())));
3181
465
  } catch (error) {
3182
466
  controller.error(error);
3183
467
  }
@@ -3189,7 +473,7 @@ async function detectZstdDecoding(body) {
3189
473
  });
3190
474
  return { decoded, body: rebuilt };
3191
475
  }
3192
- __name(detectZstdDecoding, "detectZstdDecoding");
476
+ _chunkS3JO3N4Hcjs.__name.call(void 0, detectZstdDecoding, "detectZstdDecoding");
3193
477
  function concatUint8(chunks) {
3194
478
  if (chunks.length === 0) return new Uint8Array(0);
3195
479
  if (chunks.length === 1) return chunks[0];
@@ -3202,7 +486,7 @@ function concatUint8(chunks) {
3202
486
  }
3203
487
  return merged;
3204
488
  }
3205
- __name(concatUint8, "concatUint8");
489
+ _chunkS3JO3N4Hcjs.__name.call(void 0, concatUint8, "concatUint8");
3206
490
  function startsWithZstdFrameMagic(buffer) {
3207
491
  if (buffer.byteLength < ZSTD_FRAME_MAGIC.byteLength) return false;
3208
492
  let isStandardFrame = true;
@@ -3215,7 +499,7 @@ function startsWithZstdFrameMagic(buffer) {
3215
499
  if (isStandardFrame) return true;
3216
500
  return buffer[0] >= 80 && buffer[0] <= 95 && buffer[1] === 42 && buffer[2] === 77 && buffer[3] === 24;
3217
501
  }
3218
- __name(startsWithZstdFrameMagic, "startsWithZstdFrameMagic");
502
+ _chunkS3JO3N4Hcjs.__name.call(void 0, startsWithZstdFrameMagic, "startsWithZstdFrameMagic");
3219
503
  function rewriteProxyLocation(headers, upstreamOrigin, incomingOrigin) {
3220
504
  const location = headers.get("location");
3221
505
  if (!location) return;
@@ -3224,14 +508,14 @@ function rewriteProxyLocation(headers, upstreamOrigin, incomingOrigin) {
3224
508
  if (url.origin === upstreamOrigin) {
3225
509
  headers.set("location", `${incomingOrigin}${url.pathname}${url.search}${url.hash}`);
3226
510
  }
3227
- } catch {
511
+ } catch (e3) {
3228
512
  }
3229
513
  }
3230
- __name(rewriteProxyLocation, "rewriteProxyLocation");
514
+ _chunkS3JO3N4Hcjs.__name.call(void 0, rewriteProxyLocation, "rewriteProxyLocation");
3231
515
  function isAbortError(error) {
3232
516
  return error instanceof Error && error.name === "AbortError";
3233
517
  }
3234
- __name(isAbortError, "isAbortError");
518
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isAbortError, "isAbortError");
3235
519
  async function waitForAgentRuntime(origin, healthPath, timeoutMs, child) {
3236
520
  const deadline = Date.now() + timeoutMs;
3237
521
  const healthUrl = new URL(healthPath || "/", origin);
@@ -3247,7 +531,7 @@ async function waitForAgentRuntime(origin, healthPath, timeoutMs, child) {
3247
531
  redirect: "manual"
3248
532
  });
3249
533
  return;
3250
- } catch {
534
+ } catch (e4) {
3251
535
  await delay(100);
3252
536
  } finally {
3253
537
  clearTimeout(timer);
@@ -3255,7 +539,7 @@ async function waitForAgentRuntime(origin, healthPath, timeoutMs, child) {
3255
539
  }
3256
540
  throw new Error(`Agent runtime at ${origin} did not answer before the startup timeout.`);
3257
541
  }
3258
- __name(waitForAgentRuntime, "waitForAgentRuntime");
542
+ _chunkS3JO3N4Hcjs.__name.call(void 0, waitForAgentRuntime, "waitForAgentRuntime");
3259
543
  function emitProcessOutput(text, stream, onOutput) {
3260
544
  if (!onOutput) return;
3261
545
  for (const line of text.split(/\r?\n/)) {
@@ -3263,13 +547,13 @@ function emitProcessOutput(text, stream, onOutput) {
3263
547
  if (value) onOutput(value, stream);
3264
548
  }
3265
549
  }
3266
- __name(emitProcessOutput, "emitProcessOutput");
550
+ _chunkS3JO3N4Hcjs.__name.call(void 0, emitProcessOutput, "emitProcessOutput");
3267
551
  function terminateChild(child) {
3268
552
  if (child.exitCode === null && child.signalCode === null) {
3269
553
  child.kill("SIGTERM");
3270
554
  }
3271
555
  }
3272
- __name(terminateChild, "terminateChild");
556
+ _chunkS3JO3N4Hcjs.__name.call(void 0, terminateChild, "terminateChild");
3273
557
  async function waitForChildExit(child, timeoutMs) {
3274
558
  if (child.exitCode !== null || child.signalCode !== null) return true;
3275
559
  return await new Promise((resolveExit) => {
@@ -3277,26 +561,25 @@ async function waitForChildExit(child, timeoutMs) {
3277
561
  child.off("exit", onExit);
3278
562
  resolveExit(false);
3279
563
  }, timeoutMs);
3280
- const onExit = /* @__PURE__ */ __name(() => {
564
+ const onExit = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => {
3281
565
  clearTimeout(timer);
3282
566
  resolveExit(true);
3283
567
  }, "onExit");
3284
568
  child.once("exit", onExit);
3285
569
  });
3286
570
  }
3287
- __name(waitForChildExit, "waitForChildExit");
571
+ _chunkS3JO3N4Hcjs.__name.call(void 0, waitForChildExit, "waitForChildExit");
3288
572
  function delay(ms) {
3289
573
  return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
3290
574
  }
3291
- __name(delay, "delay");
3292
- // Annotate the CommonJS export names for ESM import in node:
3293
- 0 && (module.exports = {
3294
- applyAgentRuntimeViteProxy,
3295
- createAgentRuntimeIntegration,
3296
- findAvailableAgentRuntimePort,
3297
- normalizeAgentOrigin,
3298
- normalizeAgentRoutePrefix,
3299
- proxyAgentRuntimeRequest,
3300
- resolveProjectPackageBin,
3301
- startManagedAgentRuntime
3302
- });
575
+ _chunkS3JO3N4Hcjs.__name.call(void 0, delay, "delay");
576
+
577
+
578
+
579
+
580
+
581
+
582
+
583
+
584
+
585
+ exports.applyAgentRuntimeViteProxy = applyAgentRuntimeViteProxy; exports.createAgentRuntimeIntegration = createAgentRuntimeIntegration; exports.findAvailableAgentRuntimePort = findAvailableAgentRuntimePort; exports.normalizeAgentOrigin = normalizeAgentOrigin; exports.normalizeAgentRoutePrefix = normalizeAgentRoutePrefix; exports.proxyAgentRuntimeRequest = proxyAgentRuntimeRequest; exports.resolveProjectPackageBin = resolveProjectPackageBin; exports.startManagedAgentRuntime = startManagedAgentRuntime;