@farm.js/core 0.1.0-beta.3 → 0.1.0-beta.5

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 (193) hide show
  1. package/dist/agent-runtime.d.mts +2 -1
  2. package/dist/agent-runtime.d.ts +2 -1
  3. package/dist/api/route-manager.cjs +313 -10
  4. package/dist/api/route-manager.cjs.map +1 -1
  5. package/dist/api/route-manager.d.mts +3 -2
  6. package/dist/api/route-manager.d.ts +3 -2
  7. package/dist/api/route-manager.mjs +6 -5
  8. package/dist/api/runtime.cjs +313 -10
  9. package/dist/api/runtime.cjs.map +1 -1
  10. package/dist/api/runtime.d.mts +2 -1
  11. package/dist/api/runtime.d.ts +2 -1
  12. package/dist/api/runtime.mjs +4 -3
  13. package/dist/api.cjs +642 -57
  14. package/dist/api.cjs.map +1 -1
  15. package/dist/api.d.mts +3 -2
  16. package/dist/api.d.ts +3 -2
  17. package/dist/api.mjs +29 -9
  18. package/dist/{app-DOKxo-LH.d.ts → app-BjN-da13.d.ts} +38 -3
  19. package/dist/{app-BB3Iu3xh.d.mts → app-CakAr8Be.d.mts} +38 -3
  20. package/dist/app-markdown.d.mts +2 -1
  21. package/dist/app-markdown.d.ts +2 -1
  22. package/dist/cache.cjs +395 -12
  23. package/dist/cache.cjs.map +1 -1
  24. package/dist/cache.d.mts +100 -6
  25. package/dist/cache.d.ts +100 -6
  26. package/dist/cache.mjs +8 -2
  27. package/dist/{chunk-XUBZ7JI4.mjs → chunk-2CUKEMVR.mjs} +187 -16
  28. package/dist/chunk-2CUKEMVR.mjs.map +1 -0
  29. package/dist/{chunk-OHC6VCDI.mjs → chunk-2NHCNRF6.mjs} +521 -42
  30. package/dist/chunk-2NHCNRF6.mjs.map +1 -0
  31. package/dist/{chunk-6WXJ54TC.mjs → chunk-65A7QIKI.mjs} +5 -5
  32. package/dist/{chunk-6WXJ54TC.mjs.map → chunk-65A7QIKI.mjs.map} +1 -1
  33. package/dist/{chunk-5QH4IKY3.mjs → chunk-7N62DNSO.mjs} +2 -2
  34. package/dist/{chunk-XJSHJN4M.mjs → chunk-A2LUXHD2.mjs} +593 -49
  35. package/dist/chunk-A2LUXHD2.mjs.map +1 -0
  36. package/dist/chunk-ALCLXXTY.mjs +187 -0
  37. package/dist/chunk-ALCLXXTY.mjs.map +1 -0
  38. package/dist/{chunk-CSU4KJJF.mjs → chunk-C2ROET2V.mjs} +2 -2
  39. package/dist/{chunk-JNYVN7YP.mjs → chunk-EEABSBKK.mjs} +2 -2
  40. package/dist/{chunk-JNYVN7YP.mjs.map → chunk-EEABSBKK.mjs.map} +1 -1
  41. package/dist/{chunk-BIOIOWXZ.mjs → chunk-HNIQFZKB.mjs} +2 -2
  42. package/dist/{chunk-MH6FKW2I.mjs → chunk-J5YWQVI5.mjs} +4 -4
  43. package/dist/chunk-J5YWQVI5.mjs.map +1 -0
  44. package/dist/{chunk-G5I34UA6.mjs → chunk-JDEOUK5V.mjs} +4 -4
  45. package/dist/{chunk-T543TMFY.mjs → chunk-NM3CRAAL.mjs} +3 -2
  46. package/dist/chunk-NM3CRAAL.mjs.map +1 -0
  47. package/dist/{chunk-LWMGIEJA.mjs → chunk-PFE6GMNE.mjs} +47 -37
  48. package/dist/chunk-PFE6GMNE.mjs.map +1 -0
  49. package/dist/{chunk-6VS6CKAV.mjs → chunk-QM746KUO.mjs} +8 -1
  50. package/dist/chunk-QM746KUO.mjs.map +1 -0
  51. package/dist/{chunk-5FW6PQ3J.mjs → chunk-QTZZ2ISQ.mjs} +41 -16
  52. package/dist/chunk-QTZZ2ISQ.mjs.map +1 -0
  53. package/dist/{chunk-SHRJG6OG.mjs → chunk-RBRLLZL5.mjs} +18 -3
  54. package/dist/chunk-RBRLLZL5.mjs.map +1 -0
  55. package/dist/{chunk-NRRFGX45.mjs → chunk-TQAEEJB4.mjs} +3 -3
  56. package/dist/{chunk-45LKHSHJ.mjs → chunk-UB5UOSHB.mjs} +24 -12
  57. package/dist/chunk-UB5UOSHB.mjs.map +1 -0
  58. package/dist/chunk-V3XURYJO.mjs +756 -0
  59. package/dist/chunk-V3XURYJO.mjs.map +1 -0
  60. package/dist/{chunk-HZYXGV4K.mjs → chunk-VY2UYN5R.mjs} +24 -4
  61. package/dist/chunk-VY2UYN5R.mjs.map +1 -0
  62. package/dist/{chunk-C33RALN7.mjs → chunk-W2CRQFF6.mjs} +79 -15
  63. package/dist/chunk-W2CRQFF6.mjs.map +1 -0
  64. package/dist/{chunk-LG3YINQN.mjs → chunk-Z5CQMP54.mjs} +3 -3
  65. package/dist/{client-DiViK9yK.d.mts → client-BT1mFQas.d.mts} +23 -4
  66. package/dist/{client-DpEBJbts.d.ts → client-Nn0q4eO4.d.ts} +23 -4
  67. package/dist/{client-plugins-CTnsZz_A.d.ts → client-plugins-Cw4qUGsw.d.ts} +6 -0
  68. package/dist/{client-plugins-Cnr0D3kk.d.mts → client-plugins-DQQ1adXM.d.mts} +6 -0
  69. package/dist/client-plugins.d.mts +2 -1
  70. package/dist/client-plugins.d.ts +2 -1
  71. package/dist/client.cjs +665 -82
  72. package/dist/client.cjs.map +1 -1
  73. package/dist/client.d.mts +71 -5
  74. package/dist/client.d.ts +71 -5
  75. package/dist/client.mjs +10 -7
  76. package/dist/config.d.mts +2 -1
  77. package/dist/config.d.ts +2 -1
  78. package/dist/{devtools-HE4FTUDN.mjs → devtools-LVC3VB5P.mjs} +4 -4
  79. package/dist/docs.cjs +11 -1
  80. package/dist/docs.cjs.map +1 -1
  81. package/dist/docs.mjs +4 -4
  82. package/dist/index.cjs +2113 -198
  83. package/dist/index.cjs.map +1 -1
  84. package/dist/index.d.mts +16 -16
  85. package/dist/index.d.ts +16 -16
  86. package/dist/index.mjs +49 -21
  87. package/dist/index.mjs.map +1 -1
  88. package/dist/integrations.d.mts +2 -1
  89. package/dist/integrations.d.ts +2 -1
  90. package/dist/internal/build-runtime.cjs +1455 -90
  91. package/dist/internal/build-runtime.cjs.map +1 -1
  92. package/dist/internal/build-runtime.d.mts +4 -3
  93. package/dist/internal/build-runtime.d.ts +4 -3
  94. package/dist/internal/build-runtime.mjs +15 -14
  95. package/dist/internal/config-runtime.cjs +12 -1
  96. package/dist/internal/config-runtime.cjs.map +1 -1
  97. package/dist/internal/config-runtime.d.mts +3 -2
  98. package/dist/internal/config-runtime.d.ts +3 -2
  99. package/dist/internal/config-runtime.mjs +3 -3
  100. package/dist/internal/production-runtime.cjs +282 -6
  101. package/dist/internal/production-runtime.cjs.map +1 -1
  102. package/dist/internal/production-runtime.d.mts +4 -4
  103. package/dist/internal/production-runtime.d.ts +4 -4
  104. package/dist/internal/production-runtime.mjs +4 -2
  105. package/dist/{metadata-eoVmHoyv.d.ts → metadata-BAPg_Nmo.d.ts} +1 -1
  106. package/dist/{metadata-Dp8AdvsB.d.mts → metadata-_6i9oFG3.d.mts} +1 -1
  107. package/dist/middleware.d.mts +4 -3
  108. package/dist/middleware.d.ts +4 -3
  109. package/dist/navigation.cjs +40 -15
  110. package/dist/navigation.cjs.map +1 -1
  111. package/dist/navigation.mjs +2 -2
  112. package/dist/plugin.cjs +913 -53
  113. package/dist/plugin.cjs.map +1 -1
  114. package/dist/plugin.d.mts +2 -1
  115. package/dist/plugin.d.ts +2 -1
  116. package/dist/plugin.mjs +11 -10
  117. package/dist/{production-runtime-BqTnUTai.d.ts → production-runtime-BoJDc5mc.d.ts} +1 -1
  118. package/dist/{production-runtime-DtDdG9fc.d.mts → production-runtime-DPfgMV9Y.d.mts} +1 -1
  119. package/dist/routes.cjs +276 -6
  120. package/dist/routes.cjs.map +1 -1
  121. package/dist/routes.d.mts +1 -1
  122. package/dist/routes.d.ts +1 -1
  123. package/dist/routes.mjs +3 -3
  124. package/dist/{runtime-C1B7pSGT.d.mts → runtime-9nQjVM7X.d.mts} +8 -9
  125. package/dist/{runtime-CdPHt0bv.d.ts → runtime-DgeS2skB.d.ts} +8 -9
  126. package/dist/server-action-security.cjs +28 -10
  127. package/dist/server-action-security.cjs.map +1 -1
  128. package/dist/server-action-security.d.mts +2 -1
  129. package/dist/server-action-security.d.ts +2 -1
  130. package/dist/server-action-security.mjs +2 -2
  131. package/dist/server-fn-client.d.mts +1 -0
  132. package/dist/server-fn-client.d.ts +1 -0
  133. package/dist/server-fn.cjs +785 -3
  134. package/dist/server-fn.cjs.map +1 -1
  135. package/dist/server-fn.d.mts +10 -1
  136. package/dist/server-fn.d.ts +10 -1
  137. package/dist/server-fn.mjs +6 -3
  138. package/dist/server-plugins.d.mts +3 -2
  139. package/dist/server-plugins.d.ts +3 -2
  140. package/dist/server-query-client.cjs +279 -8
  141. package/dist/server-query-client.cjs.map +1 -1
  142. package/dist/server-query-client.mjs +4 -4
  143. package/dist/server-query.cjs +381 -10
  144. package/dist/server-query.cjs.map +1 -1
  145. package/dist/server-query.mjs +5 -5
  146. package/dist/server.cjs +1086 -76
  147. package/dist/server.cjs.map +1 -1
  148. package/dist/server.d.mts +8 -7
  149. package/dist/server.d.ts +8 -7
  150. package/dist/server.mjs +31 -16
  151. package/dist/server.mjs.map +1 -1
  152. package/dist/testing.cjs +341 -20
  153. package/dist/testing.cjs.map +1 -1
  154. package/dist/testing.d.mts +3 -2
  155. package/dist/testing.d.ts +3 -2
  156. package/dist/testing.mjs +7 -6
  157. package/dist/testing.mjs.map +1 -1
  158. package/dist/transport-BmbGTXA5.d.mts +49 -0
  159. package/dist/transport-BmbGTXA5.d.ts +49 -0
  160. package/dist/{utils-8USa5BiY.d.mts → utils-CHXlMDkg.d.mts} +1 -1
  161. package/dist/{utils-DKJb6K6G.d.ts → utils-Drsyz1Vj.d.ts} +1 -1
  162. package/dist/version.cjs +1 -1
  163. package/dist/version.cjs.map +1 -1
  164. package/dist/version.mjs +1 -1
  165. package/dist/vite.cjs +914 -54
  166. package/dist/vite.cjs.map +1 -1
  167. package/dist/vite.d.mts +2 -1
  168. package/dist/vite.d.ts +2 -1
  169. package/dist/vite.mjs +11 -10
  170. package/package.json +1 -1
  171. package/types/api.d.ts +44 -0
  172. package/types/client.d.ts +85 -4
  173. package/dist/chunk-45LKHSHJ.mjs.map +0 -1
  174. package/dist/chunk-5FW6PQ3J.mjs.map +0 -1
  175. package/dist/chunk-6VS6CKAV.mjs.map +0 -1
  176. package/dist/chunk-C33RALN7.mjs.map +0 -1
  177. package/dist/chunk-GZWT6VI5.mjs +0 -382
  178. package/dist/chunk-GZWT6VI5.mjs.map +0 -1
  179. package/dist/chunk-HZYXGV4K.mjs.map +0 -1
  180. package/dist/chunk-LWMGIEJA.mjs.map +0 -1
  181. package/dist/chunk-MH6FKW2I.mjs.map +0 -1
  182. package/dist/chunk-OHC6VCDI.mjs.map +0 -1
  183. package/dist/chunk-SHRJG6OG.mjs.map +0 -1
  184. package/dist/chunk-T543TMFY.mjs.map +0 -1
  185. package/dist/chunk-XJSHJN4M.mjs.map +0 -1
  186. package/dist/chunk-XUBZ7JI4.mjs.map +0 -1
  187. /package/dist/{chunk-5QH4IKY3.mjs.map → chunk-7N62DNSO.mjs.map} +0 -0
  188. /package/dist/{chunk-CSU4KJJF.mjs.map → chunk-C2ROET2V.mjs.map} +0 -0
  189. /package/dist/{chunk-BIOIOWXZ.mjs.map → chunk-HNIQFZKB.mjs.map} +0 -0
  190. /package/dist/{chunk-G5I34UA6.mjs.map → chunk-JDEOUK5V.mjs.map} +0 -0
  191. /package/dist/{chunk-NRRFGX45.mjs.map → chunk-TQAEEJB4.mjs.map} +0 -0
  192. /package/dist/{chunk-LG3YINQN.mjs.map → chunk-Z5CQMP54.mjs.map} +0 -0
  193. /package/dist/{devtools-HE4FTUDN.mjs.map → devtools-LVC3VB5P.mjs.map} +0 -0
@@ -36,16 +36,36 @@ var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvali
36
36
  var globalState = globalThis;
37
37
  function getFarmCacheInvalidationState() {
38
38
  return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
39
- listeners: /* @__PURE__ */ new Set()
39
+ listeners: /* @__PURE__ */ new Set(),
40
+ taskListeners: /* @__PURE__ */ new Set()
40
41
  });
41
42
  }
42
43
  __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
44
+ function notifyFarmCacheInvalidation(key) {
45
+ if (typeof key !== "string" || key.length === 0) return;
46
+ for (const listener of getFarmCacheInvalidationState().listeners) {
47
+ listener(key);
48
+ }
49
+ }
50
+ __name(notifyFarmCacheInvalidation, "notifyFarmCacheInvalidation");
51
+ function notifyFarmCacheTask(task) {
52
+ for (const listener of getFarmCacheInvalidationState().taskListeners) {
53
+ listener(task);
54
+ }
55
+ }
56
+ __name(notifyFarmCacheTask, "notifyFarmCacheTask");
43
57
  function subscribeFarmCacheInvalidation(listener) {
44
58
  const state = getFarmCacheInvalidationState();
45
59
  state.listeners.add(listener);
46
60
  return () => state.listeners.delete(listener);
47
61
  }
48
62
  __name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
63
+ function subscribeFarmCacheTask(listener) {
64
+ const state = getFarmCacheInvalidationState();
65
+ state.taskListeners.add(listener);
66
+ return () => state.taskListeners.delete(listener);
67
+ }
68
+ __name(subscribeFarmCacheTask, "subscribeFarmCacheTask");
49
69
 
50
70
  // src/server-action-security.ts
51
71
  var SERVER_ACTION_STORAGE_KEY = /* @__PURE__ */ Symbol.for("farm.serverActionStorage");
@@ -61,6 +81,9 @@ __name(getServerActionSignal, "getServerActionSignal");
61
81
  subscribeFarmCacheInvalidation((key) => {
62
82
  getServerActionExecutionContext()?.invalidations.add(key);
63
83
  });
84
+ subscribeFarmCacheTask((task) => {
85
+ getServerActionExecutionContext()?.cacheTasks.add(task);
86
+ });
64
87
  function getServerActionStorage() {
65
88
  const globalState2 = globalThis;
66
89
  if (!globalState2[SERVER_ACTION_STORAGE_KEY]) {
@@ -89,6 +112,748 @@ function _resolveCurrentRequest() {
89
112
  }
90
113
  __name(_resolveCurrentRequest, "_resolveCurrentRequest");
91
114
 
115
+ // src/observability.ts
116
+ var runtimeHandlers = /* @__PURE__ */ new Set();
117
+ var observabilityState = {
118
+ logs: false,
119
+ handlers: []
120
+ };
121
+ function emitFarmEvent(input) {
122
+ const event = {
123
+ timestamp: Date.now(),
124
+ level: inferFarmEventLevel(input.type),
125
+ ...input
126
+ };
127
+ if (!shouldEmitFarmEvent(event)) {
128
+ return event;
129
+ }
130
+ if (observabilityState.logs) {
131
+ logFarmEvent(event);
132
+ }
133
+ for (const handler of [...observabilityState.handlers, ...runtimeHandlers]) {
134
+ try {
135
+ Promise.resolve(handler(event)).catch((error) => {
136
+ console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
137
+ });
138
+ } catch (error) {
139
+ console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
140
+ }
141
+ }
142
+ return event;
143
+ }
144
+ __name(emitFarmEvent, "emitFarmEvent");
145
+ function shouldEmitFarmEvent(event) {
146
+ if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
147
+ return false;
148
+ }
149
+ if (observabilityState.events && !observabilityState.events.has(event.type)) {
150
+ return false;
151
+ }
152
+ return true;
153
+ }
154
+ __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
155
+ function inferFarmEventLevel(type) {
156
+ if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
157
+ return "error";
158
+ }
159
+ if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
160
+ return "warn";
161
+ }
162
+ if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
163
+ return "debug";
164
+ }
165
+ return "info";
166
+ }
167
+ __name(inferFarmEventLevel, "inferFarmEventLevel");
168
+ function logFarmEvent(event) {
169
+ const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
170
+ switch (event.level) {
171
+ case "error":
172
+ console.error(message);
173
+ break;
174
+ case "warn":
175
+ console.warn(message);
176
+ break;
177
+ default:
178
+ console.log(message);
179
+ break;
180
+ }
181
+ }
182
+ __name(logFarmEvent, "logFarmEvent");
183
+ function formatFarmEventDetails(event) {
184
+ const details = [];
185
+ const record = event;
186
+ for (const key of [
187
+ "route",
188
+ "pathname",
189
+ "method",
190
+ "status",
191
+ "key",
192
+ "tag",
193
+ "path",
194
+ "reason",
195
+ "durationMs",
196
+ "integration",
197
+ "operation",
198
+ "plugin",
199
+ "hook",
200
+ "target",
201
+ "count"
202
+ ]) {
203
+ const value = record[key];
204
+ if (value !== void 0) {
205
+ details.push(`${key}=${formatDetailValue(value)}`);
206
+ }
207
+ }
208
+ return details.length > 0 ? ` ${details.join(" ")}` : "";
209
+ }
210
+ __name(formatFarmEventDetails, "formatFarmEventDetails");
211
+ function formatDetailValue(value) {
212
+ if (typeof value === "string") {
213
+ return value;
214
+ }
215
+ if (typeof value === "number" || typeof value === "boolean") {
216
+ return String(value);
217
+ }
218
+ try {
219
+ return JSON.stringify(value);
220
+ } catch {
221
+ return String(value);
222
+ }
223
+ }
224
+ __name(formatDetailValue, "formatDetailValue");
225
+ function formatError(error) {
226
+ return error instanceof Error ? error.message : String(error);
227
+ }
228
+ __name(formatError, "formatError");
229
+
230
+ // src/cache.ts
231
+ var _FarmDataCache = class _FarmDataCache {
232
+ constructor(config = {}) {
233
+ this.entries = /* @__PURE__ */ new Map();
234
+ this.inflight = /* @__PURE__ */ new Map();
235
+ this.invalidatedTagVersions = /* @__PURE__ */ new Map();
236
+ this.version = 0;
237
+ this.namespace = "farm";
238
+ this.local = true;
239
+ this.lease = {
240
+ enabled: true,
241
+ ttlMs: 1e4,
242
+ waitTimeoutMs: 1e4,
243
+ pollIntervalMs: 25
244
+ };
245
+ this.configure(config);
246
+ }
247
+ configure(config = {}) {
248
+ this.adapter = config.adapter;
249
+ this.namespace = normalizeCacheNamespace(config.namespace || "farm");
250
+ this.local = !config.adapter;
251
+ this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
252
+ enabled: true,
253
+ ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
254
+ waitTimeoutMs: normalizePositiveDuration(
255
+ config.lease?.waitTimeoutMs,
256
+ 1e4,
257
+ "cache.lease.waitTimeoutMs"
258
+ ),
259
+ pollIntervalMs: normalizePositiveDuration(
260
+ config.lease?.pollIntervalMs,
261
+ 25,
262
+ "cache.lease.pollIntervalMs"
263
+ )
264
+ };
265
+ if (!this.local) {
266
+ this.entries.clear();
267
+ this.inflight.clear();
268
+ this.invalidatedTagVersions.clear();
269
+ this.version = 0;
270
+ }
271
+ }
272
+ get adapterName() {
273
+ return this.adapter?.name || (this.adapter ? "custom" : "memory");
274
+ }
275
+ get hasAdapter() {
276
+ return this.adapter !== void 0;
277
+ }
278
+ get size() {
279
+ return this.entries.size;
280
+ }
281
+ get(key, options = {}) {
282
+ return this.getEntry(key, options)?.value;
283
+ }
284
+ getEntry(key, options = {}) {
285
+ const entry = this.entries.get(key);
286
+ if (!entry) {
287
+ emitFarmEvent({ type: "cache.miss", key });
288
+ return void 0;
289
+ }
290
+ const stale = this.isStale(entry, options.now);
291
+ if (stale) {
292
+ emitFarmEvent({
293
+ type: "cache.stale",
294
+ key,
295
+ tags: Array.from(entry.tags),
296
+ revalidate: entry.revalidate
297
+ });
298
+ }
299
+ if (!options.allowStale && stale) {
300
+ emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
301
+ return void 0;
302
+ }
303
+ emitFarmEvent({
304
+ type: "cache.hit",
305
+ key,
306
+ tags: Array.from(entry.tags),
307
+ revalidate: entry.revalidate,
308
+ stale
309
+ });
310
+ return this.toPublicEntry(entry);
311
+ }
312
+ async getEntryAsync(key, options = {}) {
313
+ if (this.local) {
314
+ const localEntry = this.getEntry(key, options);
315
+ if (localEntry) return localEntry;
316
+ }
317
+ if (!this.adapter) {
318
+ return this.local ? void 0 : this.getEntry(key, options);
319
+ }
320
+ const entry = await this.adapter.get(this.createAdapterKey(key));
321
+ if (!entry) {
322
+ emitFarmEvent({ type: "cache.miss", key });
323
+ return void 0;
324
+ }
325
+ assertFarmCacheEntry(entry, key);
326
+ const stale = await this.isAdapterEntryStale(entry, options.now);
327
+ if (stale) {
328
+ emitFarmEvent({
329
+ type: "cache.stale",
330
+ key,
331
+ tags: [...entry.tags],
332
+ revalidate: entry.revalidate
333
+ });
334
+ if (!options.allowStale) {
335
+ emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
336
+ return void 0;
337
+ }
338
+ }
339
+ emitFarmEvent({
340
+ type: "cache.hit",
341
+ key,
342
+ tags: [...entry.tags],
343
+ revalidate: entry.revalidate,
344
+ stale
345
+ });
346
+ if (this.local && !stale) {
347
+ this.hydrateLocalEntry(entry);
348
+ }
349
+ return { ...entry, key };
350
+ }
351
+ set(key, value, options = {}) {
352
+ const tags = /* @__PURE__ */ new Set();
353
+ for (const tag of options.tags ?? []) {
354
+ tags.add(normalizeCacheTag(tag));
355
+ }
356
+ for (const routePath of options.paths ?? []) {
357
+ tags.add(createPathCacheTag(routePath));
358
+ }
359
+ const entry = {
360
+ key,
361
+ value,
362
+ tags,
363
+ tagVersions: void 0,
364
+ createdAt: options.createdAt ?? Date.now(),
365
+ createdVersion: ++this.version,
366
+ revalidate: normalizeRevalidate(options.revalidate)
367
+ };
368
+ this.entries.set(key, entry);
369
+ emitFarmEvent({
370
+ type: "cache.set",
371
+ key,
372
+ tags: Array.from(tags),
373
+ revalidate: entry.revalidate
374
+ });
375
+ return this.toPublicEntry(entry);
376
+ }
377
+ async setAsync(key, value, options = {}, tagVersions) {
378
+ const tags = normalizeCacheOptionsTags(options);
379
+ const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
380
+ const entry = {
381
+ key,
382
+ value,
383
+ tags: Array.from(tags),
384
+ tagVersions: capturedVersions,
385
+ createdAt: options.createdAt ?? Date.now(),
386
+ createdVersion: ++this.version,
387
+ revalidate: normalizeRevalidate(options.revalidate)
388
+ };
389
+ if (this.local) {
390
+ this.hydrateLocalEntry(entry);
391
+ }
392
+ if (this.adapter) {
393
+ await this.adapter.set(this.createAdapterKey(key), entry);
394
+ }
395
+ emitFarmEvent({
396
+ type: "cache.set",
397
+ key,
398
+ tags: [...entry.tags],
399
+ revalidate: entry.revalidate
400
+ });
401
+ return entry;
402
+ }
403
+ delete(key) {
404
+ const deleted = this.entries.delete(key);
405
+ emitFarmEvent({ type: "cache.delete", key, deleted });
406
+ return deleted;
407
+ }
408
+ async deleteAsync(key) {
409
+ const deleted = this.entries.delete(key);
410
+ if (this.adapter) {
411
+ await this.adapter.delete(this.createAdapterKey(key));
412
+ }
413
+ emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
414
+ return this.adapter ? true : deleted;
415
+ }
416
+ clear() {
417
+ const count = this.entries.size;
418
+ this.entries.clear();
419
+ this.inflight.clear();
420
+ this.invalidatedTagVersions.clear();
421
+ this.version = 0;
422
+ emitFarmEvent({ type: "cache.clear", count });
423
+ }
424
+ async clearAsync() {
425
+ this.clear();
426
+ await this.adapter?.clear?.();
427
+ }
428
+ isStale(entry, now = Date.now()) {
429
+ if (typeof entry.revalidate === "number" && entry.revalidate > 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
430
+ return true;
431
+ }
432
+ for (const tag of entry.tags) {
433
+ const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
434
+ if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
435
+ return true;
436
+ }
437
+ }
438
+ return false;
439
+ }
440
+ async isStaleAsync(entry, now = Date.now()) {
441
+ if (this.adapter) {
442
+ return this.isAdapterEntryStale(entry, now);
443
+ }
444
+ return this.isStale(entry, now);
445
+ }
446
+ revalidateTag(tag, options = {}) {
447
+ const normalized = normalizeCacheTag(tag);
448
+ const count = this.invalidateTag(normalized);
449
+ emitFarmEvent(
450
+ options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
451
+ );
452
+ return count;
453
+ }
454
+ async revalidateTagAsync(tag, options = {}) {
455
+ const normalized = normalizeCacheTag(tag);
456
+ const count = this.invalidateTag(normalized);
457
+ await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
458
+ emitFarmEvent(
459
+ options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
460
+ );
461
+ return count;
462
+ }
463
+ revalidatePath(routePath) {
464
+ const normalizedPath = normalizeRevalidatePath(routePath);
465
+ const pathTag = createPathCacheTag(normalizedPath);
466
+ const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
467
+ const count = this.invalidateTag(pathTag);
468
+ emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
469
+ if (pprCount > 0) {
470
+ emitFarmEvent({
471
+ type: "ppr.shell.invalidated",
472
+ route: normalizedPath,
473
+ reason: "revalidatePath",
474
+ count: pprCount
475
+ });
476
+ }
477
+ return count;
478
+ }
479
+ async revalidatePathAsync(routePath) {
480
+ const normalizedPath = normalizeRevalidatePath(routePath);
481
+ const pathTag = createPathCacheTag(normalizedPath);
482
+ const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
483
+ const count = this.invalidateTag(pathTag);
484
+ await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
485
+ emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
486
+ if (pprCount > 0) {
487
+ emitFarmEvent({
488
+ type: "ppr.shell.invalidated",
489
+ route: normalizedPath,
490
+ reason: "revalidatePath",
491
+ count: pprCount
492
+ });
493
+ }
494
+ return count;
495
+ }
496
+ async getOrSet(key, producer, options = {}) {
497
+ const cached = await this.getEntryAsync(key);
498
+ if (cached) {
499
+ return cached.value;
500
+ }
501
+ const inflight = this.inflight.get(key);
502
+ if (inflight) {
503
+ emitFarmEvent({ type: "cache.dedupe", key });
504
+ return inflight;
505
+ }
506
+ const tags = Array.from(normalizeCacheOptionsTags(options));
507
+ const promise = this.fillCacheEntry(key, producer, options, tags).catch((error) => {
508
+ emitFarmEvent({ type: "cache.error", key, operation: "set", error });
509
+ throw error;
510
+ }).finally(() => {
511
+ this.inflight.delete(key);
512
+ });
513
+ this.inflight.set(key, promise);
514
+ return promise;
515
+ }
516
+ async fillCacheEntry(key, producer, options, tags) {
517
+ const leaseKey = `${this.namespace}:lease:${key}`;
518
+ let leaseToken;
519
+ if (this.adapter?.acquireLease && this.adapter.releaseLease && this.lease.enabled) {
520
+ leaseToken = await this.adapter.acquireLease(leaseKey, this.lease.ttlMs);
521
+ if (!leaseToken) {
522
+ const shared = await this.waitForAdapterEntry(key);
523
+ if (shared) {
524
+ emitFarmEvent({ type: "cache.dedupe", key });
525
+ return shared.value;
526
+ }
527
+ leaseToken = await this.adapter.acquireLease(leaseKey, this.lease.ttlMs);
528
+ }
529
+ }
530
+ try {
531
+ const initialTagVersions = await this.getAdapterTagVersions(tags);
532
+ const value = await producer();
533
+ await this.setAsync(key, value, options, initialTagVersions);
534
+ return value;
535
+ } finally {
536
+ if (leaseToken && this.adapter?.releaseLease) {
537
+ await this.adapter.releaseLease(leaseKey, leaseToken);
538
+ }
539
+ }
540
+ }
541
+ async waitForAdapterEntry(key) {
542
+ const deadline = Date.now() + this.lease.waitTimeoutMs;
543
+ while (Date.now() < deadline) {
544
+ await delay(this.lease.pollIntervalMs);
545
+ const entry = await this.getEntryAsync(key);
546
+ if (entry) return entry;
547
+ }
548
+ return void 0;
549
+ }
550
+ countEntriesForTag(tag) {
551
+ let count = 0;
552
+ for (const entry of this.entries.values()) {
553
+ if (entry.tags.has(tag)) {
554
+ count++;
555
+ }
556
+ }
557
+ return count;
558
+ }
559
+ countEntriesForTags(tags) {
560
+ let count = 0;
561
+ for (const entry of this.entries.values()) {
562
+ if (tags.every((tag) => entry.tags.has(tag))) {
563
+ count++;
564
+ }
565
+ }
566
+ return count;
567
+ }
568
+ invalidateTag(normalizedTag) {
569
+ this.invalidatedTagVersions.set(normalizedTag, ++this.version);
570
+ return this.countEntriesForTag(normalizedTag);
571
+ }
572
+ toPublicEntry(entry) {
573
+ return {
574
+ key: entry.key,
575
+ value: entry.value,
576
+ tags: Array.from(entry.tags),
577
+ tagVersions: entry.tagVersions,
578
+ createdAt: entry.createdAt,
579
+ createdVersion: entry.createdVersion,
580
+ revalidate: entry.revalidate
581
+ };
582
+ }
583
+ hydrateLocalEntry(entry) {
584
+ this.entries.set(entry.key, {
585
+ key: entry.key,
586
+ value: entry.value,
587
+ tags: new Set(entry.tags.map(normalizeCacheTag)),
588
+ tagVersions: entry.tagVersions,
589
+ createdAt: entry.createdAt,
590
+ createdVersion: entry.createdVersion ?? ++this.version,
591
+ revalidate: normalizeRevalidate(entry.revalidate)
592
+ });
593
+ }
594
+ createAdapterKey(key) {
595
+ return `${this.namespace}:entry:${key}`;
596
+ }
597
+ createAdapterTag(tag) {
598
+ return `${this.namespace}:tag:${tag}`;
599
+ }
600
+ async getAdapterTagVersions(tags) {
601
+ if (!this.adapter?.getTagVersions || tags.length === 0) return {};
602
+ const normalized = tags.map(normalizeCacheTag);
603
+ const physicalTags = normalized.map((tag) => this.createAdapterTag(tag));
604
+ const versions = await this.adapter.getTagVersions(physicalTags);
605
+ return Object.fromEntries(
606
+ normalized.map((tag, index) => [
607
+ tag,
608
+ normalizeAdapterVersion(versions[physicalTags[index]])
609
+ ])
610
+ );
611
+ }
612
+ async isAdapterEntryStale(entry, now = Date.now()) {
613
+ if (typeof entry.revalidate === "number" && entry.revalidate > 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
614
+ return true;
615
+ }
616
+ const currentVersions = await this.getAdapterTagVersions(entry.tags);
617
+ for (const tag of entry.tags) {
618
+ if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
619
+ return true;
620
+ }
621
+ }
622
+ return false;
623
+ }
624
+ };
625
+ __name(_FarmDataCache, "FarmDataCache");
626
+ var FarmDataCache = _FarmDataCache;
627
+ var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
628
+ var farmDataCacheGlobal = globalThis;
629
+ var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
630
+ var functionIds = /* @__PURE__ */ new WeakMap();
631
+ var nextFunctionId = 0;
632
+ function getFarmDataCache() {
633
+ return sharedFarmDataCache;
634
+ }
635
+ __name(getFarmDataCache, "getFarmDataCache");
636
+ function updateTag(tag) {
637
+ const cache = getFarmDataCache();
638
+ if (cache.hasAdapter) {
639
+ const task = cache.revalidateTagAsync(tag, { source: "updateTag" }).then(() => void 0);
640
+ notifyFarmCacheTask(task);
641
+ return task;
642
+ }
643
+ cache.revalidateTag(tag, { source: "updateTag" });
644
+ }
645
+ __name(updateTag, "updateTag");
646
+ function revalidatePath(routePath) {
647
+ const cache = getFarmDataCache();
648
+ if (cache.hasAdapter) {
649
+ const task = cache.revalidatePathAsync(routePath).then(() => void 0);
650
+ notifyFarmCacheTask(task);
651
+ return task;
652
+ }
653
+ cache.revalidatePath(routePath);
654
+ }
655
+ __name(revalidatePath, "revalidatePath");
656
+ function invalidate(key) {
657
+ const clientKey = createRouteDataCacheKey(key);
658
+ const task = updateTag(createRouteDataCacheTag(key));
659
+ notifyFarmCacheInvalidation(clientKey);
660
+ return task;
661
+ }
662
+ __name(invalidate, "invalidate");
663
+ async function applyFarmCacheInvalidationTargets(targets) {
664
+ if (!Array.isArray(targets)) {
665
+ throw new TypeError("Cache invalidations must resolve to an array of targets.");
666
+ }
667
+ const clientKeys = [];
668
+ for (const target of targets) {
669
+ assertFarmCacheInvalidationTarget(target);
670
+ if ("key" in target) {
671
+ await invalidate(target.key);
672
+ clientKeys.push(createRouteDataCacheKey(target.key));
673
+ } else if ("path" in target) {
674
+ await revalidatePath(target.path);
675
+ } else {
676
+ await updateTag(target.tag);
677
+ }
678
+ }
679
+ return Array.from(new Set(clientKeys));
680
+ }
681
+ __name(applyFarmCacheInvalidationTargets, "applyFarmCacheInvalidationTargets");
682
+ function createPathCacheTag(routePath) {
683
+ return `path:${normalizeRevalidatePath(routePath)}`;
684
+ }
685
+ __name(createPathCacheTag, "createPathCacheTag");
686
+ function createRouteDataCacheTag(key) {
687
+ return `route-data:${createRouteDataCacheKey(key)}`;
688
+ }
689
+ __name(createRouteDataCacheTag, "createRouteDataCacheTag");
690
+ function createRouteDataCacheKey(key) {
691
+ return createFarmCacheKey(Array.isArray(key) ? key : [key]);
692
+ }
693
+ __name(createRouteDataCacheKey, "createRouteDataCacheKey");
694
+ function normalizeRevalidatePath(routePath) {
695
+ if (typeof routePath !== "string") {
696
+ throw new TypeError("revalidatePath expects a path string.");
697
+ }
698
+ let normalized = routePath.trim();
699
+ if (!normalized) {
700
+ throw new Error("revalidatePath expects a non-empty path.");
701
+ }
702
+ try {
703
+ if (/^https?:\/\//.test(normalized)) {
704
+ normalized = new URL(normalized).pathname;
705
+ }
706
+ } catch {
707
+ }
708
+ normalized = normalized.split("?")[0] ?? normalized;
709
+ normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
710
+ normalized = normalized.replace(/\/{2,}/g, "/");
711
+ if (normalized.length > 1) {
712
+ normalized = normalized.replace(/\/+$/, "");
713
+ }
714
+ return normalized || "/";
715
+ }
716
+ __name(normalizeRevalidatePath, "normalizeRevalidatePath");
717
+ function createFarmCacheKey(parts) {
718
+ return stableSerialize(parts);
719
+ }
720
+ __name(createFarmCacheKey, "createFarmCacheKey");
721
+ function normalizeRevalidate(revalidate) {
722
+ if (revalidate === false || revalidate === void 0) {
723
+ return revalidate;
724
+ }
725
+ if (!Number.isFinite(revalidate) || revalidate <= 0) {
726
+ return void 0;
727
+ }
728
+ return revalidate;
729
+ }
730
+ __name(normalizeRevalidate, "normalizeRevalidate");
731
+ function normalizeCacheTag(tag) {
732
+ if (typeof tag !== "string") {
733
+ throw new TypeError("Cache tags must be strings.");
734
+ }
735
+ const normalized = tag.trim();
736
+ if (!normalized) {
737
+ throw new Error("Cache tags cannot be empty.");
738
+ }
739
+ return normalized;
740
+ }
741
+ __name(normalizeCacheTag, "normalizeCacheTag");
742
+ function normalizeCacheNamespace(namespace) {
743
+ if (typeof namespace !== "string") {
744
+ throw new TypeError("Cache namespace must be a string.");
745
+ }
746
+ const normalized = namespace.trim().replace(/:+$/g, "");
747
+ if (!normalized) {
748
+ throw new Error("Cache namespace cannot be empty.");
749
+ }
750
+ return normalized;
751
+ }
752
+ __name(normalizeCacheNamespace, "normalizeCacheNamespace");
753
+ function normalizeAdapterVersion(value) {
754
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
755
+ }
756
+ __name(normalizeAdapterVersion, "normalizeAdapterVersion");
757
+ function normalizePositiveDuration(value, fallback, name) {
758
+ if (value === void 0) return fallback;
759
+ if (!Number.isFinite(value) || value <= 0) {
760
+ throw new TypeError(`${name} must be a positive number of milliseconds.`);
761
+ }
762
+ return Math.floor(value);
763
+ }
764
+ __name(normalizePositiveDuration, "normalizePositiveDuration");
765
+ function delay(ms) {
766
+ return new Promise((resolve) => setTimeout(resolve, ms));
767
+ }
768
+ __name(delay, "delay");
769
+ function normalizeCacheOptionsTags(options) {
770
+ const tags = /* @__PURE__ */ new Set();
771
+ for (const tag of options.tags ?? []) {
772
+ tags.add(normalizeCacheTag(tag));
773
+ }
774
+ for (const routePath of options.paths ?? []) {
775
+ tags.add(createPathCacheTag(routePath));
776
+ }
777
+ return tags;
778
+ }
779
+ __name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
780
+ function assertFarmCacheEntry(entry, expectedKey) {
781
+ if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
782
+ throw new TypeError(
783
+ `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
784
+ );
785
+ }
786
+ }
787
+ __name(assertFarmCacheEntry, "assertFarmCacheEntry");
788
+ function assertFarmCacheInvalidationTarget(target) {
789
+ if (!target || typeof target !== "object") {
790
+ throw new TypeError("Cache invalidation targets must be { key }, { path }, or { tag }.");
791
+ }
792
+ if ("key" in target) {
793
+ const key = target.key;
794
+ if (typeof key === "string" || Array.isArray(key)) return;
795
+ } else if ("path" in target && typeof target.path === "string") {
796
+ return;
797
+ } else if ("tag" in target && typeof target.tag === "string") {
798
+ return;
799
+ }
800
+ throw new TypeError("Cache invalidation targets must contain a string/array key, path, or tag.");
801
+ }
802
+ __name(assertFarmCacheInvalidationTarget, "assertFarmCacheInvalidationTarget");
803
+ function getFunctionCacheIdentity(fn) {
804
+ if (fn.name) {
805
+ return `name:${fn.name}`;
806
+ }
807
+ let id = functionIds.get(fn);
808
+ if (!id) {
809
+ id = ++nextFunctionId;
810
+ functionIds.set(fn, id);
811
+ }
812
+ return `anonymous:${id}`;
813
+ }
814
+ __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
815
+ function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
816
+ if (value === null) return "null";
817
+ if (value === void 0) return "undefined";
818
+ const valueType = typeof value;
819
+ if (valueType === "string") return JSON.stringify(value);
820
+ if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
821
+ return `${valueType}:${String(value)}`;
822
+ }
823
+ if (valueType === "symbol") {
824
+ return `symbol:${String(value)}`;
825
+ }
826
+ if (valueType === "function") {
827
+ return `function:${getFunctionCacheIdentity(value)}`;
828
+ }
829
+ if (value instanceof Date) {
830
+ return `date:${value.toISOString()}`;
831
+ }
832
+ if (value instanceof URL) {
833
+ return `url:${value.toString()}`;
834
+ }
835
+ if (value instanceof RegExp) {
836
+ return `regexp:${value.toString()}`;
837
+ }
838
+ if (Array.isArray(value)) {
839
+ return `[${value.map((item) => stableSerialize(item, seen)).join(",")}]`;
840
+ }
841
+ if (value && typeof value === "object") {
842
+ if (seen.has(value)) {
843
+ return "[Circular]";
844
+ }
845
+ seen.add(value);
846
+ const entries = Object.entries(value).sort(
847
+ ([a], [b]) => a.localeCompare(b)
848
+ );
849
+ const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
850
+ seen.delete(value);
851
+ return `{${serialized}}`;
852
+ }
853
+ return String(value);
854
+ }
855
+ __name(stableSerialize, "stableSerialize");
856
+
92
857
  // src/server-fn.ts
93
858
  var FARM_SERVER_FN_SYMBOL = /* @__PURE__ */ Symbol.for("farm.server-fn");
94
859
  var UNSAFE_FORM_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
@@ -126,8 +891,21 @@ function createServerFn(options) {
126
891
  request,
127
892
  signal
128
893
  };
129
- const result = await runServerFnMiddleware(middleware, handlerContext, options.handler);
130
- return _parseServerFnSchema(options.output, result, "output");
894
+ let resolvedContext = Object.freeze(/* @__PURE__ */ Object.create(null));
895
+ const result = await runServerFnMiddleware(middleware, handlerContext, async (context) => {
896
+ resolvedContext = context.context;
897
+ return options.handler(context);
898
+ });
899
+ const parsedResult = await _parseServerFnSchema(options.output, result, "output");
900
+ if (options.invalidates) {
901
+ const declaration = typeof options.invalidates === "function" ? await options.invalidates({
902
+ ...handlerContext,
903
+ context: resolvedContext,
904
+ result: parsedResult
905
+ }) : options.invalidates;
906
+ await applyFarmCacheInvalidationTargets(declaration);
907
+ }
908
+ return parsedResult;
131
909
  }, "serverFn");
132
910
  Object.defineProperties(serverFn, {
133
911
  [FARM_SERVER_FN_SYMBOL]: {
@@ -149,6 +927,10 @@ function createServerFn(options) {
149
927
  __farmServerFnMiddleware: {
150
928
  value: middleware,
151
929
  enumerable: false
930
+ },
931
+ __farmServerFnInvalidates: {
932
+ value: options.invalidates,
933
+ enumerable: false
152
934
  }
153
935
  });
154
936
  return serverFn;