@farm.js/core 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/dist/after.cjs +12 -225
  2. package/dist/agent-runtime.cjs +83 -2800
  3. package/dist/api/client.cjs +17 -4060
  4. package/dist/api/route-manager.cjs +34 -4354
  5. package/dist/api/runtime.cjs +29 -2696
  6. package/dist/api.cjs +88 -8434
  7. package/dist/app-markdown.cjs +39 -280
  8. package/dist/cache.cjs +38 -1560
  9. package/dist/chunk-22GUSVNJ.cjs +351 -0
  10. package/dist/chunk-2CQ74SP6.cjs +13 -0
  11. package/dist/chunk-2SJ4RQ6P.cjs +57 -0
  12. package/dist/chunk-3376ZTRC.cjs +1 -0
  13. package/dist/{chunk-YD4J4XCI.mjs → chunk-3XG26Z3J.mjs} +1 -1
  14. package/dist/chunk-4PNUXIVU.cjs +472 -0
  15. package/dist/chunk-4PPEPOZZ.cjs +21 -0
  16. package/dist/chunk-4ZFL5GFN.cjs +520 -0
  17. package/dist/chunk-5OVTOKGH.cjs +65 -0
  18. package/dist/chunk-5QIKR7RR.cjs +224 -0
  19. package/dist/chunk-5ZSWG4UX.cjs +127 -0
  20. package/dist/chunk-62YJ2IEB.cjs +238 -0
  21. package/dist/chunk-6EODJYCX.cjs +183 -0
  22. package/dist/chunk-6EXBPJ24.cjs +434 -0
  23. package/dist/chunk-6QQDAAAZ.cjs +38 -0
  24. package/dist/chunk-6V4TDWEC.cjs +455 -0
  25. package/dist/chunk-72ADZ6GQ.cjs +19 -0
  26. package/dist/chunk-75BRBIFP.cjs +172 -0
  27. package/dist/chunk-7W3CPVXS.cjs +24 -0
  28. package/dist/chunk-A6WIQH5Z.cjs +31 -0
  29. package/dist/chunk-AFOD3LYZ.cjs +377 -0
  30. package/dist/chunk-AMDMVWMI.cjs +39 -0
  31. package/dist/chunk-AORPIPNB.cjs +552 -0
  32. package/dist/chunk-ARJWXNQL.cjs +256 -0
  33. package/dist/chunk-AWRISO2H.cjs +2199 -0
  34. package/dist/chunk-AYJR42WX.cjs +711 -0
  35. package/dist/chunk-B4CH33IG.cjs +644 -0
  36. package/dist/chunk-BIDYX3SL.cjs +91 -0
  37. package/dist/chunk-BSTRERPP.cjs +40 -0
  38. package/dist/chunk-BYODCJD6.cjs +663 -0
  39. package/dist/chunk-C3VRMB6H.cjs +85 -0
  40. package/dist/chunk-C5GUTBZK.cjs +173 -0
  41. package/dist/chunk-CIAGU2X4.cjs +337 -0
  42. package/dist/chunk-CMGMGHUZ.cjs +27 -0
  43. package/dist/chunk-CXP5U3RW.cjs +54 -0
  44. package/dist/chunk-D2ULAULS.cjs +166 -0
  45. package/dist/chunk-D7JTOLFK.cjs +285 -0
  46. package/dist/chunk-DVM4FKZL.cjs +169 -0
  47. package/dist/chunk-DYEJQTDN.cjs +49 -0
  48. package/dist/chunk-E2BMSZ2W.cjs +151 -0
  49. package/dist/chunk-E3UK5IIB.cjs +593 -0
  50. package/dist/chunk-EM6SBQKM.cjs +470 -0
  51. package/dist/chunk-FJSWYIR7.cjs +482 -0
  52. package/dist/chunk-FK6GO24V.cjs +54 -0
  53. package/dist/chunk-FXUUWYAX.cjs +654 -0
  54. package/dist/chunk-G3HRIVEY.cjs +395 -0
  55. package/dist/chunk-G643DQCH.cjs +13 -0
  56. package/dist/chunk-G7HXGLEC.cjs +175 -0
  57. package/dist/chunk-GDSHDTJ4.cjs +152 -0
  58. package/dist/chunk-GNEO2XOF.cjs +2040 -0
  59. package/dist/{chunk-56DAX2BE.mjs → chunk-GYKJCFTS.mjs} +1 -1
  60. package/dist/chunk-H6G5INWM.cjs +1094 -0
  61. package/dist/chunk-HBTUGXHS.cjs +180 -0
  62. package/dist/chunk-HREOKQWT.cjs +45 -0
  63. package/dist/chunk-I4J452B7.cjs +435 -0
  64. package/dist/chunk-I57LW5VZ.cjs +94 -0
  65. package/dist/chunk-I7PUUDGY.cjs +389 -0
  66. package/dist/chunk-IAMRBF3Z.cjs +86 -0
  67. package/dist/chunk-IKNRN4VS.cjs +14214 -0
  68. package/dist/chunk-IQXFRNY2.cjs +169 -0
  69. package/dist/chunk-IXTFU4PL.cjs +2355 -0
  70. package/dist/chunk-J2OP5GG3.cjs +725 -0
  71. package/dist/chunk-J3LOGE4T.cjs +42 -0
  72. package/dist/chunk-J7FSKED3.cjs +93 -0
  73. package/dist/chunk-JDNHKPTD.cjs +22 -0
  74. package/dist/chunk-JSROZYYO.cjs +164 -0
  75. package/dist/chunk-K6FNHVDR.cjs +696 -0
  76. package/dist/chunk-KGZIORNL.cjs +43 -0
  77. package/dist/{chunk-MVIWBEJF.mjs → chunk-KPNVGRBL.mjs} +1 -1
  78. package/dist/chunk-KR6CKSXT.cjs +15 -0
  79. package/dist/chunk-KROWKCUH.cjs +185 -0
  80. package/dist/chunk-KVFPGF2M.cjs +46 -0
  81. package/dist/chunk-LCCBO7PJ.cjs +46 -0
  82. package/dist/chunk-LIUGYUX3.cjs +22 -0
  83. package/dist/chunk-LTNGXMQ6.cjs +55 -0
  84. package/dist/chunk-M2L4MYDQ.cjs +14 -0
  85. package/dist/chunk-MCJLA63J.cjs +1 -0
  86. package/dist/chunk-MKB2EGIR.cjs +148 -0
  87. package/dist/chunk-MQ3H6LT5.cjs +202 -0
  88. package/dist/chunk-MT763TDW.cjs +43 -0
  89. package/dist/chunk-MWSK6C4J.cjs +18 -0
  90. package/dist/chunk-MWWVKDW3.cjs +169 -0
  91. package/dist/chunk-NO3WWW3N.cjs +192 -0
  92. package/dist/chunk-NV3A5DXM.cjs +862 -0
  93. package/dist/chunk-NWOD6NIT.cjs +9 -0
  94. package/dist/chunk-NZKJGRB3.cjs +230 -0
  95. package/dist/chunk-OAVTUMJP.cjs +1496 -0
  96. package/dist/chunk-OHY2ZWUG.cjs +25 -0
  97. package/dist/chunk-OI6CMLWX.cjs +47 -0
  98. package/dist/chunk-OIEOCXKG.cjs +453 -0
  99. package/dist/chunk-OWOUTKIJ.cjs +558 -0
  100. package/dist/chunk-OX6O6WVA.cjs +74 -0
  101. package/dist/chunk-OXSIH4D6.cjs +476 -0
  102. package/dist/chunk-OYEUREB6.cjs +35 -0
  103. package/dist/chunk-PCOTGFSM.cjs +139 -0
  104. package/dist/chunk-PZYCPSCC.cjs +35 -0
  105. package/dist/chunk-QBK2AA4U.cjs +445 -0
  106. package/dist/chunk-QBPXNZGV.cjs +487 -0
  107. package/dist/chunk-QNPEUFHQ.cjs +27 -0
  108. package/dist/chunk-QZRVZSPN.cjs +236 -0
  109. package/dist/chunk-R5A5KNVX.cjs +20 -0
  110. package/dist/chunk-R5JIFR6B.cjs +42 -0
  111. package/dist/chunk-R6AIILII.cjs +193 -0
  112. package/dist/chunk-RG3ZOTG5.cjs +34 -0
  113. package/dist/chunk-ROUTX2E5.cjs +390 -0
  114. package/dist/chunk-RTHIVJ2G.cjs +54 -0
  115. package/dist/chunk-S3A45T7F.cjs +166 -0
  116. package/dist/chunk-S3JO3N4H.cjs +17 -0
  117. package/dist/chunk-SK35NQKK.cjs +27 -0
  118. package/dist/chunk-SU7MH53P.cjs +180 -0
  119. package/dist/chunk-SVRTJOUF.cjs +113 -0
  120. package/dist/chunk-SWN467MP.cjs +18 -0
  121. package/dist/chunk-SYQ3MOWW.cjs +73 -0
  122. package/dist/chunk-T5CERMEH.cjs +417 -0
  123. package/dist/chunk-TFAXUHWX.cjs +206 -0
  124. package/dist/chunk-TIWHTW3Q.cjs +24 -0
  125. package/dist/chunk-TKJZFIML.cjs +20 -0
  126. package/dist/chunk-TKNSDBBN.cjs +193 -0
  127. package/dist/chunk-TWGMSEHX.cjs +525 -0
  128. package/dist/chunk-TYQUSXUG.cjs +1357 -0
  129. package/dist/chunk-U4KT7QP3.cjs +23 -0
  130. package/dist/chunk-UJ2C4ICS.cjs +277 -0
  131. package/dist/chunk-UN5GHC5V.cjs +10244 -0
  132. package/dist/chunk-UQZ4AYTH.cjs +168 -0
  133. package/dist/chunk-US2QVW3E.cjs +36 -0
  134. package/dist/chunk-VB6UCX3V.cjs +421 -0
  135. package/dist/chunk-VEKFLAQM.cjs +300 -0
  136. package/dist/chunk-VQDBNVOO.cjs +14 -0
  137. package/dist/chunk-W4E7WMXE.cjs +71 -0
  138. package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
  139. package/dist/chunk-WMAPPDMM.cjs +28 -0
  140. package/dist/chunk-WMOGFOUJ.cjs +223 -0
  141. package/dist/chunk-WPYFSQKK.cjs +37 -0
  142. package/dist/chunk-WZMNW2IW.cjs +1415 -0
  143. package/dist/chunk-XGC343EY.cjs +443 -0
  144. package/dist/chunk-XSKZORAS.cjs +727 -0
  145. package/dist/chunk-XWAWFQFS.cjs +82 -0
  146. package/dist/chunk-Y4YMF2NQ.cjs +460 -0
  147. package/dist/chunk-Y4YWHNKU.cjs +250 -0
  148. package/dist/chunk-Y53ZSFN6.cjs +504 -0
  149. package/dist/chunk-YA6LLTIJ.cjs +411 -0
  150. package/dist/chunk-YFPGHF5F.cjs +202 -0
  151. package/dist/chunk-YJRZR7VU.cjs +28 -0
  152. package/dist/chunk-YTAABQEV.cjs +1 -0
  153. package/dist/chunk-YX3DBN4M.cjs +18 -0
  154. package/dist/chunk-YZTASLPQ.cjs +64 -0
  155. package/dist/chunk-Z5HIWVDP.cjs +2173 -0
  156. package/dist/chunk-ZEG3OPIB.cjs +93 -0
  157. package/dist/chunk-ZMN3H73H.cjs +155 -0
  158. package/dist/client/lifecycle.cjs +6 -35
  159. package/dist/client-plugins.cjs +7 -448
  160. package/dist/client.cjs +171 -9808
  161. package/dist/config.cjs +8 -36
  162. package/dist/cron.cjs +24 -491
  163. package/dist/deferred.cjs +26 -475
  164. package/dist/deployment.cjs +39 -210
  165. package/dist/devtools-OUIPHVV6.cjs +388 -0
  166. package/dist/devtools-client-4WAPJY5L.cjs +254 -0
  167. package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
  168. package/dist/docs.cjs +46 -5657
  169. package/dist/env-types.cjs +5 -226
  170. package/dist/env.cjs +21 -338
  171. package/dist/environment/vite.cjs +8 -372
  172. package/dist/environment.cjs +12 -94
  173. package/dist/font.cjs +13 -63
  174. package/dist/headers.cjs +7 -123
  175. package/dist/i18n/client.cjs +55 -294
  176. package/dist/i18n/index.cjs +22 -209
  177. package/dist/i18n/server.cjs +22 -745
  178. package/dist/image/server.cjs +13 -729
  179. package/dist/image/sharp.cjs +33 -171
  180. package/dist/image.cjs +41 -85
  181. package/dist/index.cjs +1151 -68080
  182. package/dist/index.mjs +3 -3
  183. package/dist/instrumentation.cjs +12 -138
  184. package/dist/integration-orm-55F7CII5.cjs +13 -0
  185. package/dist/integrations.cjs +55 -4090
  186. package/dist/internal/app-markdown-runtime.cjs +27 -224
  187. package/dist/internal/build-runtime.cjs +120 -52259
  188. package/dist/internal/build-runtime.mjs +3 -3
  189. package/dist/internal/cli-runtime.cjs +67 -13811
  190. package/dist/internal/client-error-overlay.cjs +80 -733
  191. package/dist/internal/client-error-overlay.mjs +1 -1
  192. package/dist/internal/client-runtime.cjs +81 -913
  193. package/dist/internal/compression-runtime.cjs +8 -214
  194. package/dist/internal/config-runtime.cjs +42 -6547
  195. package/dist/internal/docs-precompiled-runtime.cjs +26 -46
  196. package/dist/internal/infra-analytics-runtime.cjs +10 -536
  197. package/dist/internal/isolated-boundary.cjs +14 -414
  198. package/dist/internal/metadata-image-runtime.cjs +7 -285
  199. package/dist/internal/product-telemetry-runtime.cjs +42 -97
  200. package/dist/internal/product-telemetry-runtime.mjs +1 -1
  201. package/dist/internal/production-node-env.cjs +6 -63
  202. package/dist/internal/production-runtime.cjs +418 -7133
  203. package/dist/internal/request-cookies.cjs +6 -54
  204. package/dist/json-ld.cjs +24 -50
  205. package/dist/layers-E4WPJNY5.cjs +17 -0
  206. package/dist/manager-G4B2IPYE.cjs +14 -0
  207. package/dist/markdown.cjs +21 -547
  208. package/dist/middleware.cjs +36 -2995
  209. package/dist/navigation.cjs +22 -2588
  210. package/dist/nitro-4I2MYLY2.cjs +652 -0
  211. package/dist/observability.cjs +22 -614
  212. package/dist/og.cjs +5 -28
  213. package/dist/plugin.cjs +106 -37442
  214. package/dist/plugin.mjs +2 -2
  215. package/dist/query/client.cjs +113 -449
  216. package/dist/query/index.cjs +26 -288
  217. package/dist/query/parsers.cjs +23 -247
  218. package/dist/query/server.cjs +36 -298
  219. package/dist/renderer/react/client.cjs +9 -43
  220. package/dist/renderer/react/server.cjs +40 -103
  221. package/dist/renderer/react/vite.cjs +7 -29
  222. package/dist/renderer-client.cjs +126 -4295
  223. package/dist/renderer.cjs +31 -249
  224. package/dist/request.cjs +5 -68
  225. package/dist/router.cjs +11 -474
  226. package/dist/routes.cjs +42 -2461
  227. package/dist/schema-dev-notice-MXSZMVDG.cjs +56 -0
  228. package/dist/schema.cjs +6 -33
  229. package/dist/search-client-G3RICOFU.cjs +13 -0
  230. package/dist/server-action-security.cjs +25 -541
  231. package/dist/server-fn-client.cjs +6 -337
  232. package/dist/server-fn.cjs +32 -1841
  233. package/dist/server-plugins.cjs +15 -884
  234. package/dist/server-query-client.cjs +15 -1883
  235. package/dist/server-query.cjs +16 -1838
  236. package/dist/server.cjs +296 -44681
  237. package/dist/server.mjs +2 -2
  238. package/dist/storage.cjs +57 -576
  239. package/dist/testing.cjs +89 -3186
  240. package/dist/theme/client.cjs +13 -108
  241. package/dist/theme/index.cjs +6 -68
  242. package/dist/theme/runtime.cjs +13 -78
  243. package/dist/theme/server.cjs +10 -179
  244. package/dist/version.cjs +4 -32
  245. package/dist/version.mjs +1 -1
  246. package/dist/vite.cjs +119 -37773
  247. package/dist/vite.mjs +2 -2
  248. package/dist/workflows.cjs +19 -1040
  249. package/package.json +1 -1
@@ -1,4253 +1,85 @@
1
- "use strict";
2
- "use client";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
10
- var __export = (target, all) => {
11
- for (var name in all)
12
- __defProp(target, name, { get: all[name], enumerable: true });
13
- };
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") {
16
- for (let key of __getOwnPropNames(from))
17
- if (!__hasOwnProp.call(to, key) && key !== except)
18
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
- // If the importer is in node compatibility mode or this is not an ESM
24
- // file that has been converted to a CommonJS file using a Babel-
25
- // compatible transform (i.e. "__esModule" has not been set), then set
26
- // "default" to the CommonJS "module.exports" for node compatibility.
27
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
- mod
29
- ));
30
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
-
32
- // src/renderer-client.ts
33
- var renderer_client_exports = {};
34
- __export(renderer_client_exports, {
35
- createRendererAction: () => createRendererAction,
36
- createRendererI18n: () => createRendererI18n,
37
- createRendererQuery: () => createRendererQuery,
38
- createRendererRouter: () => createRendererRouter,
39
- createRendererTheme: () => createRendererTheme
40
- });
41
- module.exports = __toCommonJS(renderer_client_exports);
42
-
43
- // src/routing/specificity.ts
44
- var _AmbiguousRouteError = class _AmbiguousRouteError extends Error {
45
- constructor(message) {
46
- super(message);
47
- this.name = "AmbiguousRouteError";
48
- }
49
- };
50
- __name(_AmbiguousRouteError, "AmbiguousRouteError");
51
- var AmbiguousRouteError = _AmbiguousRouteError;
52
- var _NonTerminalCatchAllRouteError = class _NonTerminalCatchAllRouteError extends TypeError {
53
- constructor(message) {
54
- super(message);
55
- this.name = "NonTerminalCatchAllRouteError";
56
- }
57
- };
58
- __name(_NonTerminalCatchAllRouteError, "NonTerminalCatchAllRouteError");
59
- var NonTerminalCatchAllRouteError = _NonTerminalCatchAllRouteError;
60
- var _DuplicateRouteParameterError = class _DuplicateRouteParameterError extends AmbiguousRouteError {
61
- constructor(message) {
62
- super(message);
63
- this.name = "DuplicateRouteParameterError";
64
- }
65
- };
66
- __name(_DuplicateRouteParameterError, "DuplicateRouteParameterError");
67
- var DuplicateRouteParameterError = _DuplicateRouteParameterError;
68
- var _ReservedRouteParameterError = class _ReservedRouteParameterError extends AmbiguousRouteError {
69
- constructor(message) {
70
- super(message);
71
- this.name = "ReservedRouteParameterError";
72
- }
73
- };
74
- __name(_ReservedRouteParameterError, "ReservedRouteParameterError");
75
- var ReservedRouteParameterError = _ReservedRouteParameterError;
76
- var _BrowserUnstableRouteError = class _BrowserUnstableRouteError extends TypeError {
77
- constructor(message) {
78
- super(message);
79
- this.name = "BrowserUnstableRouteError";
80
- }
81
- };
82
- __name(_BrowserUnstableRouteError, "BrowserUnstableRouteError");
83
- var BrowserUnstableRouteError = _BrowserUnstableRouteError;
84
- var SEGMENT_RANK = {
85
- static: 4,
86
- dynamic: 3,
87
- "catch-all": 1,
88
- "optional-catch-all": 0
89
- };
90
- var ROUTE_END_RANK = 2;
91
- function compareRouteSpecificity(left, right) {
92
- const length = Math.max(left.length, right.length);
93
- for (let index = 0; index < length; index++) {
94
- const leftRank = index < left.length ? SEGMENT_RANK[left[index]] : ROUTE_END_RANK;
95
- const rightRank = index < right.length ? SEGMENT_RANK[right[index]] : ROUTE_END_RANK;
96
- if (leftRank !== rightRank) return rightRank - leftRank;
97
- }
98
- return 0;
99
- }
100
- __name(compareRouteSpecificity, "compareRouteSpecificity");
101
- var ROUTER_PARAMETER_NAME = "[A-Za-z0-9_$-]+";
102
- var PAGE_PARAMETER_PATTERN = /^(?:\[\[\.\.\.(.+)\]\]|\[\.\.\.(.+)\]|\[(.+)\])$/;
103
- var ROUTER_PARAMETER_PATTERN = /^(?:\[\[\.\.\.([A-Za-z0-9_$-]+)\]\]|\[\.\.\.([A-Za-z0-9_$-]+)\]|\[([A-Za-z0-9_$-]+)\]|:([A-Za-z0-9_$-]+)|\*([A-Za-z0-9_$-]+)\??)$/;
104
- var RESERVED_PARAMETER_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
105
- function assertBrowserStableRoutePath(pattern) {
106
- if (pattern.includes("\\") || hasControlCharacter(pattern)) {
107
- throw new BrowserUnstableRouteError(
108
- `Route path "${pattern}" cannot contain backslashes or control characters.`
109
- );
110
- }
111
- for (const segment of pattern.split("/").filter(Boolean)) {
112
- if (segment.startsWith("(") && segment.endsWith(")") || segment.startsWith("[") && segment.endsWith("]")) {
113
- continue;
114
- }
115
- let decoded = segment;
116
- try {
117
- decoded = decodeURIComponent(segment);
118
- } catch {
119
- }
120
- if (decoded === "." || decoded === ".." || decoded.includes("/") || decoded.includes("\\") || hasControlCharacter(decoded)) {
121
- throw new BrowserUnstableRouteError(
122
- `Route path "${pattern}" contains browser-unstable segment "${segment}".`
123
- );
124
- }
125
- }
126
- }
127
- __name(assertBrowserStableRoutePath, "assertBrowserStableRoutePath");
128
- function hasControlCharacter(value) {
129
- return Array.from(value).some((character) => {
130
- const code = character.charCodeAt(0);
131
- return code <= 31 || code >= 127 && code <= 159;
132
- });
133
- }
134
- __name(hasControlCharacter, "hasControlCharacter");
135
- function assertUniqueRouteParameters(pattern, syntax = "page") {
136
- const parameterPattern = syntax === "router" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;
137
- const names = /* @__PURE__ */ new Set();
138
- for (const segment of splitRoutePattern(pattern, syntax)) {
139
- const match = parameterPattern.exec(segment);
140
- const name = match?.slice(1).find(Boolean);
141
- if (!name) continue;
142
- if (RESERVED_PARAMETER_NAMES.has(name)) {
143
- throw new ReservedRouteParameterError(
144
- `Route parameter "${name}" in route "${pattern}" is reserved. Use a different parameter name.`
145
- );
146
- }
147
- if (names.has(name)) {
148
- throw new DuplicateRouteParameterError(
149
- `Duplicate route parameter "${name}" in route "${pattern}". Each dynamic segment must use a unique name.`
150
- );
151
- }
152
- names.add(name);
153
- }
154
- }
155
- __name(assertUniqueRouteParameters, "assertUniqueRouteParameters");
156
- function splitRoutePattern(pattern, syntax) {
157
- return pattern.replace(/\\/g, "/").split("/").filter(Boolean).filter(
158
- (segment) => syntax === "api" ? true : !(segment.startsWith("(") && segment.endsWith(")"))
159
- );
160
- }
161
- __name(splitRoutePattern, "splitRoutePattern");
162
- function assertTerminalCatchAll(pattern, syntax = "page") {
163
- const segments = splitRoutePattern(pattern, syntax);
164
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
165
- const catchAllPattern = new RegExp(
166
- syntax === "router" ? `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\]|\\*${parameterName}\\??)$` : `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\])$`
167
- );
168
- const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));
169
- if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {
170
- throw new NonTerminalCatchAllRouteError(
171
- `Catch-all segment "${segments[catchAllIndex]}" must be the final segment in route "${pattern}".`
172
- );
173
- }
174
- }
175
- __name(assertTerminalCatchAll, "assertTerminalCatchAll");
176
- function getRoutePatternShape(pattern, syntax = "page") {
177
- assertTerminalCatchAll(pattern, syntax);
178
- const segments = splitRoutePattern(pattern, syntax).map((segment) => {
179
- const specificity = getPatternSegmentSpecificity(segment, syntax);
180
- if (specificity !== "static") return specificity;
181
- try {
182
- return `static:${decodeURIComponent(segment)}`;
183
- } catch {
184
- return `static:${segment}`;
185
- }
186
- });
187
- return segments.length === 0 ? "/" : JSON.stringify(segments);
188
- }
189
- __name(getRoutePatternShape, "getRoutePatternShape");
190
- function getPatternSegmentSpecificity(segment, syntax) {
191
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
192
- const supportsColonAndStar = syntax === "router";
193
- if (new RegExp(`^\\[\\[\\.\\.\\.${parameterName}\\]\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}\\?$`).test(segment)) {
194
- return "optional-catch-all";
195
- }
196
- if (new RegExp(`^\\[\\.\\.\\.${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}$`).test(segment)) {
197
- return "catch-all";
198
- }
199
- if (new RegExp(`^\\[${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment)) {
200
- return "dynamic";
201
- }
202
- return "static";
203
- }
204
- __name(getPatternSegmentSpecificity, "getPatternSegmentSpecificity");
205
-
206
- // src/routing/matcher.ts
207
- function parseRoutePattern(pattern) {
208
- assertBrowserStableRoutePath(pattern);
209
- assertTerminalCatchAll(pattern, "router");
210
- assertUniqueRouteParameters(pattern, "router");
211
- return splitRoutePattern2(pattern).filter((part) => !isRouteGroup(part)).map((part) => {
212
- const optionalCatchAll = part.match(/^\[\[\.\.\.([A-Za-z0-9_$-]+)\]\]$/);
213
- if (optionalCatchAll) {
214
- return {
215
- type: "dynamic",
216
- name: optionalCatchAll[1],
217
- catchAll: true,
218
- optional: true
219
- };
220
- }
221
- const catchAll = part.match(/^\[\.\.\.([A-Za-z0-9_$-]+)\]$/);
222
- if (catchAll) {
223
- return {
224
- type: "dynamic",
225
- name: catchAll[1],
226
- catchAll: true,
227
- optional: false
228
- };
229
- }
230
- const dynamic = part.match(/^\[([A-Za-z0-9_$-]+)\]$/) || part.match(/^:([A-Za-z0-9_$-]+)$/);
231
- if (dynamic) {
232
- return {
233
- type: "dynamic",
234
- name: dynamic[1],
235
- catchAll: false,
236
- optional: false
237
- };
238
- }
239
- const star = part.match(/^\*([A-Za-z0-9_$-]+)(\?)?$/);
240
- if (star) {
241
- return {
242
- type: "dynamic",
243
- name: star[1],
244
- catchAll: true,
245
- optional: !!star[2]
246
- };
247
- }
248
- return {
249
- type: "static",
250
- value: decodePathSegment(part)
251
- };
252
- });
253
- }
254
- __name(parseRoutePattern, "parseRoutePattern");
255
- function matchSegmentParts(segments, parts, allowTrailingSegments = false) {
256
- const params = {};
257
- if (segments.length === 0) {
258
- return parts.length === 0 ? params : null;
259
- }
260
- let pathIndex = 0;
261
- for (const segment of segments) {
262
- if (segment.type === "static") {
263
- if (decodePathSegment(parts[pathIndex] || "") !== segment.value) return null;
264
- pathIndex++;
265
- continue;
266
- }
267
- if (segment.catchAll) {
268
- const remaining = parts.slice(pathIndex).map(decodePathSegment);
269
- if (remaining.length === 0 && !segment.optional) return null;
270
- params[segment.name] = remaining.join("/");
271
- pathIndex = parts.length;
272
- continue;
273
- }
274
- const value = parts[pathIndex];
275
- if (!value) return null;
276
- params[segment.name] = decodePathSegment(value);
277
- pathIndex++;
278
- }
279
- return allowTrailingSegments || pathIndex === parts.length ? params : null;
280
- }
281
- __name(matchSegmentParts, "matchSegmentParts");
282
- function normalizePathname(value) {
283
- const raw = value || "/";
284
- let pathname = raw;
285
- try {
286
- pathname = new URL(raw, "http://farm.local").pathname;
287
- } catch {
288
- pathname = raw.split(/[?#]/, 1)[0] || "/";
289
- }
290
- pathname = pathname.replace(/\\/g, "/").replace(/\/+/g, "/");
291
- if (!pathname.startsWith("/")) pathname = `/${pathname}`;
292
- if (pathname.length > 1) pathname = pathname.replace(/\/+$/, "");
293
- return pathname || "/";
294
- }
295
- __name(normalizePathname, "normalizePathname");
296
- function splitNormalizedPathname(pathname) {
297
- return pathname.split("/").filter(Boolean);
298
- }
299
- __name(splitNormalizedPathname, "splitNormalizedPathname");
300
- function normalizeRoutePattern(value) {
301
- let pathname = (value || "/").replace(/\\/g, "/").replace(/\/+/g, "/");
302
- if (!pathname.startsWith("/")) pathname = `/${pathname}`;
303
- if (pathname.length > 1) pathname = pathname.replace(/\/+$/, "");
304
- return pathname || "/";
305
- }
306
- __name(normalizeRoutePattern, "normalizeRoutePattern");
307
- function splitRoutePattern2(pattern) {
308
- return normalizeRoutePattern(pattern).split("/").filter(Boolean);
309
- }
310
- __name(splitRoutePattern2, "splitRoutePattern");
311
- function isRouteGroup(part) {
312
- return part.startsWith("(") && part.endsWith(")");
313
- }
314
- __name(isRouteGroup, "isRouteGroup");
315
- function decodePathSegment(value) {
316
- try {
317
- return decodeURIComponent(value);
318
- } catch {
319
- return value;
320
- }
321
- }
322
- __name(decodePathSegment, "decodePathSegment");
323
-
324
- // src/router.ts
325
- function createFarmRouter(routes) {
326
- const normalizedRoutes = routes.map(normalizeRouteInput);
327
- const patternsByShape = /* @__PURE__ */ new Map();
328
- for (const entry of normalizedRoutes) {
329
- const shape = getRoutePatternShape(entry.route.path, "router");
330
- const existingPattern = patternsByShape.get(shape);
331
- if (existingPattern) {
332
- throw new AmbiguousRouteError(
333
- `Ambiguous route patterns "${existingPattern}" and "${entry.route.path}" match the same URLs. Keep only one route for this URL shape.`
334
- );
335
- }
336
- patternsByShape.set(shape, entry.route.path);
337
- }
338
- normalizedRoutes.sort(compareRoutes);
339
- const exactRoutes = /* @__PURE__ */ new Map();
340
- for (const entry of normalizedRoutes) {
341
- if (entry.segments.every((segment) => segment.type === "static")) {
342
- const pathname = entry.segments.length ? `/${entry.segments.map((segment) => encodePathSegment(segment.value)).join("/")}` : "/";
343
- exactRoutes.set(pathname, entry);
344
- }
345
- }
346
- return {
347
- routes: normalizedRoutes.map((entry) => entry.route),
348
- match(pathname) {
349
- const normalizedPathname = normalizePathname(pathname);
350
- const exactRoute = exactRoutes.get(normalizedPathname);
351
- if (exactRoute) {
352
- return {
353
- route: exactRoute.route,
354
- pathname: normalizedPathname,
355
- params: {}
356
- };
357
- }
358
- const parts = splitNormalizedPathname(normalizedPathname);
359
- for (const entry of normalizedRoutes) {
360
- const params = matchSegmentParts(entry.segments, parts);
361
- if (params) {
362
- return {
363
- route: entry.route,
364
- pathname: normalizedPathname,
365
- params
366
- };
367
- }
368
- }
369
- return null;
370
- },
371
- build: buildFarmRoutePath,
372
- isActive: isFarmRouteActive
373
- };
374
- }
375
- __name(createFarmRouter, "createFarmRouter");
376
- function buildFarmRoutePath(pattern, params = {}, options = {}) {
377
- const parts = [];
378
- for (const segment of parseRoutePattern(pattern)) {
379
- if (segment.type === "static") {
380
- parts.push(encodePathSegment(segment.value));
381
- continue;
382
- }
383
- const value = params[segment.name];
384
- const values = Array.isArray(value) ? value : value == null ? [] : [value];
385
- if (values.length === 0) {
386
- if (segment.optional) continue;
387
- throw new Error(`Missing route param "${segment.name}" for ${pattern}.`);
388
- }
389
- if (!segment.catchAll && values.length > 1) {
390
- throw new Error(`Route param "${segment.name}" for ${pattern} expects a single value.`);
391
- }
392
- const encodedValues = values.map((item) => {
393
- const value2 = String(item);
394
- if (!value2) {
395
- throw new Error(
396
- `Route param "${segment.name}" for ${pattern} cannot contain an empty path segment.`
397
- );
398
- }
399
- return encodePathSegment(value2);
400
- });
401
- parts.push(...encodedValues);
402
- }
403
- let pathname = parts.length ? `/${parts.join("/")}` : "/";
404
- if (options.trailingSlash && pathname !== "/") {
405
- pathname = `${pathname}/`;
406
- }
407
- return appendQueryAndHash(pathname, options);
408
- }
409
- __name(buildFarmRoutePath, "buildFarmRoutePath");
410
- function isFarmRouteActive(pattern, pathname, options = {}) {
411
- const normalizedPathname = normalizePathname(pathname);
412
- const segments = parseRoutePattern(pattern);
413
- const parts = splitNormalizedPathname(normalizedPathname);
414
- if (matchSegmentParts(segments, parts)) return true;
415
- if (options.exact !== false) return false;
416
- if (segments.length === 0) return normalizedPathname === "/";
417
- return matchSegmentParts(segments, parts, true) !== null;
418
- }
419
- __name(isFarmRouteActive, "isFarmRouteActive");
420
- function normalizeRouteInput(input, index) {
421
- const route = typeof input === "string" ? { path: input } : input;
422
- const segments = parseRoutePattern(route.path);
423
- const path = normalizeRoutePattern(route.path);
424
- return {
425
- route: {
426
- ...route,
427
- path
428
- },
429
- segments,
430
- specificity: segments.map(getRouterSegmentSpecificity),
431
- index
432
- };
433
- }
434
- __name(normalizeRouteInput, "normalizeRouteInput");
435
- function compareRoutes(left, right) {
436
- const specificity = compareRouteSpecificity(left.specificity, right.specificity);
437
- if (specificity !== 0) return specificity;
438
- return left.index - right.index;
439
- }
440
- __name(compareRoutes, "compareRoutes");
441
- function getRouterSegmentSpecificity(segment) {
442
- if (segment.type === "static") return "static";
443
- if (!segment.catchAll) return "dynamic";
444
- return segment.optional ? "optional-catch-all" : "catch-all";
445
- }
446
- __name(getRouterSegmentSpecificity, "getRouterSegmentSpecificity");
447
- function encodePathSegment(value) {
448
- return encodeURIComponent(value);
449
- }
450
- __name(encodePathSegment, "encodePathSegment");
451
- function appendQueryAndHash(pathname, options) {
452
- const search = createSearchParams(options.query);
453
- const hash = options.hash ? `#${options.hash.replace(/^#/, "")}` : "";
454
- const query = search.toString();
455
- return `${pathname}${query ? `?${query}` : ""}${hash}`;
456
- }
457
- __name(appendQueryAndHash, "appendQueryAndHash");
458
- function createSearchParams(query) {
459
- if (query instanceof URLSearchParams) return query;
460
- const search = new URLSearchParams();
461
- if (!query) return search;
462
- for (const [key, value] of Object.entries(query)) {
463
- const values = Array.isArray(value) ? value : [value];
464
- for (const item of values) {
465
- if (item == null) continue;
466
- search.append(key, String(item));
467
- }
468
- }
469
- return search;
470
- }
471
- __name(createSearchParams, "createSearchParams");
472
-
473
- // src/deferred.ts
474
- var FARM_DEFERRED_CONTENT_TYPE = "application/x-farm-deferred+json";
475
- var FARM_DEFERRED_ERROR_CODE = "FARM_DEFERRED_DATA_ERROR";
476
- var FARM_DEFERRED_MARKER = "$farmDeferred";
477
- var _DeferredDataError = class _DeferredDataError extends Error {
478
- constructor(message = "Deferred route data failed to load") {
479
- super(message);
480
- this.name = "DeferredDataError";
481
- this.code = FARM_DEFERRED_ERROR_CODE;
482
- }
483
- };
484
- __name(_DeferredDataError, "DeferredDataError");
485
- var DeferredDataError = _DeferredDataError;
486
- async function readDeferredDataResponse(response, options = {}) {
487
- const contentType = response.headers.get("Content-Type") || "";
488
- if (!contentType.toLowerCase().startsWith(FARM_DEFERRED_CONTENT_TYPE)) {
489
- const data2 = await response.json();
490
- notifyDeferredComplete(options);
491
- return data2;
492
- }
493
- if (!response.body) {
494
- throw new DeferredDataError("Deferred route data response has no body");
495
- }
496
- const reader = response.body.getReader();
497
- const decoder = new TextDecoder();
498
- const controllers = /* @__PURE__ */ new Map();
499
- let buffer = "";
500
- let complete = false;
501
- const readLine = /* @__PURE__ */ __name(async () => {
502
- while (true) {
503
- const newline = buffer.indexOf("\n");
504
- if (newline >= 0) {
505
- const line = buffer.slice(0, newline);
506
- buffer = buffer.slice(newline + 1);
507
- return line;
508
- }
509
- if (complete) {
510
- if (!buffer) return void 0;
511
- const line = buffer;
512
- buffer = "";
513
- return line;
514
- }
515
- const chunk = await reader.read();
516
- complete = chunk.done;
517
- if (chunk.value) buffer += decoder.decode(chunk.value, { stream: !chunk.done });
518
- if (chunk.done) buffer += decoder.decode();
519
- }
520
- }, "readLine");
521
- const firstLine = await readLine();
522
- if (!firstLine) {
523
- reader.releaseLock();
524
- throw new DeferredDataError("Deferred route data response is empty");
525
- }
526
- const initial = parseDeferredMessage(firstLine);
527
- if (initial.type !== "data") {
528
- reader.releaseLock();
529
- throw new DeferredDataError("Deferred route data response is invalid");
530
- }
531
- const data = reviveDeferredValue(initial.data, controllers);
532
- void (async () => {
533
- try {
534
- for (let line = await readLine(); line !== void 0; line = await readLine()) {
535
- if (!line) continue;
536
- const message = parseDeferredMessage(line);
537
- if (message.type === "resolve") {
538
- const controller = getControlledDeferred(message.id, controllers);
539
- controller.resolve(reviveDeferredValue(message.data, controllers));
540
- } else if (message.type === "reject") {
541
- getControlledDeferred(message.id, controllers).reject(
542
- new DeferredDataError(message.error?.message)
543
- );
544
- }
545
- }
546
- const outstanding = rejectPendingDeferred(
547
- controllers,
548
- "Deferred route data stream ended before completion"
549
- );
550
- if (outstanding === 0) notifyDeferredComplete(options);
551
- } catch {
552
- rejectPendingDeferred(controllers, "Deferred route data stream could not be read");
553
- } finally {
554
- reader.releaseLock();
555
- }
556
- })();
557
- return data;
558
- }
559
- __name(readDeferredDataResponse, "readDeferredDataResponse");
560
- function notifyDeferredComplete(options) {
561
- try {
562
- options.onComplete?.();
563
- } catch {
564
- }
565
- }
566
- __name(notifyDeferredComplete, "notifyDeferredComplete");
567
- function reviveDeferredValue(value, controllers, settlements, applyingSettlements = /* @__PURE__ */ new Set()) {
568
- if (isDeferredMarker(value)) {
569
- const id = value[FARM_DEFERRED_MARKER];
570
- if (id.startsWith("!")) {
571
- return { [FARM_DEFERRED_MARKER]: id.slice(1) };
572
- }
573
- const controller = getControlledDeferred(id, controllers);
574
- const settlement = settlements?.[id];
575
- if (settlement && controller.promise.status === "pending") {
576
- if (applyingSettlements.has(id)) return controller.promise;
577
- applyingSettlements.add(id);
578
- if (settlement.status === "fulfilled") {
579
- controller.resolve(
580
- reviveDeferredValue(settlement.value, controllers, settlements, applyingSettlements)
581
- );
582
- } else {
583
- controller.reject(new DeferredDataError(settlement.error.message));
584
- }
585
- applyingSettlements.delete(id);
586
- } else if (settlements && controller.promise.status === "pending") {
587
- controller.reject(new DeferredDataError("Deferred route data was not resolved"));
588
- }
589
- return controller.promise;
590
- }
591
- if (Array.isArray(value)) {
592
- return value.map(
593
- (item) => reviveDeferredValue(item, controllers, settlements, applyingSettlements)
594
- );
595
- }
596
- if (!value || typeof value !== "object") return value;
597
- const prototype = Object.getPrototypeOf(value);
598
- if (prototype !== Object.prototype && prototype !== null) return value;
599
- const output = {};
600
- for (const [key, item] of Object.entries(value)) {
601
- defineDataProperty(
602
- output,
603
- key,
604
- reviveDeferredValue(item, controllers, settlements, applyingSettlements)
605
- );
606
- }
607
- return output;
608
- }
609
- __name(reviveDeferredValue, "reviveDeferredValue");
610
- function defineDataProperty(output, key, value) {
611
- if (key === "__proto__") {
612
- Object.defineProperty(output, key, {
613
- value,
614
- enumerable: true,
615
- writable: true,
616
- configurable: true
617
- });
618
- } else {
619
- output[key] = value;
620
- }
621
- }
622
- __name(defineDataProperty, "defineDataProperty");
623
- function getControlledDeferred(id, controllers) {
624
- const existing = controllers.get(id);
625
- if (existing) return existing;
626
- let nativeResolve;
627
- let nativeReject;
628
- const promise = new Promise((resolve, reject) => {
629
- nativeResolve = resolve;
630
- nativeReject = reject;
631
- });
632
- promise.status = "pending";
633
- promise.catch(() => void 0);
634
- const controlled = {
635
- promise,
636
- resolve(value) {
637
- if (promise.status !== "pending") return;
638
- promise.status = "fulfilled";
639
- promise.value = value;
640
- nativeResolve(value);
641
- },
642
- reject(error) {
643
- if (promise.status !== "pending") return;
644
- promise.status = "rejected";
645
- promise.reason = error;
646
- nativeReject(error);
647
- }
648
- };
649
- controllers.set(id, controlled);
650
- return controlled;
651
- }
652
- __name(getControlledDeferred, "getControlledDeferred");
653
- function isDeferredMarker(value) {
654
- return Boolean(
655
- value && typeof value === "object" && Object.keys(value).length === 1 && typeof value[FARM_DEFERRED_MARKER] === "string"
656
- );
657
- }
658
- __name(isDeferredMarker, "isDeferredMarker");
659
- function parseDeferredMessage(line) {
660
- try {
661
- return JSON.parse(line);
662
- } catch {
663
- throw new DeferredDataError("Deferred route data response contains invalid JSON");
664
- }
665
- }
666
- __name(parseDeferredMessage, "parseDeferredMessage");
667
- function rejectPendingDeferred(controllers, message) {
668
- let rejected = 0;
669
- for (const controller of controllers.values()) {
670
- if (controller.promise.status === "pending") {
671
- controller.reject(new DeferredDataError(message));
672
- rejected += 1;
673
- }
674
- }
675
- return rejected;
676
- }
677
- __name(rejectPendingDeferred, "rejectPendingDeferred");
678
-
679
- // src/client-cancellation.ts
680
- function createClientCancellation(signal, timeoutMs = 0, parent) {
681
- let timer;
682
- let invalid;
683
- let timeoutReason;
684
- const signals = [signal, parent].filter((value) => !!value);
685
- if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2147483647) {
686
- invalid = new RangeError(
687
- "timeoutMs must be an integer between 0 and 2147483647 (0 disables the deadline)."
688
- );
689
- } else if (timeoutMs > 0) {
690
- const controller = new AbortController();
691
- signals.push(controller.signal);
692
- timer = setTimeout(() => {
693
- timeoutReason = new DOMException("Client request timed out", "TimeoutError");
694
- controller.abort(timeoutReason);
695
- }, timeoutMs);
696
- }
697
- const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
698
- let active = 0;
699
- let closed = false;
700
- const cleanup = /* @__PURE__ */ __name(() => {
701
- if (closed && active === 0 && timer !== void 0) {
702
- clearTimeout(timer);
703
- timer = void 0;
704
- }
705
- }, "cleanup");
706
- const check = /* @__PURE__ */ __name(() => {
707
- if (invalid) throw invalid;
708
- combined?.throwIfAborted();
709
- }, "check");
710
- return {
711
- signal: combined,
712
- get timedOut() {
713
- return timeoutReason !== void 0 && combined?.reason === timeoutReason;
714
- },
715
- check,
716
- hold() {
717
- active++;
718
- return () => {
719
- active--;
720
- cleanup();
721
- };
722
- },
723
- // A race also bounds cooperative local dispatch and custom HTTP implementations.
724
- // Late completion is consumed, but cannot turn a cancelled result into success.
725
- async run(work) {
726
- check();
727
- active++;
728
- let abort;
729
- try {
730
- if (!combined) return await work();
731
- return await new Promise((resolve, reject) => {
732
- abort = /* @__PURE__ */ __name(() => reject(combined.reason), "abort");
733
- combined.addEventListener("abort", abort, { once: true });
734
- Promise.resolve().then(() => {
735
- check();
736
- return work();
737
- }).then(resolve, reject);
738
- });
739
- } finally {
740
- if (abort) combined?.removeEventListener("abort", abort);
741
- active--;
742
- cleanup();
743
- }
744
- },
745
- async delay(ms) {
746
- let retryTimer;
747
- try {
748
- await this.run(
749
- () => new Promise((resolve) => {
750
- retryTimer = setTimeout(resolve, ms);
751
- })
752
- );
753
- } finally {
754
- if (retryTimer !== void 0) clearTimeout(retryTimer);
755
- }
756
- },
757
- dispose() {
758
- closed = true;
759
- cleanup();
760
- }
761
- };
762
- }
763
- __name(createClientCancellation, "createClientCancellation");
764
-
765
- // src/client/history-sync.ts
766
- var FARM_HISTORY_CHANGE_EVENT = "farm:historychange";
767
- function dispatchHistoryChange(kind) {
768
- window.dispatchEvent(
769
- new CustomEvent(FARM_HISTORY_CHANGE_EVENT, {
770
- detail: { kind }
771
- })
772
- );
773
- }
774
- __name(dispatchHistoryChange, "dispatchHistoryChange");
775
- function notifyHistoryChange(kind) {
776
- if (typeof window === "undefined") return;
777
- setTimeout(() => {
778
- if (kind === "url-search" && !getInstalledFarmSPARouter()) {
779
- window.dispatchEvent(new PopStateEvent("popstate"));
780
- return;
781
- }
782
- dispatchHistoryChange(kind);
783
- }, 0);
784
- }
785
- __name(notifyHistoryChange, "notifyHistoryChange");
786
- function notifyRouterHistoryChange() {
787
- if (typeof window === "undefined") return;
788
- setTimeout(() => dispatchHistoryChange("url-search"), 0);
789
- }
790
- __name(notifyRouterHistoryChange, "notifyRouterHistoryChange");
791
- function subscribeHistoryChange(listener) {
792
- if (typeof window === "undefined") return () => {
793
- };
794
- window.addEventListener("popstate", listener);
795
- window.addEventListener(FARM_HISTORY_CHANGE_EVENT, listener);
796
- return () => {
797
- window.removeEventListener("popstate", listener);
798
- window.removeEventListener(FARM_HISTORY_CHANGE_EVENT, listener);
799
- };
800
- }
801
- __name(subscribeHistoryChange, "subscribeHistoryChange");
802
-
803
- // src/deployment.ts
804
- var FARM_DEPLOYMENT_ID_HEADER = "x-farm-deployment-id";
805
- var FARM_DEPLOYMENT_MISMATCH_HEADER = "x-farm-deployment-mismatch";
806
- var FARM_DEPLOYMENT_MISMATCH_CODE = "FARM_DEPLOYMENT_MISMATCH";
807
- var FARM_DEPLOYMENT_MISMATCH_STATUS = 409;
808
- var _FarmDeploymentMismatchError = class _FarmDeploymentMismatchError extends Error {
809
- constructor(clientDeploymentId, serverDeploymentId) {
810
- super("The application was updated while this page was open. Refresh before trying again.");
811
- this.clientDeploymentId = clientDeploymentId;
812
- this.serverDeploymentId = serverDeploymentId;
813
- this.name = "FarmDeploymentMismatchError";
814
- this.code = FARM_DEPLOYMENT_MISMATCH_CODE;
815
- this.retryable = false;
816
- }
817
- };
818
- __name(_FarmDeploymentMismatchError, "FarmDeploymentMismatchError");
819
- var FarmDeploymentMismatchError = _FarmDeploymentMismatchError;
820
- function createFarmDeploymentRequestHeaders(deploymentId, init) {
821
- const headers = new Headers(init);
822
- if (deploymentId) {
823
- headers.set(FARM_DEPLOYMENT_ID_HEADER, deploymentId);
824
- }
825
- return headers;
826
- }
827
- __name(createFarmDeploymentRequestHeaders, "createFarmDeploymentRequestHeaders");
828
- function getFarmResponseDeploymentId(response) {
829
- return response.headers.get(FARM_DEPLOYMENT_ID_HEADER)?.trim() || void 0;
830
- }
831
- __name(getFarmResponseDeploymentId, "getFarmResponseDeploymentId");
832
- function isFarmDeploymentMismatchResponse(response, clientDeploymentId) {
833
- const serverDeploymentId = getFarmResponseDeploymentId(response);
834
- if (clientDeploymentId && serverDeploymentId && clientDeploymentId !== serverDeploymentId) {
835
- return true;
836
- }
837
- return response.status === FARM_DEPLOYMENT_MISMATCH_STATUS && response.headers.get(FARM_DEPLOYMENT_MISMATCH_HEADER) === "1";
838
- }
839
- __name(isFarmDeploymentMismatchResponse, "isFarmDeploymentMismatchResponse");
840
- function createFarmDeploymentMismatchError(response, clientDeploymentId) {
841
- return new FarmDeploymentMismatchError(
842
- clientDeploymentId,
843
- getFarmResponseDeploymentId(response) || "unknown"
844
- );
845
- }
846
- __name(createFarmDeploymentMismatchError, "createFarmDeploymentMismatchError");
847
-
848
- // src/client/hash-target.ts
849
- function getHashTargetElement(hash) {
850
- const fragment = hash.startsWith("#") ? hash.slice(1) : hash;
851
- if (!fragment) return null;
852
- let decoded = fragment;
853
- try {
854
- decoded = decodeURIComponent(fragment);
855
- } catch {
856
- }
857
- return document.getElementById(decoded) || document.getElementById(fragment) || document.getElementsByName(decoded)[0] || null;
858
- }
859
- __name(getHashTargetElement, "getHashTargetElement");
860
-
861
- // src/client/navigation-url.ts
862
- function isFarmExternalNavigationURL(url, currentOrigin) {
863
- return url.protocol !== "http:" && url.protocol !== "https:" || url.origin !== currentOrigin;
864
- }
865
- __name(isFarmExternalNavigationURL, "isFarmExternalNavigationURL");
866
- function resolveFarmNavigationURL(href, documentUrl) {
867
- return new URL(href, documentUrl);
868
- }
869
- __name(resolveFarmNavigationURL, "resolveFarmNavigationURL");
870
-
871
- // src/agent-json-ld.ts
872
- function pruneUndefined(object) {
873
- const result = {};
874
- for (const [key, value] of Object.entries(object)) {
875
- if (value !== void 0 && value !== null && value !== "") result[key] = value;
876
- }
877
- return result;
878
- }
879
- __name(pruneUndefined, "pruneUndefined");
880
- function serializeJsonLd(value) {
881
- return JSON.stringify(value).replace(/</g, "\\u003c");
882
- }
883
- __name(serializeJsonLd, "serializeJsonLd");
884
- function renderFarmAgentJsonLd(config, context2) {
885
- const base = pruneUndefined({
886
- name: config.name ?? context2.siteName ?? context2.title,
887
- url: config.url ?? context2.metadataBase,
888
- description: config.description ?? context2.description,
889
- logo: config.logo,
890
- sameAs: config.sameAs && config.sameAs.length > 0 ? config.sameAs : void 0
891
- });
892
- const object = {
893
- "@context": "https://schema.org",
894
- "@type": config.type || "Organization",
895
- ...base,
896
- ...config.properties || {}
897
- };
898
- if (Object.keys(object).length <= 2 && !config.properties) {
899
- return "";
900
- }
901
- return `<script type="application/ld+json">${serializeJsonLd(object)}</script>`;
902
- }
903
- __name(renderFarmAgentJsonLd, "renderFarmAgentJsonLd");
904
-
905
- // src/metadata.ts
906
- var FARM_METADATA_ATTRIBUTE = "data-farm-metadata";
907
- function renderMetadataHead(metadata, options = {}) {
908
- const resolvedMetadata = metadata || {};
909
- const metadataBase = resolveMetadataBase(resolvedMetadata);
910
- const explicitTitle = resolveMetadataTitle(resolvedMetadata.title);
911
- const title = explicitTitle || "Farm.js App";
912
- const tags = [];
913
- appendMetaName(tags, "description", resolvedMetadata.description);
914
- appendMetaName(tags, "keywords", normalizeKeywords(resolvedMetadata.keywords));
915
- appendMetaName(tags, "author", resolvedMetadata.author);
916
- if (Array.isArray(resolvedMetadata.authors)) {
917
- for (const author of resolvedMetadata.authors) {
918
- appendMetaName(tags, "author", author?.name);
919
- if (author?.url) {
920
- appendLink(tags, "author", resolveMetadataUrl(author.url, metadataBase));
921
- }
922
- }
923
- }
924
- appendMetaName(tags, "creator", resolvedMetadata.creator);
925
- appendMetaName(tags, "publisher", resolvedMetadata.publisher);
926
- appendMetaName(tags, "robots", normalizeRobots(resolvedMetadata.robots));
927
- if (isRecord(resolvedMetadata.robots)) {
928
- appendMetaName(tags, "googlebot", normalizeRobots(resolvedMetadata.robots.googleBot));
929
- }
930
- const alternates = resolvedMetadata.alternates;
931
- const explicitCanonical = isRecord(alternates) ? alternates.canonical : void 0;
932
- const canonicalHref = explicitCanonical != null ? resolveMetadataUrl(explicitCanonical, metadataBase) : options.pathname ? resolveMetadataUrl(sanitizeSelfCanonicalPathname(options.pathname), metadataBase) : void 0;
933
- if (canonicalHref) {
934
- appendLink(tags, "canonical", canonicalHref);
935
- }
936
- if (isRecord(alternates) && isRecord(alternates.languages)) {
937
- for (const [language, href] of Object.entries(alternates.languages)) {
938
- appendLink(tags, "alternate", resolveMetadataUrl(href, metadataBase), {
939
- hreflang: language
940
- });
941
- }
942
- }
943
- if (isRecord(alternates) && isRecord(alternates.types)) {
944
- for (const [type, value] of Object.entries(alternates.types)) {
945
- for (const entry of normalizeArray(value)) {
946
- const link = isRecord(entry) ? entry : { url: entry };
947
- appendLink(tags, "alternate", resolveMetadataUrl(link.url, metadataBase), {
948
- type,
949
- title: link.title
950
- });
951
- }
952
- }
953
- }
954
- const hasFavicon = appendIcons(tags, resolvedMetadata.icons, metadataBase);
955
- if (resolvedMetadata.manifest) {
956
- appendLink(
957
- tags,
958
- "manifest",
959
- resolveMetadataUrl(resolvedMetadata.manifest, metadataBase)
960
- );
961
- }
962
- appendNamedMetaRecord(tags, resolvedMetadata.other);
963
- appendOpenGraph(tags, resolvedMetadata.openGraph, metadataBase);
964
- appendTwitter(tags, resolvedMetadata.twitter, metadataBase);
965
- appendVerification(tags, resolvedMetadata.verification);
966
- if (options.jsonLd) {
967
- const jsonLdConfig = options.jsonLd === true ? {} : options.jsonLd;
968
- const jsonLdScript = renderFarmAgentJsonLd(jsonLdConfig, {
969
- metadataBase,
970
- siteName: isRecord(resolvedMetadata.openGraph) ? normalizeContent(resolvedMetadata.openGraph.siteName) : void 0,
971
- title: explicitTitle,
972
- description: normalizeContent(resolvedMetadata.description)
973
- });
974
- if (jsonLdScript) tags.push(jsonLdScript);
975
- }
976
- for (const entry of normalizeArray(resolvedMetadata.jsonLd)) {
977
- if (!isRecord(entry)) continue;
978
- tags.push(
979
- `<script type="application/ld+json" ${FARM_METADATA_ATTRIBUTE}>${serializeJsonLd(entry)}</script>`
980
- );
981
- }
982
- return {
983
- title: escapeText(title),
984
- tags: tags.length > 0 ? `
985
- ${tags.join("\n ")}` : "",
986
- hasFavicon,
987
- hasExplicitTitle: Boolean(explicitTitle)
988
- };
989
- }
990
- __name(renderMetadataHead, "renderMetadataHead");
991
- function appendOpenGraph(tags, openGraph, metadataBase) {
992
- if (!isRecord(openGraph)) return;
993
- appendMetaProperty(tags, "og:title", openGraph.title);
994
- appendMetaProperty(tags, "og:description", openGraph.description);
995
- appendMetaProperty(tags, "og:url", resolveMetadataUrl(openGraph.url, metadataBase));
996
- appendMetaProperty(tags, "og:site_name", openGraph.siteName);
997
- appendMetaProperty(tags, "og:type", openGraph.type ?? "website");
998
- appendMetaProperty(tags, "og:locale", openGraph.locale);
999
- const images = normalizeMetadataImages(
1000
- openGraph.images ?? openGraph.image,
1001
- metadataBase
1002
- );
1003
- for (const image of images) {
1004
- appendMetaProperty(tags, "og:image", image.url);
1005
- appendMetaProperty(tags, "og:image:width", image.width);
1006
- appendMetaProperty(tags, "og:image:height", image.height);
1007
- appendMetaProperty(tags, "og:image:alt", image.alt);
1008
- appendMetaProperty(tags, "og:image:type", image.type);
1009
- }
1010
- if (openGraph.type === "article") {
1011
- appendMetaProperty(tags, "article:published_time", normalizeDate(openGraph.publishedTime));
1012
- appendMetaProperty(tags, "article:modified_time", normalizeDate(openGraph.modifiedTime));
1013
- for (const author of normalizeArray(openGraph.authors)) {
1014
- appendMetaProperty(tags, "article:author", author);
1015
- }
1016
- appendMetaProperty(tags, "article:section", openGraph.section);
1017
- for (const tag of normalizeArray(openGraph.tags)) {
1018
- appendMetaProperty(tags, "article:tag", tag);
1019
- }
1020
- }
1021
- }
1022
- __name(appendOpenGraph, "appendOpenGraph");
1023
- function appendTwitter(tags, twitter, metadataBase) {
1024
- if (!isRecord(twitter)) return;
1025
- appendMetaName(tags, "twitter:card", twitter.card);
1026
- appendMetaName(tags, "twitter:site", twitter.site);
1027
- appendMetaName(tags, "twitter:creator", twitter.creator);
1028
- appendMetaName(tags, "twitter:title", twitter.title);
1029
- appendMetaName(tags, "twitter:description", twitter.description);
1030
- for (const image of normalizeMetadataImages(twitter.images, metadataBase)) {
1031
- appendMetaName(tags, "twitter:image", image.url);
1032
- appendMetaName(tags, "twitter:image:alt", image.alt);
1033
- }
1034
- }
1035
- __name(appendTwitter, "appendTwitter");
1036
- function appendNamedMetaRecord(tags, record) {
1037
- if (!isRecord(record)) return;
1038
- for (const [name, value] of Object.entries(record)) {
1039
- for (const content of normalizeArray(value)) {
1040
- appendMetaName(tags, name, content, true);
1041
- }
1042
- }
1043
- }
1044
- __name(appendNamedMetaRecord, "appendNamedMetaRecord");
1045
- function appendIcons(tags, icons, metadataBase) {
1046
- if (!icons) return false;
1047
- if (typeof icons === "string") {
1048
- const initialTagCount2 = tags.length;
1049
- appendLink(tags, "icon", resolveMetadataUrl(icons, metadataBase));
1050
- return tags.length > initialTagCount2;
1051
- }
1052
- if (!isRecord(icons)) return false;
1053
- const initialTagCount = tags.length;
1054
- appendIconList(tags, "icon", icons.icon, metadataBase);
1055
- appendIconList(tags, "shortcut icon", icons.shortcut, metadataBase);
1056
- const hasFavicon = tags.length > initialTagCount;
1057
- appendIconList(tags, "apple-touch-icon", icons.apple, metadataBase);
1058
- return hasFavicon;
1059
- }
1060
- __name(appendIcons, "appendIcons");
1061
- function appendIconList(tags, rel, value, metadataBase) {
1062
- for (const icon of normalizeArray(value)) {
1063
- if (typeof icon === "string") {
1064
- appendLink(tags, rel, resolveMetadataUrl(icon, metadataBase));
1065
- continue;
1066
- }
1067
- if (!isRecord(icon)) continue;
1068
- appendLink(tags, rel, resolveMetadataUrl(icon.url, metadataBase), {
1069
- sizes: icon.sizes,
1070
- type: icon.type
1071
- });
1072
- }
1073
- }
1074
- __name(appendIconList, "appendIconList");
1075
- function appendMetaName(tags, name, content, marked = false) {
1076
- const normalized = normalizeContent(content);
1077
- if (!normalized || !name) return;
1078
- const marker = marked ? ` ${FARM_METADATA_ATTRIBUTE}` : "";
1079
- tags.push(
1080
- `<meta name="${escapeAttribute(name)}" content="${escapeAttribute(normalized)}"${marker}>`
1081
- );
1082
- }
1083
- __name(appendMetaName, "appendMetaName");
1084
- function appendMetaProperty(tags, property, content) {
1085
- const normalized = normalizeContent(content);
1086
- if (!normalized) return;
1087
- tags.push(
1088
- `<meta property="${escapeAttribute(property)}" content="${escapeAttribute(normalized)}">`
1089
- );
1090
- }
1091
- __name(appendMetaProperty, "appendMetaProperty");
1092
- var VERIFICATION_META_NAMES = [
1093
- ["google", "google-site-verification"],
1094
- ["bing", "msvalidate.01"],
1095
- ["yandex", "yandex-verification"]
1096
- ];
1097
- function appendVerification(tags, verification) {
1098
- if (!isRecord(verification)) return;
1099
- for (const [key, name] of VERIFICATION_META_NAMES) {
1100
- for (const token of normalizeArray(verification[key])) {
1101
- appendMetaName(tags, name, token);
1102
- }
1103
- }
1104
- appendNamedMetaRecord(tags, verification.other);
1105
- }
1106
- __name(appendVerification, "appendVerification");
1107
- function appendLink(tags, rel, href, attrs = {}) {
1108
- const normalizedHref = normalizeContent(href);
1109
- if (!normalizedHref) return;
1110
- const attrText = Object.entries(attrs).map(([key, value]) => {
1111
- const normalized = normalizeContent(value);
1112
- return normalized ? ` ${key}="${escapeAttribute(normalized)}"` : "";
1113
- }).join("");
1114
- tags.push(
1115
- `<link rel="${escapeAttribute(rel)}" href="${escapeAttribute(normalizedHref)}"${attrText}>`
1116
- );
1117
- }
1118
- __name(appendLink, "appendLink");
1119
- function normalizeMetadataImages(value, metadataBase) {
1120
- return normalizeArray(value).map((item) => {
1121
- if (typeof item === "string") {
1122
- return { url: resolveMetadataUrl(item, metadataBase) || item };
1123
- }
1124
- if (!isRecord(item)) return null;
1125
- const rawUrl = item.url || item.src;
1126
- const url = resolveMetadataUrl(rawUrl, metadataBase);
1127
- if (!url) return null;
1128
- return {
1129
- url,
1130
- width: normalizeNumber(item.width),
1131
- height: normalizeNumber(item.height),
1132
- alt: typeof item.alt === "string" ? item.alt : void 0,
1133
- type: typeof item.type === "string" ? item.type : void 0
1134
- };
1135
- }).filter((item) => item !== null);
1136
- }
1137
- __name(normalizeMetadataImages, "normalizeMetadataImages");
1138
- function normalizeArray(value) {
1139
- if (value == null) return [];
1140
- return Array.isArray(value) ? value : [value];
1141
- }
1142
- __name(normalizeArray, "normalizeArray");
1143
- function resolveMetadataTitle(title) {
1144
- if (typeof title === "string") return title;
1145
- if (isRecord(title)) {
1146
- return normalizeContent(title.default);
1147
- }
1148
- return void 0;
1149
- }
1150
- __name(resolveMetadataTitle, "resolveMetadataTitle");
1151
- function normalizeKeywords(keywords) {
1152
- if (Array.isArray(keywords)) return keywords.filter(Boolean).join(", ");
1153
- return keywords;
1154
- }
1155
- __name(normalizeKeywords, "normalizeKeywords");
1156
- var ROBOTS_FLAGS = ["noarchive", "nosnippet", "noimageindex"];
1157
- var ROBOTS_VALUES = [
1158
- "max-snippet",
1159
- "max-image-preview",
1160
- "max-video-preview",
1161
- "unavailable_after"
1162
- ];
1163
- function normalizeRobots(robots) {
1164
- if (typeof robots === "string") return robots;
1165
- if (!isRecord(robots)) return void 0;
1166
- const values = [];
1167
- if (typeof robots.index === "boolean") values.push(robots.index ? "index" : "noindex");
1168
- if (typeof robots.follow === "boolean") values.push(robots.follow ? "follow" : "nofollow");
1169
- for (const flag of ROBOTS_FLAGS) {
1170
- if (robots[flag] === true) values.push(flag);
1171
- }
1172
- for (const directive of ROBOTS_VALUES) {
1173
- const value = normalizeContent(robots[directive]);
1174
- if (value) values.push(`${directive}:${value}`);
1175
- }
1176
- return values.join(", ") || void 0;
1177
- }
1178
- __name(normalizeRobots, "normalizeRobots");
1179
- function resolveMetadataBase(metadata) {
1180
- const base = metadata.metadataBase;
1181
- if (!base) return void 0;
1182
- return String(base);
1183
- }
1184
- __name(resolveMetadataBase, "resolveMetadataBase");
1185
- function sanitizeSelfCanonicalPathname(pathname) {
1186
- if (typeof pathname !== "string" || pathname.length === 0) return "/";
1187
- const collapsed = pathname.replace(/^[/\\]+/, "/");
1188
- return collapsed.startsWith("/") ? collapsed : `/${collapsed}`;
1189
- }
1190
- __name(sanitizeSelfCanonicalPathname, "sanitizeSelfCanonicalPathname");
1191
- function resolveMetadataUrl(value, metadataBase) {
1192
- const normalized = normalizeContent(value);
1193
- if (!normalized) return void 0;
1194
- if (!metadataBase) return normalized;
1195
- try {
1196
- return new URL(normalized, metadataBase).toString();
1197
- } catch {
1198
- return normalized;
1199
- }
1200
- }
1201
- __name(resolveMetadataUrl, "resolveMetadataUrl");
1202
- function normalizeNumber(value) {
1203
- if (typeof value === "number" && Number.isFinite(value)) return value;
1204
- if (typeof value === "string") {
1205
- const parsed = Number(value);
1206
- return Number.isFinite(parsed) ? parsed : void 0;
1207
- }
1208
- return void 0;
1209
- }
1210
- __name(normalizeNumber, "normalizeNumber");
1211
- function normalizeDate(value) {
1212
- if (value instanceof Date) {
1213
- return Number.isNaN(value.getTime()) ? void 0 : value.toISOString();
1214
- }
1215
- return normalizeContent(value);
1216
- }
1217
- __name(normalizeDate, "normalizeDate");
1218
- function normalizeContent(value) {
1219
- if (value == null) return void 0;
1220
- if (typeof value === "string") return value;
1221
- if (typeof value === "number" || typeof value === "boolean") return String(value);
1222
- if (value instanceof URL) return value.toString();
1223
- return void 0;
1224
- }
1225
- __name(normalizeContent, "normalizeContent");
1226
- function isRecord(value) {
1227
- return !!value && typeof value === "object" && !Array.isArray(value);
1228
- }
1229
- __name(isRecord, "isRecord");
1230
- function escapeText(value) {
1231
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1232
- }
1233
- __name(escapeText, "escapeText");
1234
- function escapeAttribute(value) {
1235
- return escapeText(value).replace(/"/g, "&quot;");
1236
- }
1237
- __name(escapeAttribute, "escapeAttribute");
1238
-
1239
- // src/client/metadata-reconciler.ts
1240
- var MANAGED_ATTRIBUTE = FARM_METADATA_ATTRIBUTE;
1241
- var OWNED_SELECTORS = [
1242
- 'meta[name="description"]',
1243
- 'meta[name="keywords"]',
1244
- 'meta[name="author"]',
1245
- 'meta[name="google-site-verification"]',
1246
- 'meta[name="msvalidate.01"]',
1247
- 'meta[name="yandex-verification"]',
1248
- 'meta[name="creator"]',
1249
- 'meta[name="publisher"]',
1250
- 'meta[name="robots"]',
1251
- 'meta[name="googlebot"]',
1252
- 'link[rel="author"]',
1253
- 'link[rel="canonical"]',
1254
- 'link[rel="alternate"]',
1255
- 'meta[property^="og:"]',
1256
- 'meta[property^="article:"]',
1257
- 'meta[name^="twitter:"]',
1258
- // Meta tags named by the app carry the marker, since no fixed name matches them.
1259
- `meta[${MANAGED_ATTRIBUTE}]`
1260
- ].join(", ");
1261
- var ICON_SELECTORS = [
1262
- 'link[rel="icon"]',
1263
- 'link[rel="shortcut icon"]',
1264
- 'link[rel="apple-touch-icon"]'
1265
- ].join(", ");
1266
- var MANIFEST_SELECTOR = 'link[rel="manifest"]';
1267
- var PAGE_JSON_LD_SELECTOR = `script[type="application/ld+json"][${MANAGED_ATTRIBUTE}]`;
1268
- function removeAll(selector) {
1269
- for (const element of Array.from(document.head.querySelectorAll(selector))) {
1270
- element.remove();
1271
- }
1272
- }
1273
- __name(removeAll, "removeAll");
1274
- function applyFarmMetadataToDocument(metadata, pathname) {
1275
- document.title = resolveMetadataTitle(metadata?.title) || "Farm.js App";
1276
- const rendered = renderMetadataHead(metadata, { pathname });
1277
- const template = document.createElement("template");
1278
- template.innerHTML = rendered.tags;
1279
- removeAll(OWNED_SELECTORS);
1280
- removeAll(PAGE_JSON_LD_SELECTOR);
1281
- if (metadata?.icons) removeAll(ICON_SELECTORS);
1282
- if (metadata?.manifest) removeAll(MANIFEST_SELECTOR);
1283
- for (const element of Array.from(template.content.children)) {
1284
- element.setAttribute(MANAGED_ATTRIBUTE, "");
1285
- document.head.appendChild(element);
1286
- }
1287
- }
1288
- __name(applyFarmMetadataToDocument, "applyFarmMetadataToDocument");
1289
-
1290
- // src/i18n/bridge.ts
1291
- var FARM_I18N_SNAPSHOT_RESOLVER = /* @__PURE__ */ Symbol.for("farm.i18n.snapshotResolver");
1292
- function getActiveFarmI18nSnapshot() {
1293
- if (typeof window !== "undefined" && window.__FARM_I18N__) {
1294
- return window.__FARM_I18N__;
1295
- }
1296
- return globalThis[FARM_I18N_SNAPSHOT_RESOLVER]?.();
1297
- }
1298
- __name(getActiveFarmI18nSnapshot, "getActiveFarmI18nSnapshot");
1299
-
1300
- // src/base-path.ts
1301
- var FARM_BASE_PATH = /* @__PURE__ */ Symbol.for("farm.basePath");
1302
- function getFarmGlobalState() {
1303
- return globalThis;
1304
- }
1305
- __name(getFarmGlobalState, "getFarmGlobalState");
1306
- function getFarmBasePath() {
1307
- return getFarmGlobalState()[FARM_BASE_PATH] ?? "";
1308
- }
1309
- __name(getFarmBasePath, "getFarmBasePath");
1310
- function applyFarmBasePath(href, basePath = getFarmBasePath()) {
1311
- const normalizedBasePath = normalizeFarmBasePath(basePath);
1312
- if (!normalizedBasePath || !href.startsWith("/") || href.startsWith("//")) return href;
1313
- const canonicalHref = canonicalizeAppRelativeHref(href);
1314
- if (canonicalHref === normalizedBasePath || canonicalHref.startsWith(`${normalizedBasePath}/`) || canonicalHref.startsWith(`${normalizedBasePath}?`) || canonicalHref.startsWith(`${normalizedBasePath}#`)) {
1315
- return canonicalHref;
1316
- }
1317
- return `${normalizedBasePath}${canonicalHref}`;
1318
- }
1319
- __name(applyFarmBasePath, "applyFarmBasePath");
1320
- function canonicalizeAppRelativeHref(href) {
1321
- const origin = "http://farm.local";
1322
- const resolved = new URL(href, origin);
1323
- if (resolved.origin !== origin) {
1324
- throw new Error("Farm app-relative href cannot change the URL origin.");
1325
- }
1326
- return `${resolved.pathname}${resolved.search}${resolved.hash}`;
1327
- }
1328
- __name(canonicalizeAppRelativeHref, "canonicalizeAppRelativeHref");
1329
- function stripFarmBasePath(pathname, basePath = getFarmBasePath()) {
1330
- const normalizedBasePath = normalizeFarmBasePath(basePath);
1331
- if (!normalizedBasePath) return pathname || "/";
1332
- if (pathname === normalizedBasePath) return "/";
1333
- if (!pathname.startsWith(`${normalizedBasePath}/`)) return pathname || "/";
1334
- return pathname.slice(normalizedBasePath.length) || "/";
1335
- }
1336
- __name(stripFarmBasePath, "stripFarmBasePath");
1337
- function normalizeFarmBasePath(basePath) {
1338
- if (!basePath || basePath === "/") return "";
1339
- const hasUnstableCharacters = /* @__PURE__ */ __name((candidate) => candidate.includes("\\") || Array.from(candidate).some((character) => {
1340
- const code = character.charCodeAt(0);
1341
- return code <= 31 || code >= 127 && code <= 159;
1342
- }), "hasUnstableCharacters");
1343
- if (hasUnstableCharacters(basePath)) {
1344
- throw new Error("Farm basePath cannot contain backslashes or control characters.");
1345
- }
1346
- const pathname = basePath.trim();
1347
- if (!pathname || pathname === "/") return "";
1348
- if (pathname.includes("?") || pathname.includes("#")) {
1349
- throw new Error("Farm basePath cannot contain a query string or hash.");
1350
- }
1351
- if (pathname.startsWith("//") || /^[a-z][a-z\d+.-]*:\/\//i.test(pathname)) {
1352
- throw new Error('Farm basePath must be a pathname such as "/docs", not a URL.');
1353
- }
1354
- for (const segment of pathname.split("/")) {
1355
- let decoded = segment;
1356
- try {
1357
- decoded = decodeURIComponent(segment);
1358
- } catch {
1359
- }
1360
- if (hasUnstableCharacters(decoded)) {
1361
- throw new Error("Farm basePath cannot contain backslashes or control characters.");
1362
- }
1363
- if (decoded.includes("/")) {
1364
- throw new Error("Farm basePath cannot contain percent-encoded path separators.");
1365
- }
1366
- if (decoded === "." || decoded === "..") {
1367
- throw new Error('Farm basePath cannot contain "." or ".." path segments.');
1368
- }
1369
- }
1370
- return `/${pathname}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
1371
- }
1372
- __name(normalizeFarmBasePath, "normalizeFarmBasePath");
1373
-
1374
- // src/i18n/routing.ts
1375
- function resolveFarmLocalePath(pathname, config) {
1376
- const normalized = normalizePathname2(stripFarmBasePath(pathname, config.basePath));
1377
- if (config.routing === "none") {
1378
- return { pathname: normalized, explicit: false };
1379
- }
1380
- const segments = normalized.split("/").filter(Boolean);
1381
- const firstSegment = segments[0];
1382
- const locale = config.locales.find(
1383
- (candidate) => candidate.toLowerCase() === firstSegment?.toLowerCase()
1384
- );
1385
- if (!locale) {
1386
- return { pathname: normalized, explicit: false };
1387
- }
1388
- const remaining = segments.slice(1);
1389
- return {
1390
- locale,
1391
- pathname: remaining.length > 0 ? `/${remaining.join("/")}` : "/",
1392
- explicit: true
1393
- };
1394
- }
1395
- __name(resolveFarmLocalePath, "resolveFarmLocalePath");
1396
- function stripFarmLocaleFromPathname(pathname, config) {
1397
- return resolveFarmLocalePath(pathname, config).pathname;
1398
- }
1399
- __name(stripFarmLocaleFromPathname, "stripFarmLocaleFromPathname");
1400
- function localizeFarmPathname(pathname, locale, config) {
1401
- const internalPathname = resolveFarmLocalePath(pathname, config).pathname;
1402
- let localizedPathname = internalPathname;
1403
- if (config.routing === "none") {
1404
- return applyFarmBasePath(localizedPathname, config.basePath);
1405
- }
1406
- if (config.routing === "prefix-except-default" && locale === config.defaultLocale) {
1407
- return applyFarmBasePath(localizedPathname, config.basePath);
1408
- }
1409
- localizedPathname = internalPathname === "/" ? `/${locale}` : `/${locale}${internalPathname}`;
1410
- return applyFarmBasePath(localizedPathname, config.basePath);
1411
- }
1412
- __name(localizeFarmPathname, "localizeFarmPathname");
1413
- function localizeFarmHref(href, locale, config) {
1414
- if (!href.startsWith("/") || href.startsWith("//")) return href;
1415
- const url = new URL(href, "http://farm.local");
1416
- url.pathname = localizeFarmPathname(url.pathname, locale, config);
1417
- return `${url.pathname}${url.search}${url.hash}`;
1418
- }
1419
- __name(localizeFarmHref, "localizeFarmHref");
1420
- function normalizePathname2(pathname) {
1421
- const withLeadingSlash = pathname.startsWith("/") ? pathname : `/${pathname}`;
1422
- if (withLeadingSlash === "/") return "/";
1423
- return withLeadingSlash.replace(/\/{2,}/g, "/").replace(/\/$/, "") || "/";
1424
- }
1425
- __name(normalizePathname2, "normalizePathname");
1426
-
1427
- // src/i18n/client-state.ts
1428
- var listeners = /* @__PURE__ */ new Set();
1429
- var compiledFarmI18nMessages = /* @__PURE__ */ new Map();
1430
- var currentSnapshot;
1431
- function getFarmI18nClientState() {
1432
- return currentSnapshot || getActiveFarmI18nSnapshot();
1433
- }
1434
- __name(getFarmI18nClientState, "getFarmI18nClientState");
1435
- function subscribeFarmI18n(listener) {
1436
- listeners.add(listener);
1437
- return () => listeners.delete(listener);
1438
- }
1439
- __name(subscribeFarmI18n, "subscribeFarmI18n");
1440
- function _hydrateFarmI18n(snapshot) {
1441
- if (!snapshot) return;
1442
- const changed = currentSnapshot?.locale !== snapshot.locale;
1443
- currentSnapshot = snapshot;
1444
- if (typeof window !== "undefined") window.__FARM_I18N__ = snapshot;
1445
- if (typeof document !== "undefined") {
1446
- document.documentElement.lang = snapshot.locale;
1447
- document.documentElement.dir = snapshot.direction;
1448
- }
1449
- if (changed) compiledFarmI18nMessages.clear();
1450
- for (const listener of listeners) listener();
1451
- }
1452
- __name(_hydrateFarmI18n, "_hydrateFarmI18n");
1453
- function isFarmLocaleChangeHref(href) {
1454
- const snapshot = getFarmI18nClientState();
1455
- if (!snapshot || typeof window === "undefined") return false;
1456
- if (snapshot.routing === "none") return false;
1457
- const target = resolveFarmNavigationURL(href, window.location.href);
1458
- const match = resolveFarmLocalePath(target.pathname, snapshot);
1459
- const targetLocale = match.locale || snapshot.defaultLocale;
1460
- return targetLocale !== snapshot.locale;
1461
- }
1462
- __name(isFarmLocaleChangeHref, "isFarmLocaleChangeHref");
1463
-
1464
- // src/client/spa-router.ts
1465
- var MAX_CONCURRENT_VIEWPORT_PREFETCHES = 4;
1466
- var FARM_PAGE_STATE_KEY = "__farmPageState";
1467
- var FARM_INTERCEPT_FROM_KEY = "__farmInterceptFrom";
1468
- var FARM_HISTORY_INDEX_KEY = "__farmHistoryIndex";
1469
- function readHistoryIndex(state) {
1470
- if (!state || typeof state !== "object") return null;
1471
- const value = state[FARM_HISTORY_INDEX_KEY];
1472
- return typeof value === "number" && Number.isFinite(value) ? value : null;
1473
- }
1474
- __name(readHistoryIndex, "readHistoryIndex");
1475
- var IDLE_NAVIGATION_STATE = {
1476
- state: "idle",
1477
- pending: false,
1478
- from: null,
1479
- to: null,
1480
- action: null,
1481
- startedAt: null
1482
- };
1483
- function getActiveLayoutChainHeader() {
1484
- if (typeof document === "undefined") return void 0;
1485
- const patterns = Array.from(
1486
- document.querySelectorAll('[data-farm-layout-boundary="true"]')
1487
- ).map((element) => element.dataset.farmLayoutPattern).filter((pattern) => Boolean(pattern));
1488
- return patterns.length > 0 ? JSON.stringify(patterns) : void 0;
1489
- }
1490
- __name(getActiveLayoutChainHeader, "getActiveLayoutChainHeader");
1491
- var routerInstance = null;
1492
- var _SPARouter = class _SPARouter {
1493
- constructor(options = {}) {
1494
- this.cache = /* @__PURE__ */ new Map();
1495
- this.prefetchingUrls = /* @__PURE__ */ new Set();
1496
- this.pendingPrefetches = /* @__PURE__ */ new Map();
1497
- this.cacheGeneration = 0;
1498
- this.observedPrefetchLinks = /* @__PURE__ */ new Map();
1499
- this.prefetchTimers = /* @__PURE__ */ new Map();
1500
- this.viewportPrefetchQueue = [];
1501
- this.viewportPrefetchTasksByHref = /* @__PURE__ */ new Map();
1502
- this.viewportPrefetchTasksByElement = /* @__PURE__ */ new Map();
1503
- this.activeViewportPrefetches = 0;
1504
- this.destroyed = false;
1505
- this.blockers = /* @__PURE__ */ new Set();
1506
- this.unloadBlockers = /* @__PURE__ */ new Map();
1507
- this.navigationListeners = /* @__PURE__ */ new Set();
1508
- this.navigationState = IDLE_NAVIGATION_STATE;
1509
- this.currentHistoryPath = null;
1510
- this.currentHistoryHash = "";
1511
- this.currentHistoryIndex = null;
1512
- this.suppressNextPopState = false;
1513
- this.navigationSequence = 0;
1514
- this.scrollElements = /* @__PURE__ */ new Map();
1515
- this.onPopState = /* @__PURE__ */ __name((event) => {
1516
- void this.handlePopState(event);
1517
- }, "onPopState");
1518
- this.onBeforeUnload = /* @__PURE__ */ __name((event) => {
1519
- if (this.shouldBlockUnload()) {
1520
- event.preventDefault();
1521
- event.returnValue = "";
1522
- }
1523
- this.saveScrollPosition(window.location.pathname + window.location.search);
1524
- }, "onBeforeUnload");
1525
- this.options = {
1526
- prefetchTimeout: options.prefetchTimeout ?? 100,
1527
- cacheMaxAge: options.cacheMaxAge ?? 3e4,
1528
- // 30 seconds
1529
- scrollRestoration: options.scrollRestoration ?? true,
1530
- shouldUseDocumentNavigation: options.shouldUseDocumentNavigation ?? (() => false),
1531
- deploymentId: options.deploymentId ?? readBrowserDeploymentId()
1532
- };
1533
- if (typeof window !== "undefined") {
1534
- window.addEventListener("popstate", this.onPopState);
1535
- window.addEventListener("beforeunload", this.onBeforeUnload);
1536
- this.currentHistoryPath = window.location.pathname + window.location.search;
1537
- this.currentHistoryHash = window.location.hash;
1538
- this.currentInterceptFrom = window.history.state?.[FARM_INTERCEPT_FROM_KEY];
1539
- const existingIndex = readHistoryIndex(window.history.state);
1540
- if (existingIndex == null) {
1541
- try {
1542
- window.history.replaceState(
1543
- {
1544
- ...window.history.state ?? {},
1545
- [FARM_HISTORY_INDEX_KEY]: 0
1546
- },
1547
- "",
1548
- window.location.href
1549
- );
1550
- this.currentHistoryIndex = 0;
1551
- } catch {
1552
- this.currentHistoryIndex = null;
1553
- }
1554
- } else {
1555
- this.currentHistoryIndex = existingIndex;
1556
- }
1557
- }
1558
- }
1559
- /** Remove global listeners. Intended for tests and teardown. */
1560
- destroy() {
1561
- if (typeof window === "undefined") return;
1562
- this.destroyed = true;
1563
- this.cancelActiveNavigation();
1564
- this.clearCache();
1565
- this.prefetchObserver?.disconnect();
1566
- this.prefetchObserver = void 0;
1567
- for (const timer of this.prefetchTimers.values()) clearTimeout(timer);
1568
- this.observedPrefetchLinks.clear();
1569
- this.prefetchTimers.clear();
1570
- for (const task of this.viewportPrefetchQueue) task.cancelled = true;
1571
- this.viewportPrefetchQueue.length = 0;
1572
- this.viewportPrefetchTasksByHref.clear();
1573
- this.viewportPrefetchTasksByElement.clear();
1574
- window.removeEventListener("popstate", this.onPopState);
1575
- window.removeEventListener("beforeunload", this.onBeforeUnload);
1576
- }
1577
- /**
1578
- * Set the navigation handler that updates React
1579
- */
1580
- setNavigationHandler(handler) {
1581
- this.onNavigate = handler;
1582
- }
1583
- /**
1584
- * Connect Farm's browser plugin lifecycle to SPA navigation.
1585
- */
1586
- setClientPluginManager(manager) {
1587
- this.clientPlugins = manager;
1588
- }
1589
- /**
1590
- * Navigate to a new URL
1591
- */
1592
- async navigate(href, options = {}) {
1593
- const {
1594
- replace = false,
1595
- scroll = true,
1596
- state,
1597
- viewTransition = false,
1598
- refresh = false
1599
- } = options;
1600
- const url = resolveFarmNavigationURL(href, window.location.href);
1601
- const pathname = url.pathname;
1602
- const search = url.search;
1603
- const fullPath = pathname + search;
1604
- if (isFarmExternalNavigationURL(url, window.location.origin) || isFarmLocaleChangeHref(url.toString()) || this.options.shouldUseDocumentNavigation(pathname)) {
1605
- this.cancelActiveNavigation();
1606
- if (replace) window.location.replace(url.toString());
1607
- else window.location.assign(url.toString());
1608
- return;
1609
- }
1610
- if (!refresh && pathname === window.location.pathname && search === window.location.search) {
1611
- this.cancelActiveNavigation();
1612
- if (url.hash === window.location.hash) return;
1613
- this.writePageState(
1614
- replace ? "replace" : "push",
1615
- state === void 0 ? readPageState() : state,
1616
- url.toString()
1617
- );
1618
- if (scroll) {
1619
- if (url.hash) {
1620
- getHashTargetElement(url.hash)?.scrollIntoView();
1621
- } else {
1622
- window.scrollTo(0, 0);
1623
- }
1624
- }
1625
- return;
1626
- }
1627
- const from = window.location.pathname + window.location.search;
1628
- if (await this.shouldBlockNavigation({
1629
- from,
1630
- to: fullPath,
1631
- action: replace ? "replace" : "push"
1632
- })) {
1633
- return;
1634
- }
1635
- if (this.options.scrollRestoration) {
1636
- this.saveScrollPosition(window.location.pathname + window.location.search);
1637
- }
1638
- const navigation = this.startNavigation({
1639
- from,
1640
- to: createNavigationLocation(url),
1641
- action: replace ? "replace" : "push"
1642
- });
1643
- let clientNavigation;
1644
- try {
1645
- clientNavigation = await this.clientPlugins?.beginNavigation({
1646
- from,
1647
- to: url,
1648
- action: replace ? "replace" : "push"
1649
- });
1650
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
1651
- const pageData = await this.fetchPageData(
1652
- fullPath,
1653
- true,
1654
- from,
1655
- refresh,
1656
- navigation.controller.signal
1657
- );
1658
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
1659
- if (clientNavigation) {
1660
- await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);
1661
- }
1662
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
1663
- await this.runViewTransition(
1664
- viewTransition,
1665
- () => this.isCurrentNavigation(navigation, clientNavigation) ? this.commitNavigation({
1666
- fullPath,
1667
- pageData,
1668
- pathname,
1669
- replace,
1670
- scroll,
1671
- state,
1672
- url
1673
- }) : Promise.resolve()
1674
- );
1675
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
1676
- if (clientNavigation) {
1677
- await this.clientPlugins?.resolveNavigation(clientNavigation);
1678
- void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);
1679
- }
1680
- this.finishNavigation(navigation);
1681
- } catch (error) {
1682
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
1683
- if (clientNavigation) {
1684
- await this.clientPlugins?.failNavigation(clientNavigation, error);
1685
- }
1686
- this.finishNavigation(navigation);
1687
- console.error("[Farm.js] Navigation error:", error);
1688
- window.location.href = href;
1689
- }
1690
- }
1691
- /**
1692
- * Re-render the active route from the server while preserving the document,
1693
- * shared layouts, client runtime, and browser history entry.
1694
- */
1695
- refresh(options = {}) {
1696
- return this.navigate(window.location.href, {
1697
- ...options,
1698
- replace: true,
1699
- refresh: true,
1700
- scroll: options.scroll ?? false
1701
- });
1702
- }
1703
- /**
1704
- * Prefetch a URL
1705
- */
1706
- async prefetch(href) {
1707
- if (this.destroyed) return;
1708
- if (isFarmLocaleChangeHref(href)) return;
1709
- const url = resolveFarmNavigationURL(href, window.location.href);
1710
- if (isFarmExternalNavigationURL(url, window.location.origin)) return;
1711
- if (this.options.shouldUseDocumentNavigation(url.pathname)) return;
1712
- const fullPath = url.pathname + url.search;
1713
- const interceptFrom = window.location.pathname + window.location.search;
1714
- if (this.prefetchingUrls.has(fullPath)) return;
1715
- if (this.isCached(fullPath, interceptFrom)) return;
1716
- this.prefetchingUrls.add(fullPath);
1717
- try {
1718
- await this.fetchPageData(fullPath, false, interceptFrom);
1719
- } catch (error) {
1720
- console.warn("[Farm.js] Prefetch failed:", href, error);
1721
- } finally {
1722
- this.prefetchingUrls.delete(fullPath);
1723
- }
1724
- }
1725
- /**
1726
- * Observe an element for viewport intersection (prefetch when visible)
1727
- */
1728
- observeForPrefetch(element) {
1729
- if (this.destroyed || typeof IntersectionObserver === "undefined") return;
1730
- const href = element.getAttribute("href");
1731
- if (!href || this.isExternalUrl(href)) return;
1732
- this.unobserveForPrefetch(element);
1733
- const observer = this.getPrefetchObserver();
1734
- this.observedPrefetchLinks.set(element, href);
1735
- observer.observe(element);
1736
- }
1737
- /**
1738
- * Stop observing an element
1739
- */
1740
- unobserveForPrefetch(element) {
1741
- if (this.observedPrefetchLinks.delete(element)) {
1742
- this.prefetchObserver?.unobserve(element);
1743
- }
1744
- const timer = this.prefetchTimers.get(element);
1745
- if (timer !== void 0) {
1746
- clearTimeout(timer);
1747
- this.prefetchTimers.delete(element);
1748
- }
1749
- this.cancelQueuedViewportPrefetch(element);
1750
- }
1751
- getPrefetchObserver() {
1752
- this.prefetchObserver ?? (this.prefetchObserver = new IntersectionObserver(
1753
- (entries) => {
1754
- for (const entry of entries) {
1755
- if (!entry.isIntersecting) continue;
1756
- const element = entry.target;
1757
- const href = this.observedPrefetchLinks.get(element);
1758
- if (!href) continue;
1759
- this.prefetchObserver?.unobserve(element);
1760
- this.observedPrefetchLinks.delete(element);
1761
- const timer = setTimeout(() => {
1762
- if (this.prefetchTimers.get(element) !== timer) return;
1763
- this.prefetchTimers.delete(element);
1764
- this.enqueueViewportPrefetch(element, href);
1765
- }, this.options.prefetchTimeout);
1766
- this.prefetchTimers.set(element, timer);
1767
- }
1768
- },
1769
- { rootMargin: "200px" }
1770
- ));
1771
- return this.prefetchObserver;
1772
- }
1773
- enqueueViewportPrefetch(element, href) {
1774
- if (this.destroyed) return;
1775
- let task = this.viewportPrefetchTasksByHref.get(href);
1776
- if (!task) {
1777
- task = { href, elements: /* @__PURE__ */ new Set(), cancelled: false, started: false };
1778
- this.viewportPrefetchTasksByHref.set(href, task);
1779
- this.viewportPrefetchQueue.push(task);
1780
- }
1781
- task.elements.add(element);
1782
- this.viewportPrefetchTasksByElement.set(element, task);
1783
- this.drainViewportPrefetchQueue();
1784
- }
1785
- cancelQueuedViewportPrefetch(element) {
1786
- const task = this.viewportPrefetchTasksByElement.get(element);
1787
- if (!task) return;
1788
- this.viewportPrefetchTasksByElement.delete(element);
1789
- task.elements.delete(element);
1790
- if (task.elements.size > 0) return;
1791
- if (task.started) return;
1792
- task.cancelled = true;
1793
- if (this.viewportPrefetchTasksByHref.get(task.href) === task) {
1794
- this.viewportPrefetchTasksByHref.delete(task.href);
1795
- }
1796
- }
1797
- drainViewportPrefetchQueue() {
1798
- while (!this.destroyed && this.activeViewportPrefetches < MAX_CONCURRENT_VIEWPORT_PREFETCHES && this.viewportPrefetchQueue.length > 0) {
1799
- const task = this.viewportPrefetchQueue.shift();
1800
- if (task.cancelled || task.elements.size === 0) {
1801
- if (this.viewportPrefetchTasksByHref.get(task.href) === task) {
1802
- this.viewportPrefetchTasksByHref.delete(task.href);
1803
- }
1804
- continue;
1805
- }
1806
- task.started = true;
1807
- this.activeViewportPrefetches += 1;
1808
- let prefetchResult;
1809
- try {
1810
- prefetchResult = this.prefetch(task.href);
1811
- } catch {
1812
- prefetchResult = void 0;
1813
- }
1814
- void Promise.resolve(prefetchResult).catch(() => void 0).finally(() => {
1815
- if (this.viewportPrefetchTasksByHref.get(task.href) === task) {
1816
- this.viewportPrefetchTasksByHref.delete(task.href);
1817
- }
1818
- for (const element of task.elements) {
1819
- if (this.viewportPrefetchTasksByElement.get(element) === task) {
1820
- this.viewportPrefetchTasksByElement.delete(element);
1821
- }
1822
- }
1823
- this.activeViewportPrefetches -= 1;
1824
- this.drainViewportPrefetchQueue();
1825
- });
1826
- }
1827
- }
1828
- addBlocker(blocker, shouldBlockUnload) {
1829
- this.blockers.add(blocker);
1830
- this.unloadBlockers.set(
1831
- blocker,
1832
- shouldBlockUnload ?? (() => this.evaluateBlockerForUnload(blocker))
1833
- );
1834
- return () => {
1835
- this.blockers.delete(blocker);
1836
- this.unloadBlockers.delete(blocker);
1837
- };
1838
- }
1839
- getNavigationState() {
1840
- return this.navigationState;
1841
- }
1842
- subscribeNavigation(listener) {
1843
- this.navigationListeners.add(listener);
1844
- listener(this.navigationState);
1845
- return () => {
1846
- this.navigationListeners.delete(listener);
1847
- };
1848
- }
1849
- registerScrollElement(key, element) {
1850
- this.scrollElements.set(key, element);
1851
- this.restoreScrollElement(window.location.pathname + window.location.search, key, element);
1852
- return () => {
1853
- if (this.scrollElements.get(key) === element) {
1854
- this.scrollElements.delete(key);
1855
- }
1856
- };
1857
- }
1858
- pushState(state, href) {
1859
- this.writePageState("push", state, href);
1860
- }
1861
- replaceState(state, href) {
1862
- this.writePageState("replace", state, href);
1863
- }
1864
- /** @internal Keep shallow URL-search writes inside the router's history bookkeeping. */
1865
- writeURLSearch(action, href) {
1866
- this.writePageState(action, readPageState(), href, false);
1867
- }
1868
- async commitNavigation(options) {
1869
- const historyUrl = resolveFarmNavigationURL(
1870
- options.pageData.canonicalPath || options.fullPath,
1871
- window.location.href
1872
- );
1873
- historyUrl.hash = options.url.hash;
1874
- const historyPath = historyUrl.pathname + historyUrl.search + historyUrl.hash;
1875
- const historyState = createHistoryState(
1876
- historyPath,
1877
- options.state,
1878
- options.replace ? window.history.state : void 0,
1879
- options.pageData.interception?.from ?? null
1880
- );
1881
- const nextHistoryIndex = this.currentHistoryIndex == null ? null : options.replace ? this.currentHistoryIndex : this.currentHistoryIndex + 1;
1882
- if (nextHistoryIndex != null) {
1883
- historyState[FARM_HISTORY_INDEX_KEY] = nextHistoryIndex;
1884
- }
1885
- if (options.replace) {
1886
- window.history.replaceState(historyState, "", historyPath);
1887
- } else {
1888
- window.history.pushState(historyState, "", historyPath);
1889
- }
1890
- this.currentHistoryIndex = nextHistoryIndex;
1891
- const resolvedHistoryUrl = resolveFarmNavigationURL(historyPath, window.location.href);
1892
- this.currentHistoryPath = resolvedHistoryUrl.pathname + resolvedHistoryUrl.search;
1893
- this.currentHistoryHash = resolvedHistoryUrl.hash;
1894
- this.currentInterceptFrom = historyState[FARM_INTERCEPT_FROM_KEY];
1895
- notifyRouterHistoryChange();
1896
- this.updateDocumentMetadata(options.pageData.metadata);
1897
- _hydrateFarmI18n(options.pageData.i18n);
1898
- if (this.onNavigate) {
1899
- await this.onNavigate(options.pageData);
1900
- }
1901
- if (options.scroll) {
1902
- if (options.url.hash) {
1903
- const element = getHashTargetElement(options.url.hash);
1904
- if (element) {
1905
- element.scrollIntoView();
1906
- }
1907
- } else {
1908
- window.scrollTo(0, 0);
1909
- }
1910
- } else if (this.options.scrollRestoration) {
1911
- const restorePath = this.currentHistoryPath ?? options.fullPath;
1912
- this.restoreWindowScroll(restorePath);
1913
- this.restoreScrollElements(restorePath);
1914
- }
1915
- }
1916
- async runViewTransition(mode, callback) {
1917
- if (!mode || typeof document === "undefined") {
1918
- await callback();
1919
- return;
1920
- }
1921
- const startViewTransition = document.startViewTransition;
1922
- if (typeof startViewTransition !== "function") {
1923
- await callback();
1924
- return;
1925
- }
1926
- const transition = startViewTransition.call(document, () => callback());
1927
- const updateDone = transition?.updateCallbackDone || transition?.ready;
1928
- if (updateDone && typeof updateDone.then === "function") {
1929
- await updateDone;
1930
- }
1931
- transition?.finished?.catch?.(() => void 0);
1932
- }
1933
- /**
1934
- * Fetch page data from cache or server
1935
- */
1936
- async fetchPageData(path, recover = true, interceptFrom, fresh = false, signal) {
1937
- const cacheKey = getPageDataCacheKey(path, interceptFrom);
1938
- const cached = fresh ? void 0 : this.cache.get(cacheKey);
1939
- if (cached && Date.now() - cached.timestamp < this.options.cacheMaxAge) {
1940
- return cached.data;
1941
- }
1942
- const activeLayoutChain = getActiveLayoutChainHeader();
1943
- const prefetchKey = JSON.stringify([path, interceptFrom, activeLayoutChain]);
1944
- let generation = this.cacheGeneration;
1945
- const pending = this.pendingPrefetches.get(prefetchKey);
1946
- if (pending && recover) {
1947
- if (fresh) {
1948
- pending.cacheable = false;
1949
- pending.resolve(void 0);
1950
- this.pendingPrefetches.delete(prefetchKey);
1951
- } else {
1952
- const cancellation = createClientCancellation(signal);
1953
- try {
1954
- const data = await cancellation.run(() => pending.data);
1955
- cancellation.check();
1956
- if (data && pending.cacheable && generation === this.cacheGeneration) return data;
1957
- } finally {
1958
- cancellation.dispose();
1959
- }
1960
- }
1961
- }
1962
- generation = this.cacheGeneration;
1963
- let prefetch;
1964
- if (!recover) {
1965
- let resolve;
1966
- const data = new Promise((done) => {
1967
- resolve = done;
1968
- });
1969
- prefetch = { data, resolve, cacheable: true };
1970
- this.pendingPrefetches.set(prefetchKey, prefetch);
1971
- }
1972
- const cacheData = /* @__PURE__ */ __name((data) => {
1973
- if (!this.destroyed && generation === this.cacheGeneration && prefetch?.cacheable !== false) {
1974
- this.cachePageData(cacheKey, data);
1975
- }
1976
- }, "cacheData");
1977
- try {
1978
- return await this.requestPageData(
1979
- path,
1980
- recover,
1981
- interceptFrom,
1982
- activeLayoutChain,
1983
- signal,
1984
- cacheData,
1985
- prefetch?.resolve
1986
- );
1987
- } finally {
1988
- prefetch?.resolve(void 0);
1989
- if (prefetch && this.pendingPrefetches.get(prefetchKey) === prefetch) {
1990
- this.pendingPrefetches.delete(prefetchKey);
1991
- }
1992
- }
1993
- }
1994
- async requestPageData(path, recover, interceptFrom, activeLayoutChain, signal, cacheData, resolvePrefetch) {
1995
- const response = await fetch(`/__farm/page-data?path=${encodeURIComponent(path)}`, {
1996
- signal,
1997
- headers: createFarmDeploymentRequestHeaders(this.options.deploymentId, {
1998
- Accept: "application/x-farm-deferred+json, application/json",
1999
- "X-Farm-SPA": "1",
2000
- ...activeLayoutChain ? { "X-Farm-Layout-Chain": activeLayoutChain } : {},
2001
- ...interceptFrom ? { "X-Farm-Intercept-From": interceptFrom } : {}
2002
- })
2003
- });
2004
- if (isFarmDeploymentMismatchResponse(response, this.options.deploymentId)) {
2005
- const error = createFarmDeploymentMismatchError(
2006
- response,
2007
- this.options.deploymentId || "unknown"
2008
- );
2009
- dispatchDeploymentMismatch(error);
2010
- if (recover) {
2011
- window.location.assign(path);
2012
- }
2013
- throw error;
2014
- }
2015
- if (!response.ok) {
2016
- throw new Error(`Failed to fetch page data: ${response.status}`);
2017
- }
2018
- const isDeferredResponse = (response.headers.get("Content-Type") || "").toLowerCase().startsWith("application/x-farm-deferred+json");
2019
- if (!isDeferredResponse) {
2020
- const data2 = await readDeferredDataResponse(response);
2021
- cacheData(data2);
2022
- resolvePrefetch?.(data2);
2023
- return data2;
2024
- }
2025
- resolvePrefetch?.(void 0);
2026
- let data;
2027
- let streamCompleted = false;
2028
- const markStreamComplete = /* @__PURE__ */ __name(() => {
2029
- streamCompleted = true;
2030
- if (data) cacheData(data);
2031
- }, "markStreamComplete");
2032
- data = await readDeferredDataResponse(response, {
2033
- onComplete: markStreamComplete
2034
- });
2035
- if (streamCompleted) cacheData(data);
2036
- return data;
2037
- }
2038
- cachePageData(cacheKey, data) {
2039
- const now = Date.now();
2040
- for (const [key, entry] of this.cache) {
2041
- if (now - entry.timestamp >= this.options.cacheMaxAge) this.cache.delete(key);
2042
- }
2043
- this.cache.set(cacheKey, { data, timestamp: now });
2044
- }
2045
- /**
2046
- * Put the browser URL back on the rendered page after a blocked pop. When
2047
- * both entries carry a Farm history index the traversal is reversed
2048
- * exactly; otherwise the current path is pushed again, which restores the
2049
- * address bar at the cost of one extra history entry.
2050
- */
2051
- revertBlockedPopState(event, from) {
2052
- const eventIndex = readHistoryIndex(event.state);
2053
- if (eventIndex != null && this.currentHistoryIndex != null) {
2054
- const delta = eventIndex - this.currentHistoryIndex;
2055
- if (delta !== 0) {
2056
- this.suppressNextPopState = true;
2057
- window.history.go(-delta);
2058
- return;
2059
- }
2060
- }
2061
- try {
2062
- const restoredState = {
2063
- path: from
2064
- };
2065
- if (this.currentHistoryIndex != null && eventIndex != null) {
2066
- restoredState[FARM_HISTORY_INDEX_KEY] = eventIndex + 1;
2067
- this.currentHistoryIndex = eventIndex + 1;
2068
- }
2069
- window.history.pushState(restoredState, "", from);
2070
- } catch {
2071
- }
2072
- }
2073
- /**
2074
- * Handle browser back/forward navigation
2075
- */
2076
- async handlePopState(event) {
2077
- if (document.documentElement.dataset.farmDocsRuntime === "true") return;
2078
- if (this.suppressNextPopState) {
2079
- this.suppressNextPopState = false;
2080
- return;
2081
- }
2082
- const path = window.location.pathname + window.location.search;
2083
- const from = this.currentHistoryPath ?? path;
2084
- if (path === from && window.location.hash !== this.currentHistoryHash && event.state?.[FARM_INTERCEPT_FROM_KEY] === this.currentInterceptFrom) {
2085
- this.cancelActiveNavigation();
2086
- this.currentHistoryHash = window.location.hash;
2087
- this.currentHistoryIndex = readHistoryIndex(event.state);
2088
- return;
2089
- }
2090
- if (await this.shouldBlockNavigation({
2091
- from,
2092
- to: path,
2093
- action: "pop"
2094
- })) {
2095
- this.revertBlockedPopState(event, from);
2096
- return;
2097
- }
2098
- this.currentHistoryPath = path;
2099
- this.currentHistoryHash = window.location.hash;
2100
- this.currentInterceptFrom = event.state?.[FARM_INTERCEPT_FROM_KEY];
2101
- this.currentHistoryIndex = readHistoryIndex(event.state);
2102
- const navigation = this.startNavigation({
2103
- from,
2104
- to: createNavigationLocation(new URL(window.location.href)),
2105
- action: "pop"
2106
- });
2107
- let clientNavigation;
2108
- try {
2109
- clientNavigation = await this.clientPlugins?.beginNavigation({
2110
- from: null,
2111
- to: window.location.href,
2112
- action: "pop"
2113
- });
2114
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
2115
- const interceptFrom = typeof event.state?.[FARM_INTERCEPT_FROM_KEY] === "string" ? event.state[FARM_INTERCEPT_FROM_KEY] : void 0;
2116
- const pageData = await this.fetchPageData(
2117
- path,
2118
- true,
2119
- interceptFrom,
2120
- false,
2121
- navigation.controller.signal
2122
- );
2123
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
2124
- if (clientNavigation) {
2125
- await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);
2126
- }
2127
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
2128
- this.updateDocumentMetadata(pageData.metadata);
2129
- _hydrateFarmI18n(pageData.i18n);
2130
- if (this.onNavigate) {
2131
- await this.onNavigate(pageData);
2132
- }
2133
- const destinationPath = window.location.pathname + window.location.search;
2134
- if (window.location.hash) {
2135
- const target = getHashTargetElement(window.location.hash);
2136
- if (target) {
2137
- target.scrollIntoView();
2138
- } else if (this.options.scrollRestoration) {
2139
- this.restoreWindowScroll(destinationPath);
2140
- }
2141
- } else if (this.options.scrollRestoration) {
2142
- this.restoreWindowScroll(destinationPath);
2143
- }
2144
- if (this.options.scrollRestoration) {
2145
- this.restoreScrollElements(destinationPath);
2146
- }
2147
- if (clientNavigation) {
2148
- await this.clientPlugins?.resolveNavigation(clientNavigation);
2149
- void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);
2150
- }
2151
- this.finishNavigation(navigation);
2152
- } catch (error) {
2153
- if (!this.isCurrentNavigation(navigation, clientNavigation)) return;
2154
- if (clientNavigation) {
2155
- await this.clientPlugins?.failNavigation(clientNavigation, error);
2156
- }
2157
- this.finishNavigation(navigation);
2158
- console.error("[Farm.js] Popstate navigation error:", error);
2159
- window.location.reload();
2160
- }
2161
- }
2162
- /**
2163
- * Check if URL is cached
2164
- */
2165
- isCached(path, interceptFrom) {
2166
- const cached = this.cache.get(getPageDataCacheKey(path, interceptFrom));
2167
- return cached !== void 0 && Date.now() - cached.timestamp < this.options.cacheMaxAge;
2168
- }
2169
- /**
2170
- * Check if URL is external
2171
- */
2172
- isExternalUrl(href) {
2173
- return href.startsWith("http://") || href.startsWith("https://") || href.startsWith("//");
2174
- }
2175
- async shouldBlockNavigation(context2) {
2176
- for (const blocker of this.blockers) {
2177
- if (await blocker(context2)) {
2178
- return true;
2179
- }
2180
- }
2181
- return false;
2182
- }
2183
- evaluateBlockerForUnload(blocker) {
2184
- const path = window.location.pathname + window.location.search;
2185
- const result = blocker({ from: path, to: path, action: "replace" });
2186
- if (result && typeof result !== "boolean") {
2187
- void result.catch(() => void 0);
2188
- return true;
2189
- }
2190
- return result === true;
2191
- }
2192
- shouldBlockUnload() {
2193
- for (const blocker of this.blockers) {
2194
- try {
2195
- if (this.unloadBlockers.get(blocker)?.()) return true;
2196
- } catch {
2197
- return true;
2198
- }
2199
- }
2200
- return false;
2201
- }
2202
- updateDocumentMetadata(metadata) {
2203
- applyFarmMetadataToDocument(metadata, window.location.pathname);
2204
- }
2205
- startNavigation(options) {
2206
- this.activeNavigation?.controller.abort("superseded");
2207
- const navigation = {
2208
- id: ++this.navigationSequence,
2209
- controller: new AbortController()
2210
- };
2211
- this.activeNavigation = navigation;
2212
- this.setNavigationState({
2213
- state: "loading",
2214
- pending: true,
2215
- from: options.from,
2216
- to: options.to,
2217
- action: options.action,
2218
- startedAt: Date.now()
2219
- });
2220
- return navigation;
2221
- }
2222
- isCurrentNavigation(navigation, clientNavigation) {
2223
- return this.activeNavigation?.id === navigation.id && !navigation.controller.signal.aborted && !clientNavigation?.signal.aborted;
2224
- }
2225
- finishNavigation(navigation) {
2226
- if (this.activeNavigation?.id !== navigation.id) return;
2227
- this.activeNavigation = void 0;
2228
- this.setNavigationState(IDLE_NAVIGATION_STATE);
2229
- }
2230
- cancelActiveNavigation() {
2231
- if (!this.activeNavigation) return;
2232
- this.activeNavigation.controller.abort("superseded");
2233
- this.activeNavigation = void 0;
2234
- this.setNavigationState(IDLE_NAVIGATION_STATE);
2235
- }
2236
- setNavigationState(state) {
2237
- this.navigationState = state;
2238
- for (const listener of this.navigationListeners) {
2239
- listener(state);
2240
- }
2241
- }
2242
- writePageState(action, state, href, notify = true) {
2243
- if (typeof window === "undefined") return;
2244
- const url = href ? resolveFarmNavigationURL(href, window.location.href).toString() : window.location.href;
2245
- const parsedUrl = new URL(url);
2246
- const nextPath = parsedUrl.pathname + parsedUrl.search;
2247
- const historyPath = nextPath + parsedUrl.hash;
2248
- const nextState = createHistoryState(historyPath, state, window.history.state);
2249
- if (action === "replace") {
2250
- window.history.replaceState(nextState, "", url);
2251
- } else {
2252
- if (this.currentHistoryIndex != null) {
2253
- nextState[FARM_HISTORY_INDEX_KEY] = this.currentHistoryIndex + 1;
2254
- }
2255
- window.history.pushState(nextState, "", url);
2256
- this.currentHistoryIndex = this.currentHistoryIndex == null ? null : this.currentHistoryIndex + 1;
2257
- }
2258
- this.currentHistoryPath = nextPath;
2259
- this.currentHistoryHash = parsedUrl.hash;
2260
- this.currentInterceptFrom = nextState[FARM_INTERCEPT_FROM_KEY];
2261
- if (notify) notifyHistoryChange("page-state");
2262
- }
2263
- /**
2264
- * Save scroll position for a path
2265
- */
2266
- saveScrollPosition(path) {
2267
- try {
2268
- sessionStorage.setItem(
2269
- `farm-scroll-${path}`,
2270
- JSON.stringify({ x: window.scrollX, y: window.scrollY })
2271
- );
2272
- for (const [key, element] of this.scrollElements) {
2273
- sessionStorage.setItem(
2274
- getScrollElementStorageKey(path, key),
2275
- JSON.stringify({ x: element.scrollLeft, y: element.scrollTop })
2276
- );
2277
- }
2278
- } catch {
2279
- }
2280
- }
2281
- /**
2282
- * Restore the saved window scroll position for a path.
2283
- */
2284
- restoreWindowScroll(path) {
2285
- try {
2286
- const saved = sessionStorage.getItem(`farm-scroll-${path}`);
2287
- if (saved) {
2288
- const { x, y } = JSON.parse(saved);
2289
- setTimeout(() => window.scrollTo(x, y), 0);
2290
- }
2291
- } catch {
2292
- }
2293
- }
2294
- /**
2295
- * Restore saved scroll positions for every registered scroll element. Keys
2296
- * are hash-stripped (see getScrollElementStorageKey), so this runs regardless
2297
- * of whether the destination URL carries a fragment.
2298
- */
2299
- restoreScrollElements(path) {
2300
- try {
2301
- for (const [key, element] of this.scrollElements) {
2302
- this.restoreScrollElement(path, key, element);
2303
- }
2304
- } catch {
2305
- }
2306
- }
2307
- restoreScrollElement(path, key, element) {
2308
- try {
2309
- const saved = sessionStorage.getItem(getScrollElementStorageKey(path, key));
2310
- if (!saved) return;
2311
- const { x, y } = JSON.parse(saved);
2312
- setTimeout(() => {
2313
- element.scrollLeft = x;
2314
- element.scrollTop = y;
2315
- }, 0);
2316
- } catch {
2317
- }
2318
- }
2319
- /**
2320
- * Clear the page cache
2321
- */
2322
- clearCache() {
2323
- this.cacheGeneration += 1;
2324
- this.cache.clear();
2325
- for (const pending of this.pendingPrefetches.values()) {
2326
- pending.cacheable = false;
2327
- pending.resolve(void 0);
2328
- }
2329
- this.pendingPrefetches.clear();
2330
- }
2331
- };
2332
- __name(_SPARouter, "SPARouter");
2333
- var SPARouter = _SPARouter;
2334
- function readBrowserDeploymentId() {
2335
- if (typeof window === "undefined") return void 0;
2336
- const runtimeId = window.__FARM_DEPLOYMENT_ID__;
2337
- if (typeof runtimeId === "string" && runtimeId) return runtimeId;
2338
- return document.querySelector('meta[name="farm-deployment-id"]')?.content;
2339
- }
2340
- __name(readBrowserDeploymentId, "readBrowserDeploymentId");
2341
- function dispatchDeploymentMismatch(error) {
2342
- if (typeof window === "undefined" || typeof CustomEvent === "undefined") return;
2343
- window.dispatchEvent(new CustomEvent("farm:deployment-mismatch", { detail: error }));
2344
- }
2345
- __name(dispatchDeploymentMismatch, "dispatchDeploymentMismatch");
2346
- function getInstalledFarmSPARouter() {
2347
- if (typeof window === "undefined") return void 0;
2348
- return window.__FARM_SPA_ROUTER__;
2349
- }
2350
- __name(getInstalledFarmSPARouter, "getInstalledFarmSPARouter");
2351
- function getRouter() {
2352
- if (typeof window === "undefined") {
2353
- return new SPARouter();
2354
- }
2355
- const installedRouter = getInstalledFarmSPARouter();
2356
- if (installedRouter) {
2357
- routerInstance = installedRouter;
2358
- return installedRouter;
2359
- }
2360
- if (!routerInstance) {
2361
- routerInstance = new SPARouter();
2362
- }
2363
- return routerInstance;
2364
- }
2365
- __name(getRouter, "getRouter");
2366
- function readPageState() {
2367
- if (typeof window === "undefined") return null;
2368
- const state = window.history.state;
2369
- if (!state || typeof state !== "object") return null;
2370
- return state[FARM_PAGE_STATE_KEY] ?? null;
2371
- }
2372
- __name(readPageState, "readPageState");
2373
- function createHistoryState(path, pageState, currentState, interceptFrom) {
2374
- const base = currentState && typeof currentState === "object" ? { ...currentState } : {};
2375
- const nextState = {
2376
- ...base,
2377
- path,
2378
- [FARM_PAGE_STATE_KEY]: pageState
2379
- };
2380
- if (interceptFrom === null) {
2381
- delete nextState[FARM_INTERCEPT_FROM_KEY];
2382
- } else if (interceptFrom) {
2383
- nextState[FARM_INTERCEPT_FROM_KEY] = interceptFrom;
2384
- }
2385
- return nextState;
2386
- }
2387
- __name(createHistoryState, "createHistoryState");
2388
- function getPageDataCacheKey(path, interceptFrom) {
2389
- return interceptFrom ? `${path}
2390
- intercept:${interceptFrom}` : path;
2391
- }
2392
- __name(getPageDataCacheKey, "getPageDataCacheKey");
2393
- function createNavigationLocation(url) {
2394
- return {
2395
- href: url.href,
2396
- pathname: url.pathname,
2397
- search: url.search,
2398
- hash: url.hash
2399
- };
2400
- }
2401
- __name(createNavigationLocation, "createNavigationLocation");
2402
- function getScrollElementStorageKey(path, key) {
2403
- return `farm-scroll-${path}:${key}`;
2404
- }
2405
- __name(getScrollElementStorageKey, "getScrollElementStorageKey");
2406
-
2407
- // src/tracing.ts
2408
- var import_api = require("@opentelemetry/api");
2409
- var FARM_TRACER_NAME = "@farm.js/core";
2410
- var ALL_SPAN_KINDS = [
2411
- "request",
2412
- "render",
2413
- "middleware",
2414
- "api",
2415
- "integration",
2416
- "storage",
2417
- "ppr",
2418
- "build",
2419
- "plugin"
2420
- ];
2421
- var DEFAULT_IGNORED_PATHS = [
2422
- "/@vite/",
2423
- "/@fs/",
2424
- "/@id/",
2425
- "/@react-refresh",
2426
- "/node_modules/",
2427
- "/__vite",
2428
- "/.well-known/appspecific/"
2429
- ];
2430
- var FARM_REQUEST_METHOD_CONTEXT_KEY = (0, import_api.createContextKey)("@farm.js/core/request-method");
2431
- var TRACING_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/tracing-runtime/v1");
2432
- var runtime = globalThis;
2433
- var tracingState = runtime[TRACING_RUNTIME] ?? (runtime[TRACING_RUNTIME] = normalizeFarmTracingConfig(false));
2434
- function normalizeFarmTracingConfig(config) {
2435
- if (!config) {
2436
- return {
2437
- enabled: false,
2438
- spans: new Set(ALL_SPAN_KINDS),
2439
- recordEvents: true,
2440
- attributes: {},
2441
- ignorePaths: DEFAULT_IGNORED_PATHS
2442
- };
2443
- }
2444
- if (config === true) {
2445
- return {
2446
- enabled: true,
2447
- spans: new Set(ALL_SPAN_KINDS),
2448
- recordEvents: true,
2449
- attributes: {},
2450
- ignorePaths: DEFAULT_IGNORED_PATHS
2451
- };
2452
- }
2453
- return {
2454
- enabled: config.enabled ?? true,
2455
- spans: new Set(config.spans ?? ALL_SPAN_KINDS),
2456
- recordEvents: config.recordEvents ?? true,
2457
- attributes: { ...config.attributes },
2458
- ignorePaths: [...DEFAULT_IGNORED_PATHS, ...config.ignorePaths ?? []]
2459
- };
2460
- }
2461
- __name(normalizeFarmTracingConfig, "normalizeFarmTracingConfig");
2462
- function recordFarmEventTrace(event) {
2463
- if (!tracingState.enabled) return void 0;
2464
- const activeContext = import_api.context.active();
2465
- const activeSpan = import_api.trace.getSpan(activeContext);
2466
- const traceContext = getSpanTraceContext(activeSpan);
2467
- if (activeSpan && traceContext) {
2468
- if (event.type === "route.matched") {
2469
- const method = activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) ?? "HTTP";
2470
- activeSpan.updateName(`${method} ${event.route}`);
2471
- activeSpan.setAttribute("http.route", event.route);
2472
- activeSpan.setAttribute("farm.route", event.route);
2473
- }
2474
- if (tracingState.recordEvents) {
2475
- activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);
2476
- }
2477
- const error = event.type === "request.error" ? void 0 : getEventError(event);
2478
- if (error !== void 0) {
2479
- if (event.type === "render.error") {
2480
- recordSpanException(activeSpan, error);
2481
- } else {
2482
- recordSpanError(activeSpan, error);
2483
- }
2484
- }
2485
- }
2486
- const completedTraceContext = recordCompletedEventSpan(event, activeContext);
2487
- return traceContext ?? completedTraceContext;
2488
- }
2489
- __name(recordFarmEventTrace, "recordFarmEventTrace");
2490
- function recordCompletedEventSpan(event, parentContext) {
2491
- const descriptor = getCompletedSpanDescriptor(event);
2492
- if (!descriptor || !tracingState.spans.has(descriptor.kind)) return void 0;
2493
- const tracer = import_api.trace.getTracer(FARM_TRACER_NAME);
2494
- const span = tracer.startSpan(
2495
- descriptor.name,
2496
- {
2497
- kind: import_api.SpanKind.INTERNAL,
2498
- startTime: event.timestamp - descriptor.durationMs,
2499
- attributes: {
2500
- ...tracingState.attributes,
2501
- ...toEventAttributes(event),
2502
- "farm.event.type": event.type
2503
- }
2504
- },
2505
- parentContext
2506
- );
2507
- const status = "status" in event && typeof event.status === "number" ? event.status : void 0;
2508
- if (status !== void 0) setResponseStatus(span, status);
2509
- const error = getEventError(event);
2510
- if (error !== void 0) recordSpanError(span, error);
2511
- const traceContext = getSpanTraceContext(span);
2512
- span.end(event.timestamp);
2513
- return traceContext;
2514
- }
2515
- __name(recordCompletedEventSpan, "recordCompletedEventSpan");
2516
- function getCompletedSpanDescriptor(event) {
2517
- if (!("durationMs" in event) || typeof event.durationMs !== "number") return void 0;
2518
- switch (event.type) {
2519
- case "render.complete":
2520
- return { kind: "render", name: `farm.render ${event.route}`, durationMs: event.durationMs };
2521
- case "render.stream.shellReady":
2522
- return {
2523
- kind: "render",
2524
- name: `farm.render.shell ${event.route}`,
2525
- durationMs: event.durationMs
2526
- };
2527
- case "render.stream.complete":
2528
- return {
2529
- kind: "render",
2530
- name: `farm.render.stream ${event.route}`,
2531
- durationMs: event.durationMs
2532
- };
2533
- case "middleware.complete":
2534
- return {
2535
- kind: "middleware",
2536
- name: `farm.middleware ${event.name ?? event.route ?? "anonymous"}`,
2537
- durationMs: event.durationMs
2538
- };
2539
- case "api.request.complete":
2540
- case "api.error":
2541
- return {
2542
- kind: "api",
2543
- name: `farm.api ${event.method} ${event.route}`,
2544
- durationMs: event.durationMs
2545
- };
2546
- case "integration.api.call.complete":
2547
- return {
2548
- kind: "integration",
2549
- name: `farm.integration ${event.integration}.${event.operation}`,
2550
- durationMs: event.durationMs
2551
- };
2552
- case "storage.query.complete":
2553
- return {
2554
- kind: "storage",
2555
- name: `farm.storage ${event.operation}`,
2556
- durationMs: event.durationMs
2557
- };
2558
- case "ppr.refresh.complete":
2559
- return {
2560
- kind: "ppr",
2561
- name: `farm.ppr.refresh ${event.route}`,
2562
- durationMs: event.durationMs
2563
- };
2564
- case "build.complete":
2565
- return {
2566
- kind: "build",
2567
- name: `farm.build${event.target ? ` ${event.target}` : ""}`,
2568
- durationMs: event.durationMs
2569
- };
2570
- case "plugin.hook.complete":
2571
- return {
2572
- kind: "plugin",
2573
- name: `farm.plugin ${event.plugin}.${event.hook}`,
2574
- durationMs: event.durationMs
2575
- };
2576
- default:
2577
- return void 0;
2578
- }
2579
- }
2580
- __name(getCompletedSpanDescriptor, "getCompletedSpanDescriptor");
2581
- function hashFarmCacheKey(value) {
2582
- let hash = 2166136261;
2583
- for (let index = 0; index < value.length; index++) {
2584
- hash ^= value.charCodeAt(index);
2585
- hash = Math.imul(hash, 16777619);
2586
- }
2587
- return (hash >>> 0).toString(16).padStart(8, "0");
2588
- }
2589
- __name(hashFarmCacheKey, "hashFarmCacheKey");
2590
- function toEventAttributes(event) {
2591
- const attributes = {};
2592
- const redactKey = typeof event.type === "string" && event.type.startsWith("cache.");
2593
- for (const [key, value] of Object.entries(event)) {
2594
- if (key === "timestamp" || key === "level" || key === "error" || key === "traceId" || key === "spanId" || key === "traceSampled" || value === void 0) {
2595
- continue;
2596
- }
2597
- if (redactKey && key === "key" && typeof value === "string") {
2598
- attributes["farm.key_hash"] = hashFarmCacheKey(value);
2599
- continue;
2600
- }
2601
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2602
- attributes[`farm.${key}`] = value;
2603
- } else if (Array.isArray(value)) {
2604
- if (value.every((entry) => typeof entry === "string")) {
2605
- attributes[`farm.${key}`] = value;
2606
- } else if (value.every((entry) => typeof entry === "number")) {
2607
- attributes[`farm.${key}`] = value;
2608
- } else if (value.every((entry) => typeof entry === "boolean")) {
2609
- attributes[`farm.${key}`] = value;
2610
- }
2611
- }
2612
- }
2613
- return attributes;
2614
- }
2615
- __name(toEventAttributes, "toEventAttributes");
2616
- function getEventError(event) {
2617
- return "error" in event ? event.error : void 0;
2618
- }
2619
- __name(getEventError, "getEventError");
2620
- function recordSpanException(span, error) {
2621
- const normalized = error instanceof Error ? error : new Error(String(error));
2622
- span.recordException(normalized);
2623
- return normalized;
2624
- }
2625
- __name(recordSpanException, "recordSpanException");
2626
- function recordSpanError(span, error) {
2627
- const normalized = recordSpanException(span, error);
2628
- span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: normalized.message });
2629
- }
2630
- __name(recordSpanError, "recordSpanError");
2631
- function setResponseStatus(span, status) {
2632
- span.setAttribute("http.response.status_code", status);
2633
- if (status >= 500) {
2634
- span.setStatus({ code: import_api.SpanStatusCode.ERROR });
2635
- }
2636
- }
2637
- __name(setResponseStatus, "setResponseStatus");
2638
- function getSpanTraceContext(span) {
2639
- if (!span) return void 0;
2640
- const spanContext = span.spanContext();
2641
- if (!(0, import_api.isSpanContextValid)(spanContext)) return void 0;
2642
- return {
2643
- traceId: spanContext.traceId,
2644
- spanId: spanContext.spanId,
2645
- traceSampled: (spanContext.traceFlags & 1) === 1
2646
- };
2647
- }
2648
- __name(getSpanTraceContext, "getSpanTraceContext");
2649
-
2650
- // src/observability.ts
2651
- var OBSERVABILITY_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/observability-runtime/v1");
2652
- var runtime2 = globalThis;
2653
- var shared = runtime2[OBSERVABILITY_RUNTIME] ?? (runtime2[OBSERVABILITY_RUNTIME] = {
2654
- handlers: /* @__PURE__ */ new Set(),
2655
- unfilteredHandlers: /* @__PURE__ */ new Set(),
2656
- config: { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) }
2657
- });
2658
- var runtimeHandlers = shared.handlers;
2659
- var unfilteredRuntimeHandlers = shared.unfilteredHandlers;
2660
- var observabilityState = shared.config;
2661
- function emitFarmEvent(input) {
2662
- const event = {
2663
- timestamp: Date.now(),
2664
- level: inferFarmEventLevel(input.type),
2665
- ...input
2666
- };
2667
- const traceContext = recordFarmEventTrace(event);
2668
- if (traceContext) {
2669
- event.traceId = traceContext.traceId;
2670
- event.spanId = traceContext.spanId;
2671
- event.traceSampled = traceContext.traceSampled;
2672
- }
2673
- notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);
2674
- if (!shouldEmitFarmEvent(event)) return event;
2675
- if (observabilityState.logs) {
2676
- logFarmEvent(event);
2677
- }
2678
- notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);
2679
- return event;
2680
- }
2681
- __name(emitFarmEvent, "emitFarmEvent");
2682
- function notifyFarmEventHandlers(event, handlers) {
2683
- for (const handler of handlers) {
2684
- try {
2685
- Promise.resolve(handler(event)).catch((error) => {
2686
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
2687
- });
2688
- } catch (error) {
2689
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
2690
- }
2691
- }
2692
- }
2693
- __name(notifyFarmEventHandlers, "notifyFarmEventHandlers");
2694
- function shouldEmitFarmEvent(event) {
2695
- if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
2696
- return false;
2697
- }
2698
- if (observabilityState.events && !observabilityState.events.has(event.type)) {
2699
- return false;
2700
- }
2701
- return true;
2702
- }
2703
- __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
2704
- function inferFarmEventLevel(type) {
2705
- if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
2706
- return "error";
2707
- }
2708
- if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
2709
- return "warn";
2710
- }
2711
- if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
2712
- return "debug";
2713
- }
2714
- return "info";
2715
- }
2716
- __name(inferFarmEventLevel, "inferFarmEventLevel");
2717
- function logFarmEvent(event) {
2718
- const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
2719
- switch (event.level) {
2720
- case "error":
2721
- console.error(message);
2722
- break;
2723
- case "warn":
2724
- console.warn(message);
2725
- break;
2726
- default:
2727
- console.log(message);
2728
- break;
2729
- }
2730
- }
2731
- __name(logFarmEvent, "logFarmEvent");
2732
- function formatFarmEventDetails(event) {
2733
- const details = [];
2734
- const record = event;
2735
- for (const key of [
2736
- "route",
2737
- "pathname",
2738
- "method",
2739
- "status",
2740
- "key",
2741
- "tag",
2742
- "path",
2743
- "reason",
2744
- "durationMs",
2745
- "integration",
2746
- "server",
2747
- "tool",
2748
- "outcome",
2749
- "operation",
2750
- "plugin",
2751
- "hook",
2752
- "target",
2753
- "count"
2754
- ]) {
2755
- const value = record[key];
2756
- if (value !== void 0) {
2757
- details.push(`${key}=${formatDetailValue(value)}`);
2758
- }
2759
- }
2760
- return details.length > 0 ? ` ${details.join(" ")}` : "";
2761
- }
2762
- __name(formatFarmEventDetails, "formatFarmEventDetails");
2763
- function formatDetailValue(value) {
2764
- if (typeof value === "string") {
2765
- return value;
2766
- }
2767
- if (typeof value === "number" || typeof value === "boolean") {
2768
- return String(value);
2769
- }
2770
- try {
2771
- return JSON.stringify(value);
2772
- } catch {
2773
- return String(value);
2774
- }
2775
- }
2776
- __name(formatDetailValue, "formatDetailValue");
2777
- function formatError(error) {
2778
- return error instanceof Error ? error.message : String(error);
2779
- }
2780
- __name(formatError, "formatError");
2781
-
2782
- // src/cache-invalidation.ts
2783
- var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
2784
- var globalState = globalThis;
2785
- function getFarmCacheInvalidationState() {
2786
- return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
2787
- listeners: /* @__PURE__ */ new Set(),
2788
- taskListeners: /* @__PURE__ */ new Set()
2789
- });
2790
- }
2791
- __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
2792
- function subscribeFarmCacheInvalidation(listener) {
2793
- const state = getFarmCacheInvalidationState();
2794
- state.listeners.add(listener);
2795
- return () => state.listeners.delete(listener);
2796
- }
2797
- __name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
2798
-
2799
- // src/cache-invalidation-stream.ts
2800
- var MAX_BUFFERED_BYTES = 64 * 1024;
2801
- var textEncoder = new TextEncoder();
2802
-
2803
- // src/cache.ts
2804
- var _FarmDataCache = class _FarmDataCache {
2805
- constructor(config = {}) {
2806
- this.entries = /* @__PURE__ */ new Map();
2807
- this.inflight = /* @__PURE__ */ new Map();
2808
- /** Local entries by tag, so tag counts and pruning never scan unrelated entries. */
2809
- this.entriesByTag = /* @__PURE__ */ new Map();
2810
- this.invalidatedTagVersions = /* @__PURE__ */ new Map();
2811
- this.activeGenerations = /* @__PURE__ */ new Set();
2812
- this.version = 0;
2813
- this.generation = 0;
2814
- this.namespace = "farm";
2815
- this.local = true;
2816
- this.maxEntries = 1024;
2817
- this.lease = {
2818
- enabled: true,
2819
- ttlMs: 1e4,
2820
- waitTimeoutMs: 1e4,
2821
- pollIntervalMs: 25
2822
- };
2823
- this.configure(config);
2824
- }
2825
- configure(config = {}) {
2826
- this.generation++;
2827
- this.entries.clear();
2828
- this.entriesByTag.clear();
2829
- this.inflight.clear();
2830
- this.invalidatedTagVersions.clear();
2831
- this.activeGenerations.clear();
2832
- this.version = 0;
2833
- this.adapter = config.adapter;
2834
- this.namespace = normalizeCacheNamespace(config.namespace || "farm");
2835
- this.local = !config.adapter;
2836
- this.maxEntries = normalizePositiveInteger(config.maxEntries, 1024, "cache.maxEntries");
2837
- this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
2838
- enabled: true,
2839
- ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
2840
- waitTimeoutMs: normalizePositiveDuration(
2841
- config.lease?.waitTimeoutMs,
2842
- 1e4,
2843
- "cache.lease.waitTimeoutMs"
2844
- ),
2845
- pollIntervalMs: normalizePositiveDuration(
2846
- config.lease?.pollIntervalMs,
2847
- 25,
2848
- "cache.lease.pollIntervalMs"
2849
- )
2850
- };
2851
- }
2852
- get adapterName() {
2853
- return this.adapter?.name || (this.adapter ? "custom" : "memory");
2854
- }
2855
- get hasAdapter() {
2856
- return this.adapter !== void 0;
2857
- }
2858
- get size() {
2859
- return this.entries.size;
2860
- }
2861
- get(key, options = {}) {
2862
- return this.getEntry(key, options)?.value;
2863
- }
2864
- getEntry(key, options = {}) {
2865
- const entry = this.entries.get(key);
2866
- if (!entry) {
2867
- emitFarmEvent({ type: "cache.miss", key });
2868
- return void 0;
2869
- }
2870
- const stale = this.isStale(entry, options.now);
2871
- if (stale) {
2872
- emitFarmEvent({
2873
- type: "cache.stale",
2874
- key,
2875
- tags: Array.from(entry.tags),
2876
- revalidate: entry.revalidate
2877
- });
2878
- }
2879
- if (!options.allowStale && stale) {
2880
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
2881
- return void 0;
2882
- }
2883
- this.touchEntry(key, entry);
2884
- emitFarmEvent({
2885
- type: "cache.hit",
2886
- key,
2887
- tags: Array.from(entry.tags),
2888
- revalidate: entry.revalidate,
2889
- stale
2890
- });
2891
- return this.toPublicEntry(entry);
2892
- }
2893
- async getEntryAsync(key, options = {}) {
2894
- if (this.local) {
2895
- const localEntry = this.getEntry(key, options);
2896
- if (localEntry) return localEntry;
2897
- }
2898
- if (!this.adapter) {
2899
- return this.local ? void 0 : this.getEntry(key, options);
2900
- }
2901
- const generation = this.generation;
2902
- const adapter = this.adapter;
2903
- const namespace = this.namespace;
2904
- const entry = await adapter.get(`${namespace}:entry:${key}`);
2905
- if (generation !== this.generation) return void 0;
2906
- if (!entry) {
2907
- emitFarmEvent({ type: "cache.miss", key });
2908
- return void 0;
2909
- }
2910
- assertFarmCacheEntry(entry, key);
2911
- const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);
2912
- if (generation !== this.generation) return void 0;
2913
- if (stale) {
2914
- emitFarmEvent({
2915
- type: "cache.stale",
2916
- key,
2917
- tags: [...entry.tags],
2918
- revalidate: entry.revalidate
2919
- });
2920
- if (!options.allowStale) {
2921
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
2922
- return void 0;
2923
- }
2924
- }
2925
- emitFarmEvent({
2926
- type: "cache.hit",
2927
- key,
2928
- tags: [...entry.tags],
2929
- revalidate: entry.revalidate,
2930
- stale
2931
- });
2932
- if (this.local && !stale) {
2933
- this.hydrateLocalEntry(entry);
2934
- }
2935
- return { ...entry, key };
2936
- }
2937
- set(key, value, options = {}) {
2938
- const revalidate = normalizeRevalidate(options.revalidate);
2939
- const tags = /* @__PURE__ */ new Set();
2940
- for (const tag of options.tags ?? []) {
2941
- tags.add(normalizeCacheTag(tag));
2942
- }
2943
- for (const routePath of options.paths ?? []) {
2944
- tags.add(createPathCacheTag(routePath));
2945
- }
2946
- const entry = {
2947
- key,
2948
- value,
2949
- tags,
2950
- tagVersions: void 0,
2951
- createdAt: options.createdAt ?? Date.now(),
2952
- createdVersion: ++this.version,
2953
- revalidate
2954
- };
2955
- this.storeLocalEntry(entry);
2956
- emitFarmEvent({
2957
- type: "cache.set",
2958
- key,
2959
- tags: Array.from(tags),
2960
- revalidate: entry.revalidate
2961
- });
2962
- return this.toPublicEntry(entry);
2963
- }
2964
- async setAsync(key, value, options = {}, tagVersions) {
2965
- return this.writeAsync(key, value, options, tagVersions);
2966
- }
2967
- async writeAsync(key, value, options, tagVersions, createdVersion) {
2968
- const revalidate = normalizeRevalidate(options.revalidate);
2969
- const tags = normalizeCacheOptionsTags(options);
2970
- const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
2971
- const entry = {
2972
- key,
2973
- value,
2974
- tags: Array.from(tags),
2975
- tagVersions: capturedVersions,
2976
- createdAt: options.createdAt ?? Date.now(),
2977
- createdVersion: createdVersion ?? ++this.version,
2978
- revalidate
2979
- };
2980
- if (this.local) {
2981
- this.hydrateLocalEntry(entry);
2982
- }
2983
- if (this.adapter) {
2984
- await this.adapter.set(this.createAdapterKey(key), entry);
2985
- }
2986
- emitFarmEvent({
2987
- type: "cache.set",
2988
- key,
2989
- tags: [...entry.tags],
2990
- revalidate: entry.revalidate
2991
- });
2992
- return entry;
2993
- }
2994
- delete(key) {
2995
- const deleted = this.deleteLocalEntry(key);
2996
- emitFarmEvent({ type: "cache.delete", key, deleted });
2997
- return deleted;
2998
- }
2999
- async deleteAsync(key) {
3000
- const deleted = this.deleteLocalEntry(key);
3001
- if (this.adapter) {
3002
- await this.adapter.delete(this.createAdapterKey(key));
3003
- }
3004
- emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
3005
- return this.adapter ? true : deleted;
3006
- }
3007
- clear() {
3008
- const count = this.entries.size;
3009
- this.generation++;
3010
- this.entries.clear();
3011
- this.entriesByTag.clear();
3012
- this.inflight.clear();
3013
- this.invalidatedTagVersions.clear();
3014
- this.activeGenerations.clear();
3015
- this.version = 0;
3016
- emitFarmEvent({ type: "cache.clear", count });
3017
- }
3018
- async clearAsync() {
3019
- this.clear();
3020
- await this.adapter?.clear?.();
3021
- }
3022
- isStale(entry, now = Date.now()) {
3023
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
3024
- return true;
3025
- }
3026
- for (const tag of entry.tags) {
3027
- const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
3028
- if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
3029
- return true;
3030
- }
3031
- }
3032
- return false;
3033
- }
3034
- async isStaleAsync(entry, now = Date.now()) {
3035
- if (this.adapter) {
3036
- return this.isAdapterEntryStale(entry, now);
3037
- }
3038
- return this.isStale(entry, now);
3039
- }
3040
- revalidateTag(tag, options = {}) {
3041
- const normalized = normalizeCacheTag(tag);
3042
- const count = this.invalidateTag(normalized);
3043
- emitFarmEvent(
3044
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
3045
- );
3046
- return count;
3047
- }
3048
- async revalidateTagAsync(tag, options = {}) {
3049
- const normalized = normalizeCacheTag(tag);
3050
- const count = this.invalidateTag(normalized);
3051
- await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
3052
- emitFarmEvent(
3053
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
3054
- );
3055
- return count;
3056
- }
3057
- revalidatePath(routePath) {
3058
- const normalizedPath = normalizeRevalidatePath(routePath);
3059
- const pathTag = createPathCacheTag(normalizedPath);
3060
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
3061
- const count = this.invalidateTag(pathTag);
3062
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
3063
- if (pprCount > 0) {
3064
- emitFarmEvent({
3065
- type: "ppr.shell.invalidated",
3066
- route: normalizedPath,
3067
- reason: "revalidatePath",
3068
- count: pprCount
3069
- });
3070
- }
3071
- return count;
3072
- }
3073
- async revalidatePathAsync(routePath) {
3074
- const normalizedPath = normalizeRevalidatePath(routePath);
3075
- const pathTag = createPathCacheTag(normalizedPath);
3076
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
3077
- const count = this.invalidateTag(pathTag);
3078
- await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
3079
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
3080
- if (pprCount > 0) {
3081
- emitFarmEvent({
3082
- type: "ppr.shell.invalidated",
3083
- route: normalizedPath,
3084
- reason: "revalidatePath",
3085
- count: pprCount
3086
- });
3087
- }
3088
- return count;
3089
- }
3090
- async getOrSet(key, producer, options = {}) {
3091
- normalizeRevalidate(options.revalidate);
3092
- const cached = await this.getEntryAsync(key);
3093
- if (cached) {
3094
- return cached.value;
3095
- }
3096
- const inflight = this.inflight.get(key);
3097
- if (inflight && !this.wasInvalidatedSince(inflight.tags, inflight.startVersion)) {
3098
- emitFarmEvent({ type: "cache.dedupe", key });
3099
- return inflight.promise;
3100
- }
3101
- const tags = Array.from(normalizeCacheOptionsTags(options));
3102
- const generation = this.generation;
3103
- const startVersion = this.version;
3104
- const promise = this.fillCacheEntry(key, producer, options, tags, generation).catch((error) => {
3105
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
3106
- throw error;
3107
- }).finally(() => {
3108
- if (this.inflight.get(key)?.promise === promise) {
3109
- this.inflight.delete(key);
3110
- }
3111
- });
3112
- this.inflight.set(key, { promise, tags, startVersion });
3113
- return promise;
3114
- }
3115
- /** A fill that started before one of its tags was invalidated cannot satisfy later readers. */
3116
- wasInvalidatedSince(tags, version) {
3117
- for (const tag of tags) {
3118
- const invalidatedVersion = this.invalidatedTagVersions.get(tag);
3119
- if (invalidatedVersion !== void 0 && invalidatedVersion > version) return true;
3120
- }
3121
- return false;
3122
- }
3123
- async fillCacheEntry(key, producer, options, tags, generation) {
3124
- const adapter = this.adapter;
3125
- const namespace = this.namespace;
3126
- const lease = { ...this.lease };
3127
- const leaseKey = `${namespace}:lease:${key}`;
3128
- let leaseToken;
3129
- if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {
3130
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
3131
- if (!leaseToken) {
3132
- const shared2 = await this.waitForAdapterEntry(
3133
- key,
3134
- adapter,
3135
- namespace,
3136
- lease,
3137
- generation
3138
- );
3139
- if (shared2) {
3140
- emitFarmEvent({ type: "cache.dedupe", key });
3141
- return shared2.value;
3142
- }
3143
- if (generation === this.generation) {
3144
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
3145
- }
3146
- }
3147
- }
3148
- const initialCreatedVersion = this.version;
3149
- const activeGeneration = {
3150
- tags: new Set(tags),
3151
- createdVersion: initialCreatedVersion
3152
- };
3153
- this.activeGenerations.add(activeGeneration);
3154
- try {
3155
- const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);
3156
- const value = await producer();
3157
- if (generation === this.generation) {
3158
- await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);
3159
- }
3160
- return value;
3161
- } finally {
3162
- this.activeGenerations.delete(activeGeneration);
3163
- this.pruneInvalidatedTagVersions(activeGeneration.tags);
3164
- if (leaseToken && adapter?.releaseLease) {
3165
- try {
3166
- await adapter.releaseLease(leaseKey, leaseToken);
3167
- } catch (error) {
3168
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
3169
- }
3170
- }
3171
- }
3172
- }
3173
- async waitForAdapterEntry(key, adapter, namespace, lease, generation) {
3174
- const deadline = Date.now() + lease.waitTimeoutMs;
3175
- while (Date.now() < deadline) {
3176
- await delay(lease.pollIntervalMs);
3177
- if (generation !== this.generation) return void 0;
3178
- const entry = await adapter.get(`${namespace}:entry:${key}`);
3179
- if (generation !== this.generation) return void 0;
3180
- if (!entry) {
3181
- emitFarmEvent({ type: "cache.miss", key });
3182
- continue;
3183
- }
3184
- assertFarmCacheEntry(entry, key);
3185
- const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);
3186
- if (generation !== this.generation) return void 0;
3187
- if (stale) {
3188
- emitFarmEvent({
3189
- type: "cache.stale",
3190
- key,
3191
- tags: [...entry.tags],
3192
- revalidate: entry.revalidate
3193
- });
3194
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
3195
- } else {
3196
- emitFarmEvent({
3197
- type: "cache.hit",
3198
- key,
3199
- tags: [...entry.tags],
3200
- revalidate: entry.revalidate,
3201
- stale: false
3202
- });
3203
- return { ...entry, key };
3204
- }
3205
- }
3206
- return void 0;
3207
- }
3208
- countEntriesForTags(tags) {
3209
- let count = 0;
3210
- for (const entry of this.entriesByTag.get(tags[0]) ?? []) {
3211
- if (tags.every((tag) => entry.tags.has(tag))) {
3212
- count++;
3213
- }
3214
- }
3215
- return count;
3216
- }
3217
- invalidateTag(normalizedTag) {
3218
- const count = this.entriesByTag.get(normalizedTag)?.size ?? 0;
3219
- this.invalidatedTagVersions.delete(normalizedTag);
3220
- this.invalidatedTagVersions.set(normalizedTag, ++this.version);
3221
- this.pruneInvalidatedTagVersions([normalizedTag]);
3222
- return count;
3223
- }
3224
- toPublicEntry(entry) {
3225
- return {
3226
- key: entry.key,
3227
- value: entry.value,
3228
- tags: Array.from(entry.tags),
3229
- tagVersions: entry.tagVersions,
3230
- createdAt: entry.createdAt,
3231
- createdVersion: entry.createdVersion,
3232
- revalidate: entry.revalidate
3233
- };
3234
- }
3235
- hydrateLocalEntry(entry) {
3236
- this.storeLocalEntry({
3237
- key: entry.key,
3238
- value: entry.value,
3239
- tags: new Set(entry.tags.map(normalizeCacheTag)),
3240
- tagVersions: entry.tagVersions,
3241
- createdAt: entry.createdAt,
3242
- createdVersion: entry.createdVersion ?? ++this.version,
3243
- revalidate: normalizeRevalidate(entry.revalidate)
3244
- });
3245
- }
3246
- touchEntry(key, entry) {
3247
- this.entries.delete(key);
3248
- this.entries.set(key, entry);
3249
- }
3250
- storeLocalEntry(entry) {
3251
- const removed = [];
3252
- const replaced = this.detachLocalEntry(entry.key);
3253
- if (replaced) removed.push(replaced);
3254
- this.entries.set(entry.key, entry);
3255
- for (const tag of entry.tags) {
3256
- let tagged = this.entriesByTag.get(tag);
3257
- if (!tagged) this.entriesByTag.set(tag, tagged = /* @__PURE__ */ new Set());
3258
- tagged.add(entry);
3259
- }
3260
- while (this.entries.size > this.maxEntries) {
3261
- const oldestKey = this.entries.keys().next().value;
3262
- if (oldestKey === void 0) break;
3263
- removed.push(this.detachLocalEntry(oldestKey));
3264
- }
3265
- for (const removedEntry of removed) this.pruneInvalidatedTagVersions(removedEntry.tags);
3266
- }
3267
- deleteLocalEntry(key) {
3268
- const entry = this.detachLocalEntry(key);
3269
- if (!entry) return false;
3270
- this.pruneInvalidatedTagVersions(entry.tags);
3271
- return true;
3272
- }
3273
- detachLocalEntry(key) {
3274
- const entry = this.entries.get(key);
3275
- if (!entry) return void 0;
3276
- this.entries.delete(key);
3277
- for (const tag of entry.tags) {
3278
- const tagged = this.entriesByTag.get(tag);
3279
- if (!tagged) continue;
3280
- tagged.delete(entry);
3281
- if (tagged.size === 0) this.entriesByTag.delete(tag);
3282
- }
3283
- return entry;
3284
- }
3285
- /**
3286
- * Drop invalidation versions that no local entry or active fill can be stale against.
3287
- * Callers pass only the tags whose dependents just changed, so the cost is bounded by
3288
- * the entries sharing those tags rather than by the whole cache.
3289
- */
3290
- pruneInvalidatedTagVersions(tags) {
3291
- tags: for (const tag of tags) {
3292
- const invalidatedVersion = this.invalidatedTagVersions.get(tag);
3293
- if (invalidatedVersion === void 0) continue;
3294
- for (const entry of this.entriesByTag.get(tag) ?? []) {
3295
- if (entry.createdVersion < invalidatedVersion) continue tags;
3296
- }
3297
- for (const generation of this.activeGenerations) {
3298
- if (generation.tags.has(tag) && generation.createdVersion < invalidatedVersion)
3299
- continue tags;
3300
- }
3301
- this.invalidatedTagVersions.delete(tag);
3302
- }
3303
- }
3304
- createAdapterKey(key) {
3305
- return `${this.namespace}:entry:${key}`;
3306
- }
3307
- createAdapterTag(tag) {
3308
- return `${this.namespace}:tag:${tag}`;
3309
- }
3310
- async getAdapterTagVersions(tags, adapter = this.adapter, namespace = this.namespace) {
3311
- if (!adapter?.getTagVersions || tags.length === 0) return {};
3312
- const normalized = tags.map(normalizeCacheTag);
3313
- const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);
3314
- const versions = await adapter.getTagVersions(physicalTags);
3315
- return Object.fromEntries(
3316
- normalized.map((tag, index) => [
3317
- tag,
3318
- normalizeAdapterVersion(versions[physicalTags[index]])
3319
- ])
3320
- );
3321
- }
3322
- async isAdapterEntryStale(entry, now = Date.now(), adapter = this.adapter, namespace = this.namespace) {
3323
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
3324
- return true;
3325
- }
3326
- const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);
3327
- for (const tag of entry.tags) {
3328
- if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
3329
- return true;
3330
- }
3331
- }
3332
- return false;
3333
- }
3334
- };
3335
- __name(_FarmDataCache, "FarmDataCache");
3336
- var FarmDataCache = _FarmDataCache;
3337
- var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
3338
- var farmDataCacheGlobal = globalThis;
3339
- var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
3340
- function createPathCacheTag(routePath) {
3341
- return `path:${normalizeRevalidatePath(routePath)}`;
3342
- }
3343
- __name(createPathCacheTag, "createPathCacheTag");
3344
- function normalizeRevalidatePath(routePath) {
3345
- if (typeof routePath !== "string") {
3346
- throw new TypeError("revalidatePath expects a path string.");
3347
- }
3348
- let normalized = routePath.trim();
3349
- if (!normalized) {
3350
- throw new Error("revalidatePath expects a non-empty path.");
3351
- }
3352
- try {
3353
- if (/^https?:\/\//i.test(normalized)) {
3354
- normalized = new URL(normalized).pathname;
3355
- }
3356
- } catch {
3357
- }
3358
- normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;
3359
- normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
3360
- normalized = normalized.replace(/\/{2,}/g, "/");
3361
- normalized = new URL(normalized, "http://farm.invalid").pathname;
3362
- if (normalized.length > 1) {
3363
- normalized = normalized.replace(/\/+$/, "");
3364
- }
3365
- return normalized || "/";
3366
- }
3367
- __name(normalizeRevalidatePath, "normalizeRevalidatePath");
3368
- function createFarmCacheKey(parts) {
3369
- return stableSerialize(parts);
3370
- }
3371
- __name(createFarmCacheKey, "createFarmCacheKey");
3372
- function normalizeRevalidate(revalidate) {
3373
- if (revalidate === false || revalidate === void 0) {
3374
- return revalidate;
3375
- }
3376
- if (!Number.isFinite(revalidate) || revalidate < 0) {
3377
- throw new TypeError("Cache revalidate must be false or a finite, non-negative number.");
3378
- }
3379
- return revalidate;
3380
- }
3381
- __name(normalizeRevalidate, "normalizeRevalidate");
3382
- function normalizeCacheTag(tag) {
3383
- if (typeof tag !== "string") {
3384
- throw new TypeError("Cache tags must be strings.");
3385
- }
3386
- const normalized = tag.trim();
3387
- if (!normalized) {
3388
- throw new Error("Cache tags cannot be empty.");
3389
- }
3390
- return normalized;
3391
- }
3392
- __name(normalizeCacheTag, "normalizeCacheTag");
3393
- function normalizeCacheNamespace(namespace) {
3394
- if (typeof namespace !== "string") {
3395
- throw new TypeError("Cache namespace must be a string.");
3396
- }
3397
- const normalized = namespace.trim().replace(/:+$/g, "");
3398
- if (!normalized) {
3399
- throw new Error("Cache namespace cannot be empty.");
3400
- }
3401
- return normalized;
3402
- }
3403
- __name(normalizeCacheNamespace, "normalizeCacheNamespace");
3404
- function normalizeAdapterVersion(value) {
3405
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
3406
- }
3407
- __name(normalizeAdapterVersion, "normalizeAdapterVersion");
3408
- function normalizePositiveDuration(value, fallback, name) {
3409
- if (value === void 0) return fallback;
3410
- if (!Number.isFinite(value) || value <= 0) {
3411
- throw new TypeError(`${name} must be a positive number of milliseconds.`);
3412
- }
3413
- return Math.floor(value);
3414
- }
3415
- __name(normalizePositiveDuration, "normalizePositiveDuration");
3416
- function normalizePositiveInteger(value, fallback, name) {
3417
- if (value === void 0) return fallback;
3418
- if (!Number.isSafeInteger(value) || value <= 0) {
3419
- throw new TypeError(`${name} must be a positive integer.`);
3420
- }
3421
- return value;
3422
- }
3423
- __name(normalizePositiveInteger, "normalizePositiveInteger");
3424
- function delay(ms) {
3425
- return new Promise((resolve) => setTimeout(resolve, ms));
3426
- }
3427
- __name(delay, "delay");
3428
- function normalizeCacheOptionsTags(options) {
3429
- const tags = /* @__PURE__ */ new Set();
3430
- for (const tag of options.tags ?? []) {
3431
- tags.add(normalizeCacheTag(tag));
3432
- }
3433
- for (const routePath of options.paths ?? []) {
3434
- tags.add(createPathCacheTag(routePath));
3435
- }
3436
- return tags;
3437
- }
3438
- __name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
3439
- function assertFarmCacheEntry(entry, expectedKey) {
3440
- if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
3441
- throw new TypeError(
3442
- `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
3443
- );
3444
- }
3445
- }
3446
- __name(assertFarmCacheEntry, "assertFarmCacheEntry");
3447
- function getFunctionCacheIdentity(fn) {
3448
- const name = fn.name || "anonymous";
3449
- return `${name}:${hashFunctionSource(String(fn))}`;
3450
- }
3451
- __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
3452
- function hashFunctionSource(source) {
3453
- let hash = 2166136261;
3454
- for (let index = 0; index < source.length; index++) {
3455
- hash ^= source.charCodeAt(index);
3456
- hash = Math.imul(hash, 16777619);
3457
- }
3458
- return (hash >>> 0).toString(36);
3459
- }
3460
- __name(hashFunctionSource, "hashFunctionSource");
3461
- function compareCodepoint(a, b) {
3462
- return a < b ? -1 : a > b ? 1 : 0;
3463
- }
3464
- __name(compareCodepoint, "compareCodepoint");
3465
- function serializeBinaryBytes(bytes) {
3466
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
3467
- }
3468
- __name(serializeBinaryBytes, "serializeBinaryBytes");
3469
- function serializeCanonicalStringEntries(entries, seen) {
3470
- const valuesByKey = /* @__PURE__ */ new Map();
3471
- for (const [key, item] of entries) {
3472
- const values = valuesByKey.get(key);
3473
- if (values) values.push(item);
3474
- else valuesByKey.set(key, [item]);
3475
- }
3476
- return Array.from(valuesByKey.keys()).sort(compareCodepoint).flatMap(
3477
- (key) => valuesByKey.get(key).map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`)
3478
- ).join(",");
3479
- }
3480
- __name(serializeCanonicalStringEntries, "serializeCanonicalStringEntries");
3481
- function isPlainCacheKeyObject(value) {
3482
- const prototype = Object.getPrototypeOf(value);
3483
- if (prototype === null) return true;
3484
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
3485
- return Object.getPrototypeOf(prototype) === null && typeof constructor === "function" && constructor.name === "Object";
3486
- }
3487
- __name(isPlainCacheKeyObject, "isPlainCacheKeyObject");
3488
- function getCacheKeyValueType(value) {
3489
- const prototype = Object.getPrototypeOf(value);
3490
- const constructor = prototype ? Object.getOwnPropertyDescriptor(prototype, "constructor")?.value : void 0;
3491
- if (typeof constructor === "function" && constructor.name) {
3492
- return constructor.name;
3493
- }
3494
- return Object.prototype.toString.call(value).slice(8, -1) || "object";
3495
- }
3496
- __name(getCacheKeyValueType, "getCacheKeyValueType");
3497
- function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
3498
- if (value === null) return "null";
3499
- if (value === void 0) return "undefined";
3500
- const valueType = typeof value;
3501
- if (valueType === "string") return JSON.stringify(value);
3502
- if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
3503
- return `${valueType}:${String(value)}`;
3504
- }
3505
- if (valueType === "symbol") {
3506
- return `symbol:${String(value)}`;
3507
- }
3508
- if (valueType === "function") {
3509
- return `function:${getFunctionCacheIdentity(value)}`;
3510
- }
3511
- if (value instanceof Date) {
3512
- return Number.isNaN(value.getTime()) ? "date:invalid" : `date:${value.toISOString()}`;
3513
- }
3514
- if (value instanceof URL) {
3515
- return `url:${value.toString()}`;
3516
- }
3517
- if (value instanceof RegExp) {
3518
- return `regexp:${value.toString()}`;
3519
- }
3520
- if (value instanceof ArrayBuffer) {
3521
- return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
3522
- }
3523
- if (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer) {
3524
- return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
3525
- }
3526
- if (ArrayBuffer.isView(value)) {
3527
- const viewType = Object.prototype.toString.call(value).slice(8, -1);
3528
- const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
3529
- return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;
3530
- }
3531
- if (value && typeof value === "object") {
3532
- if (seen.has(value)) {
3533
- return "[Circular]";
3534
- }
3535
- seen.add(value);
3536
- if (Array.isArray(value)) {
3537
- const items = [];
3538
- for (let index = 0; index < value.length; index++) {
3539
- items.push(
3540
- Object.prototype.hasOwnProperty.call(value, index) ? stableSerialize(value[index], seen) : "[Hole]"
3541
- );
3542
- }
3543
- seen.delete(value);
3544
- return `[${items.join(",")}]`;
3545
- }
3546
- if (value instanceof Set) {
3547
- const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);
3548
- seen.delete(value);
3549
- return `set:[${items.join(",")}]`;
3550
- }
3551
- if (value instanceof Map) {
3552
- const items = Array.from(
3553
- value,
3554
- ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`
3555
- ).sort(compareCodepoint);
3556
- seen.delete(value);
3557
- return `map:[${items.join(",")}]`;
3558
- }
3559
- if (value instanceof URLSearchParams) {
3560
- const serialized2 = serializeCanonicalStringEntries(value, seen);
3561
- seen.delete(value);
3562
- return `urlsearchparams:[${serialized2}]`;
3563
- }
3564
- if (value instanceof Headers) {
3565
- const serialized2 = serializeCanonicalStringEntries(value, seen);
3566
- seen.delete(value);
3567
- return `headers:[${serialized2}]`;
3568
- }
3569
- if (!isPlainCacheKeyObject(value)) {
3570
- throw new TypeError(
3571
- `Cache keys do not support ${getCacheKeyValueType(value)} values. Convert the value to an explicit stable string or structured key before caching.`
3572
- );
3573
- }
3574
- const entries = Object.entries(value).sort(
3575
- ([a], [b]) => compareCodepoint(a, b)
3576
- );
3577
- const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
3578
- seen.delete(value);
3579
- return `{${serialized}}`;
3580
- }
3581
- return String(value);
3582
- }
3583
- __name(stableSerialize, "stableSerialize");
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client";
3584
2
 
3585
- // src/client-cache.ts
3586
- var invalidationTrackers = /* @__PURE__ */ new WeakMap();
3587
- function trackFarmClientCacheInvalidations(cache) {
3588
- let trackers = invalidationTrackers.get(cache);
3589
- if (!trackers) {
3590
- trackers = /* @__PURE__ */ new Set();
3591
- invalidationTrackers.set(cache, trackers);
3592
- }
3593
- const keys = /* @__PURE__ */ new Set();
3594
- trackers.add(keys);
3595
- return {
3596
- has(key) {
3597
- const resolved = cache.resolveKey(key);
3598
- for (const invalidated of keys) {
3599
- if (cache.resolveKey(invalidated) === resolved) return true;
3600
- }
3601
- return false;
3602
- },
3603
- dispose() {
3604
- if (!trackers.delete(keys)) return;
3605
- keys.clear();
3606
- if (trackers.size === 0) invalidationTrackers.delete(cache);
3607
- }
3608
- };
3609
- }
3610
- __name(trackFarmClientCacheInvalidations, "trackFarmClientCacheInvalidations");
3611
- var cacheFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((unsubscribe) => unsubscribe()) : void 0;
3612
- var DEFAULT_GC_SWEEP_INTERVAL_MS = 3e4;
3613
- var _FarmClientDataCache = class _FarmClientDataCache {
3614
- constructor(options = {}) {
3615
- this.entries = /* @__PURE__ */ new Map();
3616
- this.aliases = /* @__PURE__ */ new Map();
3617
- this.aliasesByTarget = /* @__PURE__ */ new Map();
3618
- this.invalidatedAt = /* @__PURE__ */ new Map();
3619
- this.listeners = /* @__PURE__ */ new Map();
3620
- this.inflight = /* @__PURE__ */ new Map();
3621
- this.pendingMetadataSweeps = /* @__PURE__ */ new Set();
3622
- this.gcSweepIntervalMs = options.gcSweepIntervalMs ?? DEFAULT_GC_SWEEP_INTERVAL_MS;
3623
- if (options.subscribeToInvalidation !== false) {
3624
- if (typeof WeakRef === "function") {
3625
- const reference = new WeakRef(this);
3626
- const unsubscribe = _FarmClientDataCache.subscribeWeakCache(reference);
3627
- cacheFinalizer?.register(this, unsubscribe, reference);
3628
- this.unsubscribeInvalidation = unsubscribe;
3629
- } else {
3630
- this.unsubscribeInvalidation = subscribeFarmCacheInvalidation(
3631
- (key) => this.applyInvalidation(key, Date.now(), false)
3632
- );
3633
- }
3634
- }
3635
- }
3636
- // This closure must only capture a weak reference, never the cache itself.
3637
- static subscribeWeakCache(reference) {
3638
- const unsubscribe = subscribeFarmCacheInvalidation((key) => {
3639
- const cache = reference.deref();
3640
- if (cache) cache.applyInvalidation(key, Date.now(), false);
3641
- else dispose();
3642
- });
3643
- function dispose() {
3644
- unsubscribe();
3645
- cacheFinalizer?.unregister(reference);
3646
- }
3647
- __name(dispose, "dispose");
3648
- return dispose;
3649
- }
3650
- get size() {
3651
- return this.entries.size;
3652
- }
3653
- /** @internal Attach or detach the persistence engine's observation sink. */
3654
- attachPersistence(sink) {
3655
- this.persistence = sink;
3656
- }
3657
- resolveKey(key) {
3658
- let resolved = key;
3659
- const seen = /* @__PURE__ */ new Set();
3660
- while (this.aliases.has(resolved) && !seen.has(resolved)) {
3661
- seen.add(resolved);
3662
- resolved = this.aliases.get(resolved);
3663
- }
3664
- return resolved;
3665
- }
3666
- get(key, now = Date.now()) {
3667
- const resolved = this.resolveKey(key);
3668
- const entry = this.entries.get(resolved);
3669
- if (!entry) return void 0;
3670
- if (entry.gcAt !== void 0 && now >= entry.gcAt) {
3671
- if (entry.fetching) return void 0;
3672
- this.entries.delete(resolved);
3673
- this.persistence?.onDelete(resolved);
3674
- this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
3675
- this.emit(resolved);
3676
- return void 0;
3677
- }
3678
- return entry;
3679
- }
3680
- set(key, entry) {
3681
- const resolved = this.resolveKey(key);
3682
- const invalidatedAt = this.invalidatedAt.get(resolved);
3683
- const nextEntry = invalidatedAt !== void 0 && invalidatedAt > entry.updatedAt ? { ...entry, staleAt: 0, invalidatedAt } : { ...entry, invalidatedAt: void 0 };
3684
- if (invalidatedAt === void 0 || entry.updatedAt >= invalidatedAt) {
3685
- this.invalidatedAt.delete(resolved);
3686
- }
3687
- this.entries.set(resolved, nextEntry);
3688
- this.pendingMetadataSweeps.delete(resolved);
3689
- if (nextEntry.gcAt !== void 0) this.scheduleGcSweep();
3690
- this.persistence?.onSet(resolved, nextEntry);
3691
- this.emit(resolved);
3692
- return this;
3693
- }
3694
- delete(key) {
3695
- const resolved = this.resolveKey(key);
3696
- const deleted = this.entries.delete(resolved);
3697
- this.inflight.delete(resolved);
3698
- if (deleted) this.persistence?.onDelete(resolved);
3699
- if (deleted || this.pendingMetadataSweeps.has(resolved)) {
3700
- this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
3701
- }
3702
- this.emit(resolved);
3703
- return deleted;
3704
- }
3705
- clear() {
3706
- const keys = /* @__PURE__ */ new Set([...this.entries.keys(), ...this.listeners.keys()]);
3707
- this.entries.clear();
3708
- this.aliases.clear();
3709
- this.aliasesByTarget.clear();
3710
- this.invalidatedAt.clear();
3711
- this.inflight.clear();
3712
- this.pendingMetadataSweeps.clear();
3713
- this.persistence?.onClear();
3714
- for (const key of keys) this.emit(key);
3715
- }
3716
- dispose() {
3717
- this.unsubscribeInvalidation?.();
3718
- this.unsubscribeInvalidation = void 0;
3719
- if (this.gcTimer !== void 0) {
3720
- clearTimeout(this.gcTimer);
3721
- this.gcTimer = void 0;
3722
- }
3723
- this.clear();
3724
- }
3725
- isStale(key, now = Date.now()) {
3726
- const entry = this.get(key, now);
3727
- return !entry || entry.invalidatedAt !== void 0 || now >= entry.staleAt;
3728
- }
3729
- invalidate(key, now = Date.now()) {
3730
- this.applyInvalidation(key, now, true);
3731
- }
3732
- applyInvalidation(key, now, retainUnowned) {
3733
- const resolved = this.resolveKey(key);
3734
- for (const keys of invalidationTrackers.get(this) ?? []) keys.add(resolved);
3735
- const entry = this.entries.get(resolved);
3736
- const alreadyRetained = this.invalidatedAt.has(resolved);
3737
- if (retainUnowned || entry || alreadyRetained || this.hasMetadataOwner(resolved)) {
3738
- this.invalidatedAt.set(resolved, now);
3739
- if (!entry && !retainUnowned && !alreadyRetained) this.pendingMetadataSweeps.add(resolved);
3740
- }
3741
- if (entry) {
3742
- this.entries.set(resolved, {
3743
- ...entry,
3744
- staleAt: 0,
3745
- invalidatedAt: now
3746
- });
3747
- }
3748
- this.emit(resolved, "invalidate");
3749
- }
3750
- hasMetadataOwner(key) {
3751
- const related = /* @__PURE__ */ new Set([key]);
3752
- for (const target of related) {
3753
- if (this.listeners.has(target) || this.inflight.has(target)) return true;
3754
- for (const alias of this.aliasesByTarget.get(target) ?? []) related.add(alias);
3755
- }
3756
- return false;
3757
- }
3758
- alias(alias, key) {
3759
- const resolved = this.resolveKey(key);
3760
- if (alias === resolved) return;
3761
- const aliasEntry = this.entries.get(alias);
3762
- const aliasInvalidatedAt = this.invalidatedAt.get(alias) ?? aliasEntry?.invalidatedAt;
3763
- const resolvedInvalidatedAt = this.invalidatedAt.get(resolved);
3764
- if (aliasEntry && !this.entries.has(resolved)) {
3765
- this.entries.set(resolved, aliasEntry);
3766
- this.persistence?.onSet(resolved, aliasEntry);
3767
- }
3768
- if (this.entries.delete(alias)) this.persistence?.onDelete(alias);
3769
- this.invalidatedAt.delete(alias);
3770
- const invalidatedAt = [aliasInvalidatedAt, resolvedInvalidatedAt].reduce(
3771
- (latest, value) => value === void 0 ? latest : latest === void 0 ? value : Math.max(latest, value),
3772
- void 0
3773
- );
3774
- const resolvedEntry = this.entries.get(resolved);
3775
- if (invalidatedAt !== void 0 && (!resolvedEntry || invalidatedAt > resolvedEntry.updatedAt)) {
3776
- this.invalidatedAt.set(resolved, invalidatedAt);
3777
- if (resolvedEntry) {
3778
- this.entries.set(resolved, {
3779
- ...resolvedEntry,
3780
- staleAt: 0,
3781
- invalidatedAt
3782
- });
3783
- }
3784
- } else if (invalidatedAt !== void 0) {
3785
- this.invalidatedAt.delete(resolved);
3786
- if (resolvedEntry?.invalidatedAt !== void 0) {
3787
- this.entries.set(resolved, { ...resolvedEntry, invalidatedAt: void 0 });
3788
- }
3789
- }
3790
- const aliasInflight = this.inflight.get(alias);
3791
- if (aliasInflight && !this.inflight.has(resolved)) {
3792
- this.inflight.set(resolved, aliasInflight);
3793
- }
3794
- this.inflight.delete(alias);
3795
- if (this.pendingMetadataSweeps.delete(alias) && !this.entries.has(resolved)) {
3796
- this.pendingMetadataSweeps.add(resolved);
3797
- }
3798
- const previousTarget = this.aliases.get(alias);
3799
- if (previousTarget !== resolved) {
3800
- const previousResolved = previousTarget !== void 0 && this.pendingMetadataSweeps.size > 0 ? this.resolveKey(alias) : void 0;
3801
- this.removeAlias(alias);
3802
- this.aliases.set(alias, resolved);
3803
- let aliases = this.aliasesByTarget.get(resolved);
3804
- if (!aliases) this.aliasesByTarget.set(resolved, aliases = /* @__PURE__ */ new Set());
3805
- aliases.add(alias);
3806
- if (previousResolved !== void 0) this.sweepPendingEntryMetadata(previousResolved);
3807
- }
3808
- this.emit(alias);
3809
- this.emit(resolved, this.invalidatedAt.has(resolved) ? "invalidate" : void 0);
3810
- }
3811
- subscribe(key, listener) {
3812
- let listeners2 = this.listeners.get(key);
3813
- if (!listeners2) {
3814
- listeners2 = /* @__PURE__ */ new Set();
3815
- this.listeners.set(key, listeners2);
3816
- }
3817
- listeners2.add(listener);
3818
- return () => {
3819
- listeners2.delete(listener);
3820
- if (listeners2.size === 0 && this.listeners.get(key) === listeners2) {
3821
- this.listeners.delete(key);
3822
- this.sweepPendingEntryMetadata(key);
3823
- }
3824
- };
3825
- }
3826
- getInflight(key) {
3827
- return this.inflight.get(this.resolveKey(key));
3828
- }
3829
- setInflight(key, promise) {
3830
- this.inflight.set(this.resolveKey(key), promise);
3831
- }
3832
- deleteInflight(key) {
3833
- const resolved = this.resolveKey(key);
3834
- if (this.inflight.delete(resolved)) this.sweepPendingEntryMetadata(resolved);
3835
- }
3836
- scheduleGcSweep() {
3837
- if (this.gcSweepIntervalMs === false || this.gcTimer !== void 0) return;
3838
- const timer = setTimeout(() => {
3839
- this.gcTimer = void 0;
3840
- this.sweepExpiredEntries();
3841
- }, this.gcSweepIntervalMs);
3842
- timer.unref?.();
3843
- this.gcTimer = timer;
3844
- }
3845
- sweepExpiredEntries(now = Date.now()) {
3846
- const watched = /* @__PURE__ */ new Set();
3847
- for (const key of this.listeners.keys()) watched.add(this.resolveKey(key));
3848
- let remaining = false;
3849
- const swept = /* @__PURE__ */ new Set();
3850
- for (const [key, entry] of this.entries) {
3851
- if (entry.gcAt === void 0) continue;
3852
- if (now < entry.gcAt || entry.fetching || this.inflight.has(key) || watched.has(key)) {
3853
- remaining = true;
3854
- continue;
3855
- }
3856
- this.entries.delete(key);
3857
- this.persistence?.onDelete(key);
3858
- swept.add(key);
3859
- }
3860
- if (swept.size > 0) this.sweepEntryMetadata(swept);
3861
- if (remaining) this.scheduleGcSweep();
3862
- }
3863
- /**
3864
- * Entry eviction alone leaves the per-key metadata behind. `invalidatedAt`
3865
- * marks and provisional aliases are created per query invocation, so with
3866
- * dynamic keys they accumulate for the lifetime of the page even though the
3867
- * entries they describe are long gone.
3868
- */
3869
- sweepEntryMetadata(swept) {
3870
- const protectedKeys = /* @__PURE__ */ new Set();
3871
- for (const key of swept) if (this.hasMetadataOwner(key)) protectedKeys.add(key);
3872
- for (const key of swept) {
3873
- if (this.entries.has(key)) {
3874
- this.pendingMetadataSweeps.delete(key);
3875
- } else if (protectedKeys.has(key)) {
3876
- this.pendingMetadataSweeps.add(key);
3877
- } else {
3878
- this.pendingMetadataSweeps.delete(key);
3879
- this.invalidatedAt.delete(key);
3880
- }
3881
- }
3882
- const related = /* @__PURE__ */ new Set();
3883
- const targets = new Set(swept);
3884
- for (const target of targets) {
3885
- for (const alias of this.aliasesByTarget.get(target) ?? []) {
3886
- related.add(alias);
3887
- targets.add(alias);
3888
- }
3889
- }
3890
- const removable = [];
3891
- for (const alias of related) {
3892
- if (this.entries.has(alias) || this.listeners.has(alias) || this.inflight.has(alias))
3893
- continue;
3894
- const resolved = this.resolveKey(alias);
3895
- if (!swept.has(resolved)) continue;
3896
- if (this.entries.has(resolved) || protectedKeys.has(resolved)) continue;
3897
- removable.push(alias);
3898
- }
3899
- for (const alias of removable) {
3900
- this.removeAlias(alias);
3901
- this.invalidatedAt.delete(alias);
3902
- }
3903
- }
3904
- removeAlias(alias) {
3905
- const target = this.aliases.get(alias);
3906
- if (target === void 0) return;
3907
- this.aliases.delete(alias);
3908
- const aliases = this.aliasesByTarget.get(target);
3909
- aliases?.delete(alias);
3910
- if (aliases?.size === 0) this.aliasesByTarget.delete(target);
3911
- }
3912
- sweepPendingEntryMetadata(key) {
3913
- if (this.pendingMetadataSweeps.size === 0) return;
3914
- if (key !== void 0) {
3915
- const resolved = this.resolveKey(key);
3916
- if (this.pendingMetadataSweeps.has(resolved)) {
3917
- this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
3918
- }
3919
- return;
3920
- }
3921
- this.sweepEntryMetadata(new Set(this.pendingMetadataSweeps));
3922
- }
3923
- emit(key, event) {
3924
- this.notifyListeners(key, event);
3925
- if (this.listeners.size === 0) return;
3926
- for (const [alias, target] of this.aliases) {
3927
- if (!this.listeners.has(alias)) continue;
3928
- if (this.resolveKey(target) === key) {
3929
- this.notifyListeners(alias, event);
3930
- }
3931
- }
3932
- }
3933
- notifyListeners(key, event) {
3934
- for (const listener of this.listeners.get(key) ?? []) {
3935
- try {
3936
- listener(event);
3937
- } catch (error) {
3938
- const detail = error instanceof Error ? error.stack ?? error.message : String(error);
3939
- console.warn(`[farm:client-cache] cache listener failed: ${detail}`);
3940
- }
3941
- }
3942
- }
3943
- };
3944
- __name(_FarmClientDataCache, "FarmClientDataCache");
3945
- var FarmClientDataCache = _FarmClientDataCache;
3946
- var FARM_CLIENT_DATA_CACHE = /* @__PURE__ */ Symbol.for("farm.clientDataCache");
3947
- var clientCacheGlobal = globalThis;
3948
- var sharedFarmClientDataCache = clientCacheGlobal[FARM_CLIENT_DATA_CACHE] ?? (clientCacheGlobal[FARM_CLIENT_DATA_CACHE] = new FarmClientDataCache());
3949
- function getFarmClientDataCache() {
3950
- return sharedFarmClientDataCache;
3951
- }
3952
- __name(getFarmClientDataCache, "getFarmClientDataCache");
3953
3
 
3954
- // src/client-revalidation.ts
3955
- function attachRevalidationListeners(refresh, options = {}) {
3956
- if (typeof window === "undefined") return () => {
3957
- };
3958
- const onFocus = options.refetchOnWindowFocus === false ? void 0 : refresh;
3959
- const onOnline = options.refetchOnReconnect === false ? void 0 : refresh;
3960
- if (onFocus) window.addEventListener("focus", onFocus);
3961
- if (onOnline) window.addEventListener("online", onOnline);
3962
- return () => {
3963
- if (onFocus) window.removeEventListener("focus", onFocus);
3964
- if (onOnline) window.removeEventListener("online", onOnline);
3965
- };
3966
- }
3967
- __name(attachRevalidationListeners, "attachRevalidationListeners");
4
+ var _chunkDYEJQTDNcjs = require('./chunk-DYEJQTDN.cjs');
3968
5
 
3969
- // src/server-query-runtime.ts
3970
- var FARM_SERVER_QUERY_CLIENT_STATE = /* @__PURE__ */ Symbol.for("farm.serverQueryClientState");
3971
- var serverQueryClientGlobal = globalThis;
3972
- var serverQueryClientState = serverQueryClientGlobal[FARM_SERVER_QUERY_CLIENT_STATE] ?? (serverQueryClientGlobal[FARM_SERVER_QUERY_CLIENT_STATE] = {
3973
- functionIds: /* @__PURE__ */ new WeakMap(),
3974
- nextFunctionId: 0,
3975
- active: [],
3976
- latestOwners: /* @__PURE__ */ new Map(),
3977
- owners: /* @__PURE__ */ new Set()
3978
- });
3979
- serverQueryClientState.latestOwners ?? (serverQueryClientState.latestOwners = /* @__PURE__ */ new Map());
3980
- serverQueryClientState.owners ?? (serverQueryClientState.owners = /* @__PURE__ */ new Set());
3981
- function isServerQueryOwnerSuperseded(owner, key) {
3982
- const cache = getFarmClientDataCache();
3983
- const resolved = cache.resolveKey(key);
3984
- for (const superseded of owner.supersededKeys ?? []) {
3985
- if (cache.resolveKey(superseded) === resolved) return true;
3986
- }
3987
- return false;
3988
- }
3989
- __name(isServerQueryOwnerSuperseded, "isServerQueryOwnerSuperseded");
3990
- function claimServerQueryKey(owner, key) {
3991
- if (isServerQueryOwnerSuperseded(owner, key)) return false;
3992
- const resolved = getFarmClientDataCache().resolveKey(key);
3993
- for (const older of serverQueryClientState.owners) {
3994
- if (older === owner) break;
3995
- older.supersededKeys.add(resolved);
3996
- }
3997
- return true;
3998
- }
3999
- __name(claimServerQueryKey, "claimServerQueryKey");
4000
- var RAW_SERVER_QUERY_SYMBOL = /* @__PURE__ */ Symbol.for("farm.server-query");
4001
- function assertNotRawServerQueryInBrowser(query) {
4002
- if (typeof window === "undefined" || typeof document === "undefined") return;
4003
- if (!query?.[RAW_SERVER_QUERY_SYMBOL]) return;
4004
- throw new Error(
4005
- [
4006
- "useServerQuery received a raw server query implementation in the browser.",
4007
- "Server query handlers run only on the server. Enable the server-function transform (add @farm.js/plugin/rsc and set experimental.serverActions: true in farm.config.ts) so client imports become server references,",
4008
- "or call the query from server code / an API route (createAPIClient) instead."
4009
- ].join("\n")
4010
- );
4011
- }
4012
- __name(assertNotRawServerQueryInBrowser, "assertNotRawServerQueryInBrowser");
4013
- function isCurrentServerQueryOwner(provisionalKey, owner) {
4014
- return serverQueryClientState.latestOwners.get(provisionalKey) === owner && !isServerQueryOwnerSuperseded(owner, provisionalKey);
4015
- }
4016
- __name(isCurrentServerQueryOwner, "isCurrentServerQueryOwner");
4017
- function createServerQueryCallKey(query, input) {
4018
- let id = serverQueryClientState.functionIds.get(query);
4019
- if (!id) {
4020
- id = ++serverQueryClientState.nextFunctionId;
4021
- serverQueryClientState.functionIds.set(query, id);
4022
- }
4023
- return createFarmCacheKey(["server-query-call", id, input]);
4024
- }
4025
- __name(createServerQueryCallKey, "createServerQueryCallKey");
4026
- async function fetchServerQuery(query, input, options = {}) {
4027
- const cache = getFarmClientDataCache();
4028
- const provisionalKey = createServerQueryCallKey(query, input);
4029
- const entry = cache.get(provisionalKey);
4030
- const stale = cache.isStale(provisionalKey);
4031
- const inflight = cache.getInflight(provisionalKey);
4032
- if (!options.force && entry && stale && (entry.status !== "pending" || entry.updatedAt !== 0) && entry.status !== "error" && (options.swr ?? true)) {
4033
- if (!inflight) {
4034
- void executeServerQuery(query, input, provisionalKey, options).catch(() => void 0);
4035
- }
4036
- return entry.data;
4037
- }
4038
- if (inflight && !options.force) return inflight;
4039
- if (!options.force && entry && !stale && entry.status !== "error") return entry.data;
4040
- return executeServerQuery(query, input, provisionalKey, options);
4041
- }
4042
- __name(fetchServerQuery, "fetchServerQuery");
4043
- async function executeServerQuery(query, input, provisionalKey, options) {
4044
- assertNotRawServerQueryInBrowser(query);
4045
- const cache = getFarmClientDataCache();
4046
- const inflight = cache.getInflight(provisionalKey);
4047
- if (inflight && !options.force) return inflight;
4048
- const owner = {
4049
- invalidations: trackFarmClientCacheInvalidations(cache),
4050
- supersededKeys: /* @__PURE__ */ new Set()
4051
- };
4052
- serverQueryClientState.latestOwners.set(provisionalKey, owner);
4053
- serverQueryClientState.owners.add(owner);
4054
- claimServerQueryKey(owner, provisionalKey);
4055
- const previous = cache.get(provisionalKey);
4056
- cache.set(provisionalKey, {
4057
- data: previous?.data,
4058
- updatedAt: previous?.updatedAt ?? 0,
4059
- staleAt: previous?.staleAt ?? 0,
4060
- gcAt: previous?.gcAt,
4061
- invalidatedAt: previous?.invalidatedAt,
4062
- status: "pending",
4063
- error: null,
4064
- fetching: true
4065
- });
4066
- let promise;
4067
- promise = (async () => {
4068
- await Promise.resolve();
4069
- try {
4070
- serverQueryClientState.active.push({ provisionalKey, owner });
4071
- let pending;
4072
- try {
4073
- pending = query(input);
4074
- } finally {
4075
- serverQueryClientState.active.pop();
4076
- }
4077
- const data = await pending;
4078
- const transported = cache.get(provisionalKey);
4079
- if (isCurrentServerQueryOwner(provisionalKey, owner) && (!transported || transported.fetching)) {
4080
- const updatedAt = Date.now();
4081
- cache.set(provisionalKey, {
4082
- data,
4083
- updatedAt,
4084
- staleAt: owner.invalidations.has(provisionalKey) ? 0 : options.staleTime === false ? Number.POSITIVE_INFINITY : updatedAt + (options.staleTime ?? 0),
4085
- status: "success",
4086
- error: null,
4087
- fetching: false
4088
- });
4089
- }
4090
- return data;
4091
- } catch (cause) {
4092
- const error = normalizeServerQueryError(cause);
4093
- if (isCurrentServerQueryOwner(provisionalKey, owner)) {
4094
- const current = cache.get(provisionalKey);
4095
- cache.set(provisionalKey, {
4096
- data: current?.data,
4097
- updatedAt: current?.updatedAt ?? 0,
4098
- staleAt: current?.staleAt ?? 0,
4099
- gcAt: current?.gcAt,
4100
- invalidatedAt: current?.invalidatedAt,
4101
- status: "error",
4102
- error,
4103
- fetching: false
4104
- });
4105
- }
4106
- throw error;
4107
- } finally {
4108
- const invalidated = isCurrentServerQueryOwner(provisionalKey, owner) && owner.invalidations.has(provisionalKey);
4109
- owner.invalidations.dispose();
4110
- serverQueryClientState.owners.delete(owner);
4111
- owner.supersededKeys.clear();
4112
- if (cache.getInflight(provisionalKey) === promise) {
4113
- cache.deleteInflight(provisionalKey);
4114
- }
4115
- if (serverQueryClientState.latestOwners.get(provisionalKey) === owner) {
4116
- serverQueryClientState.latestOwners.delete(provisionalKey);
4117
- }
4118
- if (invalidated) cache.invalidate(provisionalKey);
4119
- }
4120
- })();
4121
- cache.setInflight(provisionalKey, promise);
4122
- return promise;
4123
- }
4124
- __name(executeServerQuery, "executeServerQuery");
4125
- function normalizeServerQueryError(cause) {
4126
- if (cause instanceof Error) return cause;
4127
- const error = new Error(typeof cause === "string" ? cause : "Server query failed");
4128
- error.cause = cause;
4129
- return error;
4130
- }
4131
- __name(normalizeServerQueryError, "normalizeServerQueryError");
4132
6
 
4133
- // src/theme/runtime.ts
4134
- var FALLBACK_CLIENT_SNAPSHOT = Object.freeze({
4135
- theme: "system",
4136
- resolvedTheme: "light",
4137
- mounted: true
4138
- });
4139
- var cachedClientSnapshot = FALLBACK_CLIENT_SNAPSHOT;
4140
- function snapshotsMatch(left, right) {
4141
- return left.theme === right.theme && left.resolvedTheme === right.resolvedTheme && left.mounted === right.mounted;
4142
- }
4143
- __name(snapshotsMatch, "snapshotsMatch");
4144
- function getTheme() {
4145
- const next = typeof window === "undefined" ? FALLBACK_CLIENT_SNAPSHOT : window.__FARM_THEME__?.snapshot;
4146
- if (!next) return cachedClientSnapshot;
4147
- if (!snapshotsMatch(cachedClientSnapshot, next)) cachedClientSnapshot = next;
4148
- return cachedClientSnapshot;
4149
- }
4150
- __name(getTheme, "getTheme");
4151
- function setTheme(theme) {
4152
- const runtime3 = typeof window === "undefined" ? void 0 : window.__FARM_THEME__;
4153
- if (!runtime3) {
4154
- throw new Error("The FARMJS theme runtime is not enabled. Add `theme` to farm.config.ts.");
4155
- }
4156
- runtime3.setTheme(theme);
4157
- }
4158
- __name(setTheme, "setTheme");
4159
- function toggleTheme() {
4160
- const next = getTheme().resolvedTheme === "dark" ? "light" : "dark";
4161
- setTheme(next);
4162
- return next;
4163
- }
4164
- __name(toggleTheme, "toggleTheme");
4165
- function subscribeTheme(listener) {
4166
- if (typeof window === "undefined") return () => {
4167
- };
4168
- const handleThemeChange = /* @__PURE__ */ __name(() => {
4169
- getTheme();
4170
- listener();
4171
- }, "handleThemeChange");
4172
- window.addEventListener("farm:themechange", handleThemeChange);
4173
- return () => window.removeEventListener("farm:themechange", handleThemeChange);
4174
- }
4175
- __name(subscribeTheme, "subscribeTheme");
4176
7
 
4177
- // src/i18n/resolver.ts
4178
- function createFarmLocaleCookie(locale, config) {
4179
- const cookie = config.cookie;
4180
- let value = `${encodeURIComponent(cookie.name)}=${encodeURIComponent(locale)}`;
4181
- value += `; Max-Age=${cookie.maxAge}`;
4182
- value += `; Path=${cookie.path}`;
4183
- value += `; SameSite=${capitalize(cookie.sameSite)}`;
4184
- if (cookie.secure) value += "; Secure";
4185
- return value;
4186
- }
4187
- __name(createFarmLocaleCookie, "createFarmLocaleCookie");
4188
- function capitalize(value) {
4189
- return value.charAt(0).toUpperCase() + value.slice(1);
4190
- }
4191
- __name(capitalize, "capitalize");
4192
8
 
4193
- // src/i18n/client-runtime.ts
4194
- var import_intl_messageformat = __toESM(require("intl-messageformat"));
4195
- var readOwnMessage = /* @__PURE__ */ __name((messages, key) => Object.prototype.hasOwnProperty.call(messages, key) ? messages[key] : void 0, "readOwnMessage");
4196
- var translate = /* @__PURE__ */ __name((key, values, rich = false) => {
4197
- const snapshot = requireSnapshot();
4198
- const message = readOwnMessage(snapshot.messages, key);
4199
- if (message === void 0) return key;
4200
- const cacheKey = `${snapshot.locale}\0${key}\0${message}`;
4201
- let formatter = compiledFarmI18nMessages.get(cacheKey);
4202
- if (!formatter) {
4203
- formatter = new import_intl_messageformat.default(message, snapshot.locale);
4204
- compiledFarmI18nMessages.set(cacheKey, formatter);
4205
- }
4206
- const result = formatter.format(values);
4207
- if (rich) return Array.isArray(result) && result.length === 1 ? result[0] : result;
4208
- if (Array.isArray(result) && result.some((part) => typeof part !== "string")) {
4209
- throw new Error(`Farm i18n message "${key}" contains rich content. Render it with t.rich().`);
4210
- }
4211
- return Array.isArray(result) ? result.join("") : String(result);
4212
- }, "translate");
4213
- var t = /* @__PURE__ */ __name(((key, values) => translate(key, values)), "t");
4214
- t.rich = (key, values) => translate(key, values, true);
4215
- t.raw = (key) => readOwnMessage(requireSnapshot().messages, key) ?? key;
4216
- t.has = (key) => Object.prototype.hasOwnProperty.call(requireSnapshot().messages, key);
4217
- function createFarmClientTranslator() {
4218
- return ((key, ...args) => t(key, ...args));
4219
- }
4220
- __name(createFarmClientTranslator, "createFarmClientTranslator");
4221
- function requireSnapshot() {
4222
- const snapshot = getFarmI18nClientState();
4223
- if (!snapshot) {
4224
- throw new Error("Farm i18n is not configured or has not been hydrated.");
4225
- }
4226
- return snapshot;
4227
- }
4228
- __name(requireSnapshot, "requireSnapshot");
9
+ var _chunkY4YWHNKUcjs = require('./chunk-Y4YWHNKU.cjs');
10
+
11
+
12
+
13
+
14
+
15
+ var _chunkFK6GO24Vcjs = require('./chunk-FK6GO24V.cjs');
16
+
17
+
18
+ var _chunkSU7MH53Pcjs = require('./chunk-SU7MH53P.cjs');
19
+ require('./chunk-PCOTGFSM.cjs');
20
+
21
+
22
+
23
+
24
+ var _chunkWJ3HK3LJcjs = require('./chunk-WJ3HK3LJ.cjs');
25
+
26
+
27
+
28
+ var _chunk5OVTOKGHcjs = require('./chunk-5OVTOKGH.cjs');
29
+ require('./chunk-R5A5KNVX.cjs');
30
+ require('./chunk-SWN467MP.cjs');
31
+
32
+
33
+ var _chunkI7PUUDGYcjs = require('./chunk-I7PUUDGY.cjs');
34
+ require('./chunk-J7FSKED3.cjs');
35
+ require('./chunk-SK35NQKK.cjs');
36
+
37
+
38
+ var _chunk75BRBIFPcjs = require('./chunk-75BRBIFP.cjs');
39
+ require('./chunk-OXSIH4D6.cjs');
40
+ require('./chunk-R5JIFR6B.cjs');
41
+ require('./chunk-C5GUTBZK.cjs');
42
+ require('./chunk-QBK2AA4U.cjs');
43
+ require('./chunk-H6G5INWM.cjs');
44
+ require('./chunk-ZEG3OPIB.cjs');
45
+ require('./chunk-LIUGYUX3.cjs');
46
+ require('./chunk-E3UK5IIB.cjs');
47
+
48
+
49
+
50
+ var _chunkBIDYX3SLcjs = require('./chunk-BIDYX3SL.cjs');
51
+
52
+
53
+
54
+
55
+
56
+ var _chunkI57LW5VZcjs = require('./chunk-I57LW5VZ.cjs');
57
+ require('./chunk-NO3WWW3N.cjs');
58
+
59
+
60
+ var _chunkS3JO3N4Hcjs = require('./chunk-S3JO3N4H.cjs');
4229
61
 
4230
62
  // src/renderer-client.ts
4231
63
  function createRendererRouter(options = {}) {
4232
- const basePath = options.basePath === void 0 ? getFarmBasePath() : normalizeFarmBasePath(options.basePath);
4233
- const matcher = options.routes?.length ? createFarmRouter([...options.routes]) : null;
4234
- const router = getRouter();
64
+ const basePath = options.basePath === void 0 ? _chunkI57LW5VZcjs.getFarmBasePath.call(void 0, ) : _chunkI57LW5VZcjs.normalizeFarmBasePath.call(void 0, options.basePath);
65
+ const matcher = _optionalChain([options, 'access', _ => _.routes, 'optionalAccess', _2 => _2.length]) ? _chunkSU7MH53Pcjs.createFarmRouter.call(void 0, [...options.routes]) : null;
66
+ const router = _chunkWJ3HK3LJcjs.getRouter.call(void 0, );
4235
67
  let snapshot = readRendererRouterSnapshot(basePath, matcher, router.getNavigationState());
4236
- const read = /* @__PURE__ */ __name(() => {
68
+ const read = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => {
4237
69
  snapshot = readRendererRouterSnapshot(basePath, matcher, router.getNavigationState());
4238
70
  return snapshot;
4239
71
  }, "read");
4240
72
  return {
4241
- getSnapshot: /* @__PURE__ */ __name(() => snapshot, "getSnapshot"),
73
+ getSnapshot: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => snapshot, "getSnapshot"),
4242
74
  subscribe(listener) {
4243
75
  if (typeof window === "undefined") return () => {
4244
76
  };
4245
- const notify = /* @__PURE__ */ __name(() => {
77
+ const notify = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => {
4246
78
  read();
4247
79
  listener();
4248
80
  }, "notify");
4249
81
  const unsubscribeNavigation = router.subscribeNavigation(notify);
4250
- const unsubscribeHistory = subscribeHistoryChange(notify);
82
+ const unsubscribeHistory = _chunkWJ3HK3LJcjs.subscribeHistoryChange.call(void 0, notify);
4251
83
  read();
4252
84
  return () => {
4253
85
  unsubscribeNavigation();
@@ -4263,8 +95,8 @@ function createRendererRouter(options = {}) {
4263
95
  replace: true
4264
96
  });
4265
97
  },
4266
- refresh: /* @__PURE__ */ __name((refreshOptions) => typeof window === "undefined" ? Promise.resolve() : router.refresh(refreshOptions), "refresh"),
4267
- prefetch: /* @__PURE__ */ __name((href) => typeof window === "undefined" ? Promise.resolve() : router.prefetch(resolveRendererHref(href, basePath)), "prefetch"),
98
+ refresh: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (refreshOptions) => typeof window === "undefined" ? Promise.resolve() : router.refresh(refreshOptions), "refresh"),
99
+ prefetch: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (href) => typeof window === "undefined" ? Promise.resolve() : router.prefetch(resolveRendererHref(href, basePath)), "prefetch"),
4268
100
  back() {
4269
101
  if (typeof window !== "undefined") window.history.back();
4270
102
  },
@@ -4285,11 +117,11 @@ function createRendererRouter(options = {}) {
4285
117
  }
4286
118
  };
4287
119
  }
4288
- __name(createRendererRouter, "createRendererRouter");
120
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createRendererRouter, "createRendererRouter");
4289
121
  function createRendererAction(target, options = {}) {
4290
122
  const serverFn = resolveRendererServerFn(target);
4291
- const listeners2 = /* @__PURE__ */ new Set();
4292
- const initialResult = options.initialResult ?? null;
123
+ const listeners = /* @__PURE__ */ new Set();
124
+ const initialResult = _nullishCoalesce(options.initialResult, () => ( null));
4293
125
  let requestId = 0;
4294
126
  let pendingCount = 0;
4295
127
  let latestSettledStatus = "idle";
@@ -4299,21 +131,21 @@ function createRendererAction(target, options = {}) {
4299
131
  data: initialResult,
4300
132
  error: null
4301
133
  };
4302
- const update = /* @__PURE__ */ __name((next) => {
134
+ const update = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (next) => {
4303
135
  snapshot = next;
4304
- for (const listener of listeners2) listener();
136
+ for (const listener of listeners) listener();
4305
137
  }, "update");
4306
138
  return {
4307
- getSnapshot: /* @__PURE__ */ __name(() => snapshot, "getSnapshot"),
139
+ getSnapshot: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => snapshot, "getSnapshot"),
4308
140
  subscribe(listener) {
4309
- listeners2.add(listener);
4310
- return () => listeners2.delete(listener);
141
+ listeners.add(listener);
142
+ return () => listeners.delete(listener);
4311
143
  },
4312
144
  async submit(input) {
4313
145
  const currentRequest = ++requestId;
4314
146
  const previous = snapshot.data;
4315
147
  const formData = isRendererFormData(input) ? input : void 0;
4316
- const optimistic = options.optimistic?.({ input, formData, current: previous });
148
+ const optimistic = _optionalChain([options, 'access', _3 => _3.optimistic, 'optionalCall', _4 => _4({ input, formData, current: previous })]);
4317
149
  const hasOptimistic = optimistic !== void 0;
4318
150
  pendingCount += 1;
4319
151
  update({
@@ -4333,8 +165,8 @@ function createRendererAction(target, options = {}) {
4333
165
  data: result,
4334
166
  error: null
4335
167
  });
4336
- options.onSuccess?.(result);
4337
- options.onSettled?.(result, null);
168
+ _optionalChain([options, 'access', _5 => _5.onSuccess, 'optionalCall', _6 => _6(result)]);
169
+ _optionalChain([options, 'access', _7 => _7.onSettled, 'optionalCall', _8 => _8(result, null)]);
4338
170
  } else if (pendingCount === 0) {
4339
171
  update({ ...snapshot, pending: false, status: latestSettledStatus });
4340
172
  }
@@ -4350,8 +182,8 @@ function createRendererAction(target, options = {}) {
4350
182
  data: hasOptimistic && options.rollbackOnError ? previous : options.resetOnSubmit === false ? snapshot.data : null,
4351
183
  error
4352
184
  });
4353
- options.onError?.(error);
4354
- options.onSettled?.(null, error);
185
+ _optionalChain([options, 'access', _9 => _9.onError, 'optionalCall', _10 => _10(error)]);
186
+ _optionalChain([options, 'access', _11 => _11.onSettled, 'optionalCall', _12 => _12(null, error)]);
4355
187
  } else if (pendingCount === 0) {
4356
188
  update({ ...snapshot, pending: false, status: latestSettledStatus });
4357
189
  }
@@ -4366,21 +198,21 @@ function createRendererAction(target, options = {}) {
4366
198
  }
4367
199
  };
4368
200
  }
4369
- __name(createRendererAction, "createRendererAction");
201
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createRendererAction, "createRendererAction");
4370
202
  function createRendererQuery(query, input, options = {}) {
4371
- const cache = getFarmClientDataCache();
4372
- const key = createServerQueryCallKey(query, input);
4373
- const listeners2 = /* @__PURE__ */ new Set();
203
+ const cache = _chunkI7PUUDGYcjs.getFarmClientDataCache.call(void 0, );
204
+ const key = _chunkY4YWHNKUcjs.createServerQueryCallKey.call(void 0, query, input);
205
+ const listeners = /* @__PURE__ */ new Set();
4374
206
  let unsubscribeCache;
4375
207
  let cleanupBrowser;
4376
- const run = /* @__PURE__ */ __name((force = false) => fetchServerQuery(query, input, { ...options, force }), "run");
4377
- const ensureStarted = /* @__PURE__ */ __name(() => {
208
+ const run = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (force = false) => _chunkY4YWHNKUcjs.fetchServerQuery.call(void 0, query, input, { ...options, force }), "run");
209
+ const ensureStarted = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => {
4378
210
  if (options.enabled === false || unsubscribeCache) return;
4379
211
  unsubscribeCache = cache.subscribe(key, () => {
4380
- for (const listener of listeners2) listener();
212
+ for (const listener of listeners) listener();
4381
213
  });
4382
214
  if (!cache.get(key) || cache.isStale(key)) void run().catch(() => void 0);
4383
- cleanupBrowser = attachRevalidationListeners(
215
+ cleanupBrowser = _chunkY4YWHNKUcjs.attachRevalidationListeners.call(void 0,
4384
216
  () => {
4385
217
  if (cache.isStale(key)) void run().catch(() => void 0);
4386
218
  },
@@ -4393,60 +225,60 @@ function createRendererQuery(query, input, options = {}) {
4393
225
  return {
4394
226
  getSnapshot() {
4395
227
  const entry = cache.get(key);
4396
- const status = entry?.status ?? (entry ? "success" : "idle");
228
+ const status = _nullishCoalesce(_optionalChain([entry, 'optionalAccess', _13 => _13.status]), () => ( (entry ? "success" : "idle")));
4397
229
  return {
4398
- data: entry?.data,
4399
- error: entry?.error ?? null,
230
+ data: _optionalChain([entry, 'optionalAccess', _14 => _14.data]),
231
+ error: _nullishCoalesce(_optionalChain([entry, 'optionalAccess', _15 => _15.error]), () => ( null)),
4400
232
  status,
4401
- pending: status === "pending" && (entry?.updatedAt ?? 0) === 0,
4402
- fetching: entry?.fetching ?? false,
233
+ pending: status === "pending" && (_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _16 => _16.updatedAt]), () => ( 0))) === 0,
234
+ fetching: _nullishCoalesce(_optionalChain([entry, 'optionalAccess', _17 => _17.fetching]), () => ( false)),
4403
235
  stale: cache.isStale(key)
4404
236
  };
4405
237
  },
4406
238
  subscribe(listener) {
4407
- listeners2.add(listener);
239
+ listeners.add(listener);
4408
240
  ensureStarted();
4409
- return () => listeners2.delete(listener);
241
+ return () => listeners.delete(listener);
4410
242
  },
4411
- refetch: /* @__PURE__ */ __name(() => run(true), "refetch"),
243
+ refetch: /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, () => run(true), "refetch"),
4412
244
  dispose() {
4413
- unsubscribeCache?.();
4414
- cleanupBrowser?.();
245
+ _optionalChain([unsubscribeCache, 'optionalCall', _18 => _18()]);
246
+ _optionalChain([cleanupBrowser, 'optionalCall', _19 => _19()]);
4415
247
  unsubscribeCache = void 0;
4416
248
  cleanupBrowser = void 0;
4417
- listeners2.clear();
249
+ listeners.clear();
4418
250
  }
4419
251
  };
4420
252
  }
4421
- __name(createRendererQuery, "createRendererQuery");
253
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createRendererQuery, "createRendererQuery");
4422
254
  function createRendererTheme() {
4423
255
  return {
4424
- getSnapshot: getTheme,
4425
- subscribe: subscribeTheme,
4426
- setTheme,
4427
- toggleTheme
256
+ getSnapshot: _chunkFK6GO24Vcjs.getTheme,
257
+ subscribe: _chunkFK6GO24Vcjs.subscribeTheme,
258
+ setTheme: _chunkFK6GO24Vcjs.setTheme,
259
+ toggleTheme: _chunkFK6GO24Vcjs.toggleTheme
4428
260
  };
4429
261
  }
4430
- __name(createRendererTheme, "createRendererTheme");
262
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createRendererTheme, "createRendererTheme");
4431
263
  function createRendererI18n() {
4432
264
  return {
4433
- getSnapshot: getFarmI18nClientState,
4434
- subscribe: subscribeFarmI18n,
4435
- t: createFarmClientTranslator(),
265
+ getSnapshot: _chunk5OVTOKGHcjs.getFarmI18nClientState,
266
+ subscribe: _chunk5OVTOKGHcjs.subscribeFarmI18n,
267
+ t: _chunkDYEJQTDNcjs.createFarmClientTranslator.call(void 0, ),
4436
268
  setLocale(locale) {
4437
- const snapshot = getFarmI18nClientState();
269
+ const snapshot = _chunk5OVTOKGHcjs.getFarmI18nClientState.call(void 0, );
4438
270
  if (!snapshot) throw new Error("Farm i18n is not configured or has not been hydrated.");
4439
271
  if (!snapshot.locales.includes(locale)) {
4440
272
  throw new Error(`Unsupported Farm i18n locale "${locale}".`);
4441
273
  }
4442
274
  if (typeof window === "undefined") return;
4443
- document.cookie = createFarmLocaleCookie(locale, { cookie: snapshot.cookie });
275
+ document.cookie = _chunk75BRBIFPcjs.createFarmLocaleCookie.call(void 0, locale, { cookie: snapshot.cookie });
4444
276
  const href = `${window.location.pathname}${window.location.search}${window.location.hash}`;
4445
- window.location.assign(localizeFarmHref(href, locale, snapshot));
277
+ window.location.assign(_chunkBIDYX3SLcjs.localizeFarmHref.call(void 0, href, locale, snapshot));
4446
278
  }
4447
279
  };
4448
280
  }
4449
- __name(createRendererI18n, "createRendererI18n");
281
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createRendererI18n, "createRendererI18n");
4450
282
  function readRendererRouterSnapshot(basePath, matcher, navigation) {
4451
283
  if (typeof window === "undefined") {
4452
284
  return {
@@ -4458,22 +290,22 @@ function readRendererRouterSnapshot(basePath, matcher, navigation) {
4458
290
  };
4459
291
  }
4460
292
  const url = new URL(window.location.href);
4461
- const pathname = stripFarmBasePath(url.pathname, basePath);
4462
- const i18n = getFarmI18nClientState();
4463
- const routePathname = i18n ? stripFarmLocaleFromPathname(pathname, i18n) : pathname;
293
+ const pathname = _chunkI57LW5VZcjs.stripFarmBasePath.call(void 0, url.pathname, basePath);
294
+ const i18n = _chunk5OVTOKGHcjs.getFarmI18nClientState.call(void 0, );
295
+ const routePathname = i18n ? _chunkBIDYX3SLcjs.stripFarmLocaleFromPathname.call(void 0, pathname, i18n) : pathname;
4464
296
  return {
4465
297
  pathname,
4466
298
  searchParams: url.searchParams,
4467
- params: matcher?.match(routePathname)?.params || {},
4468
- pageState: readPageState(),
299
+ params: _optionalChain([matcher, 'optionalAccess', _20 => _20.match, 'call', _21 => _21(routePathname), 'optionalAccess', _22 => _22.params]) || {},
300
+ pageState: _chunkWJ3HK3LJcjs.readPageState.call(void 0, ),
4469
301
  navigation
4470
302
  };
4471
303
  }
4472
- __name(readRendererRouterSnapshot, "readRendererRouterSnapshot");
304
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readRendererRouterSnapshot, "readRendererRouterSnapshot");
4473
305
  function resolveRendererHref(href, basePath) {
4474
- return applyFarmBasePath(href, basePath);
306
+ return _chunkI57LW5VZcjs.applyFarmBasePath.call(void 0, href, basePath);
4475
307
  }
4476
- __name(resolveRendererHref, "resolveRendererHref");
308
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveRendererHref, "resolveRendererHref");
4477
309
  function resolveRendererServerFn(target) {
4478
310
  if (typeof target === "function") return target;
4479
311
  if (target && typeof target.action === "function") return target.action;
@@ -4481,23 +313,22 @@ function resolveRendererServerFn(target) {
4481
313
  "createRendererAction requires a server function or a route with a declared action"
4482
314
  );
4483
315
  }
4484
- __name(resolveRendererServerFn, "resolveRendererServerFn");
316
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveRendererServerFn, "resolveRendererServerFn");
4485
317
  function normalizeRendererClientError(cause) {
4486
318
  if (cause instanceof Error) return cause;
4487
319
  const error = new Error(typeof cause === "string" ? cause : "FARMJS client operation failed");
4488
320
  error.cause = cause;
4489
321
  return error;
4490
322
  }
4491
- __name(normalizeRendererClientError, "normalizeRendererClientError");
323
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeRendererClientError, "normalizeRendererClientError");
4492
324
  function isRendererFormData(value) {
4493
325
  return typeof FormData !== "undefined" && value instanceof FormData;
4494
326
  }
4495
- __name(isRendererFormData, "isRendererFormData");
4496
- // Annotate the CommonJS export names for ESM import in node:
4497
- 0 && (module.exports = {
4498
- createRendererAction,
4499
- createRendererI18n,
4500
- createRendererQuery,
4501
- createRendererRouter,
4502
- createRendererTheme
4503
- });
327
+ _chunkS3JO3N4Hcjs.__name.call(void 0, isRendererFormData, "isRendererFormData");
328
+
329
+
330
+
331
+
332
+
333
+
334
+ exports.createRendererAction = createRendererAction; exports.createRendererI18n = createRendererI18n; exports.createRendererQuery = createRendererQuery; exports.createRendererRouter = createRendererRouter; exports.createRendererTheme = createRendererTheme;