@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,899 +1,30 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
20
2
 
21
- // src/server-plugins.ts
22
- var server_plugins_exports = {};
23
- __export(server_plugins_exports, {
24
- createCompressionPlugin: () => createCompressionPlugin,
25
- createEnvPlugin: () => createEnvPlugin,
26
- createHeadersPlugin: () => createHeadersPlugin,
27
- createLoggerPlugin: () => createLoggerPlugin,
28
- createRedirectsPlugin: () => createRedirectsPlugin,
29
- createRewritesPlugin: () => createRewritesPlugin
30
- });
31
- module.exports = __toCommonJS(server_plugins_exports);
32
3
 
33
- // src/navigation-errors.ts
34
- function isFarmRedirectStatus(status) {
35
- return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
36
- }
37
- __name(isFarmRedirectStatus, "isFarmRedirectStatus");
38
4
 
39
- // src/redirect-query.ts
40
- function appendFarmRedirectQuery(destination, search) {
41
- if (!search || search === "?") return destination;
42
- const hashIndex = destination.indexOf("#");
43
- const pathAndQuery = hashIndex === -1 ? destination : destination.slice(0, hashIndex);
44
- if (pathAndQuery.includes("?")) return destination;
45
- if (hashIndex === -1) return `${destination}${search}`;
46
- return `${pathAndQuery}${search}${destination.slice(hashIndex)}`;
47
- }
48
- __name(appendFarmRedirectQuery, "appendFarmRedirectQuery");
49
5
 
50
- // src/server/request.ts
51
- var import_node_async_hooks = require("async_hooks");
52
- var import_node_stream = require("stream");
6
+ var _chunkQZRVZSPNcjs = require('./chunk-QZRVZSPN.cjs');
53
7
 
54
- // src/server/request-bridge.ts
55
- var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
56
- function getGlobalState() {
57
- return globalThis;
58
- }
59
- __name(getGlobalState, "getGlobalState");
60
- function _setCurrentRequestResolver(resolver) {
61
- getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;
62
- }
63
- __name(_setCurrentRequestResolver, "_setCurrentRequestResolver");
64
8
 
65
- // src/server/request.ts
66
- var REQUEST_STORAGE_KEY = /* @__PURE__ */ Symbol.for("@farm.js/core/request-storage");
67
- function getRequestStore() {
68
- const runtime = globalThis;
69
- const existing = runtime[REQUEST_STORAGE_KEY];
70
- if (existing instanceof import_node_async_hooks.AsyncLocalStorage) {
71
- return existing;
72
- }
73
- const storage = new import_node_async_hooks.AsyncLocalStorage();
74
- runtime[REQUEST_STORAGE_KEY] = storage;
75
- return storage;
76
- }
77
- __name(getRequestStore, "getRequestStore");
78
- var requestStore = getRequestStore();
79
- _setCurrentRequestResolver(() => requestStore.getStore());
80
- function resolveFarmRequestURL(req, options = {}) {
81
- if (options.origin) {
82
- return new URL(req.url || "/", options.origin);
83
- }
84
- const forwardedHost = options.trustProxy ? firstForwardedHeaderValue(req.headers["x-forwarded-host"]) : void 0;
85
- const fallbackHost = firstForwardedHeaderValue(req.headers.host) || "localhost";
86
- const forwardedProto = options.trustProxy ? firstForwardedHeaderValue(req.headers["x-forwarded-proto"]) : void 0;
87
- const normalizedProto = forwardedProto?.toLowerCase();
88
- const proto = normalizedProto === "https" || normalizedProto === "http" ? normalizedProto : isEncryptedFarmRequest(req) ? "https" : "http";
89
- return new URL(req.url || "/", resolveRequestOrigin(proto, forwardedHost, fallbackHost));
90
- }
91
- __name(resolveFarmRequestURL, "resolveFarmRequestURL");
92
- function isEncryptedFarmRequest(req) {
93
- return Boolean(req.socket?.encrypted);
94
- }
95
- __name(isEncryptedFarmRequest, "isEncryptedFarmRequest");
96
- function firstForwardedHeaderValue(value) {
97
- const first = Array.isArray(value) ? value[0] : value;
98
- const token = first?.split(",", 1)[0]?.trim();
99
- return token || void 0;
100
- }
101
- __name(firstForwardedHeaderValue, "firstForwardedHeaderValue");
102
- function resolveRequestOrigin(proto, host, fallback) {
103
- for (const candidate of [host, fallback, "localhost"]) {
104
- if (!candidate) continue;
105
- if (/[\s/?#@\\]/u.test(candidate)) continue;
106
- try {
107
- const url = new URL(`${proto}://${candidate}`);
108
- if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) continue;
109
- return url.origin;
110
- } catch {
111
- }
112
- }
113
- return `${proto}://localhost`;
114
- }
115
- __name(resolveRequestOrigin, "resolveRequestOrigin");
9
+ var _chunkR6AIILIIcjs = require('./chunk-R6AIILII.cjs');
116
10
 
117
- // src/base-path.ts
118
- var FARM_BASE_PATH = /* @__PURE__ */ Symbol.for("farm.basePath");
119
- function getFarmGlobalState() {
120
- return globalThis;
121
- }
122
- __name(getFarmGlobalState, "getFarmGlobalState");
123
- function getFarmBasePath() {
124
- return getFarmGlobalState()[FARM_BASE_PATH] ?? "";
125
- }
126
- __name(getFarmBasePath, "getFarmBasePath");
127
- function applyFarmBasePath(href, basePath = getFarmBasePath()) {
128
- const normalizedBasePath = normalizeFarmBasePath(basePath);
129
- if (!normalizedBasePath || !href.startsWith("/") || href.startsWith("//")) return href;
130
- const canonicalHref = canonicalizeAppRelativeHref(href);
131
- if (canonicalHref === normalizedBasePath || canonicalHref.startsWith(`${normalizedBasePath}/`) || canonicalHref.startsWith(`${normalizedBasePath}?`) || canonicalHref.startsWith(`${normalizedBasePath}#`)) {
132
- return canonicalHref;
133
- }
134
- return `${normalizedBasePath}${canonicalHref}`;
135
- }
136
- __name(applyFarmBasePath, "applyFarmBasePath");
137
- function canonicalizeAppRelativeHref(href) {
138
- const origin = "http://farm.local";
139
- const resolved = new URL(href, origin);
140
- if (resolved.origin !== origin) {
141
- throw new Error("Farm app-relative href cannot change the URL origin.");
142
- }
143
- return `${resolved.pathname}${resolved.search}${resolved.hash}`;
144
- }
145
- __name(canonicalizeAppRelativeHref, "canonicalizeAppRelativeHref");
146
- function stripFarmBasePath(pathname, basePath = getFarmBasePath()) {
147
- const normalizedBasePath = normalizeFarmBasePath(basePath);
148
- if (!normalizedBasePath) return pathname || "/";
149
- if (pathname === normalizedBasePath) return "/";
150
- if (!pathname.startsWith(`${normalizedBasePath}/`)) return pathname || "/";
151
- return pathname.slice(normalizedBasePath.length) || "/";
152
- }
153
- __name(stripFarmBasePath, "stripFarmBasePath");
154
- function normalizeFarmBasePath(basePath) {
155
- if (!basePath || basePath === "/") return "";
156
- const hasUnstableCharacters = /* @__PURE__ */ __name((candidate) => candidate.includes("\\") || Array.from(candidate).some((character) => {
157
- const code = character.charCodeAt(0);
158
- return code <= 31 || code >= 127 && code <= 159;
159
- }), "hasUnstableCharacters");
160
- if (hasUnstableCharacters(basePath)) {
161
- throw new Error("Farm basePath cannot contain backslashes or control characters.");
162
- }
163
- const pathname = basePath.trim();
164
- if (!pathname || pathname === "/") return "";
165
- if (pathname.includes("?") || pathname.includes("#")) {
166
- throw new Error("Farm basePath cannot contain a query string or hash.");
167
- }
168
- if (pathname.startsWith("//") || /^[a-z][a-z\d+.-]*:\/\//i.test(pathname)) {
169
- throw new Error('Farm basePath must be a pathname such as "/docs", not a URL.');
170
- }
171
- for (const segment of pathname.split("/")) {
172
- let decoded = segment;
173
- try {
174
- decoded = decodeURIComponent(segment);
175
- } catch {
176
- }
177
- if (hasUnstableCharacters(decoded)) {
178
- throw new Error("Farm basePath cannot contain backslashes or control characters.");
179
- }
180
- if (decoded.includes("/")) {
181
- throw new Error("Farm basePath cannot contain percent-encoded path separators.");
182
- }
183
- if (decoded === "." || decoded === "..") {
184
- throw new Error('Farm basePath cannot contain "." or ".." path segments.');
185
- }
186
- }
187
- return `/${pathname}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
188
- }
189
- __name(normalizeFarmBasePath, "normalizeFarmBasePath");
190
11
 
191
- // src/i18n/routing.ts
192
- function resolveFarmLocalePath(pathname, config) {
193
- const normalized = normalizePathname(stripFarmBasePath(pathname, config.basePath));
194
- if (config.routing === "none") {
195
- return { pathname: normalized, explicit: false };
196
- }
197
- const segments = normalized.split("/").filter(Boolean);
198
- const firstSegment = segments[0];
199
- const locale = config.locales.find(
200
- (candidate) => candidate.toLowerCase() === firstSegment?.toLowerCase()
201
- );
202
- if (!locale) {
203
- return { pathname: normalized, explicit: false };
204
- }
205
- const remaining = segments.slice(1);
206
- return {
207
- locale,
208
- pathname: remaining.length > 0 ? `/${remaining.join("/")}` : "/",
209
- explicit: true
210
- };
211
- }
212
- __name(resolveFarmLocalePath, "resolveFarmLocalePath");
213
- function localizeFarmPathname(pathname, locale, config) {
214
- const internalPathname = resolveFarmLocalePath(pathname, config).pathname;
215
- let localizedPathname = internalPathname;
216
- if (config.routing === "none") {
217
- return applyFarmBasePath(localizedPathname, config.basePath);
218
- }
219
- if (config.routing === "prefix-except-default" && locale === config.defaultLocale) {
220
- return applyFarmBasePath(localizedPathname, config.basePath);
221
- }
222
- localizedPathname = internalPathname === "/" ? `/${locale}` : `/${locale}${internalPathname}`;
223
- return applyFarmBasePath(localizedPathname, config.basePath);
224
- }
225
- __name(localizeFarmPathname, "localizeFarmPathname");
226
- function localizeFarmHref(href, locale, config) {
227
- if (!href.startsWith("/") || href.startsWith("//")) return href;
228
- const url = new URL(href, "http://farm.local");
229
- url.pathname = localizeFarmPathname(url.pathname, locale, config);
230
- return `${url.pathname}${url.search}${url.hash}`;
231
- }
232
- __name(localizeFarmHref, "localizeFarmHref");
233
- function normalizePathname(pathname) {
234
- const withLeadingSlash = pathname.startsWith("/") ? pathname : `/${pathname}`;
235
- if (withLeadingSlash === "/") return "/";
236
- return withLeadingSlash.replace(/\/{2,}/g, "/").replace(/\/$/, "") || "/";
237
- }
238
- __name(normalizePathname, "normalizePathname");
12
+ var _chunkYZTASLPQcjs = require('./chunk-YZTASLPQ.cjs');
13
+ require('./chunk-YX3DBN4M.cjs');
14
+ require('./chunk-DVM4FKZL.cjs');
15
+ require('./chunk-OX6O6WVA.cjs');
16
+ require('./chunk-5ZSWG4UX.cjs');
17
+ require('./chunk-US2QVW3E.cjs');
18
+ require('./chunk-U4KT7QP3.cjs');
19
+ require('./chunk-BIDYX3SL.cjs');
20
+ require('./chunk-I57LW5VZ.cjs');
21
+ require('./chunk-NO3WWW3N.cjs');
22
+ require('./chunk-S3JO3N4H.cjs');
239
23
 
240
- // src/routing/specificity.ts
241
- var _BrowserUnstableRouteError = class _BrowserUnstableRouteError extends TypeError {
242
- constructor(message) {
243
- super(message);
244
- this.name = "BrowserUnstableRouteError";
245
- }
246
- };
247
- __name(_BrowserUnstableRouteError, "BrowserUnstableRouteError");
248
- var BrowserUnstableRouteError = _BrowserUnstableRouteError;
249
- function assertBrowserStableRoutePath(pattern) {
250
- if (pattern.includes("\\") || hasControlCharacter(pattern)) {
251
- throw new BrowserUnstableRouteError(
252
- `Route path "${pattern}" cannot contain backslashes or control characters.`
253
- );
254
- }
255
- for (const segment of pattern.split("/").filter(Boolean)) {
256
- if (segment.startsWith("(") && segment.endsWith(")") || segment.startsWith("[") && segment.endsWith("]")) {
257
- continue;
258
- }
259
- let decoded = segment;
260
- try {
261
- decoded = decodeURIComponent(segment);
262
- } catch {
263
- }
264
- if (decoded === "." || decoded === ".." || decoded.includes("/") || decoded.includes("\\") || hasControlCharacter(decoded)) {
265
- throw new BrowserUnstableRouteError(
266
- `Route path "${pattern}" contains browser-unstable segment "${segment}".`
267
- );
268
- }
269
- }
270
- }
271
- __name(assertBrowserStableRoutePath, "assertBrowserStableRoutePath");
272
- function hasControlCharacter(value) {
273
- return Array.from(value).some((character) => {
274
- const code = character.charCodeAt(0);
275
- return code <= 31 || code >= 127 && code <= 159;
276
- });
277
- }
278
- __name(hasControlCharacter, "hasControlCharacter");
279
24
 
280
- // src/utils/decode.ts
281
- function decodeRouteSegment(segment) {
282
- try {
283
- return decodeURIComponent(segment);
284
- } catch {
285
- return segment;
286
- }
287
- }
288
- __name(decodeRouteSegment, "decodeRouteSegment");
289
- function canonicalizeRequestPathname(pathname) {
290
- const encoded = pathname.includes("%");
291
- if (!encoded && !pathname.includes("//")) return pathname;
292
- const collapsed = pathname.replace(/\/{2,}/g, "/");
293
- if (!encoded) return collapsed;
294
- return collapsed.split("/").map((segment) => {
295
- const decoded = decodeRouteSegment(segment);
296
- return decoded === segment ? segment : decoded.replace(/\//g, "%2F");
297
- }).join("/");
298
- }
299
- __name(canonicalizeRequestPathname, "canonicalizeRequestPathname");
300
25
 
301
- // src/plugins/route-pattern.ts
302
- function validateConfigRouteSource(source, field = "Config route source") {
303
- if (typeof source !== "string" || source.length === 0) {
304
- throw new TypeError(`${field} must be a non-empty pathname pattern.`);
305
- }
306
- if (source.trim() !== source) {
307
- throw new Error(`${field} cannot contain leading or trailing whitespace.`);
308
- }
309
- if (!source.startsWith("/")) {
310
- throw new Error(`${field} must start with "/".`);
311
- }
312
- if (source.includes("?") || source.includes("#")) {
313
- throw new Error(`${field} must be a pathname without a query string or hash.`);
314
- }
315
- if (source.includes("\\") || Array.from(source).some((character) => {
316
- const code = character.charCodeAt(0);
317
- return code <= 31 || code >= 127 && code <= 159;
318
- })) {
319
- throw new Error(`${field} cannot contain backslashes or control characters.`);
320
- }
321
- assertBrowserStableRoutePath(source);
322
- return source;
323
- }
324
- __name(validateConfigRouteSource, "validateConfigRouteSource");
325
- function resolveConfigRoutePathname(pathname, i18n) {
326
- const localizedPathname = i18n?.enabled ? resolveFarmLocalePath(pathname, i18n) : { pathname };
327
- return {
328
- pathname: normalizeConfigRoutePathname(canonicalizeRequestPathname(localizedPathname.pathname)),
329
- ...i18n?.enabled && "locale" in localizedPathname ? { locale: localizedPathname.locale } : {}
330
- };
331
- }
332
- __name(resolveConfigRoutePathname, "resolveConfigRoutePathname");
333
- function normalizeConfigRoutePathname(pathname) {
334
- if (!pathname || pathname === "/") return "/";
335
- return pathname.endsWith("/") ? pathname.replace(/\/+$/, "") || "/" : pathname;
336
- }
337
- __name(normalizeConfigRoutePathname, "normalizeConfigRoutePathname");
338
- function localizeConfigRouteDestination(destination, locale, i18n) {
339
- return locale && i18n?.enabled ? localizeFarmHref(destination, locale, i18n) : destination;
340
- }
341
- __name(localizeConfigRouteDestination, "localizeConfigRouteDestination");
342
- function appendCatchAll(pattern) {
343
- return pattern.endsWith("/") ? `${pattern.slice(0, -1)}(?:/(.*))?` : `${pattern}(.*)`;
344
- }
345
- __name(appendCatchAll, "appendCatchAll");
346
- function escapeRegexCharacter(character) {
347
- return /[\\^$.*+?()[\]{}|]/.test(character) ? `\\${character}` : character;
348
- }
349
- __name(escapeRegexCharacter, "escapeRegexCharacter");
350
- function compileConfigRoutePattern(source) {
351
- validateConfigRouteSource(source);
352
- const tokens = [];
353
- let pattern = "";
354
- let captureIndex = 1;
355
- for (let index = 0; index < source.length; ) {
356
- const rest = source.slice(index);
357
- const parameter = rest.match(/^:([A-Za-z0-9_]+)(\*)?/);
358
- if (parameter) {
359
- tokens.push({
360
- kind: "param",
361
- name: parameter[1],
362
- captureIndex,
363
- catchAll: parameter[2] === "*"
364
- });
365
- pattern = parameter[2] ? appendCatchAll(pattern) : `${pattern}([^/]+)`;
366
- captureIndex += 1;
367
- index += parameter[0].length;
368
- continue;
369
- }
370
- if (source[index] === "*") {
371
- tokens.push({ kind: "wildcard", captureIndex });
372
- pattern = appendCatchAll(pattern);
373
- captureIndex += 1;
374
- index += 1;
375
- continue;
376
- }
377
- pattern += escapeRegexCharacter(source[index]);
378
- index += 1;
379
- }
380
- return { regex: new RegExp(`^${pattern}$`), tokens };
381
- }
382
- __name(compileConfigRoutePattern, "compileConfigRoutePattern");
383
- function interpolateConfigRouteDestination(destination, match, tokens) {
384
- const namedCaptures = /* @__PURE__ */ new Map();
385
- const wildcardCaptures = [];
386
- const captures = /* @__PURE__ */ new Map();
387
- for (const token of tokens) {
388
- const value = normalizeConfigRouteCapture(
389
- match[token.captureIndex] || "",
390
- token.kind === "wildcard" || token.catchAll
391
- );
392
- captures.set(token.captureIndex, value);
393
- if (token.kind === "param") {
394
- namedCaptures.set(token.name, value);
395
- } else {
396
- wildcardCaptures.push(value);
397
- }
398
- }
399
- let result = "";
400
- let wildcardIndex = 0;
401
- for (let index = 0; index < destination.length; ) {
402
- const rest = destination.slice(index);
403
- const parameter = rest.match(/^:([A-Za-z0-9_]+)(\*)?/);
404
- if (parameter) {
405
- const value = namedCaptures.get(parameter[1]);
406
- result += value === void 0 ? parameter[0] : value;
407
- index += parameter[0].length;
408
- continue;
409
- }
410
- const capture = rest.match(/^\$(\d+)/);
411
- if (capture) {
412
- result += captures.get(Number(capture[1])) ?? "";
413
- index += capture[0].length;
414
- continue;
415
- }
416
- if (destination[index] === "*") {
417
- result += wildcardCaptures[wildcardIndex] || "";
418
- wildcardIndex += 1;
419
- index += 1;
420
- continue;
421
- }
422
- result += destination[index];
423
- index += 1;
424
- }
425
- return result;
426
- }
427
- __name(interpolateConfigRouteDestination, "interpolateConfigRouteDestination");
428
- function normalizeConfigRouteCapture(value, catchAll) {
429
- const segments = catchAll ? value.split("/").filter(Boolean) : [value];
430
- return segments.map((segment) => encodeConfigRouteSegment(decodeConfigRouteSegment(segment))).join("/");
431
- }
432
- __name(normalizeConfigRouteCapture, "normalizeConfigRouteCapture");
433
- function decodeConfigRouteSegment(segment) {
434
- try {
435
- return decodeURIComponent(segment);
436
- } catch {
437
- return segment;
438
- }
439
- }
440
- __name(decodeConfigRouteSegment, "decodeConfigRouteSegment");
441
- function encodeConfigRouteSegment(segment) {
442
- return encodeURIComponent(segment).replace(
443
- /[!'()*]/g,
444
- (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`
445
- );
446
- }
447
- __name(encodeConfigRouteSegment, "encodeConfigRouteSegment");
448
26
 
449
- // src/plugins/redirects.ts
450
- function createRedirectsPlugin(redirects, {
451
- beforeRequest: overrideBeforeRequest,
452
- afterResponse: overrideAfterResponse,
453
- i18n
454
- } = {}) {
455
- for (const redirect of redirects) {
456
- if (redirect.statusCode !== void 0 && !isFarmRedirectStatus(redirect.statusCode)) {
457
- throw new RangeError(
458
- `Redirect "${redirect.source}" statusCode must be one of 301, 302, 303, 307, or 308.`
459
- );
460
- }
461
- }
462
- const compiledRedirects = redirects.map((redirect) => ({
463
- redirect,
464
- pattern: compileConfigRoutePattern(redirect.source)
465
- }));
466
- return {
467
- name: "farm:redirects",
468
- enforce: "pre",
469
- async beforeRequest(req, res, context) {
470
- if (overrideBeforeRequest) {
471
- await overrideBeforeRequest(req, res, context);
472
- }
473
- const url = resolveFarmRequestURL(req);
474
- const routePath = resolveConfigRoutePathname(url.pathname, i18n);
475
- const pathname = routePath.pathname;
476
- for (const { redirect, pattern } of compiledRedirects) {
477
- const match = pathname.match(pattern.regex);
478
- if (match) {
479
- const localizedDestination = localizeConfigRouteDestination(
480
- interpolateConfigRouteDestination(redirect.destination, match, pattern.tokens),
481
- routePath.locale,
482
- i18n
483
- );
484
- const destination = appendFarmRedirectQuery(localizedDestination, url.search);
485
- const statusCode = redirect.statusCode ?? (redirect.permanent ? 308 : 307);
486
- res.writeHead(statusCode, {
487
- Location: destination
488
- });
489
- res.end();
490
- return;
491
- }
492
- }
493
- },
494
- async afterResponse(req, res, context) {
495
- if (overrideAfterResponse) {
496
- await overrideAfterResponse(req, res, context);
497
- }
498
- }
499
- };
500
- }
501
- __name(createRedirectsPlugin, "createRedirectsPlugin");
502
27
 
503
- // src/plugins/headers.ts
504
- var FARM_CONFIG_HEADERS_FINALIZER = /* @__PURE__ */ Symbol.for("farm.configHeadersFinalizer");
505
- function appendConfiguredLinkHeader(res, value) {
506
- const current = res.getHeader("Link");
507
- if (current === void 0) {
508
- res.setHeader("Link", value);
509
- return;
510
- }
511
- const currentValue = Array.isArray(current) ? current.join(", ") : String(current);
512
- if (currentValue !== value && !currentValue.endsWith(`, ${value}`)) {
513
- res.setHeader("Link", `${currentValue}, ${value}`);
514
- }
515
- }
516
- __name(appendConfiguredLinkHeader, "appendConfiguredLinkHeader");
517
- function appendConfiguredSetCookieHeader(res, value) {
518
- const current = res.getHeader("Set-Cookie");
519
- if (current === void 0) {
520
- res.setHeader("Set-Cookie", value);
521
- return;
522
- }
523
- const values = (Array.isArray(current) ? current : [current]).map(String);
524
- if (!values.includes(value)) {
525
- res.setHeader("Set-Cookie", [...values, value]);
526
- }
527
- }
528
- __name(appendConfiguredSetCookieHeader, "appendConfiguredSetCookieHeader");
529
- function applyResponseHeaders(res, matchedHeaders) {
530
- for (const headers of matchedHeaders) {
531
- for (const header of headers) {
532
- const key = header.key.toLowerCase();
533
- if (key === "link") {
534
- appendConfiguredLinkHeader(res, header.value);
535
- } else if (key === "set-cookie") {
536
- appendConfiguredSetCookieHeader(res, header.value);
537
- } else {
538
- res.setHeader(header.key, header.value);
539
- }
540
- }
541
- }
542
- }
543
- __name(applyResponseHeaders, "applyResponseHeaders");
544
- function applyWriteHeadHeaders(res, headers) {
545
- if (Array.isArray(headers)) {
546
- let setCookieWritten = false;
547
- for (let index = 0; index + 1 < headers.length; index += 2) {
548
- const key = String(headers[index]);
549
- const value = headers[index + 1];
550
- if (key.toLowerCase() === "set-cookie" && setCookieWritten) {
551
- const current = res.getHeader("Set-Cookie");
552
- const values = (Array.isArray(current) ? current : [current]).filter(
553
- (entry) => entry !== void 0
554
- );
555
- res.setHeader("Set-Cookie", [...values, ...Array.isArray(value) ? value : [value]]);
556
- } else {
557
- res.setHeader(key, value);
558
- if (key.toLowerCase() === "set-cookie") setCookieWritten = true;
559
- }
560
- }
561
- return;
562
- }
563
- if (!headers || typeof headers !== "object") return;
564
- for (const [key, value] of Object.entries(headers)) {
565
- if (value !== void 0) res.setHeader(key, value);
566
- }
567
- }
568
- __name(applyWriteHeadHeaders, "applyWriteHeadHeaders");
569
- function createHeadersPlugin(headers, {
570
- beforeRequest: overrideBeforeRequest,
571
- afterResponse: overrideAfterResponse,
572
- i18n
573
- } = {}) {
574
- const compiledHeaders = headers.map((config) => ({
575
- config,
576
- pattern: compileConfigRoutePattern(config.source)
577
- }));
578
- return {
579
- name: "farm:headers",
580
- enforce: "pre",
581
- async beforeRequest(req, res, context) {
582
- if (overrideBeforeRequest) {
583
- await overrideBeforeRequest(req, res, context);
584
- }
585
- const url = resolveFarmRequestURL(req);
586
- const pathname = resolveConfigRoutePathname(url.pathname, i18n).pathname;
587
- const matchedHeaders = compiledHeaders.filter(({ pattern }) => pattern.regex.test(pathname)).map(({ config }) => config.headers);
588
- applyResponseHeaders(res, matchedHeaders);
589
- const responseWithFinalizer = res;
590
- if (matchedHeaders.length === 0 || responseWithFinalizer[FARM_CONFIG_HEADERS_FINALIZER]) {
591
- return;
592
- }
593
- responseWithFinalizer[FARM_CONFIG_HEADERS_FINALIZER] = true;
594
- const writeHead = res.writeHead;
595
- res.writeHead = ((statusCode, ...args) => {
596
- const statusMessage = typeof args[0] === "string" ? args.shift() : void 0;
597
- applyWriteHeadHeaders(res, args[0]);
598
- applyResponseHeaders(res, matchedHeaders);
599
- return statusMessage === void 0 ? writeHead.call(res, statusCode) : writeHead.call(res, statusCode, statusMessage);
600
- });
601
- },
602
- async afterResponse(req, res, context) {
603
- if (overrideAfterResponse) {
604
- await overrideAfterResponse(req, res, context);
605
- }
606
- }
607
- };
608
- }
609
- __name(createHeadersPlugin, "createHeadersPlugin");
610
28
 
611
- // src/plugins/rewrites.ts
612
- var FARM_CONFIG_REWRITES_PLUGIN_NAME = "farm:rewrites";
613
- function createRewritesPlugin(rewrites, {
614
- beforeRequest: overrideBeforeRequest,
615
- afterResponse: overrideAfterResponse,
616
- i18n
617
- } = {}) {
618
- const compiledRewrites = rewrites.map((rewrite) => ({
619
- rewrite,
620
- pattern: compileConfigRoutePattern(rewrite.source)
621
- }));
622
- return {
623
- name: FARM_CONFIG_REWRITES_PLUGIN_NAME,
624
- enforce: "pre",
625
- async beforeRequest(req, res, context) {
626
- if (overrideBeforeRequest) {
627
- await overrideBeforeRequest(req, res, context);
628
- }
629
- const url = resolveFarmRequestURL(req);
630
- const routePath = resolveConfigRoutePathname(url.pathname, i18n);
631
- const pathname = routePath.pathname;
632
- for (const { rewrite, pattern } of compiledRewrites) {
633
- const match = pathname.match(pattern.regex);
634
- if (match) {
635
- const newPath = localizeConfigRouteDestination(
636
- interpolateConfigRouteDestination(rewrite.destination, match, pattern.tokens),
637
- routePath.locale,
638
- i18n
639
- );
640
- const destinationUrl = new URL(newPath, url);
641
- if (!destinationUrl.search && url.search) {
642
- destinationUrl.search = url.search;
643
- }
644
- req.url = destinationUrl.origin === url.origin ? destinationUrl.pathname + destinationUrl.search : destinationUrl.href;
645
- break;
646
- }
647
- }
648
- },
649
- async afterResponse(req, res, context) {
650
- if (overrideAfterResponse) {
651
- await overrideAfterResponse(req, res, context);
652
- }
653
- }
654
- };
655
- }
656
- __name(createRewritesPlugin, "createRewritesPlugin");
657
29
 
658
- // src/plugins/env.ts
659
- function createEnvPlugin(env, {
660
- beforeRequest: overrideBeforeRequest,
661
- afterResponse: overrideAfterResponse
662
- } = {}) {
663
- return {
664
- name: "farm:env",
665
- configResolved(config, context) {
666
- for (const [key, value] of Object.entries(env)) {
667
- process.env[key] = value;
668
- }
669
- },
670
- async beforeRequest(req, res, context) {
671
- if (overrideBeforeRequest) {
672
- await overrideBeforeRequest(req, res, context);
673
- }
674
- },
675
- async afterResponse(req, res, context) {
676
- if (overrideAfterResponse) {
677
- await overrideAfterResponse(req, res, context);
678
- }
679
- }
680
- };
681
- }
682
- __name(createEnvPlugin, "createEnvPlugin");
683
-
684
- // src/plugins/compression.ts
685
- var import_node_stream2 = require("stream");
686
- var import_node_zlib = require("zlib");
687
- var Q_VALUE = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/;
688
- function parseEncodingQuality(header) {
689
- const qualities = /* @__PURE__ */ new Map();
690
- for (const item of header.split(",")) {
691
- const [rawEncoding, ...parameters] = item.trim().split(";");
692
- const encoding = rawEncoding?.trim().toLowerCase();
693
- if (!encoding) continue;
694
- let quality = 1;
695
- for (const parameter of parameters) {
696
- const [rawName, rawValue] = parameter.split("=", 2);
697
- if (rawName?.trim().toLowerCase() !== "q") continue;
698
- const value = rawValue?.trim() ?? "";
699
- quality = Q_VALUE.test(value) ? Number(value) : 0;
700
- }
701
- qualities.set(encoding, Math.max(qualities.get(encoding) ?? 0, quality));
702
- }
703
- return qualities;
704
- }
705
- __name(parseEncodingQuality, "parseEncodingQuality");
706
- function selectEncoding(header) {
707
- if (!header.trim()) return void 0;
708
- const qualities = parseEncodingQuality(header);
709
- const wildcard = qualities.get("*") ?? 0;
710
- const quality = /* @__PURE__ */ __name((encoding) => qualities.get(encoding) ?? wildcard, "quality");
711
- const brotli = quality("br");
712
- const gzip2 = quality("gzip");
713
- if (brotli <= 0 && gzip2 <= 0) return void 0;
714
- return brotli >= gzip2 ? "br" : "gzip";
715
- }
716
- __name(selectEncoding, "selectEncoding");
717
- var COMPRESSIBLE_MEDIA_TYPES = /* @__PURE__ */ new Set([
718
- "application/javascript",
719
- "application/json",
720
- "application/ndjson",
721
- "application/wasm",
722
- "application/x-ndjson",
723
- "application/xml",
724
- // Font formats that store raw glyph tables. `font/woff` and `font/woff2` are
725
- // deliberately absent: their payloads are already deflate and brotli streams.
726
- "application/vnd.ms-fontobject",
727
- "font/otf",
728
- "font/ttf"
729
- ]);
730
- var COMPRESSIBLE_MEDIA_TYPE_SUFFIXES = ["+json", "+xml"];
731
- function isCompressibleMediaType(mediaType) {
732
- if (!mediaType) return false;
733
- if (mediaType === "text/event-stream") return false;
734
- if (mediaType.startsWith("text/")) return true;
735
- if (COMPRESSIBLE_MEDIA_TYPES.has(mediaType)) return true;
736
- return COMPRESSIBLE_MEDIA_TYPE_SUFFIXES.some((suffix) => mediaType.endsWith(suffix));
737
- }
738
- __name(isCompressibleMediaType, "isCompressibleMediaType");
739
- function isCompressionEligible(request, response) {
740
- if (request.method !== "HEAD" && !response.body || response.status === 204 || response.status === 205 || response.status === 304 || response.headers.has("content-encoding") || response.headers.has("content-range") || response.headers.get("cache-control")?.toLowerCase().includes("no-transform")) {
741
- return false;
742
- }
743
- const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
744
- return isCompressibleMediaType(mediaType);
745
- }
746
- __name(isCompressionEligible, "isCompressionEligible");
747
- function appendVary(headers, value) {
748
- const current = headers.get("vary");
749
- const values = current ? current.split(",").map((item) => item.trim()).filter(Boolean) : [];
750
- if (values.includes("*")) return;
751
- if (!values.some((item) => item.toLowerCase() === value.toLowerCase())) {
752
- values.push(value);
753
- }
754
- headers.set("vary", values.join(", "));
755
- }
756
- __name(appendVary, "appendVary");
757
- var BROTLI_QUALITY = 5;
758
- function compressedHeaders(response, encoding) {
759
- const headers = new Headers(response.headers);
760
- headers.set("content-encoding", encoding);
761
- headers.delete("content-length");
762
- appendVary(headers, "Accept-Encoding");
763
- const etag = headers.get("etag");
764
- if (etag && !etag.startsWith("W/")) {
765
- headers.set("etag", `W/${etag}`);
766
- }
767
- return headers;
768
- }
769
- __name(compressedHeaders, "compressedHeaders");
770
- function compressBufferedResponse(response, text, encoding) {
771
- const headers = compressedHeaders(response, encoding);
772
- response.body?.cancel().catch(() => {
773
- });
774
- const input = Buffer.from(text);
775
- let cancelled = false;
776
- const body = new ReadableStream({
777
- start(controller) {
778
- const done = /* @__PURE__ */ __name((error, output) => {
779
- if (cancelled) return;
780
- if (error) {
781
- controller.error(error);
782
- return;
783
- }
784
- controller.enqueue(new Uint8Array(output.buffer, output.byteOffset, output.byteLength));
785
- controller.close();
786
- }, "done");
787
- if (encoding === "br") {
788
- (0, import_node_zlib.brotliCompress)(
789
- input,
790
- { params: { [import_node_zlib.constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY } },
791
- done
792
- );
793
- } else {
794
- (0, import_node_zlib.gzip)(input, done);
795
- }
796
- },
797
- cancel() {
798
- cancelled = true;
799
- }
800
- });
801
- return new Response(body, {
802
- status: response.status,
803
- statusText: response.statusText,
804
- headers
805
- });
806
- }
807
- __name(compressBufferedResponse, "compressBufferedResponse");
808
- function compressResponse(response, encoding) {
809
- const compressor = encoding === "br" ? (0, import_node_zlib.createBrotliCompress)({
810
- flush: import_node_zlib.constants.BROTLI_OPERATION_FLUSH,
811
- params: { [import_node_zlib.constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY }
812
- }) : (0, import_node_zlib.createGzip)({ flush: import_node_zlib.constants.Z_SYNC_FLUSH });
813
- const input = import_node_stream2.Readable.fromWeb(response.body);
814
- const output = (0, import_node_stream2.pipeline)(input, compressor, () => {
815
- });
816
- const headers = compressedHeaders(response, encoding);
817
- return new Response(import_node_stream2.Readable.toWeb(output), {
818
- status: response.status,
819
- statusText: response.statusText,
820
- headers
821
- });
822
- }
823
- __name(compressResponse, "compressResponse");
824
- function varyIdentityResponse(response) {
825
- const headers = new Headers(response.headers);
826
- appendVary(headers, "Accept-Encoding");
827
- return new Response(response.body, {
828
- status: response.status,
829
- statusText: response.statusText,
830
- headers
831
- });
832
- }
833
- __name(varyIdentityResponse, "varyIdentityResponse");
834
- function compressFarmResponse(request, response, bufferedText) {
835
- if (!isCompressionEligible(request, response)) return response;
836
- if (request.method === "HEAD") return varyIdentityResponse(response);
837
- const encoding = selectEncoding(request.headers.get("accept-encoding") ?? "");
838
- if (!encoding) return varyIdentityResponse(response);
839
- return bufferedText === void 0 ? compressResponse(response, encoding) : compressBufferedResponse(response, bufferedText, encoding);
840
- }
841
- __name(compressFarmResponse, "compressFarmResponse");
842
- function createCompressionPlugin({
843
- beforeRequest: overrideBeforeRequest,
844
- afterResponse: overrideAfterResponse
845
- } = {}) {
846
- return {
847
- name: "farm:compression",
848
- enforce: "post",
849
- runtime: {
850
- after({ request, response, isProd }) {
851
- if (!isProd) return;
852
- return compressFarmResponse(request, response);
853
- }
854
- },
855
- async beforeRequest(req, res, context) {
856
- if (overrideBeforeRequest) {
857
- await overrideBeforeRequest(req, res, context);
858
- }
859
- },
860
- async afterResponse(req, res, context) {
861
- if (overrideAfterResponse) {
862
- await overrideAfterResponse(req, res, context);
863
- }
864
- }
865
- };
866
- }
867
- __name(createCompressionPlugin, "createCompressionPlugin");
868
-
869
- // src/plugins/logger.ts
870
- function createLoggerPlugin({
871
- beforeRequest,
872
- afterResponse
873
- } = {}) {
874
- const plugin = {
875
- name: "farm:logger",
876
- enforce: "post"
877
- };
878
- if (beforeRequest) {
879
- plugin.beforeRequest = async (req, res, context) => {
880
- await beforeRequest(req, res, context);
881
- };
882
- }
883
- if (afterResponse) {
884
- plugin.afterResponse = async (req, res, context) => {
885
- await afterResponse(req, res, context);
886
- };
887
- }
888
- return plugin;
889
- }
890
- __name(createLoggerPlugin, "createLoggerPlugin");
891
- // Annotate the CommonJS export names for ESM import in node:
892
- 0 && (module.exports = {
893
- createCompressionPlugin,
894
- createEnvPlugin,
895
- createHeadersPlugin,
896
- createLoggerPlugin,
897
- createRedirectsPlugin,
898
- createRewritesPlugin
899
- });
30
+ exports.createCompressionPlugin = _chunkR6AIILIIcjs.createCompressionPlugin; exports.createEnvPlugin = _chunkQZRVZSPNcjs.createEnvPlugin; exports.createHeadersPlugin = _chunkQZRVZSPNcjs.createHeadersPlugin; exports.createLoggerPlugin = _chunkQZRVZSPNcjs.createLoggerPlugin; exports.createRedirectsPlugin = _chunkQZRVZSPNcjs.createRedirectsPlugin; exports.createRewritesPlugin = _chunkYZTASLPQcjs.createRewritesPlugin;