@farm.js/core 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/dist/after.cjs +12 -225
  2. package/dist/agent-runtime.cjs +83 -2800
  3. package/dist/api/client.cjs +17 -4060
  4. package/dist/api/route-manager.cjs +34 -4354
  5. package/dist/api/runtime.cjs +29 -2696
  6. package/dist/api.cjs +88 -8434
  7. package/dist/app-markdown.cjs +39 -280
  8. package/dist/cache.cjs +38 -1560
  9. package/dist/chunk-22GUSVNJ.cjs +351 -0
  10. package/dist/chunk-2CQ74SP6.cjs +13 -0
  11. package/dist/chunk-2SJ4RQ6P.cjs +57 -0
  12. package/dist/chunk-3376ZTRC.cjs +1 -0
  13. package/dist/{chunk-YD4J4XCI.mjs → chunk-3XG26Z3J.mjs} +1 -1
  14. package/dist/chunk-4PNUXIVU.cjs +472 -0
  15. package/dist/chunk-4PPEPOZZ.cjs +21 -0
  16. package/dist/chunk-4ZFL5GFN.cjs +520 -0
  17. package/dist/chunk-5OVTOKGH.cjs +65 -0
  18. package/dist/chunk-5QIKR7RR.cjs +224 -0
  19. package/dist/chunk-5ZSWG4UX.cjs +127 -0
  20. package/dist/chunk-62YJ2IEB.cjs +238 -0
  21. package/dist/chunk-6EODJYCX.cjs +183 -0
  22. package/dist/chunk-6EXBPJ24.cjs +434 -0
  23. package/dist/chunk-6QQDAAAZ.cjs +38 -0
  24. package/dist/chunk-6V4TDWEC.cjs +455 -0
  25. package/dist/chunk-72ADZ6GQ.cjs +19 -0
  26. package/dist/chunk-75BRBIFP.cjs +172 -0
  27. package/dist/chunk-7W3CPVXS.cjs +24 -0
  28. package/dist/chunk-A6WIQH5Z.cjs +31 -0
  29. package/dist/chunk-AFOD3LYZ.cjs +377 -0
  30. package/dist/chunk-AMDMVWMI.cjs +39 -0
  31. package/dist/chunk-AORPIPNB.cjs +552 -0
  32. package/dist/chunk-ARJWXNQL.cjs +256 -0
  33. package/dist/chunk-AWRISO2H.cjs +2199 -0
  34. package/dist/chunk-AYJR42WX.cjs +711 -0
  35. package/dist/chunk-B4CH33IG.cjs +644 -0
  36. package/dist/chunk-BIDYX3SL.cjs +91 -0
  37. package/dist/chunk-BSTRERPP.cjs +40 -0
  38. package/dist/chunk-BYODCJD6.cjs +663 -0
  39. package/dist/chunk-C3VRMB6H.cjs +85 -0
  40. package/dist/chunk-C5GUTBZK.cjs +173 -0
  41. package/dist/chunk-CIAGU2X4.cjs +337 -0
  42. package/dist/chunk-CMGMGHUZ.cjs +27 -0
  43. package/dist/chunk-CXP5U3RW.cjs +54 -0
  44. package/dist/chunk-D2ULAULS.cjs +166 -0
  45. package/dist/chunk-D7JTOLFK.cjs +285 -0
  46. package/dist/chunk-DVM4FKZL.cjs +169 -0
  47. package/dist/chunk-DYEJQTDN.cjs +49 -0
  48. package/dist/chunk-E2BMSZ2W.cjs +151 -0
  49. package/dist/chunk-E3UK5IIB.cjs +593 -0
  50. package/dist/chunk-EM6SBQKM.cjs +470 -0
  51. package/dist/chunk-FJSWYIR7.cjs +482 -0
  52. package/dist/chunk-FK6GO24V.cjs +54 -0
  53. package/dist/chunk-FXUUWYAX.cjs +654 -0
  54. package/dist/chunk-G3HRIVEY.cjs +395 -0
  55. package/dist/chunk-G643DQCH.cjs +13 -0
  56. package/dist/chunk-G7HXGLEC.cjs +175 -0
  57. package/dist/chunk-GDSHDTJ4.cjs +152 -0
  58. package/dist/chunk-GNEO2XOF.cjs +2040 -0
  59. package/dist/{chunk-56DAX2BE.mjs → chunk-GYKJCFTS.mjs} +1 -1
  60. package/dist/chunk-H6G5INWM.cjs +1094 -0
  61. package/dist/chunk-HBTUGXHS.cjs +180 -0
  62. package/dist/chunk-HREOKQWT.cjs +45 -0
  63. package/dist/chunk-I4J452B7.cjs +435 -0
  64. package/dist/chunk-I57LW5VZ.cjs +94 -0
  65. package/dist/chunk-I7PUUDGY.cjs +389 -0
  66. package/dist/chunk-IAMRBF3Z.cjs +86 -0
  67. package/dist/chunk-IKNRN4VS.cjs +14214 -0
  68. package/dist/chunk-IQXFRNY2.cjs +169 -0
  69. package/dist/chunk-IXTFU4PL.cjs +2355 -0
  70. package/dist/chunk-J2OP5GG3.cjs +725 -0
  71. package/dist/chunk-J3LOGE4T.cjs +42 -0
  72. package/dist/chunk-J7FSKED3.cjs +93 -0
  73. package/dist/chunk-JDNHKPTD.cjs +22 -0
  74. package/dist/chunk-JSROZYYO.cjs +164 -0
  75. package/dist/chunk-K6FNHVDR.cjs +696 -0
  76. package/dist/chunk-KGZIORNL.cjs +43 -0
  77. package/dist/{chunk-MVIWBEJF.mjs → chunk-KPNVGRBL.mjs} +1 -1
  78. package/dist/chunk-KR6CKSXT.cjs +15 -0
  79. package/dist/chunk-KROWKCUH.cjs +185 -0
  80. package/dist/chunk-KVFPGF2M.cjs +46 -0
  81. package/dist/chunk-LCCBO7PJ.cjs +46 -0
  82. package/dist/chunk-LIUGYUX3.cjs +22 -0
  83. package/dist/chunk-LTNGXMQ6.cjs +55 -0
  84. package/dist/chunk-M2L4MYDQ.cjs +14 -0
  85. package/dist/chunk-MCJLA63J.cjs +1 -0
  86. package/dist/chunk-MKB2EGIR.cjs +148 -0
  87. package/dist/chunk-MQ3H6LT5.cjs +202 -0
  88. package/dist/chunk-MT763TDW.cjs +43 -0
  89. package/dist/chunk-MWSK6C4J.cjs +18 -0
  90. package/dist/chunk-MWWVKDW3.cjs +169 -0
  91. package/dist/chunk-NO3WWW3N.cjs +192 -0
  92. package/dist/chunk-NV3A5DXM.cjs +862 -0
  93. package/dist/chunk-NWOD6NIT.cjs +9 -0
  94. package/dist/chunk-NZKJGRB3.cjs +230 -0
  95. package/dist/chunk-OAVTUMJP.cjs +1496 -0
  96. package/dist/chunk-OHY2ZWUG.cjs +25 -0
  97. package/dist/chunk-OI6CMLWX.cjs +47 -0
  98. package/dist/chunk-OIEOCXKG.cjs +453 -0
  99. package/dist/chunk-OWOUTKIJ.cjs +558 -0
  100. package/dist/chunk-OX6O6WVA.cjs +74 -0
  101. package/dist/chunk-OXSIH4D6.cjs +476 -0
  102. package/dist/chunk-OYEUREB6.cjs +35 -0
  103. package/dist/chunk-PCOTGFSM.cjs +139 -0
  104. package/dist/chunk-PZYCPSCC.cjs +35 -0
  105. package/dist/chunk-QBK2AA4U.cjs +445 -0
  106. package/dist/chunk-QBPXNZGV.cjs +487 -0
  107. package/dist/chunk-QNPEUFHQ.cjs +27 -0
  108. package/dist/chunk-QZRVZSPN.cjs +236 -0
  109. package/dist/chunk-R5A5KNVX.cjs +20 -0
  110. package/dist/chunk-R5JIFR6B.cjs +42 -0
  111. package/dist/chunk-R6AIILII.cjs +193 -0
  112. package/dist/chunk-RG3ZOTG5.cjs +34 -0
  113. package/dist/chunk-ROUTX2E5.cjs +390 -0
  114. package/dist/chunk-RTHIVJ2G.cjs +54 -0
  115. package/dist/chunk-S3A45T7F.cjs +166 -0
  116. package/dist/chunk-S3JO3N4H.cjs +17 -0
  117. package/dist/chunk-SK35NQKK.cjs +27 -0
  118. package/dist/chunk-SU7MH53P.cjs +180 -0
  119. package/dist/chunk-SVRTJOUF.cjs +113 -0
  120. package/dist/chunk-SWN467MP.cjs +18 -0
  121. package/dist/chunk-SYQ3MOWW.cjs +73 -0
  122. package/dist/chunk-T5CERMEH.cjs +417 -0
  123. package/dist/chunk-TFAXUHWX.cjs +206 -0
  124. package/dist/chunk-TIWHTW3Q.cjs +24 -0
  125. package/dist/chunk-TKJZFIML.cjs +20 -0
  126. package/dist/chunk-TKNSDBBN.cjs +193 -0
  127. package/dist/chunk-TWGMSEHX.cjs +525 -0
  128. package/dist/chunk-TYQUSXUG.cjs +1357 -0
  129. package/dist/chunk-U4KT7QP3.cjs +23 -0
  130. package/dist/chunk-UJ2C4ICS.cjs +277 -0
  131. package/dist/chunk-UN5GHC5V.cjs +10244 -0
  132. package/dist/chunk-UQZ4AYTH.cjs +168 -0
  133. package/dist/chunk-US2QVW3E.cjs +36 -0
  134. package/dist/chunk-VB6UCX3V.cjs +421 -0
  135. package/dist/chunk-VEKFLAQM.cjs +300 -0
  136. package/dist/chunk-VQDBNVOO.cjs +14 -0
  137. package/dist/chunk-W4E7WMXE.cjs +71 -0
  138. package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
  139. package/dist/chunk-WMAPPDMM.cjs +28 -0
  140. package/dist/chunk-WMOGFOUJ.cjs +223 -0
  141. package/dist/chunk-WPYFSQKK.cjs +37 -0
  142. package/dist/chunk-WZMNW2IW.cjs +1415 -0
  143. package/dist/chunk-XGC343EY.cjs +443 -0
  144. package/dist/chunk-XSKZORAS.cjs +727 -0
  145. package/dist/chunk-XWAWFQFS.cjs +82 -0
  146. package/dist/chunk-Y4YMF2NQ.cjs +460 -0
  147. package/dist/chunk-Y4YWHNKU.cjs +250 -0
  148. package/dist/chunk-Y53ZSFN6.cjs +504 -0
  149. package/dist/chunk-YA6LLTIJ.cjs +411 -0
  150. package/dist/chunk-YFPGHF5F.cjs +202 -0
  151. package/dist/chunk-YJRZR7VU.cjs +28 -0
  152. package/dist/chunk-YTAABQEV.cjs +1 -0
  153. package/dist/chunk-YX3DBN4M.cjs +18 -0
  154. package/dist/chunk-YZTASLPQ.cjs +64 -0
  155. package/dist/chunk-Z5HIWVDP.cjs +2173 -0
  156. package/dist/chunk-ZEG3OPIB.cjs +93 -0
  157. package/dist/chunk-ZMN3H73H.cjs +155 -0
  158. package/dist/client/lifecycle.cjs +6 -35
  159. package/dist/client-plugins.cjs +7 -448
  160. package/dist/client.cjs +171 -9808
  161. package/dist/config.cjs +8 -36
  162. package/dist/cron.cjs +24 -491
  163. package/dist/deferred.cjs +26 -475
  164. package/dist/deployment.cjs +39 -210
  165. package/dist/devtools-OUIPHVV6.cjs +388 -0
  166. package/dist/devtools-client-4WAPJY5L.cjs +254 -0
  167. package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
  168. package/dist/docs.cjs +46 -5657
  169. package/dist/env-types.cjs +5 -226
  170. package/dist/env.cjs +21 -338
  171. package/dist/environment/vite.cjs +8 -372
  172. package/dist/environment.cjs +12 -94
  173. package/dist/font.cjs +13 -63
  174. package/dist/headers.cjs +7 -123
  175. package/dist/i18n/client.cjs +55 -294
  176. package/dist/i18n/index.cjs +22 -209
  177. package/dist/i18n/server.cjs +22 -745
  178. package/dist/image/server.cjs +13 -729
  179. package/dist/image/sharp.cjs +33 -171
  180. package/dist/image.cjs +41 -85
  181. package/dist/index.cjs +1151 -68080
  182. package/dist/index.mjs +3 -3
  183. package/dist/instrumentation.cjs +12 -138
  184. package/dist/integration-orm-55F7CII5.cjs +13 -0
  185. package/dist/integrations.cjs +55 -4090
  186. package/dist/internal/app-markdown-runtime.cjs +27 -224
  187. package/dist/internal/build-runtime.cjs +120 -52259
  188. package/dist/internal/build-runtime.mjs +3 -3
  189. package/dist/internal/cli-runtime.cjs +67 -13811
  190. package/dist/internal/client-error-overlay.cjs +80 -733
  191. package/dist/internal/client-error-overlay.mjs +1 -1
  192. package/dist/internal/client-runtime.cjs +81 -913
  193. package/dist/internal/compression-runtime.cjs +8 -214
  194. package/dist/internal/config-runtime.cjs +42 -6547
  195. package/dist/internal/docs-precompiled-runtime.cjs +26 -46
  196. package/dist/internal/infra-analytics-runtime.cjs +10 -536
  197. package/dist/internal/isolated-boundary.cjs +14 -414
  198. package/dist/internal/metadata-image-runtime.cjs +7 -285
  199. package/dist/internal/product-telemetry-runtime.cjs +42 -97
  200. package/dist/internal/product-telemetry-runtime.mjs +1 -1
  201. package/dist/internal/production-node-env.cjs +6 -63
  202. package/dist/internal/production-runtime.cjs +418 -7133
  203. package/dist/internal/request-cookies.cjs +6 -54
  204. package/dist/json-ld.cjs +24 -50
  205. package/dist/layers-E4WPJNY5.cjs +17 -0
  206. package/dist/manager-G4B2IPYE.cjs +14 -0
  207. package/dist/markdown.cjs +21 -547
  208. package/dist/middleware.cjs +36 -2995
  209. package/dist/navigation.cjs +22 -2588
  210. package/dist/nitro-4I2MYLY2.cjs +652 -0
  211. package/dist/observability.cjs +22 -614
  212. package/dist/og.cjs +5 -28
  213. package/dist/plugin.cjs +106 -37442
  214. package/dist/plugin.mjs +2 -2
  215. package/dist/query/client.cjs +113 -449
  216. package/dist/query/index.cjs +26 -288
  217. package/dist/query/parsers.cjs +23 -247
  218. package/dist/query/server.cjs +36 -298
  219. package/dist/renderer/react/client.cjs +9 -43
  220. package/dist/renderer/react/server.cjs +40 -103
  221. package/dist/renderer/react/vite.cjs +7 -29
  222. package/dist/renderer-client.cjs +126 -4295
  223. package/dist/renderer.cjs +31 -249
  224. package/dist/request.cjs +5 -68
  225. package/dist/router.cjs +11 -474
  226. package/dist/routes.cjs +42 -2461
  227. package/dist/schema-dev-notice-MXSZMVDG.cjs +56 -0
  228. package/dist/schema.cjs +6 -33
  229. package/dist/search-client-G3RICOFU.cjs +13 -0
  230. package/dist/server-action-security.cjs +25 -541
  231. package/dist/server-fn-client.cjs +6 -337
  232. package/dist/server-fn.cjs +32 -1841
  233. package/dist/server-plugins.cjs +15 -884
  234. package/dist/server-query-client.cjs +15 -1883
  235. package/dist/server-query.cjs +16 -1838
  236. package/dist/server.cjs +296 -44681
  237. package/dist/server.mjs +2 -2
  238. package/dist/storage.cjs +57 -576
  239. package/dist/testing.cjs +89 -3186
  240. package/dist/theme/client.cjs +13 -108
  241. package/dist/theme/index.cjs +6 -68
  242. package/dist/theme/runtime.cjs +13 -78
  243. package/dist/theme/server.cjs +10 -179
  244. package/dist/version.cjs +4 -32
  245. package/dist/version.mjs +1 -1
  246. package/dist/vite.cjs +119 -37773
  247. package/dist/vite.mjs +2 -2
  248. package/dist/workflows.cjs +19 -1040
  249. package/package.json +1 -1
@@ -0,0 +1,2355 @@
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
+
4
+
5
+ var _chunkLTNGXMQ6cjs = require('./chunk-LTNGXMQ6.cjs');
6
+
7
+
8
+
9
+
10
+ var _chunkI7PUUDGYcjs = require('./chunk-I7PUUDGY.cjs');
11
+
12
+
13
+ var _chunkJ7FSKED3cjs = require('./chunk-J7FSKED3.cjs');
14
+
15
+
16
+ var _chunk72ADZ6GQcjs = require('./chunk-72ADZ6GQ.cjs');
17
+
18
+
19
+
20
+ var _chunkG7HXGLECcjs = require('./chunk-G7HXGLEC.cjs');
21
+
22
+
23
+
24
+
25
+ var _chunkARJWXNQLcjs = require('./chunk-ARJWXNQL.cjs');
26
+
27
+
28
+
29
+ var _chunkS3A45T7Fcjs = require('./chunk-S3A45T7F.cjs');
30
+
31
+
32
+
33
+
34
+ var _chunkZEG3OPIBcjs = require('./chunk-ZEG3OPIB.cjs');
35
+
36
+
37
+ var _chunkU4KT7QP3cjs = require('./chunk-U4KT7QP3.cjs');
38
+
39
+
40
+ var _chunkS3JO3N4Hcjs = require('./chunk-S3JO3N4H.cjs');
41
+
42
+ // src/client-headers.ts
43
+ function resolveClientHeaders(source) {
44
+ const value = typeof source === "function" ? source() : source;
45
+ if (value && typeof value.then === "function") {
46
+ return Promise.resolve(value).then((headers) => new Headers(headers));
47
+ }
48
+ return new Headers(value);
49
+ }
50
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveClientHeaders, "resolveClientHeaders");
51
+
52
+ // src/integration-client.ts
53
+ var _IntegrationClientError = class _IntegrationClientError extends Error {
54
+ constructor(message, response, data) {
55
+ super(message);
56
+ this.name = "IntegrationClientError";
57
+ this.status = response.status;
58
+ this.response = response;
59
+ this.data = data;
60
+ }
61
+ };
62
+ _chunkS3JO3N4Hcjs.__name.call(void 0, _IntegrationClientError, "IntegrationClientError");
63
+ var IntegrationClientError = _IntegrationClientError;
64
+ var INTEGRATION_RUNTIME_REGISTRY_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRuntimeRegistry");
65
+ var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
66
+ var INTEGRATION_REQUEST_DISPATCHER_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRequestDispatcher");
67
+ function isOperation(value) {
68
+ return !!value && typeof value === "object" && value.kind === "farm-integration-api-operation";
69
+ }
70
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isOperation, "isOperation");
71
+ function tryResolveSourceAPI(source) {
72
+ if ("kind" in source && source.kind === "farm-integration") {
73
+ if (!source.api) {
74
+ return null;
75
+ }
76
+ return source.api;
77
+ }
78
+ return source;
79
+ }
80
+ _chunkS3JO3N4Hcjs.__name.call(void 0, tryResolveSourceAPI, "tryResolveSourceAPI");
81
+ function getIntegrationRuntimeRegistry() {
82
+ const globalState = globalThis;
83
+ return globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] || /* @__PURE__ */ new Map();
84
+ }
85
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getIntegrationRuntimeRegistry, "getIntegrationRuntimeRegistry");
86
+ function getRegisteredIntegrationRuntimeLocal(key) {
87
+ return getIntegrationRuntimeRegistry().get(key);
88
+ }
89
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getRegisteredIntegrationRuntimeLocal, "getRegisteredIntegrationRuntimeLocal");
90
+ function getRegisteredIntegrationsLocal() {
91
+ return Object.fromEntries(
92
+ Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [
93
+ key,
94
+ runtime.integration
95
+ ])
96
+ );
97
+ }
98
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getRegisteredIntegrationsLocal, "getRegisteredIntegrationsLocal");
99
+ function resolveCurrentRequestLocal() {
100
+ const globalState = globalThis;
101
+ return _optionalChain([globalState, 'access', _ => _[CURRENT_REQUEST_RESOLVER_KEY], 'optionalCall', _2 => _2()]);
102
+ }
103
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveCurrentRequestLocal, "resolveCurrentRequestLocal");
104
+ function resolveIntegrationRequestDispatcherLocal() {
105
+ const globalState = globalThis;
106
+ return globalState[INTEGRATION_REQUEST_DISPATCHER_KEY];
107
+ }
108
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveIntegrationRequestDispatcherLocal, "resolveIntegrationRequestDispatcherLocal");
109
+ var INTEGRATION_DATA_HEADER = "x-farm-integration-data";
110
+ var INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;
111
+ var BLOCKED_INTEGRATION_DATA_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
112
+ function isIntegrationClientData(value) {
113
+ return !!value && typeof value === "object" && !Array.isArray(value);
114
+ }
115
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isIntegrationClientData, "isIntegrationClientData");
116
+ function isPlainIntegrationDataObject(value) {
117
+ if (!isIntegrationClientData(value)) {
118
+ return false;
119
+ }
120
+ const prototype = Object.getPrototypeOf(value);
121
+ return prototype === Object.prototype || prototype === null;
122
+ }
123
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isPlainIntegrationDataObject, "isPlainIntegrationDataObject");
124
+ function sanitizeIntegrationClientDataValue(value) {
125
+ if (Array.isArray(value)) {
126
+ return value.map((item) => sanitizeIntegrationClientDataValue(item));
127
+ }
128
+ if (!isPlainIntegrationDataObject(value)) {
129
+ return value;
130
+ }
131
+ const sanitized = {};
132
+ for (const [key, item] of Object.entries(value)) {
133
+ if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {
134
+ continue;
135
+ }
136
+ sanitized[key] = sanitizeIntegrationClientDataValue(item);
137
+ }
138
+ return sanitized;
139
+ }
140
+ _chunkS3JO3N4Hcjs.__name.call(void 0, sanitizeIntegrationClientDataValue, "sanitizeIntegrationClientDataValue");
141
+ function normalizeIntegrationClientData(value) {
142
+ if (!isIntegrationClientData(value)) {
143
+ return void 0;
144
+ }
145
+ const sanitized = sanitizeIntegrationClientDataValue(value);
146
+ return isIntegrationClientData(sanitized) && Object.keys(sanitized).length > 0 ? sanitized : void 0;
147
+ }
148
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeIntegrationClientData, "normalizeIntegrationClientData");
149
+ function getIntegrationDataHeaderByteLength(value) {
150
+ return new TextEncoder().encode(value).byteLength;
151
+ }
152
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getIntegrationDataHeaderByteLength, "getIntegrationDataHeaderByteLength");
153
+ function mergeIntegrationClientData(...values) {
154
+ let merged;
155
+ for (const value of values) {
156
+ const data = normalizeIntegrationClientData(value);
157
+ if (!data) {
158
+ continue;
159
+ }
160
+ merged = {
161
+ ...merged,
162
+ ...data
163
+ };
164
+ }
165
+ return merged && Object.keys(merged).length > 0 ? merged : void 0;
166
+ }
167
+ _chunkS3JO3N4Hcjs.__name.call(void 0, mergeIntegrationClientData, "mergeIntegrationClientData");
168
+ function serializeIntegrationClientData(data) {
169
+ const serialized = JSON.stringify(data);
170
+ if (getIntegrationDataHeaderByteLength(serialized) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {
171
+ throw new Error(
172
+ `Integration client data must be smaller than ${INTEGRATION_DATA_HEADER_MAX_LENGTH} bytes when sent over HTTP headers.`
173
+ );
174
+ }
175
+ return serialized;
176
+ }
177
+ _chunkS3JO3N4Hcjs.__name.call(void 0, serializeIntegrationClientData, "serializeIntegrationClientData");
178
+ function appendIntegrationClientDataHeader(headers, data) {
179
+ if (!data) {
180
+ return;
181
+ }
182
+ headers.set(INTEGRATION_DATA_HEADER, serializeIntegrationClientData(data));
183
+ }
184
+ _chunkS3JO3N4Hcjs.__name.call(void 0, appendIntegrationClientDataHeader, "appendIntegrationClientDataHeader");
185
+ function resolveAutomaticClientNamespaces() {
186
+ const globalState = globalThis;
187
+ const manifest = _optionalChain([globalState, 'access', _3 => _3.window, 'optionalAccess', _4 => _4.__FARM_INTEGRATION_API_MANIFEST__]) || globalState.__FARM_INTEGRATION_API_MANIFEST__ || {};
188
+ return Object.entries(manifest).map(([key, api]) => [key, api, api]);
189
+ }
190
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveAutomaticClientNamespaces, "resolveAutomaticClientNamespaces");
191
+ function resolveAutomaticServerNamespaces() {
192
+ return Object.entries(getRegisteredIntegrationsLocal()).flatMap(([key, source]) => {
193
+ const api = tryResolveSourceAPI(source);
194
+ return api ? [[key, api, source]] : [];
195
+ });
196
+ }
197
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveAutomaticServerNamespaces, "resolveAutomaticServerNamespaces");
198
+ function appendQuery(url, query) {
199
+ if (!query) {
200
+ return;
201
+ }
202
+ for (const [key, value] of Object.entries(query)) {
203
+ if (value == null) {
204
+ continue;
205
+ }
206
+ if (Array.isArray(value)) {
207
+ for (const item of value) {
208
+ if (item != null) {
209
+ url.searchParams.append(key, String(item));
210
+ }
211
+ }
212
+ continue;
213
+ }
214
+ url.searchParams.set(key, String(value));
215
+ }
216
+ }
217
+ _chunkS3JO3N4Hcjs.__name.call(void 0, appendQuery, "appendQuery");
218
+ function appendHeaders(target, source) {
219
+ if (!source) {
220
+ return;
221
+ }
222
+ const headers = new Headers(source);
223
+ headers.forEach((value, key) => {
224
+ target.set(key, value);
225
+ });
226
+ }
227
+ _chunkS3JO3N4Hcjs.__name.call(void 0, appendHeaders, "appendHeaders");
228
+ var DEFAULT_FORWARDED_HEADERS = [
229
+ "authorization",
230
+ "cookie",
231
+ "x-client-ip",
232
+ "x-forwarded-for",
233
+ "x-forwarded-host",
234
+ "x-forwarded-proto",
235
+ "x-real-ip"
236
+ ];
237
+ function resolveRequestLike(request) {
238
+ if (!request) {
239
+ return void 0;
240
+ }
241
+ if (request instanceof Request) {
242
+ return {
243
+ url: request.url,
244
+ headers: request.headers
245
+ };
246
+ }
247
+ return {
248
+ url: request.url,
249
+ headers: request.headers ? new Headers(request.headers) : void 0
250
+ };
251
+ }
252
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveRequestLike, "resolveRequestLike");
253
+ function resolveServerBaseURL(explicitBaseURL, request) {
254
+ if (explicitBaseURL) {
255
+ return explicitBaseURL;
256
+ }
257
+ if (_optionalChain([request, 'optionalAccess', _5 => _5.url])) {
258
+ try {
259
+ return new URL(request.url).origin;
260
+ } catch (e) {
261
+ }
262
+ }
263
+ const headers = _optionalChain([request, 'optionalAccess', _6 => _6.headers]);
264
+ const host = _optionalChain([headers, 'optionalAccess', _7 => _7.get, 'call', _8 => _8("x-forwarded-host")]) || _optionalChain([headers, 'optionalAccess', _9 => _9.get, 'call', _10 => _10("host")]);
265
+ if (host) {
266
+ const proto = _optionalChain([headers, 'optionalAccess', _11 => _11.get, 'call', _12 => _12("x-forwarded-proto")]) || "http";
267
+ return `${proto}://${host}`;
268
+ }
269
+ return "http://localhost:3000";
270
+ }
271
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveServerBaseURL, "resolveServerBaseURL");
272
+ function resolveForwardHeaders(request, forwardHeaders) {
273
+ if (!_optionalChain([request, 'optionalAccess', _13 => _13.headers]) || forwardHeaders === false) {
274
+ return new Headers();
275
+ }
276
+ const allowed = Array.isArray(forwardHeaders) && forwardHeaders.length > 0 ? new Set(forwardHeaders.map((item) => item.toLowerCase())) : new Set(DEFAULT_FORWARDED_HEADERS);
277
+ const headers = new Headers();
278
+ request.headers.forEach((value, key) => {
279
+ if (allowed.has(key.toLowerCase())) {
280
+ headers.set(key, value);
281
+ }
282
+ });
283
+ return headers;
284
+ }
285
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveForwardHeaders, "resolveForwardHeaders");
286
+ function createBody(format, body, headers) {
287
+ if (body == null || format === "none") {
288
+ return void 0;
289
+ }
290
+ if (format === "form") {
291
+ if (body instanceof FormData || body instanceof URLSearchParams) {
292
+ return body;
293
+ }
294
+ const form = new URLSearchParams();
295
+ for (const [key, value] of Object.entries(body)) {
296
+ if (value == null) {
297
+ continue;
298
+ }
299
+ if (Array.isArray(value)) {
300
+ for (const item of value) {
301
+ if (item != null) {
302
+ form.append(key, String(item));
303
+ }
304
+ }
305
+ continue;
306
+ }
307
+ form.set(key, String(value));
308
+ }
309
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
310
+ return form;
311
+ }
312
+ headers.set("content-type", "application/json");
313
+ return JSON.stringify(body);
314
+ }
315
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createBody, "createBody");
316
+ function createOperationBody(operation, body, headers) {
317
+ const requestBody = createBody(operation.bodyFormat, body, headers);
318
+ if (operation.method === "QUERY" && requestBody === void 0 && !headers.has("content-type")) {
319
+ headers.set(
320
+ "content-type",
321
+ operation.bodyFormat === "form" ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json"
322
+ );
323
+ }
324
+ return requestBody;
325
+ }
326
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createOperationBody, "createOperationBody");
327
+ async function parseResponseData(response) {
328
+ if (response.status === 204 || response.status === 205) {
329
+ return void 0;
330
+ }
331
+ const contentType = response.headers.get("content-type") || "";
332
+ if (isJSONMediaType(contentType)) {
333
+ return await response.json();
334
+ }
335
+ return await response.text();
336
+ }
337
+ _chunkS3JO3N4Hcjs.__name.call(void 0, parseResponseData, "parseResponseData");
338
+ function isJSONMediaType(contentType) {
339
+ const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
340
+ return mediaType === "application/json" || mediaType.endsWith("+json");
341
+ }
342
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isJSONMediaType, "isJSONMediaType");
343
+ async function safeParseResponseData(response) {
344
+ try {
345
+ return await parseResponseData(response);
346
+ } catch (e2) {
347
+ return void 0;
348
+ }
349
+ }
350
+ _chunkS3JO3N4Hcjs.__name.call(void 0, safeParseResponseData, "safeParseResponseData");
351
+ function createResponseError(response, errorData) {
352
+ const message = typeof errorData === "string" ? errorData : typeof errorData === "object" && errorData ? String(
353
+ errorData.error || errorData.message || response.statusText
354
+ ) : response.statusText || "Integration request failed.";
355
+ return new IntegrationClientError(message, response, errorData);
356
+ }
357
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createResponseError, "createResponseError");
358
+ function normalizeExecutionError(error) {
359
+ if (error instanceof Error) {
360
+ return error;
361
+ }
362
+ if (typeof error === "string" && error.length > 0) {
363
+ return new Error(error);
364
+ }
365
+ return new Error("Integration request failed.");
366
+ }
367
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeExecutionError, "normalizeExecutionError");
368
+ async function finalizeOperationResponse(operation, response) {
369
+ if (!response.ok) {
370
+ const errorData = await safeParseResponseData(response);
371
+ return {
372
+ data: null,
373
+ error: createResponseError(response, errorData)
374
+ };
375
+ }
376
+ if (operation.responseFormat === "response") {
377
+ return {
378
+ data: response,
379
+ error: null
380
+ };
381
+ }
382
+ return {
383
+ data: await parseResponseData(response),
384
+ error: null
385
+ };
386
+ }
387
+ _chunkS3JO3N4Hcjs.__name.call(void 0, finalizeOperationResponse, "finalizeOperationResponse");
388
+ var integrationRequestCounter = 0;
389
+ var noIntegrationObservers = {
390
+ response(_response) {
391
+ },
392
+ finish(result) {
393
+ return result;
394
+ }
395
+ };
396
+ function createIntegrationObservers(operation, options, requestOptions) {
397
+ if (!options.onRequest && !options.onResponse && !options.onError && !_optionalChain([requestOptions, 'optionalAccess', _14 => _14.onRequest]) && !_optionalChain([requestOptions, 'optionalAccess', _15 => _15.onResponse]) && !_optionalChain([requestOptions, 'optionalAccess', _16 => _16.onError])) {
398
+ return noIntegrationObservers;
399
+ }
400
+ const requestEvent = {
401
+ requestId: `integration-${Date.now()}-${++integrationRequestCounter}`,
402
+ method: operation.method,
403
+ path: _nullishCoalesce(operation.path, () => ( "")),
404
+ attempt: 0,
405
+ timestamp: Date.now()
406
+ };
407
+ let response;
408
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onRequest, [requestEvent]);
409
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, _optionalChain([requestOptions, 'optionalAccess', _17 => _17.onRequest]), [requestEvent]);
410
+ return {
411
+ response(value) {
412
+ response = value;
413
+ },
414
+ finish(result) {
415
+ const data = result.error ? void 0 : result.data;
416
+ const event = {
417
+ ...requestEvent,
418
+ timestamp: Date.now(),
419
+ response,
420
+ data,
421
+ error: _nullishCoalesce(result.error, () => ( void 0)),
422
+ ok: !result.error,
423
+ status: _optionalChain([response, 'optionalAccess', _18 => _18.status])
424
+ };
425
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onResponse, [data, result.error, event]);
426
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, _optionalChain([requestOptions, 'optionalAccess', _19 => _19.onResponse]), [data, result.error, event]);
427
+ if (result.error) {
428
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onError, [result.error]);
429
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, _optionalChain([requestOptions, 'optionalAccess', _20 => _20.onError]), [result.error]);
430
+ }
431
+ return result;
432
+ }
433
+ };
434
+ }
435
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createIntegrationObservers, "createIntegrationObservers");
436
+ async function executeClientOperation(operation, input, options, requestOptions) {
437
+ const cancellation = _chunkJ7FSKED3cjs.createClientCancellation.call(void 0,
438
+ _optionalChain([requestOptions, 'optionalAccess', _21 => _21.signal]),
439
+ _nullishCoalesce(_optionalChain([requestOptions, 'optionalAccess', _22 => _22.timeoutMs]), () => ( options.timeoutMs))
440
+ );
441
+ const observers = createIntegrationObservers(operation, options, requestOptions);
442
+ try {
443
+ const result = await cancellation.run(async () => {
444
+ if (!operation.path) {
445
+ return {
446
+ data: null,
447
+ error: new Error(
448
+ "Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
449
+ )
450
+ };
451
+ }
452
+ const baseURL = options.baseURL || (typeof window !== "undefined" ? window.location.origin : "http://localhost:3000");
453
+ const url = _chunkS3A45T7Fcjs.resolveFarmAPIRequestURL.call(void 0, operation.path, baseURL);
454
+ appendQuery(url, input.query);
455
+ const resolved = resolveClientHeaders(options.headers);
456
+ const headers = resolved instanceof Headers ? resolved : await resolved;
457
+ cancellation.check();
458
+ appendHeaders(headers, operation.headers);
459
+ appendHeaders(headers, _optionalChain([requestOptions, 'optionalAccess', _23 => _23.headers]));
460
+ headers.set("x-farm-integration-client", "1");
461
+ if (operation.responseFormat !== "response") {
462
+ headers.set("accept", "application/json");
463
+ }
464
+ appendIntegrationClientDataHeader(
465
+ headers,
466
+ mergeIntegrationClientData(options.data, _optionalChain([requestOptions, 'optionalAccess', _24 => _24.data]))
467
+ );
468
+ const body = createOperationBody(operation, input.body, headers);
469
+ const response = await (_nullishCoalesce(options.fetch, () => ( fetch)))(url.toString(), {
470
+ method: operation.method,
471
+ headers,
472
+ body,
473
+ credentials: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([requestOptions, 'optionalAccess', _25 => _25.credentials]), () => ( operation.credentials)), () => ( options.credentials)), () => ( "include")),
474
+ signal: cancellation.signal
475
+ });
476
+ cancellation.check();
477
+ observers.response(response);
478
+ if (!response.ok) {
479
+ const errorData = await safeParseResponseData(response);
480
+ return {
481
+ data: null,
482
+ error: createResponseError(response, errorData)
483
+ };
484
+ }
485
+ if (operation.responseFormat === "response") {
486
+ return {
487
+ data: response,
488
+ error: null
489
+ };
490
+ }
491
+ return {
492
+ data: await parseResponseData(response),
493
+ error: null
494
+ };
495
+ });
496
+ return observers.finish(result);
497
+ } catch (error) {
498
+ return observers.finish({
499
+ data: null,
500
+ error: normalizeExecutionError(error)
501
+ });
502
+ } finally {
503
+ cancellation.dispose();
504
+ }
505
+ }
506
+ _chunkS3JO3N4Hcjs.__name.call(void 0, executeClientOperation, "executeClientOperation");
507
+ async function executeServerOperation(operation, input, options, requestOptions, integrationKey, source) {
508
+ const currentRequest = _optionalChain([requestOptions, 'optionalAccess', _26 => _26.request]) instanceof Request ? requestOptions.request : options.request instanceof Request ? options.request : resolveCurrentRequestLocal();
509
+ const cancellation = _chunkJ7FSKED3cjs.createClientCancellation.call(void 0,
510
+ _optionalChain([requestOptions, 'optionalAccess', _27 => _27.signal]),
511
+ _nullishCoalesce(_optionalChain([requestOptions, 'optionalAccess', _28 => _28.timeoutMs]), () => ( options.timeoutMs)),
512
+ _optionalChain([currentRequest, 'optionalAccess', _29 => _29.signal])
513
+ );
514
+ const observers = createIntegrationObservers(operation, options, requestOptions);
515
+ try {
516
+ const result = await cancellation.run(async () => {
517
+ if (!operation.path) {
518
+ return {
519
+ data: null,
520
+ error: new Error(
521
+ "Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
522
+ )
523
+ };
524
+ }
525
+ const serverRequestOptions = requestOptions && ("request" in requestOptions || "baseURL" in requestOptions || "forwardHeaders" in requestOptions) ? requestOptions : void 0;
526
+ const request = resolveRequestLike(
527
+ _nullishCoalesce(_nullishCoalesce(_optionalChain([serverRequestOptions, 'optionalAccess', _30 => _30.request]), () => ( options.request)), () => ( currentRequest))
528
+ );
529
+ const baseURL = resolveServerBaseURL(
530
+ _nullishCoalesce(_optionalChain([serverRequestOptions, 'optionalAccess', _31 => _31.baseURL]), () => ( options.baseURL)),
531
+ request
532
+ );
533
+ const origin = resolveServerBaseURL(void 0, request);
534
+ const url = new URL(operation.path, new URL(baseURL, origin));
535
+ appendQuery(url, input.query);
536
+ const headers = new Headers();
537
+ appendHeaders(
538
+ headers,
539
+ resolveForwardHeaders(
540
+ request,
541
+ _nullishCoalesce(_optionalChain([serverRequestOptions, 'optionalAccess', _32 => _32.forwardHeaders]), () => ( options.forwardHeaders))
542
+ )
543
+ );
544
+ const resolved = resolveClientHeaders(options.headers);
545
+ appendHeaders(headers, resolved instanceof Headers ? resolved : await resolved);
546
+ cancellation.check();
547
+ appendHeaders(headers, operation.headers);
548
+ appendHeaders(headers, _optionalChain([requestOptions, 'optionalAccess', _33 => _33.headers]));
549
+ headers.set("x-farm-integration-client", "1");
550
+ if (operation.responseFormat !== "response") {
551
+ headers.set("accept", "application/json");
552
+ }
553
+ const data = mergeIntegrationClientData(options.data, _optionalChain([requestOptions, 'optionalAccess', _34 => _34.data]));
554
+ if (integrationKey) {
555
+ const runtime = "kind" in (source || {}) && source.kind === "farm-integration" ? getRegisteredIntegrationRuntimeLocal(integrationKey) || {
556
+ integration: source,
557
+ config: {},
558
+ isDev: process.env.NODE_ENV !== "production",
559
+ isProd: process.env.NODE_ENV === "production"
560
+ } : getRegisteredIntegrationRuntimeLocal(integrationKey);
561
+ if (runtime) {
562
+ const dispatchIntegrationRequest = resolveIntegrationRequestDispatcherLocal();
563
+ const body2 = createOperationBody(operation, input.body, headers);
564
+ const directResponse = dispatchIntegrationRequest ? await dispatchIntegrationRequest(
565
+ runtime,
566
+ new Request(url.toString(), {
567
+ method: operation.method,
568
+ headers,
569
+ body: body2,
570
+ signal: cancellation.signal
571
+ }),
572
+ {
573
+ currentRequest,
574
+ data,
575
+ internal: true
576
+ }
577
+ ) : null;
578
+ cancellation.check();
579
+ if (directResponse) {
580
+ observers.response(directResponse);
581
+ return await finalizeOperationResponse(operation, directResponse);
582
+ }
583
+ }
584
+ }
585
+ appendIntegrationClientDataHeader(headers, data);
586
+ const body = createOperationBody(operation, input.body, headers);
587
+ const httpURL = _chunkS3A45T7Fcjs.resolveFarmAPIRequestURL.call(void 0, operation.path, baseURL, origin);
588
+ appendQuery(httpURL, input.query);
589
+ const response = await (_nullishCoalesce(options.fetch, () => ( fetch)))(httpURL.toString(), {
590
+ method: operation.method,
591
+ headers,
592
+ body,
593
+ credentials: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([requestOptions, 'optionalAccess', _35 => _35.credentials]), () => ( operation.credentials)), () => ( options.credentials)), () => ( "include")),
594
+ signal: cancellation.signal
595
+ });
596
+ cancellation.check();
597
+ observers.response(response);
598
+ return await finalizeOperationResponse(operation, response);
599
+ });
600
+ return observers.finish(result);
601
+ } catch (error) {
602
+ return observers.finish({
603
+ data: null,
604
+ error: normalizeExecutionError(error)
605
+ });
606
+ } finally {
607
+ cancellation.dispose();
608
+ }
609
+ }
610
+ _chunkS3JO3N4Hcjs.__name.call(void 0, executeServerOperation, "executeServerOperation");
611
+ function createIntegrationClient(sources, options = {}) {
612
+ const rawSources = "integrations" in sources ? sources.integrations : sources;
613
+ const isServer = options.isServer === true;
614
+ const namespaces = Object.entries(rawSources).map(([key, source]) => {
615
+ const api = tryResolveSourceAPI(source);
616
+ if (!api) {
617
+ return null;
618
+ }
619
+ return [key, api, source];
620
+ }).filter(
621
+ (value) => value !== null
622
+ );
623
+ const cache = /* @__PURE__ */ new Map();
624
+ const integrationNamespaces = new Proxy(
625
+ {},
626
+ {
627
+ get(target, property) {
628
+ if (typeof property !== "string") {
629
+ return void 0;
630
+ }
631
+ if (Reflect.has(target, property)) {
632
+ return Reflect.get(target, property);
633
+ }
634
+ if (cache.has(property)) {
635
+ return cache.get(property);
636
+ }
637
+ const match = namespaces.find(([key]) => key === property);
638
+ if (!match) {
639
+ return void 0;
640
+ }
641
+ const namespace = isServer ? createServerNamespaceProxy(
642
+ match[0],
643
+ match[2],
644
+ match[1],
645
+ options
646
+ ) : createNamespaceProxy(match[1], options);
647
+ cache.set(property, namespace);
648
+ return namespace;
649
+ }
650
+ }
651
+ );
652
+ if ("integrations" in sources) {
653
+ Object.defineProperty(integrationNamespaces, "integrations", {
654
+ value: integrationNamespaces,
655
+ enumerable: false,
656
+ configurable: false,
657
+ writable: false
658
+ });
659
+ return integrationNamespaces;
660
+ }
661
+ return integrationNamespaces;
662
+ }
663
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createIntegrationClient, "createIntegrationClient");
664
+ function createAutomaticIntegrationAliases(isServer, options = {}) {
665
+ const cache = isServer ? /* @__PURE__ */ new Map() : null;
666
+ const integrationNamespaces = new Proxy(
667
+ {},
668
+ {
669
+ get(_target, property) {
670
+ if (typeof property !== "string") {
671
+ return void 0;
672
+ }
673
+ if (property === "integrations") {
674
+ return integrationNamespaces;
675
+ }
676
+ if (_optionalChain([cache, 'optionalAccess', _36 => _36.has, 'call', _37 => _37(property)])) {
677
+ return cache.get(property);
678
+ }
679
+ const namespaces = isServer ? resolveAutomaticServerNamespaces() : resolveAutomaticClientNamespaces();
680
+ const match = namespaces.find(([key]) => key === property);
681
+ if (!match) {
682
+ return void 0;
683
+ }
684
+ const namespace = isServer ? createServerNamespaceProxy(
685
+ match[0],
686
+ match[2],
687
+ match[1],
688
+ options
689
+ ) : createNamespaceProxy(match[1], options);
690
+ _optionalChain([cache, 'optionalAccess', _38 => _38.set, 'call', _39 => _39(property, namespace)]);
691
+ return namespace;
692
+ }
693
+ }
694
+ );
695
+ Object.defineProperty(integrationNamespaces, "integrations", {
696
+ value: integrationNamespaces,
697
+ enumerable: false,
698
+ configurable: false,
699
+ writable: false
700
+ });
701
+ return integrationNamespaces;
702
+ }
703
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createAutomaticIntegrationAliases, "createAutomaticIntegrationAliases");
704
+ function integrationsClient(options = {}) {
705
+ return createAutomaticIntegrationAliases(
706
+ false,
707
+ options
708
+ );
709
+ }
710
+ _chunkS3JO3N4Hcjs.__name.call(void 0, integrationsClient, "integrationsClient");
711
+ function integrationsServer(options = {}) {
712
+ return createAutomaticIntegrationAliases(true, {
713
+ ...options,
714
+ isServer: true
715
+ });
716
+ }
717
+ _chunkS3JO3N4Hcjs.__name.call(void 0, integrationsServer, "integrationsServer");
718
+ function createIntegrationServerClient(sources, options = {}) {
719
+ return createIntegrationClient(sources, {
720
+ ...options,
721
+ isServer: true
722
+ });
723
+ }
724
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createIntegrationServerClient, "createIntegrationServerClient");
725
+ function createIntegrationApi(sources, options = {}) {
726
+ const client = createIntegrationClient(sources, options);
727
+ return {
728
+ ...client,
729
+ server(serverOptions = {}) {
730
+ return createIntegrationServerClient(sources, {
731
+ ...options,
732
+ ...serverOptions
733
+ });
734
+ }
735
+ };
736
+ }
737
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createIntegrationApi, "createIntegrationApi");
738
+ function isIntegrationClientOptionsInput(value) {
739
+ return !!value && typeof value === "object" && !Array.isArray(value) && ("baseURL" in value || "headers" in value || "credentials" in value || "timeoutMs" in value || "fetch" in value || "onRequest" in value || "onResponse" in value || "onError" in value || "data" in value || "isServer" in value);
740
+ }
741
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isIntegrationClientOptionsInput, "isIntegrationClientOptionsInput");
742
+ function resolveIntegrationServerOptions(clientOptions = {}, serverOptions = {}) {
743
+ const data = mergeIntegrationClientData(clientOptions.data, serverOptions.data);
744
+ return {
745
+ baseURL: clientOptions.baseURL,
746
+ headers: clientOptions.headers,
747
+ credentials: clientOptions.credentials,
748
+ timeoutMs: clientOptions.timeoutMs,
749
+ fetch: clientOptions.fetch,
750
+ onRequest: clientOptions.onRequest,
751
+ onResponse: clientOptions.onResponse,
752
+ onError: clientOptions.onError,
753
+ ...serverOptions,
754
+ ...data ? { data } : {}
755
+ };
756
+ }
757
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveIntegrationServerOptions, "resolveIntegrationServerOptions");
758
+ function createIntegrationClients(sources, clientOptions, serverOptions) {
759
+ if (arguments.length === 0 || isIntegrationClientOptionsInput(sources)) {
760
+ const automaticClientOptions = isIntegrationClientOptionsInput(sources) ? sources : {};
761
+ const automaticServerOptions = arguments.length > 1 ? clientOptions : void 0;
762
+ return {
763
+ api: integrationsServer(
764
+ resolveIntegrationServerOptions(
765
+ automaticClientOptions,
766
+ automaticServerOptions
767
+ )
768
+ ),
769
+ apiClient: integrationsClient(automaticClientOptions)
770
+ };
771
+ }
772
+ const explicitSources = sources && "integrations" in sources ? sources.integrations : sources;
773
+ return {
774
+ api: createIntegrationServerClient(
775
+ {
776
+ integrations: explicitSources
777
+ },
778
+ resolveIntegrationServerOptions(clientOptions, serverOptions)
779
+ ),
780
+ apiClient: createIntegrationClient(
781
+ {
782
+ integrations: explicitSources
783
+ },
784
+ clientOptions
785
+ )
786
+ };
787
+ }
788
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createIntegrationClients, "createIntegrationClients");
789
+ function createIntegrations(sources, clientOptions, serverOptions) {
790
+ if (arguments.length === 0) {
791
+ return createIntegrationClients();
792
+ }
793
+ return createIntegrationClients(
794
+ sources,
795
+ clientOptions,
796
+ serverOptions
797
+ );
798
+ }
799
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createIntegrations, "createIntegrations");
800
+ function createClientSafeIntegrationAPI(api) {
801
+ if (!api) {
802
+ return void 0;
803
+ }
804
+ const entries = Object.entries(api).map(([key, value]) => {
805
+ if (isOperation(value)) {
806
+ return [
807
+ key,
808
+ {
809
+ kind: value.kind,
810
+ path: value.path,
811
+ method: value.method,
812
+ bodyFormat: value.bodyFormat,
813
+ responseFormat: value.responseFormat,
814
+ credentials: value.credentials,
815
+ isServer: value.isServer,
816
+ __pathless: value.__pathless
817
+ }
818
+ ];
819
+ }
820
+ if (value && typeof value === "object") {
821
+ return [key, createClientSafeIntegrationAPI(value)];
822
+ }
823
+ return [key, value];
824
+ });
825
+ return Object.fromEntries(entries);
826
+ }
827
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createClientSafeIntegrationAPI, "createClientSafeIntegrationAPI");
828
+ function getIntegrationAPIManifest() {
829
+ const manifestEntries = Object.entries(getRegisteredIntegrationsLocal()).map(([key, integration]) => {
830
+ const api = createClientSafeIntegrationAPI(integration.api);
831
+ return api ? [key, api] : null;
832
+ }).filter((value) => value !== null);
833
+ return Object.fromEntries(manifestEntries);
834
+ }
835
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getIntegrationAPIManifest, "getIntegrationAPIManifest");
836
+ function integrationClients(sources, clientOptions, serverOptions) {
837
+ if (arguments.length === 0) {
838
+ return createIntegrationClients();
839
+ }
840
+ return createIntegrationClients(
841
+ sources,
842
+ clientOptions,
843
+ serverOptions
844
+ );
845
+ }
846
+ _chunkS3JO3N4Hcjs.__name.call(void 0, integrationClients, "integrationClients");
847
+ function resolveSingleNamespaceOperation(api) {
848
+ const entries = Object.entries(api);
849
+ if (entries.length !== 1) {
850
+ return null;
851
+ }
852
+ const [, value] = entries[0];
853
+ return isOperation(value) ? value : null;
854
+ }
855
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveSingleNamespaceOperation, "resolveSingleNamespaceOperation");
856
+ function createClientOperationCaller(operation, property, options) {
857
+ if (operation.isServer === true) {
858
+ return async () => {
859
+ throw new Error(
860
+ `Integration method "${property}" is registered with isServer: true and is only available from a server integration client.`
861
+ );
862
+ };
863
+ }
864
+ return async (input = {}, requestOptions) => {
865
+ if (typeof window === "undefined") {
866
+ throw new Error(
867
+ "Client integration API cannot be called on the server. Pass { isServer: true } to createIntegrationClient(...) during server rendering, or provide { isServer: true, request } outside it."
868
+ );
869
+ }
870
+ return executeClientOperation(operation, input, options, requestOptions);
871
+ };
872
+ }
873
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createClientOperationCaller, "createClientOperationCaller");
874
+ function createServerOperationCaller(operation, options, integrationKey, source) {
875
+ return async (input = {}, requestOptions) => {
876
+ if (typeof window !== "undefined") {
877
+ throw new Error(
878
+ "Server integration API cannot be called in the browser. Remove { isServer: true } and create a client integration API instead."
879
+ );
880
+ }
881
+ return executeServerOperation(
882
+ operation,
883
+ input,
884
+ options,
885
+ requestOptions,
886
+ integrationKey,
887
+ source
888
+ );
889
+ };
890
+ }
891
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createServerOperationCaller, "createServerOperationCaller");
892
+ function createNamespaceProxy(api, options) {
893
+ const cache = /* @__PURE__ */ new Map();
894
+ const directOperation = resolveSingleNamespaceOperation(api);
895
+ const target = directOperation ? createClientOperationCaller(directOperation, directOperation.method.toLowerCase(), options) : {};
896
+ return new Proxy(target, {
897
+ get(targetObject, property, receiver) {
898
+ if (typeof property !== "string") {
899
+ return Reflect.get(targetObject, property, receiver);
900
+ }
901
+ if (cache.has(property)) {
902
+ return cache.get(property);
903
+ }
904
+ const value = api[property];
905
+ if (!value) {
906
+ return Reflect.get(targetObject, property, receiver);
907
+ }
908
+ if (isOperation(value)) {
909
+ const caller = createClientOperationCaller(value, property, options);
910
+ cache.set(property, caller);
911
+ return caller;
912
+ }
913
+ const namespace = createNamespaceProxy(value, options);
914
+ cache.set(property, namespace);
915
+ return namespace;
916
+ }
917
+ });
918
+ }
919
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createNamespaceProxy, "createNamespaceProxy");
920
+ function createServerNamespaceProxy(integrationKey, source, api, options) {
921
+ const cache = /* @__PURE__ */ new Map();
922
+ const directOperation = resolveSingleNamespaceOperation(api);
923
+ const target = directOperation ? createServerOperationCaller(directOperation, options, integrationKey, source) : {};
924
+ return new Proxy(target, {
925
+ get(targetObject, property, receiver) {
926
+ if (typeof property !== "string") {
927
+ return Reflect.get(targetObject, property, receiver);
928
+ }
929
+ if (cache.has(property)) {
930
+ return cache.get(property);
931
+ }
932
+ const value = api[property];
933
+ if (!value) {
934
+ return Reflect.get(targetObject, property, receiver);
935
+ }
936
+ if (isOperation(value)) {
937
+ const caller = createServerOperationCaller(value, options, integrationKey, source);
938
+ cache.set(property, caller);
939
+ return caller;
940
+ }
941
+ const namespace = createServerNamespaceProxy(
942
+ integrationKey,
943
+ source,
944
+ value,
945
+ options
946
+ );
947
+ cache.set(property, namespace);
948
+ return namespace;
949
+ }
950
+ });
951
+ }
952
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createServerNamespaceProxy, "createServerNamespaceProxy");
953
+
954
+ // src/api/client-routes.ts
955
+ var _ClientRouteManifest = class _ClientRouteManifest {
956
+ constructor(routes) {
957
+ this.candidates = /* @__PURE__ */ new Map();
958
+ this.nextSegments = /* @__PURE__ */ new Map();
959
+ this.routes = new Map(
960
+ routes.map((route) => [
961
+ route.path.replace(/\/$/, ""),
962
+ {
963
+ path: route.path.replace(/\/$/, ""),
964
+ methods: [...route.methods]
965
+ }
966
+ ])
967
+ );
968
+ const addCandidate = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (path, route) => {
969
+ let candidates = this.candidates.get(path);
970
+ if (!candidates) this.candidates.set(path, candidates = []);
971
+ candidates.push(route);
972
+ }, "addCandidate");
973
+ for (const route of this.routes.values()) {
974
+ addCandidate(route.path, route);
975
+ const segments = route.path.split("/");
976
+ let parent = "";
977
+ for (let i = 0; i < segments.length; i++) {
978
+ const segment = segments[i];
979
+ if (i > 0 && _chunkG7HXGLECcjs.parseDynamicSegment.call(void 0, segment)) {
980
+ let next = this.nextSegments.get(parent);
981
+ if (!next) this.nextSegments.set(parent, next = /* @__PURE__ */ new Set());
982
+ next.add(segment);
983
+ if (i === segments.length - 1) addCandidate(parent, route);
984
+ }
985
+ parent = i === 0 ? segment : `${parent}/${segment}`;
986
+ }
987
+ }
988
+ }
989
+ bind(path, input) {
990
+ const params = readParams(input);
991
+ const normalized = path.replace(/\/$/, "");
992
+ const candidates = new Set(
993
+ [..._nullishCoalesce(this.nextSegments.get(normalized), () => ( []))].filter((segment2) => {
994
+ const dynamic2 = _chunkG7HXGLECcjs.parseDynamicSegment.call(void 0, segment2);
995
+ return dynamic2 && Object.keys(params).every((key) => key === dynamic2.name) && (Object.prototype.hasOwnProperty.call(params, dynamic2.name) || dynamic2.optional);
996
+ })
997
+ );
998
+ if (candidates.size !== 1)
999
+ throw new TypeError(
1000
+ `Cannot bind route params at ${path}: supply exactly the next dynamic segment's parameter.`
1001
+ );
1002
+ const segment = [...candidates][0];
1003
+ const dynamic = _chunkG7HXGLECcjs.parseDynamicSegment.call(void 0, segment);
1004
+ encodeParameter(dynamic, params[dynamic.name]);
1005
+ return {
1006
+ segment,
1007
+ params: Object.freeze(
1008
+ Object.fromEntries(
1009
+ Object.entries(params).map(([key, value]) => [
1010
+ key,
1011
+ Array.isArray(value) ? Object.freeze([...value]) : value
1012
+ ])
1013
+ )
1014
+ )
1015
+ };
1016
+ }
1017
+ resolve(path, method, bound, input) {
1018
+ const normalized = path.replace(/\/$/, "");
1019
+ const supplied = readParams(_optionalChain([input, 'optionalAccess', _40 => _40.params]));
1020
+ const candidates = (_nullishCoalesce(this.candidates.get(normalized), () => ( []))).filter((route2) => {
1021
+ if (route2.path === normalized) return true;
1022
+ if (!route2.path.startsWith(`${normalized}/`)) return false;
1023
+ const tail = route2.path.slice(normalized.length + 1);
1024
+ return !tail.includes("/") && Boolean(_chunkG7HXGLECcjs.parseDynamicSegment.call(void 0, tail)) && _optionalChain([input, 'optionalAccess', _41 => _41.params]) !== void 0;
1025
+ });
1026
+ const selected = candidates.filter((route2) => {
1027
+ const unbound = route2.path.split("/").map(_chunkG7HXGLECcjs.parseDynamicSegment).filter((part) => part && !Object.prototype.hasOwnProperty.call(bound, part.name));
1028
+ return Object.keys(supplied).every((key) => unbound.some((part) => part.name === key)) && unbound.every(
1029
+ (part) => part.optional || Object.prototype.hasOwnProperty.call(supplied, part.name)
1030
+ );
1031
+ });
1032
+ if (selected.length !== 1)
1033
+ throw new TypeError(
1034
+ `Cannot resolve ${method} ${normalized}: missing, unexpected, or ambiguous route params.`
1035
+ );
1036
+ const route = selected[0];
1037
+ if (!route.methods.includes(method) && !(method === "HEAD" && route.methods.includes("GET"))) {
1038
+ throw new TypeError(`${method} is not registered for ${route.path}.`);
1039
+ }
1040
+ const params = { ...bound, ...supplied };
1041
+ const resolved = route.path.split("/").map((segment) => {
1042
+ const dynamic = _chunkG7HXGLECcjs.parseDynamicSegment.call(void 0, segment);
1043
+ return dynamic ? encodeParameter(dynamic, params[dynamic.name]) : segment;
1044
+ }).filter(Boolean).join("/");
1045
+ const pathname = `/${resolved}`;
1046
+ const winner = _chunkG7HXGLECcjs.matchAPIRoute.call(void 0, this.routes, pathname);
1047
+ if (_optionalChain([winner, 'optionalAccess', _42 => _42.route, 'access', _43 => _43.path]) !== route.path) {
1048
+ throw new TypeError(
1049
+ `Route ${route.path} resolves to ${pathname}, which is shadowed by ${_nullishCoalesce(_optionalChain([winner, 'optionalAccess', _44 => _44.route, 'access', _45 => _45.path]), () => ( "another route"))}.`
1050
+ );
1051
+ }
1052
+ return pathname;
1053
+ }
1054
+ };
1055
+ _chunkS3JO3N4Hcjs.__name.call(void 0, _ClientRouteManifest, "ClientRouteManifest");
1056
+ var ClientRouteManifest = _ClientRouteManifest;
1057
+ function readParams(input) {
1058
+ if (input === void 0) return {};
1059
+ if (!input || typeof input !== "object" || Array.isArray(input) || ![Object.prototype, null].includes(Object.getPrototypeOf(input))) {
1060
+ throw new TypeError("Route params must be a plain object.");
1061
+ }
1062
+ for (const key of Object.keys(input)) {
1063
+ if (["__proto__", "constructor", "prototype"].includes(key))
1064
+ throw new TypeError(`Unsafe route parameter ${key}.`);
1065
+ }
1066
+ return input;
1067
+ }
1068
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readParams, "readParams");
1069
+ function encodeParameter(parameter, value) {
1070
+ if (parameter.optional && value === void 0) return "";
1071
+ const parts = parameter.catchAll ? value : [value];
1072
+ if (!Array.isArray(parts) || !parts.length && !parameter.optional) {
1073
+ throw new TypeError(
1074
+ `Route parameter ${parameter.name} must be ${parameter.catchAll ? "a non-empty array of strings" : "a string"}.`
1075
+ );
1076
+ }
1077
+ return Array.from(parts, (part) => {
1078
+ if (typeof part !== "string" || !part || part === "." || part === ".." || Array.from(part).some(
1079
+ (character) => character.charCodeAt(0) <= 31 || character.charCodeAt(0) >= 127 && character.charCodeAt(0) <= 159
1080
+ )) {
1081
+ throw new TypeError(`Invalid value for route parameter ${parameter.name}.`);
1082
+ }
1083
+ return encodeURIComponent(part);
1084
+ }).join("/");
1085
+ }
1086
+ _chunkS3JO3N4Hcjs.__name.call(void 0, encodeParameter, "encodeParameter");
1087
+
1088
+ // src/api/client.ts
1089
+ var FARM_API_ROUTE_REF_SYMBOL = /* @__PURE__ */ Symbol.for("farm.api.route-ref");
1090
+ var FARM_API_ROUTE_META_SYMBOL = /* @__PURE__ */ Symbol.for("farm.api.route-meta");
1091
+ var _APIClientError = class _APIClientError extends Error {
1092
+ constructor(code, data, options) {
1093
+ super(options.message);
1094
+ this.name = "APIClientError";
1095
+ this.code = code;
1096
+ this.data = data;
1097
+ this.status = options.status;
1098
+ this.response = options.response;
1099
+ }
1100
+ };
1101
+ _chunkS3JO3N4Hcjs.__name.call(void 0, _APIClientError, "APIClientError");
1102
+ var APIClientError = _APIClientError;
1103
+ var FARM_IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "QUERY"]);
1104
+ var FARM_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 425, 429]);
1105
+ function isFarmRetryableFailure(context) {
1106
+ if (!FARM_IDEMPOTENT_METHODS.has(context.method)) return false;
1107
+ if (context.status === void 0) return true;
1108
+ return context.status >= 500 || FARM_RETRYABLE_STATUSES.has(context.status);
1109
+ }
1110
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isFarmRetryableFailure, "isFarmRetryableFailure");
1111
+ function createApiClients(options = {}) {
1112
+ const localScopes = /* @__PURE__ */ new WeakMap();
1113
+ const routeMeta = /* @__PURE__ */ new WeakMap();
1114
+ const api = createNestedProxy(
1115
+ [],
1116
+ async (path, method, input, clientOptions) => {
1117
+ if (typeof window !== "undefined") {
1118
+ throw new Error(
1119
+ "api is server-only. Use apiClient from createApiClients() in the browser."
1120
+ );
1121
+ }
1122
+ const currentRequest = _chunkU4KT7QP3cjs._resolveCurrentRequest.call(void 0, );
1123
+ const runtime = _chunk72ADZ6GQcjs.resolveAPIRequestRuntime.call(void 0, );
1124
+ if (!currentRequest || !runtime) {
1125
+ throw new Error(
1126
+ "api requires an active Farm server request. Call it from a server page, query, action, or API handler; use apiClient with an absolute baseURL for standalone HTTP calls."
1127
+ );
1128
+ }
1129
+ let localClients = localScopes.get(runtime);
1130
+ if (!localClients) {
1131
+ localClients = /* @__PURE__ */ new WeakMap();
1132
+ localScopes.set(runtime, localClients);
1133
+ }
1134
+ let local = localClients.get(currentRequest);
1135
+ if (!local) {
1136
+ const origin = new URL(currentRequest.url).origin;
1137
+ const headers = new Headers();
1138
+ for (const name of ["cookie", "authorization", "accept-language"]) {
1139
+ const value = currentRequest.headers.get(name);
1140
+ if (value !== null) headers.set(name, value);
1141
+ }
1142
+ local = createAPIClientRuntime(
1143
+ {
1144
+ ...options,
1145
+ integrations: false,
1146
+ baseURL: new URL(runtime.basePath, origin).toString()
1147
+ },
1148
+ {
1149
+ headers,
1150
+ signal: currentRequest.signal,
1151
+ cache: new (0, _chunkI7PUUDGYcjs.FarmClientDataCache)({ subscribeToInvalidation: false }),
1152
+ routeMeta,
1153
+ fetch: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (url, init) => {
1154
+ if (new URL(url).origin !== origin) {
1155
+ throw new Error(
1156
+ "api can only dispatch to this Farm app. Use apiClient for HTTP calls."
1157
+ );
1158
+ }
1159
+ currentRequest.signal.throwIfAborted();
1160
+ return runtime.dispatch(new Request(url, init));
1161
+ }, "fetch")
1162
+ }
1163
+ );
1164
+ localClients.set(currentRequest, local);
1165
+ }
1166
+ return local.request(path, method, input, clientOptions);
1167
+ },
1168
+ routeMeta,
1169
+ "/api",
1170
+ true,
1171
+ options.integrations === false ? void 0 : {
1172
+ integrations: integrationsServer({
1173
+ baseURL: options.baseURL,
1174
+ headers: options.headers,
1175
+ credentials: options.credentials,
1176
+ timeoutMs: options.timeoutMs,
1177
+ fetch: options.fetch,
1178
+ onRequest: options.onRequest,
1179
+ onResponse: options.onResponse,
1180
+ onError: options.onError,
1181
+ ...options.integrations
1182
+ })
1183
+ },
1184
+ options.routes ? new ClientRouteManifest(options.routes) : void 0
1185
+ );
1186
+ return {
1187
+ api,
1188
+ apiClient: createAPIClient(options)
1189
+ };
1190
+ }
1191
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createApiClients, "createApiClients");
1192
+ function createAPIClient(options = {}) {
1193
+ return createAPIClientRuntime(options).client;
1194
+ }
1195
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createAPIClient, "createAPIClient");
1196
+ function createAPIClientRuntime(options = {}, transport) {
1197
+ _nullishCoalesce(options, () => ( (options = {})));
1198
+ const baseURL = options.baseURL || _chunkS3A45T7Fcjs.getFarmAPIBaseURL.call(void 0, );
1199
+ const httpFetch = options.fetch;
1200
+ const integrationOptions = options.integrations === false ? false : {
1201
+ baseURL: options.baseURL,
1202
+ headers: options.headers,
1203
+ credentials: options.credentials,
1204
+ timeoutMs: options.timeoutMs,
1205
+ fetch: httpFetch,
1206
+ onRequest: options.onRequest,
1207
+ onResponse: options.onResponse,
1208
+ onError: options.onError,
1209
+ ...typeof options.integrations === "object" ? options.integrations : {}
1210
+ };
1211
+ const rootAliases = integrationOptions === false ? void 0 : {
1212
+ integrations: integrationsClient(integrationOptions)
1213
+ };
1214
+ const sharedCacheState = _nullishCoalesce(_optionalChain([transport, 'optionalAccess', _46 => _46.cache]), () => ( _chunkI7PUUDGYcjs.getFarmClientDataCache.call(void 0, )));
1215
+ const localCaches = transport ? /* @__PURE__ */ new Set([sharedCacheState]) : void 0;
1216
+ const sharedInflightState = /* @__PURE__ */ new Map();
1217
+ let scopedRequestState;
1218
+ const routeMeta = _nullishCoalesce(_optionalChain([transport, 'optionalAccess', _47 => _47.routeMeta]), () => ( /* @__PURE__ */ new WeakMap()));
1219
+ let requestCounter = 0;
1220
+ const fetchClient = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (path, requestOptions, defaultHeaders, cancellation) => {
1221
+ const url = _chunkS3A45T7Fcjs.resolveFarmAPIRequestURL.call(void 0, path, baseURL);
1222
+ const method = String(requestOptions.method || "GET").toUpperCase();
1223
+ if (requestOptions.query) {
1224
+ appendAPIQuery(url.searchParams, requestOptions.query);
1225
+ }
1226
+ const headers = new Headers(defaultHeaders);
1227
+ new Headers(requestOptions.headers).forEach((value, key) => headers.set(key, value));
1228
+ const fetchOptions = {
1229
+ method,
1230
+ headers,
1231
+ credentials: options.credentials,
1232
+ signal: cancellation.signal
1233
+ };
1234
+ if (method === "QUERY" && !headers.has("content-type")) {
1235
+ headers.set("content-type", "application/json");
1236
+ }
1237
+ if (requestOptions.body !== void 0) {
1238
+ if (isFormData(requestOptions.body)) {
1239
+ headers.delete("content-type");
1240
+ fetchOptions.body = requestOptions.body;
1241
+ } else {
1242
+ if (!headers.has("content-type")) headers.set("content-type", "application/json");
1243
+ fetchOptions.body = JSON.stringify(requestOptions.body);
1244
+ }
1245
+ }
1246
+ cancellation.check();
1247
+ const response = await (_nullishCoalesce(_nullishCoalesce(_optionalChain([transport, 'optionalAccess', _48 => _48.fetch]), () => ( httpFetch)), () => ( fetch)))(url.toString(), fetchOptions);
1248
+ cancellation.check();
1249
+ const invalidations = _chunkZEG3OPIBcjs.decodeFarmCacheInvalidations.call(void 0,
1250
+ _optionalChain([response, 'access', _49 => _49.headers, 'optionalAccess', _50 => _50.get, 'optionalCall', _51 => _51(_chunkZEG3OPIBcjs.FARM_CACHE_INVALIDATION_HEADER)])
1251
+ );
1252
+ if (transport) {
1253
+ for (const cache of localCaches) {
1254
+ for (const key of invalidations) cache.invalidate(key);
1255
+ }
1256
+ } else {
1257
+ _chunkZEG3OPIBcjs.applyFarmCacheInvalidations.call(void 0, invalidations);
1258
+ }
1259
+ let data;
1260
+ try {
1261
+ data = await readAPIResponseData(response, method);
1262
+ cancellation.check();
1263
+ } catch (decodeError) {
1264
+ if (!(decodeError instanceof APIResponseDecodeError)) throw decodeError;
1265
+ if (response.ok) throw decodeError.cause;
1266
+ return { response, data: void 0, decodeError: decodeError.cause };
1267
+ }
1268
+ return { response, data };
1269
+ }, "fetchClient");
1270
+ const request = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (path, method, input = {}, clientOptions) => {
1271
+ const maxRetries = _chunkLTNGXMQ6cjs.resolveClientRetryCount.call(void 0, _optionalChain([clientOptions, 'optionalAccess', _52 => _52.retry, 'optionalAccess', _53 => _53.count]));
1272
+ if (typeof _optionalChain([clientOptions, 'optionalAccess', _54 => _54.retry, 'optionalAccess', _55 => _55.delay]) !== "function") {
1273
+ _chunkLTNGXMQ6cjs.resolveClientRetryDelay.call(void 0, _optionalChain([clientOptions, 'optionalAccess', _56 => _56.retry, 'optionalAccess', _57 => _57.delay]));
1274
+ }
1275
+ const cancellation = _chunkJ7FSKED3cjs.createClientCancellation.call(void 0,
1276
+ _optionalChain([clientOptions, 'optionalAccess', _58 => _58.signal]),
1277
+ _nullishCoalesce(_optionalChain([clientOptions, 'optionalAccess', _59 => _59.timeoutMs]), () => ( options.timeoutMs)),
1278
+ _optionalChain([transport, 'optionalAccess', _60 => _60.signal])
1279
+ );
1280
+ const normalizeCallError = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (error) => {
1281
+ if (!_optionalChain([cancellation, 'access', _61 => _61.signal, 'optionalAccess', _62 => _62.aborted])) return normalizeError(error);
1282
+ const normalized = new APIClientError(
1283
+ cancellation.timedOut ? "timeout" : "aborted",
1284
+ void 0,
1285
+ {
1286
+ status: 0,
1287
+ message: cancellation.timedOut ? "Client request timed out" : "Client request aborted"
1288
+ }
1289
+ );
1290
+ normalized.cause = cancellation.signal.reason;
1291
+ return normalized;
1292
+ }, "normalizeCallError");
1293
+ try {
1294
+ const methodUpper = method.toUpperCase();
1295
+ const requestId = `${Date.now()}-${++requestCounter}`;
1296
+ const defaultHeaders = new Headers(_optionalChain([transport, 'optionalAccess', _63 => _63.headers]));
1297
+ let requestContextError;
1298
+ try {
1299
+ cancellation.check();
1300
+ const resolved = resolveClientHeaders(options.headers);
1301
+ const headers = resolved instanceof Headers ? resolved : await cancellation.run(() => resolved);
1302
+ cancellation.check();
1303
+ headers.forEach((value, name) => defaultHeaders.set(name, value));
1304
+ } catch (error) {
1305
+ requestContextError = normalizeCallError(error);
1306
+ }
1307
+ const cacheOptions = _optionalChain([clientOptions, 'optionalAccess', _64 => _64.cache]) ? {
1308
+ ...options.cacheDefaults,
1309
+ ...clientOptions.cache
1310
+ } : void 0;
1311
+ const configuredCacheKey = _nullishCoalesce(_optionalChain([clientOptions, 'optionalAccess', _65 => _65.key]), () => ( _optionalChain([cacheOptions, 'optionalAccess', _66 => _66.key])));
1312
+ const cacheKey = _chunkI7PUUDGYcjs.normalizeFarmClientCacheKey.call(void 0,
1313
+ _nullishCoalesce(configuredCacheKey, () => ( buildCacheKey(methodUpper, path, input, baseURL, defaultHeaders)))
1314
+ );
1315
+ const now = Date.now();
1316
+ const emitStatus = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (phase, payload) => {
1317
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0,
1318
+ _optionalChain([clientOptions, 'optionalAccess', _67 => _67.onStatus]),
1319
+ [
1320
+ {
1321
+ phase,
1322
+ requestId,
1323
+ method: methodUpper,
1324
+ key: cacheKey,
1325
+ input,
1326
+ timestamp: Date.now(),
1327
+ ...payload
1328
+ }
1329
+ ],
1330
+ "API client onStatus"
1331
+ );
1332
+ }, "emitStatus");
1333
+ const policy = _nullishCoalesce(_optionalChain([cacheOptions, 'optionalAccess', _68 => _68.policy]), () => ( (cacheOptions ? "cache-first" : "network-only")));
1334
+ const staleTime = _nullishCoalesce(_optionalChain([cacheOptions, 'optionalAccess', _69 => _69.staleTime]), () => ( 0));
1335
+ const hasReliableDefaultCacheKey = methodUpper !== "QUERY" || !isFormData(_optionalChain([input, 'optionalAccess', _70 => _70.body])) || configuredCacheKey !== void 0;
1336
+ const isCacheEnabled = Boolean(cacheOptions) && (methodUpper === "GET" || methodUpper === "QUERY") && hasReliableDefaultCacheKey;
1337
+ const needsCacheState = isCacheEnabled || Boolean(_optionalChain([clientOptions, 'optionalAccess', _71 => _71.optimistic, 'optionalAccess', _72 => _72.update, 'optionalAccess', _73 => _73.length])) || Boolean(_optionalChain([clientOptions, 'optionalAccess', _74 => _74.invalidate]));
1338
+ let requestCacheContext = void 0;
1339
+ if (needsCacheState && !requestContextError) {
1340
+ try {
1341
+ requestCacheContext = getRequestCacheContext(
1342
+ { headers: defaultHeaders, credentials: options.credentials },
1343
+ input,
1344
+ // Custom transports can inject an identity outside visible headers.
1345
+ // Never share their cached data with other client instances.
1346
+ httpFetch ? "client" : _optionalChain([cacheOptions, 'optionalAccess', _75 => _75.scope])
1347
+ );
1348
+ } catch (error) {
1349
+ requestContextError = normalizeError(error);
1350
+ }
1351
+ }
1352
+ let cacheState = sharedCacheState;
1353
+ let inflightState = sharedInflightState;
1354
+ let requestScopedState;
1355
+ if (requestCacheContext !== void 0) {
1356
+ if (scopedRequestState && scopedRequestState.context !== requestCacheContext) {
1357
+ scopedRequestState.retired = true;
1358
+ if (scopedRequestState.inflight.size === 0) scopedRequestState.cache.dispose();
1359
+ scopedRequestState = void 0;
1360
+ }
1361
+ _nullishCoalesce(scopedRequestState, () => ( (scopedRequestState = {
1362
+ context: requestCacheContext,
1363
+ cache: new (0, _chunkI7PUUDGYcjs.FarmClientDataCache)({ subscribeToInvalidation: !transport }),
1364
+ inflight: /* @__PURE__ */ new Map(),
1365
+ retired: false
1366
+ })));
1367
+ requestScopedState = scopedRequestState;
1368
+ cacheState = requestScopedState.cache;
1369
+ _optionalChain([localCaches, 'optionalAccess', _76 => _76.add, 'call', _77 => _77(cacheState)]);
1370
+ inflightState = requestScopedState.inflight;
1371
+ }
1372
+ const optimisticState = getOptimisticState(cacheState);
1373
+ const entry = getValidCacheEntry(cacheState, cacheKey, now);
1374
+ const isStale = entry ? isEntryStale(entry, now) : true;
1375
+ const applyOptimisticUpdates = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => {
1376
+ if (!_optionalChain([clientOptions, 'optionalAccess', _78 => _78.optimistic, 'optionalAccess', _79 => _79.update, 'optionalAccess', _80 => _80.length])) return [];
1377
+ const snapshots = /* @__PURE__ */ new Map();
1378
+ for (const update of clientOptions.optimistic.update) {
1379
+ const [target, targetInput, updater] = update.length === 2 ? [update[0], void 0, update[1]] : [update[0], update[1], update[2]];
1380
+ const targetKey = resolveTargetKey(
1381
+ routeMeta,
1382
+ target,
1383
+ targetInput,
1384
+ baseURL,
1385
+ defaultHeaders,
1386
+ transport ? baseURL : void 0
1387
+ );
1388
+ if (!targetKey) continue;
1389
+ const targetEntry = getValidCacheEntry(cacheState, targetKey, now);
1390
+ const currentEntry = cacheState.get(targetKey);
1391
+ let stack = optimisticState.get(targetKey);
1392
+ if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {
1393
+ stack = void 0;
1394
+ }
1395
+ if (!stack) {
1396
+ stack = {
1397
+ entry: targetEntry ? { ...targetEntry } : void 0,
1398
+ layers: [],
1399
+ renderedEntry: currentEntry
1400
+ };
1401
+ optimisticState.set(targetKey, stack);
1402
+ }
1403
+ let snapshot = snapshots.get(targetKey);
1404
+ if (!snapshot) {
1405
+ const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;
1406
+ const layer = {
1407
+ updaters: [],
1408
+ updatedAt: now,
1409
+ staleAt: _nullishCoalesce(_optionalChain([targetEntry, 'optionalAccess', _81 => _81.staleAt]), () => ( now + (_nullishCoalesce(_nullishCoalesce(_optionalChain([cacheOptions, 'optionalAccess', _82 => _82.staleTime]), () => ( _optionalChain([options, 'access', _83 => _83.cacheDefaults, 'optionalAccess', _84 => _84.staleTime]))), () => ( 0))))),
1410
+ gcAt: _nullishCoalesce(_optionalChain([targetEntry, 'optionalAccess', _85 => _85.gcAt]), () => ( getGcAt(now, _nullishCoalesce(_optionalChain([cacheOptions, 'optionalAccess', _86 => _86.gcTime]), () => ( _optionalChain([options, 'access', _87 => _87.cacheDefaults, 'optionalAccess', _88 => _88.gcTime]))))))
1411
+ };
1412
+ stack.layers.push(layer);
1413
+ snapshot = {
1414
+ key: targetKey,
1415
+ stack,
1416
+ layer
1417
+ };
1418
+ snapshots.set(targetKey, snapshot);
1419
+ snapshot.layer.updaters.push(updater);
1420
+ const nextEntry2 = applyOptimisticLayer(previousEntry, {
1421
+ ...snapshot.layer,
1422
+ updaters: [updater]
1423
+ });
1424
+ storeOptimisticEntry(cacheState, targetKey, stack, nextEntry2);
1425
+ continue;
1426
+ }
1427
+ snapshot.layer.updaters.push(updater);
1428
+ const nextEntry = applyOptimisticLayer(stack.renderedEntry, {
1429
+ ...snapshot.layer,
1430
+ updaters: [updater]
1431
+ });
1432
+ storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);
1433
+ }
1434
+ return Array.from(snapshots.values());
1435
+ }, "applyOptimisticUpdates");
1436
+ const rollbackOptimisticUpdates = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (snapshots) => {
1437
+ if (!_optionalChain([clientOptions, 'optionalAccess', _89 => _89.optimistic, 'optionalAccess', _90 => _90.rollbackOnError])) return;
1438
+ settleOptimisticUpdates(cacheState, optimisticState, snapshots, "rollback");
1439
+ }, "rollbackOptimisticUpdates");
1440
+ const invalidateUncommittedOptimisticUpdates = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (snapshots) => {
1441
+ if (_optionalChain([clientOptions, 'optionalAccess', _91 => _91.optimistic, 'optionalAccess', _92 => _92.rollbackOnError])) return;
1442
+ for (const key of settleOptimisticUpdates(
1443
+ cacheState,
1444
+ optimisticState,
1445
+ snapshots,
1446
+ "invalidate"
1447
+ )) {
1448
+ emitStatus("invalidated", { key });
1449
+ }
1450
+ }, "invalidateUncommittedOptimisticUpdates");
1451
+ const executeNetwork = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async (opts) => {
1452
+ const release = cancellation.hold();
1453
+ let unsubscribeInvalidation;
1454
+ let readOwners;
1455
+ let readOwner;
1456
+ const resolvedCacheKey = cacheState.resolveKey(cacheKey);
1457
+ try {
1458
+ const dedupeMs = _nullishCoalesce(_optionalChain([cacheOptions, 'optionalAccess', _93 => _93.dedupeMs]), () => ( 0));
1459
+ const inflight = inflightState.get(cacheKey);
1460
+ const allowDedupe = isCacheEnabled && dedupeMs > 0 && !cancellation.signal && !requestContextError;
1461
+ if (allowDedupe && inflight && !inflight.cancellable && now - inflight.startedAt < dedupeMs) {
1462
+ emitStatus("pending", { isBackground: _optionalChain([opts, 'optionalAccess', _94 => _94.isBackground]), data: _optionalChain([entry, 'optionalAccess', _95 => _95.data]) });
1463
+ const result2 = await inflight.promise;
1464
+ if (result2.error) {
1465
+ emitStatus("error", { error: result2.error, isBackground: _optionalChain([opts, 'optionalAccess', _96 => _96.isBackground]) });
1466
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onError, [result2.error]);
1467
+ if (_optionalChain([opts, 'optionalAccess', _97 => _97.callCallbacks]) !== false) {
1468
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, _optionalChain([clientOptions, 'optionalAccess', _98 => _98.onError]), [result2.error], "API client onError");
1469
+ }
1470
+ } else {
1471
+ emitStatus("success", { data: result2.data, isBackground: _optionalChain([opts, 'optionalAccess', _99 => _99.isBackground]) });
1472
+ if (_optionalChain([opts, 'optionalAccess', _100 => _100.callCallbacks]) !== false) {
1473
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0,
1474
+ _optionalChain([clientOptions, 'optionalAccess', _101 => _101.onSuccess]),
1475
+ [result2.data],
1476
+ "API client onSuccess"
1477
+ );
1478
+ }
1479
+ }
1480
+ return result2;
1481
+ }
1482
+ let invalidatedDuringRequest = false;
1483
+ if (isCacheEnabled) {
1484
+ readOwners = getCacheReadOwners(cacheState);
1485
+ readOwner = {};
1486
+ readOwners.set(resolvedCacheKey, readOwner);
1487
+ unsubscribeInvalidation = cacheState.subscribe(cacheKey, (event) => {
1488
+ if (event === "invalidate") invalidatedDuringRequest = true;
1489
+ });
1490
+ }
1491
+ emitStatus(_optionalChain([opts, 'optionalAccess', _102 => _102.isBackground]) ? "revalidating" : "pending", {
1492
+ isBackground: _optionalChain([opts, 'optionalAccess', _103 => _103.isBackground])
1493
+ });
1494
+ const promise = (async () => {
1495
+ const shouldRetryFailure = _nullishCoalesce(_optionalChain([clientOptions, 'optionalAccess', _104 => _104.retry, 'optionalAccess', _105 => _105.shouldRetry]), () => ( isFarmRetryableFailure));
1496
+ let attempt = 0;
1497
+ while (true) {
1498
+ if (options.onRequest || _optionalChain([clientOptions, 'optionalAccess', _106 => _106.onRequest])) {
1499
+ const requestEvent = {
1500
+ requestId,
1501
+ method: methodUpper,
1502
+ key: cacheKey,
1503
+ path,
1504
+ input,
1505
+ attempt,
1506
+ timestamp: Date.now()
1507
+ };
1508
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onRequest, [requestEvent]);
1509
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0,
1510
+ _optionalChain([clientOptions, 'optionalAccess', _107 => _107.onRequest]),
1511
+ [requestEvent],
1512
+ "API client onRequest"
1513
+ );
1514
+ }
1515
+ try {
1516
+ if (requestContextError) throw requestContextError;
1517
+ const { response, data, decodeError } = await cancellation.run(
1518
+ () => fetchClient(
1519
+ path,
1520
+ {
1521
+ ...input,
1522
+ method: methodUpper
1523
+ },
1524
+ defaultHeaders,
1525
+ cancellation
1526
+ )
1527
+ );
1528
+ const error = response.ok ? null : createResponseError2(response, data, decodeError);
1529
+ const responseEvent = {
1530
+ requestId,
1531
+ method: methodUpper,
1532
+ key: cacheKey,
1533
+ path,
1534
+ input,
1535
+ attempt,
1536
+ timestamp: Date.now(),
1537
+ response,
1538
+ data: response.ok ? data : void 0,
1539
+ error: _nullishCoalesce(error, () => ( void 0)),
1540
+ ok: response.ok,
1541
+ status: response.status
1542
+ };
1543
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onResponse, [
1544
+ response.ok ? data : void 0,
1545
+ error,
1546
+ responseEvent
1547
+ ]);
1548
+ notifyResponseObserver(
1549
+ _optionalChain([clientOptions, 'optionalAccess', _108 => _108.onResponse]),
1550
+ response.ok ? data : void 0,
1551
+ error,
1552
+ responseEvent
1553
+ );
1554
+ if (!error) {
1555
+ return { data, error: null, key: cacheKey };
1556
+ }
1557
+ if (attempt >= maxRetries || !shouldRetryFailure({
1558
+ attempt,
1559
+ method: methodUpper,
1560
+ status: response.status,
1561
+ error
1562
+ })) {
1563
+ return { data: void 0, error, key: cacheKey };
1564
+ }
1565
+ } catch (err) {
1566
+ const error = normalizeCallError(err);
1567
+ const responseEvent = {
1568
+ requestId,
1569
+ method: methodUpper,
1570
+ key: cacheKey,
1571
+ path,
1572
+ input,
1573
+ attempt,
1574
+ timestamp: Date.now(),
1575
+ error,
1576
+ ok: false
1577
+ };
1578
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onResponse, [void 0, error, responseEvent]);
1579
+ notifyResponseObserver(_optionalChain([clientOptions, 'optionalAccess', _109 => _109.onResponse]), void 0, error, responseEvent);
1580
+ if (attempt >= maxRetries || requestContextError || _optionalChain([cancellation, 'access', _110 => _110.signal, 'optionalAccess', _111 => _111.aborted]) || !shouldRetryFailure({ attempt, method: methodUpper, error })) {
1581
+ return { data: void 0, error, key: cacheKey };
1582
+ }
1583
+ }
1584
+ attempt += 1;
1585
+ const delay = _chunkLTNGXMQ6cjs.resolveClientRetryDelay.call(void 0,
1586
+ typeof _optionalChain([clientOptions, 'optionalAccess', _112 => _112.retry, 'optionalAccess', _113 => _113.delay]) === "function" ? clientOptions.retry.delay(attempt) : _optionalChain([clientOptions, 'optionalAccess', _114 => _114.retry, 'optionalAccess', _115 => _115.delay])
1587
+ );
1588
+ if (delay > 0) {
1589
+ try {
1590
+ await cancellation.delay(delay);
1591
+ } catch (error) {
1592
+ return { data: void 0, error: normalizeCallError(error), key: cacheKey };
1593
+ }
1594
+ }
1595
+ }
1596
+ })();
1597
+ const inflightEntry = {
1598
+ promise,
1599
+ startedAt: now,
1600
+ cancellable: !!cancellation.signal || !!requestContextError
1601
+ };
1602
+ inflightState.set(cacheKey, inflightEntry);
1603
+ try {
1604
+ const result2 = await promise;
1605
+ if (inflightState.get(cacheKey) === inflightEntry && _optionalChain([readOwners, 'optionalAccess', _116 => _116.get, 'call', _117 => _117(resolvedCacheKey)]) === readOwner && !invalidatedDuringRequest && !result2.error && isCacheEnabled && !_chunkARJWXNQLcjs.isFarmAPIStream.call(void 0, result2.data)) {
1606
+ const updatedAt = Date.now();
1607
+ const cached = {
1608
+ data: result2.data,
1609
+ updatedAt,
1610
+ staleAt: updatedAt + staleTime,
1611
+ gcAt: getGcAt(updatedAt, _optionalChain([cacheOptions, 'optionalAccess', _118 => _118.gcTime])),
1612
+ invalidatedAt: void 0,
1613
+ persist: _optionalChain([cacheOptions, 'optionalAccess', _119 => _119.persist]) === true ? true : void 0,
1614
+ [API_CACHE_REFETCH]: createCacheRefetch(
1615
+ request,
1616
+ path,
1617
+ method,
1618
+ input,
1619
+ cacheKey,
1620
+ cacheOptions,
1621
+ clientOptions,
1622
+ options.onError
1623
+ )
1624
+ };
1625
+ cacheState.set(cacheKey, cached);
1626
+ }
1627
+ if (result2.error) {
1628
+ emitStatus("error", { error: result2.error, isBackground: _optionalChain([opts, 'optionalAccess', _120 => _120.isBackground]) });
1629
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, options.onError, [result2.error]);
1630
+ if (_optionalChain([opts, 'optionalAccess', _121 => _121.callCallbacks]) !== false) {
1631
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, _optionalChain([clientOptions, 'optionalAccess', _122 => _122.onError]), [result2.error], "API client onError");
1632
+ }
1633
+ } else {
1634
+ emitStatus("success", { data: result2.data, isBackground: _optionalChain([opts, 'optionalAccess', _123 => _123.isBackground]) });
1635
+ if (_optionalChain([opts, 'optionalAccess', _124 => _124.callCallbacks]) !== false) {
1636
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0,
1637
+ _optionalChain([clientOptions, 'optionalAccess', _125 => _125.onSuccess]),
1638
+ [result2.data],
1639
+ "API client onSuccess"
1640
+ );
1641
+ }
1642
+ }
1643
+ return result2;
1644
+ } finally {
1645
+ if (inflightState.get(cacheKey) === inflightEntry) {
1646
+ inflightState.delete(cacheKey);
1647
+ }
1648
+ if (requestContextError && requestScopedState) {
1649
+ requestScopedState.retired = true;
1650
+ if (scopedRequestState === requestScopedState) scopedRequestState = void 0;
1651
+ }
1652
+ if (_optionalChain([requestScopedState, 'optionalAccess', _126 => _126.retired]) && requestScopedState.inflight.size === 0) {
1653
+ requestScopedState.cache.dispose();
1654
+ }
1655
+ }
1656
+ } finally {
1657
+ if (readOwner && _optionalChain([readOwners, 'optionalAccess', _127 => _127.get, 'call', _128 => _128(resolvedCacheKey)]) === readOwner) {
1658
+ readOwners.delete(resolvedCacheKey);
1659
+ }
1660
+ _optionalChain([unsubscribeInvalidation, 'optionalCall', _129 => _129()]);
1661
+ release();
1662
+ }
1663
+ }, "executeNetwork");
1664
+ const invalidateTargets = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, async () => {
1665
+ if (!_optionalChain([clientOptions, 'optionalAccess', _130 => _130.invalidate])) return;
1666
+ const invalidateOptions = Array.isArray(clientOptions.invalidate) ? { targets: clientOptions.invalidate, refetch: false } : {
1667
+ targets: clientOptions.invalidate.targets,
1668
+ refetch: _nullishCoalesce(clientOptions.invalidate.refetch, () => ( false))
1669
+ };
1670
+ const refetches = /* @__PURE__ */ new Set();
1671
+ for (const target of invalidateOptions.targets) {
1672
+ const targetKey = resolveTargetKey(
1673
+ routeMeta,
1674
+ target,
1675
+ void 0,
1676
+ baseURL,
1677
+ defaultHeaders,
1678
+ transport ? baseURL : void 0
1679
+ );
1680
+ if (!targetKey) continue;
1681
+ const existing = cacheState.get(targetKey);
1682
+ const invalidatedAt = Date.now();
1683
+ cacheState.invalidate(targetKey, invalidatedAt);
1684
+ if (existing) {
1685
+ const stack = optimisticState.get(targetKey);
1686
+ if (_optionalChain([stack, 'optionalAccess', _131 => _131.renderedEntry]) === existing) {
1687
+ stack.invalidatedAt = invalidatedAt;
1688
+ stack.renderedEntry = cacheState.get(targetKey);
1689
+ }
1690
+ }
1691
+ emitStatus("invalidated", { key: targetKey });
1692
+ const refetch = _optionalChain([existing, 'optionalAccess', _132 => _132[API_CACHE_REFETCH]]);
1693
+ if (invalidateOptions.refetch && refetch) {
1694
+ refetches.add(refetch);
1695
+ }
1696
+ }
1697
+ for (const refetch of refetches) refetch();
1698
+ }, "invalidateTargets");
1699
+ const optimisticSnapshots = requestContextError ? [] : applyOptimisticUpdates();
1700
+ if (isCacheEnabled && !requestContextError && !_optionalChain([cancellation, 'access', _133 => _133.signal, 'optionalAccess', _134 => _134.aborted])) {
1701
+ if (entry && !isStale && policy !== "network-only") {
1702
+ emitStatus("success", { data: entry.data });
1703
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, _optionalChain([clientOptions, 'optionalAccess', _135 => _135.onSuccess]), [entry.data], "API client onSuccess");
1704
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0,
1705
+ _optionalChain([clientOptions, 'optionalAccess', _136 => _136.onSettled]),
1706
+ [entry.data, null],
1707
+ "API client onSettled"
1708
+ );
1709
+ return { data: entry.data, error: null, key: cacheKey };
1710
+ }
1711
+ if (entry && isStale && policy === "stale-while-revalidate") {
1712
+ emitStatus("success", { data: entry.data });
1713
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, _optionalChain([clientOptions, 'optionalAccess', _137 => _137.onSuccess]), [entry.data], "API client onSuccess");
1714
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0,
1715
+ _optionalChain([clientOptions, 'optionalAccess', _138 => _138.onSettled]),
1716
+ [entry.data, null],
1717
+ "API client onSettled"
1718
+ );
1719
+ void executeNetwork({ isBackground: true, callCallbacks: false });
1720
+ return { data: entry.data, error: null, key: cacheKey };
1721
+ }
1722
+ }
1723
+ const result = await executeNetwork();
1724
+ if (result.error) {
1725
+ if (_optionalChain([cancellation, 'access', _139 => _139.signal, 'optionalAccess', _140 => _140.aborted])) {
1726
+ settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, "rollback");
1727
+ } else {
1728
+ rollbackOptimisticUpdates(optimisticSnapshots);
1729
+ invalidateUncommittedOptimisticUpdates(optimisticSnapshots);
1730
+ }
1731
+ } else {
1732
+ settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, "commit");
1733
+ await invalidateTargets();
1734
+ }
1735
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0,
1736
+ _optionalChain([clientOptions, 'optionalAccess', _141 => _141.onSettled]),
1737
+ [result.data, result.error],
1738
+ "API client onSettled"
1739
+ );
1740
+ return result;
1741
+ } finally {
1742
+ cancellation.dispose();
1743
+ }
1744
+ }, "request");
1745
+ const client = createNestedProxy(
1746
+ [],
1747
+ request,
1748
+ routeMeta,
1749
+ baseURL,
1750
+ isSameOriginAPIBaseURL(baseURL),
1751
+ rootAliases,
1752
+ options.routes ? new ClientRouteManifest(options.routes) : void 0
1753
+ );
1754
+ return { client, request };
1755
+ }
1756
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createAPIClientRuntime, "createAPIClientRuntime");
1757
+ async function readAPIResponseData(response, method) {
1758
+ if (method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304) {
1759
+ return void 0;
1760
+ }
1761
+ if (!_optionalChain([response, 'access', _142 => _142.headers, 'optionalAccess', _143 => _143.get]) && typeof response.json === "function") {
1762
+ return readResponseJSON(response);
1763
+ }
1764
+ if (response.body === null) return void 0;
1765
+ if (_chunkARJWXNQLcjs.isJSONStreamResponse.call(void 0, response)) {
1766
+ return _chunkARJWXNQLcjs.readJSONStream.call(void 0, response);
1767
+ }
1768
+ const contentType = _optionalChain([response, 'access', _144 => _144.headers, 'access', _145 => _145.get, 'call', _146 => _146("content-type"), 'optionalAccess', _147 => _147.split, 'call', _148 => _148(";", 1), 'access', _149 => _149[0], 'optionalAccess', _150 => _150.trim, 'call', _151 => _151(), 'access', _152 => _152.toLowerCase, 'call', _153 => _153()]);
1769
+ if (typeof response.arrayBuffer === "function") {
1770
+ const data = await response.arrayBuffer();
1771
+ if (data.byteLength === 0) return void 0;
1772
+ if (!contentType || contentType === "application/json" || contentType.endsWith("+json")) {
1773
+ return parseResponseJSON(new TextDecoder().decode(data));
1774
+ }
1775
+ if (contentType.startsWith("text/") || contentType === "application/xml" || contentType === "application/xhtml+xml" || contentType === "application/graphql") {
1776
+ return new TextDecoder().decode(data);
1777
+ }
1778
+ return data;
1779
+ }
1780
+ if ((!contentType || contentType === "application/json" || contentType.endsWith("+json")) && typeof response.json === "function") {
1781
+ return readResponseJSON(response);
1782
+ }
1783
+ if ((_optionalChain([contentType, 'optionalAccess', _154 => _154.startsWith, 'call', _155 => _155("text/")]) || contentType === "application/xml" || contentType === "application/xhtml+xml" || contentType === "application/graphql") && typeof response.text === "function") {
1784
+ return response.text();
1785
+ }
1786
+ if (typeof response.json === "function") {
1787
+ return readResponseJSON(response);
1788
+ }
1789
+ return void 0;
1790
+ }
1791
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readAPIResponseData, "readAPIResponseData");
1792
+ var _APIResponseDecodeError = class _APIResponseDecodeError extends Error {
1793
+ constructor(cause) {
1794
+ super(cause instanceof Error ? cause.message : "Failed to decode JSON response");
1795
+ this.name = "APIResponseDecodeError";
1796
+ this.cause = cause;
1797
+ }
1798
+ };
1799
+ _chunkS3JO3N4Hcjs.__name.call(void 0, _APIResponseDecodeError, "APIResponseDecodeError");
1800
+ var APIResponseDecodeError = _APIResponseDecodeError;
1801
+ function parseResponseJSON(value) {
1802
+ try {
1803
+ return JSON.parse(value);
1804
+ } catch (error) {
1805
+ throw new APIResponseDecodeError(error);
1806
+ }
1807
+ }
1808
+ _chunkS3JO3N4Hcjs.__name.call(void 0, parseResponseJSON, "parseResponseJSON");
1809
+ async function readResponseJSON(response) {
1810
+ try {
1811
+ return await response.json();
1812
+ } catch (error) {
1813
+ if (error instanceof SyntaxError) throw new APIResponseDecodeError(error);
1814
+ throw error;
1815
+ }
1816
+ }
1817
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readResponseJSON, "readResponseJSON");
1818
+ function createNestedProxy(path, client, routeMeta, baseURL, sameOrigin, rootAliases, manifest, bound = {}) {
1819
+ const target = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => {
1820
+ }, "target");
1821
+ const proxy = new Proxy(target, {
1822
+ // When accessing a property (api.hello)
1823
+ get(_target, prop) {
1824
+ if (prop === "then") return void 0;
1825
+ if (prop === "$params") {
1826
+ return (params) => {
1827
+ if (!manifest)
1828
+ throw new TypeError(
1829
+ "$params requires createAPIClient({ routes: apiRoutes }) from the generated API manifest."
1830
+ );
1831
+ const scope = manifest.bind(buildProxyRoutePath(path), params);
1832
+ return createNestedProxy(
1833
+ [...path, scope.segment],
1834
+ client,
1835
+ routeMeta,
1836
+ baseURL,
1837
+ sameOrigin,
1838
+ rootAliases,
1839
+ manifest,
1840
+ Object.freeze({ ...bound, ...scope.params })
1841
+ );
1842
+ };
1843
+ }
1844
+ if (prop === FARM_API_ROUTE_REF_SYMBOL) {
1845
+ return path.length > 0;
1846
+ }
1847
+ if (prop === FARM_API_ROUTE_META_SYMBOL) {
1848
+ let metadata;
1849
+ try {
1850
+ metadata = resolveRouteMeta({ path, baseURL, manifest, bound });
1851
+ } catch (e3) {
1852
+ return null;
1853
+ }
1854
+ const requestURL = _chunkS3A45T7Fcjs.resolveFarmAPIRequestURL.call(void 0, metadata.routePath, baseURL);
1855
+ return Object.freeze({
1856
+ path: `${requestURL.pathname}${requestURL.search}${requestURL.hash}`,
1857
+ method: metadata.method,
1858
+ baseURL: requestURL.origin,
1859
+ sameOrigin
1860
+ });
1861
+ }
1862
+ if (path.length === 0 && typeof prop === "string" && rootAliases && Object.prototype.hasOwnProperty.call(rootAliases, prop)) {
1863
+ return rootAliases[prop];
1864
+ }
1865
+ if (typeof prop !== "string") {
1866
+ return Reflect.get(_target, prop);
1867
+ }
1868
+ return createNestedProxy(
1869
+ [...path, prop],
1870
+ client,
1871
+ routeMeta,
1872
+ baseURL,
1873
+ sameOrigin,
1874
+ rootAliases,
1875
+ manifest,
1876
+ bound
1877
+ );
1878
+ },
1879
+ // When calling as a function
1880
+ apply(_target, _thisArg, args) {
1881
+ const lastPart = path[path.length - 1];
1882
+ const httpMethods = ["get", "head", "query", "post", "put", "delete", "patch", "options"];
1883
+ if (httpMethods.includes(lastPart)) {
1884
+ const routePath = buildProxyRoutePath(path.slice(0, -1));
1885
+ const method = lastPart.toUpperCase();
1886
+ const [options, clientOptions] = args;
1887
+ const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;
1888
+ if (!manifest && _optionalChain([options, 'optionalAccess', _156 => _156.params]))
1889
+ throw new TypeError("Dynamic params require the generated routes manifest.");
1890
+ return client(resolved, method, options, clientOptions);
1891
+ } else {
1892
+ const routePath = buildProxyRoutePath(path);
1893
+ const [options, clientOptions] = args;
1894
+ const method = _optionalChain([options, 'optionalAccess', _157 => _157.method]) || "GET";
1895
+ const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;
1896
+ return client(resolved, method, options, clientOptions);
1897
+ }
1898
+ }
1899
+ });
1900
+ routeMeta.set(proxy, { path: [...path], baseURL, manifest, bound });
1901
+ return proxy;
1902
+ }
1903
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createNestedProxy, "createNestedProxy");
1904
+ function buildProxyRoutePath(path) {
1905
+ return "/api/" + path.join("/").replace(/^\/+/, "");
1906
+ }
1907
+ _chunkS3JO3N4Hcjs.__name.call(void 0, buildProxyRoutePath, "buildProxyRoutePath");
1908
+ function isAPIRouteRef(value) {
1909
+ return typeof value === "function" && value[FARM_API_ROUTE_REF_SYMBOL] === true;
1910
+ }
1911
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isAPIRouteRef, "isAPIRouteRef");
1912
+ function getAPIRouteRefMetadata(value) {
1913
+ if (!isAPIRouteRef(value)) return null;
1914
+ const metadata = value[FARM_API_ROUTE_META_SYMBOL];
1915
+ if (!metadata || typeof metadata !== "object") return null;
1916
+ const candidate = metadata;
1917
+ if (typeof candidate.path !== "string" || typeof candidate.method !== "string" || typeof candidate.baseURL !== "string" || typeof candidate.sameOrigin !== "boolean") {
1918
+ return null;
1919
+ }
1920
+ return {
1921
+ path: candidate.path,
1922
+ method: candidate.method,
1923
+ baseURL: candidate.baseURL,
1924
+ sameOrigin: candidate.sameOrigin
1925
+ };
1926
+ }
1927
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getAPIRouteRefMetadata, "getAPIRouteRefMetadata");
1928
+ function createServerAPIClient(endpoints, options = {}) {
1929
+ if (options.integrations === false || Object.prototype.hasOwnProperty.call(endpoints, "integrations")) {
1930
+ return endpoints;
1931
+ }
1932
+ Object.defineProperty(endpoints, "integrations", {
1933
+ get() {
1934
+ return integrationsServer(
1935
+ typeof options.integrations === "object" ? options.integrations : {}
1936
+ );
1937
+ },
1938
+ enumerable: false,
1939
+ configurable: true
1940
+ });
1941
+ return endpoints;
1942
+ }
1943
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createServerAPIClient, "createServerAPIClient");
1944
+ var API_CACHE_REFETCH = /* @__PURE__ */ Symbol.for("farm.api.cache-refetch");
1945
+ function createCacheRefetch(request, path, method, input, key, cache, options, onError) {
1946
+ const readOptions = {
1947
+ cache: { ...cache, key, policy: "network-only", dedupeMs: 0 },
1948
+ retry: _optionalChain([options, 'optionalAccess', _158 => _158.retry]),
1949
+ timeoutMs: _optionalChain([options, 'optionalAccess', _159 => _159.timeoutMs])
1950
+ };
1951
+ return () => {
1952
+ void request(path, method, input, readOptions).catch((error) => {
1953
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, onError, [normalizeError(error)]);
1954
+ });
1955
+ };
1956
+ }
1957
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createCacheRefetch, "createCacheRefetch");
1958
+ var optimisticStates = /* @__PURE__ */ new WeakMap();
1959
+ var cacheReadOwners = /* @__PURE__ */ new WeakMap();
1960
+ function getCacheReadOwners(cache) {
1961
+ let owners = cacheReadOwners.get(cache);
1962
+ if (!owners) {
1963
+ owners = /* @__PURE__ */ new Map();
1964
+ cacheReadOwners.set(cache, owners);
1965
+ }
1966
+ return owners;
1967
+ }
1968
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getCacheReadOwners, "getCacheReadOwners");
1969
+ function getOptimisticState(cache) {
1970
+ let state = optimisticStates.get(cache);
1971
+ if (!state) {
1972
+ state = /* @__PURE__ */ new Map();
1973
+ optimisticStates.set(cache, state);
1974
+ }
1975
+ return state;
1976
+ }
1977
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getOptimisticState, "getOptimisticState");
1978
+ function applyOptimisticLayer(entry, layer) {
1979
+ let data = _optionalChain([entry, 'optionalAccess', _160 => _160.data]);
1980
+ for (const updater of layer.updaters) data = updater(data);
1981
+ return {
1982
+ data,
1983
+ updatedAt: layer.updatedAt,
1984
+ staleAt: _nullishCoalesce(_optionalChain([entry, 'optionalAccess', _161 => _161.staleAt]), () => ( layer.staleAt)),
1985
+ gcAt: _nullishCoalesce(_optionalChain([entry, 'optionalAccess', _162 => _162.gcAt]), () => ( layer.gcAt)),
1986
+ invalidatedAt: _optionalChain([entry, 'optionalAccess', _163 => _163.invalidatedAt]),
1987
+ [API_CACHE_REFETCH]: _optionalChain([entry, 'optionalAccess', _164 => _164[API_CACHE_REFETCH]])
1988
+ };
1989
+ }
1990
+ _chunkS3JO3N4Hcjs.__name.call(void 0, applyOptimisticLayer, "applyOptimisticLayer");
1991
+ function storeOptimisticEntry(cacheState, key, stack, entry) {
1992
+ if (!entry) {
1993
+ cacheState.delete(key);
1994
+ stack.renderedEntry = void 0;
1995
+ return;
1996
+ }
1997
+ cacheState.set(key, entry);
1998
+ if (stack.invalidatedAt !== void 0) {
1999
+ cacheState.invalidate(key, stack.invalidatedAt);
2000
+ }
2001
+ stack.renderedEntry = cacheState.get(key);
2002
+ }
2003
+ _chunkS3JO3N4Hcjs.__name.call(void 0, storeOptimisticEntry, "storeOptimisticEntry");
2004
+ function reconcileOptimisticInvalidation(cacheState, key, stack) {
2005
+ const current = cacheState.get(key);
2006
+ const rendered = stack.renderedEntry;
2007
+ if (current === rendered) return true;
2008
+ if (!current || !rendered || current.data !== rendered.data || current.updatedAt !== rendered.updatedAt || current.gcAt !== rendered.gcAt || current.status !== rendered.status || current.error !== rendered.error || current.fetching !== rendered.fetching || current.staleAt !== 0 || current.invalidatedAt === void 0) {
2009
+ return false;
2010
+ }
2011
+ stack.invalidatedAt = current.invalidatedAt;
2012
+ stack.renderedEntry = current;
2013
+ return true;
2014
+ }
2015
+ _chunkS3JO3N4Hcjs.__name.call(void 0, reconcileOptimisticInvalidation, "reconcileOptimisticInvalidation");
2016
+ function renderOptimisticStack(cacheState, key, stack) {
2017
+ let entry = stack.entry ? { ...stack.entry } : void 0;
2018
+ for (const layer of stack.layers) entry = applyOptimisticLayer(entry, layer);
2019
+ storeOptimisticEntry(cacheState, key, stack, entry);
2020
+ }
2021
+ _chunkS3JO3N4Hcjs.__name.call(void 0, renderOptimisticStack, "renderOptimisticStack");
2022
+ function settleOptimisticUpdates(cacheState, optimisticState, snapshots, outcome) {
2023
+ const settledKeys = [];
2024
+ for (const snapshot of snapshots) {
2025
+ const stack = optimisticState.get(snapshot.key);
2026
+ if (stack !== snapshot.stack) continue;
2027
+ if (!reconcileOptimisticInvalidation(cacheState, snapshot.key, stack)) {
2028
+ optimisticState.delete(snapshot.key);
2029
+ continue;
2030
+ }
2031
+ if (outcome === "rollback") {
2032
+ stack.layers = stack.layers.filter((layer) => layer !== snapshot.layer);
2033
+ } else {
2034
+ snapshot.layer.committed = true;
2035
+ if (outcome === "invalidate") stack.invalidatedAt = Date.now();
2036
+ }
2037
+ while (_optionalChain([stack, 'access', _165 => _165.layers, 'access', _166 => _166[0], 'optionalAccess', _167 => _167.committed])) {
2038
+ stack.entry = applyOptimisticLayer(stack.entry, stack.layers.shift());
2039
+ }
2040
+ renderOptimisticStack(cacheState, snapshot.key, stack);
2041
+ if (stack.layers.length === 0) optimisticState.delete(snapshot.key);
2042
+ settledKeys.push(snapshot.key);
2043
+ }
2044
+ return settledKeys;
2045
+ }
2046
+ _chunkS3JO3N4Hcjs.__name.call(void 0, settleOptimisticUpdates, "settleOptimisticUpdates");
2047
+ function applyServerFnOptimisticUpdates(updates, now = Date.now()) {
2048
+ const cacheState = _chunkI7PUUDGYcjs.getFarmClientDataCache.call(void 0, );
2049
+ const optimisticState = getOptimisticState(cacheState);
2050
+ const snapshots = /* @__PURE__ */ new Map();
2051
+ for (const update of updates) {
2052
+ if (update.length !== 2) continue;
2053
+ const [target, updater] = update;
2054
+ if (typeof updater !== "function") continue;
2055
+ const targetKey = typeof target === "string" || Array.isArray(target) ? _chunkI7PUUDGYcjs.normalizeFarmClientCacheKey.call(void 0, target) : null;
2056
+ if (!targetKey) continue;
2057
+ const targetEntry = getValidCacheEntry(cacheState, targetKey, now);
2058
+ const currentEntry = cacheState.get(targetKey);
2059
+ let stack = optimisticState.get(targetKey);
2060
+ if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {
2061
+ stack = void 0;
2062
+ }
2063
+ if (!stack) {
2064
+ stack = {
2065
+ entry: targetEntry ? { ...targetEntry } : void 0,
2066
+ layers: [],
2067
+ renderedEntry: currentEntry
2068
+ };
2069
+ optimisticState.set(targetKey, stack);
2070
+ }
2071
+ let snapshot = snapshots.get(targetKey);
2072
+ if (!snapshot) {
2073
+ const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;
2074
+ const layer = {
2075
+ updaters: [],
2076
+ updatedAt: now,
2077
+ // A server function has no cache policy of its own; preserve the
2078
+ // target read's freshness metadata when it exists.
2079
+ staleAt: _nullishCoalesce(_optionalChain([targetEntry, 'optionalAccess', _168 => _168.staleAt]), () => ( now)),
2080
+ gcAt: _optionalChain([targetEntry, 'optionalAccess', _169 => _169.gcAt])
2081
+ };
2082
+ stack.layers.push(layer);
2083
+ snapshot = { key: targetKey, stack, layer };
2084
+ snapshots.set(targetKey, snapshot);
2085
+ snapshot.layer.updaters.push(updater);
2086
+ const nextEntry2 = applyOptimisticLayer(previousEntry, {
2087
+ ...snapshot.layer,
2088
+ updaters: [updater]
2089
+ });
2090
+ storeOptimisticEntry(cacheState, targetKey, stack, nextEntry2);
2091
+ continue;
2092
+ }
2093
+ snapshot.layer.updaters.push(updater);
2094
+ const nextEntry = applyOptimisticLayer(stack.renderedEntry, {
2095
+ ...snapshot.layer,
2096
+ updaters: [updater]
2097
+ });
2098
+ storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);
2099
+ }
2100
+ return Array.from(snapshots.values());
2101
+ }
2102
+ _chunkS3JO3N4Hcjs.__name.call(void 0, applyServerFnOptimisticUpdates, "applyServerFnOptimisticUpdates");
2103
+ function settleServerFnOptimisticUpdates(snapshots, outcome) {
2104
+ if (snapshots.length === 0) return;
2105
+ const cacheState = _chunkI7PUUDGYcjs.getFarmClientDataCache.call(void 0, );
2106
+ settleOptimisticUpdates(cacheState, getOptimisticState(cacheState), snapshots, outcome);
2107
+ }
2108
+ _chunkS3JO3N4Hcjs.__name.call(void 0, settleServerFnOptimisticUpdates, "settleServerFnOptimisticUpdates");
2109
+ function resolveServerFnInvalidateTargets(invalidate) {
2110
+ const targets = Array.isArray(invalidate) ? invalidate : invalidate.targets;
2111
+ const keys = [];
2112
+ for (const target of targets) {
2113
+ if (typeof target === "string" || Array.isArray(target)) {
2114
+ if (Array.isArray(target) && typeof target[0] === "function") continue;
2115
+ keys.push(_chunkI7PUUDGYcjs.normalizeFarmClientCacheKey.call(void 0, target));
2116
+ } else if (target && typeof target === "object" && "key" in target) {
2117
+ keys.push(_chunkI7PUUDGYcjs.normalizeFarmClientCacheKey.call(void 0, target.key));
2118
+ }
2119
+ }
2120
+ return keys;
2121
+ }
2122
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveServerFnInvalidateTargets, "resolveServerFnInvalidateTargets");
2123
+ function buildCacheKey(method, path, input, baseURL, defaultHeaders) {
2124
+ const keyInput = input && typeof input === "object" ? {
2125
+ query: input.query,
2126
+ body: input.body,
2127
+ ...method === "QUERY" ? {
2128
+ contentType: _nullishCoalesce(_nullishCoalesce(getHeader(input.headers, "content-type"), () => ( getHeader(defaultHeaders, "content-type"))), () => ( "application/json")),
2129
+ contentEncoding: _nullishCoalesce(getHeader(input.headers, "content-encoding"), () => ( getHeader(defaultHeaders, "content-encoding")))
2130
+ } : {}
2131
+ } : input;
2132
+ const url = _chunkS3A45T7Fcjs.resolveFarmAPIRequestURL.call(void 0, path, baseURL);
2133
+ return `${method}:${url.origin}${url.pathname}:${stableStringify(_nullishCoalesce(keyInput, () => ( {})))}`;
2134
+ }
2135
+ _chunkS3JO3N4Hcjs.__name.call(void 0, buildCacheKey, "buildCacheKey");
2136
+ function isSameOriginAPIBaseURL(baseURL) {
2137
+ if (typeof window === "undefined") return baseURL.startsWith("/");
2138
+ return _chunkS3A45T7Fcjs.resolveFarmAPIRequestURL.call(void 0, "/api", baseURL).origin === window.location.origin;
2139
+ }
2140
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isSameOriginAPIBaseURL, "isSameOriginAPIBaseURL");
2141
+ function stableStringify(value) {
2142
+ if (value === null || value === void 0) return String(value);
2143
+ if (value instanceof Date) return value.toISOString();
2144
+ if (typeof value === "bigint") return `bigint:${value.toString()}`;
2145
+ if (typeof value !== "object") return JSON.stringify(value);
2146
+ if (Array.isArray(value)) {
2147
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
2148
+ }
2149
+ if (value instanceof URLSearchParams) {
2150
+ return `urlsearchparams:${stableStringify(Array.from(value.entries()))}`;
2151
+ }
2152
+ const keys = Object.keys(value).sort();
2153
+ const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
2154
+ return `{${entries.join(",")}}`;
2155
+ }
2156
+ _chunkS3JO3N4Hcjs.__name.call(void 0, stableStringify, "stableStringify");
2157
+ function getHeader(headers, name) {
2158
+ if (!headers || typeof headers !== "object") return void 0;
2159
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
2160
+ return _nullishCoalesce(headers.get(name), () => ( void 0));
2161
+ }
2162
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
2163
+ return _optionalChain([entry, 'optionalAccess', _170 => _170[1]]) === void 0 ? void 0 : String(entry[1]);
2164
+ }
2165
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getHeader, "getHeader");
2166
+ function getRequestCacheContext(options, input, scope) {
2167
+ const credentials = _nullishCoalesce(options.credentials, () => ( "same-origin"));
2168
+ const headers = new Headers(options.headers);
2169
+ const requestHeaders = input && typeof input === "object" && "headers" in input ? input.headers : void 0;
2170
+ if (requestHeaders) {
2171
+ new Headers(requestHeaders).forEach((value, key) => headers.set(key, value));
2172
+ }
2173
+ const carriesBrowserIdentity = credentials !== "omit" || [...headers].length > 0;
2174
+ if (scope !== "client" && !carriesBrowserIdentity) return void 0;
2175
+ return stableStringify({
2176
+ credentials,
2177
+ headers: [...headers].sort(([left], [right]) => left.localeCompare(right))
2178
+ });
2179
+ }
2180
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getRequestCacheContext, "getRequestCacheContext");
2181
+ function getGcAt(now, gcTime) {
2182
+ if (gcTime === void 0) return void 0;
2183
+ if (!Number.isFinite(gcTime) || gcTime <= 0) return now;
2184
+ return now + gcTime;
2185
+ }
2186
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getGcAt, "getGcAt");
2187
+ function getValidCacheEntry(cacheState, key, now) {
2188
+ const entry = cacheState.get(key);
2189
+ if (!entry) return void 0;
2190
+ if (entry.gcAt !== void 0 && now >= entry.gcAt) {
2191
+ cacheState.delete(key);
2192
+ return void 0;
2193
+ }
2194
+ return entry;
2195
+ }
2196
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getValidCacheEntry, "getValidCacheEntry");
2197
+ function isEntryStale(entry, now) {
2198
+ if (entry.invalidatedAt !== void 0) return true;
2199
+ return now >= entry.staleAt;
2200
+ }
2201
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isEntryStale, "isEntryStale");
2202
+ function resolveTargetKey(routeMeta, target, input, baseURL = "http://localhost:3000", defaultHeaders, localBaseURL) {
2203
+ if (!target) return null;
2204
+ if (typeof target === "string") return target;
2205
+ if (typeof target === "function") {
2206
+ const meta = routeMeta.get(target);
2207
+ if (!meta) return null;
2208
+ const { method, routePath } = resolveRouteMeta(meta, input);
2209
+ return buildCacheKey(
2210
+ method,
2211
+ routePath,
2212
+ _nullishCoalesce(input, () => ( {})),
2213
+ _nullishCoalesce(localBaseURL, () => ( meta.baseURL)),
2214
+ defaultHeaders
2215
+ );
2216
+ }
2217
+ if (Array.isArray(target)) {
2218
+ const [route, routeInput] = target;
2219
+ if (typeof route === "function") {
2220
+ return resolveTargetKey(routeMeta, route, routeInput, baseURL, defaultHeaders, localBaseURL);
2221
+ }
2222
+ return _chunkI7PUUDGYcjs.normalizeFarmClientCacheKey.call(void 0, target);
2223
+ }
2224
+ if ("key" in target) return _chunkI7PUUDGYcjs.normalizeFarmClientCacheKey.call(void 0, target.key);
2225
+ if ("path" in target) {
2226
+ const method = _nullishCoalesce(target.method, () => ( "GET"));
2227
+ return buildCacheKey(method, target.path, _nullishCoalesce(target.input, () => ( {})), baseURL, defaultHeaders);
2228
+ }
2229
+ return null;
2230
+ }
2231
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveTargetKey, "resolveTargetKey");
2232
+ function resolveRouteMeta(meta, input) {
2233
+ const httpMethods = ["get", "head", "query", "post", "put", "delete", "patch", "options"];
2234
+ const lastPart = meta.path[meta.path.length - 1];
2235
+ if (lastPart && httpMethods.includes(lastPart)) {
2236
+ return {
2237
+ routePath: meta.manifest ? meta.manifest.resolve(
2238
+ buildProxyRoutePath(meta.path.slice(0, -1)),
2239
+ lastPart.toUpperCase(),
2240
+ _nullishCoalesce(meta.bound, () => ( {})),
2241
+ input
2242
+ ) : buildProxyRoutePath(meta.path.slice(0, -1)),
2243
+ method: lastPart.toUpperCase()
2244
+ };
2245
+ }
2246
+ return {
2247
+ routePath: meta.manifest ? meta.manifest.resolve(buildProxyRoutePath(meta.path), "GET", _nullishCoalesce(meta.bound, () => ( {})), input) : buildProxyRoutePath(meta.path),
2248
+ method: "GET"
2249
+ };
2250
+ }
2251
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveRouteMeta, "resolveRouteMeta");
2252
+ function normalizeError(error) {
2253
+ if (error instanceof APIClientError) return error;
2254
+ const normalized = new APIClientError("network_error", void 0, {
2255
+ status: 0,
2256
+ message: error instanceof Error ? error.message : typeof error === "string" ? error : "Network request failed"
2257
+ });
2258
+ normalized.cause = error;
2259
+ return normalized;
2260
+ }
2261
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeError, "normalizeError");
2262
+ function notifyResponseObserver(observer, data, error, event) {
2263
+ _chunkLTNGXMQ6cjs.notifyClientObserver.call(void 0, observer, [data, error, event], "API client onResponse");
2264
+ }
2265
+ _chunkS3JO3N4Hcjs.__name.call(void 0, notifyResponseObserver, "notifyResponseObserver");
2266
+ function isFormData(value) {
2267
+ return typeof value === "object" && value !== null && (typeof FormData !== "undefined" && value instanceof FormData || Object.prototype.toString.call(value) === "[object FormData]" && typeof value.entries === "function");
2268
+ }
2269
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isFormData, "isFormData");
2270
+ function appendAPIQuery(searchParams, query) {
2271
+ if (query instanceof URLSearchParams) {
2272
+ const keys = new Set(query.keys());
2273
+ for (const key of keys) searchParams.delete(key);
2274
+ query.forEach((value, key) => searchParams.append(key, value));
2275
+ return;
2276
+ }
2277
+ if (!query || typeof query !== "object" || Array.isArray(query)) {
2278
+ throw new TypeError("API query input must be an object or URLSearchParams.");
2279
+ }
2280
+ for (const [key, value] of Object.entries(query)) {
2281
+ if (value === void 0 || value === null) continue;
2282
+ searchParams.delete(key);
2283
+ const values = Array.isArray(value) ? value : [value];
2284
+ for (const item of values) {
2285
+ if (item === void 0 || item === null) continue;
2286
+ if (!isAPIQueryPrimitive(item)) {
2287
+ throw new TypeError(
2288
+ `API query parameter "${key}" must be a string, number, boolean, bigint, or an array of those values.`
2289
+ );
2290
+ }
2291
+ searchParams.append(key, String(item));
2292
+ }
2293
+ }
2294
+ }
2295
+ _chunkS3JO3N4Hcjs.__name.call(void 0, appendAPIQuery, "appendAPIQuery");
2296
+ function isAPIQueryPrimitive(value) {
2297
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint";
2298
+ }
2299
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isAPIQueryPrimitive, "isAPIQueryPrimitive");
2300
+ function createResponseError2(response, data, cause) {
2301
+ const expected = readEndpointErrorEnvelope(data);
2302
+ if (expected) {
2303
+ return new APIClientError(expected.code, expected.data, {
2304
+ status: response.status,
2305
+ message: expected.message,
2306
+ response
2307
+ });
2308
+ }
2309
+ const error = new APIClientError("http_error", data, {
2310
+ status: response.status,
2311
+ message: `HTTP ${response.status}: ${response.statusText}`,
2312
+ response
2313
+ });
2314
+ if (cause !== void 0) error.cause = cause;
2315
+ return error;
2316
+ }
2317
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createResponseError2, "createResponseError");
2318
+ function readEndpointErrorEnvelope(data) {
2319
+ if (!data || typeof data !== "object") return null;
2320
+ const error = data.error;
2321
+ if (!error || typeof error !== "object") return null;
2322
+ const code = error.code;
2323
+ const message = error.message;
2324
+ if (typeof code !== "string" || typeof message !== "string") return null;
2325
+ return {
2326
+ code,
2327
+ message,
2328
+ data: error.data
2329
+ };
2330
+ }
2331
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readEndpointErrorEnvelope, "readEndpointErrorEnvelope");
2332
+
2333
+
2334
+
2335
+
2336
+
2337
+
2338
+
2339
+
2340
+
2341
+
2342
+
2343
+
2344
+
2345
+
2346
+
2347
+
2348
+
2349
+
2350
+
2351
+
2352
+
2353
+
2354
+
2355
+ exports.IntegrationClientError = IntegrationClientError; exports.createIntegrationClient = createIntegrationClient; exports.integrationsClient = integrationsClient; exports.integrationsServer = integrationsServer; exports.createIntegrationServerClient = createIntegrationServerClient; exports.createIntegrationApi = createIntegrationApi; exports.createIntegrationClients = createIntegrationClients; exports.createIntegrations = createIntegrations; exports.getIntegrationAPIManifest = getIntegrationAPIManifest; exports.integrationClients = integrationClients; exports.FARM_API_ROUTE_REF_SYMBOL = FARM_API_ROUTE_REF_SYMBOL; exports.FARM_API_ROUTE_META_SYMBOL = FARM_API_ROUTE_META_SYMBOL; exports.APIClientError = APIClientError; exports.createApiClients = createApiClients; exports.createAPIClient = createAPIClient; exports.isAPIRouteRef = isAPIRouteRef; exports.getAPIRouteRefMetadata = getAPIRouteRefMetadata; exports.createServerAPIClient = createServerAPIClient; exports.applyServerFnOptimisticUpdates = applyServerFnOptimisticUpdates; exports.settleServerFnOptimisticUpdates = settleServerFnOptimisticUpdates; exports.resolveServerFnInvalidateTargets = resolveServerFnInvalidateTargets;