@farm.js/core 0.1.17 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/dist/after.cjs +12 -225
  2. package/dist/agent-runtime.cjs +83 -2800
  3. package/dist/api/client.cjs +17 -4060
  4. package/dist/api/route-manager.cjs +34 -4354
  5. package/dist/api/runtime.cjs +29 -2696
  6. package/dist/api.cjs +88 -8434
  7. package/dist/app-markdown.cjs +39 -280
  8. package/dist/app-markdown.mjs +3 -3
  9. package/dist/cache.cjs +38 -1560
  10. package/dist/chunk-22GUSVNJ.cjs +351 -0
  11. package/dist/{chunk-EN7WTEAY.mjs → chunk-2ANEVVF7.mjs} +1 -1
  12. package/dist/chunk-2CQ74SP6.cjs +13 -0
  13. package/dist/{chunk-YD4J4XCI.mjs → chunk-2GNATDDE.mjs} +1 -1
  14. package/dist/chunk-2SJ4RQ6P.cjs +57 -0
  15. package/dist/chunk-3376ZTRC.cjs +1 -0
  16. package/dist/chunk-4PNUXIVU.cjs +472 -0
  17. package/dist/chunk-4PPEPOZZ.cjs +21 -0
  18. package/dist/chunk-4ZFL5GFN.cjs +520 -0
  19. package/dist/chunk-5OVTOKGH.cjs +65 -0
  20. package/dist/chunk-5QIKR7RR.cjs +224 -0
  21. package/dist/chunk-5ZSWG4UX.cjs +127 -0
  22. package/dist/chunk-62YJ2IEB.cjs +238 -0
  23. package/dist/chunk-6EODJYCX.cjs +183 -0
  24. package/dist/chunk-6EXBPJ24.cjs +434 -0
  25. package/dist/chunk-6QQDAAAZ.cjs +38 -0
  26. package/dist/chunk-6V4TDWEC.cjs +455 -0
  27. package/dist/chunk-72ADZ6GQ.cjs +19 -0
  28. package/dist/chunk-75BRBIFP.cjs +172 -0
  29. package/dist/{chunk-ZCNJKLA2.mjs → chunk-7BC6GAL7.mjs} +1 -1
  30. package/dist/chunk-7W3CPVXS.cjs +24 -0
  31. package/dist/chunk-A6WIQH5Z.cjs +31 -0
  32. package/dist/chunk-A777V5WU.cjs +725 -0
  33. package/dist/chunk-AFOD3LYZ.cjs +377 -0
  34. package/dist/chunk-AH7HOAQ3.cjs +151 -0
  35. package/dist/chunk-AMDMVWMI.cjs +39 -0
  36. package/dist/chunk-AORPIPNB.cjs +552 -0
  37. package/dist/chunk-ARJWXNQL.cjs +256 -0
  38. package/dist/chunk-AYJR42WX.cjs +711 -0
  39. package/dist/chunk-BBVSJVBZ.cjs +600 -0
  40. package/dist/chunk-BIDYX3SL.cjs +91 -0
  41. package/dist/chunk-BYODCJD6.cjs +663 -0
  42. package/dist/chunk-C3VRMB6H.cjs +85 -0
  43. package/dist/chunk-C5GUTBZK.cjs +173 -0
  44. package/dist/chunk-CIAGU2X4.cjs +337 -0
  45. package/dist/chunk-CMGMGHUZ.cjs +27 -0
  46. package/dist/chunk-CXP5U3RW.cjs +54 -0
  47. package/dist/chunk-D2ULAULS.cjs +166 -0
  48. package/dist/chunk-D7JTOLFK.cjs +285 -0
  49. package/dist/chunk-DVM4FKZL.cjs +169 -0
  50. package/dist/chunk-DYEJQTDN.cjs +49 -0
  51. package/dist/chunk-E2ROOWQC.cjs +2225 -0
  52. package/dist/chunk-E3UK5IIB.cjs +593 -0
  53. package/dist/chunk-EM6SBQKM.cjs +470 -0
  54. package/dist/chunk-FJSWYIR7.cjs +482 -0
  55. package/dist/chunk-FK6GO24V.cjs +54 -0
  56. package/dist/{chunk-MVIWBEJF.mjs → chunk-FVZGEVTO.mjs} +7 -7
  57. package/dist/chunk-FXUUWYAX.cjs +654 -0
  58. package/dist/chunk-G3HRIVEY.cjs +395 -0
  59. package/dist/chunk-G643DQCH.cjs +13 -0
  60. package/dist/chunk-G7HXGLEC.cjs +175 -0
  61. package/dist/chunk-GDSHDTJ4.cjs +152 -0
  62. package/dist/chunk-GPVTX3HT.cjs +1415 -0
  63. package/dist/chunk-H6G5INWM.cjs +1094 -0
  64. package/dist/{chunk-DHDVMXYK.mjs → chunk-HALDNTIV.mjs} +30 -4
  65. package/dist/chunk-HBTUGXHS.cjs +180 -0
  66. package/dist/chunk-HREOKQWT.cjs +45 -0
  67. package/dist/{chunk-5QOEPUYE.mjs → chunk-HSDL2AUR.mjs} +1 -1
  68. package/dist/chunk-I4J452B7.cjs +435 -0
  69. package/dist/chunk-I57LW5VZ.cjs +94 -0
  70. package/dist/chunk-I5YBCWQ6.cjs +40 -0
  71. package/dist/chunk-I7PUUDGY.cjs +389 -0
  72. package/dist/chunk-IAMRBF3Z.cjs +86 -0
  73. package/dist/chunk-IQXFRNY2.cjs +169 -0
  74. package/dist/chunk-ISTFC3MZ.cjs +1357 -0
  75. package/dist/chunk-IXTFU4PL.cjs +2355 -0
  76. package/dist/chunk-J3LOGE4T.cjs +42 -0
  77. package/dist/chunk-J7FSKED3.cjs +93 -0
  78. package/dist/chunk-JDNHKPTD.cjs +22 -0
  79. package/dist/chunk-JSROZYYO.cjs +164 -0
  80. package/dist/chunk-K6FNHVDR.cjs +696 -0
  81. package/dist/chunk-KGZIORNL.cjs +43 -0
  82. package/dist/chunk-KR6CKSXT.cjs +15 -0
  83. package/dist/chunk-KROWKCUH.cjs +185 -0
  84. package/dist/chunk-KVFPGF2M.cjs +46 -0
  85. package/dist/{chunk-TNBAYAWO.mjs → chunk-L4DVIHOC.mjs} +1 -1
  86. package/dist/chunk-LCCBO7PJ.cjs +46 -0
  87. package/dist/chunk-LIUGYUX3.cjs +22 -0
  88. package/dist/chunk-LTNGXMQ6.cjs +55 -0
  89. package/dist/chunk-M2L4MYDQ.cjs +14 -0
  90. package/dist/chunk-MCJLA63J.cjs +1 -0
  91. package/dist/chunk-MKB2EGIR.cjs +148 -0
  92. package/dist/chunk-MQ3H6LT5.cjs +202 -0
  93. package/dist/chunk-MT763TDW.cjs +43 -0
  94. package/dist/{chunk-XWAYMDLB.mjs → chunk-MVUREHPN.mjs} +1 -1
  95. package/dist/chunk-MWSK6C4J.cjs +18 -0
  96. package/dist/chunk-MWWVKDW3.cjs +169 -0
  97. package/dist/{chunk-6VQIKZZO.mjs → chunk-N255VYFP.mjs} +1 -1
  98. package/dist/chunk-NBAHDVOJ.cjs +2040 -0
  99. package/dist/chunk-NO3WWW3N.cjs +192 -0
  100. package/dist/chunk-NSFC3LHB.cjs +10244 -0
  101. package/dist/chunk-NZKJGRB3.cjs +230 -0
  102. package/dist/chunk-OAVTUMJP.cjs +1496 -0
  103. package/dist/{chunk-SXHV42UQ.mjs → chunk-OFEY6KHO.mjs} +88 -13
  104. package/dist/chunk-OHY2ZWUG.cjs +25 -0
  105. package/dist/chunk-OI6CMLWX.cjs +47 -0
  106. package/dist/chunk-OWOUTKIJ.cjs +558 -0
  107. package/dist/chunk-OX6O6WVA.cjs +74 -0
  108. package/dist/chunk-OXSIH4D6.cjs +476 -0
  109. package/dist/chunk-OYDRPBBV.cjs +453 -0
  110. package/dist/chunk-OYEUREB6.cjs +35 -0
  111. package/dist/chunk-PCOTGFSM.cjs +139 -0
  112. package/dist/{chunk-76DG3LF3.mjs → chunk-PGQBL5DN.mjs} +1 -1
  113. package/dist/chunk-PZYCPSCC.cjs +35 -0
  114. package/dist/chunk-QBK2AA4U.cjs +445 -0
  115. package/dist/{chunk-UTBVHYS3.mjs → chunk-QBPKKQTD.mjs} +2 -2
  116. package/dist/chunk-QBPXNZGV.cjs +487 -0
  117. package/dist/chunk-QNPEUFHQ.cjs +27 -0
  118. package/dist/chunk-QZRVZSPN.cjs +236 -0
  119. package/dist/chunk-R5A5KNVX.cjs +20 -0
  120. package/dist/chunk-R5JIFR6B.cjs +42 -0
  121. package/dist/chunk-R6AIILII.cjs +193 -0
  122. package/dist/chunk-RFYO7QUD.cjs +9 -0
  123. package/dist/chunk-RG3ZOTG5.cjs +34 -0
  124. package/dist/chunk-ROUTX2E5.cjs +390 -0
  125. package/dist/chunk-RTHIVJ2G.cjs +54 -0
  126. package/dist/chunk-S27FMYAM.cjs +644 -0
  127. package/dist/chunk-S3A45T7F.cjs +166 -0
  128. package/dist/chunk-S3JO3N4H.cjs +17 -0
  129. package/dist/chunk-SK35NQKK.cjs +27 -0
  130. package/dist/chunk-SU7MH53P.cjs +180 -0
  131. package/dist/chunk-SVRTJOUF.cjs +113 -0
  132. package/dist/chunk-SWN467MP.cjs +18 -0
  133. package/dist/chunk-SYQ3MOWW.cjs +73 -0
  134. package/dist/chunk-T5CERMEH.cjs +417 -0
  135. package/dist/chunk-TFAXUHWX.cjs +206 -0
  136. package/dist/chunk-TIWHTW3Q.cjs +24 -0
  137. package/dist/chunk-TKJZFIML.cjs +20 -0
  138. package/dist/chunk-TKNSDBBN.cjs +193 -0
  139. package/dist/chunk-U4KT7QP3.cjs +23 -0
  140. package/dist/chunk-U5BMPGS3.cjs +862 -0
  141. package/dist/chunk-UJ2C4ICS.cjs +277 -0
  142. package/dist/chunk-UQZ4AYTH.cjs +168 -0
  143. package/dist/chunk-US2QVW3E.cjs +36 -0
  144. package/dist/{chunk-QGVJVSNX.mjs → chunk-V4AICMQA.mjs} +2 -2
  145. package/dist/chunk-VB6UCX3V.cjs +421 -0
  146. package/dist/chunk-VEKFLAQM.cjs +300 -0
  147. package/dist/chunk-VQDBNVOO.cjs +14 -0
  148. package/dist/chunk-W4E7WMXE.cjs +71 -0
  149. package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
  150. package/dist/chunk-WMAPPDMM.cjs +28 -0
  151. package/dist/chunk-WMOGFOUJ.cjs +223 -0
  152. package/dist/chunk-WPYFSQKK.cjs +37 -0
  153. package/dist/{chunk-56DAX2BE.mjs → chunk-WZXN4R5Y.mjs} +24 -13
  154. package/dist/chunk-XDGMADQM.cjs +14225 -0
  155. package/dist/chunk-XGC343EY.cjs +443 -0
  156. package/dist/chunk-XSKZORAS.cjs +727 -0
  157. package/dist/chunk-XWAWFQFS.cjs +82 -0
  158. package/dist/chunk-Y4YMF2NQ.cjs +460 -0
  159. package/dist/chunk-Y4YWHNKU.cjs +250 -0
  160. package/dist/chunk-Y53ZSFN6.cjs +504 -0
  161. package/dist/chunk-YA6LLTIJ.cjs +411 -0
  162. package/dist/chunk-YFPGHF5F.cjs +202 -0
  163. package/dist/chunk-YJRZR7VU.cjs +28 -0
  164. package/dist/chunk-YTAABQEV.cjs +1 -0
  165. package/dist/chunk-YX3DBN4M.cjs +18 -0
  166. package/dist/chunk-YZTASLPQ.cjs +64 -0
  167. package/dist/chunk-Z5HIWVDP.cjs +2173 -0
  168. package/dist/chunk-ZEG3OPIB.cjs +93 -0
  169. package/dist/chunk-ZMN3H73H.cjs +155 -0
  170. package/dist/client/lifecycle.cjs +6 -35
  171. package/dist/client-plugins.cjs +7 -448
  172. package/dist/client.cjs +171 -9808
  173. package/dist/config.cjs +8 -36
  174. package/dist/cron.cjs +24 -491
  175. package/dist/deferred.cjs +26 -475
  176. package/dist/deployment.cjs +39 -210
  177. package/dist/devtools-5KGPDVKL.cjs +388 -0
  178. package/dist/{devtools-UFVTMQX5.mjs → devtools-FY5R7TQ4.mjs} +3 -3
  179. package/dist/devtools-client-4WAPJY5L.cjs +254 -0
  180. package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
  181. package/dist/docs.cjs +46 -5657
  182. package/dist/docs.mjs +5 -5
  183. package/dist/env-types.cjs +5 -226
  184. package/dist/env.cjs +21 -338
  185. package/dist/environment/vite.cjs +8 -372
  186. package/dist/environment.cjs +12 -94
  187. package/dist/font.cjs +13 -63
  188. package/dist/headers.cjs +7 -123
  189. package/dist/i18n/client.cjs +55 -294
  190. package/dist/i18n/index.cjs +22 -209
  191. package/dist/i18n/server.cjs +22 -745
  192. package/dist/image/server.cjs +13 -729
  193. package/dist/image/sharp.cjs +33 -171
  194. package/dist/image.cjs +41 -85
  195. package/dist/index.cjs +1151 -68080
  196. package/dist/index.mjs +14 -14
  197. package/dist/instrumentation.cjs +12 -138
  198. package/dist/integration-orm-55F7CII5.cjs +13 -0
  199. package/dist/integrations.cjs +55 -4090
  200. package/dist/internal/app-markdown-runtime.cjs +27 -224
  201. package/dist/internal/app-markdown-runtime.mjs +2 -2
  202. package/dist/internal/build-runtime.cjs +120 -52259
  203. package/dist/internal/build-runtime.mjs +13 -13
  204. package/dist/internal/cli-runtime.cjs +67 -13811
  205. package/dist/internal/cli-runtime.mjs +7 -7
  206. package/dist/internal/client-error-overlay.cjs +80 -733
  207. package/dist/internal/client-error-overlay.mjs +1 -1
  208. package/dist/internal/client-runtime.cjs +81 -913
  209. package/dist/internal/compression-runtime.cjs +8 -214
  210. package/dist/internal/config-runtime.cjs +42 -6547
  211. package/dist/internal/config-runtime.mjs +3 -3
  212. package/dist/internal/docs-precompiled-runtime.cjs +26 -46
  213. package/dist/internal/infra-analytics-runtime.cjs +10 -536
  214. package/dist/internal/isolated-boundary.cjs +14 -414
  215. package/dist/internal/metadata-image-runtime.cjs +7 -285
  216. package/dist/internal/product-telemetry-runtime.cjs +42 -97
  217. package/dist/internal/product-telemetry-runtime.mjs +1 -1
  218. package/dist/internal/production-node-env.cjs +6 -63
  219. package/dist/internal/production-runtime.cjs +418 -7133
  220. package/dist/internal/production-runtime.mjs +3 -3
  221. package/dist/internal/request-cookies.cjs +6 -54
  222. package/dist/json-ld.cjs +24 -50
  223. package/dist/layers-E4WPJNY5.cjs +17 -0
  224. package/dist/manager-G4B2IPYE.cjs +14 -0
  225. package/dist/markdown.cjs +21 -547
  226. package/dist/markdown.mjs +1 -1
  227. package/dist/middleware.cjs +36 -2995
  228. package/dist/navigation.cjs +22 -2588
  229. package/dist/nitro-4I2MYLY2.cjs +652 -0
  230. package/dist/observability.cjs +22 -614
  231. package/dist/og.cjs +5 -28
  232. package/dist/plugin.cjs +106 -37442
  233. package/dist/plugin.mjs +9 -9
  234. package/dist/query/client.cjs +113 -449
  235. package/dist/query/index.cjs +26 -288
  236. package/dist/query/parsers.cjs +23 -247
  237. package/dist/query/server.cjs +36 -298
  238. package/dist/renderer/react/client.cjs +9 -43
  239. package/dist/renderer/react/server.cjs +40 -103
  240. package/dist/renderer/react/vite.cjs +7 -29
  241. package/dist/renderer-client.cjs +126 -4295
  242. package/dist/renderer.cjs +31 -249
  243. package/dist/request.cjs +5 -68
  244. package/dist/router.cjs +11 -474
  245. package/dist/routes.cjs +42 -2461
  246. package/dist/{schema-dev-notice-2IE2F2XI.mjs → schema-dev-notice-O67CPXJ6.mjs} +1 -1
  247. package/dist/schema-dev-notice-Y7MQEFGN.cjs +56 -0
  248. package/dist/schema.cjs +6 -33
  249. package/dist/search-client-G3RICOFU.cjs +13 -0
  250. package/dist/server-action-security.cjs +25 -541
  251. package/dist/server-fn-client.cjs +6 -337
  252. package/dist/server-fn.cjs +32 -1841
  253. package/dist/server-plugins.cjs +15 -884
  254. package/dist/server-query-client.cjs +15 -1883
  255. package/dist/server-query.cjs +16 -1838
  256. package/dist/server.cjs +296 -44681
  257. package/dist/server.mjs +11 -11
  258. package/dist/storage.cjs +57 -576
  259. package/dist/testing.cjs +89 -3186
  260. package/dist/theme/client.cjs +13 -108
  261. package/dist/theme/index.cjs +6 -68
  262. package/dist/theme/runtime.cjs +13 -78
  263. package/dist/theme/server.cjs +10 -179
  264. package/dist/version.cjs +4 -32
  265. package/dist/version.mjs +1 -1
  266. package/dist/vite.cjs +119 -37773
  267. package/dist/vite.mjs +9 -9
  268. package/dist/workflows.cjs +19 -1040
  269. package/package.json +1 -1
@@ -1,1843 +1,21 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
20
2
 
21
- // src/server-query.ts
22
- var server_query_exports = {};
23
- __export(server_query_exports, {
24
- FARM_SERVER_QUERY_SYMBOL: () => FARM_SERVER_QUERY_SYMBOL,
25
- createServerQuery: () => createServerQuery
26
- });
27
- module.exports = __toCommonJS(server_query_exports);
28
3
 
29
- // src/tracing.ts
30
- var import_api = require("@opentelemetry/api");
31
- var FARM_TRACER_NAME = "@farm.js/core";
32
- var ALL_SPAN_KINDS = [
33
- "request",
34
- "render",
35
- "middleware",
36
- "api",
37
- "integration",
38
- "storage",
39
- "ppr",
40
- "build",
41
- "plugin"
42
- ];
43
- var DEFAULT_IGNORED_PATHS = [
44
- "/@vite/",
45
- "/@fs/",
46
- "/@id/",
47
- "/@react-refresh",
48
- "/node_modules/",
49
- "/__vite",
50
- "/.well-known/appspecific/"
51
- ];
52
- var FARM_REQUEST_METHOD_CONTEXT_KEY = (0, import_api.createContextKey)("@farm.js/core/request-method");
53
- var TRACING_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/tracing-runtime/v1");
54
- var runtime = globalThis;
55
- var tracingState = runtime[TRACING_RUNTIME] ?? (runtime[TRACING_RUNTIME] = normalizeFarmTracingConfig(false));
56
- function normalizeFarmTracingConfig(config) {
57
- if (!config) {
58
- return {
59
- enabled: false,
60
- spans: new Set(ALL_SPAN_KINDS),
61
- recordEvents: true,
62
- attributes: {},
63
- ignorePaths: DEFAULT_IGNORED_PATHS
64
- };
65
- }
66
- if (config === true) {
67
- return {
68
- enabled: true,
69
- spans: new Set(ALL_SPAN_KINDS),
70
- recordEvents: true,
71
- attributes: {},
72
- ignorePaths: DEFAULT_IGNORED_PATHS
73
- };
74
- }
75
- return {
76
- enabled: config.enabled ?? true,
77
- spans: new Set(config.spans ?? ALL_SPAN_KINDS),
78
- recordEvents: config.recordEvents ?? true,
79
- attributes: { ...config.attributes },
80
- ignorePaths: [...DEFAULT_IGNORED_PATHS, ...config.ignorePaths ?? []]
81
- };
82
- }
83
- __name(normalizeFarmTracingConfig, "normalizeFarmTracingConfig");
84
- function recordFarmEventTrace(event) {
85
- if (!tracingState.enabled) return void 0;
86
- const activeContext = import_api.context.active();
87
- const activeSpan = import_api.trace.getSpan(activeContext);
88
- const traceContext = getSpanTraceContext(activeSpan);
89
- if (activeSpan && traceContext) {
90
- if (event.type === "route.matched") {
91
- const method = activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) ?? "HTTP";
92
- activeSpan.updateName(`${method} ${event.route}`);
93
- activeSpan.setAttribute("http.route", event.route);
94
- activeSpan.setAttribute("farm.route", event.route);
95
- }
96
- if (tracingState.recordEvents) {
97
- activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);
98
- }
99
- const error = event.type === "request.error" ? void 0 : getEventError(event);
100
- if (error !== void 0) {
101
- if (event.type === "render.error") {
102
- recordSpanException(activeSpan, error);
103
- } else {
104
- recordSpanError(activeSpan, error);
105
- }
106
- }
107
- }
108
- const completedTraceContext = recordCompletedEventSpan(event, activeContext);
109
- return traceContext ?? completedTraceContext;
110
- }
111
- __name(recordFarmEventTrace, "recordFarmEventTrace");
112
- function recordCompletedEventSpan(event, parentContext) {
113
- const descriptor = getCompletedSpanDescriptor(event);
114
- if (!descriptor || !tracingState.spans.has(descriptor.kind)) return void 0;
115
- const tracer = import_api.trace.getTracer(FARM_TRACER_NAME);
116
- const span = tracer.startSpan(
117
- descriptor.name,
118
- {
119
- kind: import_api.SpanKind.INTERNAL,
120
- startTime: event.timestamp - descriptor.durationMs,
121
- attributes: {
122
- ...tracingState.attributes,
123
- ...toEventAttributes(event),
124
- "farm.event.type": event.type
125
- }
126
- },
127
- parentContext
128
- );
129
- const status = "status" in event && typeof event.status === "number" ? event.status : void 0;
130
- if (status !== void 0) setResponseStatus(span, status);
131
- const error = getEventError(event);
132
- if (error !== void 0) recordSpanError(span, error);
133
- const traceContext = getSpanTraceContext(span);
134
- span.end(event.timestamp);
135
- return traceContext;
136
- }
137
- __name(recordCompletedEventSpan, "recordCompletedEventSpan");
138
- function getCompletedSpanDescriptor(event) {
139
- if (!("durationMs" in event) || typeof event.durationMs !== "number") return void 0;
140
- switch (event.type) {
141
- case "render.complete":
142
- return { kind: "render", name: `farm.render ${event.route}`, durationMs: event.durationMs };
143
- case "render.stream.shellReady":
144
- return {
145
- kind: "render",
146
- name: `farm.render.shell ${event.route}`,
147
- durationMs: event.durationMs
148
- };
149
- case "render.stream.complete":
150
- return {
151
- kind: "render",
152
- name: `farm.render.stream ${event.route}`,
153
- durationMs: event.durationMs
154
- };
155
- case "middleware.complete":
156
- return {
157
- kind: "middleware",
158
- name: `farm.middleware ${event.name ?? event.route ?? "anonymous"}`,
159
- durationMs: event.durationMs
160
- };
161
- case "api.request.complete":
162
- case "api.error":
163
- return {
164
- kind: "api",
165
- name: `farm.api ${event.method} ${event.route}`,
166
- durationMs: event.durationMs
167
- };
168
- case "integration.api.call.complete":
169
- return {
170
- kind: "integration",
171
- name: `farm.integration ${event.integration}.${event.operation}`,
172
- durationMs: event.durationMs
173
- };
174
- case "storage.query.complete":
175
- return {
176
- kind: "storage",
177
- name: `farm.storage ${event.operation}`,
178
- durationMs: event.durationMs
179
- };
180
- case "ppr.refresh.complete":
181
- return {
182
- kind: "ppr",
183
- name: `farm.ppr.refresh ${event.route}`,
184
- durationMs: event.durationMs
185
- };
186
- case "build.complete":
187
- return {
188
- kind: "build",
189
- name: `farm.build${event.target ? ` ${event.target}` : ""}`,
190
- durationMs: event.durationMs
191
- };
192
- case "plugin.hook.complete":
193
- return {
194
- kind: "plugin",
195
- name: `farm.plugin ${event.plugin}.${event.hook}`,
196
- durationMs: event.durationMs
197
- };
198
- default:
199
- return void 0;
200
- }
201
- }
202
- __name(getCompletedSpanDescriptor, "getCompletedSpanDescriptor");
203
- function hashFarmCacheKey(value) {
204
- let hash = 2166136261;
205
- for (let index = 0; index < value.length; index++) {
206
- hash ^= value.charCodeAt(index);
207
- hash = Math.imul(hash, 16777619);
208
- }
209
- return (hash >>> 0).toString(16).padStart(8, "0");
210
- }
211
- __name(hashFarmCacheKey, "hashFarmCacheKey");
212
- function toEventAttributes(event) {
213
- const attributes = {};
214
- const redactKey = typeof event.type === "string" && event.type.startsWith("cache.");
215
- for (const [key, value] of Object.entries(event)) {
216
- if (key === "timestamp" || key === "level" || key === "error" || key === "traceId" || key === "spanId" || key === "traceSampled" || value === void 0) {
217
- continue;
218
- }
219
- if (redactKey && key === "key" && typeof value === "string") {
220
- attributes["farm.key_hash"] = hashFarmCacheKey(value);
221
- continue;
222
- }
223
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
224
- attributes[`farm.${key}`] = value;
225
- } else if (Array.isArray(value)) {
226
- if (value.every((entry) => typeof entry === "string")) {
227
- attributes[`farm.${key}`] = value;
228
- } else if (value.every((entry) => typeof entry === "number")) {
229
- attributes[`farm.${key}`] = value;
230
- } else if (value.every((entry) => typeof entry === "boolean")) {
231
- attributes[`farm.${key}`] = value;
232
- }
233
- }
234
- }
235
- return attributes;
236
- }
237
- __name(toEventAttributes, "toEventAttributes");
238
- function getEventError(event) {
239
- return "error" in event ? event.error : void 0;
240
- }
241
- __name(getEventError, "getEventError");
242
- function recordSpanException(span, error) {
243
- const normalized = error instanceof Error ? error : new Error(String(error));
244
- span.recordException(normalized);
245
- return normalized;
246
- }
247
- __name(recordSpanException, "recordSpanException");
248
- function recordSpanError(span, error) {
249
- const normalized = recordSpanException(span, error);
250
- span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: normalized.message });
251
- }
252
- __name(recordSpanError, "recordSpanError");
253
- function setResponseStatus(span, status) {
254
- span.setAttribute("http.response.status_code", status);
255
- if (status >= 500) {
256
- span.setStatus({ code: import_api.SpanStatusCode.ERROR });
257
- }
258
- }
259
- __name(setResponseStatus, "setResponseStatus");
260
- function getSpanTraceContext(span) {
261
- if (!span) return void 0;
262
- const spanContext = span.spanContext();
263
- if (!(0, import_api.isSpanContextValid)(spanContext)) return void 0;
264
- return {
265
- traceId: spanContext.traceId,
266
- spanId: spanContext.spanId,
267
- traceSampled: (spanContext.traceFlags & 1) === 1
268
- };
269
- }
270
- __name(getSpanTraceContext, "getSpanTraceContext");
4
+ var _chunkZMN3H73Hcjs = require('./chunk-ZMN3H73H.cjs');
5
+ require('./chunk-G3HRIVEY.cjs');
6
+ require('./chunk-SK35NQKK.cjs');
7
+ require('./chunk-T5CERMEH.cjs');
8
+ require('./chunk-SVRTJOUF.cjs');
9
+ require('./chunk-EM6SBQKM.cjs');
10
+ require('./chunk-H6G5INWM.cjs');
11
+ require('./chunk-ZEG3OPIB.cjs');
12
+ require('./chunk-LIUGYUX3.cjs');
13
+ require('./chunk-E3UK5IIB.cjs');
14
+ require('./chunk-OX6O6WVA.cjs');
15
+ require('./chunk-U4KT7QP3.cjs');
16
+ require('./chunk-NO3WWW3N.cjs');
17
+ require('./chunk-S3JO3N4H.cjs');
271
18
 
272
- // src/observability.ts
273
- var OBSERVABILITY_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/observability-runtime/v1");
274
- var runtime2 = globalThis;
275
- var shared = runtime2[OBSERVABILITY_RUNTIME] ?? (runtime2[OBSERVABILITY_RUNTIME] = {
276
- handlers: /* @__PURE__ */ new Set(),
277
- unfilteredHandlers: /* @__PURE__ */ new Set(),
278
- config: { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) }
279
- });
280
- var runtimeHandlers = shared.handlers;
281
- var unfilteredRuntimeHandlers = shared.unfilteredHandlers;
282
- var observabilityState = shared.config;
283
- function emitFarmEvent(input) {
284
- const event = {
285
- timestamp: Date.now(),
286
- level: inferFarmEventLevel(input.type),
287
- ...input
288
- };
289
- const traceContext = recordFarmEventTrace(event);
290
- if (traceContext) {
291
- event.traceId = traceContext.traceId;
292
- event.spanId = traceContext.spanId;
293
- event.traceSampled = traceContext.traceSampled;
294
- }
295
- notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);
296
- if (!shouldEmitFarmEvent(event)) return event;
297
- if (observabilityState.logs) {
298
- logFarmEvent(event);
299
- }
300
- notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);
301
- return event;
302
- }
303
- __name(emitFarmEvent, "emitFarmEvent");
304
- function notifyFarmEventHandlers(event, handlers) {
305
- for (const handler of handlers) {
306
- try {
307
- Promise.resolve(handler(event)).catch((error) => {
308
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
309
- });
310
- } catch (error) {
311
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
312
- }
313
- }
314
- }
315
- __name(notifyFarmEventHandlers, "notifyFarmEventHandlers");
316
- function shouldEmitFarmEvent(event) {
317
- if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
318
- return false;
319
- }
320
- if (observabilityState.events && !observabilityState.events.has(event.type)) {
321
- return false;
322
- }
323
- return true;
324
- }
325
- __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
326
- function inferFarmEventLevel(type) {
327
- if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
328
- return "error";
329
- }
330
- if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
331
- return "warn";
332
- }
333
- if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
334
- return "debug";
335
- }
336
- return "info";
337
- }
338
- __name(inferFarmEventLevel, "inferFarmEventLevel");
339
- function logFarmEvent(event) {
340
- const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
341
- switch (event.level) {
342
- case "error":
343
- console.error(message);
344
- break;
345
- case "warn":
346
- console.warn(message);
347
- break;
348
- default:
349
- console.log(message);
350
- break;
351
- }
352
- }
353
- __name(logFarmEvent, "logFarmEvent");
354
- function formatFarmEventDetails(event) {
355
- const details = [];
356
- const record = event;
357
- for (const key of [
358
- "route",
359
- "pathname",
360
- "method",
361
- "status",
362
- "key",
363
- "tag",
364
- "path",
365
- "reason",
366
- "durationMs",
367
- "integration",
368
- "server",
369
- "tool",
370
- "outcome",
371
- "operation",
372
- "plugin",
373
- "hook",
374
- "target",
375
- "count"
376
- ]) {
377
- const value = record[key];
378
- if (value !== void 0) {
379
- details.push(`${key}=${formatDetailValue(value)}`);
380
- }
381
- }
382
- return details.length > 0 ? ` ${details.join(" ")}` : "";
383
- }
384
- __name(formatFarmEventDetails, "formatFarmEventDetails");
385
- function formatDetailValue(value) {
386
- if (typeof value === "string") {
387
- return value;
388
- }
389
- if (typeof value === "number" || typeof value === "boolean") {
390
- return String(value);
391
- }
392
- try {
393
- return JSON.stringify(value);
394
- } catch {
395
- return String(value);
396
- }
397
- }
398
- __name(formatDetailValue, "formatDetailValue");
399
- function formatError(error) {
400
- return error instanceof Error ? error.message : String(error);
401
- }
402
- __name(formatError, "formatError");
403
19
 
404
- // src/cache-invalidation.ts
405
- var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
406
- var globalState = globalThis;
407
- function getFarmCacheInvalidationState() {
408
- return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
409
- listeners: /* @__PURE__ */ new Set(),
410
- taskListeners: /* @__PURE__ */ new Set()
411
- });
412
- }
413
- __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
414
- function warnFarmCacheListenerError(scope, error) {
415
- const detail = error instanceof Error ? error.stack ?? error.message : String(error);
416
- console.warn(`[farm:cache] ${scope} listener failed: ${detail}`);
417
- }
418
- __name(warnFarmCacheListenerError, "warnFarmCacheListenerError");
419
- function notifyFarmCacheInvalidation(key, source = "local") {
420
- if (typeof key !== "string" || key.length === 0) return;
421
- for (const listener of getFarmCacheInvalidationState().listeners) {
422
- try {
423
- listener(key, source);
424
- } catch (error) {
425
- warnFarmCacheListenerError("invalidation", error);
426
- }
427
- }
428
- }
429
- __name(notifyFarmCacheInvalidation, "notifyFarmCacheInvalidation");
430
- function notifyFarmCacheTask(task) {
431
- for (const listener of getFarmCacheInvalidationState().taskListeners) {
432
- try {
433
- listener(task);
434
- } catch (error) {
435
- warnFarmCacheListenerError("task", error);
436
- }
437
- }
438
- }
439
- __name(notifyFarmCacheTask, "notifyFarmCacheTask");
440
- function subscribeFarmCacheInvalidation(listener) {
441
- const state = getFarmCacheInvalidationState();
442
- state.listeners.add(listener);
443
- return () => state.listeners.delete(listener);
444
- }
445
- __name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
446
- function subscribeFarmCacheTask(listener) {
447
- const state = getFarmCacheInvalidationState();
448
- state.taskListeners.add(listener);
449
- return () => state.taskListeners.delete(listener);
450
- }
451
- __name(subscribeFarmCacheTask, "subscribeFarmCacheTask");
452
20
 
453
- // src/cache-invalidation-stream.ts
454
- var MAX_BUFFERED_BYTES = 64 * 1024;
455
- var textEncoder = new TextEncoder();
456
-
457
- // src/cache.ts
458
- var _FarmDataCache = class _FarmDataCache {
459
- constructor(config = {}) {
460
- this.entries = /* @__PURE__ */ new Map();
461
- this.inflight = /* @__PURE__ */ new Map();
462
- /** Local entries by tag, so tag counts and pruning never scan unrelated entries. */
463
- this.entriesByTag = /* @__PURE__ */ new Map();
464
- this.invalidatedTagVersions = /* @__PURE__ */ new Map();
465
- this.activeGenerations = /* @__PURE__ */ new Set();
466
- this.version = 0;
467
- this.generation = 0;
468
- this.namespace = "farm";
469
- this.local = true;
470
- this.maxEntries = 1024;
471
- this.lease = {
472
- enabled: true,
473
- ttlMs: 1e4,
474
- waitTimeoutMs: 1e4,
475
- pollIntervalMs: 25
476
- };
477
- this.configure(config);
478
- }
479
- configure(config = {}) {
480
- this.generation++;
481
- this.entries.clear();
482
- this.entriesByTag.clear();
483
- this.inflight.clear();
484
- this.invalidatedTagVersions.clear();
485
- this.activeGenerations.clear();
486
- this.version = 0;
487
- this.adapter = config.adapter;
488
- this.namespace = normalizeCacheNamespace(config.namespace || "farm");
489
- this.local = !config.adapter;
490
- this.maxEntries = normalizePositiveInteger(config.maxEntries, 1024, "cache.maxEntries");
491
- this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
492
- enabled: true,
493
- ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
494
- waitTimeoutMs: normalizePositiveDuration(
495
- config.lease?.waitTimeoutMs,
496
- 1e4,
497
- "cache.lease.waitTimeoutMs"
498
- ),
499
- pollIntervalMs: normalizePositiveDuration(
500
- config.lease?.pollIntervalMs,
501
- 25,
502
- "cache.lease.pollIntervalMs"
503
- )
504
- };
505
- }
506
- get adapterName() {
507
- return this.adapter?.name || (this.adapter ? "custom" : "memory");
508
- }
509
- get hasAdapter() {
510
- return this.adapter !== void 0;
511
- }
512
- get size() {
513
- return this.entries.size;
514
- }
515
- get(key, options = {}) {
516
- return this.getEntry(key, options)?.value;
517
- }
518
- getEntry(key, options = {}) {
519
- const entry = this.entries.get(key);
520
- if (!entry) {
521
- emitFarmEvent({ type: "cache.miss", key });
522
- return void 0;
523
- }
524
- const stale = this.isStale(entry, options.now);
525
- if (stale) {
526
- emitFarmEvent({
527
- type: "cache.stale",
528
- key,
529
- tags: Array.from(entry.tags),
530
- revalidate: entry.revalidate
531
- });
532
- }
533
- if (!options.allowStale && stale) {
534
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
535
- return void 0;
536
- }
537
- this.touchEntry(key, entry);
538
- emitFarmEvent({
539
- type: "cache.hit",
540
- key,
541
- tags: Array.from(entry.tags),
542
- revalidate: entry.revalidate,
543
- stale
544
- });
545
- return this.toPublicEntry(entry);
546
- }
547
- async getEntryAsync(key, options = {}) {
548
- if (this.local) {
549
- const localEntry = this.getEntry(key, options);
550
- if (localEntry) return localEntry;
551
- }
552
- if (!this.adapter) {
553
- return this.local ? void 0 : this.getEntry(key, options);
554
- }
555
- const generation = this.generation;
556
- const adapter = this.adapter;
557
- const namespace = this.namespace;
558
- const entry = await adapter.get(`${namespace}:entry:${key}`);
559
- if (generation !== this.generation) return void 0;
560
- if (!entry) {
561
- emitFarmEvent({ type: "cache.miss", key });
562
- return void 0;
563
- }
564
- assertFarmCacheEntry(entry, key);
565
- const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);
566
- if (generation !== this.generation) return void 0;
567
- if (stale) {
568
- emitFarmEvent({
569
- type: "cache.stale",
570
- key,
571
- tags: [...entry.tags],
572
- revalidate: entry.revalidate
573
- });
574
- if (!options.allowStale) {
575
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
576
- return void 0;
577
- }
578
- }
579
- emitFarmEvent({
580
- type: "cache.hit",
581
- key,
582
- tags: [...entry.tags],
583
- revalidate: entry.revalidate,
584
- stale
585
- });
586
- if (this.local && !stale) {
587
- this.hydrateLocalEntry(entry);
588
- }
589
- return { ...entry, key };
590
- }
591
- set(key, value, options = {}) {
592
- const revalidate = normalizeRevalidate(options.revalidate);
593
- const tags = /* @__PURE__ */ new Set();
594
- for (const tag of options.tags ?? []) {
595
- tags.add(normalizeCacheTag(tag));
596
- }
597
- for (const routePath of options.paths ?? []) {
598
- tags.add(createPathCacheTag(routePath));
599
- }
600
- const entry = {
601
- key,
602
- value,
603
- tags,
604
- tagVersions: void 0,
605
- createdAt: options.createdAt ?? Date.now(),
606
- createdVersion: ++this.version,
607
- revalidate
608
- };
609
- this.storeLocalEntry(entry);
610
- emitFarmEvent({
611
- type: "cache.set",
612
- key,
613
- tags: Array.from(tags),
614
- revalidate: entry.revalidate
615
- });
616
- return this.toPublicEntry(entry);
617
- }
618
- async setAsync(key, value, options = {}, tagVersions) {
619
- return this.writeAsync(key, value, options, tagVersions);
620
- }
621
- async writeAsync(key, value, options, tagVersions, createdVersion) {
622
- const revalidate = normalizeRevalidate(options.revalidate);
623
- const tags = normalizeCacheOptionsTags(options);
624
- const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
625
- const entry = {
626
- key,
627
- value,
628
- tags: Array.from(tags),
629
- tagVersions: capturedVersions,
630
- createdAt: options.createdAt ?? Date.now(),
631
- createdVersion: createdVersion ?? ++this.version,
632
- revalidate
633
- };
634
- if (this.local) {
635
- this.hydrateLocalEntry(entry);
636
- }
637
- if (this.adapter) {
638
- await this.adapter.set(this.createAdapterKey(key), entry);
639
- }
640
- emitFarmEvent({
641
- type: "cache.set",
642
- key,
643
- tags: [...entry.tags],
644
- revalidate: entry.revalidate
645
- });
646
- return entry;
647
- }
648
- delete(key) {
649
- const deleted = this.deleteLocalEntry(key);
650
- emitFarmEvent({ type: "cache.delete", key, deleted });
651
- return deleted;
652
- }
653
- async deleteAsync(key) {
654
- const deleted = this.deleteLocalEntry(key);
655
- if (this.adapter) {
656
- await this.adapter.delete(this.createAdapterKey(key));
657
- }
658
- emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
659
- return this.adapter ? true : deleted;
660
- }
661
- clear() {
662
- const count = this.entries.size;
663
- this.generation++;
664
- this.entries.clear();
665
- this.entriesByTag.clear();
666
- this.inflight.clear();
667
- this.invalidatedTagVersions.clear();
668
- this.activeGenerations.clear();
669
- this.version = 0;
670
- emitFarmEvent({ type: "cache.clear", count });
671
- }
672
- async clearAsync() {
673
- this.clear();
674
- await this.adapter?.clear?.();
675
- }
676
- isStale(entry, now = Date.now()) {
677
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
678
- return true;
679
- }
680
- for (const tag of entry.tags) {
681
- const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
682
- if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
683
- return true;
684
- }
685
- }
686
- return false;
687
- }
688
- async isStaleAsync(entry, now = Date.now()) {
689
- if (this.adapter) {
690
- return this.isAdapterEntryStale(entry, now);
691
- }
692
- return this.isStale(entry, now);
693
- }
694
- revalidateTag(tag, options = {}) {
695
- const normalized = normalizeCacheTag(tag);
696
- const count = this.invalidateTag(normalized);
697
- emitFarmEvent(
698
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
699
- );
700
- return count;
701
- }
702
- async revalidateTagAsync(tag, options = {}) {
703
- const normalized = normalizeCacheTag(tag);
704
- const count = this.invalidateTag(normalized);
705
- await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
706
- emitFarmEvent(
707
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
708
- );
709
- return count;
710
- }
711
- revalidatePath(routePath) {
712
- const normalizedPath = normalizeRevalidatePath(routePath);
713
- const pathTag = createPathCacheTag(normalizedPath);
714
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
715
- const count = this.invalidateTag(pathTag);
716
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
717
- if (pprCount > 0) {
718
- emitFarmEvent({
719
- type: "ppr.shell.invalidated",
720
- route: normalizedPath,
721
- reason: "revalidatePath",
722
- count: pprCount
723
- });
724
- }
725
- return count;
726
- }
727
- async revalidatePathAsync(routePath) {
728
- const normalizedPath = normalizeRevalidatePath(routePath);
729
- const pathTag = createPathCacheTag(normalizedPath);
730
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
731
- const count = this.invalidateTag(pathTag);
732
- await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
733
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
734
- if (pprCount > 0) {
735
- emitFarmEvent({
736
- type: "ppr.shell.invalidated",
737
- route: normalizedPath,
738
- reason: "revalidatePath",
739
- count: pprCount
740
- });
741
- }
742
- return count;
743
- }
744
- async getOrSet(key, producer, options = {}) {
745
- normalizeRevalidate(options.revalidate);
746
- const cached = await this.getEntryAsync(key);
747
- if (cached) {
748
- return cached.value;
749
- }
750
- const inflight = this.inflight.get(key);
751
- if (inflight && !this.wasInvalidatedSince(inflight.tags, inflight.startVersion)) {
752
- emitFarmEvent({ type: "cache.dedupe", key });
753
- return inflight.promise;
754
- }
755
- const tags = Array.from(normalizeCacheOptionsTags(options));
756
- const generation = this.generation;
757
- const startVersion = this.version;
758
- const promise = this.fillCacheEntry(key, producer, options, tags, generation).catch((error) => {
759
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
760
- throw error;
761
- }).finally(() => {
762
- if (this.inflight.get(key)?.promise === promise) {
763
- this.inflight.delete(key);
764
- }
765
- });
766
- this.inflight.set(key, { promise, tags, startVersion });
767
- return promise;
768
- }
769
- /** A fill that started before one of its tags was invalidated cannot satisfy later readers. */
770
- wasInvalidatedSince(tags, version) {
771
- for (const tag of tags) {
772
- const invalidatedVersion = this.invalidatedTagVersions.get(tag);
773
- if (invalidatedVersion !== void 0 && invalidatedVersion > version) return true;
774
- }
775
- return false;
776
- }
777
- async fillCacheEntry(key, producer, options, tags, generation) {
778
- const adapter = this.adapter;
779
- const namespace = this.namespace;
780
- const lease = { ...this.lease };
781
- const leaseKey = `${namespace}:lease:${key}`;
782
- let leaseToken;
783
- if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {
784
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
785
- if (!leaseToken) {
786
- const shared2 = await this.waitForAdapterEntry(
787
- key,
788
- adapter,
789
- namespace,
790
- lease,
791
- generation
792
- );
793
- if (shared2) {
794
- emitFarmEvent({ type: "cache.dedupe", key });
795
- return shared2.value;
796
- }
797
- if (generation === this.generation) {
798
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
799
- }
800
- }
801
- }
802
- const initialCreatedVersion = this.version;
803
- const activeGeneration = {
804
- tags: new Set(tags),
805
- createdVersion: initialCreatedVersion
806
- };
807
- this.activeGenerations.add(activeGeneration);
808
- try {
809
- const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);
810
- const value = await producer();
811
- if (generation === this.generation) {
812
- await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);
813
- }
814
- return value;
815
- } finally {
816
- this.activeGenerations.delete(activeGeneration);
817
- this.pruneInvalidatedTagVersions(activeGeneration.tags);
818
- if (leaseToken && adapter?.releaseLease) {
819
- try {
820
- await adapter.releaseLease(leaseKey, leaseToken);
821
- } catch (error) {
822
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
823
- }
824
- }
825
- }
826
- }
827
- async waitForAdapterEntry(key, adapter, namespace, lease, generation) {
828
- const deadline = Date.now() + lease.waitTimeoutMs;
829
- while (Date.now() < deadline) {
830
- await delay(lease.pollIntervalMs);
831
- if (generation !== this.generation) return void 0;
832
- const entry = await adapter.get(`${namespace}:entry:${key}`);
833
- if (generation !== this.generation) return void 0;
834
- if (!entry) {
835
- emitFarmEvent({ type: "cache.miss", key });
836
- continue;
837
- }
838
- assertFarmCacheEntry(entry, key);
839
- const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);
840
- if (generation !== this.generation) return void 0;
841
- if (stale) {
842
- emitFarmEvent({
843
- type: "cache.stale",
844
- key,
845
- tags: [...entry.tags],
846
- revalidate: entry.revalidate
847
- });
848
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
849
- } else {
850
- emitFarmEvent({
851
- type: "cache.hit",
852
- key,
853
- tags: [...entry.tags],
854
- revalidate: entry.revalidate,
855
- stale: false
856
- });
857
- return { ...entry, key };
858
- }
859
- }
860
- return void 0;
861
- }
862
- countEntriesForTags(tags) {
863
- let count = 0;
864
- for (const entry of this.entriesByTag.get(tags[0]) ?? []) {
865
- if (tags.every((tag) => entry.tags.has(tag))) {
866
- count++;
867
- }
868
- }
869
- return count;
870
- }
871
- invalidateTag(normalizedTag) {
872
- const count = this.entriesByTag.get(normalizedTag)?.size ?? 0;
873
- this.invalidatedTagVersions.delete(normalizedTag);
874
- this.invalidatedTagVersions.set(normalizedTag, ++this.version);
875
- this.pruneInvalidatedTagVersions([normalizedTag]);
876
- return count;
877
- }
878
- toPublicEntry(entry) {
879
- return {
880
- key: entry.key,
881
- value: entry.value,
882
- tags: Array.from(entry.tags),
883
- tagVersions: entry.tagVersions,
884
- createdAt: entry.createdAt,
885
- createdVersion: entry.createdVersion,
886
- revalidate: entry.revalidate
887
- };
888
- }
889
- hydrateLocalEntry(entry) {
890
- this.storeLocalEntry({
891
- key: entry.key,
892
- value: entry.value,
893
- tags: new Set(entry.tags.map(normalizeCacheTag)),
894
- tagVersions: entry.tagVersions,
895
- createdAt: entry.createdAt,
896
- createdVersion: entry.createdVersion ?? ++this.version,
897
- revalidate: normalizeRevalidate(entry.revalidate)
898
- });
899
- }
900
- touchEntry(key, entry) {
901
- this.entries.delete(key);
902
- this.entries.set(key, entry);
903
- }
904
- storeLocalEntry(entry) {
905
- const removed = [];
906
- const replaced = this.detachLocalEntry(entry.key);
907
- if (replaced) removed.push(replaced);
908
- this.entries.set(entry.key, entry);
909
- for (const tag of entry.tags) {
910
- let tagged = this.entriesByTag.get(tag);
911
- if (!tagged) this.entriesByTag.set(tag, tagged = /* @__PURE__ */ new Set());
912
- tagged.add(entry);
913
- }
914
- while (this.entries.size > this.maxEntries) {
915
- const oldestKey = this.entries.keys().next().value;
916
- if (oldestKey === void 0) break;
917
- removed.push(this.detachLocalEntry(oldestKey));
918
- }
919
- for (const removedEntry of removed) this.pruneInvalidatedTagVersions(removedEntry.tags);
920
- }
921
- deleteLocalEntry(key) {
922
- const entry = this.detachLocalEntry(key);
923
- if (!entry) return false;
924
- this.pruneInvalidatedTagVersions(entry.tags);
925
- return true;
926
- }
927
- detachLocalEntry(key) {
928
- const entry = this.entries.get(key);
929
- if (!entry) return void 0;
930
- this.entries.delete(key);
931
- for (const tag of entry.tags) {
932
- const tagged = this.entriesByTag.get(tag);
933
- if (!tagged) continue;
934
- tagged.delete(entry);
935
- if (tagged.size === 0) this.entriesByTag.delete(tag);
936
- }
937
- return entry;
938
- }
939
- /**
940
- * Drop invalidation versions that no local entry or active fill can be stale against.
941
- * Callers pass only the tags whose dependents just changed, so the cost is bounded by
942
- * the entries sharing those tags rather than by the whole cache.
943
- */
944
- pruneInvalidatedTagVersions(tags) {
945
- tags: for (const tag of tags) {
946
- const invalidatedVersion = this.invalidatedTagVersions.get(tag);
947
- if (invalidatedVersion === void 0) continue;
948
- for (const entry of this.entriesByTag.get(tag) ?? []) {
949
- if (entry.createdVersion < invalidatedVersion) continue tags;
950
- }
951
- for (const generation of this.activeGenerations) {
952
- if (generation.tags.has(tag) && generation.createdVersion < invalidatedVersion)
953
- continue tags;
954
- }
955
- this.invalidatedTagVersions.delete(tag);
956
- }
957
- }
958
- createAdapterKey(key) {
959
- return `${this.namespace}:entry:${key}`;
960
- }
961
- createAdapterTag(tag) {
962
- return `${this.namespace}:tag:${tag}`;
963
- }
964
- async getAdapterTagVersions(tags, adapter = this.adapter, namespace = this.namespace) {
965
- if (!adapter?.getTagVersions || tags.length === 0) return {};
966
- const normalized = tags.map(normalizeCacheTag);
967
- const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);
968
- const versions = await adapter.getTagVersions(physicalTags);
969
- return Object.fromEntries(
970
- normalized.map((tag, index) => [
971
- tag,
972
- normalizeAdapterVersion(versions[physicalTags[index]])
973
- ])
974
- );
975
- }
976
- async isAdapterEntryStale(entry, now = Date.now(), adapter = this.adapter, namespace = this.namespace) {
977
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
978
- return true;
979
- }
980
- const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);
981
- for (const tag of entry.tags) {
982
- if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
983
- return true;
984
- }
985
- }
986
- return false;
987
- }
988
- };
989
- __name(_FarmDataCache, "FarmDataCache");
990
- var FarmDataCache = _FarmDataCache;
991
- var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
992
- var farmDataCacheGlobal = globalThis;
993
- var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
994
- function getFarmDataCache() {
995
- return sharedFarmDataCache;
996
- }
997
- __name(getFarmDataCache, "getFarmDataCache");
998
- function updateTag(tag) {
999
- const cache = getFarmDataCache();
1000
- if (cache.hasAdapter) {
1001
- const task = cache.revalidateTagAsync(tag, { source: "updateTag" }).then(() => void 0);
1002
- notifyFarmCacheTask(task);
1003
- return task;
1004
- }
1005
- cache.revalidateTag(tag, { source: "updateTag" });
1006
- }
1007
- __name(updateTag, "updateTag");
1008
- function revalidatePath(routePath) {
1009
- const cache = getFarmDataCache();
1010
- if (cache.hasAdapter) {
1011
- const task = cache.revalidatePathAsync(routePath).then(() => void 0);
1012
- notifyFarmCacheTask(task);
1013
- return task;
1014
- }
1015
- cache.revalidatePath(routePath);
1016
- }
1017
- __name(revalidatePath, "revalidatePath");
1018
- function invalidate(key) {
1019
- const clientKey = createRouteDataCacheKey(key);
1020
- const task = updateTag(createRouteDataCacheTag(key));
1021
- notifyFarmCacheInvalidation(clientKey);
1022
- return task;
1023
- }
1024
- __name(invalidate, "invalidate");
1025
- async function applyFarmCacheInvalidationTargets(targets) {
1026
- if (!Array.isArray(targets)) {
1027
- throw new TypeError("Cache invalidations must resolve to an array of targets.");
1028
- }
1029
- const clientKeys = [];
1030
- for (const target of targets) {
1031
- assertFarmCacheInvalidationTarget(target);
1032
- if ("key" in target) {
1033
- await invalidate(target.key);
1034
- clientKeys.push(createRouteDataCacheKey(target.key));
1035
- } else if ("path" in target) {
1036
- await revalidatePath(target.path);
1037
- } else {
1038
- await updateTag(target.tag);
1039
- }
1040
- }
1041
- return Array.from(new Set(clientKeys));
1042
- }
1043
- __name(applyFarmCacheInvalidationTargets, "applyFarmCacheInvalidationTargets");
1044
- function createPathCacheTag(routePath) {
1045
- return `path:${normalizeRevalidatePath(routePath)}`;
1046
- }
1047
- __name(createPathCacheTag, "createPathCacheTag");
1048
- function createRouteDataCacheTag(key) {
1049
- return `route-data:${createRouteDataCacheKey(key)}`;
1050
- }
1051
- __name(createRouteDataCacheTag, "createRouteDataCacheTag");
1052
- function createRouteDataCacheKey(key) {
1053
- return createFarmCacheKey(Array.isArray(key) ? key : [key]);
1054
- }
1055
- __name(createRouteDataCacheKey, "createRouteDataCacheKey");
1056
- function normalizeRevalidatePath(routePath) {
1057
- if (typeof routePath !== "string") {
1058
- throw new TypeError("revalidatePath expects a path string.");
1059
- }
1060
- let normalized = routePath.trim();
1061
- if (!normalized) {
1062
- throw new Error("revalidatePath expects a non-empty path.");
1063
- }
1064
- try {
1065
- if (/^https?:\/\//i.test(normalized)) {
1066
- normalized = new URL(normalized).pathname;
1067
- }
1068
- } catch {
1069
- }
1070
- normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;
1071
- normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
1072
- normalized = normalized.replace(/\/{2,}/g, "/");
1073
- normalized = new URL(normalized, "http://farm.invalid").pathname;
1074
- if (normalized.length > 1) {
1075
- normalized = normalized.replace(/\/+$/, "");
1076
- }
1077
- return normalized || "/";
1078
- }
1079
- __name(normalizeRevalidatePath, "normalizeRevalidatePath");
1080
- function createFarmCacheKey(parts) {
1081
- return stableSerialize(parts);
1082
- }
1083
- __name(createFarmCacheKey, "createFarmCacheKey");
1084
- function normalizeRevalidate(revalidate) {
1085
- if (revalidate === false || revalidate === void 0) {
1086
- return revalidate;
1087
- }
1088
- if (!Number.isFinite(revalidate) || revalidate < 0) {
1089
- throw new TypeError("Cache revalidate must be false or a finite, non-negative number.");
1090
- }
1091
- return revalidate;
1092
- }
1093
- __name(normalizeRevalidate, "normalizeRevalidate");
1094
- function normalizeCacheTag(tag) {
1095
- if (typeof tag !== "string") {
1096
- throw new TypeError("Cache tags must be strings.");
1097
- }
1098
- const normalized = tag.trim();
1099
- if (!normalized) {
1100
- throw new Error("Cache tags cannot be empty.");
1101
- }
1102
- return normalized;
1103
- }
1104
- __name(normalizeCacheTag, "normalizeCacheTag");
1105
- function normalizeCacheNamespace(namespace) {
1106
- if (typeof namespace !== "string") {
1107
- throw new TypeError("Cache namespace must be a string.");
1108
- }
1109
- const normalized = namespace.trim().replace(/:+$/g, "");
1110
- if (!normalized) {
1111
- throw new Error("Cache namespace cannot be empty.");
1112
- }
1113
- return normalized;
1114
- }
1115
- __name(normalizeCacheNamespace, "normalizeCacheNamespace");
1116
- function normalizeAdapterVersion(value) {
1117
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
1118
- }
1119
- __name(normalizeAdapterVersion, "normalizeAdapterVersion");
1120
- function normalizePositiveDuration(value, fallback, name) {
1121
- if (value === void 0) return fallback;
1122
- if (!Number.isFinite(value) || value <= 0) {
1123
- throw new TypeError(`${name} must be a positive number of milliseconds.`);
1124
- }
1125
- return Math.floor(value);
1126
- }
1127
- __name(normalizePositiveDuration, "normalizePositiveDuration");
1128
- function normalizePositiveInteger(value, fallback, name) {
1129
- if (value === void 0) return fallback;
1130
- if (!Number.isSafeInteger(value) || value <= 0) {
1131
- throw new TypeError(`${name} must be a positive integer.`);
1132
- }
1133
- return value;
1134
- }
1135
- __name(normalizePositiveInteger, "normalizePositiveInteger");
1136
- function delay(ms) {
1137
- return new Promise((resolve) => setTimeout(resolve, ms));
1138
- }
1139
- __name(delay, "delay");
1140
- function normalizeCacheOptionsTags(options) {
1141
- const tags = /* @__PURE__ */ new Set();
1142
- for (const tag of options.tags ?? []) {
1143
- tags.add(normalizeCacheTag(tag));
1144
- }
1145
- for (const routePath of options.paths ?? []) {
1146
- tags.add(createPathCacheTag(routePath));
1147
- }
1148
- return tags;
1149
- }
1150
- __name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
1151
- function assertFarmCacheEntry(entry, expectedKey) {
1152
- if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
1153
- throw new TypeError(
1154
- `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
1155
- );
1156
- }
1157
- }
1158
- __name(assertFarmCacheEntry, "assertFarmCacheEntry");
1159
- function assertFarmCacheInvalidationTarget(target) {
1160
- if (!target || typeof target !== "object") {
1161
- throw new TypeError("Cache invalidation targets must be { key }, { path }, or { tag }.");
1162
- }
1163
- if ("key" in target) {
1164
- const key = target.key;
1165
- if (typeof key === "string" || Array.isArray(key)) return;
1166
- } else if ("path" in target && typeof target.path === "string") {
1167
- return;
1168
- } else if ("tag" in target && typeof target.tag === "string") {
1169
- return;
1170
- }
1171
- throw new TypeError("Cache invalidation targets must contain a string/array key, path, or tag.");
1172
- }
1173
- __name(assertFarmCacheInvalidationTarget, "assertFarmCacheInvalidationTarget");
1174
- function getFunctionCacheIdentity(fn) {
1175
- const name = fn.name || "anonymous";
1176
- return `${name}:${hashFunctionSource(String(fn))}`;
1177
- }
1178
- __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
1179
- function hashFunctionSource(source) {
1180
- let hash = 2166136261;
1181
- for (let index = 0; index < source.length; index++) {
1182
- hash ^= source.charCodeAt(index);
1183
- hash = Math.imul(hash, 16777619);
1184
- }
1185
- return (hash >>> 0).toString(36);
1186
- }
1187
- __name(hashFunctionSource, "hashFunctionSource");
1188
- function compareCodepoint(a, b) {
1189
- return a < b ? -1 : a > b ? 1 : 0;
1190
- }
1191
- __name(compareCodepoint, "compareCodepoint");
1192
- function serializeBinaryBytes(bytes) {
1193
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1194
- }
1195
- __name(serializeBinaryBytes, "serializeBinaryBytes");
1196
- function serializeCanonicalStringEntries(entries, seen) {
1197
- const valuesByKey = /* @__PURE__ */ new Map();
1198
- for (const [key, item] of entries) {
1199
- const values = valuesByKey.get(key);
1200
- if (values) values.push(item);
1201
- else valuesByKey.set(key, [item]);
1202
- }
1203
- return Array.from(valuesByKey.keys()).sort(compareCodepoint).flatMap(
1204
- (key) => valuesByKey.get(key).map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`)
1205
- ).join(",");
1206
- }
1207
- __name(serializeCanonicalStringEntries, "serializeCanonicalStringEntries");
1208
- function isPlainCacheKeyObject(value) {
1209
- const prototype = Object.getPrototypeOf(value);
1210
- if (prototype === null) return true;
1211
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
1212
- return Object.getPrototypeOf(prototype) === null && typeof constructor === "function" && constructor.name === "Object";
1213
- }
1214
- __name(isPlainCacheKeyObject, "isPlainCacheKeyObject");
1215
- function getCacheKeyValueType(value) {
1216
- const prototype = Object.getPrototypeOf(value);
1217
- const constructor = prototype ? Object.getOwnPropertyDescriptor(prototype, "constructor")?.value : void 0;
1218
- if (typeof constructor === "function" && constructor.name) {
1219
- return constructor.name;
1220
- }
1221
- return Object.prototype.toString.call(value).slice(8, -1) || "object";
1222
- }
1223
- __name(getCacheKeyValueType, "getCacheKeyValueType");
1224
- function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
1225
- if (value === null) return "null";
1226
- if (value === void 0) return "undefined";
1227
- const valueType = typeof value;
1228
- if (valueType === "string") return JSON.stringify(value);
1229
- if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
1230
- return `${valueType}:${String(value)}`;
1231
- }
1232
- if (valueType === "symbol") {
1233
- return `symbol:${String(value)}`;
1234
- }
1235
- if (valueType === "function") {
1236
- return `function:${getFunctionCacheIdentity(value)}`;
1237
- }
1238
- if (value instanceof Date) {
1239
- return Number.isNaN(value.getTime()) ? "date:invalid" : `date:${value.toISOString()}`;
1240
- }
1241
- if (value instanceof URL) {
1242
- return `url:${value.toString()}`;
1243
- }
1244
- if (value instanceof RegExp) {
1245
- return `regexp:${value.toString()}`;
1246
- }
1247
- if (value instanceof ArrayBuffer) {
1248
- return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
1249
- }
1250
- if (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer) {
1251
- return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
1252
- }
1253
- if (ArrayBuffer.isView(value)) {
1254
- const viewType = Object.prototype.toString.call(value).slice(8, -1);
1255
- const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
1256
- return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;
1257
- }
1258
- if (value && typeof value === "object") {
1259
- if (seen.has(value)) {
1260
- return "[Circular]";
1261
- }
1262
- seen.add(value);
1263
- if (Array.isArray(value)) {
1264
- const items = [];
1265
- for (let index = 0; index < value.length; index++) {
1266
- items.push(
1267
- Object.prototype.hasOwnProperty.call(value, index) ? stableSerialize(value[index], seen) : "[Hole]"
1268
- );
1269
- }
1270
- seen.delete(value);
1271
- return `[${items.join(",")}]`;
1272
- }
1273
- if (value instanceof Set) {
1274
- const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);
1275
- seen.delete(value);
1276
- return `set:[${items.join(",")}]`;
1277
- }
1278
- if (value instanceof Map) {
1279
- const items = Array.from(
1280
- value,
1281
- ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`
1282
- ).sort(compareCodepoint);
1283
- seen.delete(value);
1284
- return `map:[${items.join(",")}]`;
1285
- }
1286
- if (value instanceof URLSearchParams) {
1287
- const serialized2 = serializeCanonicalStringEntries(value, seen);
1288
- seen.delete(value);
1289
- return `urlsearchparams:[${serialized2}]`;
1290
- }
1291
- if (value instanceof Headers) {
1292
- const serialized2 = serializeCanonicalStringEntries(value, seen);
1293
- seen.delete(value);
1294
- return `headers:[${serialized2}]`;
1295
- }
1296
- if (!isPlainCacheKeyObject(value)) {
1297
- throw new TypeError(
1298
- `Cache keys do not support ${getCacheKeyValueType(value)} values. Convert the value to an explicit stable string or structured key before caching.`
1299
- );
1300
- }
1301
- const entries = Object.entries(value).sort(
1302
- ([a], [b]) => compareCodepoint(a, b)
1303
- );
1304
- const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
1305
- seen.delete(value);
1306
- return `{${serialized}}`;
1307
- }
1308
- return String(value);
1309
- }
1310
- __name(stableSerialize, "stableSerialize");
1311
-
1312
- // src/server-action-security.ts
1313
- var import_node_async_hooks = require("async_hooks");
1314
-
1315
- // src/server-fn-error.ts
1316
- var FARM_SERVER_FN_FAILURE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.server-fn.failure");
1317
- var _ServerFnFailure = class _ServerFnFailure extends Error {
1318
- constructor(code, data, options) {
1319
- super(options.message);
1320
- this.name = "ServerFnFailure";
1321
- this.code = code;
1322
- this.data = data;
1323
- this.status = options.status;
1324
- Object.defineProperty(this, FARM_SERVER_FN_FAILURE_SYMBOL, {
1325
- value: true,
1326
- enumerable: false
1327
- });
1328
- }
1329
- };
1330
- __name(_ServerFnFailure, "ServerFnFailure");
1331
- var ServerFnFailure = _ServerFnFailure;
1332
-
1333
- // src/server-action-security.ts
1334
- var SERVER_ACTION_STORAGE_KEY = /* @__PURE__ */ Symbol.for("farm.serverActionStorage");
1335
- var FALLBACK_ABORT_CONTROLLER_KEY = /* @__PURE__ */ Symbol.for("farm.serverActionFallbackAbortController");
1336
- function getServerActionExecutionContext() {
1337
- return getServerActionStorage().getStore();
1338
- }
1339
- __name(getServerActionExecutionContext, "getServerActionExecutionContext");
1340
- function getServerActionSignal() {
1341
- return getServerActionExecutionContext()?.signal ?? getFallbackAbortController().signal;
1342
- }
1343
- __name(getServerActionSignal, "getServerActionSignal");
1344
- subscribeFarmCacheInvalidation((key) => {
1345
- getServerActionExecutionContext()?.invalidations.add(key);
1346
- });
1347
- subscribeFarmCacheTask((task) => {
1348
- getServerActionExecutionContext()?.cacheTasks.add(task);
1349
- });
1350
- function getServerActionStorage() {
1351
- const globalState2 = globalThis;
1352
- if (!globalState2[SERVER_ACTION_STORAGE_KEY]) {
1353
- globalState2[SERVER_ACTION_STORAGE_KEY] = new import_node_async_hooks.AsyncLocalStorage();
1354
- }
1355
- return globalState2[SERVER_ACTION_STORAGE_KEY];
1356
- }
1357
- __name(getServerActionStorage, "getServerActionStorage");
1358
- function getFallbackAbortController() {
1359
- const globalState2 = globalThis;
1360
- if (!globalState2[FALLBACK_ABORT_CONTROLLER_KEY]) {
1361
- globalState2[FALLBACK_ABORT_CONTROLLER_KEY] = new AbortController();
1362
- }
1363
- return globalState2[FALLBACK_ABORT_CONTROLLER_KEY];
1364
- }
1365
- __name(getFallbackAbortController, "getFallbackAbortController");
1366
-
1367
- // src/server/request-bridge.ts
1368
- var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
1369
- function getGlobalState() {
1370
- return globalThis;
1371
- }
1372
- __name(getGlobalState, "getGlobalState");
1373
- function _resolveCurrentRequest() {
1374
- return getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY]?.();
1375
- }
1376
- __name(_resolveCurrentRequest, "_resolveCurrentRequest");
1377
-
1378
- // src/server-fn.ts
1379
- var FARM_SERVER_FN_SYMBOL = /* @__PURE__ */ Symbol.for("farm.server-fn");
1380
- var FARM_SERVER_FUNCTION_DESCRIPTOR = /* @__PURE__ */ Symbol.for("farm.server-function.descriptor");
1381
- var _ServerFnInputError = class _ServerFnInputError extends Error {
1382
- constructor(cause) {
1383
- super("Server function input is invalid");
1384
- this.cause = cause;
1385
- }
1386
- };
1387
- __name(_ServerFnInputError, "ServerFnInputError");
1388
- var ServerFnInputError = _ServerFnInputError;
1389
- function createServerFunctionDescriptor(kind, options, run) {
1390
- return Object.freeze({
1391
- kind,
1392
- input: options.input,
1393
- output: options.output,
1394
- mcp: options.mcp === void 0 ? void 0 : Object.freeze({ ...options.mcp }),
1395
- run
1396
- });
1397
- }
1398
- __name(createServerFunctionDescriptor, "createServerFunctionDescriptor");
1399
- function _attachServerFunctionDescriptor(target, descriptor) {
1400
- Object.defineProperty(target, FARM_SERVER_FUNCTION_DESCRIPTOR, {
1401
- value: descriptor,
1402
- enumerable: false
1403
- });
1404
- }
1405
- __name(_attachServerFunctionDescriptor, "_attachServerFunctionDescriptor");
1406
- function getServerFunctionRunner(value) {
1407
- if (typeof value !== "function") return void 0;
1408
- return value[FARM_SERVER_FUNCTION_DESCRIPTOR];
1409
- }
1410
- __name(getServerFunctionRunner, "getServerFunctionRunner");
1411
- function _runServerFunctionForCaller(value, input) {
1412
- const runner = getServerFunctionRunner(value);
1413
- if (!runner) throw new TypeError("Expected a function created with createServerFn");
1414
- return runner.run(input);
1415
- }
1416
- __name(_runServerFunctionForCaller, "_runServerFunctionForCaller");
1417
- var UNSAFE_FORM_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1418
- function createServerFn(options) {
1419
- if (!options || typeof options.handler !== "function") {
1420
- throw new TypeError("createServerFn requires a handler function");
1421
- }
1422
- const middleware = resolveServerFnMiddleware(options.middleware);
1423
- const errors = normalizeServerFnErrors(options.errors);
1424
- const error = createServerFnErrorHandler(errors);
1425
- const run = /* @__PURE__ */ __name(async (value, labelInputErrors) => {
1426
- const formData = isFormData(value) ? value : void 0;
1427
- const rawInput = formData ? formDataToObject(formData) : value;
1428
- let input;
1429
- try {
1430
- input = await _parseServerFnSchema(options.input, rawInput, "input");
1431
- } catch (cause) {
1432
- throw labelInputErrors && isSchemaValidationFailure(cause) ? new ServerFnInputError(cause) : cause;
1433
- }
1434
- const executionContext = getServerActionExecutionContext();
1435
- const request = executionContext?.request ?? _resolveCurrentRequest();
1436
- const signal = executionContext?.signal ?? request?.signal ?? getServerActionSignal();
1437
- const handlerContext = {
1438
- input,
1439
- rawInput,
1440
- formData,
1441
- request,
1442
- signal
1443
- };
1444
- let resolvedContext = Object.freeze(/* @__PURE__ */ Object.create(null));
1445
- const result = await runServerFnMiddleware(middleware, handlerContext, async (context2) => {
1446
- resolvedContext = context2.context;
1447
- return options.handler({ ...context2, error });
1448
- });
1449
- const parsedResult = await _parseServerFnSchema(options.output, result, "output");
1450
- if (options.invalidates) {
1451
- const declaration = typeof options.invalidates === "function" ? await options.invalidates({
1452
- ...handlerContext,
1453
- context: resolvedContext,
1454
- result: parsedResult
1455
- }) : options.invalidates;
1456
- await applyFarmCacheInvalidationTargets(declaration);
1457
- }
1458
- return parsedResult;
1459
- }, "run");
1460
- const serverFn = /* @__PURE__ */ __name((value) => run(value, false), "serverFn");
1461
- Object.defineProperties(serverFn, {
1462
- [FARM_SERVER_FN_SYMBOL]: {
1463
- value: true,
1464
- enumerable: false
1465
- },
1466
- __farmServerFn: {
1467
- value: true,
1468
- enumerable: false
1469
- },
1470
- __farmServerFnInput: {
1471
- value: options.input,
1472
- enumerable: false
1473
- },
1474
- __farmServerFnOutput: {
1475
- value: options.output,
1476
- enumerable: false
1477
- },
1478
- __farmServerFnError: {
1479
- value: void 0,
1480
- enumerable: false
1481
- },
1482
- __farmServerFnMiddleware: {
1483
- value: middleware,
1484
- enumerable: false
1485
- },
1486
- __farmServerFnInvalidates: {
1487
- value: options.invalidates,
1488
- enumerable: false
1489
- }
1490
- });
1491
- _attachServerFunctionDescriptor(
1492
- serverFn,
1493
- createServerFunctionDescriptor("action", options, (value) => run(value, true))
1494
- );
1495
- return serverFn;
1496
- }
1497
- __name(createServerFn, "createServerFn");
1498
- async function runServerFnMiddleware(middleware, handlerContext, handler) {
1499
- const dispatch = /* @__PURE__ */ __name(async (index, context2) => {
1500
- const current = middleware[index];
1501
- if (!current) {
1502
- return handler({ ...handlerContext, context: context2 });
1503
- }
1504
- let nextCalled = false;
1505
- const result = await current.handler({
1506
- ...handlerContext,
1507
- context: context2,
1508
- next: /* @__PURE__ */ __name(async (nextOptions) => {
1509
- if (nextCalled) {
1510
- throw new Error("Server function middleware next() can only be called once");
1511
- }
1512
- nextCalled = true;
1513
- return dispatch(index + 1, mergeServerFnContext(context2, nextOptions?.context));
1514
- }, "next")
1515
- });
1516
- if (!nextCalled) {
1517
- throw new Error("Server function middleware must call next()");
1518
- }
1519
- return result;
1520
- }, "dispatch");
1521
- return dispatch(0, Object.freeze(/* @__PURE__ */ Object.create(null)));
1522
- }
1523
- __name(runServerFnMiddleware, "runServerFnMiddleware");
1524
- function normalizeServerFnErrors(definitions) {
1525
- if (definitions === void 0) return Object.freeze({});
1526
- if (!isPlainServerFnObject(definitions)) {
1527
- throw new TypeError("createServerFn errors must be an object");
1528
- }
1529
- const normalized = /* @__PURE__ */ Object.create(null);
1530
- for (const [code, definition] of Object.entries(definitions)) {
1531
- if (!code.trim()) {
1532
- throw new TypeError("Server function error codes cannot be empty");
1533
- }
1534
- if (!definition || typeof definition !== "object") {
1535
- throw new TypeError(`Server function error "${code}" must be an object`);
1536
- }
1537
- if (!Number.isInteger(definition.status) || definition.status < 400 || definition.status > 599) {
1538
- throw new TypeError(
1539
- `Server function error "${code}" status must be an integer between 400 and 599`
1540
- );
1541
- }
1542
- if (!definition.data || typeof definition.data.parse !== "function" && typeof definition.data.safeParse !== "function") {
1543
- throw new TypeError(
1544
- `Server function error "${code}" data must provide synchronous parse() or safeParse()`
1545
- );
1546
- }
1547
- if (definition.message !== void 0 && typeof definition.message !== "string") {
1548
- throw new TypeError(`Server function error "${code}" message must be a string`);
1549
- }
1550
- normalized[code] = Object.freeze({ ...definition });
1551
- }
1552
- return Object.freeze(normalized);
1553
- }
1554
- __name(normalizeServerFnErrors, "normalizeServerFnErrors");
1555
- function createServerFnErrorHandler(definitions) {
1556
- return ((code, data) => {
1557
- const definition = definitions[code];
1558
- if (!definition) {
1559
- throw new TypeError(`Server function error "${code}" is not declared`);
1560
- }
1561
- const parsed = parseServerFnFailureData(code, definition.data, data);
1562
- throw new ServerFnFailure(code, parsed, {
1563
- status: definition.status,
1564
- message: definition.message ?? "Server function failed"
1565
- });
1566
- });
1567
- }
1568
- __name(createServerFnErrorHandler, "createServerFnErrorHandler");
1569
- function parseServerFnFailureData(code, schema, value) {
1570
- if (typeof schema.safeParse === "function") {
1571
- const result2 = schema.safeParse(value);
1572
- if (isPromiseLike(result2)) {
1573
- throw new TypeError(`Server function error "${code}" data schema must parse synchronously`);
1574
- }
1575
- return unwrapSafeParseResult(result2);
1576
- }
1577
- const result = schema.parse(value);
1578
- if (isPromiseLike(result)) {
1579
- throw new TypeError(`Server function error "${code}" data schema must parse synchronously`);
1580
- }
1581
- return result;
1582
- }
1583
- __name(parseServerFnFailureData, "parseServerFnFailureData");
1584
- function isPlainServerFnObject(value) {
1585
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1586
- const prototype = Object.getPrototypeOf(value);
1587
- return prototype === Object.prototype || prototype === null;
1588
- }
1589
- __name(isPlainServerFnObject, "isPlainServerFnObject");
1590
- function isPromiseLike(value) {
1591
- return Boolean(
1592
- value && (typeof value === "object" || typeof value === "function") && "then" in value && typeof value.then === "function"
1593
- );
1594
- }
1595
- __name(isPromiseLike, "isPromiseLike");
1596
- function resolveServerFnMiddleware(middleware) {
1597
- const resolved = [];
1598
- const seen = /* @__PURE__ */ new Set();
1599
- const visiting = /* @__PURE__ */ new Set();
1600
- const visit = /* @__PURE__ */ __name((entry) => {
1601
- assertServerFnMiddleware(entry);
1602
- if (seen.has(entry)) return;
1603
- if (visiting.has(entry)) {
1604
- throw new Error("Server function middleware dependencies cannot contain a cycle");
1605
- }
1606
- visiting.add(entry);
1607
- for (const dependency of entry.middleware) {
1608
- visit(dependency);
1609
- }
1610
- visiting.delete(entry);
1611
- seen.add(entry);
1612
- resolved.push(entry);
1613
- }, "visit");
1614
- for (const entry of middleware ?? []) {
1615
- visit(entry);
1616
- }
1617
- return Object.freeze(resolved);
1618
- }
1619
- __name(resolveServerFnMiddleware, "resolveServerFnMiddleware");
1620
- function assertServerFnMiddleware(value) {
1621
- if (!value || typeof value !== "object" || value.__farmServerFnMiddleware !== true || typeof value.handler !== "function" || !Array.isArray(value.middleware)) {
1622
- throw new TypeError("createServerFn middleware must be created with createServerMiddleware");
1623
- }
1624
- }
1625
- __name(assertServerFnMiddleware, "assertServerFnMiddleware");
1626
- function mergeServerFnContext(current, added) {
1627
- if (added !== void 0 && (added === null || typeof added !== "object" || Array.isArray(added))) {
1628
- throw new TypeError("Server function middleware context must be an object");
1629
- }
1630
- return Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), current, added));
1631
- }
1632
- __name(mergeServerFnContext, "mergeServerFnContext");
1633
- async function _parseServerFnSchema(schema, value, contract, owner = "createServerFn") {
1634
- if (!schema) return value;
1635
- if (typeof schema.safeParseAsync === "function") {
1636
- const result = await schema.safeParseAsync(value);
1637
- return unwrapSafeParseResult(result);
1638
- }
1639
- if (typeof schema.safeParse === "function") {
1640
- const result = schema.safeParse(value);
1641
- return unwrapSafeParseResult(await result);
1642
- }
1643
- if (typeof schema.parseAsync === "function") {
1644
- return schema.parseAsync(value);
1645
- }
1646
- if (typeof schema.parse === "function") {
1647
- return schema.parse(value);
1648
- }
1649
- throw new TypeError(`${owner} ${contract} must provide parse, parseAsync, or safeParse`);
1650
- }
1651
- __name(_parseServerFnSchema, "_parseServerFnSchema");
1652
- var schemaValidationFailures = /* @__PURE__ */ new WeakSet();
1653
- function isSchemaValidationFailure(error) {
1654
- if (!error || typeof error !== "object") return false;
1655
- return schemaValidationFailures.has(error) || Array.isArray(error.issues);
1656
- }
1657
- __name(isSchemaValidationFailure, "isSchemaValidationFailure");
1658
- function unwrapSafeParseResult(result) {
1659
- if (result && typeof result === "object" && "success" in result && result.success === false) {
1660
- const error = result.error;
1661
- if (error && typeof error === "object") schemaValidationFailures.add(error);
1662
- throw error;
1663
- }
1664
- if (result && typeof result === "object" && "success" in result && result.success === true) {
1665
- return result.data;
1666
- }
1667
- return result;
1668
- }
1669
- __name(unwrapSafeParseResult, "unwrapSafeParseResult");
1670
- function formDataToObject(formData) {
1671
- const output = /* @__PURE__ */ Object.create(null);
1672
- for (const [key, value] of formData.entries()) {
1673
- if (!isSafeFormKey(key)) continue;
1674
- const existing = output[key];
1675
- if (existing === void 0) {
1676
- output[key] = value;
1677
- } else if (Array.isArray(existing)) {
1678
- existing.push(value);
1679
- } else {
1680
- output[key] = [existing, value];
1681
- }
1682
- }
1683
- return output;
1684
- }
1685
- __name(formDataToObject, "formDataToObject");
1686
- function isSafeFormKey(key) {
1687
- return !key.startsWith("$ACTION_") && !UNSAFE_FORM_KEYS.has(key);
1688
- }
1689
- __name(isSafeFormKey, "isSafeFormKey");
1690
- function isFormData(value) {
1691
- if (!value || typeof value !== "object") return false;
1692
- if (typeof FormData !== "undefined" && value instanceof FormData) {
1693
- return true;
1694
- }
1695
- return Object.prototype.toString.call(value) === "[object FormData]" && typeof value.entries === "function";
1696
- }
1697
- __name(isFormData, "isFormData");
1698
-
1699
- // src/server-query-protocol.ts
1700
- var FARM_SERVER_QUERY_RESULT_VERSION = 1;
1701
- function createFarmServerQueryResult(data, metadata) {
1702
- return {
1703
- __farmServerQuery: {
1704
- version: FARM_SERVER_QUERY_RESULT_VERSION,
1705
- ...metadata
1706
- },
1707
- data
1708
- };
1709
- }
1710
- __name(createFarmServerQueryResult, "createFarmServerQueryResult");
1711
-
1712
- // src/server-query.ts
1713
- var FARM_SERVER_QUERY_SYMBOL = /* @__PURE__ */ Symbol.for("farm.server-query");
1714
- var requestInflight = /* @__PURE__ */ new WeakMap();
1715
- var detachedInflight = /* @__PURE__ */ new Map();
1716
- function createServerQuery(options) {
1717
- if (!options || typeof options.handler !== "function") {
1718
- throw new TypeError("createServerQuery requires a handler function");
1719
- }
1720
- if (typeof options.key !== "function") {
1721
- throw new TypeError("createServerQuery requires a key function");
1722
- }
1723
- const staleTime = normalizeServerQueryStaleTime(options.staleTime);
1724
- const execute = createServerFn({
1725
- input: options.input,
1726
- middleware: options.middleware,
1727
- handler: /* @__PURE__ */ __name(async (context2) => {
1728
- const routeKey = await options.key(context2);
1729
- assertServerQueryKey(routeKey);
1730
- const clientKey = createRouteDataCacheKey(routeKey);
1731
- const cacheKey = createFarmCacheKey(["route-data", routeKey]);
1732
- const producer = /* @__PURE__ */ __name(async () => {
1733
- const value = await options.handler(context2);
1734
- return _parseServerFnSchema(options.output, value, "output", "createServerQuery");
1735
- }, "producer");
1736
- let data;
1737
- let updatedAt;
1738
- if (staleTime === 0) {
1739
- data = await dedupeServerQueryRequest(cacheKey, context2.request, producer);
1740
- updatedAt = Date.now();
1741
- } else {
1742
- const cache = getFarmDataCache();
1743
- data = await cache.getOrSet(cacheKey, producer, {
1744
- tags: [createRouteDataCacheTag(routeKey)],
1745
- revalidate: staleTime === false ? false : staleTime / 1e3
1746
- });
1747
- updatedAt = (await cache.getEntryAsync(cacheKey, { allowStale: true }))?.createdAt ?? Date.now();
1748
- }
1749
- return createFarmServerQueryResult(data, {
1750
- key: clientKey,
1751
- staleTime,
1752
- updatedAt,
1753
- ...options.persist === true ? { persist: true } : {}
1754
- });
1755
- }, "handler")
1756
- });
1757
- const query = /* @__PURE__ */ __name(async (input) => {
1758
- const result = await execute(input);
1759
- return getServerActionExecutionContext() ? result : result.data;
1760
- }, "query");
1761
- Object.defineProperties(query, {
1762
- [FARM_SERVER_QUERY_SYMBOL]: {
1763
- value: true,
1764
- enumerable: false
1765
- },
1766
- __farmServerQuery: {
1767
- value: true,
1768
- enumerable: false
1769
- },
1770
- __farmServerQueryInput: {
1771
- value: options.input,
1772
- enumerable: false
1773
- },
1774
- __farmServerQueryOutput: {
1775
- value: options.output,
1776
- enumerable: false
1777
- }
1778
- });
1779
- _attachServerFunctionDescriptor(
1780
- query,
1781
- createServerFunctionDescriptor("query", options, async (value) => {
1782
- const result = await _runServerFunctionForCaller(
1783
- execute,
1784
- value
1785
- );
1786
- return result.data;
1787
- })
1788
- );
1789
- return query;
1790
- }
1791
- __name(createServerQuery, "createServerQuery");
1792
- async function dedupeServerQueryRequest(key, request, producer) {
1793
- let inflight;
1794
- if (request) {
1795
- inflight = requestInflight.get(request) ?? /* @__PURE__ */ new Map();
1796
- requestInflight.set(request, inflight);
1797
- } else {
1798
- inflight = detachedInflight;
1799
- }
1800
- const existing = inflight.get(key);
1801
- if (existing) return existing;
1802
- const promise = Promise.resolve().then(producer);
1803
- inflight.set(key, promise);
1804
- try {
1805
- return await promise;
1806
- } finally {
1807
- inflight.delete(key);
1808
- }
1809
- }
1810
- __name(dedupeServerQueryRequest, "dedupeServerQueryRequest");
1811
- function normalizeServerQueryStaleTime(value) {
1812
- if (value === false) return false;
1813
- if (value === void 0) return 0;
1814
- if (typeof value === "number") {
1815
- if (!Number.isFinite(value) || value < 0) {
1816
- throw new TypeError("createServerQuery staleTime must be a non-negative duration");
1817
- }
1818
- return value;
1819
- }
1820
- const match = value.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)$/);
1821
- if (!match) {
1822
- throw new TypeError('createServerQuery staleTime must look like "250ms", "30s", "5m", or "1h"');
1823
- }
1824
- const amount = Number(match[1]);
1825
- const unit = match[2];
1826
- const multiplier = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : 36e5;
1827
- return amount * multiplier;
1828
- }
1829
- __name(normalizeServerQueryStaleTime, "normalizeServerQueryStaleTime");
1830
- function assertServerQueryKey(key) {
1831
- if (typeof key === "string") {
1832
- if (key.trim().length > 0) return;
1833
- } else if (Array.isArray(key)) {
1834
- return;
1835
- }
1836
- throw new TypeError("createServerQuery key must return a non-empty string or an array");
1837
- }
1838
- __name(assertServerQueryKey, "assertServerQueryKey");
1839
- // Annotate the CommonJS export names for ESM import in node:
1840
- 0 && (module.exports = {
1841
- FARM_SERVER_QUERY_SYMBOL,
1842
- createServerQuery
1843
- });
21
+ exports.FARM_SERVER_QUERY_SYMBOL = _chunkZMN3H73Hcjs.FARM_SERVER_QUERY_SYMBOL; exports.createServerQuery = _chunkZMN3H73Hcjs.createServerQuery;