@farm.js/core 0.1.0-beta.97 → 0.1.0-beta.98

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 (248) hide show
  1. package/dist/after.cjs.map +1 -0
  2. package/dist/agent-runtime.cjs +7 -3
  3. package/dist/agent-runtime.cjs.map +1 -0
  4. package/dist/agent-runtime.d.mts +2 -2
  5. package/dist/agent-runtime.d.ts +2 -2
  6. package/dist/agent-runtime.mjs +2 -1
  7. package/dist/agent-runtime.mjs.map +1 -1
  8. package/dist/api/route-manager.cjs.map +1 -0
  9. package/dist/api/route-manager.d.mts +2 -2
  10. package/dist/api/route-manager.d.ts +2 -2
  11. package/dist/api/runtime.cjs.map +1 -0
  12. package/dist/api.cjs +26 -1
  13. package/dist/api.cjs.map +1 -0
  14. package/dist/api.d.mts +3 -3
  15. package/dist/api.d.ts +3 -3
  16. package/dist/api.mjs +2 -2
  17. package/dist/{app-CIOx3LvY.d.ts → app-CJKz2mbi.d.ts} +4 -4
  18. package/dist/{app-DBd6437H.d.mts → app-DMEGFLR2.d.mts} +4 -4
  19. package/dist/app-markdown.cjs.map +1 -0
  20. package/dist/app-markdown.d.mts +3 -3
  21. package/dist/app-markdown.d.ts +3 -3
  22. package/dist/cache.cjs.map +1 -0
  23. package/dist/{chunk-WD2EBM3I.mjs → chunk-3CQJV3NC.mjs} +2 -2
  24. package/dist/{chunk-I3OOUWO5.mjs → chunk-3GDRV7SG.mjs} +2 -2
  25. package/dist/{chunk-X4SFHKFH.mjs → chunk-6KJY25DQ.mjs} +5 -5
  26. package/dist/{chunk-FP5Q67FO.mjs → chunk-AAEZP2EY.mjs} +9 -9
  27. package/dist/{chunk-WMJGA32P.mjs → chunk-BXVOHG6B.mjs} +27 -2
  28. package/dist/{chunk-WMJGA32P.mjs.map → chunk-BXVOHG6B.mjs.map} +1 -1
  29. package/dist/{chunk-BZAIS65C.mjs → chunk-DIHNOVZZ.mjs} +40 -13
  30. package/dist/chunk-DIHNOVZZ.mjs.map +1 -0
  31. package/dist/{chunk-ISSFLGJ5.mjs → chunk-FDWECN3W.mjs} +8 -4
  32. package/dist/chunk-FDWECN3W.mjs.map +1 -0
  33. package/dist/chunk-FDWXXTWR.mjs +114 -0
  34. package/dist/chunk-FDWXXTWR.mjs.map +1 -0
  35. package/dist/{chunk-J3MPQ4MQ.mjs → chunk-IHADQ6J7.mjs} +2 -2
  36. package/dist/{chunk-J3MPQ4MQ.mjs.map → chunk-IHADQ6J7.mjs.map} +1 -1
  37. package/dist/{chunk-FSIXEIOB.mjs → chunk-L7FSTPGS.mjs} +2 -2
  38. package/dist/{chunk-AAC66ILR.mjs → chunk-LXXG3K2Y.mjs} +61 -2
  39. package/dist/chunk-LXXG3K2Y.mjs.map +1 -0
  40. package/dist/{chunk-GJ7W6LNK.mjs → chunk-N5RK4LK6.mjs} +3 -3
  41. package/dist/{chunk-WKDAA6V2.mjs → chunk-NBF56FXB.mjs} +20 -5
  42. package/dist/chunk-NBF56FXB.mjs.map +1 -0
  43. package/dist/chunk-RKUPOYQV.mjs +28 -0
  44. package/dist/chunk-RKUPOYQV.mjs.map +1 -0
  45. package/dist/{chunk-2SKCXYLB.mjs → chunk-RL3THP3L.mjs} +54 -5
  46. package/dist/chunk-RL3THP3L.mjs.map +1 -0
  47. package/dist/{chunk-52BR7LTX.mjs → chunk-STSPSJUI.mjs} +3 -3
  48. package/dist/{chunk-EPDIF432.mjs → chunk-UOGX6UNO.mjs} +37 -17
  49. package/dist/chunk-UOGX6UNO.mjs.map +1 -0
  50. package/dist/{chunk-YIBV77KZ.mjs → chunk-URQELPSH.mjs} +2 -2
  51. package/dist/{chunk-UMUWR5XA.mjs → chunk-UWQ4EEW7.mjs} +2 -2
  52. package/dist/{chunk-IZBX2TEU.mjs → chunk-VQG3QWWK.mjs} +2 -2
  53. package/dist/{chunk-D7F7YZ7L.mjs → chunk-WA77FWAO.mjs} +8 -8
  54. package/dist/{chunk-35NPLKQJ.mjs → chunk-XWM2C267.mjs} +21 -105
  55. package/dist/chunk-XWM2C267.mjs.map +1 -0
  56. package/dist/client/lifecycle.cjs.map +1 -0
  57. package/dist/client/lifecycle.mjs +2 -2
  58. package/dist/{client-plugins-B6-07YmP.d.mts → client-plugins-CyTLPqjP.d.mts} +38 -2
  59. package/dist/{client-plugins-By6MVUX-.d.ts → client-plugins-D-UgzngJ.d.ts} +38 -2
  60. package/dist/client-plugins.cjs +1 -1
  61. package/dist/client-plugins.cjs.map +1 -0
  62. package/dist/client-plugins.d.mts +2 -2
  63. package/dist/client-plugins.d.ts +2 -2
  64. package/dist/client-plugins.mjs +2 -2
  65. package/dist/client.cjs +61 -16
  66. package/dist/client.cjs.map +1 -0
  67. package/dist/client.d.mts +5 -5
  68. package/dist/client.d.ts +5 -5
  69. package/dist/client.mjs +7 -7
  70. package/dist/config.cjs.map +1 -0
  71. package/dist/config.d.mts +2 -2
  72. package/dist/config.d.ts +2 -2
  73. package/dist/cron.cjs +48 -12
  74. package/dist/cron.cjs.map +1 -0
  75. package/dist/cron.mjs +2 -1
  76. package/dist/deferred.cjs.map +1 -0
  77. package/dist/deployment.cjs.map +1 -0
  78. package/dist/{devtools-XWZX6CCL.mjs → devtools-KQ2PXSIC.mjs} +8 -6
  79. package/dist/{devtools-XWZX6CCL.mjs.map → devtools-KQ2PXSIC.mjs.map} +1 -1
  80. package/dist/docs.cjs +7 -3
  81. package/dist/docs.cjs.map +1 -0
  82. package/dist/docs.mjs +8 -6
  83. package/dist/env-types.cjs.map +1 -0
  84. package/dist/env.cjs.map +1 -0
  85. package/dist/environment/vite.cjs.map +1 -0
  86. package/dist/environment.cjs.map +1 -0
  87. package/dist/font.cjs.map +1 -0
  88. package/dist/headers.cjs.map +1 -0
  89. package/dist/i18n/client.cjs.map +1 -0
  90. package/dist/i18n/index.cjs.map +1 -0
  91. package/dist/i18n/server.cjs.map +1 -0
  92. package/dist/image/server.cjs +19 -4
  93. package/dist/image/server.cjs.map +1 -0
  94. package/dist/image/server.d.mts +6 -0
  95. package/dist/image/server.d.ts +6 -0
  96. package/dist/image/server.mjs +1 -1
  97. package/dist/image/sharp.cjs +1 -0
  98. package/dist/image/sharp.cjs.map +1 -0
  99. package/dist/image/sharp.mjs +1 -1
  100. package/dist/image.cjs.map +1 -0
  101. package/dist/index.cjs +370 -143
  102. package/dist/index.cjs.map +1 -0
  103. package/dist/index.d.mts +10 -10
  104. package/dist/index.d.ts +10 -10
  105. package/dist/index.mjs +29 -21
  106. package/dist/index.mjs.map +1 -1
  107. package/dist/instrumentation.cjs.map +1 -0
  108. package/dist/{integration-orm-LLW6WZNK.mjs → integration-orm-G5BPBT5X.mjs} +3 -3
  109. package/dist/integrations.cjs +168 -5
  110. package/dist/integrations.cjs.map +1 -0
  111. package/dist/integrations.d.mts +2 -2
  112. package/dist/integrations.d.ts +2 -2
  113. package/dist/integrations.mjs +10 -3
  114. package/dist/internal/build-runtime.cjs +178 -51
  115. package/dist/internal/build-runtime.cjs.map +1 -0
  116. package/dist/internal/build-runtime.d.mts +4 -4
  117. package/dist/internal/build-runtime.d.ts +4 -4
  118. package/dist/internal/build-runtime.mjs +13 -11
  119. package/dist/internal/client-runtime.cjs +1 -1
  120. package/dist/internal/client-runtime.cjs.map +1 -0
  121. package/dist/internal/client-runtime.mjs +2 -2
  122. package/dist/internal/config-runtime.cjs +48 -42
  123. package/dist/internal/config-runtime.cjs.map +1 -0
  124. package/dist/internal/config-runtime.d.mts +3 -3
  125. package/dist/internal/config-runtime.d.ts +3 -3
  126. package/dist/internal/config-runtime.mjs +7 -5
  127. package/dist/internal/isolated-boundary.cjs.map +1 -0
  128. package/dist/internal/metadata-image-runtime.cjs.map +1 -0
  129. package/dist/internal/product-telemetry-runtime.cjs +6 -2
  130. package/dist/internal/product-telemetry-runtime.cjs.map +1 -0
  131. package/dist/internal/product-telemetry-runtime.mjs +6 -2
  132. package/dist/internal/product-telemetry-runtime.mjs.map +1 -1
  133. package/dist/internal/production-node-env.cjs.map +1 -0
  134. package/dist/internal/production-runtime.cjs.map +1 -0
  135. package/dist/internal/production-runtime.d.mts +8 -8
  136. package/dist/internal/production-runtime.d.ts +8 -8
  137. package/dist/markdown.cjs.map +1 -0
  138. package/dist/{metadata-route-8_V3UonT.d.ts → metadata-route-BpU8K9RI.d.ts} +1 -1
  139. package/dist/{metadata-route-CWP_HjGU.d.mts → metadata-route-D1AYgWni.d.mts} +1 -1
  140. package/dist/middleware.cjs.map +1 -0
  141. package/dist/middleware.d.mts +4 -4
  142. package/dist/middleware.d.ts +4 -4
  143. package/dist/navigation.cjs.map +1 -0
  144. package/dist/{nitro-EGRNOB5P.mjs → nitro-IITKBMUI.mjs} +4 -3
  145. package/dist/{nitro-EGRNOB5P.mjs.map → nitro-IITKBMUI.mjs.map} +1 -1
  146. package/dist/observability.cjs.map +1 -0
  147. package/dist/plugin.cjs +143 -50
  148. package/dist/plugin.cjs.map +1 -0
  149. package/dist/plugin.d.mts +2 -2
  150. package/dist/plugin.d.ts +2 -2
  151. package/dist/plugin.mjs +10 -8
  152. package/dist/{production-runtime-BGRH1dKG.d.mts → production-runtime-BIKA-BVT.d.mts} +2 -2
  153. package/dist/{production-runtime-CdmzsDax.d.ts → production-runtime-DtCUEELY.d.ts} +2 -2
  154. package/dist/query/client.cjs.map +1 -0
  155. package/dist/query/index.cjs.map +1 -0
  156. package/dist/query/parsers.cjs.map +1 -0
  157. package/dist/query/server.cjs.map +1 -0
  158. package/dist/{render-plan-DLxJYAA5.d.mts → render-plan-Dimb23ux.d.mts} +1 -1
  159. package/dist/{render-plan-0GeHiGVZ.d.ts → render-plan-rg3uiSo3.d.ts} +1 -1
  160. package/dist/renderer/react/client.cjs.map +1 -0
  161. package/dist/renderer/react/server.cjs.map +1 -0
  162. package/dist/renderer/react/vite.cjs.map +1 -0
  163. package/dist/renderer-client.cjs +26 -1
  164. package/dist/renderer-client.cjs.map +1 -0
  165. package/dist/renderer-client.d.mts +4 -4
  166. package/dist/renderer-client.d.ts +4 -4
  167. package/dist/renderer-client.mjs +2 -2
  168. package/dist/renderer.cjs.map +1 -0
  169. package/dist/{request-BstWbZ6O.d.ts → request-ColD-ChW.d.ts} +1 -1
  170. package/dist/{request-BCNXSXLh.d.mts → request-D5zvbU2Z.d.mts} +1 -1
  171. package/dist/request.cjs.map +1 -0
  172. package/dist/request.d.mts +3 -3
  173. package/dist/request.d.ts +3 -3
  174. package/dist/router.cjs.map +1 -0
  175. package/dist/routes.cjs.map +1 -0
  176. package/dist/routes.d.mts +2 -2
  177. package/dist/routes.d.ts +2 -2
  178. package/dist/server-action-security.cjs +117 -104
  179. package/dist/server-action-security.cjs.map +1 -0
  180. package/dist/server-action-security.mjs +2 -1
  181. package/dist/server-fn-client.cjs.map +1 -0
  182. package/dist/server-fn.cjs.map +1 -0
  183. package/dist/server-fn.mjs +3 -2
  184. package/dist/server-plugins.cjs.map +1 -0
  185. package/dist/server-plugins.d.mts +3 -3
  186. package/dist/server-plugins.d.ts +3 -3
  187. package/dist/server-query-client.cjs +26 -1
  188. package/dist/server-query-client.cjs.map +1 -0
  189. package/dist/server-query-client.mjs +3 -3
  190. package/dist/server-query.cjs.map +1 -0
  191. package/dist/server-query.mjs +4 -3
  192. package/dist/server.cjs +221 -116
  193. package/dist/server.cjs.map +1 -0
  194. package/dist/server.d.mts +8 -8
  195. package/dist/server.d.ts +8 -8
  196. package/dist/server.mjs +13 -11
  197. package/dist/server.mjs.map +1 -1
  198. package/dist/{spa-router-BeyAVSc6.d.mts → spa-router-BlilYGAN.d.mts} +1 -1
  199. package/dist/{spa-router-COgu4txb.d.ts → spa-router-kXORcsT_.d.ts} +1 -1
  200. package/dist/storage.cjs +7 -3
  201. package/dist/storage.cjs.map +1 -0
  202. package/dist/storage.mjs +1 -1
  203. package/dist/testing.cjs.map +1 -0
  204. package/dist/testing.d.mts +2 -2
  205. package/dist/testing.d.ts +2 -2
  206. package/dist/testing.mjs +2 -1
  207. package/dist/testing.mjs.map +1 -1
  208. package/dist/theme/client.cjs.map +1 -0
  209. package/dist/theme/index.cjs.map +1 -0
  210. package/dist/theme/runtime.cjs.map +1 -0
  211. package/dist/theme/server.cjs.map +1 -0
  212. package/dist/{utils-DkU2c_1B.d.ts → utils-BhvF7Hhl.d.ts} +1 -1
  213. package/dist/{utils-DL2VwDQl.d.mts → utils-uF32evNX.d.mts} +1 -1
  214. package/dist/version.cjs +1 -1
  215. package/dist/version.cjs.map +1 -0
  216. package/dist/version.mjs +1 -1
  217. package/dist/vite.cjs +143 -50
  218. package/dist/vite.cjs.map +1 -0
  219. package/dist/vite.d.mts +2 -2
  220. package/dist/vite.d.ts +2 -2
  221. package/dist/vite.mjs +10 -8
  222. package/dist/{workflows-ChyK_oTu.d.mts → workflows-BantWytQ.d.mts} +7 -0
  223. package/dist/{workflows-ChyK_oTu.d.ts → workflows-BantWytQ.d.ts} +7 -0
  224. package/dist/workflows.cjs +67 -4
  225. package/dist/workflows.cjs.map +1 -0
  226. package/dist/workflows.d.mts +1 -1
  227. package/dist/workflows.d.ts +1 -1
  228. package/dist/workflows.mjs +2 -1
  229. package/package.json +17 -17
  230. package/dist/chunk-2SKCXYLB.mjs.map +0 -1
  231. package/dist/chunk-35NPLKQJ.mjs.map +0 -1
  232. package/dist/chunk-AAC66ILR.mjs.map +0 -1
  233. package/dist/chunk-BZAIS65C.mjs.map +0 -1
  234. package/dist/chunk-EPDIF432.mjs.map +0 -1
  235. package/dist/chunk-ISSFLGJ5.mjs.map +0 -1
  236. package/dist/chunk-WKDAA6V2.mjs.map +0 -1
  237. /package/dist/{chunk-WD2EBM3I.mjs.map → chunk-3CQJV3NC.mjs.map} +0 -0
  238. /package/dist/{chunk-I3OOUWO5.mjs.map → chunk-3GDRV7SG.mjs.map} +0 -0
  239. /package/dist/{chunk-X4SFHKFH.mjs.map → chunk-6KJY25DQ.mjs.map} +0 -0
  240. /package/dist/{chunk-FP5Q67FO.mjs.map → chunk-AAEZP2EY.mjs.map} +0 -0
  241. /package/dist/{chunk-FSIXEIOB.mjs.map → chunk-L7FSTPGS.mjs.map} +0 -0
  242. /package/dist/{chunk-GJ7W6LNK.mjs.map → chunk-N5RK4LK6.mjs.map} +0 -0
  243. /package/dist/{chunk-52BR7LTX.mjs.map → chunk-STSPSJUI.mjs.map} +0 -0
  244. /package/dist/{chunk-YIBV77KZ.mjs.map → chunk-URQELPSH.mjs.map} +0 -0
  245. /package/dist/{chunk-UMUWR5XA.mjs.map → chunk-UWQ4EEW7.mjs.map} +0 -0
  246. /package/dist/{chunk-IZBX2TEU.mjs.map → chunk-VQG3QWWK.mjs.map} +0 -0
  247. /package/dist/{chunk-D7F7YZ7L.mjs.map → chunk-WA77FWAO.mjs.map} +0 -0
  248. /package/dist/{integration-orm-LLW6WZNK.mjs.map → integration-orm-G5BPBT5X.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tracing.ts","../src/observability.ts","../src/cache-invalidation.ts","../src/i18n/bridge.ts","../src/cache.ts","../src/routing/specificity.ts","../src/routes-shared.ts","../src/route-runtime.ts","../src/route-context.ts","../src/routes.ts","../src/api/index.ts","../src/api/endpoint.ts","../src/api/transport.ts","../src/api/route.ts","../src/api/route-shape.ts","../src/api/plugin-route-runtime.ts","../src/api/route-manager.ts","../src/utils.ts","../src/routes.server.ts","../src/i18n/server.ts","../src/i18n/runtime.ts","../src/i18n/catalog.ts","../src/i18n/config.ts","../src/server/request.ts","../src/server/request-bridge.ts","../src/api/runtime.ts","../src/server-http.ts","../src/api/config.ts","../src/api/server-path.ts","../src/api/route-schema.ts","../src/response-body.ts","../src/api/route-pattern.ts","../src/api/route-files.ts","../src/client-headers.ts","../src/client-cancellation.ts","../src/client-observers.ts","../src/integration-client.ts","../src/client-cache.ts","../src/api/client.ts","../src/api/client-routes.ts","../src/api/server-client-bridge.ts","../src/server/response.ts","../src/after.ts","../src/api/server-context.ts","../src/api/vite-plugin.ts","../src/cli-colors.ts"],"sourcesContent":["import {\n context,\n createContextKey,\n isSpanContextValid,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace,\n type Attributes,\n type Context,\n type Span,\n} from \"@opentelemetry/api\";\nimport type { FarmEvent } from \"./observability\";\n\nexport const FARM_TRACER_NAME = \"@farm.js/core\";\n\nexport type FarmTraceSpanKind =\n | \"request\"\n | \"render\"\n | \"middleware\"\n | \"api\"\n | \"integration\"\n | \"storage\"\n | \"ppr\"\n | \"build\"\n | \"plugin\";\n\nexport interface FarmTracingConfig {\n /** Enable Farm's OpenTelemetry spans. */\n enabled?: boolean;\n /** Span families to record. All families are enabled by default. */\n spans?: readonly FarmTraceSpanKind[];\n /** Add Farm lifecycle events to the active span. Defaults to true. */\n recordEvents?: boolean;\n /** Static attributes added to every Farm-created span. */\n attributes?: Attributes;\n /** Path prefixes that should not create request spans. */\n ignorePaths?: readonly string[];\n}\n\nexport type FarmTracingUserConfig = boolean | FarmTracingConfig;\n\nexport interface FarmResolvedTracingConfig {\n enabled: boolean;\n spans: ReadonlySet<FarmTraceSpanKind>;\n recordEvents: boolean;\n attributes: Attributes;\n ignorePaths: readonly string[];\n}\n\nexport interface FarmTraceContext {\n traceId: string;\n spanId: string;\n traceSampled: boolean;\n}\n\nexport interface FarmRequestSpanOptions {\n getStatusCode?: () => number | undefined;\n onStart?: () => void;\n onComplete?: (status: number, durationMs: number) => void;\n onError?: (error: unknown, durationMs: number) => void;\n}\n\nexport interface FarmSpanOptions {\n kind?: FarmTraceSpanKind;\n attributes?: Attributes;\n spanKind?: SpanKind;\n}\n\nconst ALL_SPAN_KINDS: readonly FarmTraceSpanKind[] = [\n \"request\",\n \"render\",\n \"middleware\",\n \"api\",\n \"integration\",\n \"storage\",\n \"ppr\",\n \"build\",\n \"plugin\",\n];\n\nconst DEFAULT_IGNORED_PATHS = [\n \"/@vite/\",\n \"/@fs/\",\n \"/@id/\",\n \"/@react-refresh\",\n \"/node_modules/\",\n \"/__vite\",\n \"/.well-known/appspecific/\",\n];\nconst FARM_REQUEST_METHOD_CONTEXT_KEY = createContextKey(\"@farm.js/core/request-method\");\n\nlet tracingState: FarmResolvedTracingConfig = normalizeFarmTracingConfig(false);\n\nexport function normalizeFarmTracingConfig(\n config: FarmTracingUserConfig | undefined,\n): FarmResolvedTracingConfig {\n if (!config) {\n return {\n enabled: false,\n spans: new Set(ALL_SPAN_KINDS),\n recordEvents: true,\n attributes: {},\n ignorePaths: DEFAULT_IGNORED_PATHS,\n };\n }\n\n if (config === true) {\n return {\n enabled: true,\n spans: new Set(ALL_SPAN_KINDS),\n recordEvents: true,\n attributes: {},\n ignorePaths: DEFAULT_IGNORED_PATHS,\n };\n }\n\n return {\n enabled: config.enabled ?? true,\n spans: new Set(config.spans ?? ALL_SPAN_KINDS),\n recordEvents: config.recordEvents ?? true,\n attributes: { ...config.attributes },\n ignorePaths: [...DEFAULT_IGNORED_PATHS, ...(config.ignorePaths ?? [])],\n };\n}\n\nexport function configureFarmTracing(\n config: FarmTracingUserConfig | FarmResolvedTracingConfig | undefined,\n): void {\n if (isResolvedFarmTracingConfig(config)) {\n tracingState = {\n ...config,\n spans: new Set(config.spans),\n attributes: { ...config.attributes },\n ignorePaths: [...config.ignorePaths],\n };\n return;\n }\n tracingState = normalizeFarmTracingConfig(config as FarmTracingUserConfig | undefined);\n}\n\nfunction isResolvedFarmTracingConfig(\n config: FarmTracingUserConfig | FarmResolvedTracingConfig | undefined,\n): config is FarmResolvedTracingConfig {\n return (\n !!config &&\n typeof config === \"object\" &&\n typeof config.enabled === \"boolean\" &&\n config.spans instanceof Set &&\n typeof config.recordEvents === \"boolean\" &&\n Array.isArray(config.ignorePaths)\n );\n}\n\nexport function getFarmTracingConfig(): FarmResolvedTracingConfig {\n return tracingState;\n}\n\nexport function resetFarmTracing(): void {\n tracingState = normalizeFarmTracingConfig(false);\n}\n\nexport function getFarmTraceContext(): FarmTraceContext | undefined {\n return getSpanTraceContext(trace.getSpan(context.active()));\n}\n\nexport async function runWithFarmSpan<T>(\n name: string,\n handler: () => T | Promise<T>,\n options: FarmSpanOptions = {},\n): Promise<T> {\n const spanFamily = options.kind;\n if (!tracingState.enabled || (spanFamily !== undefined && !tracingState.spans.has(spanFamily))) {\n return await handler();\n }\n\n const tracer = trace.getTracer(FARM_TRACER_NAME);\n return await tracer.startActiveSpan(\n name,\n {\n kind: options.spanKind ?? SpanKind.INTERNAL,\n attributes: {\n ...tracingState.attributes,\n ...options.attributes,\n },\n },\n async (span) => {\n try {\n return await handler();\n } catch (error) {\n recordSpanError(span, error);\n throw error;\n } finally {\n span.end();\n }\n },\n );\n}\n\nexport async function _runWithFarmRequestSpan<T>(\n request: Request,\n handler: () => T | Promise<T>,\n options: FarmRequestSpanOptions = {},\n): Promise<T> {\n const startedAt = Date.now();\n const url = new URL(request.url);\n const shouldTrace =\n tracingState.enabled &&\n tracingState.spans.has(\"request\") &&\n !tracingState.ignorePaths.some((prefix) => url.pathname.startsWith(prefix));\n\n if (!shouldTrace) {\n options.onStart?.();\n try {\n const result = await handler();\n options.onComplete?.(resolveResultStatus(result, options), Date.now() - startedAt);\n return result;\n } catch (error) {\n options.onError?.(error, Date.now() - startedAt);\n throw error;\n }\n }\n\n const extractedContext = propagation.extract(context.active(), request.headers, {\n keys(carrier) {\n return Array.from(carrier.keys());\n },\n get(carrier, key) {\n return carrier.get(key) ?? undefined;\n },\n });\n const requestContext = extractedContext.setValue(FARM_REQUEST_METHOD_CONTEXT_KEY, request.method);\n const tracer = trace.getTracer(FARM_TRACER_NAME);\n const attributes: Attributes = {\n ...tracingState.attributes,\n \"http.request.method\": request.method,\n \"url.path\": url.pathname,\n \"url.scheme\": url.protocol.replace(/:$/, \"\"),\n \"server.address\": url.hostname,\n };\n if (url.port) attributes[\"server.port\"] = Number(url.port);\n\n return await tracer.startActiveSpan(\n `${request.method} ${url.pathname}`,\n { kind: SpanKind.SERVER, attributes },\n requestContext,\n async (span) => {\n options.onStart?.();\n try {\n const result = await handler();\n const status = resolveResultStatus(result, options);\n setResponseStatus(span, status);\n options.onComplete?.(status, Date.now() - startedAt);\n return result;\n } catch (error) {\n recordSpanError(span, error);\n options.onError?.(error, Date.now() - startedAt);\n throw error;\n } finally {\n span.end();\n }\n },\n );\n}\n\nexport function recordFarmEventTrace(event: FarmEvent): FarmTraceContext | undefined {\n if (!tracingState.enabled) return undefined;\n\n const activeContext = context.active();\n const activeSpan = trace.getSpan(activeContext);\n const traceContext = getSpanTraceContext(activeSpan);\n if (activeSpan && traceContext) {\n if (event.type === \"route.matched\") {\n const method =\n (activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) as string | undefined) ?? \"HTTP\";\n activeSpan.updateName(`${method} ${event.route}`);\n activeSpan.setAttribute(\"http.route\", event.route);\n activeSpan.setAttribute(\"farm.route\", event.route);\n }\n\n if (tracingState.recordEvents) {\n activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);\n }\n\n const error = event.type === \"request.error\" ? undefined : getEventError(event);\n if (error !== undefined) {\n // A recoverable render error (caught by an error boundary) still fires\n // React's onError while the request returns a valid response, so record\n // the exception for visibility but let the actual response status\n // (setResponseStatus) decide the span status instead of forcing the whole\n // request trace to ERROR. A genuinely fatal render error surfaces through\n // the request outcome (a thrown handler or a >= 500 status) and is marked\n // there.\n if (event.type === \"render.error\") {\n recordSpanException(activeSpan, error);\n } else {\n recordSpanError(activeSpan, error);\n }\n }\n }\n\n const completedTraceContext = recordCompletedEventSpan(event, activeContext);\n return traceContext ?? completedTraceContext;\n}\n\nfunction recordCompletedEventSpan(\n event: FarmEvent,\n parentContext: Context,\n): FarmTraceContext | undefined {\n const descriptor = getCompletedSpanDescriptor(event);\n if (!descriptor || !tracingState.spans.has(descriptor.kind)) return undefined;\n\n const tracer = trace.getTracer(FARM_TRACER_NAME);\n const span = tracer.startSpan(\n descriptor.name,\n {\n kind: SpanKind.INTERNAL,\n startTime: event.timestamp - descriptor.durationMs,\n attributes: {\n ...tracingState.attributes,\n ...toEventAttributes(event),\n \"farm.event.type\": event.type,\n },\n },\n parentContext,\n );\n\n const status = \"status\" in event && typeof event.status === \"number\" ? event.status : undefined;\n if (status !== undefined) setResponseStatus(span, status);\n const error = getEventError(event);\n if (error !== undefined) recordSpanError(span, error);\n const traceContext = getSpanTraceContext(span);\n span.end(event.timestamp);\n return traceContext;\n}\n\nfunction getCompletedSpanDescriptor(\n event: FarmEvent,\n): { kind: FarmTraceSpanKind; name: string; durationMs: number } | undefined {\n if (!(\"durationMs\" in event) || typeof event.durationMs !== \"number\") return undefined;\n\n switch (event.type) {\n case \"render.complete\":\n return { kind: \"render\", name: `farm.render ${event.route}`, durationMs: event.durationMs };\n case \"render.stream.shellReady\":\n return {\n kind: \"render\",\n name: `farm.render.shell ${event.route}`,\n durationMs: event.durationMs,\n };\n case \"render.stream.complete\":\n return {\n kind: \"render\",\n name: `farm.render.stream ${event.route}`,\n durationMs: event.durationMs,\n };\n case \"middleware.complete\":\n return {\n kind: \"middleware\",\n name: `farm.middleware ${event.name ?? event.route ?? \"anonymous\"}`,\n durationMs: event.durationMs,\n };\n case \"api.request.complete\":\n case \"api.error\":\n return {\n kind: \"api\",\n name: `farm.api ${event.method} ${event.route}`,\n durationMs: event.durationMs,\n };\n case \"integration.api.call.complete\":\n return {\n kind: \"integration\",\n name: `farm.integration ${event.integration}.${event.operation}`,\n durationMs: event.durationMs,\n };\n case \"storage.query.complete\":\n return {\n kind: \"storage\",\n name: `farm.storage ${event.operation}`,\n durationMs: event.durationMs,\n };\n case \"ppr.refresh.complete\":\n return {\n kind: \"ppr\",\n name: `farm.ppr.refresh ${event.route}`,\n durationMs: event.durationMs,\n };\n case \"build.complete\":\n return {\n kind: \"build\",\n name: `farm.build${event.target ? ` ${event.target}` : \"\"}`,\n durationMs: event.durationMs,\n };\n case \"plugin.hook.complete\":\n return {\n kind: \"plugin\",\n name: `farm.plugin ${event.plugin}.${event.hook}`,\n durationMs: event.durationMs,\n };\n default:\n return undefined;\n }\n}\n\n// A runtime-agnostic, non-cryptographic digest (FNV-1a). This module is bundled\n// into browser and edge runtimes, so it must not import node:crypto; the digest\n// only needs to redact the raw cache key while keeping cache events correlatable,\n// which does not require a cryptographic hash.\nfunction hashFarmCacheKey(value: string): string {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index++) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction toEventAttributes(event: FarmEvent): Attributes {\n const attributes: Attributes = {};\n // A cache event's `key` embeds the serialized arguments of the cached call\n // (e.g. `unstable_cache(getUser)(email)` serializes the email into the key),\n // so it must never be exported verbatim to a tracing backend. Emit a stable\n // digest under `farm.key_hash` instead, preserving cross-event correlation\n // without shipping the sensitive payload.\n const redactKey = typeof event.type === \"string\" && event.type.startsWith(\"cache.\");\n for (const [key, value] of Object.entries(event)) {\n if (\n key === \"timestamp\" ||\n key === \"level\" ||\n key === \"error\" ||\n key === \"traceId\" ||\n key === \"spanId\" ||\n key === \"traceSampled\" ||\n value === undefined\n ) {\n continue;\n }\n if (redactKey && key === \"key\" && typeof value === \"string\") {\n attributes[\"farm.key_hash\"] = hashFarmCacheKey(value);\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n attributes[`farm.${key}`] = value;\n } else if (Array.isArray(value)) {\n if (value.every((entry) => typeof entry === \"string\")) {\n attributes[`farm.${key}`] = value as string[];\n } else if (value.every((entry) => typeof entry === \"number\")) {\n attributes[`farm.${key}`] = value as number[];\n } else if (value.every((entry) => typeof entry === \"boolean\")) {\n attributes[`farm.${key}`] = value as boolean[];\n }\n }\n }\n return attributes;\n}\n\nfunction getEventError(event: FarmEvent): unknown {\n return \"error\" in event ? event.error : undefined;\n}\n\nfunction recordSpanException(span: Span, error: unknown): Error {\n const normalized = error instanceof Error ? error : new Error(String(error));\n span.recordException(normalized);\n return normalized;\n}\n\nfunction recordSpanError(span: Span, error: unknown): void {\n const normalized = recordSpanException(span, error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: normalized.message });\n}\n\nfunction setResponseStatus(span: Span, status: number): void {\n span.setAttribute(\"http.response.status_code\", status);\n if (status >= 500) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n }\n}\n\nfunction resolveResultStatus<T>(result: T, options: FarmRequestSpanOptions): number {\n if (result instanceof Response) return result.status;\n return options.getStatusCode?.() ?? 200;\n}\n\nfunction getSpanTraceContext(span: Span | undefined): FarmTraceContext | undefined {\n if (!span) return undefined;\n const spanContext = span.spanContext();\n if (!isSpanContextValid(spanContext)) return undefined;\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n traceSampled: (spanContext.traceFlags & 0x01) === 0x01,\n };\n}\n","import {\n _runWithFarmRequestSpan,\n configureFarmTracing,\n getFarmTraceContext,\n normalizeFarmTracingConfig,\n recordFarmEventTrace,\n resetFarmTracing,\n runWithFarmSpan,\n type FarmRequestSpanOptions,\n type FarmResolvedTracingConfig,\n type FarmSpanOptions,\n type FarmTraceContext,\n type FarmTraceSpanKind,\n type FarmTracingConfig,\n type FarmTracingUserConfig,\n} from \"./tracing\";\n\nexport type FarmEventLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface FarmEventBase {\n type: string;\n timestamp: number;\n level: FarmEventLevel;\n requestId?: string;\n traceId?: string;\n spanId?: string;\n traceSampled?: boolean;\n route?: string;\n pathname?: string;\n}\n\nexport type FarmRequestEvent =\n | (FarmEventBase & { type: \"request.start\"; method: string; pathname: string })\n | (FarmEventBase & {\n type: \"request.complete\";\n method: string;\n pathname: string;\n status: number;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"request.error\";\n method: string;\n pathname: string;\n durationMs: number;\n error: unknown;\n });\n\nexport type FarmServerEvent =\n | (FarmEventBase & {\n type: \"server.start\";\n mode: \"dev\" | \"preview\" | \"production\";\n port?: number;\n })\n | (FarmEventBase & { type: \"server.ready\"; url?: string })\n | (FarmEventBase & { type: \"server.shutdown\"; reason?: string });\n\nexport type FarmRouteEvent =\n | (FarmEventBase & { type: \"route.discovered\"; route: string; filePath: string })\n | (FarmEventBase & {\n type: \"route.matched\";\n pathname: string;\n route: string;\n params?: Record<string, string>;\n })\n | (FarmEventBase & { type: \"route.notFound\"; pathname: string })\n | (FarmEventBase & { type: \"route.redirect\"; from: string; to: string; status?: number })\n | (FarmEventBase & { type: \"route.rewrite\"; from: string; to: string });\n\nexport type FarmRenderEvent =\n | (FarmEventBase & { type: \"render.start\"; route: string; pathname?: string })\n | (FarmEventBase & {\n type: \"render.complete\";\n route: string;\n durationMs: number;\n status?: number;\n })\n | (FarmEventBase & { type: \"render.error\"; route?: string; error: unknown })\n | (FarmEventBase & { type: \"render.stream.start\"; route: string })\n | (FarmEventBase & { type: \"render.stream.shellReady\"; route: string; durationMs: number })\n | (FarmEventBase & { type: \"render.stream.complete\"; route: string; durationMs: number });\n\nexport type FarmCacheEvent =\n | (FarmEventBase & {\n type: \"cache.hit\";\n key: string;\n route?: string;\n tags?: readonly string[];\n revalidate?: number | false;\n stale?: boolean;\n })\n | (FarmEventBase & { type: \"cache.miss\"; key: string; route?: string; reason?: string })\n | (FarmEventBase & {\n type: \"cache.set\";\n key: string;\n route?: string;\n tags?: readonly string[];\n revalidate?: number | false;\n })\n | (FarmEventBase & { type: \"cache.dedupe\"; key: string })\n | (FarmEventBase & { type: \"cache.bypass\"; key?: string; route?: string; reason: string })\n | (FarmEventBase & {\n type: \"cache.stale\";\n key: string;\n route?: string;\n tags?: readonly string[];\n revalidate?: number | false;\n })\n | (FarmEventBase & { type: \"cache.revalidatePath\"; path: string; count: number })\n | (FarmEventBase & {\n type: \"cache.revalidateTag\";\n tag: string;\n profile?: unknown;\n count: number;\n })\n | (FarmEventBase & { type: \"cache.updateTag\"; tag: string; count: number })\n | (FarmEventBase & {\n type: \"cache.invalidated\";\n key?: string;\n route?: string;\n tag?: string;\n reason?: string;\n count?: number;\n })\n | (FarmEventBase & { type: \"cache.delete\"; key: string; deleted: boolean })\n | (FarmEventBase & { type: \"cache.clear\"; count: number })\n | (FarmEventBase & {\n type: \"cache.error\";\n key?: string;\n operation: \"get\" | \"set\" | \"delete\" | \"revalidate\";\n error: unknown;\n });\n\nexport type FarmPPREvent =\n | (FarmEventBase & { type: \"ppr.shell.hit\"; route: string; key: string })\n | (FarmEventBase & { type: \"ppr.shell.miss\"; route: string; key: string })\n | (FarmEventBase & {\n type: \"ppr.shell.cached\";\n route: string;\n key: string;\n revalidate?: number;\n })\n | (FarmEventBase & { type: \"ppr.shell.bypass\"; route: string; reason: string })\n | (FarmEventBase & {\n type: \"ppr.shell.invalidated\";\n route: string;\n reason?: string;\n count?: number;\n })\n | (FarmEventBase & { type: \"ppr.suspense.holeDetected\"; route: string })\n | (FarmEventBase & { type: \"ppr.refresh.start\"; route: string })\n | (FarmEventBase & { type: \"ppr.refresh.complete\"; route: string; durationMs: number })\n | (FarmEventBase & { type: \"ppr.refresh.error\"; route: string; error: unknown });\n\nexport type FarmAPIEvent =\n | (FarmEventBase & { type: \"api.request.start\"; route: string; method: string })\n | (FarmEventBase & {\n type: \"api.request.complete\";\n route: string;\n method: string;\n status: number;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"api.validation.failed\";\n route: string;\n method: string;\n issues?: unknown;\n })\n | (FarmEventBase & {\n type: \"api.error\";\n route: string;\n method: string;\n durationMs: number;\n error: unknown;\n });\n\nexport type FarmIntegrationEvent =\n | (FarmEventBase & { type: \"integration.registered\"; name: string })\n | (FarmEventBase & { type: \"integration.config.validated\"; name: string })\n | (FarmEventBase & { type: \"integration.ready\"; name: string })\n | (FarmEventBase & { type: \"integration.disposed\"; name: string })\n | (FarmEventBase & {\n type: \"integration.api.call.start\";\n integration: string;\n operation: string;\n })\n | (FarmEventBase & {\n type: \"integration.api.call.complete\";\n integration: string;\n operation: string;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"integration.api.call.error\";\n integration: string;\n operation: string;\n error: unknown;\n })\n | (FarmEventBase & { type: \"integration.webhook.received\"; integration: string; event?: string })\n | (FarmEventBase & { type: \"integration.webhook.verified\"; integration: string; event?: string })\n | (FarmEventBase & { type: \"integration.webhook.failed\"; integration: string; reason: string });\n\nexport type FarmMiddlewareEvent =\n | (FarmEventBase & { type: \"middleware.start\"; route?: string; name?: string })\n | (FarmEventBase & {\n type: \"middleware.complete\";\n route?: string;\n name?: string;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"middleware.shortCircuit\";\n route?: string;\n name?: string;\n status?: number;\n })\n | (FarmEventBase & { type: \"middleware.error\"; route?: string; name?: string; error: unknown });\n\nexport type FarmStorageEvent =\n | (FarmEventBase & { type: \"storage.query.start\"; integration?: string; operation: string })\n | (FarmEventBase & {\n type: \"storage.query.complete\";\n integration?: string;\n operation: string;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"storage.query.error\";\n integration?: string;\n operation: string;\n error: unknown;\n })\n | (FarmEventBase & { type: \"storage.schema.ready\"; integration?: string })\n | (FarmEventBase & { type: \"storage.schema.error\"; integration?: string; error: unknown });\n\nexport type FarmBuildEvent =\n | (FarmEventBase & { type: \"build.start\"; target?: string })\n | (FarmEventBase & { type: \"build.complete\"; target?: string; durationMs: number })\n | (FarmEventBase & { type: \"build.error\"; target?: string; error: unknown })\n | (FarmEventBase & { type: \"routes.generated\"; pageCount: number; apiCount?: number })\n | (FarmEventBase & { type: \"types.generated\"; filePath: string })\n | (FarmEventBase & { type: \"manifest.generated\"; routeCount: number });\n\nexport type FarmPluginEvent =\n | (FarmEventBase & { type: \"plugin.hook.start\"; plugin: string; hook: string })\n | (FarmEventBase & {\n type: \"plugin.hook.complete\";\n plugin: string;\n hook: string;\n durationMs: number;\n })\n | (FarmEventBase & { type: \"plugin.hook.error\"; plugin: string; hook: string; error: unknown });\n\nexport type FarmErrorEvent = FarmEventBase & {\n type: \"error\";\n source: string;\n error: unknown;\n route?: string;\n};\n\nexport type FarmEvent =\n | FarmRequestEvent\n | FarmServerEvent\n | FarmRouteEvent\n | FarmRenderEvent\n | FarmCacheEvent\n | FarmPPREvent\n | FarmAPIEvent\n | FarmIntegrationEvent\n | FarmMiddlewareEvent\n | FarmStorageEvent\n | FarmBuildEvent\n | FarmPluginEvent\n | FarmErrorEvent;\n\nexport type FarmEventType = FarmEvent[\"type\"];\nexport type FarmEventHandler = (event: FarmEvent) => void | Promise<void>;\n\nexport type FarmEventInput = FarmEvent extends infer T\n ? T extends FarmEvent\n ? Omit<T, \"timestamp\" | \"level\"> & Partial<Pick<T, \"timestamp\" | \"level\">>\n : never\n : never;\n\nexport type FarmObservabilityUserConfig =\n | boolean\n | {\n logs?: boolean;\n onEvent?: FarmEventHandler | readonly FarmEventHandler[];\n events?: readonly FarmEventType[];\n tracing?: FarmTracingUserConfig;\n };\n\nexport interface FarmResolvedObservabilityConfig {\n logs: boolean;\n handlers: FarmEventHandler[];\n events?: Set<FarmEventType>;\n tracing: FarmResolvedTracingConfig;\n}\n\nexport interface FarmEventSubscriptionOptions {\n /** Receive events even when they are excluded by `observability.events`. */\n unfiltered?: boolean;\n}\n\nconst runtimeHandlers = new Set<FarmEventHandler>();\nconst unfilteredRuntimeHandlers = new Set<FarmEventHandler>();\nlet observabilityState: FarmResolvedObservabilityConfig = {\n logs: false,\n handlers: [],\n tracing: normalizeFarmTracingConfig(false),\n};\n\nexport function configureFarmObservability(config: FarmObservabilityUserConfig | undefined): void {\n observabilityState = normalizeFarmObservabilityConfig(config);\n configureFarmTracing(observabilityState.tracing);\n}\n\nexport function normalizeFarmObservabilityConfig(\n config: FarmObservabilityUserConfig | undefined,\n): FarmResolvedObservabilityConfig {\n if (config === undefined || config === false) {\n return { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) };\n }\n\n if (config === true) {\n return { logs: true, handlers: [], tracing: normalizeFarmTracingConfig(false) };\n }\n\n const handlers = config.onEvent\n ? Array.isArray(config.onEvent)\n ? [...config.onEvent]\n : [config.onEvent]\n : [];\n\n return {\n logs: config.logs ?? false,\n handlers,\n events: config.events ? new Set(config.events) : undefined,\n tracing: normalizeFarmTracingConfig(config.tracing),\n };\n}\n\nexport function onFarmEvent(\n handler: FarmEventHandler,\n options: FarmEventSubscriptionOptions = {},\n): () => void {\n const handlers = options.unfiltered ? unfilteredRuntimeHandlers : runtimeHandlers;\n handlers.add(handler);\n return () => {\n handlers.delete(handler);\n };\n}\n\nexport function resetFarmObservability(): void {\n runtimeHandlers.clear();\n unfilteredRuntimeHandlers.clear();\n observabilityState = {\n logs: false,\n handlers: [],\n tracing: normalizeFarmTracingConfig(false),\n };\n resetFarmTracing();\n}\n\nexport function emitFarmEvent(input: FarmEventInput): FarmEvent {\n const event = {\n timestamp: Date.now(),\n level: inferFarmEventLevel(input.type),\n ...input,\n } as FarmEvent;\n\n const traceContext = recordFarmEventTrace(event);\n if (traceContext) {\n event.traceId = traceContext.traceId;\n event.spanId = traceContext.spanId;\n event.traceSampled = traceContext.traceSampled;\n }\n\n notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);\n\n if (!shouldEmitFarmEvent(event)) return event;\n\n if (observabilityState.logs) {\n logFarmEvent(event);\n }\n\n notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);\n\n return event;\n}\n\nfunction notifyFarmEventHandlers(event: FarmEvent, handlers: Iterable<FarmEventHandler>): void {\n for (const handler of handlers) {\n try {\n Promise.resolve(handler(event)).catch((error) => {\n console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);\n });\n } catch (error) {\n console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);\n }\n }\n}\n\nexport async function runWithFarmRequestSpan<T>(\n request: Request,\n handler: () => T | Promise<T>,\n options: FarmRequestSpanOptions = {},\n): Promise<T> {\n const url = new URL(request.url);\n const method = request.method || \"GET\";\n return await _runWithFarmRequestSpan(request, handler, {\n ...options,\n onStart() {\n emitFarmEvent({ type: \"request.start\", method, pathname: url.pathname });\n options.onStart?.();\n },\n onComplete(status, durationMs) {\n emitFarmEvent({\n type: \"request.complete\",\n method,\n pathname: url.pathname,\n status,\n durationMs,\n });\n options.onComplete?.(status, durationMs);\n },\n onError(error, durationMs) {\n emitFarmEvent({\n type: \"request.error\",\n method,\n pathname: url.pathname,\n durationMs,\n error,\n });\n options.onError?.(error, durationMs);\n },\n });\n}\n\nexport { configureFarmTracing, getFarmTraceContext, normalizeFarmTracingConfig, runWithFarmSpan };\nexport type {\n FarmRequestSpanOptions,\n FarmResolvedTracingConfig,\n FarmSpanOptions,\n FarmTraceContext,\n FarmTraceSpanKind,\n FarmTracingConfig,\n FarmTracingUserConfig,\n};\n\nfunction shouldEmitFarmEvent(event: FarmEvent): boolean {\n if (\n !observabilityState.logs &&\n observabilityState.handlers.length === 0 &&\n runtimeHandlers.size === 0\n ) {\n return false;\n }\n\n if (observabilityState.events && !observabilityState.events.has(event.type)) {\n return false;\n }\n\n return true;\n}\n\nfunction inferFarmEventLevel(type: FarmEventType): FarmEventLevel {\n if (type === \"error\" || type.endsWith(\".error\") || type.endsWith(\".failed\")) {\n return \"error\";\n }\n if (\n type.endsWith(\".bypass\") ||\n type.endsWith(\".invalidated\") ||\n type.endsWith(\".stale\") ||\n type.endsWith(\".notFound\")\n ) {\n return \"warn\";\n }\n if (\n type.endsWith(\".hit\") ||\n type.endsWith(\".miss\") ||\n type.endsWith(\".start\") ||\n type.endsWith(\".shellReady\")\n ) {\n return \"debug\";\n }\n return \"info\";\n}\n\nfunction logFarmEvent(event: FarmEvent): void {\n const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;\n switch (event.level) {\n case \"error\":\n console.error(message);\n break;\n case \"warn\":\n console.warn(message);\n break;\n default:\n console.log(message);\n break;\n }\n}\n\nfunction formatFarmEventDetails(event: FarmEvent): string {\n const details: string[] = [];\n const record = event as unknown as Record<string, unknown>;\n\n for (const key of [\n \"route\",\n \"pathname\",\n \"method\",\n \"status\",\n \"key\",\n \"tag\",\n \"path\",\n \"reason\",\n \"durationMs\",\n \"integration\",\n \"operation\",\n \"plugin\",\n \"hook\",\n \"target\",\n \"count\",\n ]) {\n const value = record[key];\n if (value !== undefined) {\n details.push(`${key}=${formatDetailValue(value)}`);\n }\n }\n\n return details.length > 0 ? ` ${details.join(\" \")}` : \"\";\n}\n\nfunction formatDetailValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","export type FarmCacheInvalidationListener = (key: string) => void;\nexport type FarmCacheTaskListener = (task: Promise<void>) => void;\n\nexport const FARM_CACHE_INVALIDATION_HEADER = \"x-farm-cache-invalidations\";\n\ntype FarmCacheInvalidationState = {\n listeners: Set<FarmCacheInvalidationListener>;\n taskListeners: Set<FarmCacheTaskListener>;\n};\n\nconst FARM_CACHE_INVALIDATION_STATE = Symbol.for(\"farm.cacheInvalidationState\");\nconst globalState = globalThis as typeof globalThis & {\n [FARM_CACHE_INVALIDATION_STATE]?: FarmCacheInvalidationState;\n};\n\nfunction getFarmCacheInvalidationState(): FarmCacheInvalidationState {\n return (globalState[FARM_CACHE_INVALIDATION_STATE] ??= {\n listeners: new Set(),\n taskListeners: new Set(),\n });\n}\n\nfunction warnFarmCacheListenerError(scope: string, error: unknown): void {\n const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);\n console.warn(`[farm:cache] ${scope} listener failed: ${detail}`);\n}\n\nexport function notifyFarmCacheInvalidation(key: string): void {\n if (typeof key !== \"string\" || key.length === 0) return;\n\n for (const listener of getFarmCacheInvalidationState().listeners) {\n // Isolate listeners: one throwing observer must not abort the remaining\n // listeners (or the rest of a multi-key batch in applyFarmCacheInvalidations)\n // and must not surface as a 500 when invalidation runs inside a request.\n try {\n listener(key);\n } catch (error) {\n warnFarmCacheListenerError(\"invalidation\", error);\n }\n }\n}\n\nexport function notifyFarmCacheTask(task: Promise<void>): void {\n for (const listener of getFarmCacheInvalidationState().taskListeners) {\n try {\n listener(task);\n } catch (error) {\n warnFarmCacheListenerError(\"task\", error);\n }\n }\n}\n\nexport function applyFarmCacheInvalidations(keys: unknown): void {\n if (!Array.isArray(keys)) return;\n\n for (const key of keys) {\n if (typeof key === \"string\") {\n notifyFarmCacheInvalidation(key);\n }\n }\n}\n\nexport function encodeFarmCacheInvalidations(keys: readonly string[]): string | null {\n const normalized = Array.from(\n new Set(keys.filter((key) => typeof key === \"string\" && key.length > 0)),\n );\n if (normalized.length === 0) return null;\n return encodeURIComponent(JSON.stringify(normalized));\n}\n\nexport function decodeFarmCacheInvalidations(value: string | null | undefined): readonly string[] {\n if (!value) return [];\n\n try {\n const parsed = JSON.parse(decodeURIComponent(value));\n return Array.isArray(parsed)\n ? Array.from(\n new Set(parsed.filter((key): key is string => typeof key === \"string\" && key.length > 0)),\n )\n : [];\n } catch {\n return [];\n }\n}\n\nexport function subscribeFarmCacheInvalidation(\n listener: FarmCacheInvalidationListener,\n): () => void {\n const state = getFarmCacheInvalidationState();\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nexport function subscribeFarmCacheTask(listener: FarmCacheTaskListener): () => void {\n const state = getFarmCacheInvalidationState();\n state.taskListeners.add(listener);\n return () => state.taskListeners.delete(listener);\n}\n","import type { FarmI18nClientSnapshot } from \"./types\";\n\ntype SnapshotResolver = () => FarmI18nClientSnapshot | undefined;\n\nconst FARM_I18N_SNAPSHOT_RESOLVER = Symbol.for(\"farm.i18n.snapshotResolver\");\ntype GlobalWithI18nResolver = typeof globalThis & {\n [FARM_I18N_SNAPSHOT_RESOLVER]?: SnapshotResolver;\n};\n\nexport function _setFarmI18nSnapshotResolver(resolver: SnapshotResolver | undefined): void {\n (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER] = resolver;\n}\n\nexport function getActiveFarmI18nSnapshot(): FarmI18nClientSnapshot | undefined {\n if (typeof window !== \"undefined\" && window.__FARM_I18N__) {\n return window.__FARM_I18N__;\n }\n return (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER]?.();\n}\n","import { emitFarmEvent } from \"./observability\";\nimport { notifyFarmCacheInvalidation, notifyFarmCacheTask } from \"./cache-invalidation\";\nimport { getActiveFarmI18nSnapshot } from \"./i18n/bridge\";\n\nexport { applyFarmCacheInvalidations } from \"./cache-invalidation\";\n\nexport type RevalidateTagProfile =\n | \"max\"\n | \"default\"\n | \"seconds\"\n | \"minutes\"\n | \"hours\"\n | \"days\"\n | \"weeks\"\n | \"months\"\n | { expire?: number };\n\nexport interface FarmCacheOptions {\n /**\n * Tag cached data so it can be invalidated with revalidateTag/updateTag.\n */\n tags?: readonly string[];\n /**\n * Path tags let revalidatePath invalidate data tied to a route.\n */\n paths?: readonly string[];\n /**\n * Time in seconds before the entry becomes stale. False means no TTL.\n */\n revalidate?: number | false;\n}\n\nexport interface FarmCacheSetOptions extends FarmCacheOptions {\n createdAt?: number;\n}\n\nexport type RouteDataCacheKey = string | readonly unknown[];\n\nexport type FarmCacheInvalidationTarget =\n | { key: RouteDataCacheKey }\n | { path: string }\n | { tag: string };\n\ndeclare const FARM_DEFINED_CACHE_KEY_DATA: unique symbol;\n\n/**\n * A regular Farm cache key carrying the data shape stored under that key.\n *\n * The brand exists only in TypeScript. At runtime the value remains the\n * original string or structured array, so all existing cache APIs continue to\n * accept untyped keys.\n */\nexport type DefinedCacheKey<TData, TKey extends RouteDataCacheKey = RouteDataCacheKey> = TKey & {\n readonly [FARM_DEFINED_CACHE_KEY_DATA]: TData;\n};\n\nexport type CacheKeyFactory<\n TData,\n TArguments extends readonly unknown[],\n TKey extends RouteDataCacheKey = RouteDataCacheKey,\n> = (...args: TArguments) => DefinedCacheKey<TData, TKey>;\n\nexport type InferCacheKeyData<TKey> =\n TKey extends DefinedCacheKey<infer TData, RouteDataCacheKey> ? TData : unknown;\n\n/**\n * Optionally add a data type to an existing string/array cache-key factory.\n *\n * This helper does not introduce a new runtime key representation. Calling the\n * returned factory produces the exact key returned by `factory`.\n */\nexport function defineCacheKey<TData>() {\n return <const TArguments extends readonly unknown[], const TKey extends RouteDataCacheKey>(\n factory: (...args: TArguments) => TKey,\n ): CacheKeyFactory<TData, TArguments, TKey> => {\n if (typeof factory !== \"function\") {\n throw new TypeError(\"defineCacheKey expects a key factory function.\");\n }\n\n return ((...args: TArguments) => {\n const key = factory(...args);\n if (typeof key !== \"string\" && !Array.isArray(key)) {\n throw new TypeError(\n \"A defined cache key factory must return a string or structured array.\",\n );\n }\n return key as DefinedCacheKey<TData, TKey>;\n }) as CacheKeyFactory<TData, TArguments, TKey>;\n };\n}\n\nexport interface FarmCacheEntry<T = unknown> {\n key: string;\n value: T;\n tags: readonly string[];\n /**\n * Adapter tag versions captured before the cached value was produced.\n * A later version makes the entry stale across every server instance.\n */\n tagVersions?: Readonly<Record<string, number>>;\n createdAt: number;\n createdVersion?: number;\n revalidate?: number | false;\n}\n\ninterface InternalFarmCacheEntry<T = unknown> {\n key: string;\n value: T;\n tags: Set<string>;\n tagVersions?: Readonly<Record<string, number>>;\n createdAt: number;\n createdVersion: number;\n revalidate?: number | false;\n}\n\n/**\n * Asynchronous persistence contract used by distributed Farm caches.\n *\n * Implementations are responsible for serializing cache entries and making\n * tag version updates atomic when the backing service supports it.\n */\nexport interface FarmCacheAdapter {\n readonly name?: string;\n get<T = unknown>(key: string): Promise<FarmCacheEntry<T> | null | undefined>;\n set<T = unknown>(key: string, entry: FarmCacheEntry<T>): Promise<void>;\n delete(key: string): Promise<void>;\n clear?(): Promise<void>;\n getTagVersions?(tags: readonly string[]): Promise<Readonly<Record<string, number>>>;\n invalidateTags?(tags: readonly string[]): Promise<void>;\n /** Atomically acquire a short-lived regeneration lease. */\n acquireLease?(key: string, ttlMs: number): Promise<string | null | undefined>;\n /** Release the lease only when the supplied ownership token still matches. */\n releaseLease?(key: string, token: string): Promise<void>;\n}\n\nexport interface FarmClientCacheUserConfig {\n /**\n * Module path, relative to the project root, whose default export is a\n * client cache adapter (`defineClientCacheAdapter`). The module is bundled\n * into the browser entry; the server never imports it.\n */\n adapter?: string;\n /** Extra version salt, typically a build or deploy id; entries persisted under another salt are dropped. */\n version?: string;\n /** Debounce for persisted write-behind flushes, in milliseconds. */\n flushDelayMs?: number;\n}\n\nexport interface FarmCacheUserConfig {\n /** Shared cache implementation, for example a Redis-backed adapter. */\n adapter?: FarmCacheAdapter;\n /** Prefix isolating applications and deployments sharing one adapter. */\n namespace?: string;\n /** Browser cache persistence; see the client cache adapter documentation. */\n client?: FarmClientCacheUserConfig;\n /**\n * Coordinate cache fills across processes when the adapter implements\n * acquireLease/releaseLease. Set false to disable.\n */\n lease?:\n | false\n | {\n ttlMs?: number;\n waitTimeoutMs?: number;\n pollIntervalMs?: number;\n };\n}\n\nexport interface FarmCacheStorage {\n getItem<T = unknown>(key: string): Promise<T | null>;\n setItem<T = unknown>(key: string, value: T): Promise<unknown>;\n removeItem(key: string): Promise<unknown>;\n clear?(base?: string): Promise<unknown>;\n}\n\nexport interface StorageFarmCacheAdapterOptions {\n /** Prefix used inside the supplied storage client. */\n base?: string;\n}\n\n/**\n * Adapt a Farm/unstorage-compatible key-value client to the cache contract.\n *\n * This is a portable baseline adapter. Provider-specific adapters should use\n * their atomic increment/transaction primitives for tag invalidation.\n */\nexport function storageCacheAdapter(\n storage: FarmCacheStorage,\n options: StorageFarmCacheAdapterOptions = {},\n): FarmCacheAdapter {\n if (!storage || typeof storage.getItem !== \"function\" || typeof storage.setItem !== \"function\") {\n throw new TypeError(\"storageCacheAdapter expects a compatible storage client.\");\n }\n\n const base = normalizeCacheNamespace(options.base || \"farm-cache\");\n const entryKey = (key: string) => `${base}:entry:${key}`;\n const tagKey = (tag: string) => `${base}:tag:${tag}`;\n\n return {\n name: \"storage\",\n get: <T>(key: string) => storage.getItem<FarmCacheEntry<T>>(entryKey(key)),\n set: async <T>(key: string, entry: FarmCacheEntry<T>) => {\n await storage.setItem(entryKey(key), entry);\n },\n delete: async (key: string) => {\n await storage.removeItem(entryKey(key));\n },\n clear: storage.clear\n ? async () => {\n await storage.clear!(base);\n }\n : undefined,\n getTagVersions: async (tags) => {\n const versions = await Promise.all(\n tags.map(async (tag) => {\n const value = await storage.getItem<number>(tagKey(tag));\n return [tag, normalizeAdapterVersion(value)] as const;\n }),\n );\n return Object.fromEntries(versions);\n },\n invalidateTags: async (tags) => {\n await Promise.all(\n tags.map(async (tag) => {\n const key = tagKey(tag);\n const current = normalizeAdapterVersion(await storage.getItem<number>(key));\n await storage.setItem(key, Math.max(Date.now(), current + 1));\n }),\n );\n },\n };\n}\n\nexport interface GetFarmCacheEntryOptions {\n allowStale?: boolean;\n now?: number;\n}\n\ninterface FarmCacheStaleEntry {\n tags: Iterable<string>;\n createdAt: number;\n createdVersion?: number;\n revalidate?: number | false;\n}\n\nexport class FarmDataCache {\n private entries = new Map<string, InternalFarmCacheEntry>();\n private inflight = new Map<string, Promise<unknown>>();\n private invalidatedTagVersions = new Map<string, number>();\n private version = 0;\n private generation = 0;\n private adapter?: FarmCacheAdapter;\n private namespace = \"farm\";\n private local = true;\n private lease = {\n enabled: true,\n ttlMs: 10_000,\n waitTimeoutMs: 10_000,\n pollIntervalMs: 25,\n };\n\n constructor(config: FarmCacheUserConfig = {}) {\n this.configure(config);\n }\n\n configure(config: FarmCacheUserConfig = {}): void {\n this.generation++;\n this.entries.clear();\n this.inflight.clear();\n this.invalidatedTagVersions.clear();\n this.version = 0;\n this.adapter = config.adapter;\n this.namespace = normalizeCacheNamespace(config.namespace || \"farm\");\n this.local = !config.adapter;\n this.lease =\n config.lease === false\n ? { ...this.lease, enabled: false }\n : {\n enabled: true,\n ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 10_000, \"cache.lease.ttlMs\"),\n waitTimeoutMs: normalizePositiveDuration(\n config.lease?.waitTimeoutMs,\n 10_000,\n \"cache.lease.waitTimeoutMs\",\n ),\n pollIntervalMs: normalizePositiveDuration(\n config.lease?.pollIntervalMs,\n 25,\n \"cache.lease.pollIntervalMs\",\n ),\n };\n }\n\n get adapterName(): string {\n return this.adapter?.name || (this.adapter ? \"custom\" : \"memory\");\n }\n\n get hasAdapter(): boolean {\n return this.adapter !== undefined;\n }\n\n get size(): number {\n return this.entries.size;\n }\n\n get<T>(key: string, options: GetFarmCacheEntryOptions = {}): T | undefined {\n return this.getEntry<T>(key, options)?.value;\n }\n\n getEntry<T = unknown>(\n key: string,\n options: GetFarmCacheEntryOptions = {},\n ): FarmCacheEntry<T> | undefined {\n const entry = this.entries.get(key) as InternalFarmCacheEntry<T> | undefined;\n if (!entry) {\n emitFarmEvent({ type: \"cache.miss\", key });\n return undefined;\n }\n\n const stale = this.isStale(entry, options.now);\n if (stale) {\n emitFarmEvent({\n type: \"cache.stale\",\n key,\n tags: Array.from(entry.tags),\n revalidate: entry.revalidate,\n });\n }\n\n if (!options.allowStale && stale) {\n emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n return undefined;\n }\n\n emitFarmEvent({\n type: \"cache.hit\",\n key,\n tags: Array.from(entry.tags),\n revalidate: entry.revalidate,\n stale,\n });\n\n return this.toPublicEntry(entry);\n }\n\n async getEntryAsync<T = unknown>(\n key: string,\n options: GetFarmCacheEntryOptions = {},\n ): Promise<FarmCacheEntry<T> | undefined> {\n if (this.local) {\n const localEntry = this.getEntry<T>(key, options);\n if (localEntry) return localEntry;\n }\n\n if (!this.adapter) {\n return this.local ? undefined : this.getEntry<T>(key, options);\n }\n\n const generation = this.generation;\n const adapter = this.adapter;\n const namespace = this.namespace;\n const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n if (generation !== this.generation) return undefined;\n if (!entry) {\n emitFarmEvent({ type: \"cache.miss\", key });\n return undefined;\n }\n\n assertFarmCacheEntry(entry, key);\n const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);\n if (generation !== this.generation) return undefined;\n if (stale) {\n emitFarmEvent({\n type: \"cache.stale\",\n key,\n tags: [...entry.tags],\n revalidate: entry.revalidate,\n });\n if (!options.allowStale) {\n emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n return undefined;\n }\n }\n\n emitFarmEvent({\n type: \"cache.hit\",\n key,\n tags: [...entry.tags],\n revalidate: entry.revalidate,\n stale,\n });\n\n if (this.local && !stale) {\n this.hydrateLocalEntry(entry);\n }\n return { ...entry, key };\n }\n\n set<T>(key: string, value: T, options: FarmCacheSetOptions = {}): FarmCacheEntry<T> {\n const tags = new Set<string>();\n for (const tag of options.tags ?? []) {\n tags.add(normalizeCacheTag(tag));\n }\n for (const routePath of options.paths ?? []) {\n tags.add(createPathCacheTag(routePath));\n }\n\n const entry: InternalFarmCacheEntry<T> = {\n key,\n value,\n tags,\n tagVersions: undefined,\n createdAt: options.createdAt ?? Date.now(),\n createdVersion: ++this.version,\n revalidate: normalizeRevalidate(options.revalidate),\n };\n\n this.entries.set(key, entry);\n emitFarmEvent({\n type: \"cache.set\",\n key,\n tags: Array.from(tags),\n revalidate: entry.revalidate,\n });\n return this.toPublicEntry(entry);\n }\n\n async setAsync<T>(\n key: string,\n value: T,\n options: FarmCacheSetOptions = {},\n tagVersions?: Readonly<Record<string, number>>,\n ): Promise<FarmCacheEntry<T>> {\n return this.writeAsync(key, value, options, tagVersions);\n }\n\n private async writeAsync<T>(\n key: string,\n value: T,\n options: FarmCacheSetOptions,\n tagVersions?: Readonly<Record<string, number>>,\n createdVersion?: number,\n ): Promise<FarmCacheEntry<T>> {\n const tags = normalizeCacheOptionsTags(options);\n const capturedVersions =\n tagVersions ?? (await this.getAdapterTagVersions(Array.from(tags.values())));\n const entry: FarmCacheEntry<T> = {\n key,\n value,\n tags: Array.from(tags),\n tagVersions: capturedVersions,\n createdAt: options.createdAt ?? Date.now(),\n createdVersion: createdVersion ?? ++this.version,\n revalidate: normalizeRevalidate(options.revalidate),\n };\n\n if (this.local) {\n this.hydrateLocalEntry(entry);\n }\n if (this.adapter) {\n await this.adapter.set(this.createAdapterKey(key), entry);\n }\n\n emitFarmEvent({\n type: \"cache.set\",\n key,\n tags: [...entry.tags],\n revalidate: entry.revalidate,\n });\n return entry;\n }\n\n delete(key: string): boolean {\n const deleted = this.entries.delete(key);\n emitFarmEvent({ type: \"cache.delete\", key, deleted });\n return deleted;\n }\n\n async deleteAsync(key: string): Promise<boolean> {\n const deleted = this.entries.delete(key);\n if (this.adapter) {\n await this.adapter.delete(this.createAdapterKey(key));\n }\n emitFarmEvent({ type: \"cache.delete\", key, deleted: this.adapter ? true : deleted });\n return this.adapter ? true : deleted;\n }\n\n clear(): void {\n const count = this.entries.size;\n this.generation++;\n this.entries.clear();\n this.inflight.clear();\n this.invalidatedTagVersions.clear();\n this.version = 0;\n emitFarmEvent({ type: \"cache.clear\", count });\n }\n\n async clearAsync(): Promise<void> {\n this.clear();\n await this.adapter?.clear?.();\n }\n\n isStale(entry: FarmCacheStaleEntry, now = Date.now()): boolean {\n if (\n typeof entry.revalidate === \"number\" &&\n entry.revalidate >= 0 &&\n now - entry.createdAt >= entry.revalidate * 1000\n ) {\n return true;\n }\n\n for (const tag of entry.tags) {\n const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));\n if (\n typeof invalidatedVersion === \"number\" &&\n typeof entry.createdVersion === \"number\" &&\n invalidatedVersion > entry.createdVersion\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n async isStaleAsync(entry: FarmCacheEntry, now = Date.now()): Promise<boolean> {\n if (this.adapter) {\n return this.isAdapterEntryStale(entry, now);\n }\n return this.isStale(entry, now);\n }\n\n revalidateTag(\n tag: string,\n options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n ): number {\n const normalized = normalizeCacheTag(tag);\n const count = this.invalidateTag(normalized);\n emitFarmEvent(\n options.source === \"updateTag\"\n ? { type: \"cache.updateTag\", tag: normalized, count }\n : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n );\n return count;\n }\n\n async revalidateTagAsync(\n tag: string,\n options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n ): Promise<number> {\n const normalized = normalizeCacheTag(tag);\n const count = this.invalidateTag(normalized);\n await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);\n emitFarmEvent(\n options.source === \"updateTag\"\n ? { type: \"cache.updateTag\", tag: normalized, count }\n : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n );\n return count;\n }\n\n revalidatePath(routePath: string): number {\n const normalizedPath = normalizeRevalidatePath(routePath);\n const pathTag = createPathCacheTag(normalizedPath);\n const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n const count = this.invalidateTag(pathTag);\n emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n if (pprCount > 0) {\n emitFarmEvent({\n type: \"ppr.shell.invalidated\",\n route: normalizedPath,\n reason: \"revalidatePath\",\n count: pprCount,\n });\n }\n\n return count;\n }\n\n async revalidatePathAsync(routePath: string): Promise<number> {\n const normalizedPath = normalizeRevalidatePath(routePath);\n const pathTag = createPathCacheTag(normalizedPath);\n const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n const count = this.invalidateTag(pathTag);\n await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);\n emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n if (pprCount > 0) {\n emitFarmEvent({\n type: \"ppr.shell.invalidated\",\n route: normalizedPath,\n reason: \"revalidatePath\",\n count: pprCount,\n });\n }\n\n return count;\n }\n\n async getOrSet<T>(\n key: string,\n producer: () => Promise<T> | T,\n options: FarmCacheOptions = {},\n ): Promise<T> {\n const cached = await this.getEntryAsync<T>(key);\n if (cached) {\n return cached.value;\n }\n\n const inflight = this.inflight.get(key) as Promise<T> | undefined;\n if (inflight) {\n emitFarmEvent({ type: \"cache.dedupe\", key });\n return inflight;\n }\n\n const tags = Array.from(normalizeCacheOptionsTags(options));\n const generation = this.generation;\n const promise = this.fillCacheEntry(key, producer, options, tags, generation)\n .catch((error) => {\n emitFarmEvent({ type: \"cache.error\", key, operation: \"set\", error });\n throw error;\n })\n .finally(() => {\n if (this.inflight.get(key) === promise) {\n this.inflight.delete(key);\n }\n });\n\n this.inflight.set(key, promise);\n return promise;\n }\n\n private async fillCacheEntry<T>(\n key: string,\n producer: () => Promise<T> | T,\n options: FarmCacheOptions,\n tags: readonly string[],\n generation: number,\n ): Promise<T> {\n const adapter = this.adapter;\n const namespace = this.namespace;\n const lease = { ...this.lease };\n const leaseKey = `${namespace}:lease:${key}`;\n let leaseToken: string | null | undefined;\n\n if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {\n leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n if (!leaseToken) {\n const shared = await this.waitForAdapterEntry<T>(\n key,\n adapter,\n namespace,\n lease,\n generation,\n );\n if (shared) {\n emitFarmEvent({ type: \"cache.dedupe\", key });\n return shared.value;\n }\n if (generation === this.generation) {\n leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n }\n }\n }\n\n try {\n const initialCreatedVersion = this.version;\n const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);\n const value = await producer();\n if (generation === this.generation) {\n await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);\n }\n return value;\n } finally {\n if (leaseToken && adapter?.releaseLease) {\n await adapter.releaseLease(leaseKey, leaseToken);\n }\n }\n }\n\n private async waitForAdapterEntry<T>(\n key: string,\n adapter: FarmCacheAdapter,\n namespace: string,\n lease: typeof this.lease,\n generation: number,\n ): Promise<FarmCacheEntry<T> | undefined> {\n const deadline = Date.now() + lease.waitTimeoutMs;\n while (Date.now() < deadline) {\n await delay(lease.pollIntervalMs);\n if (generation !== this.generation) return undefined;\n const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n if (generation !== this.generation) return undefined;\n if (!entry) {\n emitFarmEvent({ type: \"cache.miss\", key });\n continue;\n }\n assertFarmCacheEntry(entry, key);\n const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);\n if (generation !== this.generation) return undefined;\n if (stale) {\n emitFarmEvent({\n type: \"cache.stale\",\n key,\n tags: [...entry.tags],\n revalidate: entry.revalidate,\n });\n emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n } else {\n emitFarmEvent({\n type: \"cache.hit\",\n key,\n tags: [...entry.tags],\n revalidate: entry.revalidate,\n stale: false,\n });\n return { ...entry, key };\n }\n }\n return undefined;\n }\n\n private countEntriesForTag(tag: string): number {\n let count = 0;\n for (const entry of this.entries.values()) {\n if (entry.tags.has(tag)) {\n count++;\n }\n }\n return count;\n }\n\n private countEntriesForTags(tags: readonly string[]): number {\n let count = 0;\n for (const entry of this.entries.values()) {\n if (tags.every((tag) => entry.tags.has(tag))) {\n count++;\n }\n }\n return count;\n }\n\n private invalidateTag(normalizedTag: string): number {\n this.invalidatedTagVersions.set(normalizedTag, ++this.version);\n return this.countEntriesForTag(normalizedTag);\n }\n\n private toPublicEntry<T>(entry: InternalFarmCacheEntry<T>): FarmCacheEntry<T> {\n return {\n key: entry.key,\n value: entry.value,\n tags: Array.from(entry.tags),\n tagVersions: entry.tagVersions,\n createdAt: entry.createdAt,\n createdVersion: entry.createdVersion,\n revalidate: entry.revalidate,\n };\n }\n\n private hydrateLocalEntry<T>(entry: FarmCacheEntry<T>): void {\n this.entries.set(entry.key, {\n key: entry.key,\n value: entry.value,\n tags: new Set(entry.tags.map(normalizeCacheTag)),\n tagVersions: entry.tagVersions,\n createdAt: entry.createdAt,\n createdVersion: entry.createdVersion ?? ++this.version,\n revalidate: normalizeRevalidate(entry.revalidate),\n });\n }\n\n private createAdapterKey(key: string): string {\n return `${this.namespace}:entry:${key}`;\n }\n\n private createAdapterTag(tag: string): string {\n return `${this.namespace}:tag:${tag}`;\n }\n\n private async getAdapterTagVersions(\n tags: readonly string[],\n adapter = this.adapter,\n namespace = this.namespace,\n ): Promise<Readonly<Record<string, number>>> {\n if (!adapter?.getTagVersions || tags.length === 0) return {};\n\n const normalized = tags.map(normalizeCacheTag);\n const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);\n const versions = await adapter.getTagVersions(physicalTags);\n return Object.fromEntries(\n normalized.map((tag, index) => [\n tag,\n normalizeAdapterVersion(versions[physicalTags[index]!]),\n ]),\n );\n }\n\n private async isAdapterEntryStale(\n entry: FarmCacheEntry,\n now = Date.now(),\n adapter = this.adapter,\n namespace = this.namespace,\n ): Promise<boolean> {\n if (\n typeof entry.revalidate === \"number\" &&\n entry.revalidate >= 0 &&\n now - entry.createdAt >= entry.revalidate * 1000\n ) {\n return true;\n }\n\n const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);\n for (const tag of entry.tags) {\n if (\n normalizeAdapterVersion(currentVersions[tag]) >\n normalizeAdapterVersion(entry.tagVersions?.[tag])\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\nconst FARM_DATA_CACHE_SYMBOL = Symbol.for(\"farm.dataCache\");\nconst farmDataCacheGlobal = globalThis as typeof globalThis & {\n [FARM_DATA_CACHE_SYMBOL]?: FarmDataCache;\n};\nconst sharedFarmDataCache = (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ??= new FarmDataCache());\n\nexport function getFarmDataCache(): FarmDataCache {\n return sharedFarmDataCache;\n}\n\nexport function configureFarmCache(config: FarmCacheUserConfig | undefined): void {\n sharedFarmDataCache.configure(config);\n}\n\n/**\n * Wrap an async function so its results are cached and shared across requests,\n * processes, and restarts.\n *\n * The cache key is built from the wrapped function's identity (its name and a\n * hash of its source), the active locale, `keyParts`, and the call arguments.\n * Deriving identity from the source — rather than the closure instance — is\n * deliberate: it keeps the key stable across processes and restarts so a\n * distributed cache adapter can share entries between server instances.\n *\n * The consequence is that two closures with **identical source text but\n * different captured variables** produce the same identity. Pass those captured\n * values in `keyParts` so they take part in the key; otherwise the closures\n * share a cache entry and return each other's data:\n *\n * ```ts\n * // Collides: both closures have identical source, and `table` is captured,\n * // not an argument, so it never reaches the key.\n * const makeLoader = (table: string) =>\n * unstable_cache(async (id: number) => db.get(table, id));\n *\n * // Correct: the captured value disambiguates the two closures.\n * const makeLoader = (table: string) =>\n * unstable_cache(async (id: number) => db.get(table, id), [table]);\n * ```\n *\n * Values passed as call arguments already participate in the key and do not\n * need to be repeated in `keyParts`.\n *\n * @param fn The async function to memoize.\n * @param keyParts Extra values that identify this call site. Include every\n * variable the function closes over that is not one of its arguments.\n * @param options Tags, paths, and revalidation settings for the cached entry.\n */\nexport function unstable_cache<Args extends unknown[], Result>(\n fn: (...args: Args) => Result | Promise<Result>,\n keyParts: readonly unknown[] = [],\n options: FarmCacheOptions = {},\n): (...args: Args) => Promise<Result> {\n return async (...args: Args): Promise<Result> => {\n const locale = getActiveFarmI18nSnapshot()?.locale;\n const key = createFarmCacheKey([\n \"unstable_cache\",\n getFunctionCacheIdentity(fn),\n locale ? [\"locale\", locale] : null,\n keyParts,\n args,\n ]);\n return getFarmDataCache().getOrSet<Result>(key, () => fn(...args), options);\n };\n}\n\n/**\n * Invalidate every cache entry carrying `tag`.\n *\n * Observability note: the `count` on the emitted `cache.revalidateTag` event is\n * derived from Farm's process-local entry tracking. With a shared `cache.adapter`\n * configured, entries live in the adapter rather than in local memory, so the\n * count can read as `0` even though the invalidation is still propagated to the\n * adapter and applied. Treat it as a best-effort signal, not a distributed count.\n */\nexport function revalidateTag(_tag: string, _profile?: RevalidateTagProfile): void | Promise<void> {\n const cache = getFarmDataCache();\n if (cache.hasAdapter) {\n const task = cache\n .revalidateTagAsync(_tag, {\n source: \"revalidateTag\",\n profile: _profile,\n })\n .then(() => undefined);\n notifyFarmCacheTask(task);\n return task;\n }\n cache.revalidateTag(_tag, {\n source: \"revalidateTag\",\n profile: _profile,\n });\n}\n\nexport function updateTag(tag: string): void | Promise<void> {\n const cache = getFarmDataCache();\n if (cache.hasAdapter) {\n const task = cache.revalidateTagAsync(tag, { source: \"updateTag\" }).then(() => undefined);\n notifyFarmCacheTask(task);\n return task;\n }\n cache.revalidateTag(tag, { source: \"updateTag\" });\n}\n\n/**\n * Invalidate cached data for a route path (and its PPR shell, if any).\n *\n * Observability note: the `count` on the emitted `cache.revalidatePath` event and\n * the `ppr.shell.invalidated` event are derived from process-local entry tracking.\n * With a shared `cache.adapter`, PPR shells live in the adapter rather than in\n * local memory, so the count can read as `0` and `ppr.shell.invalidated` may not\n * be emitted even though the invalidation is still propagated to the adapter and\n * applied.\n */\nexport function revalidatePath(routePath: string): void | Promise<void> {\n const cache = getFarmDataCache();\n if (cache.hasAdapter) {\n const task = cache.revalidatePathAsync(routePath).then(() => undefined);\n notifyFarmCacheTask(task);\n return task;\n }\n cache.revalidatePath(routePath);\n}\n\nexport function invalidate(key: RouteDataCacheKey): void | Promise<void> {\n const clientKey = createRouteDataCacheKey(key);\n const task = updateTag(createRouteDataCacheTag(key));\n notifyFarmCacheInvalidation(clientKey);\n return task;\n}\n\nexport function invalidateRouteData(key: RouteDataCacheKey): void | Promise<void> {\n return invalidate(key);\n}\n\n/**\n * Apply a normalized set of invalidation targets and return browser cache keys\n * that should be carried with an action/endpoint response.\n */\nexport async function applyFarmCacheInvalidationTargets(\n targets: readonly FarmCacheInvalidationTarget[],\n): Promise<readonly string[]> {\n if (!Array.isArray(targets)) {\n throw new TypeError(\"Cache invalidations must resolve to an array of targets.\");\n }\n\n const clientKeys: string[] = [];\n for (const target of targets) {\n assertFarmCacheInvalidationTarget(target);\n if (\"key\" in target) {\n await invalidate(target.key);\n clientKeys.push(createRouteDataCacheKey(target.key));\n } else if (\"path\" in target) {\n await revalidatePath(target.path);\n } else {\n await updateTag(target.tag);\n }\n }\n return Array.from(new Set(clientKeys));\n}\n\nexport function createPathCacheTag(routePath: string): string {\n return `path:${normalizeRevalidatePath(routePath)}`;\n}\n\nexport function createRouteDataCacheTag(key: RouteDataCacheKey): string {\n return `route-data:${createRouteDataCacheKey(key)}`;\n}\n\nexport function createRouteDataCacheKey(key: RouteDataCacheKey): string {\n return createFarmCacheKey(Array.isArray(key) ? key : [key]);\n}\n\nexport function normalizeRevalidatePath(routePath: string): string {\n if (typeof routePath !== \"string\") {\n throw new TypeError(\"revalidatePath expects a path string.\");\n }\n\n let normalized = routePath.trim();\n if (!normalized) {\n throw new Error(\"revalidatePath expects a non-empty path.\");\n }\n\n try {\n if (/^https?:\\/\\//i.test(normalized)) {\n normalized = new URL(normalized).pathname;\n }\n } catch {\n // Keep the original path if URL parsing fails.\n }\n\n normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;\n normalized = normalized.startsWith(\"/\") ? normalized : `/${normalized}`;\n normalized = normalized.replace(/\\/{2,}/g, \"/\");\n if (normalized.length > 1) {\n normalized = normalized.replace(/\\/+$/, \"\");\n }\n return normalized || \"/\";\n}\n\nexport function createFarmCacheKey(parts: readonly unknown[]): string {\n return stableSerialize(parts);\n}\n\nfunction normalizeRevalidate(revalidate: number | false | undefined): number | false | undefined {\n if (revalidate === false || revalidate === undefined) {\n return revalidate;\n }\n if (!Number.isFinite(revalidate) || revalidate < 0) {\n return undefined;\n }\n // 0 is meaningful: the entry is stale immediately, i.e. always re-produced.\n return revalidate;\n}\n\nfunction normalizeCacheTag(tag: string): string {\n if (typeof tag !== \"string\") {\n throw new TypeError(\"Cache tags must be strings.\");\n }\n const normalized = tag.trim();\n if (!normalized) {\n throw new Error(\"Cache tags cannot be empty.\");\n }\n return normalized;\n}\n\nfunction normalizeCacheNamespace(namespace: string): string {\n if (typeof namespace !== \"string\") {\n throw new TypeError(\"Cache namespace must be a string.\");\n }\n const normalized = namespace.trim().replace(/:+$/g, \"\");\n if (!normalized) {\n throw new Error(\"Cache namespace cannot be empty.\");\n }\n return normalized;\n}\n\nfunction normalizeAdapterVersion(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\n}\n\nfunction normalizePositiveDuration(\n value: number | undefined,\n fallback: number,\n name: string,\n): number {\n if (value === undefined) return fallback;\n if (!Number.isFinite(value) || value <= 0) {\n throw new TypeError(`${name} must be a positive number of milliseconds.`);\n }\n return Math.floor(value);\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction normalizeCacheOptionsTags(options: FarmCacheOptions): Set<string> {\n const tags = new Set<string>();\n for (const tag of options.tags ?? []) {\n tags.add(normalizeCacheTag(tag));\n }\n for (const routePath of options.paths ?? []) {\n tags.add(createPathCacheTag(routePath));\n }\n return tags;\n}\n\nfunction assertFarmCacheEntry(\n entry: FarmCacheEntry,\n expectedKey: string,\n): asserts entry is FarmCacheEntry {\n if (\n !entry ||\n typeof entry !== \"object\" ||\n entry.key !== expectedKey ||\n !Array.isArray(entry.tags) ||\n typeof entry.createdAt !== \"number\"\n ) {\n throw new TypeError(\n `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`,\n );\n }\n}\n\nfunction assertFarmCacheInvalidationTarget(\n target: unknown,\n): asserts target is FarmCacheInvalidationTarget {\n if (!target || typeof target !== \"object\") {\n throw new TypeError(\"Cache invalidation targets must be { key }, { path }, or { tag }.\");\n }\n\n if (\"key\" in target) {\n const key = (target as { key?: unknown }).key;\n if (typeof key === \"string\" || Array.isArray(key)) return;\n } else if (\"path\" in target && typeof (target as { path?: unknown }).path === \"string\") {\n return;\n } else if (\"tag\" in target && typeof (target as { tag?: unknown }).tag === \"string\") {\n return;\n }\n\n throw new TypeError(\"Cache invalidation targets must contain a string/array key, path, or tag.\");\n}\n\nfunction getFunctionCacheIdentity(fn: Function): string {\n // The name alone collides across modules — two different functions both\n // named getUser would share cache entries. Include a hash of the source so\n // only genuinely identical functions share, and the identity stays stable\n // across processes and restarts.\n const name = fn.name || \"anonymous\";\n return `${name}:${hashFunctionSource(String(fn))}`;\n}\n\nfunction hashFunctionSource(source: string): string {\n // FNV-1a, 32-bit.\n let hash = 0x811c9dc5;\n for (let index = 0; index < source.length; index++) {\n hash ^= source.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction compareCodepoint(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction serializeBinaryBytes(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction stableSerialize(value: unknown, seen = new WeakSet<object>()): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n\n const valueType = typeof value;\n if (valueType === \"string\") return JSON.stringify(value);\n if (valueType === \"number\" || valueType === \"boolean\" || valueType === \"bigint\") {\n return `${valueType}:${String(value)}`;\n }\n if (valueType === \"symbol\") {\n return `symbol:${String(value)}`;\n }\n if (valueType === \"function\") {\n return `function:${getFunctionCacheIdentity(value as Function)}`;\n }\n\n if (value instanceof Date) {\n // toISOString throws on an Invalid Date. Key building must not throw on a\n // supported type, so all invalid dates share one stable marker and the\n // caller's own validation decides what to do with the input.\n return Number.isNaN(value.getTime()) ? \"date:invalid\" : `date:${value.toISOString()}`;\n }\n if (value instanceof URL) {\n return `url:${value.toString()}`;\n }\n if (value instanceof RegExp) {\n return `regexp:${value.toString()}`;\n }\n if (value instanceof ArrayBuffer) {\n return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n }\n if (typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer) {\n return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n }\n if (ArrayBuffer.isView(value)) {\n const viewType = Object.prototype.toString.call(value).slice(8, -1);\n const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;\n }\n\n if (value && typeof value === \"object\") {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const items: string[] = [];\n for (let index = 0; index < value.length; index++) {\n items.push(\n Object.prototype.hasOwnProperty.call(value, index)\n ? stableSerialize(value[index], seen)\n : \"[Hole]\",\n );\n }\n seen.delete(value);\n return `[${items.join(\",\")}]`;\n }\n\n // Set and Map keep their contents internally, so Object.entries is empty\n // for both. Serialize the contents and sort them by codepoint so equal\n // contents give the same key regardless of insertion order.\n if (value instanceof Set) {\n const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);\n seen.delete(value);\n return `set:[${items.join(\",\")}]`;\n }\n if (value instanceof Map) {\n const items = Array.from(\n value,\n ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`,\n ).sort(compareCodepoint);\n seen.delete(value);\n return `map:[${items.join(\",\")}]`;\n }\n\n // Codepoint comparison, not localeCompare: the host locale must not\n // change how a \"stable\" key serializes, or invalidations computed on one\n // server can miss entries written by another.\n const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>\n compareCodepoint(a, b),\n );\n const serialized = entries\n .map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`)\n .join(\",\");\n\n seen.delete(value);\n return `{${serialized}}`;\n }\n\n return String(value);\n}\n","export type RouteSegmentSpecificity = \"static\" | \"dynamic\" | \"catch-all\" | \"optional-catch-all\";\n\nexport class AmbiguousRouteError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AmbiguousRouteError\";\n }\n}\n\nexport class NonTerminalCatchAllRouteError extends TypeError {\n constructor(message: string) {\n super(message);\n this.name = \"NonTerminalCatchAllRouteError\";\n }\n}\n\nexport class DuplicateRouteParameterError extends AmbiguousRouteError {\n constructor(message: string) {\n super(message);\n this.name = \"DuplicateRouteParameterError\";\n }\n}\n\nexport class ReservedRouteParameterError extends AmbiguousRouteError {\n constructor(message: string) {\n super(message);\n this.name = \"ReservedRouteParameterError\";\n }\n}\n\nexport class BrowserUnstableRouteError extends TypeError {\n constructor(message: string) {\n super(message);\n this.name = \"BrowserUnstableRouteError\";\n }\n}\n\nconst SEGMENT_RANK: Record<RouteSegmentSpecificity, number> = {\n static: 4,\n dynamic: 3,\n \"catch-all\": 1,\n \"optional-catch-all\": 0,\n};\n\n// Ending a route is more specific than consuming the same path through a\n// catch-all, while a following static or dynamic segment remains more specific.\nconst ROUTE_END_RANK = 2;\n\n/** Sort route patterns from the most specific segment sequence to the least specific. */\nexport function compareRouteSpecificity(\n left: readonly RouteSegmentSpecificity[],\n right: readonly RouteSegmentSpecificity[],\n): number {\n const length = Math.max(left.length, right.length);\n\n for (let index = 0; index < length; index++) {\n const leftRank = index < left.length ? SEGMENT_RANK[left[index]!] : ROUTE_END_RANK;\n const rightRank = index < right.length ? SEGMENT_RANK[right[index]!] : ROUTE_END_RANK;\n if (leftRank !== rightRank) return rightRank - leftRank;\n }\n\n return 0;\n}\n\nexport type RoutePatternSyntax = \"page\" | \"router\" | \"api\";\n\nconst ROUTER_PARAMETER_NAME = \"[A-Za-z0-9_$-]+\";\nconst PAGE_PARAMETER_PATTERN = /^(?:\\[\\[\\.\\.\\.(.+)\\]\\]|\\[\\.\\.\\.(.+)\\]|\\[(.+)\\])$/;\nconst ROUTER_PARAMETER_PATTERN =\n /^(?:\\[\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]\\]|\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]|\\[([A-Za-z0-9_$-]+)\\]|:([A-Za-z0-9_$-]+)|\\*([A-Za-z0-9_$-]+)\\??)$/;\nconst RESERVED_PARAMETER_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function assertBrowserStableRoutePath(pattern: string): void {\n if (pattern.includes(\"\\\\\") || hasControlCharacter(pattern)) {\n throw new BrowserUnstableRouteError(\n `Route path \"${pattern}\" cannot contain backslashes or control characters.`,\n );\n }\n\n for (const segment of pattern.split(\"/\").filter(Boolean)) {\n if (\n (segment.startsWith(\"(\") && segment.endsWith(\")\")) ||\n (segment.startsWith(\"[\") && segment.endsWith(\"]\"))\n ) {\n continue;\n }\n\n let decoded = segment;\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n // Malformed escapes stay literal in browser pathnames.\n }\n if (\n decoded === \".\" ||\n decoded === \"..\" ||\n decoded.includes(\"/\") ||\n decoded.includes(\"\\\\\") ||\n hasControlCharacter(decoded)\n ) {\n throw new BrowserUnstableRouteError(\n `Route path \"${pattern}\" contains browser-unstable segment \"${segment}\".`,\n );\n }\n }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n return Array.from(value).some((character) => {\n const code = character.charCodeAt(0);\n return code <= 31 || (code >= 127 && code <= 159);\n });\n}\n\nexport function assertUniqueRouteParameters(\n pattern: string,\n syntax: RoutePatternSyntax = \"page\",\n): void {\n const parameterPattern = syntax === \"router\" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;\n const names = new Set<string>();\n\n for (const segment of splitRoutePattern(pattern, syntax)) {\n const match = parameterPattern.exec(segment);\n const name = match?.slice(1).find(Boolean);\n if (!name) continue;\n if (RESERVED_PARAMETER_NAMES.has(name)) {\n throw new ReservedRouteParameterError(\n `Route parameter \"${name}\" in route \"${pattern}\" is reserved. Use a different parameter name.`,\n );\n }\n if (names.has(name)) {\n throw new DuplicateRouteParameterError(\n `Duplicate route parameter \"${name}\" in route \"${pattern}\". Each dynamic segment must use a unique name.`,\n );\n }\n names.add(name);\n }\n}\n\nfunction splitRoutePattern(pattern: string, syntax: RoutePatternSyntax): string[] {\n return pattern\n .replace(/\\\\/g, \"/\")\n .split(\"/\")\n .filter(Boolean)\n .filter((segment) =>\n syntax === \"api\" ? true : !(segment.startsWith(\"(\") && segment.endsWith(\")\")),\n );\n}\n\nexport function assertTerminalCatchAll(pattern: string, syntax: RoutePatternSyntax = \"page\"): void {\n const segments = splitRoutePattern(pattern, syntax);\n const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n const catchAllPattern = new RegExp(\n syntax === \"router\"\n ? `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]|\\\\*${parameterName}\\\\??)$`\n : `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\])$`,\n );\n const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));\n if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {\n throw new NonTerminalCatchAllRouteError(\n `Catch-all segment \"${segments[catchAllIndex]}\" must be the final segment in route \"${pattern}\".`,\n );\n }\n}\n\n/** Return the URL-matching shape of a route without its parameter names. */\nexport function getRoutePatternShape(pattern: string, syntax: RoutePatternSyntax = \"page\"): string {\n assertTerminalCatchAll(pattern, syntax);\n const segments = splitRoutePattern(pattern, syntax).map((segment) => {\n const specificity = getPatternSegmentSpecificity(segment, syntax);\n if (specificity !== \"static\") return specificity;\n\n try {\n return `static:${decodeURIComponent(segment)}`;\n } catch {\n return `static:${segment}`;\n }\n });\n\n return segments.length === 0 ? \"/\" : JSON.stringify(segments);\n}\n\n/** Return the specificity of every URL-consuming segment in a route pattern. */\nexport function getRoutePatternSpecificity(\n pattern: string,\n syntax: RoutePatternSyntax = \"page\",\n): RouteSegmentSpecificity[] {\n assertTerminalCatchAll(pattern, syntax);\n return splitRoutePattern(pattern, syntax).map((segment) =>\n getPatternSegmentSpecificity(segment, syntax),\n );\n}\n\nfunction getPatternSegmentSpecificity(\n segment: string,\n syntax: RoutePatternSyntax,\n): RouteSegmentSpecificity {\n const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n const supportsColonAndStar = syntax === \"router\";\n if (\n new RegExp(`^\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]$`).test(segment) ||\n (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}\\\\?$`).test(segment))\n ) {\n return \"optional-catch-all\";\n }\n if (\n new RegExp(`^\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]$`).test(segment) ||\n (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}$`).test(segment))\n ) {\n return \"catch-all\";\n }\n if (\n new RegExp(`^\\\\[${parameterName}\\\\]$`).test(segment) ||\n (supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment))\n ) {\n return \"dynamic\";\n }\n\n return \"static\";\n}\n","import type { ParsedRoute } from \"./types\";\nimport {\n assertBrowserStableRoutePath,\n assertTerminalCatchAll,\n assertUniqueRouteParameters,\n} from \"./routing/specificity\";\n\nexport const PROGRAMMATIC_ROUTE_FILE_NAMES = [\n \"farm.route.ts\",\n \"farm.route.tsx\",\n \"farm.route.js\",\n \"farm.route.jsx\",\n \"farm.routes.ts\",\n \"farm.routes.tsx\",\n \"farm.routes.js\",\n \"farm.routes.jsx\",\n \"routes.ts\",\n \"routes.tsx\",\n \"routes.js\",\n \"routes.jsx\",\n] as const;\n\nexport interface ProgrammaticRouteSearchClientOptions {\n stripDefaults?: boolean | readonly string[];\n preserve?: readonly string[];\n temporary?: readonly string[];\n}\n\ntype ProgrammaticRouteSearchLike =\n | { parse(value: unknown): unknown }\n | ({\n schema?: { parse(value: unknown): unknown };\n } & ProgrammaticRouteSearchClientOptions);\n\nexport function getProgrammaticRouteSearchClientOptions(\n search: ProgrammaticRouteSearchLike | undefined,\n): ProgrammaticRouteSearchClientOptions | undefined {\n if (!search || \"parse\" in search) return undefined;\n\n const options: ProgrammaticRouteSearchClientOptions = {};\n if (typeof search.stripDefaults !== \"undefined\") options.stripDefaults = search.stripDefaults;\n if (search.preserve?.length) options.preserve = [...search.preserve];\n if (search.temporary?.length) options.temporary = [...search.temporary];\n\n return Object.keys(options).length > 0 ? options : undefined;\n}\n\nexport function isProgrammaticRoutesFileName(fileName: string): boolean {\n const normalized = fileName.replace(/\\\\/g, \"/\");\n const baseName = normalized.split(\"/\").pop() || normalized;\n return PROGRAMMATIC_ROUTE_FILE_NAMES.includes(\n baseName as (typeof PROGRAMMATIC_ROUTE_FILE_NAMES)[number],\n );\n}\n\nexport function createProgrammaticRouteModuleId(\n filePath: string,\n kind: \"page\" | \"layout\" | \"api\",\n routePath: string,\n): string {\n return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeProgrammaticRoutePath(routePath))}`;\n}\n\nexport function parseProgrammaticRouteModuleId(moduleId: string): {\n filePath: string;\n kind: \"page\" | \"layout\" | \"api\";\n routePath: string;\n} | null {\n const queryIndex = moduleId.indexOf(\"?\");\n if (queryIndex === -1) return null;\n\n const filePath = moduleId.slice(0, queryIndex);\n const params = new URLSearchParams(moduleId.slice(queryIndex + 1));\n const value = params.get(\"farm-route\");\n if (!value) return null;\n\n const separator = value.indexOf(\":\");\n if (separator === -1) return null;\n\n const kind = value.slice(0, separator);\n if (kind !== \"page\" && kind !== \"layout\" && kind !== \"api\") return null;\n\n return {\n filePath,\n kind,\n routePath: normalizeProgrammaticRoutePath(value.slice(separator + 1)),\n };\n}\n\nexport function parseProgrammaticRoutePath(\n routePath: string,\n type: ParsedRoute[\"type\"] = \"page\",\n): ParsedRoute {\n const fileName = type === \"layout\" ? \"layout.tsx\" : \"page.tsx\";\n const normalized = normalizeProgrammaticRoutePath(routePath);\n assertTerminalCatchAll(normalized);\n assertUniqueRouteParameters(normalized);\n const filePath =\n normalized === \"/\" ? fileName : `${normalized.slice(1).replace(/\\/+$/, \"\")}/${fileName}`;\n\n return {\n filePath,\n segments: normalized\n .split(\"/\")\n .filter(Boolean)\n .filter((segment) => !(segment.startsWith(\"(\") && segment.endsWith(\")\")))\n .map(parseRouteSegment),\n type,\n };\n}\n\nexport function scanProgrammaticPagePaths(source: string): string[] {\n const paths = new Set<string>();\n const callRe = /\\b(?:page|createRoute)\\s*\\(\\s*([\"'`])([^\"'`]+)\\1/g;\n\n for (const match of source.matchAll(callRe)) {\n if (match[2]) paths.add(normalizeProgrammaticRoutePath(match[2]));\n }\n\n return Array.from(paths);\n}\n\nexport function normalizeProgrammaticRoutePath(routePath: string): string {\n if (routePath.includes(\"?\") || routePath.includes(\"#\")) {\n throw new TypeError(\n `Programmatic route path \"${routePath}\" must be a pathname without a query string or hash.`,\n );\n }\n const withSlash = routePath.startsWith(\"/\") ? routePath : `/${routePath}`;\n const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n assertBrowserStableRoutePath(withoutTrailing);\n return withoutTrailing || \"/\";\n}\n\nfunction parseRouteSegment(segment: string): ParsedRoute[\"segments\"][number] {\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n let name = segment.slice(1, -1);\n let isOptional = false;\n let isCatchAll = false;\n\n if (name.startsWith(\"[\") && name.endsWith(\"]\")) {\n isOptional = true;\n name = name.slice(1, -1);\n }\n\n if (name.startsWith(\"...\")) {\n isCatchAll = true;\n name = name.slice(3);\n }\n\n return { segment: name, isDynamic: true, isOptional, isCatchAll };\n }\n\n return { segment, isDynamic: false, isOptional: false, isCatchAll: false };\n}\n","export type FarmRouteRuntime = \"auto\" | \"node\" | \"edge\";\nexport type FarmRouteRegions = \"auto\" | readonly string[];\nexport type FarmRouteMaxDuration = \"auto\" | number;\n\n/** Portable execution controls shared by file, programmatic, and config routes. */\nexport interface FarmRouteRuntimeConfig {\n runtime?: FarmRouteRuntime;\n regions?: FarmRouteRegions;\n maxDuration?: FarmRouteMaxDuration;\n}\n\nexport interface ResolvedFarmRouteRuntimeConfig {\n runtime: FarmRouteRuntime;\n regions?: string[];\n maxDuration?: number;\n}\n\nexport type FarmRouteRuntimeEntryKind = \"page\" | \"api\" | \"metadata\" | \"rule\";\nexport type FarmRouteRenderingMode = \"static\" | \"dynamic\";\n\nexport interface FarmRouteRuntimeManifestEntry extends ResolvedFarmRouteRuntimeConfig {\n kind: FarmRouteRuntimeEntryKind;\n pattern: string;\n rendering: FarmRouteRenderingMode;\n source?: string;\n}\n\nexport interface FarmRouteRuntimeManifest {\n version: 1;\n routes: FarmRouteRuntimeManifestEntry[];\n}\n\nexport function normalizeFarmRouteRuntimeConfig(\n value: FarmRouteRuntimeConfig | null | undefined,\n source = \"Route configuration\",\n): FarmRouteRuntimeConfig {\n if (!value) return {};\n\n const normalized: FarmRouteRuntimeConfig = {};\n\n if (value.runtime !== undefined) {\n if (value.runtime !== \"auto\" && value.runtime !== \"node\" && value.runtime !== \"edge\") {\n throw new TypeError(`${source} runtime must be \"auto\", \"node\", or \"edge\"`);\n }\n normalized.runtime = value.runtime;\n }\n\n if (value.regions !== undefined) {\n if (value.regions === \"auto\") {\n normalized.regions = \"auto\";\n } else {\n if (!Array.isArray(value.regions) || value.regions.length === 0) {\n throw new TypeError(`${source} regions must be \"auto\" or a non-empty string array`);\n }\n\n const regions = Array.from(\n new Set(\n value.regions.map((region) => {\n if (\n typeof region !== \"string\" ||\n !region.trim() ||\n /[\\u0000-\\u001f\\u007f]/.test(region)\n ) {\n throw new TypeError(`${source} regions must contain non-empty region identifiers`);\n }\n return region.trim();\n }),\n ),\n );\n\n normalized.regions = regions;\n }\n }\n\n if (value.maxDuration !== undefined) {\n if (value.maxDuration === \"auto\") {\n normalized.maxDuration = \"auto\";\n } else if (\n typeof value.maxDuration !== \"number\" ||\n !Number.isInteger(value.maxDuration) ||\n value.maxDuration <= 0\n ) {\n throw new TypeError(`${source} maxDuration must be \"auto\" or a positive integer in seconds`);\n } else {\n normalized.maxDuration = value.maxDuration;\n }\n }\n\n return normalized;\n}\n\n/** Merge from lowest to highest precedence. Explicit \"auto\" values reset inherited hints. */\nexport function mergeFarmRouteRuntimeConfigs(\n ...configs: Array<FarmRouteRuntimeConfig | null | undefined>\n): FarmRouteRuntimeConfig {\n const merged: FarmRouteRuntimeConfig = {};\n\n for (const config of configs) {\n if (!config) continue;\n if (config.runtime !== undefined) merged.runtime = config.runtime;\n if (config.regions !== undefined) merged.regions = config.regions;\n if (config.maxDuration !== undefined) merged.maxDuration = config.maxDuration;\n }\n\n return merged;\n}\n\nexport function resolveFarmRouteRuntimeConfig(\n config: FarmRouteRuntimeConfig | null | undefined,\n source?: string,\n): ResolvedFarmRouteRuntimeConfig {\n const normalized = normalizeFarmRouteRuntimeConfig(config, source);\n\n return {\n runtime: normalized.runtime ?? \"auto\",\n ...(normalized.regions && normalized.regions !== \"auto\"\n ? { regions: [...normalized.regions] }\n : {}),\n ...(typeof normalized.maxDuration === \"number\" ? { maxDuration: normalized.maxDuration } : {}),\n };\n}\n\nexport function hasFarmRouteRuntimeControls(\n config: FarmRouteRuntimeConfig | null | undefined,\n): boolean {\n return Boolean(\n config &&\n (config.runtime !== undefined ||\n config.regions !== undefined ||\n config.maxDuration !== undefined),\n );\n}\n\nexport function getFarmRouteRuntimeConfig(value: unknown): FarmRouteRuntimeConfig {\n if (!value || typeof value !== \"object\") return {};\n const route = value as FarmRouteRuntimeConfig;\n return {\n ...(route.runtime !== undefined ? { runtime: route.runtime } : {}),\n ...(route.regions !== undefined ? { regions: route.regions } : {}),\n ...(route.maxDuration !== undefined ? { maxDuration: route.maxDuration } : {}),\n };\n}\n\nexport function createFarmRouteRuntimeKey(config: ResolvedFarmRouteRuntimeConfig): string {\n return JSON.stringify({\n runtime: config.runtime,\n regions: config.regions || null,\n maxDuration: config.maxDuration || null,\n });\n}\n\n/** Resolve matching route rules from broadest to most specific. */\nexport function resolveFarmRouteRuleRuntimeConfig(\n pathname: string,\n routeRules: Record<string, FarmRouteRuntimeConfig> | null | undefined,\n): FarmRouteRuntimeConfig {\n if (!routeRules) return {};\n\n const matches = Object.entries(routeRules)\n .filter(\n ([pattern, rule]) =>\n hasFarmRouteRuntimeControls(rule) && farmRouteRuleMatches(pattern, pathname),\n )\n .sort(([left], [right]) => compareFarmRouteRuleSpecificity(left, right));\n\n return mergeFarmRouteRuntimeConfigs(...matches.map(([, rule]) => rule));\n}\n\nexport function farmRouteRuleMatches(pattern: string, pathname: string): boolean {\n const normalizedPattern = normalizeRoutePattern(pattern);\n const normalizedPathname = normalizeRoutePattern(pathname);\n if (normalizedPattern === normalizedPathname) return true;\n\n const expression = normalizedPattern\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (segment === \"**\") return \".*\";\n if (segment === \"*\") return \"[^/]+\";\n if (/^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)) return \".*\";\n if (/^\\[\\.\\.\\..+\\]$/.test(segment)) return \".+\";\n if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return \"[^/]+\";\n return escapeRegExp(segment);\n })\n .join(\"/\");\n\n return new RegExp(`^/${expression}/?$`).test(normalizedPathname);\n}\n\nfunction compareFarmRouteRuleSpecificity(left: string, right: string): number {\n const leftScore = getFarmRouteRuleSpecificity(left);\n const rightScore = getFarmRouteRuleSpecificity(right);\n return leftScore - rightScore || left.localeCompare(right);\n}\n\nfunction getFarmRouteRuleSpecificity(pattern: string): number {\n return normalizeRoutePattern(pattern)\n .split(\"/\")\n .filter(Boolean)\n .reduce((score, segment) => {\n if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n if (segment === \"*\" || segment.startsWith(\"[...\")) return score + 10;\n if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return score + 50;\n return score + 100;\n }, 0);\n}\n\nfunction normalizeRoutePattern(value: string): string {\n const withSlash = value.trim().startsWith(\"/\") ? value.trim() : `/${value.trim()}`;\n return withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import type { FarmConfig, FarmContextFactoryInput } from \"./types\";\n\nexport const FARM_ROUTE_CONTEXT_SYMBOL = Symbol.for(\"farm.routeContext\");\n\nexport type FarmRouteContextCarrier<TContext = unknown> = {\n [FARM_ROUTE_CONTEXT_SYMBOL]?: TContext;\n};\n\nexport async function resolveFarmRouteContext(\n config: Pick<FarmConfig, \"context\">,\n input: FarmContextFactoryInput,\n): Promise<unknown> {\n if (typeof config.context !== \"function\") {\n return undefined;\n }\n\n return config.context(input);\n}\n\nexport function withFarmRouteContext<TProps extends object, TContext>(\n props: TProps,\n context: TContext | undefined,\n): TProps & FarmRouteContextCarrier<TContext> {\n if (context === undefined) {\n return props as TProps & FarmRouteContextCarrier<TContext>;\n }\n\n Object.defineProperty(props, FARM_ROUTE_CONTEXT_SYMBOL, {\n value: context,\n enumerable: false,\n configurable: true,\n });\n\n return props as TProps & FarmRouteContextCarrier<TContext>;\n}\n\nexport function getFarmRouteContext<TContext = unknown>(props: unknown): TContext | undefined {\n if (!props || typeof props !== \"object\") {\n return undefined;\n }\n\n return (props as FarmRouteContextCarrier<TContext>)[FARM_ROUTE_CONTEXT_SYMBOL];\n}\n","import type { ComponentType } from \"react\";\nimport {\n createFarmCacheKey,\n createRouteDataCacheTag,\n getFarmDataCache,\n type FarmCacheOptions,\n type RouteDataCacheKey,\n} from \"./cache\";\nimport { getFarmRouteContext } from \"./route-context\";\nimport { normalizeFarmRouteRuntimeConfig, type FarmRouteRuntimeConfig } from \"./route-runtime\";\nimport type { ServerFn } from \"./server-fn\";\nimport type { FarmServerRendererRuntime } from \"./renderer\";\nimport { parseProgrammaticRoutePath as parseSharedProgrammaticRoutePath } from \"./routes-shared\";\nimport type {\n FarmAppContext,\n LayoutProps,\n Metadata,\n PageProps,\n ParsedRoute,\n PluginContextProps,\n RouteModule,\n} from \"./types\";\n\nexport type ProgrammaticRouteRenderMode = \"static\" | \"dynamic\";\nexport type ProgrammaticRouteMethod =\n | \"GET\"\n | \"HEAD\"\n | \"QUERY\"\n | \"POST\"\n | \"PUT\"\n | \"DELETE\"\n | \"PATCH\"\n | \"OPTIONS\";\n\nexport type ProgrammaticRoutePrimitive = string | number | boolean;\nexport type ProgrammaticStaticPathParams = Record<\n string,\n ProgrammaticRoutePrimitive | readonly ProgrammaticRoutePrimitive[]\n>;\nexport type ProgrammaticStaticPath =\n | string\n | readonly ProgrammaticRoutePrimitive[]\n | ProgrammaticStaticPathParams;\nexport type ProgrammaticStaticPaths = () =>\n | readonly ProgrammaticStaticPath[]\n | Promise<readonly ProgrammaticStaticPath[]>;\n\nexport interface ProgrammaticRouteSchema<TOutput = unknown> {\n parse(value: unknown): TOutput;\n}\n\nexport interface ProgrammaticRouteSearchOptions<TOutput = ProgrammaticRouteSearchFallback> {\n schema?: ProgrammaticRouteSchema<TOutput>;\n stripDefaults?: boolean | readonly string[];\n preserve?: readonly string[];\n temporary?: readonly string[];\n}\n\nexport type ProgrammaticRouteSearchConfig<TOutput = ProgrammaticRouteSearchFallback> =\n | ProgrammaticRouteSchema<TOutput>\n | ProgrammaticRouteSearchOptions<TOutput>;\n\nexport type InferProgrammaticRouteSchema<TSchema, TFallback> =\n TSchema extends ProgrammaticRouteSchema<infer TOutput> ? TOutput : TFallback;\n\nexport type InferProgrammaticRouteSearch<TSearch, TFallback> =\n TSearch extends ProgrammaticRouteSearchOptions<infer TOutput>\n ? TOutput\n : TSearch extends ProgrammaticRouteSchema<infer TOutput>\n ? TOutput\n : TFallback;\n\nexport type ProgrammaticRouteParamsFallback = Record<string, string>;\nexport type ProgrammaticRouteSearchFallback = Record<string, string | string[] | undefined>;\nexport type ProgrammaticRouteMaybePromise<T> = T | Promise<T>;\nexport type ProgrammaticRouteAction = ServerFn<any, any, any>;\nexport type ProgrammaticRouteActions = Readonly<Record<string, ProgrammaticRouteAction>>;\nexport type ProgrammaticRouteDefaultAction<\n TActions extends ProgrammaticRouteActions,\n TDefaultAction extends keyof TActions | undefined,\n> = [TDefaultAction] extends [undefined]\n ? TActions[keyof TActions]\n : TActions[Extract<TDefaultAction, keyof TActions>];\nexport type ProgrammaticRouteActionContract<\n TActions extends ProgrammaticRouteActions,\n TDefaultAction extends keyof TActions | undefined,\n> = keyof TActions extends never\n ? {\n actions?: undefined;\n defaultAction?: undefined;\n action?: undefined;\n }\n : {\n actions: Readonly<TActions>;\n defaultAction: [TDefaultAction] extends [undefined]\n ? keyof TActions\n : Extract<TDefaultAction, keyof TActions>;\n action: ProgrammaticRouteDefaultAction<TActions, TDefaultAction>;\n };\nexport type ProgrammaticRouteWithActions<\n TRoute extends ProgrammaticPageRoute<any, any, any, any>,\n TActions extends ProgrammaticRouteActions,\n TDefaultAction extends keyof TActions | undefined,\n> = Omit<TRoute, \"actions\" | \"defaultAction\" | \"action\"> &\n ProgrammaticRouteActionContract<TActions, TDefaultAction>;\nexport type ProgrammaticRouteDataStaleTime =\n | number\n | false\n | `${number}ms`\n | `${number}s`\n | `${number}m`\n | `${number}h`;\nexport type ProgrammaticRouteContext = keyof FarmAppContext extends never\n ? unknown\n : FarmAppContext;\n\nexport type ProgrammaticRouteComponentProps<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TData = undefined,\n> = Omit<PageProps, \"params\" | \"searchParams\"> & {\n params: TParams;\n search: TSearch;\n searchParams: Promise<TSearch>;\n} & ([TData] extends [undefined] ? { data?: undefined } : { data: TData });\n\nexport type ProgrammaticRouteDataContext<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TContext = ProgrammaticRouteContext,\n> = Omit<ProgrammaticRouteComponentProps<TParams, TSearch>, \"context\" | \"data\"> & {\n context: TContext;\n pluginContext?: PluginContextProps;\n};\n\nexport type ProgrammaticRouteDataCacheContext<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TBefore = unknown,\n TContext = ProgrammaticRouteContext,\n> = ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: TBefore;\n};\n\nexport type ProgrammaticRouteGuardContext<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TContext = ProgrammaticRouteContext,\n> = ProgrammaticRouteDataContext<TParams, TSearch, TContext>;\n\nexport type ProgrammaticRouteGuard<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TContext = ProgrammaticRouteContext,\n> = (\n context: ProgrammaticRouteGuardContext<TParams, TSearch, TContext>,\n) => ProgrammaticRouteMaybePromise<void>;\n\nexport type ProgrammaticRouteErrorComponentProps<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n> = Partial<ProgrammaticRouteComponentProps<TParams, TSearch>> & {\n error: unknown;\n};\n\nexport type ProgrammaticRoutePendingComponentProps<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n> = Partial<ProgrammaticRouteComponentProps<TParams, TSearch>>;\n\nexport type ProgrammaticRouteDataCacheKeys<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TBefore = unknown,\n TContext = ProgrammaticRouteContext,\n> =\n | readonly string[]\n | ((\n context: ProgrammaticRouteDataCacheContext<TParams, TSearch, TBefore, TContext>,\n ) => ProgrammaticRouteMaybePromise<readonly string[]>);\n\nexport interface ProgrammaticRouteDataHooks<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TBefore = unknown,\n TData = unknown,\n TContext = ProgrammaticRouteContext,\n> {\n key?: (\n context: ProgrammaticRouteDataCacheContext<TParams, TSearch, NoInfer<TBefore>, TContext>,\n ) => ProgrammaticRouteMaybePromise<RouteDataCacheKey | null | undefined>;\n staleTime?: ProgrammaticRouteDataStaleTime;\n tags?: ProgrammaticRouteDataCacheKeys<TParams, TSearch, NoInfer<TBefore>, TContext>;\n paths?: ProgrammaticRouteDataCacheKeys<TParams, TSearch, NoInfer<TBefore>, TContext>;\n before?: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext>,\n ) => ProgrammaticRouteMaybePromise<TBefore>;\n main: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: NoInfer<TBefore>;\n },\n ) => ProgrammaticRouteMaybePromise<TData>;\n after?: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: NoInfer<TBefore>;\n data: NoInfer<TData>;\n },\n ) => ProgrammaticRouteMaybePromise<void>;\n}\n\nexport type InferProgrammaticRouteData<TDataHooks> = TDataHooks extends {\n main: (...args: any[]) => infer TResult;\n}\n ? Awaited<TResult>\n : undefined;\n\nexport interface ProgrammaticPageRoute<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TDataHooks extends ProgrammaticRouteDataHooks<TParams, TSearch, any, any, any> | undefined =\n | ProgrammaticRouteDataHooks<TParams, TSearch, any, any, any>\n | undefined,\n TContext = ProgrammaticRouteContext,\n> extends FarmRouteRuntimeConfig {\n kind: \"page\";\n path: string;\n component: ComponentType<any>;\n params?: ProgrammaticRouteSchema<TParams>;\n search?: ProgrammaticRouteSearchConfig<TSearch>;\n guard?: ProgrammaticRouteGuard<TParams, TSearch, TContext>;\n data?: TDataHooks;\n /** Named server functions owned by this route. */\n actions?: ProgrammaticRouteActions;\n /** Named action selected by `useAction(route)`. The first action is used when omitted. */\n defaultAction?: string;\n /** Resolved default server function for client and server calls. */\n action?: ProgrammaticRouteAction;\n pending?: ComponentType<ProgrammaticRoutePendingComponentProps<TParams, TSearch>>;\n error?: ComponentType<ProgrammaticRouteErrorComponentProps<TParams, TSearch>>;\n notFound?: ComponentType<ProgrammaticRouteErrorComponentProps<TParams, TSearch>>;\n render?: ProgrammaticRouteRenderMode;\n staticPaths?: ProgrammaticStaticPaths;\n revalidate?: number | false;\n ppr?: boolean;\n metadata?: Metadata & Record<string, any>;\n generateMetadata?: RouteModule[\"generateMetadata\"];\n}\n\nexport interface ProgrammaticLayoutRoute extends FarmRouteRuntimeConfig {\n kind: \"layout\";\n path: string;\n component: ComponentType<LayoutProps>;\n metadata?: Metadata & Record<string, any>;\n generateMetadata?: (props: { params: Record<string, string> }) => Promise<Metadata> | Metadata;\n}\n\nexport type ProgrammaticApiRouteOptions = Partial<Record<ProgrammaticRouteMethod, any>> & {\n render?: ProgrammaticRouteRenderMode;\n} & FarmRouteRuntimeConfig;\n\nexport interface ProgrammaticApiRoute extends FarmRouteRuntimeConfig {\n kind: \"api\";\n path: string;\n methods: Partial<Record<ProgrammaticRouteMethod, any>>;\n render?: ProgrammaticRouteRenderMode;\n}\n\nexport interface ProgrammaticRedirectRoute {\n kind: \"redirect\";\n source: string;\n destination: string;\n permanent?: boolean;\n statusCode?: number;\n}\n\nexport type ProgrammaticRouteDefinition =\n | ProgrammaticPageRoute<any, any>\n | ProgrammaticLayoutRoute\n | ProgrammaticApiRoute\n | ProgrammaticRedirectRoute;\n\nexport interface ProgrammaticRouteManifest {\n readonly __farmRoutes: true;\n routes: ProgrammaticRouteDefinition[];\n}\n\nexport interface ProgrammaticRouteBuilder {\n page(\n path: string,\n options: Omit<ProgrammaticPageRoute<any, any>, \"kind\" | \"path\">,\n ): ProgrammaticPageRoute;\n layout(\n path: string,\n options: Omit<ProgrammaticLayoutRoute, \"kind\" | \"path\">,\n ): ProgrammaticLayoutRoute;\n api(path: string, options: ProgrammaticApiRouteOptions): ProgrammaticApiRoute;\n redirect(\n source: string,\n destination: string,\n options?: Omit<ProgrammaticRedirectRoute, \"kind\" | \"source\" | \"destination\">,\n ): ProgrammaticRedirectRoute;\n}\n\nexport type ProgrammaticRouteFactory = (\n builder: ProgrammaticRouteBuilder,\n) => readonly ProgrammaticRouteDefinition[];\n\ntype CreateRouteParams<TParamsSchema> = InferProgrammaticRouteSchema<\n TParamsSchema,\n ProgrammaticRouteParamsFallback\n>;\n\ntype CreateRouteSearch<TSearchConfig> = InferProgrammaticRouteSearch<\n TSearchConfig,\n ProgrammaticRouteSearchFallback\n>;\n\ntype CreateRouteSharedOptions<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n> = Omit<\n ProgrammaticPageRoute<CreateRouteParams<TParamsSchema>, CreateRouteSearch<TSearchConfig>>,\n \"kind\" | \"path\" | \"component\" | \"params\" | \"search\" | \"data\" | \"guard\" | \"action\"\n> & {\n params?: TParamsSchema;\n search?: TSearchConfig;\n guard?: ProgrammaticRouteGuard<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>\n >;\n};\n\ntype CreateRouteDataHooksWithBefore<\n TParams,\n TSearch,\n TBeforeResult,\n TMainResult,\n TContext = ProgrammaticRouteContext,\n> = Omit<\n ProgrammaticRouteDataHooks<\n TParams,\n TSearch,\n NoInfer<Awaited<TBeforeResult>>,\n NoInfer<Awaited<TMainResult>>,\n TContext\n >,\n \"before\" | \"main\"\n> & {\n before: (context: ProgrammaticRouteDataContext<TParams, TSearch, TContext>) => TBeforeResult;\n main: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: NoInfer<Awaited<TBeforeResult>>;\n },\n ) => TMainResult;\n};\n\ntype CreateRouteDataHooksWithoutBefore<\n TParams,\n TSearch,\n TMainResult,\n TContext = ProgrammaticRouteContext,\n> = Omit<\n ProgrammaticRouteDataHooks<TParams, TSearch, undefined, NoInfer<Awaited<TMainResult>>, TContext>,\n \"before\" | \"main\"\n> & {\n before?: undefined;\n main: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: undefined;\n },\n ) => TMainResult;\n};\n\ntype CreateRouteOptionsWithBefore<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n TBefore,\n TData,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n data: CreateRouteDataHooksWithBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TBefore,\n TData\n >;\n component: ComponentType<\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n NoInfer<Awaited<TData>>\n >\n >;\n};\n\ntype CreateRouteOptionsWithoutBefore<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n TData,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n data: CreateRouteDataHooksWithoutBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TData\n >;\n component: ComponentType<\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n NoInfer<Awaited<TData>>\n >\n >;\n};\n\ntype CreateRouteOptionsWithoutData<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n data?: undefined;\n component: ComponentType<\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n undefined\n >\n >;\n};\n\ntype CreateRouteComponentOption<TComponent extends ComponentType<any>, TProps> = {\n component: TComponent;\n} & (TComponent extends ComponentType<TProps> ? unknown : { component: ComponentType<TProps> });\n\nexport type CreateRouteOptions<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TBefore = unknown,\n TData = unknown,\n> =\n | CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBefore, TData>\n | CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TData>\n | CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>;\n\ntype CreateRouteActionOptions<\n TActions extends ProgrammaticRouteActions,\n TDefaultAction extends keyof TActions | undefined,\n> = keyof TActions extends never\n ? { actions?: undefined; defaultAction?: undefined }\n : { actions: TActions; defaultAction?: TDefaultAction };\n\nconst FARM_ROUTES_BRAND = Symbol.for(\"farm.routes\");\nexport const PROGRAMMATIC_ROUTE_FILE_NAMES = [\n \"farm.route.ts\",\n \"farm.route.tsx\",\n \"farm.route.js\",\n \"farm.route.jsx\",\n \"farm.routes.ts\",\n \"farm.routes.tsx\",\n \"farm.routes.js\",\n \"farm.routes.jsx\",\n \"routes.ts\",\n \"routes.tsx\",\n \"routes.js\",\n \"routes.jsx\",\n];\n\nexport function defineRoutes(\n input: readonly ProgrammaticRouteDefinition[] | ProgrammaticRouteFactory,\n): ProgrammaticRouteManifest {\n const routes = typeof input === \"function\" ? input(routesBuilder) : input;\n const manifest = {\n __farmRoutes: true as const,\n routes: routes.map(normalizeProgrammaticRoute),\n };\n\n Object.defineProperty(manifest, FARM_ROUTES_BRAND, {\n value: true,\n enumerable: false,\n });\n\n return manifest;\n}\n\nexport const routesBuilder: ProgrammaticRouteBuilder = {\n page(path, options) {\n return normalizeProgrammaticRoute({\n kind: \"page\",\n path,\n ...options,\n }) as ProgrammaticPageRoute;\n },\n layout(path, options) {\n return normalizeProgrammaticRoute({\n kind: \"layout\",\n path,\n ...options,\n }) as ProgrammaticLayoutRoute;\n },\n api(path, options) {\n const { render, runtime, regions, maxDuration, ...methods } = options;\n return normalizeProgrammaticRoute({\n kind: \"api\",\n path,\n render,\n runtime,\n regions,\n maxDuration,\n methods: normalizeApiMethods(methods),\n }) as ProgrammaticApiRoute;\n },\n redirect(source, destination, options = {}) {\n return normalizeProgrammaticRoute({\n kind: \"redirect\",\n source,\n destination,\n ...options,\n }) as ProgrammaticRedirectRoute;\n },\n};\n\nexport const page = routesBuilder.page;\nexport const layout = routesBuilder.layout;\nexport const api = routesBuilder.api;\nexport const redirect = routesBuilder.redirect;\n\nexport interface ProgrammaticRouteSearchClientOptions {\n stripDefaults?: boolean | readonly string[];\n preserve?: readonly string[];\n temporary?: readonly string[];\n}\n\nexport interface ProgrammaticRouteSearchResolution<TSearch = unknown> {\n search: TSearch;\n canonicalPath?: string;\n}\n\nexport function getProgrammaticRouteSearchSchema<TSearch = unknown>(\n search: ProgrammaticRouteSearchConfig<TSearch> | undefined,\n): ProgrammaticRouteSchema<TSearch> | undefined {\n if (!search) return undefined;\n if (isProgrammaticRouteSchema(search)) return search;\n return search.schema;\n}\n\nexport function getProgrammaticRouteSearchClientOptions(\n search: ProgrammaticRouteSearchConfig<any> | undefined,\n): ProgrammaticRouteSearchClientOptions | undefined {\n if (!search || isProgrammaticRouteSchema(search)) return undefined;\n\n const options: ProgrammaticRouteSearchClientOptions = {};\n if (typeof search.stripDefaults !== \"undefined\") options.stripDefaults = search.stripDefaults;\n if (search.preserve?.length) options.preserve = [...search.preserve];\n if (search.temporary?.length) options.temporary = [...search.temporary];\n\n return Object.keys(options).length > 0 ? options : undefined;\n}\n\nfunction resolveProgrammaticRouteSearch<TSearch>(\n searchConfig: ProgrammaticRouteSearchConfig<TSearch> | undefined,\n rawSearch: ProgrammaticRouteSearchFallback,\n path: string,\n routePath: string,\n): ProgrammaticRouteSearchResolution<TSearch | ProgrammaticRouteSearchFallback> {\n const schema = getProgrammaticRouteSearchSchema(searchConfig);\n const search = parseProgrammaticSchema(schema, rawSearch, \"search\", routePath) as\n | TSearch\n | ProgrammaticRouteSearchFallback;\n const options = getProgrammaticRouteSearchOptions(searchConfig);\n const canonicalPath = resolveProgrammaticRouteCanonicalPath({\n options,\n schema,\n rawSearch,\n parsedSearch: search,\n path,\n });\n\n return { search, canonicalPath };\n}\n\nfunction getProgrammaticRouteSearchOptions(\n search: ProgrammaticRouteSearchConfig<any> | undefined,\n): ProgrammaticRouteSearchOptions<any> | undefined {\n if (!search || isProgrammaticRouteSchema(search)) return undefined;\n return search;\n}\n\nfunction isProgrammaticRouteSchema(value: unknown): value is ProgrammaticRouteSchema<any> {\n return !!value && typeof value === \"object\" && typeof (value as any).parse === \"function\";\n}\n\nfunction resolveProgrammaticRouteCanonicalPath(input: {\n options: ProgrammaticRouteSearchOptions<any> | undefined;\n schema: ProgrammaticRouteSchema<any> | undefined;\n rawSearch: ProgrammaticRouteSearchFallback;\n parsedSearch: unknown;\n path: string;\n}): string | undefined {\n const options = input.options;\n if (!options?.temporary?.length && !options?.stripDefaults) {\n return undefined;\n }\n\n const params = createSearchParams(input.rawSearch);\n const original = params.toString();\n\n for (const key of options.temporary || []) {\n params.delete(key);\n }\n\n if (options.stripDefaults) {\n const defaultSearch = parseDefaultSearch(input.schema);\n if (defaultSearch !== undefined) {\n const keys =\n options.stripDefaults === true\n ? Array.from(new Set(Array.from(params.keys())))\n : [...options.stripDefaults];\n\n for (const key of keys) {\n if (\n params.has(key) &&\n searchValuesEqual(\n readSearchValue(input.parsedSearch, key),\n readSearchValue(defaultSearch, key),\n )\n ) {\n params.delete(key);\n }\n }\n }\n }\n\n const next = params.toString();\n if (next === original) {\n return undefined;\n }\n\n return next ? `${input.path}?${next}` : input.path;\n}\n\nfunction createSearchParams(value: ProgrammaticRouteSearchFallback): URLSearchParams {\n const params = new URLSearchParams();\n\n for (const [key, item] of Object.entries(value)) {\n if (item == null) continue;\n const values = Array.isArray(item) ? item : [item];\n for (const entry of values) {\n if (entry != null) params.append(key, String(entry));\n }\n }\n\n return params;\n}\n\nfunction parseDefaultSearch(\n schema: ProgrammaticRouteSchema<any> | undefined,\n): Record<string, unknown> | undefined {\n if (!schema) return undefined;\n\n try {\n const value = schema.parse({});\n return value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readSearchValue(value: unknown, key: string): unknown {\n return value && typeof value === \"object\" ? (value as Record<string, unknown>)[key] : undefined;\n}\n\nfunction searchValuesEqual(left: unknown, right: unknown): boolean {\n return (\n JSON.stringify(normalizeComparableValue(left)) ===\n JSON.stringify(normalizeComparableValue(right))\n );\n}\n\nfunction normalizeComparableValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(normalizeComparableValue);\n }\n if (value && typeof value === \"object\") {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((output, key) => {\n output[key] = normalizeComparableValue((value as Record<string, unknown>)[key]);\n return output;\n }, {});\n }\n return value;\n}\n\nexport function createRoute<\n const TActions extends ProgrammaticRouteActions,\n TDefaultAction extends keyof TActions | undefined = undefined,\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TBeforeResult = unknown,\n TMainResult = unknown,\n TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBeforeResult, TMainResult>,\n \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n > &\n CreateRouteActionOptions<TActions, TDefaultAction> &\n CreateRouteComponentOption<\n TComponent,\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n Awaited<TMainResult>\n >\n >,\n): ProgrammaticRouteWithActions<\n ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n CreateRouteDataHooksWithBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TBeforeResult,\n TMainResult\n >\n >,\n TActions,\n TDefaultAction\n>;\nexport function createRoute<\n const TActions extends ProgrammaticRouteActions,\n TDefaultAction extends keyof TActions | undefined = undefined,\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TMainResult = unknown,\n TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TMainResult>,\n \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n > &\n CreateRouteActionOptions<TActions, TDefaultAction> &\n CreateRouteComponentOption<\n TComponent,\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n Awaited<TMainResult>\n >\n >,\n): ProgrammaticRouteWithActions<\n ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n CreateRouteDataHooksWithoutBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TMainResult\n >\n >,\n TActions,\n TDefaultAction\n>;\nexport function createRoute<\n const TActions extends ProgrammaticRouteActions,\n TDefaultAction extends keyof TActions | undefined = undefined,\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>,\n \"actions\" | \"defaultAction\" | \"action\"\n > &\n CreateRouteActionOptions<TActions, TDefaultAction>,\n): ProgrammaticRouteWithActions<\n ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n undefined\n >,\n TActions,\n TDefaultAction\n>;\nexport function createRoute<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TBeforeResult = unknown,\n TMainResult = unknown,\n TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBeforeResult, TMainResult>,\n \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n > & { actions?: undefined; defaultAction?: undefined } & CreateRouteComponentOption<\n TComponent,\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n Awaited<TMainResult>\n >\n >,\n): ProgrammaticRouteWithActions<\n ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n CreateRouteDataHooksWithBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TBeforeResult,\n TMainResult\n >\n >,\n {},\n undefined\n>;\nexport function createRoute<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TMainResult = unknown,\n TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TMainResult>,\n \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n > & { actions?: undefined; defaultAction?: undefined } & CreateRouteComponentOption<\n TComponent,\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n Awaited<TMainResult>\n >\n >,\n): ProgrammaticRouteWithActions<\n ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n CreateRouteDataHooksWithoutBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TMainResult\n >\n >,\n {},\n undefined\n>;\nexport function createRoute<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>,\n \"actions\" | \"defaultAction\" | \"action\"\n > & { actions?: undefined; defaultAction?: undefined },\n): ProgrammaticRouteWithActions<\n ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n undefined\n >,\n {},\n undefined\n>;\nexport function createRoute(path: string, options: any): any {\n return routesBuilder.page(path, options);\n}\n\nexport function isProgrammaticRoutesFileName(fileName: string): boolean {\n const normalized = fileName.replace(/\\\\/g, \"/\");\n const baseName = normalized.split(\"/\").pop() || normalized;\n return PROGRAMMATIC_ROUTE_FILE_NAMES.includes(baseName);\n}\n\nexport function getProgrammaticRouteManifest(\n mod: Record<string, any> | null | undefined,\n): ProgrammaticRouteManifest | null {\n if (!mod) return null;\n\n const candidates = [mod.default, mod.routes, mod.Route];\n for (const candidate of candidates) {\n if (isProgrammaticRouteManifest(candidate)) {\n return candidate;\n }\n if (isProgrammaticRouteDefinition(candidate)) {\n return defineRoutes([candidate]);\n }\n if (Array.isArray(candidate)) {\n return defineRoutes(candidate as ProgrammaticRouteDefinition[]);\n }\n }\n\n const routeDefinitions = Object.values(mod).filter(isProgrammaticRouteDefinition);\n if (routeDefinitions.length > 0) {\n return defineRoutes(routeDefinitions);\n }\n\n return null;\n}\n\nexport function isProgrammaticRouteManifest(value: unknown): value is ProgrammaticRouteManifest {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as ProgrammaticRouteManifest).__farmRoutes === true &&\n Array.isArray((value as ProgrammaticRouteManifest).routes)\n );\n}\n\nexport function isProgrammaticRouteDefinition(\n value: unknown,\n): value is ProgrammaticRouteDefinition {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const kind = (value as { kind?: unknown }).kind;\n return kind === \"page\" || kind === \"layout\" || kind === \"api\" || kind === \"redirect\";\n}\n\nexport function createProgrammaticRouteModuleId(\n filePath: string,\n kind: \"page\" | \"layout\" | \"api\",\n routePath: string,\n): string {\n return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeRoutePath(routePath))}`;\n}\n\nexport function parseProgrammaticRouteModuleId(moduleId: string): {\n filePath: string;\n kind: \"page\" | \"layout\" | \"api\";\n routePath: string;\n} | null {\n const queryIndex = moduleId.indexOf(\"?\");\n if (queryIndex === -1) {\n return null;\n }\n\n const filePath = moduleId.slice(0, queryIndex);\n const params = new URLSearchParams(moduleId.slice(queryIndex + 1));\n const value = params.get(\"farm-route\");\n if (!value) {\n return null;\n }\n\n const separator = value.indexOf(\":\");\n if (separator === -1) {\n return null;\n }\n\n const kind = value.slice(0, separator);\n if (kind !== \"page\" && kind !== \"layout\" && kind !== \"api\") {\n return null;\n }\n\n return {\n filePath,\n kind,\n routePath: normalizeRoutePath(value.slice(separator + 1)),\n };\n}\n\nexport function parseProgrammaticRoutePath(\n routePath: string,\n type: ParsedRoute[\"type\"] = \"page\",\n): ParsedRoute {\n return parseSharedProgrammaticRoutePath(routePath, type);\n}\n\nexport function createRouteModuleFromProgrammaticPage(\n route: ProgrammaticPageRoute,\n rendererRuntime?: Pick<FarmServerRendererRuntime, \"createElement\" | \"Suspense\">,\n): RouteModule {\n const mod: RouteModule = {\n default: createProgrammaticPageComponent(route, rendererRuntime),\n ...normalizeFarmRouteRuntimeConfig(route, `Route \"${route.path}\"`),\n };\n\n if (route.params || route.search || route.guard || route.data) {\n (mod as any).__farmRouteSchemas = {\n params: route.params,\n search: getProgrammaticRouteSearchSchema(route.search),\n };\n (mod as any).__farmRouteSearch = getProgrammaticRouteSearchClientOptions(route.search);\n (mod as any).__farmRouteGuard = route.guard;\n (mod as any).__farmRouteData = route.data;\n (mod as any).__farmRouteParsesProps = true;\n (mod as any).__farmResolveRouteProps = (props: PageProps) =>\n resolveProgrammaticRouteProps(route, props);\n (mod as any).__farmResolveRouteCanonicalPath = (\n rawSearch: ProgrammaticRouteSearchFallback,\n path: string,\n ) => resolveProgrammaticRouteSearch(route.search, rawSearch, path, route.path).canonicalPath;\n }\n\n if (route.pending || route.error || route.notFound) {\n (mod as any).__farmRouteComponents = {\n pending: route.pending,\n error: route.error,\n notFound: route.notFound,\n };\n }\n\n if (route.render === \"static\" || route.staticPaths) {\n mod.ssg = true;\n mod.dynamic = \"force-static\";\n } else if (route.render === \"dynamic\") {\n mod.ssg = false;\n mod.dynamic = \"force-dynamic\";\n }\n\n if (typeof route.revalidate !== \"undefined\") {\n mod.revalidate = route.revalidate;\n }\n\n if (route.ppr) {\n mod.ppr = true;\n }\n\n if (route.metadata) {\n mod.metadata = route.metadata;\n }\n\n if (route.generateMetadata) {\n mod.generateMetadata = route.generateMetadata;\n }\n\n if (route.staticPaths) {\n mod.getStaticPaths = async () => normalizeStaticPaths(route.path, await route.staticPaths!());\n }\n\n return mod;\n}\n\nexport function createLayoutModuleFromProgrammaticLayout(route: ProgrammaticLayoutRoute) {\n return {\n default: route.component,\n ...normalizeFarmRouteRuntimeConfig(route, `Layout \"${route.path}\"`),\n metadata: route.metadata,\n generateMetadata: route.generateMetadata,\n };\n}\n\nexport function scanProgrammaticPagePaths(source: string): string[] {\n const paths = new Set<string>();\n const callRe = /\\b(?:page|createRoute)\\s*\\(\\s*([\"'`])([^\"'`]+)\\1/g;\n\n for (const match of source.matchAll(callRe)) {\n if (match[2]) {\n paths.add(normalizeRoutePath(match[2]));\n }\n }\n\n return Array.from(paths);\n}\n\nfunction createProgrammaticPageComponent(\n route: ProgrammaticPageRoute,\n rendererRuntime?: Pick<FarmServerRendererRuntime, \"createElement\" | \"Suspense\">,\n): ComponentType<PageProps> {\n if (\n !route.params &&\n !route.search &&\n !route.guard &&\n !route.data &&\n !route.pending &&\n !route.error &&\n !route.notFound\n ) {\n return route.component as ComponentType<PageProps>;\n }\n\n const createElement: FarmServerRendererRuntime[\"createElement\"] = (...args) => {\n if (!rendererRuntime) {\n throw new Error(\n `Programmatic route \"${route.path}\" requires a FARMJS renderer runtime before it can render.`,\n );\n }\n return rendererRuntime.createElement(...args);\n };\n const Component = route.component;\n\n if (route.pending) {\n const PendingComponent = route.pending;\n const routePropsResources = new WeakMap<object, ProgrammaticRoutePropsResource>();\n const FarmProgrammaticPageContent = function FarmProgrammaticPageContent(props: PageProps) {\n try {\n const resolvedProps = readProgrammaticRouteProps(route, props, routePropsResources);\n return createElement(Component, stripProgrammaticRoutePropsMarker(resolvedProps));\n } catch (error) {\n if (isPromiseLike(error) || isProgrammaticRedirectSignal(error)) {\n throw error;\n }\n\n if (isProgrammaticNotFoundSignal(error) && route.notFound) {\n return createElement(route.notFound, createProgrammaticRouteErrorProps(error, props));\n }\n\n if (route.error) {\n return createElement(route.error, createProgrammaticRouteErrorProps(error, props));\n }\n\n throw error;\n }\n };\n const PageContent = FarmProgrammaticPageContent as unknown as ComponentType<PageProps>;\n const FarmProgrammaticPage = function FarmProgrammaticPage(props: PageProps) {\n return createElement(\n rendererRuntime!.Suspense,\n {\n fallback: createElement(PendingComponent, createProgrammaticRoutePendingProps(props)),\n },\n createElement(PageContent, props),\n );\n };\n\n return FarmProgrammaticPage as unknown as ComponentType<PageProps>;\n }\n\n const FarmProgrammaticPageContent = async function FarmProgrammaticPageContent(props: PageProps) {\n try {\n const resolvedProps = isProgrammaticRoutePropsResolved(props)\n ? props\n : await resolveProgrammaticRouteProps(route, props);\n\n return createElement(Component, stripProgrammaticRoutePropsMarker(resolvedProps));\n } catch (error) {\n if (isProgrammaticRedirectSignal(error)) {\n throw error;\n }\n\n if (isProgrammaticNotFoundSignal(error) && route.notFound) {\n return createElement(route.notFound, createProgrammaticRouteErrorProps(error, props));\n }\n\n if (route.error) {\n return createElement(route.error, createProgrammaticRouteErrorProps(error, props));\n }\n\n throw error;\n }\n };\n\n return FarmProgrammaticPageContent as unknown as ComponentType<PageProps>;\n}\n\ntype ProgrammaticRoutePropsResource =\n | { status: \"pending\"; promise: Promise<Record<string, any>> }\n | { status: \"resolved\"; value: Record<string, any> }\n | { status: \"rejected\"; error: unknown };\n\nfunction readProgrammaticRouteProps(\n route: ProgrammaticPageRoute,\n props: PageProps,\n resources: WeakMap<object, ProgrammaticRoutePropsResource>,\n): Record<string, any> {\n if (isProgrammaticRoutePropsResolved(props)) {\n return props;\n }\n\n let resource = resources.get(props as object);\n if (!resource) {\n const deferredRouteProps = (props as any).__farmRoutePropsPromise;\n const promise = Promise.resolve<Record<string, any>>(\n isPromiseLike(deferredRouteProps)\n ? (deferredRouteProps as PromiseLike<Record<string, any>>)\n : resolveProgrammaticRouteProps(route, props),\n );\n resource = { status: \"pending\", promise };\n resources.set(props as object, resource);\n promise.then(\n (value) => resources.set(props as object, { status: \"resolved\", value }),\n (error) => resources.set(props as object, { status: \"rejected\", error }),\n );\n }\n\n if (resource.status === \"pending\") throw resource.promise;\n if (resource.status === \"rejected\") throw resource.error;\n return resource.value;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as PromiseLike<unknown>).then === \"function\",\n );\n}\n\nfunction createProgrammaticRoutePendingProps(\n props: PageProps,\n): ProgrammaticRoutePendingComponentProps {\n return {\n params: props.params,\n searchParams: props.searchParams,\n path: props.path,\n };\n}\n\nfunction createProgrammaticRouteErrorProps(\n error: unknown,\n props: PageProps,\n): ProgrammaticRouteErrorComponentProps {\n return {\n error,\n params: props.params,\n searchParams: props.searchParams,\n path: props.path,\n };\n}\n\nfunction isProgrammaticRedirectSignal(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const digest = (error as { digest?: unknown }).digest;\n return typeof digest === \"string\" && digest.startsWith(\"FARM_REDIRECT;\");\n}\n\nfunction isProgrammaticNotFoundSignal(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const digest = (error as { digest?: unknown }).digest;\n return digest === \"FARM_NOT_FOUND\";\n}\n\nasync function resolveProgrammaticRouteProps(\n route: ProgrammaticPageRoute,\n props: PageProps,\n): Promise<Record<string, any> & { __farmRoutePropsResolved: true }> {\n const rawSearch = await props.searchParams;\n const params = parseProgrammaticSchema(route.params, props.params, \"params\", route.path);\n const { search, canonicalPath } = resolveProgrammaticRouteSearch(\n route.search,\n rawSearch,\n props.path,\n route.path,\n );\n const routeContextValue = getFarmRouteContext(props);\n const pluginContext = props.context;\n const baseProps = {\n ...props,\n params,\n search,\n searchParams: Promise.resolve(search),\n };\n const routeContextProps = {\n ...baseProps,\n context: routeContextValue,\n pluginContext,\n };\n\n if (route.guard) {\n await route.guard(routeContextProps as any);\n }\n\n if (!route.data) {\n return markProgrammaticRoutePropsResolved(addCanonicalPath(baseProps, canonicalPath));\n }\n\n const before = route.data.before ? await route.data.before(routeContextProps as any) : undefined;\n const dataContext = {\n ...(routeContextProps as any),\n before,\n };\n const data = await resolveProgrammaticRouteData(route, route.data, dataContext);\n\n if (route.data.after) {\n await route.data.after({\n ...(routeContextProps as any),\n before,\n data,\n });\n }\n\n return markProgrammaticRoutePropsResolved({\n ...baseProps,\n data,\n ...(canonicalPath ? { __farmCanonicalPath: canonicalPath } : {}),\n });\n}\n\nasync function resolveProgrammaticRouteData(\n route: ProgrammaticPageRoute,\n dataHooks: ProgrammaticRouteDataHooks<any, any, any, any>,\n context: ProgrammaticRouteDataCacheContext<any, any, any>,\n): Promise<unknown> {\n if (!dataHooks?.key) {\n return dataHooks.main(context);\n }\n\n const routeDataKey = await dataHooks.key(context);\n if (routeDataKey == null) {\n return dataHooks.main(context);\n }\n\n const cacheKey = createFarmCacheKey([\"route-data\", routeDataKey]);\n const cacheOptions: FarmCacheOptions = {\n tags: [\n createRouteDataCacheTag(routeDataKey),\n ...(await resolveProgrammaticRouteDataKeys(dataHooks.tags, context)),\n ],\n paths: [\n ...(typeof context.path === \"string\" ? [context.path] : []),\n ...(await resolveProgrammaticRouteDataKeys(dataHooks.paths, context)),\n ],\n revalidate: normalizeProgrammaticRouteStaleTime(dataHooks.staleTime),\n };\n\n return getFarmDataCache().getOrSet(cacheKey, () => dataHooks.main(context), cacheOptions);\n}\n\nasync function resolveProgrammaticRouteDataKeys(\n input: ProgrammaticRouteDataCacheKeys<any, any, any> | undefined,\n context: ProgrammaticRouteDataCacheContext<any, any, any>,\n): Promise<readonly string[]> {\n if (!input) return [];\n const value = typeof input === \"function\" ? await input(context) : input;\n return value.filter((item) => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction normalizeProgrammaticRouteStaleTime(\n staleTime: ProgrammaticRouteDataStaleTime | undefined,\n): number | false | undefined {\n if (staleTime === undefined) return undefined;\n if (staleTime === false) return false;\n\n if (typeof staleTime === \"number\") {\n if (!Number.isFinite(staleTime) || staleTime <= 0) return undefined;\n return Math.max(1, Math.ceil(staleTime / 1000));\n }\n\n const match = staleTime.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)$/);\n if (!match) return undefined;\n\n const value = Number(match[1]);\n if (!Number.isFinite(value) || value <= 0) return undefined;\n\n const unit = match[2];\n const milliseconds =\n unit === \"ms\"\n ? value\n : unit === \"s\"\n ? value * 1000\n : unit === \"m\"\n ? value * 60000\n : value * 3600000;\n\n return Math.max(1, Math.ceil(milliseconds / 1000));\n}\n\nfunction isProgrammaticRoutePropsResolved(value: unknown): boolean {\n return !!value && typeof value === \"object\" && (value as any).__farmRoutePropsResolved === true;\n}\n\nfunction markProgrammaticRoutePropsResolved<T extends Record<string, any>>(\n props: T,\n): T & { __farmRoutePropsResolved: true } {\n return {\n ...props,\n __farmRoutePropsResolved: true,\n };\n}\n\nfunction addCanonicalPath<T extends Record<string, any>>(\n props: T,\n canonicalPath: string | undefined,\n): T {\n return canonicalPath ? ({ ...props, __farmCanonicalPath: canonicalPath } as T) : props;\n}\n\nfunction stripProgrammaticRoutePropsMarker<TProps>(props: TProps): TProps {\n if (!isProgrammaticRoutePropsResolved(props)) {\n return props;\n }\n\n const {\n __farmRoutePropsResolved,\n __farmCanonicalPath,\n __farmRoutePropsPromise,\n ...componentProps\n } = props as any;\n return componentProps;\n}\n\nfunction parseProgrammaticSchema<TFallback>(\n schema: ProgrammaticRouteSchema<any> | undefined,\n value: TFallback,\n label: string,\n routePath: string,\n): unknown {\n if (!schema) {\n return value;\n }\n\n try {\n return schema.parse(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n }\n}\n\nfunction normalizeProgrammaticRoute(\n route: ProgrammaticRouteDefinition,\n): ProgrammaticRouteDefinition {\n if (route.kind === \"redirect\") {\n return {\n ...route,\n source: normalizeRoutePath(route.source),\n };\n }\n\n if (route.kind === \"api\") {\n return {\n ...route,\n ...normalizeFarmRouteRuntimeConfig(route, `API route \"${route.path}\"`),\n path: normalizeRoutePath(route.path),\n methods: normalizeApiMethods(route.methods),\n };\n }\n\n const routeActions = route.kind === \"page\" ? normalizeProgrammaticRouteActions(route) : undefined;\n\n return {\n ...route,\n ...routeActions,\n ...normalizeFarmRouteRuntimeConfig(\n route,\n `${route.kind === \"layout\" ? \"Layout\" : \"Route\"} \"${route.path}\"`,\n ),\n path: normalizeRoutePath(route.path),\n };\n}\n\nfunction normalizeProgrammaticRouteActions(route: ProgrammaticPageRoute): {\n actions?: ProgrammaticRouteActions;\n defaultAction?: string;\n action?: ProgrammaticRouteAction;\n} {\n const entries = Object.entries(route.actions ?? {});\n\n if (entries.length === 0) {\n if (route.defaultAction !== undefined) {\n throw new TypeError(\n `Route \"${route.path}\" declares defaultAction without declaring any actions.`,\n );\n }\n return {};\n }\n\n for (const [name, action] of entries) {\n if (typeof action !== \"function\") {\n throw new TypeError(`Route \"${route.path}\" action \"${name}\" must be a server function.`);\n }\n }\n\n const defaultAction = route.defaultAction ?? entries[0]![0];\n const actions = Object.freeze({ ...route.actions });\n const action = actions[defaultAction];\n\n if (!action) {\n throw new TypeError(\n `Route \"${route.path}\" defaultAction \"${defaultAction}\" does not match a declared action.`,\n );\n }\n\n return {\n actions,\n defaultAction,\n action,\n };\n}\n\nfunction normalizeRoutePath(routePath: string): string {\n const withSlash = routePath.startsWith(\"/\") ? routePath : `/${routePath}`;\n const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n return withoutTrailing || \"/\";\n}\n\nfunction normalizeApiMethods(\n methods: Record<string, any>,\n): Partial<Record<ProgrammaticRouteMethod, any>> {\n const normalized: Partial<Record<ProgrammaticRouteMethod, any>> = {};\n\n for (const [method, handler] of Object.entries(methods)) {\n const normalizedMethod = method.toUpperCase() as ProgrammaticRouteMethod;\n if (handler && isProgrammaticRouteMethod(normalizedMethod)) {\n normalized[normalizedMethod] = handler;\n }\n }\n\n return normalized;\n}\n\nfunction isProgrammaticRouteMethod(method: string): method is ProgrammaticRouteMethod {\n return (\n method === \"GET\" ||\n method === \"HEAD\" ||\n method === \"QUERY\" ||\n method === \"POST\" ||\n method === \"PUT\" ||\n method === \"DELETE\" ||\n method === \"PATCH\" ||\n method === \"OPTIONS\"\n );\n}\n\nfunction normalizeStaticPaths(\n routePath: string,\n paths: readonly ProgrammaticStaticPath[],\n): Record<string, string>[] {\n const dynamicSegments = parseProgrammaticRoutePath(routePath).segments.filter(\n (segment) => segment.isDynamic,\n );\n\n return paths.map((entry) => {\n if (typeof entry === \"string\" || Array.isArray(entry)) {\n if (dynamicSegments.length !== 1) {\n throw new Error(\n `staticPaths for \"${routePath}\" must return objects when the route has ${dynamicSegments.length} dynamic params.`,\n );\n }\n\n const value = Array.isArray(entry) ? entry.join(\"/\") : entry;\n return { [dynamicSegments[0].segment]: String(value) };\n }\n\n return Object.fromEntries(\n Object.entries(entry).map(([key, value]) => [\n key,\n Array.isArray(value) ? value.map(String).join(\"/\") : String(value),\n ]),\n );\n });\n}\n","export * from \"./endpoint\";\nexport * from \"./route-manager\";\nexport * from \"./client\";\nexport * from \"./config\";\nexport { resolveFarmAPIServerBasePath } from \"./server-path\";\nexport * from \"./transport\";\nexport * from \"./vite-plugin\";\nexport * from \"./route\";\n","import { createEndpoint as betterCallEndpoint } from \"better-call\";\nimport { applyFarmCacheInvalidationTargets, type FarmCacheInvalidationTarget } from \"../cache\";\nimport { isMultipartSchema, type MultipartSchema, type TypedFormData } from \"./transport\";\nimport type { RouteSchema, RouteSchemaInput, RouteSchemaOutput } from \"./route-schema\";\n\n// Share the route factory's Zod and Standard Schema contract.\ntype AnySchema = RouteSchema;\n\ntype MaybePromise<T> = T | Promise<T>;\ntype Simplify<T> = { [TKey in keyof T]: T[TKey] } & {};\ntype UnionToIntersection<T> = (T extends unknown ? (value: T) => void : never) extends (\n value: infer TIntersection,\n) => void\n ? TIntersection\n : never;\n\n// Handlers receive parsed output; callers supply the schema input.\ntype InferOutput<T> = RouteSchemaOutput<T>;\n\ntype InferInput<T> = T extends { _input: infer I }\n ? I\n : T extends { \"~standard\": unknown }\n ? RouteSchemaInput<T>\n : T extends { parse: (data: infer I) => unknown }\n ? I\n : unknown;\n\ntype InferBodyInput<T> =\n T extends MultipartSchema<AnySchema> ? TypedFormData<InferInput<T>> : InferInput<T>;\n\ntype InferHeadersOutput<T> = [T] extends [never]\n ? Record<string, string>\n : T extends AnySchema\n ? InferOutput<T>\n : Record<string, string>;\n\nexport type EndpointErrorSchema = AnySchema & { parse: (data: unknown) => unknown };\n\ntype EndpointErrorDefinitionBase<TStatus extends number> = {\n status: TStatus;\n /** Public message safe to expose to API callers. */\n message?: string;\n};\n\nexport type EndpointErrorDefinition<\n TSchema extends EndpointErrorSchema = EndpointErrorSchema,\n TStatus extends number = number,\n> = EndpointErrorDefinitionBase<TStatus> &\n (\n | {\n /** Schema for the public error payload exposed to API callers. */\n data: TSchema;\n schema?: never;\n }\n | {\n data?: never;\n /** @deprecated Use `data` for consistency with server functions. */\n schema: TSchema;\n }\n );\n\nexport type EndpointErrorDefinitions = Record<\n string,\n EndpointErrorDefinition<EndpointErrorSchema, number>\n>;\n\ntype InferEndpointErrorSchema<TDefinition> = TDefinition extends {\n data: infer TSchema extends AnySchema;\n}\n ? TSchema\n : TDefinition extends { schema: infer TSchema extends AnySchema }\n ? TSchema\n : never;\n\nexport type EndpointErrorContracts<TErrors extends EndpointErrorDefinitions> = {\n [TCode in keyof TErrors]: {\n data: InferOutput<InferEndpointErrorSchema<TErrors[TCode]>>;\n status: TErrors[TCode][\"status\"];\n };\n};\n\nexport type EndpointErrorHandler<TErrors extends EndpointErrorDefinitions> = <\n TCode extends keyof TErrors & string,\n>(\n code: TCode,\n data: InferInput<InferEndpointErrorSchema<TErrors[TCode]>>,\n) => never;\n\n/** @deprecated Use `EndpointErrorHandler`. */\nexport type EndpointFail<TErrors extends EndpointErrorDefinitions> = EndpointErrorHandler<TErrors>;\n\nexport class EndpointFailure<TCode extends string = string, TData = unknown> extends Error {\n readonly code: TCode;\n readonly data: TData;\n readonly status: number;\n\n constructor(\n code: TCode,\n data: TData,\n options: {\n status: number;\n message: string;\n },\n ) {\n super(options.message);\n this.name = \"EndpointFailure\";\n this.code = code;\n this.data = data;\n this.status = options.status;\n }\n}\n\nexport function isEndpointFailure(value: unknown): value is EndpointFailure<string, unknown> {\n return value instanceof EndpointFailure;\n}\n\nexport type EndpointParamValue = string | string[];\nexport type EndpointParams = Record<string, EndpointParamValue>;\n\nexport type EndpointMiddlewareContext<\n TContext extends object = {},\n TBody = unknown,\n TQuery = unknown,\n THeaders = Record<string, string>,\n> = {\n body: TBody;\n query: TQuery;\n headers: THeaders;\n request: Request;\n /** Context accumulated from middleware that ran earlier in the chain. */\n context: Readonly<TContext>;\n params: EndpointParams;\n};\n\nexport type EndpointMiddlewareResult<TProvidedContext extends object = object> =\n | TProvidedContext\n | true\n | false\n | Response;\n\n/** A plain async function. No wrapper or `next()` callback is required. */\nexport type EndpointMiddleware<\n TProvidedContext extends object = object,\n TContext extends object = {},\n TBody = unknown,\n TQuery = unknown,\n THeaders = Record<string, string>,\n> = (\n ctx: EndpointMiddlewareContext<TContext, TBody, TQuery, THeaders>,\n) => MaybePromise<EndpointMiddlewareResult<TProvidedContext>>;\n\nexport type AnyEndpointMiddleware = (ctx: EndpointMiddlewareContext<any, any, any, any>) => unknown;\n\nexport type EndpointInvalidationTarget = FarmCacheInvalidationTarget;\n\nexport type EndpointInvalidationContext<\n TContext extends object = {},\n TBody = unknown,\n TQuery = unknown,\n THeaders = Record<string, string>,\n> = EndpointMiddlewareContext<TContext, TBody, TQuery, THeaders> & {\n /** The raw value returned by the endpoint handler. */\n result: unknown;\n};\n\nexport type EndpointInvalidations<\n TContext extends object = {},\n TBody = unknown,\n TQuery = unknown,\n THeaders = Record<string, string>,\n> =\n | readonly EndpointInvalidationTarget[]\n | ((\n context: EndpointInvalidationContext<TContext, TBody, TQuery, THeaders>,\n ) => readonly EndpointInvalidationTarget[] | Promise<readonly EndpointInvalidationTarget[]>);\n\ntype ValidateEndpointMiddlewares<TMiddlewares extends readonly AnyEndpointMiddleware[]> = {\n readonly [TIndex in keyof TMiddlewares]: TMiddlewares[TIndex] extends AnyEndpointMiddleware\n ? [Awaited<ReturnType<TMiddlewares[TIndex]>>] extends [EndpointMiddlewareResult<object>]\n ? TMiddlewares[TIndex]\n : never\n : never;\n};\n\ntype ContextFromMiddlewareResult<TResult> =\n Exclude<TResult, Response | boolean> extends infer TContext\n ? [TContext] extends [never]\n ? {}\n : TContext extends object\n ? TContext\n : {}\n : {};\n\ntype ContextFromMiddleware<TMiddleware> = TMiddleware extends (...args: any[]) => infer TResult\n ? ContextFromMiddlewareResult<Awaited<TResult>>\n : {};\n\nexport type InferEndpointMiddlewareContext<\n TMiddlewares extends readonly ((...args: any[]) => any)[],\n TContext extends object = {},\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends (...args: any[]) => any\n ? TRest extends readonly ((...args: any[]) => any)[]\n ? InferEndpointMiddlewareContext<\n TRest,\n Simplify<TContext & ContextFromMiddleware<TMiddleware>>\n >\n : Simplify<TContext>\n : Simplify<TContext>\n : number extends TMiddlewares[\"length\"]\n ? Simplify<TContext & UnionToIntersection<ContextFromMiddleware<TMiddlewares[number]>>>\n : Simplify<TContext>;\n\nexport type EndpointOptions<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TMiddlewares extends readonly AnyEndpointMiddleware[] = readonly [],\n TErrors extends EndpointErrorDefinitions = {},\n> = {\n method?: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"OPTIONS\";\n body?: TBody;\n query?: TQuery;\n headers?: THeaders;\n middleware?: TMiddlewares;\n /**\n * Cache keys, tags, and route paths made stale after a successful handler result.\n * The resolver receives validated input and middleware context.\n */\n invalidates?: EndpointInvalidations<\n InferEndpointMiddlewareContext<TMiddlewares>,\n InferOutput<TBody>,\n InferOutput<TQuery>,\n InferHeadersOutput<THeaders>\n >;\n errors?: TErrors;\n /** @deprecated Use plain functions in `middleware` for Farm endpoint middleware. */\n use?: any[];\n};\n\nexport type EndpointHandler<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n TContext extends object = {},\n TErrors extends EndpointErrorDefinitions = {},\n> = (ctx: {\n body: InferOutput<TBody>;\n query: InferOutput<TQuery>;\n headers: InferHeadersOutput<THeaders>;\n request: Request;\n context: Readonly<TContext>;\n params: EndpointParams;\n error: EndpointErrorHandler<TErrors>;\n /** @deprecated Use `error`. */\n fail: EndpointFail<TErrors>;\n}) => Promise<TResponse> | TResponse;\n\n// Type to represent an endpoint with its input/output types\nexport type TypedEndpoint<\n TBody = never,\n TQuery = never,\n TResponse = any,\n THeaders = Record<string, string>,\n TErrors = never,\n TBodyInput = TBody,\n TQueryInput = TQuery,\n> = {\n __types: {\n body: TBody;\n inputBody: TBodyInput;\n query: TQuery;\n inputQuery: TQueryInput;\n headers: THeaders;\n response: TResponse;\n errors: TErrors;\n };\n __path?: string;\n __method?: string;\n} & ((options?: { body?: TBodyInput; query?: TQueryInput }) => Promise<TResponse>);\n\ntype CreatedEndpoint<\n TBody extends AnySchema,\n TQuery extends AnySchema,\n THeaders extends AnySchema,\n TResponse,\n TErrors extends EndpointErrorDefinitions = {},\n> = TypedEndpoint<\n InferOutput<TBody>,\n InferOutput<TQuery>,\n Awaited<TResponse>,\n InferHeadersOutput<THeaders>,\n EndpointErrorContracts<TErrors>,\n InferBodyInput<TBody>,\n InferInput<TQuery>\n>;\n\ntype AnyEndpointOptions = EndpointOptions<\n AnySchema,\n AnySchema,\n AnySchema,\n readonly AnyEndpointMiddleware[],\n EndpointErrorDefinitions\n>;\ntype EndpointBodyFromOptions<TOptions> = TOptions extends {\n body: infer TBody extends AnySchema;\n}\n ? TBody\n : never;\ntype EndpointQueryFromOptions<TOptions> = TOptions extends {\n query: infer TQuery extends AnySchema;\n}\n ? TQuery\n : never;\ntype EndpointHeadersFromOptions<TOptions> = TOptions extends {\n headers: infer THeaders extends AnySchema;\n}\n ? THeaders\n : never;\ntype EndpointMiddlewaresFromOptions<TOptions> = TOptions extends {\n middleware: infer TMiddlewares extends readonly AnyEndpointMiddleware[];\n}\n ? TMiddlewares\n : readonly [];\ntype EndpointErrorsFromOptions<TOptions> = TOptions extends {\n errors: infer TErrors extends EndpointErrorDefinitions;\n}\n ? TErrors\n : {};\ntype MethodlessEndpointOptions = Omit<AnyEndpointOptions, \"method\">;\ntype EndpointHandlerFromOptions<TOptions, TResponse> = EndpointHandler<\n EndpointBodyFromOptions<TOptions>,\n EndpointQueryFromOptions<TOptions>,\n EndpointHeadersFromOptions<TOptions>,\n TResponse,\n InferEndpointMiddlewareContext<EndpointMiddlewaresFromOptions<TOptions>>,\n EndpointErrorsFromOptions<TOptions>\n>;\ntype ValidatedEndpointHandlerFromOptions<TOptions, TResponse> = EndpointHandlerFromOptions<\n TOptions,\n TResponse\n> &\n (EndpointMiddlewaresFromOptions<TOptions> extends ValidateEndpointMiddlewares<\n EndpointMiddlewaresFromOptions<TOptions>\n >\n ? unknown\n : never);\ntype CreatedEndpointFromOptions<TOptions, TResponse> = CreatedEndpoint<\n EndpointBodyFromOptions<TOptions>,\n EndpointQueryFromOptions<TOptions>,\n EndpointHeadersFromOptions<TOptions>,\n TResponse,\n EndpointErrorsFromOptions<TOptions>\n>;\n\n/**\n * Create a Farm.js API endpoint\n *\n * Supports two patterns:\n * 1. File-based routing (path auto-inferred from file location):\n * `export const POST = createEndpoint({ method: 'POST', body: schema }, handler)`\n * `createEndpoint({ method: 'GET', query: z.object({...}) }, handler)`\n *\n * 2. Explicit path (for routes.ts at project root):\n * `createEndpoint('/api/hello', { method: 'GET', query: z.object({...}) }, handler)`\n */\nexport function createEndpoint<const TOptions extends AnyEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function createEndpoint<const TOptions extends AnyEndpointOptions, TResponse = any>(\n path: string,\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function createEndpoint<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: EndpointOptions<TBody, TQuery, THeaders, readonly []>,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function createEndpoint<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n path: string,\n options: EndpointOptions<TBody, TQuery, THeaders, readonly []>,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function createEndpoint(\n pathOrOptions:\n | string\n | EndpointOptions<any, any, any, readonly AnyEndpointMiddleware[], EndpointErrorDefinitions>,\n optionsOrHandler:\n | EndpointOptions<any, any, any, readonly AnyEndpointMiddleware[], EndpointErrorDefinitions>\n | EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n maybeHandler?: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n): TypedEndpoint<any, any, any, any> {\n // Determine if first arg is path or options\n let path: string;\n let options: EndpointOptions<\n any,\n any,\n any,\n readonly AnyEndpointMiddleware[],\n EndpointErrorDefinitions\n >;\n let handler: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>;\n\n if (typeof pathOrOptions === \"string\") {\n // createEndpoint('/path', options, handler)\n path = pathOrOptions;\n options = optionsOrHandler as typeof options;\n handler = maybeHandler as typeof handler;\n } else {\n // createEndpoint(options, handler) - path will be set by API plugin from file location\n path = \"\";\n options = pathOrOptions;\n handler = optionsOrHandler as typeof handler;\n }\n\n if (typeof handler !== \"function\") {\n throw new TypeError(\"createEndpoint requires a handler function\");\n }\n\n const middleware = normalizeEndpointMiddleware(options.middleware);\n const errors = normalizeEndpointErrors(options.errors);\n const error = createEndpointErrorHandler(errors);\n const wrappedHandler = (async (ctx: EndpointMiddlewareContext<any, any, any, any>) => {\n const execution = await runEndpointMiddleware(\n middleware,\n ctx,\n handler,\n error,\n options.invalidates,\n );\n return execution.result;\n }) as typeof handler;\n const {\n middleware: _middleware,\n errors: _errors,\n invalidates: _invalidates,\n ...betterCallOptions\n } = options;\n\n // Create the endpoint - path will be set later by API plugin if not provided\n // We use a temporary path that will be replaced when the router is created\n const endpoint = betterCallEndpoint(\n path || \"/__farm_auto_path__\",\n betterCallOptions as any,\n wrappedHandler as any,\n ) as any;\n\n // Store the path and type information on the endpoint for later access\n // Empty/undefined path means it will be inferred from file location by the API plugin\n endpoint.__path = path || undefined;\n endpoint.__method = options.method || \"GET\";\n endpoint.__autoPath = !path; // Flag to indicate path should be auto-inferred\n endpoint.__handler = wrappedHandler; // Used by Farm's route runtime.\n endpoint.__farmInvoke = (ctx: EndpointMiddlewareContext<any, any, any, any>) =>\n runEndpointMiddleware(middleware, ctx, handler, error, options.invalidates);\n endpoint.__middleware = middleware;\n endpoint.__sourceHandler = handler;\n endpoint.__invalidates = options.invalidates;\n endpoint.__errors = errors;\n\n // Store type information for inference\n endpoint.__types = {\n body: options.body,\n inputBody: isMultipartSchema(options.body) ? \"form-data\" : options.body,\n query: options.query,\n inputQuery: options.query,\n headers: options.headers,\n response: null as any,\n errors,\n };\n\n return endpoint as any;\n}\n\nconst EMPTY_ENDPOINT_MIDDLEWARE = Object.freeze([]) as readonly AnyEndpointMiddleware[];\nconst EMPTY_ENDPOINT_CONTEXT = Object.freeze(Object.create(null)) as Readonly<\n Record<string | symbol, unknown>\n>;\nconst UNSAFE_ENDPOINT_CONTEXT_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction normalizeEndpointErrors(\n definitions: EndpointErrorDefinitions | undefined,\n): Readonly<EndpointErrorDefinitions> {\n if (definitions === undefined) return Object.freeze({});\n if (!isPlainEndpointContext(definitions)) {\n throw new TypeError(\"createEndpoint errors must be an object\");\n }\n\n const normalized: EndpointErrorDefinitions = Object.create(null);\n for (const [code, definition] of Object.entries(definitions)) {\n if (!code.trim()) {\n throw new TypeError(\"Endpoint error codes cannot be empty\");\n }\n if (!definition || typeof definition !== \"object\") {\n throw new TypeError(`Endpoint error \"${code}\" must be an object`);\n }\n if (\n !Number.isInteger(definition.status) ||\n definition.status < 400 ||\n definition.status > 599\n ) {\n throw new TypeError(`Endpoint error \"${code}\" status must be an integer between 400 and 599`);\n }\n const dataSchema = resolveEndpointErrorSchema(definition);\n if (!dataSchema || typeof dataSchema.parse !== \"function\") {\n throw new TypeError(`Endpoint error \"${code}\" requires a data schema with parse()`);\n }\n if (definition.message !== undefined && typeof definition.message !== \"string\") {\n throw new TypeError(`Endpoint error \"${code}\" message must be a string`);\n }\n\n normalized[code] = Object.freeze({ ...definition });\n }\n\n return Object.freeze(normalized);\n}\n\nfunction resolveEndpointErrorSchema(\n definition: EndpointErrorDefinition<EndpointErrorSchema, number>,\n): EndpointErrorSchema | undefined {\n if (definition.data && definition.schema) {\n throw new TypeError(\"Endpoint errors cannot define both data and schema\");\n }\n return definition.data ?? definition.schema;\n}\n\nfunction createEndpointErrorHandler(\n definitions: Readonly<EndpointErrorDefinitions>,\n): EndpointErrorHandler<EndpointErrorDefinitions> {\n return ((code: string, data: unknown): never => {\n const definition = definitions[code];\n if (!definition) {\n throw new TypeError(`Endpoint error \"${code}\" is not declared`);\n }\n\n const parsed = resolveEndpointErrorSchema(definition)!.parse(data);\n throw new EndpointFailure(code, parsed, {\n status: definition.status,\n message: definition.message ?? \"Request failed\",\n });\n }) as EndpointErrorHandler<EndpointErrorDefinitions>;\n}\n\nfunction normalizeEndpointMiddleware(\n middleware: readonly AnyEndpointMiddleware[] | undefined,\n): readonly AnyEndpointMiddleware[] {\n if (middleware === undefined) return EMPTY_ENDPOINT_MIDDLEWARE;\n if (!Array.isArray(middleware)) {\n throw new TypeError(\"createEndpoint middleware must be an array of functions\");\n }\n\n const normalized = [...middleware];\n for (const entry of normalized) {\n if (typeof entry !== \"function\") {\n throw new TypeError(\"createEndpoint middleware entries must be functions\");\n }\n }\n\n return Object.freeze(normalized);\n}\n\nasync function runEndpointMiddleware(\n middleware: readonly AnyEndpointMiddleware[],\n handlerContext: EndpointMiddlewareContext<any, any, any, any>,\n handler: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n error: EndpointErrorHandler<EndpointErrorDefinitions>,\n invalidations: EndpointInvalidations<any, any, any, any> | undefined,\n): Promise<{\n result: unknown;\n context: Readonly<Record<string | symbol, unknown>>;\n handlerExecuted: boolean;\n invalidations: readonly string[];\n}> {\n let context = createInitialEndpointContext(handlerContext.context);\n\n for (let index = 0; index < middleware.length; index++) {\n const result = await middleware[index]({ ...handlerContext, context });\n\n if (isEndpointResponse(result)) {\n return {\n result,\n context,\n handlerExecuted: false,\n invalidations: [],\n };\n }\n if (result === false) {\n return {\n result: forbiddenEndpointResponse(),\n context,\n handlerExecuted: false,\n invalidations: [],\n };\n }\n if (result === true) continue;\n\n if (!isPlainEndpointContext(result)) {\n throw new TypeError(\n `Endpoint middleware ${index + 1} must return an object, true, false, or a Response`,\n );\n }\n\n context = mergeEndpointContext(context, result, index);\n }\n\n const result = await handler({ ...handlerContext, context, error, fail: error });\n return {\n result,\n context,\n handlerExecuted: true,\n invalidations: await applyEndpointInvalidations(\n invalidations,\n {\n ...handlerContext,\n context,\n result,\n },\n result,\n ),\n };\n}\n\nasync function applyEndpointInvalidations(\n declaration: EndpointInvalidations<any, any, any, any> | undefined,\n context: EndpointInvalidationContext<any, any, any, any>,\n result: unknown,\n): Promise<readonly string[]> {\n if (!declaration || (isEndpointResponse(result) && result.status >= 400)) {\n return [];\n }\n\n const targets = typeof declaration === \"function\" ? await declaration(context) : declaration;\n if (!Array.isArray(targets)) {\n throw new TypeError(\n \"Endpoint invalidates must resolve to an array of { key }, { path }, or { tag } targets\",\n );\n }\n\n return applyFarmCacheInvalidationTargets(targets);\n}\n\nfunction createInitialEndpointContext(value: unknown) {\n if (value === undefined || value === null) return EMPTY_ENDPOINT_CONTEXT;\n if (!isPlainEndpointContext(value)) {\n throw new TypeError(\"Endpoint context must be a plain object\");\n }\n\n return mergeEndpointContext(EMPTY_ENDPOINT_CONTEXT, value);\n}\n\nfunction mergeEndpointContext(\n current: Readonly<Record<string | symbol, unknown>>,\n added: object,\n middlewareIndex?: number,\n) {\n const next = Object.assign(Object.create(null), current) as Record<string | symbol, unknown>;\n\n for (const key of Reflect.ownKeys(added)) {\n if (!Object.prototype.propertyIsEnumerable.call(added, key)) continue;\n if (typeof key === \"string\" && UNSAFE_ENDPOINT_CONTEXT_KEYS.has(key)) {\n throw new TypeError(`Endpoint middleware cannot provide the unsafe context key \"${key}\"`);\n }\n if (Object.prototype.hasOwnProperty.call(current, key)) {\n const source =\n middlewareIndex === undefined\n ? \"Endpoint context\"\n : `Endpoint middleware ${middlewareIndex + 1}`;\n throw new TypeError(`${source} cannot replace the existing context key \"${String(key)}\"`);\n }\n next[key] = (added as Record<string | symbol, unknown>)[key];\n }\n\n return Object.freeze(next);\n}\n\nfunction isPlainEndpointContext(value: unknown): value is object {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isEndpointResponse(value: unknown): value is Response {\n return (\n value instanceof Response ||\n (typeof value === \"object\" &&\n value !== null &&\n \"headers\" in value &&\n \"status\" in value &&\n typeof (value as Response).arrayBuffer === \"function\")\n );\n}\n\nfunction forbiddenEndpointResponse() {\n return new Response(JSON.stringify({ error: \"Forbidden\" }), {\n status: 403,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\n/**\n * Convenience method for GET requests\n */\nexport function GET<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function GET<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function GET<\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<never, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<never, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<never, TQuery, THeaders, TResponse>;\nexport function GET(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"GET\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"GET\" }, args[1]);\n}\n\n/**\n * Convenience method for HEAD requests\n */\nexport function HEAD<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function HEAD<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function HEAD<\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<never, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<never, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<never, TQuery, THeaders, TResponse>;\nexport function HEAD(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"HEAD\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"HEAD\" }, args[1]);\n}\n\n/**\n * Convenience method for safe, idempotent QUERY requests with a request body\n */\nexport function QUERY<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function QUERY<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function QUERY<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function QUERY(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"QUERY\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"QUERY\" }, args[1]);\n}\n\n/**\n * Convenience method for POST requests\n */\nexport function POST<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function POST<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function POST<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function POST(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"POST\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"POST\" }, args[1]);\n}\n\n/**\n * Convenience method for PUT requests\n */\nexport function PUT<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function PUT<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function PUT<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function PUT(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"PUT\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"PUT\" }, args[1]);\n}\n\n/**\n * Convenience method for DELETE requests\n */\nexport function DELETE<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function DELETE<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function DELETE<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function DELETE(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"DELETE\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"DELETE\" }, args[1]);\n}\n\n/**\n * Convenience method for PATCH requests\n */\nexport function PATCH<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function PATCH<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function PATCH<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function PATCH(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"PATCH\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"PATCH\" }, args[1]);\n}\n\n/**\n * Convenience method for OPTIONS requests\n */\nexport function OPTIONS<T = any>(\n handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function OPTIONS<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n options: TOptions,\n handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function OPTIONS<\n TBody extends AnySchema = never,\n TQuery extends AnySchema = never,\n THeaders extends AnySchema = never,\n TResponse = any,\n>(\n options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function OPTIONS(...args: any[]): any {\n if (args.length === 1) {\n return createEndpoint(\"\", { method: \"OPTIONS\" }, args[0]);\n }\n return createEndpoint(\"\", { ...args[0], method: \"OPTIONS\" }, args[1]);\n}\n","export type MultipartField = string | number | boolean | bigint | Blob | Date | null | undefined;\n\nexport type MultipartValues = Record<string, MultipartField | readonly MultipartField[]>;\n\n/**\n * A real FormData value that retains the submitted value shape for generated\n * API-client inference.\n */\nexport type TypedFormData<TValues> = FormData & {\n readonly __farmMultipartInput: TValues;\n};\n\nexport type MultipartSchema<TSchema> = TSchema & {\n readonly __farmMultipartSchema: true;\n};\n\nexport type FarmStreamResponse<TItem> = Response & {\n readonly __farmStreamItem: TItem;\n};\n\nexport interface FarmAPIStream<TItem> extends AsyncIterable<TItem> {\n readonly response: Response;\n cancel(reason?: unknown): Promise<void>;\n}\n\ntype SchemaLike = {\n parse(data: unknown): unknown;\n};\n\n/**\n * Mark a body schema as multipart. The handler still receives the schema's\n * parsed object; generated clients require `toFormData(...)` for the request.\n */\nexport function multipart<TSchema extends SchemaLike>(schema: TSchema): MultipartSchema<TSchema> {\n if (!Object.isExtensible(schema) && !isMultipartSchema(schema)) {\n throw new TypeError(\"multipart() requires an extensible schema object\");\n }\n\n if (!isMultipartSchema(schema)) {\n Object.defineProperty(schema, \"__farmMultipartSchema\", {\n value: true,\n configurable: false,\n enumerable: false,\n writable: false,\n });\n }\n\n return schema as MultipartSchema<TSchema>;\n}\n\nexport function isMultipartSchema(value: unknown): value is MultipartSchema<SchemaLike> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { __farmMultipartSchema?: unknown }).__farmMultipartSchema === true &&\n typeof (value as SchemaLike).parse === \"function\"\n );\n}\n\n/**\n * Encode a typed object as multipart FormData without converting File or Blob\n * values to JSON or base64.\n */\nexport function toFormData<TValues extends MultipartValues>(\n values: TValues,\n): TypedFormData<TValues> {\n const formData = new FormData();\n\n for (const [key, value] of Object.entries(values)) {\n if (isUnsafeFormKey(key)) continue;\n if (Array.isArray(value)) {\n for (const entry of value) appendFormValue(formData, key, entry);\n continue;\n }\n appendFormValue(formData, key, value as MultipartField);\n }\n\n return formData as TypedFormData<TValues>;\n}\n\n/**\n * Stream JSON values as newline-delimited JSON. Each source value becomes one\n * independently decodable item instead of buffering the whole response.\n */\nexport function jsonStream<TItem>(\n source: AsyncIterable<TItem> | Iterable<TItem>,\n init: ResponseInit = {},\n): FarmStreamResponse<TItem> {\n const iterator = toAsyncIterator(source);\n const encoder = new TextEncoder();\n let finished = false;\n let cleanup: Promise<unknown> | undefined;\n const closeSource = (reason?: unknown) =>\n (cleanup ??= Promise.resolve().then(() => iterator.return?.(reason)));\n\n const body = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n if (finished) return;\n\n try {\n const next = await iterator.next();\n if (finished) return;\n if (next.done) {\n finished = true;\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(`${JSON.stringify(next.value)}\\n`));\n } catch (error) {\n if (finished) return;\n finished = true;\n try {\n await closeSource(error);\n } catch {\n // Preserve the serialization/source error that failed the response stream.\n }\n controller.error(error);\n }\n },\n async cancel(reason) {\n finished = true;\n await closeSource(reason);\n },\n },\n {\n // Do not read the next application event until the response consumer\n // requests another chunk.\n highWaterMark: 0,\n },\n );\n const headers = new Headers(init.headers);\n if (!headers.has(\"content-type\")) {\n headers.set(\"content-type\", \"application/x-ndjson; charset=utf-8\");\n }\n headers.set(\"cache-control\", headers.get(\"cache-control\") ?? \"no-store\");\n\n return new Response(body, {\n ...init,\n headers,\n }) as FarmStreamResponse<TItem>;\n}\n\nexport function isJSONStreamResponse(response: { headers?: Pick<Headers, \"get\"> | null }): boolean {\n const contentType = response.headers?.get?.(\"content-type\")?.toLowerCase() ?? \"\";\n return contentType.includes(\"application/x-ndjson\") || contentType.includes(\"application/ndjson\");\n}\n\n/**\n * Decode a Farm JSON stream lazily. The response body is read only as the\n * consumer advances the async iterator, preserving fetch backpressure.\n */\nexport function readJSONStream<TItem>(response: Response): FarmAPIStream<TItem> {\n if (!response.body) {\n throw new TypeError(\"Cannot read a JSON stream response without a body\");\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n let completed = false;\n let cancelled = false;\n let claimed = false;\n let released = false;\n\n const releaseReader = () => {\n if (released) return;\n released = true;\n reader.releaseLock();\n };\n const parseLine = async (line: string) => {\n try {\n return JSON.parse(line) as TItem;\n } catch (error) {\n completed = true;\n buffer = \"\";\n // A tee branch can wait for an unread sibling during cancellation. The\n // parse failure is already known and must not wait for producer cleanup.\n void reader.cancel(error).catch(() => {});\n releaseReader();\n throw error;\n }\n };\n\n const readNext = async (): Promise<IteratorResult<TItem>> => {\n while (true) {\n if (cancelled) return { done: true, value: undefined };\n const lineEnd = buffer.indexOf(\"\\n\");\n if (lineEnd >= 0) {\n const line = buffer.slice(0, lineEnd).trim();\n buffer = buffer.slice(lineEnd + 1);\n if (!line) continue;\n return { done: false, value: await parseLine(line) };\n }\n\n if (completed) {\n const line = buffer.trim();\n buffer = \"\";\n if (!line) {\n releaseReader();\n return { done: true, value: undefined };\n }\n return { done: false, value: await parseLine(line) };\n }\n\n let chunk: ReadableStreamReadResult<Uint8Array>;\n try {\n chunk = await reader.read();\n } catch (error) {\n if (cancelled) return { done: true, value: undefined };\n completed = true;\n buffer = \"\";\n releaseReader();\n throw error;\n }\n if (cancelled) return { done: true, value: undefined };\n completed = chunk.done;\n buffer += decoder.decode(chunk.value, { stream: !chunk.done });\n }\n };\n\n let readQueue = Promise.resolve();\n const iterator: AsyncIterator<TItem> = {\n next() {\n const result = readQueue.then(readNext);\n // A failed read must not poison subsequent operations on this iterator.\n readQueue = result.then(\n () => {},\n () => {},\n );\n return result;\n },\n async return() {\n cancelled = true;\n completed = true;\n buffer = \"\";\n if (!released) {\n try {\n await reader.cancel();\n } finally {\n releaseReader();\n }\n }\n return { done: true, value: undefined };\n },\n };\n\n return {\n response,\n async cancel(reason) {\n // Cancellation must interrupt the active reader, not wait in its queue.\n cancelled = true;\n completed = true;\n buffer = \"\";\n if (!released) {\n try {\n await reader.cancel(reason);\n } finally {\n releaseReader();\n }\n }\n },\n [Symbol.asyncIterator]() {\n if (claimed) {\n throw new TypeError(\"Farm API streams can only be consumed once\");\n }\n claimed = true;\n return iterator;\n },\n };\n}\n\nexport function isFarmAPIStream(value: unknown): value is FarmAPIStream<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"response\" in value &&\n typeof (value as FarmAPIStream<unknown>).cancel === \"function\" &&\n typeof (value as FarmAPIStream<unknown>)[Symbol.asyncIterator] === \"function\"\n );\n}\n\nfunction appendFormValue(formData: FormData, key: string, value: MultipartField): void {\n if (value === undefined) return;\n if (value === null) {\n formData.append(key, \"\");\n return;\n }\n if (value instanceof Blob) {\n formData.append(key, value);\n return;\n }\n if (value instanceof Date) {\n formData.append(key, value.toISOString());\n return;\n }\n formData.append(key, String(value));\n}\n\nfunction isUnsafeFormKey(key: string): boolean {\n return key === \"__proto__\" || key === \"constructor\" || key === \"prototype\";\n}\n\nfunction toAsyncIterator<TItem>(\n source: AsyncIterable<TItem> | Iterable<TItem>,\n): AsyncIterator<TItem> {\n if (Symbol.asyncIterator in Object(source)) {\n return (source as AsyncIterable<TItem>)[Symbol.asyncIterator]();\n }\n\n const iterator = (source as Iterable<TItem>)[Symbol.iterator]();\n return {\n next: async () => iterator.next(),\n return: iterator.return ? async (value?: unknown) => iterator.return!(value) : undefined,\n };\n}\n","import {\n createEndpoint,\n type TypedEndpoint,\n type AnyEndpointMiddleware,\n type EndpointMiddlewareResult,\n type InferEndpointMiddlewareContext,\n} from \"./endpoint\";\nimport {\n assertBrowserStableRoutePath,\n assertUniqueRouteParameters,\n getRoutePatternShape,\n} from \"../routing/specificity\";\nimport type { RouteSchema, RouteSchemaInput, RouteSchemaOutput } from \"./route-schema\";\n\nexport type RouteMethod =\n | \"GET\"\n | \"HEAD\"\n | \"QUERY\"\n | \"POST\"\n | \"PUT\"\n | \"PATCH\"\n | \"DELETE\"\n | \"OPTIONS\";\nexport type RoutePathParams<Path extends string> = Path extends `${infer Head}/${infer Tail}`\n ? RoutePathParams<Head> & RoutePathParams<Tail>\n : Path extends `[[...${infer Name}]]`\n ? { [K in Name]?: string[] }\n : Path extends `[...${infer Name}]`\n ? { [K in Name]: string[] }\n : Path extends `[${infer Name}]`\n ? { [K in Name]: string }\n : {};\n\nexport interface RouteInputSchemas {\n body?: RouteSchema;\n query?: RouteSchema;\n params?: RouteSchema;\n headers?: RouteSchema;\n}\ntype Input<I, K extends PropertyKey> = K extends keyof I ? RouteSchemaInput<I[K]> : never;\ntype Output<I, K extends PropertyKey, Fallback = unknown> = K extends keyof I\n ? RouteSchemaOutput<I[K]>\n : Fallback;\n/** JSON responses have wire types, not server-side instances such as Date. */\nexport type RouteJSON<T> = T extends Response\n ? unknown\n : T extends { toJSON(): infer J }\n ? RouteJSON<J>\n : T extends bigint | symbol | ((...args: any[]) => any)\n ? never\n : T extends readonly (infer V)[]\n ? RouteJSON<V>[]\n : T extends object\n ? { [K in keyof T]: RouteJSON<T[K]> }\n : T;\n\nexport type RouteDefinition<\n P extends string = string,\n M extends RouteMethod = RouteMethod,\n E = any,\n> = {\n readonly path: P;\n readonly method: M;\n readonly endpoint: E;\n};\n\ntype RouteEndpoint<P extends string, I extends RouteInputSchemas, R> = TypedEndpoint<\n Output<I, \"body\">,\n Input<I, \"query\">,\n RouteJSON<R>,\n Input<I, \"headers\">,\n never,\n Input<I, \"body\">\n> & {\n __types: { params: RoutePathParams<P>; inputHeaders: Input<I, \"headers\"> };\n};\n\ntype TrimStart<P extends string> = P extends `/${infer Rest}` ? TrimStart<Rest> : P;\ntype Join<P extends string, C extends string> = C extends \"\" ? P : `${P}/${TrimStart<C>}`;\ntype ParamsCheck<P extends string, I extends RouteInputSchemas> = I extends { params: infer S }\n ? Exclude<keyof RoutePathParams<P>, keyof RouteSchemaOutput<S>> extends never\n ? Exclude<keyof RouteSchemaOutput<S>, keyof RoutePathParams<P>> extends never\n ? unknown\n : { __error_unknown_route_params: never }\n : { __error_missing_route_params: never }\n : unknown;\n\ntype RouteMiddlewareResults = readonly (\n | EndpointMiddlewareResult\n | Promise<EndpointMiddlewareResult>\n)[];\n// Infer callback results directly so inline middleware is contextually typed before\n// its returned context is exposed to the route handler.\ntype RouteMiddlewares<Results extends readonly unknown[]> = {\n readonly [K in keyof Results]: (context: Parameters<AnyEndpointMiddleware>[0]) => Results[K];\n};\n\nexport type RouteOptions<\n P extends string,\n I extends RouteInputSchemas,\n O extends RouteSchema | undefined,\n R,\n MiddlewareResults extends RouteMiddlewareResults = RouteMiddlewareResults,\n> = {\n input?: I & ParamsCheck<P, I>;\n /** Validate plain JSON handler results. Raw Response/stream results are never buffered. */\n output?: O;\n middleware?: RouteMiddlewares<MiddlewareResults>;\n handler(\n request: Request,\n context: {\n input: {\n body: Output<I, \"body\">;\n query: Output<I, \"query\", Record<string, string | string[]>>;\n headers: Output<I, \"headers\", Record<string, string>>;\n params: Output<I, \"params\", RoutePathParams<P>>;\n };\n params: Output<I, \"params\", RoutePathParams<P>>;\n context: Readonly<InferEndpointMiddlewareContext<RouteMiddlewares<MiddlewareResults>>>;\n },\n ): R | Promise<R>;\n};\n\ntype RouteBuilder<P extends string, M extends RouteMethod> = <\n const C extends string,\n const MiddlewareResults extends RouteMiddlewareResults,\n const I extends RouteInputSchemas = {},\n O extends RouteSchema | undefined = undefined,\n R = unknown,\n>(\n path: C,\n options: RouteOptions<Join<P, C>, I, O, R, MiddlewareResults>,\n) => RouteDefinition<\n Join<P, C>,\n M,\n RouteEndpoint<\n Join<P, C>,\n I,\n Extract<Awaited<R>, Response> extends never\n ? O extends RouteSchema\n ? RouteSchemaOutput<O>\n : Awaited<R>\n : unknown\n >\n>;\n\nexport type RouteFactory<P extends string = \"\"> = {\n [M in Lowercase<RouteMethod>]: RouteBuilder<P, Uppercase<M> & RouteMethod>;\n} & {\n /** Return a new builder; never mutate the parent scope. */\n scope<const C extends string>(path: C): RouteFactory<Join<P, C>>;\n};\n\nexport type PluginRoutes = readonly RouteDefinition[];\nexport type PluginRoutesFactory<R extends PluginRoutes = PluginRoutes> = (context: {\n route: RouteFactory;\n}) => R;\n\nexport function createRouteFactory(): RouteFactory {\n return createRouteFactoryAt(\"\");\n}\n\nfunction createRouteFactoryAt(prefix: string): RouteFactory {\n const factory: Record<string, unknown> = {\n scope(child: string) {\n return createRouteFactoryAt(joinRoutePath(prefix, child));\n },\n };\n for (const method of [\n \"GET\",\n \"HEAD\",\n \"QUERY\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"OPTIONS\",\n ] as const) {\n factory[method.toLowerCase()] = (\n child: string,\n options: RouteOptions<string, any, any, any>,\n ) => {\n const path = joinRoutePath(prefix, child);\n const input = options.input ?? {};\n const endpoint = createEndpoint(\n path,\n {\n method,\n body: input.body,\n query: input.query,\n headers: input.headers,\n middleware: options.middleware,\n },\n (ctx) =>\n options.handler(ctx.request, {\n input: { body: ctx.body, query: ctx.query, headers: ctx.headers, params: ctx.params },\n params: ctx.params,\n context: ctx.context,\n }),\n ) as any;\n endpoint.__types.params = input.params;\n endpoint.__output = options.output;\n return Object.freeze({ path, method, endpoint });\n };\n }\n return Object.freeze(factory) as RouteFactory;\n}\n\nfunction joinRoutePath(prefix: string, child: string): string {\n if (typeof child !== \"string\") throw new TypeError(\"Route paths must be strings.\");\n const path = child === \"\" ? prefix : `${prefix}/${child.replace(/^\\//, \"\")}`;\n if (!(path === \"/api\" || path.startsWith(\"/api/\")) || /[?#]|\\/\\/|\\/$/.test(path)) {\n throw new TypeError(\n `Plugin route \"${path}\" must be a canonical /api path without a query, hash, or empty segment.`,\n );\n }\n assertBrowserStableRoutePath(path);\n assertUniqueRouteParameters(path, \"api\");\n getRoutePatternShape(path, \"api\");\n for (const segment of path.split(\"/\")) {\n if ([\"__proto__\", \"constructor\", \"prototype\", \"$params\"].includes(segment)) {\n throw new TypeError(`Route segment \"${segment}\" is reserved.`);\n }\n }\n return path;\n}\n\ntype UnionToIntersection<U> = (U extends unknown ? (v: U) => void : never) extends (\n v: infer I,\n) => void\n ? I\n : never;\ntype RouteTree<P extends string, M extends string, E> = P extends `${infer Head}/${infer Tail}`\n ? { [K in Head]: RouteTree<Tail, M, E> }\n : P extends \"\"\n ? { [K in Lowercase<M>]: E }\n : { [K in P]: { [Method in Lowercase<M>]: E } };\ntype HasMethodSegment<P extends string> = P extends `${infer H}/${infer T}`\n ? H extends Lowercase<RouteMethod>\n ? true\n : HasMethodSegment<T>\n : P extends Lowercase<RouteMethod>\n ? true\n : false;\ntype DefinitionTree<D> =\n D extends RouteDefinition<infer P, infer M, infer E>\n ? string extends P\n ? {}\n : (P extends `/api/integrations${string}` ? true : HasMethodSegment<P>) extends true\n ? { [K in P extends `/api/${infer C}` ? `/${C}` : \"/\"]: { [Method in Lowercase<M>]: E } }\n : RouteTree<P extends `/api/${infer C}` ? C : \"\", M, E>\n : {};\nexport type PluginAPIRouter<C> = C extends { plugins: readonly (infer P)[] }\n ? UnionToIntersection<\n P extends { routes?: PluginRoutesFactory<infer R> } ? DefinitionTree<R[number]> : {}\n >\n : {};\n\nexport function resolvePluginRoutes(\n plugins: readonly { name: string; routes?: PluginRoutesFactory }[] = [],\n): PluginRoutes {\n return plugins.flatMap((plugin) => {\n if (!plugin.routes) return [];\n const routes = plugin.routes({ route: createRouteFactory() });\n if (!Array.isArray(routes))\n throw new TypeError(`Plugin \"${plugin.name}\" routes must return an array synchronously.`);\n for (const route of routes) {\n if (\n !route ||\n joinRoutePath(\"\", route.path) !== route.path ||\n typeof route.endpoint !== \"function\" ||\n ![\"GET\", \"HEAD\", \"QUERY\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\"].includes(\n route.method,\n )\n ) {\n throw new TypeError(`Plugin \"${plugin.name}\" returned an invalid API route.`);\n }\n }\n return routes;\n });\n}\n","import {\n AmbiguousRouteError,\n assertUniqueRouteParameters,\n getRoutePatternShape,\n} from \"../routing/specificity\";\n\nexport interface APIRouteShapeSource<TSource> {\n routePath: string;\n source: TSource;\n filePath: string;\n}\n\n/** Validate API URL shapes and return the lower-priority route replaced by this source. */\nexport function registerAPIRouteShape<TSource>(\n shapes: Map<string, APIRouteShapeSource<TSource>>,\n routePath: string,\n filePath: string,\n source: TSource,\n): string | undefined {\n assertUniqueRouteParameters(routePath, \"api\");\n const shape = getRoutePatternShape(routePath, \"api\");\n const existing = shapes.get(shape);\n const replacesPath = existing && existing.routePath !== routePath;\n\n if (replacesPath && existing.source === source) {\n throw new AmbiguousRouteError(\n `Ambiguous API routes \"${existing.routePath}\" and \"${routePath}\" match the same URLs. Found ${existing.filePath} and ${filePath}. Keep only one route for this URL shape.`,\n );\n }\n\n shapes.set(shape, { routePath, source, filePath });\n return replacesPath ? existing.routePath : undefined;\n}\n","import { resolvePluginRoutes, type PluginRoutesFactory } from \"./route\";\nimport { registerAPIRouteShape } from \"./route-shape\";\n\ninterface MountedRoute {\n path: string;\n methods: string[];\n endpoints: Record<string, any>;\n filePath?: string;\n pluginMethods?: string[];\n}\n\n/** The same registration step is used by dev discovery and the production bundle. */\nexport function mergePluginAPIRoutes(\n existing: readonly MountedRoute[],\n plugins: readonly { name: string; routes?: PluginRoutesFactory }[],\n expected?: readonly { path: string; methods: readonly string[] }[],\n): Array<MountedRoute & { filePath: string }> {\n const routes = new Map<string, MountedRoute & { filePath: string }>();\n const shapes = new Map();\n for (const route of existing) {\n registerAPIRouteShape(shapes, route.path, route.filePath || route.path, \"app\");\n routes.set(route.path, {\n ...route,\n filePath: route.filePath || \"\",\n methods: [...route.methods],\n endpoints: { ...route.endpoints },\n });\n }\n for (const definition of resolvePluginRoutes(plugins)) {\n registerAPIRouteShape(shapes, definition.path, `plugin:${definition.path}`, \"app\");\n let route = routes.get(definition.path);\n if (route?.methods.includes(definition.method)) {\n throw new Error(\n `Duplicate API route for ${definition.method} ${definition.path}. Plugin routes cannot override app or other plugin endpoints.`,\n );\n }\n if (!route) {\n route = { path: definition.path, filePath: \"\", methods: [], endpoints: {} };\n routes.set(definition.path, route);\n }\n route.methods.push(definition.method);\n route.pluginMethods = [...(route.pluginMethods ?? []), definition.method];\n route.endpoints[definition.method] = definition.endpoint;\n }\n const result = [...routes.values()];\n if (expected) {\n const signature = (entries: readonly { path: string; methods: readonly string[] }[]) =>\n entries\n .map(({ path, methods }) => `${path}:${[...methods].sort().join(\",\")}`)\n .sort()\n .join(\"\\n\");\n if (signature(result) !== signature(expected)) {\n throw new Error(\n \"Plugin API routes changed between build and runtime. Route paths and methods must be stable across environments; rebuild the app.\",\n );\n }\n }\n return result;\n}\n","import { mergePluginAPIRoutes } from \"./plugin-route-runtime\";\nimport type { FarmPlugin } from \"../plugin\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { logger } from \"../utils\";\nimport type { ProgrammaticApiRoute } from \"../routes\";\nimport { createProgrammaticRouteModuleId } from \"../routes-shared\";\nimport { findProgrammaticRouteFilesInDir } from \"../routes.server\";\nimport {\n getFarmRouteRuntimeConfig,\n normalizeFarmRouteRuntimeConfig,\n type FarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport { _runWithFarmI18nRequest, type FarmI18nRuntime } from \"../i18n/server\";\nimport {\n getAllowedAPIRouteMethods,\n invokeAPIRouteEndpoint,\n registerAPIRouteShape,\n type APIRouteShapeSource,\n matchAPIRouteAtBasePath,\n matchAPIRoute,\n resolveAPIRouteEndpoint,\n type APIRouteMatch,\n} from \"./runtime\";\nimport { isFarmAPIRouteFileName } from \"./route-files\";\nimport { AmbiguousRouteError, NonTerminalCatchAllRouteError } from \"../routing/specificity\";\n\nexport interface APIRoute extends FarmRouteRuntimeConfig {\n pluginMethods?: string[];\n path: string;\n filePath: string;\n methods: string[];\n endpoints: Record<string, any>;\n}\n\nexport interface APIRouteManagerOptions {\n plugins?: readonly FarmPlugin[];\n throwOnLoadError?: boolean;\n i18n?: FarmI18nRuntime;\n bodySizeLimit?: number;\n /** Same-origin path where canonical `/api` routes are served. */\n basePath?: string;\n}\n\nexport interface APIRouteHandlerOptions {\n /** Let a framework request boundary report the original endpoint error. */\n throwOnError?: boolean;\n}\n\nexport class APIRouteConflictError extends Error {\n constructor(routePath: string, method: string, existingFile: string, conflictingFile: string) {\n super(\n `Duplicate API route for ${method.toUpperCase()} ${routePath}: ${existingFile} conflicts with ${conflictingFile}`,\n );\n this.name = \"APIRouteConflictError\";\n }\n}\n\nexport const API_ROUTE_METHODS = [\n \"GET\",\n \"HEAD\",\n \"QUERY\",\n \"POST\",\n \"PUT\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n] as const;\n\nexport class APIRouteManager {\n private plugins: readonly FarmPlugin[];\n private routes: Map<string, APIRoute> = new Map();\n private endpointSources: Map<string, Map<string, { appDir: string; filePath: string }>> =\n new Map();\n private routeShapes = new Map<string, APIRouteShapeSource<string>>();\n private viteServer?: ViteDevServer;\n private appDirs: string[];\n private throwOnLoadError: boolean;\n private i18n?: FarmI18nRuntime;\n private bodySizeLimit?: number;\n private basePath?: string;\n\n constructor(\n appDir: string | readonly string[],\n viteServer?: ViteDevServer,\n options: APIRouteManagerOptions = {},\n ) {\n this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n this.viteServer = viteServer;\n this.plugins = options.plugins ?? [];\n this.throwOnLoadError = options.throwOnLoadError === true;\n this.i18n = options.i18n;\n this.bodySizeLimit = options.bodySizeLimit;\n this.basePath = options.basePath;\n }\n\n /**\n * Discover route.ts files in /app/api and explicit endpoints in root routes.ts\n */\n async discoverRoutes(): Promise<void> {\n const previousRoutes = this.routes;\n const previousEndpointSources = this.endpointSources;\n const previousRouteShapes = this.routeShapes;\n this.routes = new Map();\n this.endpointSources = new Map();\n this.routeShapes = new Map();\n\n try {\n for (const appDir of this.appDirs) {\n const apiDir = path.join(appDir, \"api\");\n let routeFiles: string[] = [];\n\n if (fs.existsSync(apiDir)) {\n routeFiles = this.findRouteFiles(apiDir);\n }\n\n for (const filePath of routeFiles) {\n await this.loadRoute(filePath, appDir);\n }\n\n await this.loadRootRoutes(appDir);\n await this.loadProgrammaticApiRoutes(appDir);\n }\n this.routes = new Map(\n mergePluginAPIRoutes([...this.routes.values()], this.plugins).map((route) => [\n route.path,\n route,\n ]),\n );\n } catch (error) {\n this.routes = previousRoutes;\n this.endpointSources = previousEndpointSources;\n this.routeShapes = previousRouteShapes;\n throw error;\n }\n\n if (process.env.FARM_VERBOSE) {\n logger.success(`Discovered ${this.routes.size} API routes`);\n for (const [routePath, route] of this.routes) {\n logger.info(` ${route.methods.join(\", \")} ${routePath}`);\n }\n }\n }\n\n /**\n * Recursively find all route.ts files\n */\n private findRouteFiles(dir: string): string[] {\n const files: string[] = [];\n\n if (!fs.existsSync(dir)) {\n return files;\n }\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n files.push(...this.findRouteFiles(fullPath));\n } else if (isFarmAPIRouteFileName(entry.name)) {\n files.push(fullPath);\n }\n }\n\n return files;\n }\n\n /**\n * Load a route.ts file and extract HTTP method exports\n */\n private async loadRoute(filePath: string, appDir: string): Promise<void> {\n try {\n // Convert file path to API route path\n // /app/api/auth/login/route.ts -> /api/auth/login\n const apiDir = path.join(appDir, \"api\");\n const relativePath = path.relative(apiDir, path.dirname(filePath));\n const routePath = \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n\n const routeModule = await this.loadModule(filePath);\n\n const endpoints: Record<string, any> = {};\n const availableMethods: string[] = [];\n\n for (const method of API_ROUTE_METHODS) {\n if (routeModule[method]) {\n endpoints[method] = routeModule[method];\n availableMethods.push(method);\n }\n }\n\n if (availableMethods.length > 0) {\n const existingSources = this.endpointSources.get(routePath);\n if (existingSources) {\n for (const method of availableMethods) {\n const existingSource = existingSources.get(method);\n if (existingSource?.appDir === appDir) {\n throw new APIRouteConflictError(routePath, method, existingSource.filePath, filePath);\n }\n }\n }\n const runtimeConfig = normalizeFarmRouteRuntimeConfig(\n getFarmRouteRuntimeConfig(routeModule),\n `API route \"${routePath}\"`,\n );\n this.registerRouteShape(routePath, filePath, appDir);\n const existingRoute = this.routes.get(routePath);\n const mergedMethods = existingRoute ? [...existingRoute.methods] : [];\n for (const method of availableMethods) {\n if (!mergedMethods.includes(method)) mergedMethods.push(method);\n }\n this.routes.set(routePath, {\n ...existingRoute,\n path: routePath,\n filePath,\n methods: mergedMethods,\n endpoints: { ...existingRoute?.endpoints, ...endpoints },\n ...runtimeConfig,\n });\n const nextSources = new Map(existingSources);\n for (const method of availableMethods) {\n nextSources.set(method, { appDir, filePath });\n }\n this.endpointSources.set(routePath, nextSources);\n }\n } catch (error) {\n this.handleLoadError(`Error loading route ${filePath}`, error);\n }\n }\n\n /**\n * Load explicit-path endpoints from src/routes.ts-style files.\n */\n private async loadRootRoutes(appDir: string): Promise<void> {\n const routesFile = this.findRootRoutesFile(appDir);\n if (!routesFile) {\n return;\n }\n\n try {\n const routesModule = await this.loadModule(routesFile);\n\n for (const exportValue of Object.values(routesModule)) {\n const endpoint = exportValue as any;\n if (!endpoint?.__path) {\n continue;\n }\n\n const method = String(endpoint.__method || \"GET\").toUpperCase();\n this.registerRouteShape(endpoint.__path, routesFile, appDir);\n this.addEndpoint(endpoint.__path, routesFile, method, endpoint, appDir);\n }\n } catch (error) {\n this.handleLoadError(`Error loading root API routes ${routesFile}`, error);\n }\n }\n\n private async loadProgrammaticApiRoutes(appDir: string): Promise<void> {\n const candidateRoots = [path.dirname(appDir), appDir];\n const routeFiles = Array.from(\n new Set(candidateRoots.flatMap((srcRoot) => findProgrammaticRouteFilesInDir(srcRoot))),\n );\n if (routeFiles.length === 0) return;\n\n const { getProgrammaticRouteManifest } = await import(\"../routes\");\n\n for (const routeFile of routeFiles) {\n try {\n const routesModule = await this.loadModule(routeFile);\n const manifest = getProgrammaticRouteManifest(routesModule);\n if (!manifest) continue;\n\n for (const definition of manifest.routes) {\n if (definition.kind !== \"api\") continue;\n if (!Object.values(definition.methods).some(Boolean)) continue;\n this.addProgrammaticApiRoute(routeFile, definition, appDir);\n }\n } catch (error) {\n this.handleLoadError(`Error loading programmatic API routes ${routeFile}`, error);\n }\n }\n }\n\n private handleLoadError(message: string, error: unknown): void {\n logger.error(`${message}: ${error}`);\n if (\n this.throwOnLoadError ||\n error instanceof APIRouteConflictError ||\n error instanceof AmbiguousRouteError ||\n error instanceof NonTerminalCatchAllRouteError\n ) {\n throw error;\n }\n }\n\n private findRootRoutesFile(appDir: string): string | null {\n const routeNames = [\"routes.ts\", \"routes.tsx\", \"routes.js\"];\n const candidateDirs = [path.dirname(appDir), appDir];\n const seen = new Set<string>();\n\n for (const dir of candidateDirs) {\n for (const routeName of routeNames) {\n const routesFile = path.join(dir, routeName);\n if (seen.has(routesFile)) {\n continue;\n }\n seen.add(routesFile);\n\n if (fs.existsSync(routesFile)) {\n return routesFile;\n }\n }\n }\n\n return null;\n }\n\n private async loadModule(filePath: string): Promise<Record<string, unknown>> {\n if (this.viteServer) {\n return await this.viteServer.ssrLoadModule(filePath);\n }\n\n const fileUrl = `file://${filePath}`;\n return await import(/* @vite-ignore */ fileUrl);\n }\n\n private addEndpoint(\n routePath: string,\n filePath: string,\n method: string,\n endpoint: any,\n appDir: string,\n runtimeConfig: FarmRouteRuntimeConfig = {},\n ): void {\n const normalizedMethod = method.toUpperCase();\n const existingRoute = this.routes.get(routePath);\n const existingSource = this.endpointSources.get(routePath)?.get(normalizedMethod);\n\n if (existingSource?.appDir === appDir) {\n throw new APIRouteConflictError(\n routePath,\n normalizedMethod,\n existingSource.filePath,\n filePath,\n );\n }\n\n if (existingRoute) {\n if (!existingRoute.methods.includes(normalizedMethod)) {\n existingRoute.methods.push(normalizedMethod);\n }\n existingRoute.endpoints[normalizedMethod] = endpoint;\n Object.assign(existingRoute, runtimeConfig);\n const sources = this.endpointSources.get(routePath) ?? new Map();\n sources.set(normalizedMethod, { appDir, filePath });\n this.endpointSources.set(routePath, sources);\n return;\n }\n\n this.routes.set(routePath, {\n path: routePath,\n filePath,\n methods: [normalizedMethod],\n endpoints: { [normalizedMethod]: endpoint },\n ...runtimeConfig,\n });\n this.endpointSources.set(routePath, new Map([[normalizedMethod, { appDir, filePath }]]));\n }\n\n private addProgrammaticApiRoute(\n filePath: string,\n route: ProgrammaticApiRoute,\n appDir: string,\n ): void {\n const modulePath = createProgrammaticRouteModuleId(filePath, \"api\", route.path);\n const runtimeConfig = normalizeFarmRouteRuntimeConfig(route, `API route \"${route.path}\"`);\n for (const [method, endpoint] of Object.entries(route.methods)) {\n if (endpoint) {\n this.addEndpoint(route.path, modulePath, method, endpoint, appDir, runtimeConfig);\n }\n }\n }\n\n private registerRouteShape(routePath: string, filePath: string, appDir: string): void {\n const replacedPath = registerAPIRouteShape(this.routeShapes, routePath, filePath, appDir);\n if (replacedPath) {\n this.routes.delete(replacedPath);\n this.endpointSources.delete(replacedPath);\n }\n }\n\n /**\n * Get the handler that directly invokes endpoint handlers\n */\n getHandler(options: APIRouteHandlerOptions = {}): ((req: Request) => Promise<Response>) | null {\n if (this.routes.size === 0) {\n return null;\n }\n\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const pathname = url.pathname;\n const method = request.method.toUpperCase();\n\n // Find matching route\n const match = matchAPIRouteAtBasePath(this.routes, pathname, this.basePath);\n if (!match) {\n return new Response(JSON.stringify({ error: \"Not Found\" }), {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n // Check if method is supported\n const { route, params } = match;\n const endpoint = resolveAPIRouteEndpoint(route, method);\n if (!endpoint) {\n return new Response(JSON.stringify({ error: \"Method Not Allowed\" }), {\n status: 405,\n headers: {\n Allow: getAllowedAPIRouteMethods(route).join(\", \"),\n \"Content-Type\": \"application/json\",\n },\n });\n }\n\n const invoke = async () => {\n try {\n return await invokeAPIRouteEndpoint(endpoint, request, params, this.bodySizeLimit);\n } catch (error: any) {\n if (options.throwOnError) throw error;\n console.error(`[API Error] ${pathname}:`, error);\n return new Response(JSON.stringify({ error: \"Internal Server Error\" }), {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n };\n\n return this.i18n?.config.enabled\n ? _runWithFarmI18nRequest(this.i18n, request, invoke, {\n redirect: false,\n })\n : invoke();\n };\n }\n\n /**\n * Check if a path is an API route\n */\n isAPIRoute(pathname: string): boolean {\n return Boolean(this.matchRoute(pathname));\n }\n\n matchRoute(pathname: string): APIRouteMatch<APIRoute> | null {\n return matchAPIRouteAtBasePath(this.routes, pathname, this.basePath);\n }\n\n /**\n * Get all routes for client type generation\n */\n getRoutes(): Map<string, APIRoute> {\n return this.routes;\n }\n}\n\nexport {\n getAllowedAPIRouteMethods,\n invokeAPIRouteEndpoint,\n isWebResponse,\n matchAPIRoute,\n normalizeRouteResponse,\n resolveAPIRouteEndpoint,\n} from \"./runtime\";\nexport type { APIRouteMatch, APIRouteParams, APIRouteParamValue } from \"./runtime\";\n","import type { RouteSegment, ParsedRoute } from \"./types\";\nimport path from \"path\";\nimport {\n assertBrowserStableRoutePath,\n assertTerminalCatchAll,\n assertUniqueRouteParameters,\n} from \"./routing/specificity\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { decodeRouteSegment } from \"./utils/decode\";\n\nexport function parseRoutePath(filePath: string): ParsedRoute {\n const segments: RouteSegment[] = [];\n const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n const pathParts = normalizedPath.split(\"/\").filter(Boolean);\n\n const fileName = pathParts.pop() || \"\";\n const fileType = getRouteType(fileName);\n const routePath = `/${pathParts.join(\"/\")}`;\n assertBrowserStableRoutePath(routePath);\n assertTerminalCatchAll(routePath);\n assertUniqueRouteParameters(routePath);\n\n for (const part of pathParts) {\n // Route groups like `(marketing)` organize files without adding URL\n // segments. Mirrors isRouteGroup in router.ts for programmatic routes.\n if (part.startsWith(\"(\") && part.endsWith(\")\")) continue;\n if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n let segment = part.slice(1, -1);\n const isDynamic = true;\n let isOptional = false;\n let isCatchAll = false;\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n isOptional = true;\n segment = segment.slice(1, -1);\n if (segment.startsWith(\"...\")) {\n segment = segment.slice(3);\n isCatchAll = true;\n }\n } else if (segment.startsWith(\"...\")) {\n segment = segment.slice(3);\n isCatchAll = true;\n }\n\n segments.push({ segment, isDynamic, isOptional, isCatchAll });\n } else {\n segments.push({\n segment: part,\n isDynamic: false,\n isOptional: false,\n isCatchAll: false,\n });\n }\n }\n\n return {\n segments,\n filePath: normalizedPath,\n type: fileType,\n };\n}\n\nfunction getRouteType(fileName: string): ParsedRoute[\"type\"] {\n const baseName = fileName.replace(/\\.(tsx?|jsx?|vue|svelte|mdx?|markdown)$/, \"\");\n\n switch (baseName) {\n case \"page\":\n return \"page\";\n case \"layout\":\n return \"layout\";\n case \"loading\":\n return \"loading\";\n case \"error\":\n return \"error\";\n case \"not-found\":\n return \"not-found\";\n default:\n return \"page\";\n }\n}\n\nexport function segmentsToPattern(segments: RouteSegment[]): string {\n if (segments.length === 0) return \"/\";\n\n return (\n \"/\" +\n segments\n .map((segment) => {\n if (!segment.isDynamic) return segment.segment;\n\n if (segment.isCatchAll) {\n return segment.isOptional ? `*${segment.segment}?` : `*${segment.segment}`;\n }\n\n return `:${segment.segment}`;\n })\n .join(\"/\")\n );\n}\n\nexport function matchRoute(\n url: string,\n segments: RouteSegment[],\n): { params: Record<string, string>; matches: boolean } {\n const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n const params: Record<string, string> = {};\n if (segments.length === 0) {\n return { params, matches: urlParts.length === 0 };\n }\n\n let urlIndex = 0;\n let segmentIndex = 0;\n\n while (segmentIndex < segments.length && urlIndex <= urlParts.length) {\n const segment = segments[segmentIndex];\n\n if (!segment.isDynamic) {\n if (urlParts[urlIndex] !== segment.segment) {\n return { params: {}, matches: false };\n }\n urlIndex++;\n segmentIndex++;\n } else if (segment.isCatchAll) {\n const remainingParts = urlParts.slice(urlIndex);\n\n if (remainingParts.length === 0 && !segment.isOptional) {\n return { params: {}, matches: false };\n }\n\n params[segment.segment] = remainingParts.join(\"/\");\n urlIndex = urlParts.length;\n segmentIndex++;\n } else {\n if (urlIndex >= urlParts.length) {\n return { params: {}, matches: false };\n }\n\n params[segment.segment] = urlParts[urlIndex];\n urlIndex++;\n segmentIndex++;\n }\n }\n\n const matches = segmentIndex === segments.length && urlIndex === urlParts.length;\n\n return { params, matches };\n}\n\n/** Match a route segment chain as an owner of the pathname or one of its descendants. */\nexport function matchRoutePrefix(url: string, segments: RouteSegment[]): boolean {\n const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n let urlIndex = 0;\n\n for (const segment of segments) {\n if (segment.isCatchAll) {\n return segment.isOptional || urlIndex < urlParts.length;\n }\n\n const urlPart = urlParts[urlIndex];\n if (urlPart === undefined) return false;\n if (!segment.isDynamic && segment.segment !== urlPart) return false;\n urlIndex++;\n }\n\n return true;\n}\n\nexport function resolveAppPath(root: string, ...paths: string[]): string {\n return path.resolve(root, ...paths);\n}\n\n/**\n * Convert an absolute module path inside the project root to a root-relative\n * URL path with forward slashes (e.g. `/src/app/page.tsx`), for values the\n * client passes to dynamic `import()`. On Windows the naive root-prefix slice\n * yields `\\src\\app\\page.tsx`, which is not a valid module specifier. Returns\n * undefined for paths outside the root so callers keep their own fallbacks.\n */\nexport function toRootRelativeUrlPath(\n absolutePath: string,\n projectRoot: string,\n): string | undefined {\n if (absolutePath === projectRoot) return \"\";\n if (absolutePath.startsWith(`${projectRoot}/`) || absolutePath.startsWith(`${projectRoot}\\\\`)) {\n return absolutePath.slice(projectRoot.length).replace(/\\\\/g, \"/\");\n }\n return undefined;\n}\n\n/**\n * Normalize a filesystem path to forward slashes. Node's fs accepts these on\n * every platform, and module ids handed to bundlers (e.g. Nitro handler and\n * task entries) must not contain backslashes.\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\");\n}\n\nexport function toViteModuleId(filePath: string, root: string): string {\n if (!path.isAbsolute(filePath)) return filePath;\n\n const relativePath = path.relative(root, filePath);\n if (relativePath && !relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n return `/${relativePath.split(path.sep).join(\"/\")}`;\n }\n\n const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n return normalizedPath.startsWith(\"/\") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n const fs = await import(\"fs/promises\");\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function globFiles(pattern: string, cwd: string): Promise<string[]> {\n const glob = await import(\"fast-glob\");\n return glob.default(pattern, { cwd, absolute: false });\n}\n\nexport function parseSearchParams(\n searchParams: URLSearchParams,\n): Record<string, string | string[]> {\n return searchParamsToObject(searchParams) as Record<string, string | string[]>;\n}\n\nexport const logger = {\n info: (message: string) => console.log(`[info] ${message}`),\n success: (message: string) => console.log(`[success] ${message}`),\n warn: (message: string) => console.warn(`⚠️ ${message}`),\n error: (message: string) => console.error(`❌ ${message}`),\n ready: (message: string) => console.log(`${message}`),\n event: (message: string) => console.log(` ${message}`),\n};\n","import { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { PROGRAMMATIC_ROUTE_FILE_NAMES, scanProgrammaticPagePaths } from \"./routes-shared\";\nimport type { ProgrammaticRouteManifest } from \"./routes\";\n\nexport interface LoadedProgrammaticRouteManifest {\n filePath: string;\n manifest: ProgrammaticRouteManifest;\n}\n\nexport async function loadProgrammaticRouteManifests(options: {\n root: string;\n srcDir?: string;\n loadModule: (filePath: string) => Promise<Record<string, any>>;\n}): Promise<LoadedProgrammaticRouteManifest[]> {\n const manifests: LoadedProgrammaticRouteManifest[] = [];\n const routeFiles = findProgrammaticRouteFiles(options.root, options.srcDir);\n if (routeFiles.length === 0) return manifests;\n\n const { getProgrammaticRouteManifest } = await import(\"./routes\");\n\n for (const filePath of routeFiles) {\n const mod = await options.loadModule(filePath);\n const manifest = getProgrammaticRouteManifest(mod);\n if (manifest) {\n manifests.push({ filePath, manifest });\n }\n }\n\n return manifests;\n}\n\nexport function findProgrammaticRouteFiles(root: string, srcDir = \"src\"): string[] {\n return findProgrammaticRouteFilesInDir(join(root, srcDir));\n}\n\nexport function findProgrammaticRouteFilesInDir(srcRoot: string): string[] {\n const files: string[] = [];\n\n for (const fileName of PROGRAMMATIC_ROUTE_FILE_NAMES) {\n const filePath = join(srcRoot, fileName);\n if (existsSync(filePath)) {\n files.push(filePath);\n }\n }\n\n return files;\n}\n\nexport async function discoverProgrammaticRoutePaths(\n root: string,\n srcDir = \"src\",\n): Promise<string[]> {\n const paths = new Set<string>();\n const files = new Set([\n ...findProgrammaticRouteFiles(root, srcDir),\n ...(await findProgrammaticRouteSourceFiles(join(root, srcDir))),\n ]);\n\n for (const filePath of files) {\n const source = readFileSync(filePath, \"utf8\");\n for (const routePath of scanProgrammaticPagePaths(source)) {\n paths.add(routePath);\n }\n }\n\n return Array.from(paths).sort();\n}\n\nasync function findProgrammaticRouteSourceFiles(srcRoot: string): Promise<string[]> {\n if (!existsSync(srcRoot)) {\n return [];\n }\n\n try {\n const glob = await import(\"fast-glob\");\n return await glob.default(\"**/*.{ts,tsx,js,jsx}\", {\n cwd: srcRoot,\n absolute: true,\n ignore: [\n \"**/*.d.ts\",\n \"**/node_modules/**\",\n \"**/.*/**\",\n \"farm-routes.d.ts\",\n \"farm-env.d.ts\",\n \"lib/api.generated.ts\",\n ],\n });\n } catch {\n return [];\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { FarmLocaleResolution } from \"./resolver\";\nimport { _setFarmI18nSnapshotResolver } from \"./bridge\";\nimport { FarmI18nRuntime, createFarmI18nRuntime } from \"./runtime\";\nimport type {\n FarmI18nClientSnapshot,\n FarmI18nLocale,\n FarmI18nLocaleSource,\n FarmI18nMessageArgs,\n FarmI18nMessageKey,\n FarmTranslator,\n} from \"./types\";\n\ninterface FarmI18nRequestState {\n runtime: FarmI18nRuntime;\n resolution: FarmLocaleResolution;\n snapshot: FarmI18nClientSnapshot;\n}\n\ninterface FarmListFormatOptions {\n localeMatcher?: \"lookup\" | \"best fit\";\n type?: \"conjunction\" | \"disjunction\" | \"unit\";\n style?: \"long\" | \"short\" | \"narrow\";\n}\n\nconst FARM_I18N_REQUEST_STORE = Symbol.for(\"farm.i18n.requestStore\");\nconst FARM_I18N_DEFAULT_RUNTIME = Symbol.for(\"farm.i18n.defaultRuntime\");\n\ntype GlobalFarmI18nState = typeof globalThis & {\n [FARM_I18N_REQUEST_STORE]?: AsyncLocalStorage<FarmI18nRequestState>;\n [FARM_I18N_DEFAULT_RUNTIME]?: FarmI18nRuntime;\n};\n\nfunction getRequestStore(): AsyncLocalStorage<FarmI18nRequestState> {\n const state = globalThis as GlobalFarmI18nState;\n return (state[FARM_I18N_REQUEST_STORE] ??= new AsyncLocalStorage<FarmI18nRequestState>());\n}\n\nfunction getState(): FarmI18nRequestState {\n const state = getRequestStore().getStore();\n if (!state) {\n throw new Error(\n \"No Farm i18n request context is active. Use this API while rendering, inside an API route, or use createTranslator(locale).\",\n );\n }\n return state;\n}\n\nexport function _setDefaultFarmI18nRuntime(runtime: FarmI18nRuntime | undefined): void {\n (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME] = runtime;\n}\n\nexport async function _runWithFarmI18nRequest<T>(\n runtime: FarmI18nRuntime,\n request: Request,\n fn: (resolution: FarmLocaleResolution) => T | Promise<T>,\n options: { redirect?: boolean } = {},\n): Promise<T> {\n const resolution = runtime.resolveRequest(request, options);\n const state: FarmI18nRequestState = {\n runtime,\n resolution,\n snapshot: runtime.getClientSnapshot(resolution),\n };\n return getRequestStore().run(state, () => fn(resolution));\n}\n\nexport async function runWithLocale<T>(\n locale: FarmI18nLocale,\n fn: () => T | Promise<T>,\n): Promise<T> {\n const runtime = getDefaultRuntime();\n assertLocale(runtime, locale);\n const resolution: FarmLocaleResolution = {\n locale,\n source: \"explicit\",\n pathname: \"/\",\n persist: false,\n };\n const state: FarmI18nRequestState = {\n runtime,\n resolution,\n snapshot: runtime.getClientSnapshot(resolution),\n };\n return getRequestStore().run(state, fn);\n}\n\nexport function getLocale(): FarmI18nLocale {\n return getState().resolution.locale as FarmI18nLocale;\n}\n\nexport function getLocaleSource(): FarmI18nLocaleSource {\n return getState().resolution.source;\n}\n\nexport const t = createTranslatorFromState(() => getState());\n\nexport function createTranslator(locale: FarmI18nLocale): FarmTranslator {\n const runtime = getDefaultRuntime();\n assertLocale(runtime, locale);\n return createTranslatorFromState(() => ({\n runtime,\n resolution: {\n locale,\n source: \"explicit\",\n pathname: \"/\",\n persist: false,\n },\n snapshot: runtime.getClientSnapshot({\n locale,\n source: \"explicit\",\n pathname: \"/\",\n persist: false,\n }),\n }));\n}\n\nexport function getFarmI18nClientSnapshot(): FarmI18nClientSnapshot | undefined {\n return getRequestStore().getStore()?.snapshot;\n}\n\nexport const format = {\n number(value: number, options?: Intl.NumberFormatOptions): string {\n return new Intl.NumberFormat(getLocale(), options).format(value);\n },\n currency(\n value: number,\n currency: string,\n options: Omit<Intl.NumberFormatOptions, \"style\" | \"currency\"> = {},\n ): string {\n return new Intl.NumberFormat(getLocale(), {\n ...options,\n style: \"currency\",\n currency,\n }).format(value);\n },\n date(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return new Intl.DateTimeFormat(getLocale(), options).format(value);\n },\n relativeTime(\n value: number,\n unit: Intl.RelativeTimeFormatUnit,\n options?: Intl.RelativeTimeFormatOptions,\n ): string {\n return new Intl.RelativeTimeFormat(getLocale(), options).format(value, unit);\n },\n list(values: Iterable<string>, options?: FarmListFormatOptions): string {\n const ListFormat = (Intl as any).ListFormat;\n return new ListFormat(getLocale(), options).format(Array.from(values));\n },\n};\n\nfunction getDefaultRuntime(): FarmI18nRuntime {\n const runtime = (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME];\n if (!runtime?.config.enabled) {\n throw new Error(\"Farm i18n is not configured for this application.\");\n }\n return runtime;\n}\n\nfunction assertLocale(runtime: FarmI18nRuntime, locale: string): void {\n if (!runtime.config.locales.includes(locale)) {\n throw new Error(`Unsupported Farm i18n locale \"${locale}\".`);\n }\n}\n\nfunction createTranslatorFromState(resolveState: () => FarmI18nRequestState): FarmTranslator {\n const translator = ((key: string, values?: Record<string, unknown>) => {\n const state = resolveState();\n return state.runtime.translate(state.resolution.locale, key, values);\n }) as FarmTranslator;\n translator.rich = (key: string, values?: Record<string, unknown>) => {\n const state = resolveState();\n return state.runtime.translateRich(state.resolution.locale, key, values);\n };\n translator.raw = (key: string) => {\n const state = resolveState();\n return state.runtime.getRawMessage(state.resolution.locale, key);\n };\n translator.has = (key: string) => {\n const state = resolveState();\n return state.runtime.hasMessage(state.resolution.locale, key);\n };\n return translator;\n}\n\n_setFarmI18nSnapshotResolver(() => getFarmI18nClientSnapshot());\n\nexport { FarmI18nRuntime, createFarmI18nRuntime };\nexport type { FarmI18nClientSnapshot, FarmI18nLocale, FarmI18nMessageArgs, FarmI18nMessageKey };\n","import IntlMessageFormat from \"intl-messageformat\";\nimport { readFarmI18nCatalogs } from \"./catalog\";\nimport { getFarmLocaleDirection } from \"./routing\";\nimport { resolveFarmLocaleRequest, type FarmLocaleResolution } from \"./resolver\";\nimport type { FarmI18nCatalogs, FarmI18nClientSnapshot, ResolvedFarmI18nConfig } from \"./types\";\n\nexport class FarmI18nRuntime {\n readonly config: ResolvedFarmI18nConfig;\n private catalogs: FarmI18nCatalogs;\n private compiled = new Map<string, IntlMessageFormat>();\n private warnedMissing = new Set<string>();\n\n constructor(config: ResolvedFarmI18nConfig, catalogs: FarmI18nCatalogs = {}) {\n this.config = config;\n this.catalogs = catalogs;\n }\n\n async initialize(): Promise<void> {\n if (!this.config.enabled) return;\n const bundle = await readFarmI18nCatalogs(this.config);\n this.replaceCatalogs(bundle.catalogs);\n }\n\n async reload(): Promise<void> {\n await this.initialize();\n }\n\n replaceCatalogs(catalogs: FarmI18nCatalogs): void {\n this.catalogs = catalogs;\n this.compiled.clear();\n this.warnedMissing.clear();\n }\n\n getCatalogs(): FarmI18nCatalogs {\n return Object.fromEntries(\n Object.entries(this.catalogs).map(([locale, catalog]) => [locale, { ...catalog }]),\n );\n }\n\n resolveRequest(request: Request, options: { redirect?: boolean } = {}): FarmLocaleResolution {\n return resolveFarmLocaleRequest(request, this.config, options);\n }\n\n translate(locale: string, key: string, values?: Record<string, unknown>): string {\n const result = this.formatMessage(locale, key, values);\n if (Array.isArray(result) && result.some((part) => typeof part !== \"string\")) {\n throw new Error(`Farm i18n message \"${key}\" contains rich content. Render it with t.rich().`);\n }\n return Array.isArray(result) ? result.join(\"\") : String(result);\n }\n\n translateRich(locale: string, key: string, values?: Record<string, unknown>): unknown {\n const result = this.formatMessage(locale, key, values);\n return Array.isArray(result) && result.length === 1 ? result[0] : result;\n }\n\n getRawMessage(locale: string, key: string): string {\n return this.resolveMessage(locale, key);\n }\n\n hasMessage(locale: string, key: string): boolean {\n return this.readOwnMessage(locale, key) !== undefined;\n }\n\n getClientSnapshot(resolution: FarmLocaleResolution): FarmI18nClientSnapshot {\n return {\n locale: resolution.locale,\n source: resolution.source,\n locales: this.config.locales,\n defaultLocale: this.config.defaultLocale,\n routing: this.config.routing,\n basePath: this.config.basePath,\n cookie: this.config.cookie,\n direction: getFarmLocaleDirection(resolution.locale, this.config.direction),\n messages: {\n ...this.catalogs[this.config.fallbackLocale],\n ...this.catalogs[resolution.locale],\n },\n };\n }\n\n private formatMessage(locale: string, key: string, values?: Record<string, unknown>): unknown {\n const message = this.resolveMessage(locale, key);\n const cacheKey = `${locale}\\u0000${key}\\u0000${message}`;\n let formatter = this.compiled.get(cacheKey);\n if (!formatter) {\n formatter = new IntlMessageFormat(message, locale);\n this.compiled.set(cacheKey, formatter);\n }\n return formatter.format(values as any);\n }\n\n // Look up a message by own-property only. A key named after an\n // Object.prototype member (toString, valueOf, constructor, ...) must resolve\n // to a real catalog entry or undefined, never the inherited prototype value\n // (mirrors the own-property handling added to catalog.ts in #454).\n private readOwnMessage(locale: string, key: string): string | undefined {\n const direct = this.catalogs[locale];\n if (direct && Object.prototype.hasOwnProperty.call(direct, key)) return direct[key];\n const fallback = this.catalogs[this.config.fallbackLocale];\n if (fallback && Object.prototype.hasOwnProperty.call(fallback, key)) return fallback[key];\n return undefined;\n }\n\n private resolveMessage(locale: string, key: string): string {\n const message = this.readOwnMessage(locale, key);\n if (message !== undefined) return message;\n if (this.config.strict) {\n throw new Error(`Missing Farm i18n message \"${key}\" for locale \"${locale}\".`);\n }\n const warningKey = `${locale}:${key}`;\n if (!this.warnedMissing.has(warningKey)) {\n this.warnedMissing.add(warningKey);\n console.warn(`[Farm.js] Missing i18n message \"${key}\" for locale \"${locale}\".`);\n }\n return key;\n }\n}\n\nexport function createFarmI18nRuntime(\n config: ResolvedFarmI18nConfig,\n catalogs?: FarmI18nCatalogs,\n): FarmI18nRuntime {\n return new FarmI18nRuntime(config, catalogs);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { TYPE, parse, type MessageFormatElement } from \"@formatjs/icu-messageformat-parser\";\nimport { resolveFarmI18nMessagePath } from \"./config\";\nimport type { FarmI18nCatalog, FarmI18nCatalogs, ResolvedFarmI18nConfig } from \"./types\";\n\nexport type FarmI18nArgumentKind = \"string\" | \"number\" | \"date\" | \"select\" | \"rich\";\nexport type FarmI18nMessageSignature = Record<string, FarmI18nArgumentKind>;\n\nexport interface FarmI18nCatalogBundle {\n catalogs: FarmI18nCatalogs;\n signatures: Record<string, FarmI18nMessageSignature>;\n}\n\nexport async function readFarmI18nCatalogs(\n config: ResolvedFarmI18nConfig,\n): Promise<FarmI18nCatalogBundle> {\n if (!config.enabled) {\n return { catalogs: {}, signatures: {} };\n }\n\n const catalogs: FarmI18nCatalogs = {};\n for (const locale of config.locales) {\n const filePath = resolveFarmI18nMessagePath(config, locale);\n let source: string;\n try {\n source = await readFile(filePath, \"utf8\");\n } catch (error) {\n throw new Error(\n `Unable to read Farm i18n catalog for \"${locale}\" at ${filePath}: ${messageOf(error)}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch (error) {\n throw new Error(`Invalid JSON in Farm i18n catalog ${filePath}: ${messageOf(error)}`);\n }\n catalogs[locale] = flattenFarmI18nCatalog(parsed, filePath);\n }\n\n const reference = catalogs[config.defaultLocale] || {};\n const signatures: Record<string, FarmI18nMessageSignature> = {};\n for (const [key, message] of Object.entries(reference)) {\n signatures[key] = analyzeFarmI18nMessage(message, `${config.defaultLocale}:${key}`);\n }\n\n validateFarmI18nCatalogs(config, catalogs, signatures);\n return { catalogs, signatures };\n}\n\nexport function flattenFarmI18nCatalog(input: unknown, source = \"i18n catalog\"): FarmI18nCatalog {\n if (!isPlainObject(input)) {\n throw new Error(`${source} must contain a JSON object at its root.`);\n }\n\n const output: FarmI18nCatalog = {};\n const visit = (value: unknown, segments: string[]) => {\n if (typeof value === \"string\") {\n const key = segments.join(\".\");\n if (!key) throw new Error(`${source} contains an empty message key.`);\n // Own-property check: `in` would see Object.prototype members, falsely\n // rejecting legitimate keys like \"toString\" as duplicates.\n if (Object.prototype.hasOwnProperty.call(output, key)) {\n throw new Error(`${source} contains duplicate message key \"${key}\".`);\n }\n output[key] = value;\n return;\n }\n\n if (!isPlainObject(value)) {\n const key = segments.join(\".\") || \"<root>\";\n throw new Error(`${source} message \"${key}\" must be a string or nested object.`);\n }\n\n for (const [key, nested] of Object.entries(value)) {\n if (!key.trim()) throw new Error(`${source} contains an empty message key.`);\n visit(nested, [...segments, key]);\n }\n };\n\n visit(input, []);\n return output;\n}\n\nexport function analyzeFarmI18nMessage(\n message: string,\n label = \"message\",\n): FarmI18nMessageSignature {\n let ast: MessageFormatElement[];\n try {\n ast = parse(message, { captureLocation: false });\n } catch (error) {\n throw new Error(`Invalid ICU syntax in ${label}: ${messageOf(error)}`);\n }\n\n const signature: FarmI18nMessageSignature = {};\n collectArguments(ast, signature, label);\n return signature;\n}\n\nfunction validateFarmI18nCatalogs(\n config: ResolvedFarmI18nConfig,\n catalogs: FarmI18nCatalogs,\n signatures: Record<string, FarmI18nMessageSignature>,\n): void {\n const referenceKeys = Object.keys(catalogs[config.defaultLocale] || {}).sort();\n\n for (const locale of config.locales) {\n const catalog = catalogs[locale] || {};\n const localeKeys = Object.keys(catalog).sort();\n const missing = referenceKeys.filter(\n (key) => !Object.prototype.hasOwnProperty.call(catalog, key),\n );\n const extra = localeKeys.filter(\n (key) => !Object.prototype.hasOwnProperty.call(signatures, key),\n );\n\n if (config.strict && (missing.length > 0 || extra.length > 0)) {\n const details = [\n missing.length ? `missing: ${missing.join(\", \")}` : \"\",\n extra.length ? `extra: ${extra.join(\", \")}` : \"\",\n ]\n .filter(Boolean)\n .join(\"; \");\n throw new Error(\n `Farm i18n catalog \"${locale}\" does not match the default catalog (${details}).`,\n );\n }\n\n for (const [key, message] of Object.entries(catalog)) {\n const actual = analyzeFarmI18nMessage(message, `${locale}:${key}`);\n const expected = signatures[key];\n if (!expected || sameSignature(expected, actual)) continue;\n throw new Error(\n `Farm i18n message \"${key}\" in \"${locale}\" uses different variables than \"${config.defaultLocale}\".`,\n );\n }\n }\n}\n\nfunction collectArguments(\n elements: MessageFormatElement[],\n signature: FarmI18nMessageSignature,\n label: string,\n): void {\n for (const element of elements) {\n switch (element.type) {\n case TYPE.argument:\n addArgument(signature, element.value, \"string\", label);\n break;\n case TYPE.number:\n case TYPE.plural:\n addArgument(signature, element.value, \"number\", label);\n break;\n case TYPE.date:\n case TYPE.time:\n addArgument(signature, element.value, \"date\", label);\n break;\n case TYPE.select:\n addArgument(signature, element.value, \"select\", label);\n break;\n case TYPE.tag:\n addArgument(signature, element.value, \"rich\", label);\n collectArguments(element.children, signature, label);\n break;\n }\n\n if (element.type === TYPE.plural || element.type === TYPE.select) {\n for (const option of Object.values(element.options)) {\n collectArguments(option.value, signature, label);\n }\n }\n }\n}\n\nfunction addArgument(\n signature: FarmI18nMessageSignature,\n name: string,\n kind: FarmI18nArgumentKind,\n label: string,\n): void {\n const existing = signature[name];\n if (existing && existing !== kind) {\n throw new Error(`Farm i18n ${label} uses variable \"${name}\" as both ${existing} and ${kind}.`);\n }\n signature[name] = kind;\n}\n\nfunction sameSignature(\n expected: FarmI18nMessageSignature,\n actual: FarmI18nMessageSignature,\n): boolean {\n const expectedEntries = Object.entries(expected).sort(([a], [b]) => a.localeCompare(b));\n const actualEntries = Object.entries(actual).sort(([a], [b]) => a.localeCompare(b));\n return JSON.stringify(expectedEntries) === JSON.stringify(actualEntries);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import path from \"node:path\";\nimport type {\n FarmI18nDetectionSignal,\n FarmI18nDirection,\n FarmI18nUserConfig,\n ResolvedFarmI18nConfig,\n} from \"./types\";\n\nexport const DEFAULT_FARM_I18N_COOKIE = \"farm_locale\";\nexport const DEFAULT_FARM_I18N_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\nconst DEFAULT_DETECTION: readonly FarmI18nDetectionSignal[] = [\"url\", \"cookie\", \"accept-language\"];\n\nexport function resolveFarmI18nConfig(\n input: FarmI18nUserConfig | false | undefined,\n options: { root?: string; mode?: \"development\" | \"production\"; basePath?: string } = {},\n): ResolvedFarmI18nConfig {\n const root = options.root || process.cwd();\n const basePath = options.basePath || \"/\";\n const strictByDefault = options.mode === \"production\";\n\n if (!input) {\n return {\n enabled: false,\n basePath,\n locales: [\"en\"],\n defaultLocale: \"en\",\n messages: path.join(root, \"src/messages\"),\n routing: \"none\",\n detection: [],\n fallbackLocale: \"en\",\n strict: strictByDefault,\n cookie: {\n name: DEFAULT_FARM_I18N_COOKIE,\n maxAge: DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n path: \"/\",\n sameSite: \"lax\",\n secure: options.mode === \"production\",\n },\n direction: {},\n };\n }\n\n if (!Array.isArray(input.locales) || input.locales.length === 0) {\n throw new Error(\"i18n.locales must contain at least one locale.\");\n }\n\n const locales = input.locales.map(canonicalizeLocale);\n if (new Set(locales).size !== locales.length) {\n throw new Error(\"i18n.locales must not contain duplicate locales.\");\n }\n\n const defaultLocale = canonicalizeLocale(input.defaultLocale);\n if (!locales.includes(defaultLocale)) {\n throw new Error(`i18n.defaultLocale \"${defaultLocale}\" must be included in i18n.locales.`);\n }\n\n const fallbackLocale = canonicalizeLocale(input.fallbackLocale || defaultLocale);\n if (!locales.includes(fallbackLocale)) {\n throw new Error(`i18n.fallbackLocale \"${fallbackLocale}\" must be included in i18n.locales.`);\n }\n\n const detection = resolveDetection(input);\n const sameSite = input.cookie?.sameSite ?? \"lax\";\n if (sameSite !== \"lax\" && sameSite !== \"strict\" && sameSite !== \"none\") {\n throw new Error('i18n.cookie.sameSite must be \"lax\", \"strict\", or \"none\".');\n }\n const direction: Record<string, FarmI18nDirection> = {};\n for (const [rawLocale, value] of Object.entries(input.direction || {})) {\n const locale = canonicalizeLocale(rawLocale);\n if (!locales.includes(locale)) {\n throw new Error(`i18n.direction contains unknown locale \"${rawLocale}\".`);\n }\n if (value !== \"ltr\" && value !== \"rtl\") {\n throw new Error(`i18n.direction.${rawLocale} must be \"ltr\" or \"rtl\".`);\n }\n direction[locale] = value;\n }\n\n return {\n enabled: true,\n basePath,\n locales,\n defaultLocale,\n messages: path.resolve(root, input.messages || \"src/messages\"),\n routing: input.routing || \"prefix-except-default\",\n detection,\n fallbackLocale,\n strict: input.strict ?? strictByDefault,\n cookie: {\n name: input.cookie?.name?.trim() || DEFAULT_FARM_I18N_COOKIE,\n maxAge: normalizePositiveInteger(\n input.cookie?.maxAge,\n DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n \"i18n.cookie.maxAge\",\n ),\n path: normalizeCookiePath(input.cookie?.path),\n sameSite,\n secure: input.cookie?.secure ?? options.mode === \"production\",\n },\n direction,\n };\n}\n\nexport function resolveFarmI18nMessagePath(\n config: Pick<ResolvedFarmI18nConfig, \"messages\">,\n locale: string,\n): string {\n return config.messages.includes(\"{locale}\")\n ? config.messages.split(\"{locale}\").join(locale)\n : path.join(config.messages, `${locale}.json`);\n}\n\nexport function canonicalizeLocale(locale: string): string {\n if (!locale || typeof locale !== \"string\") {\n throw new Error(\"Farm i18n locales must be non-empty strings.\");\n }\n\n try {\n return Intl.getCanonicalLocales(locale)[0]!;\n } catch {\n throw new Error(`Invalid i18n locale \"${locale}\".`);\n }\n}\n\nfunction resolveDetection(input: FarmI18nUserConfig): readonly FarmI18nDetectionSignal[] {\n if (input.detection === false || input.localeDetection === false) {\n return [\"url\"];\n }\n\n const detection = input.detection || DEFAULT_DETECTION;\n const allowed = new Set<FarmI18nDetectionSignal>([\"url\", \"cookie\", \"accept-language\"]);\n const unique: FarmI18nDetectionSignal[] = [];\n\n for (const signal of detection) {\n if (!allowed.has(signal)) {\n throw new Error(`Unsupported i18n detection signal \"${signal}\".`);\n }\n if (!unique.includes(signal)) unique.push(signal);\n }\n\n return unique;\n}\n\nfunction normalizePositiveInteger(\n value: number | undefined,\n fallback: number,\n name: string,\n): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(`${name} must be a positive integer.`);\n }\n return value;\n}\n\nfunction normalizeCookiePath(value: string | undefined): string {\n if (value === undefined) return \"/\";\n if (typeof value !== \"string\") {\n throw new Error(\"i18n.cookie.path must be a root-relative pathname.\");\n }\n\n const hasUnstableCharacters = (candidate: string) =>\n candidate.includes(\"\\\\\") ||\n Array.from(candidate).some((character) => {\n const code = character.charCodeAt(0);\n return code <= 31 || (code >= 127 && code <= 159);\n });\n\n if (hasUnstableCharacters(value)) {\n throw new Error(\"i18n.cookie.path cannot contain backslashes or control characters.\");\n }\n\n const pathname = value.trim();\n if (\n !pathname ||\n !pathname.startsWith(\"/\") ||\n pathname.startsWith(\"//\") ||\n pathname.includes(\";\") ||\n pathname.includes(\"?\") ||\n pathname.includes(\"#\")\n ) {\n throw new Error(\n \"i18n.cookie.path must be a root-relative pathname without attributes, a query, or a hash.\",\n );\n }\n\n for (const segment of pathname.split(\"/\")) {\n let decoded = segment;\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n // Malformed escapes remain literal and cannot conceal a separator or dot segment.\n }\n if (hasUnstableCharacters(decoded)) {\n throw new Error(\"i18n.cookie.path cannot contain backslashes or control characters.\");\n }\n if (decoded.includes(\"/\")) {\n throw new Error(\"i18n.cookie.path cannot contain percent-encoded path separators.\");\n }\n if (decoded === \".\" || decoded === \"..\") {\n throw new Error('i18n.cookie.path cannot contain \".\" or \"..\" path segments.');\n }\n }\n\n return pathname;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { Readable } from \"node:stream\";\nimport type { FarmRequest } from \"../types\";\nimport { _setCurrentRequestResolver } from \"./request-bridge\";\n\nconst REQUEST_STORAGE_KEY = Symbol.for(\"@farm.js/core/request-storage\");\n\nfunction getRequestStore(): AsyncLocalStorage<Request> {\n const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n const existing = runtime[REQUEST_STORAGE_KEY];\n if (existing instanceof AsyncLocalStorage) {\n return existing as AsyncLocalStorage<Request>;\n }\n\n const storage = new AsyncLocalStorage<Request>();\n runtime[REQUEST_STORAGE_KEY] = storage;\n return storage;\n}\n\nconst requestStore = getRequestStore();\n\n_setCurrentRequestResolver(() => requestStore.getStore());\n\nexport interface FarmRequestURLOptions {\n origin?: string | URL;\n trustProxy?: boolean;\n}\n\nexport function resolveFarmRequestURL(req: FarmRequest, options: FarmRequestURLOptions = {}): URL {\n if (options.origin) {\n return new URL(req.url || \"/\", options.origin);\n }\n\n const forwardedHost = options.trustProxy\n ? firstForwardedHeaderValue(req.headers[\"x-forwarded-host\"])\n : undefined;\n const fallbackHost = firstForwardedHeaderValue(req.headers.host) || \"localhost\";\n const forwardedProto = options.trustProxy\n ? firstForwardedHeaderValue(req.headers[\"x-forwarded-proto\"])\n : undefined;\n const normalizedProto = forwardedProto?.toLowerCase();\n const proto =\n normalizedProto === \"https\" || normalizedProto === \"http\"\n ? normalizedProto\n : isEncryptedFarmRequest(req)\n ? \"https\"\n : \"http\";\n return new URL(req.url || \"/\", resolveRequestOrigin(proto, forwardedHost, fallbackHost));\n}\n\nexport function createWebRequestFromFarmRequest(\n req: FarmRequest,\n options: FarmRequestURLOptions = {},\n): Request {\n const fullUrl = resolveFarmRequestURL(req, options).toString();\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value == null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(key, item);\n }\n continue;\n }\n\n headers.set(key, value);\n }\n\n const method = (req.method || \"GET\").toUpperCase();\n const init: RequestInit & { duplex?: \"half\" } = {\n method: req.method,\n headers,\n };\n\n if (method !== \"GET\" && method !== \"HEAD\") {\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array>;\n init.duplex = \"half\";\n }\n\n return new Request(fullUrl, init);\n}\n\nfunction isEncryptedFarmRequest(req: FarmRequest): boolean {\n return Boolean((req.socket as { encrypted?: boolean } | undefined)?.encrypted);\n}\n\nfunction firstForwardedHeaderValue(value: string | string[] | undefined): string | undefined {\n const first = Array.isArray(value) ? value[0] : value;\n const token = first?.split(\",\", 1)[0]?.trim();\n return token || undefined;\n}\n\nfunction resolveRequestOrigin(proto: \"http\" | \"https\", host: string | undefined, fallback: string) {\n for (const candidate of [host, fallback, \"localhost\"]) {\n if (!candidate) continue;\n if (/[\\s/?#@\\\\]/u.test(candidate)) continue;\n try {\n const url = new URL(`${proto}://${candidate}`);\n if (url.username || url.password || url.pathname !== \"/\" || url.search || url.hash) continue;\n return url.origin;\n } catch {\n // Try the next host instead of turning an untrusted proxy header into a 500.\n }\n }\n return `${proto}://localhost`;\n}\n\nexport async function _runWithCurrentRequest<T>(\n request: Request,\n fn: () => Promise<T> | T,\n): Promise<T> {\n return requestStore.run(request, fn);\n}\n\nexport function getCurrentRequest(): Request {\n const request = requestStore.getStore();\n if (!request) {\n throw new Error(\n \"No current request is available. getCurrentRequest() can only be used during server rendering.\",\n );\n }\n\n return request;\n}\n\n// Some runtimes (StackBlitz WebContainers among them) lose AsyncLocalStorage\n// context across async boundaries mid-render. Callers whose feature can\n// degrade gracefully should use this instead of getCurrentRequest() so a\n// missing store never turns into a 500.\nexport function getCurrentRequestOrNull(): Request | null {\n return requestStore.getStore() ?? null;\n}\n","type CurrentRequestResolver = () => Request | undefined;\n\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\n\ntype GlobalWithCurrentRequestResolver = typeof globalThis & {\n [CURRENT_REQUEST_RESOLVER_KEY]?: CurrentRequestResolver;\n};\n\nfunction getGlobalState(): GlobalWithCurrentRequestResolver {\n return globalThis as GlobalWithCurrentRequestResolver;\n}\n\nexport function _setCurrentRequestResolver(resolver: CurrentRequestResolver | undefined): void {\n getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;\n}\n\nexport function _resolveCurrentRequest(): Request | undefined {\n return getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n","import { _runWithCurrentRequest } from \"../server/request\";\nimport {\n decodeFarmCacheInvalidations,\n encodeFarmCacheInvalidations,\n FARM_CACHE_INVALIDATION_HEADER,\n} from \"../cache-invalidation\";\nimport { isEndpointFailure, type EndpointFailure } from \"./endpoint\";\nimport {\n bufferFarmRequestBody,\n createFarmRequestBodyErrorResponse,\n DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n} from \"../server-http\";\nimport { DEFAULT_FARM_API_BASE_PATH, normalizeFarmAPIBasePath } from \"./config\";\nimport { resolveFarmAPICanonicalPathname } from \"./server-path\";\nimport { parseRouteSchema } from \"./route-schema\";\nimport { omitFarmResponseBody } from \"../response-body\";\n\nexport { registerAPIRouteShape, type APIRouteShapeSource } from \"./route-shape\";\nexport { mergePluginAPIRoutes } from \"./plugin-route-runtime\";\n\nexport {\n matchAPIRoute,\n type APIRouteParams,\n type APIRouteParamValue,\n type APIRouteMatch,\n} from \"./route-pattern\";\nimport { matchAPIRoute, type APIRouteParams, type APIRouteMatch } from \"./route-pattern\";\ninterface APIRouteMethodTable {\n methods: string[];\n endpoints: Record<string, any>;\n}\n\nexport function resolveAPIRouteEndpoint(\n route: APIRouteMethodTable,\n method: string,\n): any | undefined {\n const normalizedMethod = method.toUpperCase();\n return (\n route.endpoints[normalizedMethod] ??\n (normalizedMethod === \"HEAD\" ? route.endpoints.GET : undefined)\n );\n}\n\nexport function getAllowedAPIRouteMethods(route: APIRouteMethodTable): string[] {\n const methods = [...route.methods];\n const getIndex = methods.indexOf(\"GET\");\n if (getIndex >= 0 && !methods.includes(\"HEAD\")) {\n methods.splice(getIndex + 1, 0, \"HEAD\");\n }\n return methods;\n}\n\n/** Match canonical routes through a configurable same-origin public API path. */\nexport function matchAPIRouteAtBasePath<T extends { path: string }>(\n routes: Map<string, T>,\n pathname: string,\n serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): APIRouteMatch<T> | null {\n const directMatch = matchAPIRoute(routes, pathname);\n if (directMatch) return directMatch;\n\n const canonicalPathname = resolveFarmAPICanonicalPathname(pathname, serverBasePath);\n return canonicalPathname === pathname ? null : matchAPIRoute(routes, canonicalPathname);\n}\n\n/** Test whether a pathname belongs to the configured local API surface. */\nexport function isFarmAPIPathname(\n pathname: string,\n serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): boolean {\n const basePath = normalizeFarmAPIBasePath(serverBasePath);\n return basePath !== \"/\" && (pathname === basePath || pathname.startsWith(`${basePath}/`));\n}\n\nexport async function invokeAPIRouteEndpoint(\n endpoint: any,\n request: Request,\n params: APIRouteParams = {},\n bodySizeLimit = DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n): Promise<Response> {\n try {\n request = await bufferFarmRequestBody(request, bodySizeLimit);\n } catch (error) {\n const response = createFarmRequestBodyErrorResponse(error);\n if (response) return response;\n throw error;\n }\n\n const response = await _runWithCurrentRequest(request, () =>\n invokeAPIRouteEndpointInContext(endpoint, request, params),\n );\n\n if (request.method.toUpperCase() !== \"HEAD\") {\n return response;\n }\n\n return omitFarmResponseBody(response);\n}\n\nasync function invokeAPIRouteEndpointInContext(\n endpoint: any,\n request: Request,\n params: APIRouteParams,\n): Promise<Response> {\n const queryContentTypeError = validateQueryContentType(request);\n if (queryContentTypeError) {\n return queryContentTypeError;\n }\n\n // `createEndpoint` brands its parsed-context handler explicitly. Plain route\n // exports always receive the Web Request regardless of their parameter name;\n // inferring a calling convention from `Function#toString()` misclassified\n // valid handlers named `context`, `ctx`, or using destructuring.\n const farmHandler = endpoint.__handler || null;\n\n if (!farmHandler) {\n const result = await endpoint(request, {\n params: Promise.resolve(params),\n });\n return normalizeRouteResponse(result);\n }\n\n const url = new URL(request.url);\n // Repeated keys collect into arrays, the same representation the rest of the\n // framework hands to routes, and the same helper this path already uses for\n // urlencoded and multipart bodies. Spread back onto a normal object so an\n // endpoint without a query schema still receives the object shape it did\n // before; `entriesToObject` has already dropped the prototype-poisoning keys.\n const query: Record<string, string | string[]> = {\n ...searchParamsToObject(url.searchParams),\n };\n\n let body: any = undefined;\n if (request.method.toUpperCase() !== \"GET\" && request.method.toUpperCase() !== \"HEAD\") {\n const parsedBody = await readRequestBody(request);\n if (parsedBody.error) return parsedBody.error;\n body = parsedBody.body;\n }\n\n const headers = Object.fromEntries(request.headers.entries());\n const types = endpoint.__types || {};\n\n const queryValidation = await validateInput(types.query, query, \"Invalid query parameters\");\n if (queryValidation instanceof Response) {\n return queryValidation;\n }\n\n const bodyValidation = await validateInput(types.body, body, \"Invalid request body\");\n if (bodyValidation instanceof Response) {\n return bodyValidation;\n }\n\n const headersValidation = await validateInput(types.headers, headers, \"Invalid request headers\");\n if (headersValidation instanceof Response) {\n return headersValidation;\n }\n\n const paramsValidation = await validateInput(types.params, params, \"Invalid route parameters\");\n if (paramsValidation instanceof Response) return paramsValidation;\n\n const handlerContext = {\n query: queryValidation,\n body: bodyValidation,\n headers: headersValidation,\n request,\n context: {},\n params: paramsValidation,\n };\n let execution: {\n result: unknown;\n context: unknown;\n handlerExecuted: boolean;\n invalidations: readonly string[];\n };\n try {\n execution =\n typeof endpoint.__farmInvoke === \"function\"\n ? await endpoint.__farmInvoke(handlerContext)\n : {\n result: await farmHandler(handlerContext),\n context: handlerContext.context,\n handlerExecuted: true,\n invalidations: [],\n };\n } catch (error) {\n if (isEndpointFailure(error)) {\n return createEndpointFailureResponse(error);\n }\n throw error;\n }\n\n if (execution.handlerExecuted && endpoint.__output && !isWebResponse(execution.result)) {\n try {\n execution.result = await parseRouteSchema(endpoint.__output, execution.result);\n } catch {\n throw new Error(\"API route returned a value that does not match its output schema.\");\n }\n }\n const response = normalizeRouteResponse(execution.result);\n return attachEndpointInvalidations(response, execution.invalidations);\n}\n\nfunction validateQueryContentType(request: Request): Response | null {\n if (request.method.toUpperCase() !== \"QUERY\" || request.headers.has(\"content-type\")) {\n return null;\n }\n\n return new Response(\n JSON.stringify({\n error: \"Invalid QUERY request\",\n message: \"QUERY requests must include a Content-Type header.\",\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n}\n\nexport function normalizeRouteResponse(result: unknown): Response {\n if (isWebResponse(result)) {\n return result;\n }\n\n if (result === undefined) {\n return new Response(null, { status: 204 });\n }\n\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nexport function isWebResponse(value: unknown): value is Response {\n return (\n value instanceof Response ||\n (typeof value === \"object\" &&\n value !== null &&\n \"headers\" in value &&\n \"status\" in value &&\n typeof (value as Response).arrayBuffer === \"function\")\n );\n}\n\nfunction attachEndpointInvalidations(response: Response, keys: readonly string[]): Response {\n const existing = decodeFarmCacheInvalidations(\n response.headers.get(FARM_CACHE_INVALIDATION_HEADER),\n );\n const encoded = encodeFarmCacheInvalidations([...existing, ...keys]);\n if (!encoded) return response;\n\n const headers = new Headers(response.headers);\n headers.set(FARM_CACHE_INVALIDATION_HEADER, encoded);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nexport function createEndpointFailureResponse(failure: EndpointFailure<string, unknown>): Response {\n return new Response(\n JSON.stringify({\n error: {\n code: failure.code,\n message: failure.message,\n data: failure.data,\n },\n }),\n {\n status: failure.status,\n headers: {\n \"cache-control\": \"no-store\",\n \"content-type\": \"application/json\",\n },\n },\n );\n}\n\ninterface RequestBodyParseResult {\n body?: unknown;\n error?: Response;\n}\n\nasync function readRequestBody(request: Request): Promise<RequestBodyParseResult> {\n const contentType = request.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n\n try {\n if (contentType === \"multipart/form-data\") {\n return { body: formDataToObject(await request.clone().formData()) };\n }\n\n const text = await request.clone().text();\n if (!text) return { body: undefined };\n if (contentType === \"application/x-www-form-urlencoded\") {\n return { body: searchParamsToObject(new URLSearchParams(text)) };\n }\n if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n return { body: JSON.parse(text) };\n }\n\n // Preserve the previous permissive behavior for callers that omit the\n // content type but still send JSON.\n return { body: JSON.parse(text) };\n } catch {\n if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n return {\n error: new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n message: \"The request body is not valid JSON.\",\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n ),\n };\n }\n // The body format is unsupported or malformed. Schema validation below\n // will turn the missing value into a typed 400 response when applicable.\n }\n\n return { body: undefined };\n}\n\nfunction formDataToObject(\n formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n return entriesToObject(formData.entries());\n}\n\nfunction searchParamsToObject(searchParams: URLSearchParams): Record<string, string | string[]> {\n return entriesToObject(searchParams.entries());\n}\n\nfunction entriesToObject<TValue>(\n entries: IterableIterator<[string, TValue]>,\n): Record<string, TValue | TValue[]> {\n const output: Record<string, TValue | TValue[]> = Object.create(null);\n for (const [key, value] of entries) {\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n const current = output[key];\n if (current === undefined) {\n output[key] = value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n output[key] = [current, value];\n }\n }\n return output;\n}\n\nasync function validateInput(\n schema: any,\n value: unknown,\n error: string,\n): Promise<unknown | Response> {\n if (!schema) return value;\n try {\n return await parseRouteSchema(schema, value);\n } catch (validationError: any) {\n return Response.json(\n {\n error,\n details: (validationError.issues || validationError.errors || []).map((issue: any) => ({\n path: issue.path,\n message: issue.message,\n code: issue.code,\n })),\n },\n { status: 400 },\n );\n }\n}\n","import { assertBrowserStableRoutePath } from \"./routing/specificity\";\n\ninterface FarmNodeAbortRequest {\n aborted?: boolean;\n once(event: \"aborted\", listener: () => void): unknown;\n off(event: \"aborted\", listener: () => void): unknown;\n}\n\ninterface FarmNodeAbortResponse {\n writableEnded: boolean;\n once(event: \"close\" | \"finish\", listener: () => void): unknown;\n off(event: \"close\" | \"finish\", listener: () => void): unknown;\n}\n\n/** Share disconnect semantics between development and production Node requests. */\nexport function createFarmNodeRequestAbortSignal(\n req: FarmNodeAbortRequest,\n res: FarmNodeAbortResponse,\n): AbortSignal {\n const controller = new AbortController();\n let disposed = false;\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n req.off(\"aborted\", abort);\n res.off(\"close\", abortOnEarlyClose);\n res.off(\"finish\", dispose);\n controller.signal.removeEventListener(\"abort\", dispose);\n };\n const abort = () => controller.abort();\n const abortOnEarlyClose = () => {\n if (!res.writableEnded) abort();\n dispose();\n };\n\n if (req.aborted) {\n controller.abort();\n return controller.signal;\n }\n\n req.once(\"aborted\", abort);\n res.once(\"close\", abortOnEarlyClose);\n res.once(\"finish\", dispose);\n controller.signal.addEventListener(\"abort\", dispose, { once: true });\n return controller.signal;\n}\n\nexport const DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 10_000_000;\nexport const DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 60_000;\nexport const DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 300_000;\nexport const DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5_000;\nexport const DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 30_000;\nconst MAX_FARM_SERVER_TIMEOUT = 2_147_483_647;\n\nexport type FarmServerDuration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport interface FarmServerHealthConfig {\n /** Liveness endpoint. It remains healthy while a production process drains. */\n livenessPath?: string;\n /** Readiness endpoint. It returns 503 until startup completes and while draining. */\n readinessPath?: string;\n}\n\nexport interface ResolvedFarmServerHealthConfig {\n enabled: boolean;\n livenessPath: string;\n readinessPath: string;\n}\n\nexport interface FarmServerConfig {\n /** Maximum request body size for API routes, integrations, workflows, and uploads. */\n bodySizeLimit?: number | string;\n /** Trust proxy-provided client address and request authority headers. Enable only behind a trusted proxy. */\n trustProxy?: boolean;\n /** Maximum time for a Node client to send complete request headers. */\n headersTimeout?: FarmServerDuration;\n /** Maximum time for a Node client to send the complete request. */\n requestTimeout?: FarmServerDuration;\n /** How long an idle Node keep-alive connection remains open after a response. */\n keepAliveTimeout?: FarmServerDuration;\n /** Maximum time the Node adapter drains traffic before forcing shutdown. */\n gracefulShutdownTimeout?: FarmServerDuration;\n /** Production liveness and readiness endpoints. Set to false to disable them. */\n health?: false | FarmServerHealthConfig;\n}\n\nexport interface ResolvedFarmServerConfig {\n bodySizeLimit: number;\n trustProxy: boolean;\n headersTimeout: number;\n requestTimeout: number;\n keepAliveTimeout: number;\n gracefulShutdownTimeout: number;\n health: ResolvedFarmServerHealthConfig;\n}\n\nexport type FarmRequestBodyErrorCode = \"BODY_TOO_LARGE\" | \"INVALID_CONTENT_LENGTH\";\n\n/** Apply the weak entity-tag comparison required by If-None-Match. */\nexport function matchesFarmIfNoneMatch(\n value: string | readonly string[] | null | undefined,\n etag: string,\n): boolean {\n const expected = parseEntityTag(trimOptionalWhitespace(etag));\n if (!expected) return false;\n\n const values = Array.isArray(value) ? value : [value];\n const combined = values\n .filter((header): header is string => typeof header === \"string\")\n .join(\",\");\n const fieldValue = trimOptionalWhitespace(combined);\n if (!fieldValue) return false;\n if (fieldValue === \"*\") return true;\n\n let matched = false;\n let hasEntityTag = false;\n for (const candidate of splitEntityTags(fieldValue)) {\n const token = trimOptionalWhitespace(candidate);\n if (!token) continue;\n\n const parsed = parseEntityTag(token);\n if (!parsed) return false;\n hasEntityTag = true;\n if (parsed === expected) matched = true;\n }\n\n return hasEntityTag && matched;\n}\n\nfunction trimOptionalWhitespace(value: string): string {\n return value.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n}\n\nfunction parseEntityTag(value: string): string | null {\n const opaqueTag = value.startsWith(\"W/\") ? value.slice(2) : value;\n if (opaqueTag.length < 2 || opaqueTag[0] !== '\"' || opaqueTag.at(-1) !== '\"') return null;\n\n for (let index = 1; index < opaqueTag.length - 1; index++) {\n const code = opaqueTag.charCodeAt(index);\n if (code === 0x21 || (code >= 0x23 && code <= 0x7e) || code >= 0x80) continue;\n return null;\n }\n\n return opaqueTag;\n}\n\nfunction splitEntityTags(value: string): string[] {\n const tags: string[] = [];\n let start = 0;\n let quoted = false;\n\n for (let index = 0; index < value.length; index++) {\n const character = value[index];\n if (character === '\"') {\n quoted = !quoted;\n } else if (character === \",\" && !quoted) {\n tags.push(value.slice(start, index));\n start = index + 1;\n }\n }\n\n tags.push(value.slice(start));\n return tags;\n}\n\nexport class FarmRequestBodyError extends Error {\n readonly code: FarmRequestBodyErrorCode;\n readonly status: number;\n\n constructor(code: FarmRequestBodyErrorCode, status: number, message: string) {\n super(message);\n this.name = \"FarmRequestBodyError\";\n this.code = code;\n this.status = status;\n }\n}\n\nexport function resolveFarmServerConfig(\n config: FarmServerConfig | ResolvedFarmServerConfig | undefined,\n): ResolvedFarmServerConfig {\n const headersTimeout = parseFarmServerDuration(\n config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,\n \"server.headersTimeout\",\n );\n const requestTimeout = parseFarmServerDuration(\n config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,\n \"server.requestTimeout\",\n );\n if (headersTimeout > requestTimeout) {\n throw new TypeError(\"server.headersTimeout must not exceed server.requestTimeout\");\n }\n\n return Object.freeze({\n bodySizeLimit: parseBodySizeLimit(\n config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n \"server.bodySizeLimit\",\n ),\n trustProxy: config?.trustProxy === true,\n headersTimeout,\n requestTimeout,\n keepAliveTimeout: parseFarmServerDuration(\n config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,\n \"server.keepAliveTimeout\",\n ),\n gracefulShutdownTimeout: parseFarmServerDuration(\n config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,\n \"server.gracefulShutdownTimeout\",\n ),\n health: resolveFarmServerHealthConfig(config?.health),\n });\n}\n\nexport function parseFarmServerDuration(\n value: FarmServerDuration,\n optionName = \"duration\",\n): number {\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`${optionName} must be a positive safe integer`);\n }\n if (value > MAX_FARM_SERVER_TIMEOUT) {\n throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n }\n return value;\n }\n\n const match = value\n .trim()\n .toLowerCase()\n .match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)$/);\n if (!match) {\n throw new TypeError(`${optionName} must be milliseconds or a duration such as \"30s\" or \"2m\"`);\n }\n\n const amount = Number(match[1]);\n const unit = match[2];\n const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n const milliseconds = Math.floor(amount * multiplier);\n if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {\n throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n }\n if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {\n throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n }\n return milliseconds;\n}\n\nfunction resolveFarmServerHealthConfig(\n config: false | FarmServerHealthConfig | ResolvedFarmServerHealthConfig | undefined,\n): ResolvedFarmServerHealthConfig {\n if (config === false || (config && \"enabled\" in config && config.enabled === false)) {\n return Object.freeze({\n enabled: false,\n livenessPath: \"/_farm/health/live\",\n readinessPath: \"/_farm/health/ready\",\n });\n }\n\n const livenessPath = normalizeHealthPath(\n config?.livenessPath ?? \"/_farm/health/live\",\n \"server.health.livenessPath\",\n );\n const readinessPath = normalizeHealthPath(\n config?.readinessPath ?? \"/_farm/health/ready\",\n \"server.health.readinessPath\",\n );\n if (livenessPath === readinessPath) {\n throw new TypeError(\"server.health livenessPath and readinessPath must be different\");\n }\n\n return Object.freeze({ enabled: true, livenessPath, readinessPath });\n}\n\nfunction normalizeHealthPath(value: string, optionName: string): string {\n const path = value.trim();\n if (!path.startsWith(\"/\") || path.includes(\"?\") || path.includes(\"#\") || path.includes(\"*\")) {\n throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);\n }\n const normalized = path.length > 1 ? path.replace(/\\/+$/, \"\") || \"/\" : path;\n assertBrowserStableRoutePath(normalized);\n return normalized;\n}\n\nexport function parseBodySizeLimit(value: number | string, optionName = \"bodySizeLimit\"): number {\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`${optionName} must be a positive safe integer`);\n }\n return value;\n }\n\n const match = value\n .trim()\n .toLowerCase()\n .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)?$/);\n if (!match) {\n throw new TypeError(`${optionName} must be bytes or a size string such as \"500kb\" or \"10mb\"`);\n }\n\n const amount = Number(match[1]);\n const unit = match[2] ?? \"b\";\n const multiplier: Record<string, number> = {\n b: 1,\n kb: 1_000,\n mb: 1_000_000,\n gb: 1_000_000_000,\n kib: 1_024,\n mib: 1_048_576,\n gib: 1_073_741_824,\n };\n const bytes = Math.floor(amount * multiplier[unit]);\n\n if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n }\n\n return bytes;\n}\n\nexport async function bufferFarmRequestBody(request: Request, limit: number): Promise<Request> {\n if (request.method === \"GET\" || request.method === \"HEAD\" || request.body === null) {\n return request;\n }\n\n const bytes = await readFarmRequestBody(request, limit);\n const body = new Uint8Array(bytes.byteLength);\n body.set(bytes);\n return new Request(request, {\n // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.\n body: body.buffer,\n });\n}\n\nexport async function readFarmRequestBody(request: Request, limit: number): Promise<Uint8Array> {\n try {\n validateContentLength(request.headers.get(\"content-length\"), limit);\n } catch (error) {\n // A cloned Request is a tee branch: its cancellation may wait for the\n // untouched branch. Rejection must not wait for producer-owned cleanup.\n void request.body?.cancel(error).catch(() => {});\n throw error;\n }\n throwIfAborted(request.signal);\n if (!request.body) return new Uint8Array();\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n const cancelBodyRead = () => {\n void reader.cancel(request.signal.reason).catch(() => {});\n };\n request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n try {\n while (true) {\n throwIfAborted(request.signal);\n const { done, value } = await reader.read();\n // Cancellation resolves a pending read as EOF, not necessarily an error.\n throwIfAborted(request.signal);\n if (done) break;\n if (!value) continue;\n\n total += value.byteLength;\n if (total > limit) {\n const error = new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n void reader.cancel(error).catch(() => {});\n throw error;\n }\n chunks.push(value);\n }\n } catch (error) {\n if (request.signal.aborted) throwIfAborted(request.signal);\n throw error;\n } finally {\n request.signal.removeEventListener(\"abort\", cancelBodyRead);\n reader.releaseLock();\n }\n\n const body = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return body;\n}\n\nexport async function readNodeRequestBody(\n request: {\n headers: Record<string, string | string[] | undefined>;\n on(event: \"data\", listener: (chunk: unknown) => void): unknown;\n on(event: \"end\", listener: () => void): unknown;\n on(event: \"error\", listener: (error: Error) => void): unknown;\n removeListener?(event: string, listener: (...args: any[]) => void): unknown;\n resume?(): unknown;\n },\n limit: number,\n): Promise<Buffer> {\n const rawContentLength = request.headers[\"content-length\"];\n const contentLength = Array.isArray(rawContentLength) ? rawContentLength[0] : rawContentLength;\n try {\n validateContentLength(contentLength, limit);\n } catch (error) {\n request.resume?.();\n throw error;\n }\n\n return await new Promise<Buffer>((resolve, reject) => {\n const chunks: Buffer[] = [];\n let total = 0;\n let settled = false;\n\n const cleanup = () => {\n request.removeListener?.(\"data\", onData);\n request.removeListener?.(\"end\", onEnd);\n request.removeListener?.(\"error\", onError);\n };\n const rejectOnce = (error: Error) => {\n if (settled) return;\n settled = true;\n cleanup();\n request.resume?.();\n reject(error);\n };\n const onData = (chunk: unknown) => {\n const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as any);\n total += bytes.byteLength;\n if (total > limit) {\n rejectOnce(new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\"));\n return;\n }\n chunks.push(bytes);\n };\n const onEnd = () => {\n if (settled) return;\n settled = true;\n cleanup();\n resolve(Buffer.concat(chunks, total));\n };\n const onError = (error: Error) => rejectOnce(error);\n\n request.on(\"data\", onData);\n request.on(\"end\", onEnd);\n request.on(\"error\", onError);\n });\n}\n\nexport function createFarmRequestBodyErrorResponse(error: unknown): Response | null {\n if (!(error instanceof FarmRequestBodyError)) return null;\n\n return new Response(error.status === 413 ? \"Payload Too Large\" : \"Bad Request\", {\n status: error.status,\n headers: {\n \"cache-control\": \"no-store\",\n \"content-type\": \"text/plain; charset=utf-8\",\n \"x-content-type-options\": \"nosniff\",\n },\n });\n}\n\nfunction validateContentLength(value: string | null | undefined, limit: number): void {\n const contentLength = value?.trim();\n if (!contentLength) return;\n if (!/^\\d+$/.test(contentLength)) {\n throw new FarmRequestBodyError(\"INVALID_CONTENT_LENGTH\", 400, \"Invalid content-length header\");\n }\n if (Number(contentLength) > limit) {\n throw new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return;\n if (signal.reason !== undefined) throw signal.reason;\n throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type { ResolvedFarmEnv } from \"../env\";\n\nexport const DEFAULT_FARM_API_BASE_PATH = \"/api\";\n\nexport interface FarmAPIConfigResolverContext {\n root: string;\n mode: \"development\" | \"production\";\n env: ResolvedFarmEnv;\n}\n\nexport type FarmAPIConfigValue =\n | string\n | undefined\n | ((context: FarmAPIConfigResolverContext) => string | undefined | Promise<string | undefined>);\n\nexport interface FarmAPIConfig {\n /**\n * Public API root. An origin-only URL is joined with `basePath`; a URL that\n * already has a path is used as-is. May be resolved from deployment context.\n */\n baseURL?: FarmAPIConfigValue;\n /** Public API path and same-origin server mount used when `baseURL` has no path. @default \"/api\" */\n basePath?: FarmAPIConfigValue;\n}\n\nexport interface ResolvedFarmAPIConfig {\n /** Fully resolved public API root, either absolute or root-relative. */\n baseURL: string;\n /** Effective pathname of `baseURL`. */\n basePath: string;\n}\n\ndeclare const __FARM_API_BASE_URL__: string | undefined;\n\nexport async function resolveFarmAPIConfig(\n config: FarmAPIConfig | undefined,\n context: FarmAPIConfigResolverContext,\n): Promise<ResolvedFarmAPIConfig> {\n const configuredBasePath = await resolveConfigValue(config?.basePath, context, \"api.basePath\");\n const basePath = normalizeFarmAPIBasePath(configuredBasePath ?? DEFAULT_FARM_API_BASE_PATH);\n const configuredBaseURL = await resolveConfigValue(config?.baseURL, context, \"api.baseURL\");\n\n return normalizeFarmAPIConfig({ baseURL: configuredBaseURL, basePath });\n}\n\n/** Normalize already-resolved API strings. */\nexport function normalizeFarmAPIConfig(\n config: { baseURL?: string; basePath?: string } | undefined,\n): ResolvedFarmAPIConfig {\n const basePath = normalizeFarmAPIBasePath(config?.basePath ?? DEFAULT_FARM_API_BASE_PATH);\n const baseURL = config?.baseURL?.trim();\n\n if (!baseURL) {\n return { baseURL: basePath, basePath };\n }\n\n if (baseURL.startsWith(\"//\")) {\n throw new Error(\n 'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\", not a network-path reference.',\n );\n }\n\n if (baseURL.startsWith(\"/\")) {\n const url = parseRootRelativeBaseURL(baseURL);\n if (url.pathname !== \"/\") {\n const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n return { baseURL: effectivePath, basePath: effectivePath };\n }\n return { baseURL: basePath, basePath };\n }\n\n let url: URL;\n try {\n url = new URL(baseURL);\n } catch {\n throw new Error(\n 'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\".',\n );\n }\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw new Error(\"Farm api.baseURL must use http or https.\");\n }\n if (url.search || url.hash) {\n throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n }\n\n if (url.pathname !== \"/\") {\n const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n return {\n baseURL: `${url.origin}${effectivePath}`,\n basePath: effectivePath,\n };\n }\n\n return {\n baseURL: basePath === \"/\" ? url.origin : `${url.origin}${basePath}`,\n basePath,\n };\n}\n\nexport function normalizeFarmAPIBasePath(value: string): string {\n const hasUnstableCharacters = (candidate: string) =>\n candidate.includes(\"\\\\\") ||\n Array.from(candidate).some((character) => {\n const code = character.charCodeAt(0);\n return code <= 31 || (code >= 127 && code <= 159);\n });\n\n if (hasUnstableCharacters(value)) {\n throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n }\n\n const path = value.trim();\n if (!path) {\n throw new Error(\"Farm api.basePath cannot be empty.\");\n }\n if (path.includes(\"?\") || path.includes(\"#\")) {\n throw new Error(\"Farm api.basePath cannot contain a query string or hash.\");\n }\n if (path.startsWith(\"//\")) {\n throw new Error('Farm api.basePath must be a pathname such as \"/api\", not a URL.');\n }\n for (const segment of path.split(\"/\")) {\n let decoded = segment;\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n // A malformed escape remains literal in a URL pathname. It cannot be a\n // dot segment, so leave the ordinary URL parser to preserve it.\n }\n if (hasUnstableCharacters(decoded)) {\n throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n }\n if (decoded.includes(\"/\")) {\n throw new Error(\"Farm api.basePath cannot contain percent-encoded path separators.\");\n }\n if (decoded === \".\" || decoded === \"..\") {\n throw new Error('Farm api.basePath cannot contain \".\" or \"..\" path segments.');\n }\n }\n\n const normalized = `/${path.replace(/^\\/+|\\/+$/g, \"\")}`;\n return normalized === \"/\" ? \"/\" : normalized;\n}\n\n/** Read the API root embedded by Farm's Vite build. */\nexport function getFarmAPIBaseURL(): string {\n if (typeof __FARM_API_BASE_URL__ !== \"undefined\" && __FARM_API_BASE_URL__) {\n return __FARM_API_BASE_URL__;\n }\n return DEFAULT_FARM_API_BASE_PATH;\n}\n\n/** Resolve a canonical Farm route such as `/api/users` against an API root. */\nexport function resolveFarmAPIRequestURL(\n routePath: string,\n baseURL = getFarmAPIBaseURL(),\n fallbackOrigin = getDefaultOrigin(),\n): URL {\n const base = new URL(baseURL, fallbackOrigin);\n if (base.pathname === \"/\") {\n return new URL(routePath, base);\n }\n\n const route = new URL(routePath, fallbackOrigin);\n const suffix = stripCanonicalAPIBasePath(route.pathname);\n const joinedPath = joinURLPath(base.pathname, suffix);\n base.pathname = joinedPath;\n base.search = route.search;\n base.hash = route.hash;\n return base;\n}\n\nasync function resolveConfigValue(\n value: FarmAPIConfigValue,\n context: FarmAPIConfigResolverContext,\n name: string,\n): Promise<string | undefined> {\n const resolved = typeof value === \"function\" ? await value(context) : value;\n if (resolved === undefined) return undefined;\n if (typeof resolved !== \"string\") {\n throw new Error(`Farm ${name} must resolve to a string or undefined.`);\n }\n if (!resolved.trim()) {\n throw new Error(`Farm ${name} cannot be empty.`);\n }\n return resolved;\n}\n\nfunction parseRootRelativeBaseURL(value: string): URL {\n const url = new URL(value, \"http://farm.local\");\n if (url.search || url.hash) {\n throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n }\n return url;\n}\n\nfunction stripCanonicalAPIBasePath(pathname: string): string {\n if (pathname === DEFAULT_FARM_API_BASE_PATH) return \"\";\n if (pathname.startsWith(`${DEFAULT_FARM_API_BASE_PATH}/`)) {\n return pathname.slice(DEFAULT_FARM_API_BASE_PATH.length + 1);\n }\n return pathname.replace(/^\\/+/, \"\");\n}\n\nfunction joinURLPath(basePath: string, suffix: string): string {\n const normalizedBase = basePath === \"/\" ? \"\" : basePath.replace(/\\/+$/, \"\");\n const normalizedSuffix = suffix.replace(/^\\/+/, \"\");\n if (!normalizedSuffix) return normalizedBase || \"/\";\n return `${normalizedBase}/${normalizedSuffix}`;\n}\n\nfunction getDefaultOrigin(): string {\n return typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\";\n}\n","import {\n DEFAULT_FARM_API_BASE_PATH,\n normalizeFarmAPIBasePath,\n resolveFarmAPIRequestURL,\n type ResolvedFarmAPIConfig,\n} from \"./config\";\n\n/** Return the same-origin path served by this Farm application. */\nexport function resolveFarmAPIServerBasePath(config: ResolvedFarmAPIConfig): string {\n // Absolute API URLs belong to another origin and must not move local routes.\n return config.baseURL.startsWith(\"/\") ? config.basePath : DEFAULT_FARM_API_BASE_PATH;\n}\n\n/** Translate a public local API pathname back to Farm's canonical `/api` route table. */\nexport function resolveFarmAPICanonicalPathname(\n pathname: string,\n serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): string {\n const basePath = normalizeFarmAPIBasePath(serverBasePath);\n if (basePath === DEFAULT_FARM_API_BASE_PATH) return pathname;\n\n if (basePath === \"/\") {\n return pathname === \"/\"\n ? DEFAULT_FARM_API_BASE_PATH\n : `${DEFAULT_FARM_API_BASE_PATH}${pathname.startsWith(\"/\") ? pathname : `/${pathname}`}`;\n }\n\n if (pathname === basePath) return DEFAULT_FARM_API_BASE_PATH;\n if (pathname.startsWith(`${basePath}/`)) {\n return `${DEFAULT_FARM_API_BASE_PATH}${pathname.slice(basePath.length)}`;\n }\n return pathname;\n}\n\n/** Resolve a canonical `/api` route to the path served by this application. */\nexport function resolveFarmAPIServerRoutePath(\n routePath: string,\n serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): string {\n return resolveFarmAPIRequestURL(routePath, serverBasePath).pathname;\n}\n","/** Server-only schema contract shared by declarative routes and the API runtime. */\nexport interface RouteSchema {\n readonly _input?: unknown;\n readonly _output?: unknown;\n parse?: (value: unknown) => unknown;\n parseAsync?: (value: unknown) => Promise<unknown>;\n readonly \"~standard\"?: {\n readonly types?: { input: unknown; output: unknown };\n validate(value: unknown): unknown;\n };\n}\n\nexport type RouteSchemaInput<T> = T extends { _input: infer I }\n ? I\n : T extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : unknown;\n\nexport type RouteSchemaOutput<T> = T extends { _output: infer O }\n ? O\n : T extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : T extends { parse: (...args: any[]) => infer O }\n ? Awaited<O>\n : unknown;\n\nexport async function parseRouteSchema(schema: RouteSchema, value: unknown): Promise<unknown> {\n if (schema[\"~standard\"]) {\n const result = (await schema[\"~standard\"].validate(value)) as {\n value?: unknown;\n issues?: readonly unknown[];\n };\n if (result.issues)\n throw Object.assign(new Error(\"Validation failed\"), { issues: result.issues });\n return result.value;\n }\n if (schema.parseAsync) return schema.parseAsync(value);\n if (schema.parse) return schema.parse(value);\n throw new TypeError(\"Route validators must implement Standard Schema or parse().\");\n}\n","/** @internal */\nexport function omitFarmResponseBody(response: Response): Response {\n if (response.body) {\n void response.body.cancel().catch(() => undefined);\n }\n\n return new Response(null, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n","import { compareRouteSpecificity, type RouteSegmentSpecificity } from \"../routing/specificity\";\n\nexport type APIRouteParamValue = string | string[];\nexport type APIRouteParams = Record<string, APIRouteParamValue>;\n\nexport interface APIRouteMatch<T extends { path: string }> {\n route: T;\n params: APIRouteParams;\n}\n\nexport function matchAPIRoute<T extends { path: string }>(\n routes: Map<string, T>,\n pathname: string,\n): APIRouteMatch<T> | null {\n const exactRoute = routes.get(pathname);\n if (exactRoute) {\n return { route: exactRoute, params: {} };\n }\n\n const normalizedPathname = normalizePathname(pathname);\n if (normalizedPathname !== pathname) {\n const normalizedRoute = routes.get(normalizedPathname);\n if (normalizedRoute) {\n return { route: normalizedRoute, params: {} };\n }\n }\n\n let bestMatch: APIRouteMatch<T> | null = null;\n let bestSpecificity: RouteSegmentSpecificity[] | null = null;\n\n for (const route of routes.values()) {\n const params = matchRoutePath(route.path, pathname);\n if (!params) continue;\n\n const specificity = getAPIRouteSpecificity(route.path);\n if (bestSpecificity === null || compareRouteSpecificity(specificity, bestSpecificity) < 0) {\n bestMatch = { route, params };\n bestSpecificity = specificity;\n }\n }\n\n return bestMatch;\n}\n\nfunction matchRoutePath(routePath: string, pathname: string): APIRouteParams | null {\n const routeSegments = getPathSegments(routePath);\n const pathnameSegments = getPathSegments(pathname);\n const params: APIRouteParams = {};\n let pathIndex = 0;\n\n for (const routeSegment of routeSegments) {\n const dynamicSegment = parseDynamicSegment(routeSegment);\n\n if (dynamicSegment?.catchAll) {\n const remainingSegments = pathnameSegments.slice(pathIndex).map(decodePathSegment);\n if (remainingSegments.length === 0 && !dynamicSegment.optional) {\n return null;\n }\n if (remainingSegments.length > 0) {\n params[dynamicSegment.name] = remainingSegments;\n }\n pathIndex = pathnameSegments.length;\n continue;\n }\n\n const pathnameSegment = pathnameSegments[pathIndex];\n if (pathnameSegment === undefined) {\n return null;\n }\n\n if (dynamicSegment) {\n params[dynamicSegment.name] = decodePathSegment(pathnameSegment);\n pathIndex++;\n continue;\n }\n\n if (decodePathSegment(routeSegment) !== decodePathSegment(pathnameSegment)) {\n return null;\n }\n\n pathIndex++;\n }\n\n return pathIndex === pathnameSegments.length ? params : null;\n}\n\nfunction getPathSegments(pathname: string): string[] {\n return normalizePathname(pathname)\n .split(\"/\")\n .filter((segment) => segment.length > 0);\n}\n\nfunction getAPIRouteSpecificity(routePath: string): RouteSegmentSpecificity[] {\n return getPathSegments(routePath).map((segment) => {\n const dynamic = parseDynamicSegment(segment);\n if (!dynamic) return \"static\";\n if (!dynamic.catchAll) return \"dynamic\";\n return dynamic.optional ? \"optional-catch-all\" : \"catch-all\";\n });\n}\n\nfunction normalizePathname(pathname: string): string {\n if (pathname.length > 1 && pathname.endsWith(\"/\")) {\n return pathname.replace(/\\/+$/, \"\");\n }\n\n return pathname;\n}\n\nexport function parseDynamicSegment(\n segment: string,\n): { name: string; catchAll: boolean; optional: boolean } | null {\n const optionalCatchAll = segment.match(/^\\[\\[\\.\\.\\.(.+)\\]\\]$/);\n if (optionalCatchAll?.[1]) {\n return { name: optionalCatchAll[1], catchAll: true, optional: true };\n }\n\n const catchAll = segment.match(/^\\[\\.\\.\\.(.+)\\]$/);\n if (catchAll?.[1]) {\n return { name: catchAll[1], catchAll: true, optional: false };\n }\n\n const dynamic = segment.match(/^\\[(.+)\\]$/);\n if (dynamic?.[1]) {\n return { name: dynamic[1], catchAll: false, optional: false };\n }\n\n return null;\n}\n\nfunction decodePathSegment(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n","export function isFarmAPIRouteFileName(fileName: string): boolean {\n return /^route\\.(?:ts|tsx|js|jsx)$/.test(fileName);\n}\n","/** Instance defaults, resolved once per call before cache lookup or dispatch. */\nexport type ClientHeaders =\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n\n/** Snapshot synchronous defaults immediately; keep async resolvers local to the call. */\nexport function resolveClientHeaders(source?: ClientHeaders): Headers | Promise<Headers> {\n const value = typeof source === \"function\" ? source() : source;\n if (value && typeof (value as Promise<Record<string, string>>).then === \"function\") {\n return Promise.resolve(value).then((headers) => new Headers(headers));\n }\n return new Headers(value as Record<string, string> | undefined);\n}\n","/** One call budget, shared by header resolution, dispatch, decoding, and retry waits. */\nexport function createClientCancellation(\n signal?: AbortSignal,\n timeoutMs = 0,\n parent?: AbortSignal,\n) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let invalid: Error | undefined;\n let timeoutReason: DOMException | undefined;\n const signals = [signal, parent].filter((value): value is AbortSignal => !!value);\n if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) {\n invalid = new RangeError(\n \"timeoutMs must be an integer between 0 and 2147483647 (0 disables the deadline).\",\n );\n } else if (timeoutMs > 0) {\n const controller = new AbortController();\n signals.push(controller.signal);\n timer = setTimeout(() => {\n timeoutReason = new DOMException(\"Client request timed out\", \"TimeoutError\");\n controller.abort(timeoutReason);\n }, timeoutMs);\n }\n const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0];\n let active = 0;\n let closed = false;\n const cleanup = () => {\n if (closed && active === 0 && timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n const check = () => {\n if (invalid) throw invalid;\n combined?.throwIfAborted();\n };\n return {\n signal: combined,\n get timedOut() {\n return timeoutReason !== undefined && combined?.reason === timeoutReason;\n },\n check,\n hold() {\n active++;\n return () => {\n active--;\n cleanup();\n };\n },\n // A race also bounds cooperative local dispatch and custom HTTP implementations.\n // Late completion is consumed, but cannot turn a cancelled result into success.\n async run<T>(work: () => T | PromiseLike<T>): Promise<T> {\n check();\n active++;\n let abort: (() => void) | undefined;\n try {\n if (!combined) return await work();\n return await new Promise<T>((resolve, reject) => {\n abort = () => reject(combined.reason);\n combined.addEventListener(\"abort\", abort, { once: true });\n Promise.resolve()\n .then(() => {\n check();\n return work();\n })\n .then(resolve, reject);\n });\n } finally {\n if (abort) combined?.removeEventListener(\"abort\", abort);\n active--;\n cleanup();\n }\n },\n async delay(ms: number) {\n let retryTimer: ReturnType<typeof setTimeout> | undefined;\n try {\n await this.run(\n () =>\n new Promise<void>((resolve) => {\n retryTimer = setTimeout(resolve, ms);\n }),\n );\n } finally {\n if (retryTimer !== undefined) clearTimeout(retryTimer);\n }\n },\n dispose() {\n closed = true;\n cleanup();\n },\n };\n}\n","/** Metadata shared by app-route and integration execution attempts. */\nexport type ClientRequestEvent = {\n requestId: string;\n method: string;\n path: string;\n attempt: number;\n timestamp: number;\n};\n\nexport type ClientResponseEvent<TData = unknown> = ClientRequestEvent & {\n response?: Response;\n data?: TData;\n error?: Error;\n ok?: boolean;\n status?: number;\n};\n\n/** Observers compose with per-call hooks; return values never replace the result. */\nexport type ClientLifecycleHooks<TData = unknown> = {\n onRequest?: (event: ClientRequestEvent) => void;\n onResponse?: (\n data: TData | undefined,\n error: Error | null,\n event: ClientResponseEvent<TData>,\n ) => void;\n onError?: (error: Error) => void;\n};\n\nexport function notifyClientObserver(\n observer: ((...args: any[]) => unknown) | undefined,\n args: unknown[],\n label = \"Client lifecycle\",\n): void {\n if (!observer) return;\n const report = (error: unknown) => {\n const reportError = (\n globalThis as typeof globalThis & { reportError?: (error: unknown) => void }\n ).reportError;\n if (typeof reportError === \"function\") {\n try {\n reportError.call(globalThis, error);\n return;\n } catch {\n /* Try the console fallback. */\n }\n }\n try {\n console.error(`[Farm.js] ${label} callback failed:`, error);\n } catch {\n /* Reporting must not affect a call. */\n }\n };\n try {\n const result = observer(...args);\n if (result && typeof (result as PromiseLike<unknown>).then === \"function\")\n void Promise.resolve(result).catch(report);\n } catch (error) {\n report(error);\n }\n}\n","import type {\n FarmIntegrationAPI,\n FarmIntegrationAPIBodyFormat,\n FarmIntegrationAPIOperation,\n} from \"./integration-api\";\nimport type { FarmIntegration as FarmIntegrationDefinition } from \"./integrations\";\nimport { resolveFarmAPIRequestURL } from \"./api/config\";\nimport { resolveClientHeaders, type ClientHeaders } from \"./client-headers\";\nimport { createClientCancellation } from \"./client-cancellation\";\nimport {\n notifyClientObserver,\n type ClientLifecycleHooks,\n type ClientRequestEvent,\n type ClientResponseEvent,\n} from \"./client-observers\";\n\n/**\n * Small per-call integration metadata. When sent from a browser, values are\n * client-controlled and should be validated before authorization decisions.\n */\nexport type IntegrationClientData = Record<string, unknown>;\n\nexport type IntegrationClientOptions = ClientLifecycleHooks & {\n baseURL?: string;\n headers?: ClientHeaders;\n credentials?: RequestCredentials;\n /** Whole-call deadline in milliseconds; 0 disables it. */\n timeoutMs?: number;\n /** HTTP transport, including server fallback; never replaces local dispatch. */\n fetch?: typeof globalThis.fetch;\n data?: IntegrationClientData;\n isServer?: false | undefined;\n};\n\ntype IntegrationRequestOptionsBase<TData = unknown> = ClientLifecycleHooks<TData> & {\n headers?: Record<string, string>;\n signal?: AbortSignal;\n timeoutMs?: number;\n credentials?: RequestCredentials;\n data?: IntegrationClientData;\n};\n\nexport type IntegrationClientRequestOptions<TData = unknown> = IntegrationRequestOptionsBase<TData>;\n\nexport type IntegrationServerRequestLike =\n | Request\n | {\n url?: string;\n headers?: HeadersInit;\n };\n\nexport type IntegrationServerClientOptions = Omit<IntegrationClientOptions, \"isServer\"> & {\n isServer: true;\n request?: IntegrationServerRequestLike;\n forwardHeaders?: boolean | readonly string[];\n};\n\nexport type IntegrationServerClientRequestOptions<TData = unknown> =\n IntegrationRequestOptionsBase<TData> & {\n baseURL?: string;\n request?: IntegrationServerRequestLike;\n forwardHeaders?: boolean | readonly string[];\n };\n\nexport class IntegrationClientError<TData = unknown> extends Error {\n readonly status: number;\n readonly response: Response;\n readonly data: TData | undefined;\n\n constructor(message: string, response: Response, data?: TData) {\n super(message);\n this.name = \"IntegrationClientError\";\n this.status = response.status;\n this.response = response;\n this.data = data;\n }\n}\n\nexport type IntegrationOperationResult<\n TData = unknown,\n TError = IntegrationClientError<unknown> | Error,\n> = {\n data: TData | null;\n error: TError | null;\n};\n\ntype ExtractOperationBody<T> = T extends {\n __types?: { body: infer TBody };\n}\n ? TBody\n : never;\n\ntype ExtractOperationQuery<T> = T extends {\n __types?: { query: infer TQuery };\n}\n ? TQuery\n : never;\n\ntype ExtractOperationResponse<T> = T extends {\n __types?: { response: infer TResponse };\n}\n ? TResponse\n : unknown;\n\nexport type InferIntegrationOperationBody<T> = ExtractOperationBody<T>;\nexport type InferIntegrationOperationQuery<T> = ExtractOperationQuery<T>;\nexport type InferIntegrationOperationResponse<T> = ExtractOperationResponse<T>;\n\ntype IsNever<T> = [T] extends [never] ? true : false;\n\ntype OperationInput<T> =\n IsNever<ExtractOperationBody<T>> extends true\n ? IsNever<ExtractOperationQuery<T>> extends true\n ? {}\n : { query?: ExtractOperationQuery<T> }\n : IsNever<ExtractOperationQuery<T>> extends true\n ? { body: ExtractOperationBody<T> }\n : { body: ExtractOperationBody<T>; query?: ExtractOperationQuery<T> };\n\ntype ClientOperation<T> = (\n options?: OperationInput<T>,\n requestOptions?: IntegrationClientRequestOptions<ExtractOperationResponse<T>>,\n) => Promise<IntegrationOperationResult<ExtractOperationResponse<T>>>;\n\ntype ServerOperation<T> = (\n options?: OperationInput<T>,\n requestOptions?: IntegrationServerClientRequestOptions<ExtractOperationResponse<T>>,\n) => Promise<IntegrationOperationResult<ExtractOperationResponse<T>>>;\n\ntype IsUnion<T, U = T> = T extends any ? ([U] extends [T] ? false : true) : never;\n\ntype SingleKey<T> = [T] extends [never] ? never : IsUnion<T> extends true ? never : T;\n\ntype ExtractAPIFromSource<TSource> = TSource extends { api?: infer TAPI }\n ? NonNullable<TAPI> extends FarmIntegrationAPI\n ? NonNullable<TAPI>\n : never\n : TSource extends FarmIntegrationAPI\n ? TSource\n : never;\n\ntype SourceKeysWithAPI<TSources extends Record<string, any>> = {\n [K in keyof TSources]: [ExtractAPIFromSource<TSources[K]>] extends [never] ? never : K;\n}[keyof TSources];\n\ntype IsServerRegisteredOperation<T> = T extends { isServer: true } ? true : false;\n\ntype ClientOperationKeys<TAPI> = {\n [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n ? IsServerRegisteredOperation<TAPI[K]> extends true\n ? never\n : K\n : never;\n}[keyof TAPI];\n\ntype ClientNamespaceShape<TAPI> = {\n [K in keyof TAPI as TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n ? IsServerRegisteredOperation<TAPI[K]> extends true\n ? never\n : K\n : K]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any, any>\n ? ClientOperation<TAPI[K]>\n : TAPI[K] extends Record<string, any>\n ? IntegrationAPIToClient<TAPI[K]>\n : never;\n};\n\ntype SingleClientOperationKey<TAPI> =\n Exclude<keyof TAPI, ClientOperationKeys<TAPI>> extends never\n ? SingleKey<ClientOperationKeys<TAPI>>\n : never;\n\ntype IntegrationAPIToClient<TAPI> =\n TAPI extends FarmIntegrationAPIOperation<any, any, any, any>\n ? ClientOperation<TAPI>\n : TAPI extends Record<string, any>\n ? [SingleClientOperationKey<TAPI>] extends [never]\n ? ClientNamespaceShape<TAPI>\n : SingleClientOperationKey<TAPI> extends keyof TAPI\n ? ClientOperation<TAPI[SingleClientOperationKey<TAPI>]> & ClientNamespaceShape<TAPI>\n : ClientNamespaceShape<TAPI>\n : never;\n\nexport type IntegrationClient<TSources extends Record<string, any>> = {\n [K in SourceKeysWithAPI<TSources>]: IntegrationAPIToClient<ExtractAPIFromSource<TSources[K]>>;\n};\n\nexport type IntegrationClientRoot<TSources extends Record<string, any>> = {\n integrations: IntegrationClient<TSources>;\n};\n\ntype ServerOperationKeys<TAPI> = {\n [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any> ? K : never;\n}[keyof TAPI];\n\ntype ServerNamespaceShape<TAPI> = {\n [K in keyof TAPI]: TAPI[K] extends FarmIntegrationAPIOperation<any, any, any>\n ? ServerOperation<TAPI[K]>\n : TAPI[K] extends Record<string, any>\n ? IntegrationAPIToServerClient<TAPI[K]>\n : never;\n};\n\ntype SingleServerOperationKey<TAPI> =\n Exclude<keyof TAPI, ServerOperationKeys<TAPI>> extends never\n ? SingleKey<ServerOperationKeys<TAPI>>\n : never;\n\ntype IntegrationAPIToServerClient<TAPI> =\n TAPI extends FarmIntegrationAPIOperation<any, any, any>\n ? ServerOperation<TAPI>\n : TAPI extends Record<string, any>\n ? [SingleServerOperationKey<TAPI>] extends [never]\n ? ServerNamespaceShape<TAPI>\n : SingleServerOperationKey<TAPI> extends keyof TAPI\n ? ServerOperation<TAPI[SingleServerOperationKey<TAPI>]> & ServerNamespaceShape<TAPI>\n : ServerNamespaceShape<TAPI>\n : never;\n\nexport type IntegrationServerClient<TSources extends Record<string, any>> = {\n [K in SourceKeysWithAPI<TSources>]: IntegrationAPIToServerClient<\n ExtractAPIFromSource<TSources[K]>\n >;\n};\n\nexport type IntegrationServerClientRoot<TSources extends Record<string, any>> = {\n integrations: IntegrationServerClient<TSources>;\n};\n\nexport type IntegrationClientAliases<TSources extends Record<string, any>> =\n IntegrationClient<TSources> & {\n integrations: IntegrationClient<TSources>;\n };\n\nexport type IntegrationServerClientAliases<TSources extends Record<string, any>> =\n IntegrationServerClient<TSources> & {\n integrations: IntegrationServerClient<TSources>;\n };\n\nexport type IntegrationAPI<TSources extends Record<string, any>> =\n IntegrationClientAliases<TSources> & {\n server: (\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n ) => IntegrationServerClientAliases<TSources>;\n };\n\nexport type IntegrationClients<TSources extends Record<string, any>> = {\n api: IntegrationServerClientAliases<TSources>;\n apiClient: IntegrationClientAliases<TSources>;\n};\n\ntype ResolvedIntegrationNamespace = readonly [\n string,\n FarmIntegrationAPI,\n FarmIntegrationDefinition | FarmIntegrationAPI,\n];\n\ntype RegisteredIntegrationRuntime = {\n integration: FarmIntegrationDefinition;\n config: unknown;\n isDev: boolean;\n isProd: boolean;\n};\n\nconst INTEGRATION_RUNTIME_REGISTRY_KEY = Symbol.for(\"farm.integrationRuntimeRegistry\");\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\nconst INTEGRATION_REQUEST_DISPATCHER_KEY = Symbol.for(\"farm.integrationRequestDispatcher\");\n\ntype IntegrationRequestDispatcher = (\n runtime: RegisteredIntegrationRuntime,\n request: Request,\n options?: { currentRequest?: Request; data?: IntegrationClientData; internal?: boolean },\n) => Promise<Response | null>;\n\ntype GlobalWithIntegrationRuntimeRegistry = typeof globalThis & {\n [INTEGRATION_RUNTIME_REGISTRY_KEY]?: Map<string, RegisteredIntegrationRuntime>;\n [CURRENT_REQUEST_RESOLVER_KEY]?: () => Request | undefined;\n [INTEGRATION_REQUEST_DISPATCHER_KEY]?: IntegrationRequestDispatcher;\n};\n\ntype GlobalWithIntegrationAPIManifest = typeof globalThis & {\n __FARM_INTEGRATION_API_MANIFEST__?: Record<string, FarmIntegrationAPI>;\n window?: {\n __FARM_INTEGRATION_API_MANIFEST__?: Record<string, FarmIntegrationAPI>;\n };\n};\n\nfunction isOperation(value: unknown): value is FarmIntegrationAPIOperation<any, any, any, any> {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as FarmIntegrationAPIOperation<any, any, any, any>).kind ===\n \"farm-integration-api-operation\"\n );\n}\n\nfunction resolveSourceAPI(\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n): FarmIntegrationAPI {\n if (\"kind\" in source && source.kind === \"farm-integration\") {\n if (!source.api) {\n throw new Error(`Integration \"${source.type}\" does not expose a client API definition.`);\n }\n\n return source.api as FarmIntegrationAPI;\n }\n\n return source as FarmIntegrationAPI;\n}\n\nfunction tryResolveSourceAPI(\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n): FarmIntegrationAPI | null {\n if (\"kind\" in source && source.kind === \"farm-integration\") {\n if (!source.api) {\n return null;\n }\n\n return source.api as FarmIntegrationAPI;\n }\n\n return source as FarmIntegrationAPI;\n}\n\nfunction getIntegrationRuntimeRegistry() {\n const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n return (\n globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] || new Map<string, RegisteredIntegrationRuntime>()\n );\n}\n\nfunction getRegisteredIntegrationRuntimeLocal(\n key: string,\n): RegisteredIntegrationRuntime | undefined {\n return getIntegrationRuntimeRegistry().get(key);\n}\n\nfunction getRegisteredIntegrationsLocal(): Record<string, FarmIntegrationDefinition> {\n return Object.fromEntries(\n Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [\n key,\n runtime.integration,\n ]),\n );\n}\n\nfunction resolveCurrentRequestLocal(): Request | undefined {\n const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n return globalState[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n\nfunction resolveIntegrationRequestDispatcherLocal(): IntegrationRequestDispatcher | undefined {\n const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n return globalState[INTEGRATION_REQUEST_DISPATCHER_KEY];\n}\n\nconst INTEGRATION_DATA_HEADER = \"x-farm-integration-data\";\nconst INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;\nconst BLOCKED_INTEGRATION_DATA_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isIntegrationClientData(value: unknown): value is IntegrationClientData {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isPlainIntegrationDataObject(value: unknown): value is Record<string, unknown> {\n if (!isIntegrationClientData(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction sanitizeIntegrationClientDataValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeIntegrationClientDataValue(item));\n }\n\n if (!isPlainIntegrationDataObject(value)) {\n return value;\n }\n\n const sanitized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {\n continue;\n }\n\n sanitized[key] = sanitizeIntegrationClientDataValue(item);\n }\n\n return sanitized;\n}\n\nfunction normalizeIntegrationClientData(\n value: IntegrationClientData | undefined,\n): IntegrationClientData | undefined {\n if (!isIntegrationClientData(value)) {\n return undefined;\n }\n\n const sanitized = sanitizeIntegrationClientDataValue(value);\n return isIntegrationClientData(sanitized) && Object.keys(sanitized).length > 0\n ? sanitized\n : undefined;\n}\n\nfunction getIntegrationDataHeaderByteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength;\n}\n\nfunction mergeIntegrationClientData(\n ...values: Array<IntegrationClientData | undefined>\n): IntegrationClientData | undefined {\n let merged: IntegrationClientData | undefined;\n\n for (const value of values) {\n const data = normalizeIntegrationClientData(value);\n if (!data) {\n continue;\n }\n\n merged = {\n ...merged,\n ...data,\n };\n }\n\n return merged && Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nfunction serializeIntegrationClientData(data: IntegrationClientData): string {\n const serialized = JSON.stringify(data);\n if (getIntegrationDataHeaderByteLength(serialized) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {\n throw new Error(\n `Integration client data must be smaller than ${INTEGRATION_DATA_HEADER_MAX_LENGTH} bytes when sent over HTTP headers.`,\n );\n }\n\n return serialized;\n}\n\nfunction appendIntegrationClientDataHeader(\n headers: Headers,\n data: IntegrationClientData | undefined,\n) {\n if (!data) {\n return;\n }\n\n headers.set(INTEGRATION_DATA_HEADER, serializeIntegrationClientData(data));\n}\n\nfunction resolveAutomaticClientNamespaces(): ResolvedIntegrationNamespace[] {\n const globalState = globalThis as GlobalWithIntegrationAPIManifest;\n const manifest =\n globalState.window?.__FARM_INTEGRATION_API_MANIFEST__ ||\n globalState.__FARM_INTEGRATION_API_MANIFEST__ ||\n {};\n\n return Object.entries(manifest).map(([key, api]) => [key, api, api] as const);\n}\n\nfunction resolveAutomaticServerNamespaces(): ResolvedIntegrationNamespace[] {\n return Object.entries(getRegisteredIntegrationsLocal()).flatMap(([key, source]) => {\n const api = tryResolveSourceAPI(source);\n return api ? [[key, api, source] as ResolvedIntegrationNamespace] : [];\n });\n}\n\nfunction appendQuery(url: URL, query: Record<string, unknown> | undefined) {\n if (!query) {\n return;\n }\n\n for (const [key, value] of Object.entries(query)) {\n if (value == null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item != null) {\n url.searchParams.append(key, String(item));\n }\n }\n continue;\n }\n\n url.searchParams.set(key, String(value));\n }\n}\n\nfunction appendHeaders(target: Headers, source: HeadersInit | undefined) {\n if (!source) {\n return;\n }\n\n const headers = new Headers(source);\n headers.forEach((value, key) => {\n target.set(key, value);\n });\n}\n\nconst DEFAULT_FORWARDED_HEADERS = [\n \"authorization\",\n \"cookie\",\n \"x-client-ip\",\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n \"x-real-ip\",\n] as const;\n\nfunction resolveRequestLike(request: IntegrationServerRequestLike | undefined) {\n if (!request) {\n return undefined;\n }\n\n if (request instanceof Request) {\n return {\n url: request.url,\n headers: request.headers,\n };\n }\n\n return {\n url: request.url,\n headers: request.headers ? new Headers(request.headers) : undefined,\n };\n}\n\nfunction resolveServerBaseURL(\n explicitBaseURL: string | undefined,\n request: ReturnType<typeof resolveRequestLike>,\n) {\n if (explicitBaseURL) {\n return explicitBaseURL;\n }\n\n if (request?.url) {\n try {\n return new URL(request.url).origin;\n } catch {\n // Fall back to forwarded headers below.\n }\n }\n\n const headers = request?.headers;\n const host = headers?.get(\"x-forwarded-host\") || headers?.get(\"host\");\n if (host) {\n const proto = headers?.get(\"x-forwarded-proto\") || \"http\";\n return `${proto}://${host}`;\n }\n\n return \"http://localhost:3000\";\n}\n\nfunction resolveForwardHeaders(\n request: ReturnType<typeof resolveRequestLike>,\n forwardHeaders: boolean | readonly string[] | undefined,\n) {\n if (!request?.headers || forwardHeaders === false) {\n return new Headers();\n }\n\n const allowed =\n Array.isArray(forwardHeaders) && forwardHeaders.length > 0\n ? new Set(forwardHeaders.map((item) => item.toLowerCase()))\n : new Set<string>(DEFAULT_FORWARDED_HEADERS);\n\n const headers = new Headers();\n request.headers.forEach((value, key) => {\n if (allowed.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n return headers;\n}\n\nfunction createBody(\n format: FarmIntegrationAPIBodyFormat | undefined,\n body: unknown,\n headers: Headers,\n): BodyInit | undefined {\n if (body == null || format === \"none\") {\n return undefined;\n }\n\n if (format === \"form\") {\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n const form = new URLSearchParams();\n for (const [key, value] of Object.entries(body as Record<string, unknown>)) {\n if (value == null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item != null) {\n form.append(key, String(item));\n }\n }\n continue;\n }\n\n form.set(key, String(value));\n }\n\n headers.set(\"content-type\", \"application/x-www-form-urlencoded;charset=UTF-8\");\n return form;\n }\n\n headers.set(\"content-type\", \"application/json\");\n return JSON.stringify(body);\n}\n\nfunction createOperationBody(\n operation: Pick<FarmIntegrationAPIOperation<any, any, any>, \"bodyFormat\" | \"method\">,\n body: unknown,\n headers: Headers,\n): BodyInit | undefined {\n const requestBody = createBody(operation.bodyFormat, body, headers);\n\n if (operation.method === \"QUERY\" && requestBody === undefined && !headers.has(\"content-type\")) {\n headers.set(\n \"content-type\",\n operation.bodyFormat === \"form\"\n ? \"application/x-www-form-urlencoded;charset=UTF-8\"\n : \"application/json\",\n );\n }\n\n return requestBody;\n}\n\nasync function parseResponseData(response: Response): Promise<unknown> {\n if (response.status === 204 || response.status === 205) {\n return undefined;\n }\n\n const contentType = response.headers.get(\"content-type\") || \"\";\n\n if (isJSONMediaType(contentType)) {\n return await response.json();\n }\n\n return await response.text();\n}\n\nfunction isJSONMediaType(contentType: string): boolean {\n const mediaType = contentType.split(\";\", 1)[0].trim().toLowerCase();\n return mediaType === \"application/json\" || mediaType.endsWith(\"+json\");\n}\n\nasync function safeParseResponseData(response: Response): Promise<unknown> {\n try {\n return await parseResponseData(response);\n } catch {\n return undefined;\n }\n}\n\nfunction createResponseError(response: Response, errorData: unknown) {\n const message =\n typeof errorData === \"string\"\n ? errorData\n : typeof errorData === \"object\" && errorData\n ? String(\n (errorData as { error?: string; message?: string }).error ||\n (errorData as { error?: string; message?: string }).message ||\n response.statusText,\n )\n : response.statusText || \"Integration request failed.\";\n\n return new IntegrationClientError(message, response, errorData);\n}\n\nfunction normalizeExecutionError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n\n if (typeof error === \"string\" && error.length > 0) {\n return new Error(error);\n }\n\n return new Error(\"Integration request failed.\");\n}\n\nasync function finalizeOperationResponse(\n operation: FarmIntegrationAPIOperation<any, any, any>,\n response: Response,\n) {\n if (!response.ok) {\n const errorData = await safeParseResponseData(response);\n return {\n data: null,\n error: createResponseError(response, errorData),\n };\n }\n\n if (operation.responseFormat === \"response\") {\n return {\n data: response,\n error: null,\n };\n }\n\n return {\n data: (await parseResponseData(response)) as unknown,\n error: null,\n };\n}\n\nlet integrationRequestCounter = 0;\nconst noIntegrationObservers = {\n response(_response: Response) {},\n finish<T extends IntegrationOperationResult>(result: T): T {\n return result;\n },\n};\n\nfunction createIntegrationObservers(\n operation: FarmIntegrationAPIOperation<any, any, any>,\n options: ClientLifecycleHooks,\n requestOptions?: ClientLifecycleHooks,\n) {\n if (\n !options.onRequest &&\n !options.onResponse &&\n !options.onError &&\n !requestOptions?.onRequest &&\n !requestOptions?.onResponse &&\n !requestOptions?.onError\n ) {\n return noIntegrationObservers;\n }\n const requestEvent: ClientRequestEvent = {\n requestId: `integration-${Date.now()}-${++integrationRequestCounter}`,\n method: operation.method,\n path: operation.path ?? \"\",\n attempt: 0,\n timestamp: Date.now(),\n };\n let response: Response | undefined;\n notifyClientObserver(options.onRequest, [requestEvent]);\n notifyClientObserver(requestOptions?.onRequest, [requestEvent]);\n return {\n response(value: Response) {\n response = value;\n },\n finish<T extends IntegrationOperationResult>(result: T): T {\n const data = result.error ? undefined : result.data;\n const event: ClientResponseEvent = {\n ...requestEvent,\n timestamp: Date.now(),\n response,\n data,\n error: result.error ?? undefined,\n ok: !result.error,\n status: response?.status,\n };\n notifyClientObserver(options.onResponse, [data, result.error, event]);\n notifyClientObserver(requestOptions?.onResponse, [data, result.error, event]);\n if (result.error) {\n notifyClientObserver(options.onError, [result.error]);\n notifyClientObserver(requestOptions?.onError, [result.error]);\n }\n return result;\n },\n };\n}\n\nasync function executeClientOperation(\n operation: FarmIntegrationAPIOperation<any, any, any>,\n input: Record<string, unknown>,\n options: IntegrationClientOptions,\n requestOptions?: IntegrationClientRequestOptions,\n) {\n const cancellation = createClientCancellation(\n requestOptions?.signal,\n requestOptions?.timeoutMs ?? options.timeoutMs,\n );\n const observers = createIntegrationObservers(operation, options, requestOptions);\n try {\n const result = await cancellation.run(async () => {\n if (!operation.path) {\n return {\n data: null,\n error: new Error(\n \"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... }).\",\n ),\n };\n }\n\n const baseURL =\n options.baseURL ||\n (typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\");\n const url = resolveFarmAPIRequestURL(operation.path, baseURL);\n appendQuery(url, input.query as Record<string, unknown> | undefined);\n\n const resolved = resolveClientHeaders(options.headers);\n const headers = resolved instanceof Headers ? resolved : await resolved;\n cancellation.check();\n appendHeaders(headers, operation.headers);\n appendHeaders(headers, requestOptions?.headers);\n headers.set(\"x-farm-integration-client\", \"1\");\n\n if (operation.responseFormat !== \"response\") {\n headers.set(\"accept\", \"application/json\");\n }\n\n appendIntegrationClientDataHeader(\n headers,\n mergeIntegrationClientData(options.data, requestOptions?.data),\n );\n\n const body = createOperationBody(operation, input.body, headers);\n const response = await (options.fetch ?? fetch)(url.toString(), {\n method: operation.method,\n headers,\n body,\n credentials:\n requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? \"include\",\n signal: cancellation.signal,\n });\n cancellation.check();\n\n observers.response(response);\n if (!response.ok) {\n const errorData = await safeParseResponseData(response);\n return {\n data: null,\n error: createResponseError(response, errorData),\n };\n }\n\n if (operation.responseFormat === \"response\") {\n return {\n data: response,\n error: null,\n };\n }\n\n return {\n data: (await parseResponseData(response)) as unknown,\n error: null,\n };\n });\n return observers.finish(result);\n } catch (error) {\n return observers.finish({\n data: null,\n error: normalizeExecutionError(error),\n });\n } finally {\n cancellation.dispose();\n }\n}\n\nasync function executeServerOperation(\n operation: FarmIntegrationAPIOperation<any, any, any>,\n input: Record<string, unknown>,\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n requestOptions?: IntegrationServerClientRequestOptions,\n integrationKey?: string,\n source?: FarmIntegrationDefinition | FarmIntegrationAPI,\n) {\n // Capture the request before any asynchronous work (including header resolvers).\n const currentRequest =\n requestOptions?.request instanceof Request\n ? requestOptions.request\n : options.request instanceof Request\n ? options.request\n : resolveCurrentRequestLocal();\n const cancellation = createClientCancellation(\n requestOptions?.signal,\n requestOptions?.timeoutMs ?? options.timeoutMs,\n currentRequest?.signal,\n );\n const observers = createIntegrationObservers(operation, options, requestOptions);\n try {\n const result = await cancellation.run(async () => {\n if (!operation.path) {\n return {\n data: null,\n error: new Error(\n \"Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... }).\",\n ),\n };\n }\n\n const serverRequestOptions =\n requestOptions &&\n (\"request\" in requestOptions ||\n \"baseURL\" in requestOptions ||\n \"forwardHeaders\" in requestOptions)\n ? requestOptions\n : undefined;\n const request = resolveRequestLike(\n serverRequestOptions?.request ?? options.request ?? currentRequest,\n );\n const baseURL = resolveServerBaseURL(\n serverRequestOptions?.baseURL ?? options.baseURL,\n request,\n );\n const origin = resolveServerBaseURL(undefined, request);\n // Registered handlers use their canonical path, not an HTTP gateway prefix.\n const url = new URL(operation.path, new URL(baseURL, origin));\n appendQuery(url, input.query as Record<string, unknown> | undefined);\n\n const headers = new Headers();\n appendHeaders(\n headers,\n resolveForwardHeaders(\n request,\n serverRequestOptions?.forwardHeaders ?? options.forwardHeaders,\n ),\n );\n const resolved = resolveClientHeaders(options.headers);\n appendHeaders(headers, resolved instanceof Headers ? resolved : await resolved);\n cancellation.check();\n appendHeaders(headers, operation.headers);\n appendHeaders(headers, requestOptions?.headers);\n headers.set(\"x-farm-integration-client\", \"1\");\n\n if (operation.responseFormat !== \"response\") {\n headers.set(\"accept\", \"application/json\");\n }\n\n const data = mergeIntegrationClientData(options.data, requestOptions?.data);\n\n if (integrationKey) {\n const runtime =\n \"kind\" in (source || {}) &&\n (source as FarmIntegrationDefinition).kind === \"farm-integration\"\n ? getRegisteredIntegrationRuntimeLocal(integrationKey) || {\n integration: source as FarmIntegrationDefinition,\n config: {},\n isDev: process.env.NODE_ENV !== \"production\",\n isProd: process.env.NODE_ENV === \"production\",\n }\n : getRegisteredIntegrationRuntimeLocal(integrationKey);\n\n if (runtime) {\n const dispatchIntegrationRequest = resolveIntegrationRequestDispatcherLocal();\n const body = createOperationBody(operation, input.body, headers);\n const directResponse = dispatchIntegrationRequest\n ? await dispatchIntegrationRequest(\n runtime,\n new Request(url.toString(), {\n method: operation.method,\n headers,\n body,\n signal: cancellation.signal,\n }),\n {\n currentRequest,\n data,\n internal: true,\n },\n )\n : null;\n\n cancellation.check();\n\n if (directResponse) {\n observers.response(directResponse);\n return await finalizeOperationResponse(operation, directResponse);\n }\n }\n }\n\n appendIntegrationClientDataHeader(headers, data);\n\n const body = createOperationBody(operation, input.body, headers);\n const httpURL = resolveFarmAPIRequestURL(operation.path, baseURL, origin);\n appendQuery(httpURL, input.query as Record<string, unknown> | undefined);\n const response = await (options.fetch ?? fetch)(httpURL.toString(), {\n method: operation.method,\n headers,\n body,\n credentials:\n requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? \"include\",\n signal: cancellation.signal,\n });\n cancellation.check();\n\n observers.response(response);\n return await finalizeOperationResponse(operation, response);\n });\n return observers.finish(result);\n } catch (error) {\n return observers.finish({\n data: null,\n error: normalizeExecutionError(error),\n });\n } finally {\n cancellation.dispose();\n }\n}\n\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options: IntegrationServerClientOptions,\n): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options?: IntegrationClientOptions,\n): IntegrationClientAliases<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: TSources,\n options: IntegrationServerClientOptions,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: TSources,\n options?: IntegrationClientOptions,\n): IntegrationClient<TSources>;\nexport function createIntegrationClient<TSources extends Record<string, any>>(\n sources: TSources | { integrations: TSources },\n options: IntegrationClientOptions | IntegrationServerClientOptions = {},\n):\n | IntegrationClient<TSources>\n | IntegrationClientAliases<TSources>\n | IntegrationServerClient<TSources>\n | IntegrationServerClientAliases<TSources> {\n const rawSources = \"integrations\" in sources ? sources.integrations : sources;\n const isServer = options.isServer === true;\n\n const namespaces = Object.entries(rawSources)\n .map(([key, source]) => {\n const api = tryResolveSourceAPI(source as FarmIntegrationDefinition | FarmIntegrationAPI);\n if (!api) {\n return null;\n }\n return [key, api, source as FarmIntegrationDefinition | FarmIntegrationAPI] as const;\n })\n .filter(\n (\n value,\n ): value is readonly [\n string,\n FarmIntegrationAPI,\n FarmIntegrationDefinition | FarmIntegrationAPI,\n ] => value !== null,\n );\n\n const cache = new Map<string, any>();\n\n const integrationNamespaces = new Proxy(\n {},\n {\n get(target, property) {\n if (typeof property !== \"string\") {\n return undefined;\n }\n\n if (Reflect.has(target, property)) {\n return Reflect.get(target, property);\n }\n\n if (cache.has(property)) {\n return cache.get(property);\n }\n\n const match = namespaces.find(([key]) => key === property);\n if (!match) {\n return undefined;\n }\n\n const namespace = isServer\n ? createServerNamespaceProxy(\n match[0],\n match[2],\n match[1],\n options as IntegrationServerClientOptions,\n )\n : createNamespaceProxy(match[1], options);\n cache.set(property, namespace);\n return namespace;\n },\n },\n ) as\n | IntegrationClient<TSources>\n | IntegrationClientAliases<TSources>\n | IntegrationServerClient<TSources>\n | IntegrationServerClientAliases<TSources>;\n\n if (\"integrations\" in sources) {\n Object.defineProperty(integrationNamespaces, \"integrations\", {\n value: integrationNamespaces,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return integrationNamespaces as\n | IntegrationClientAliases<TSources>\n | IntegrationServerClientAliases<TSources>;\n }\n\n return integrationNamespaces as IntegrationClient<TSources> | IntegrationServerClient<TSources>;\n}\n\nfunction createAutomaticIntegrationAliases<TSources extends Record<string, any>>(\n isServer: boolean,\n options: IntegrationClientOptions | IntegrationServerClientOptions = {},\n): IntegrationClientAliases<TSources> | IntegrationServerClientAliases<TSources> {\n const cache = isServer ? new Map<string, any>() : null;\n\n const integrationNamespaces = new Proxy(\n {},\n {\n get(_target, property) {\n if (typeof property !== \"string\") {\n return undefined;\n }\n\n if (property === \"integrations\") {\n return integrationNamespaces;\n }\n\n if (cache?.has(property)) {\n return cache.get(property);\n }\n\n const namespaces = isServer\n ? resolveAutomaticServerNamespaces()\n : resolveAutomaticClientNamespaces();\n const match = namespaces.find(([key]) => key === property);\n if (!match) {\n return undefined;\n }\n\n const namespace = isServer\n ? createServerNamespaceProxy(\n match[0],\n match[2],\n match[1],\n options as IntegrationServerClientOptions,\n )\n : createNamespaceProxy(match[1], options as IntegrationClientOptions);\n\n cache?.set(property, namespace);\n return namespace;\n },\n },\n ) as IntegrationClientAliases<TSources> | IntegrationServerClientAliases<TSources>;\n\n Object.defineProperty(integrationNamespaces, \"integrations\", {\n value: integrationNamespaces,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return integrationNamespaces;\n}\n\nexport function integrationsClient<\n TSources extends Record<string, any>,\n>(): IntegrationClientAliases<TSources>;\nexport function integrationsClient<TSources extends Record<string, any>>(\n options: IntegrationClientOptions,\n): IntegrationClientAliases<TSources>;\nexport function integrationsClient<TSources extends Record<string, any>>(\n options: IntegrationClientOptions = {},\n): IntegrationClientAliases<TSources> {\n return createAutomaticIntegrationAliases<TSources>(\n false,\n options,\n ) as IntegrationClientAliases<TSources>;\n}\n\nexport function integrationsServer<\n TSources extends Record<string, any>,\n>(): IntegrationServerClientAliases<TSources>;\nexport function integrationsServer<TSources extends Record<string, any>>(\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClientAliases<TSources>;\nexport function integrationsServer<TSources extends Record<string, any>>(\n options: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): IntegrationServerClientAliases<TSources> {\n return createAutomaticIntegrationAliases<TSources>(true, {\n ...options,\n isServer: true,\n }) as IntegrationServerClientAliases<TSources>;\n}\n\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(sources: {\n integrations: TSources;\n}): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: TSources,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClientAliases<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: TSources,\n options: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationServerClient<TSources>;\nexport function createIntegrationServerClient<TSources extends Record<string, any>>(\n sources: TSources | { integrations: TSources },\n options: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): IntegrationServerClient<TSources> | IntegrationServerClientAliases<TSources> {\n return createIntegrationClient(sources, {\n ...options,\n isServer: true,\n }) as IntegrationServerClient<TSources> | IntegrationServerClientAliases<TSources>;\n}\n\nexport function createIntegrationApi<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n options: IntegrationClientOptions = {},\n): IntegrationAPI<TSources> {\n const client = createIntegrationClient(sources, options);\n\n return {\n ...client,\n server(serverOptions = {}) {\n return createIntegrationServerClient(sources, {\n ...options,\n ...serverOptions,\n });\n },\n };\n}\n\nfunction isIntegrationClientOptionsInput(value: unknown): value is IntegrationClientOptions {\n return (\n !!value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n (\"baseURL\" in value ||\n \"headers\" in value ||\n \"credentials\" in value ||\n \"timeoutMs\" in value ||\n \"fetch\" in value ||\n \"onRequest\" in value ||\n \"onResponse\" in value ||\n \"onError\" in value ||\n \"data\" in value ||\n \"isServer\" in value)\n );\n}\n\nfunction resolveIntegrationServerOptions(\n clientOptions: IntegrationClientOptions = {},\n serverOptions: Omit<IntegrationServerClientOptions, \"isServer\"> = {},\n): Omit<IntegrationServerClientOptions, \"isServer\"> {\n const data = mergeIntegrationClientData(clientOptions.data, serverOptions.data);\n\n return {\n baseURL: clientOptions.baseURL,\n headers: clientOptions.headers,\n credentials: clientOptions.credentials,\n timeoutMs: clientOptions.timeoutMs,\n fetch: clientOptions.fetch,\n onRequest: clientOptions.onRequest,\n onResponse: clientOptions.onResponse,\n onError: clientOptions.onError,\n ...serverOptions,\n ...(data ? { data } : {}),\n };\n}\n\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n sources: TSources,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrationClients<TSources extends Record<string, any>>(\n sources?: TSources | { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n if (arguments.length === 0 || isIntegrationClientOptionsInput(sources)) {\n const automaticClientOptions = isIntegrationClientOptionsInput(sources) ? sources : {};\n const automaticServerOptions = arguments.length > 1 ? clientOptions : undefined;\n\n return {\n api: integrationsServer<TSources>(\n resolveIntegrationServerOptions(\n automaticClientOptions,\n automaticServerOptions as Omit<IntegrationServerClientOptions, \"isServer\"> | undefined,\n ),\n ),\n apiClient: integrationsClient<TSources>(automaticClientOptions),\n };\n }\n\n const explicitSources =\n sources && \"integrations\" in sources ? sources.integrations : (sources as TSources);\n\n return {\n api: createIntegrationServerClient(\n {\n integrations: explicitSources,\n },\n resolveIntegrationServerOptions(clientOptions, serverOptions),\n ) as IntegrationServerClientAliases<TSources>,\n apiClient: createIntegrationClient(\n {\n integrations: explicitSources,\n },\n clientOptions,\n ) as IntegrationClientAliases<TSources>,\n };\n}\n\nexport function createIntegrations<TSources extends Record<string, any>>(\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n sources: TSources,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function createIntegrations<TSources extends Record<string, any>>(\n sources?: TSources | { integrations: TSources } | IntegrationClientOptions,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n if (arguments.length === 0) {\n return createIntegrationClients<TSources>();\n }\n\n return createIntegrationClients<TSources>(\n sources as TSources,\n clientOptions,\n serverOptions,\n ) as IntegrationClients<TSources>;\n}\n\nfunction createClientSafeIntegrationAPI(\n api: FarmIntegrationAPI | undefined,\n): FarmIntegrationAPI | undefined {\n if (!api) {\n return undefined;\n }\n\n const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n if (isOperation(value)) {\n return [\n key,\n {\n kind: value.kind,\n path: value.path,\n method: value.method,\n bodyFormat: value.bodyFormat,\n responseFormat: value.responseFormat,\n credentials: value.credentials,\n isServer: value.isServer,\n __pathless: value.__pathless,\n },\n ];\n }\n\n if (value && typeof value === \"object\") {\n return [key, createClientSafeIntegrationAPI(value as FarmIntegrationAPI)];\n }\n\n return [key, value];\n });\n\n return Object.fromEntries(entries) as FarmIntegrationAPI;\n}\n\nexport function getIntegrationAPIManifest(): Record<string, FarmIntegrationAPI> {\n const manifestEntries = Object.entries(getRegisteredIntegrationsLocal())\n .map(([key, integration]) => {\n const api = createClientSafeIntegrationAPI(integration.api);\n return api ? ([key, api] as const) : null;\n })\n .filter((value): value is readonly [string, FarmIntegrationAPI] => value !== null);\n\n return Object.fromEntries(manifestEntries);\n}\n\nexport function integrationClients<TSources extends Record<string, any>>(\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n sources: TSources,\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n sources: { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources>;\nexport function integrationClients<TSources extends Record<string, any>>(\n sources?: TSources | { integrations: TSources },\n clientOptions?: IntegrationClientOptions,\n serverOptions?: Omit<IntegrationServerClientOptions, \"isServer\">,\n): IntegrationClients<TSources> {\n if (arguments.length === 0) {\n return createIntegrationClients<TSources>();\n }\n\n return createIntegrationClients<TSources>(\n sources as TSources,\n clientOptions,\n serverOptions,\n ) as IntegrationClients<TSources>;\n}\n\nfunction resolveSingleNamespaceOperation(api: FarmIntegrationAPI) {\n const entries = Object.entries(api as Record<string, unknown>);\n if (entries.length !== 1) {\n return null;\n }\n\n const [, value] = entries[0]!;\n return isOperation(value) ? value : null;\n}\n\nfunction createClientOperationCaller(\n operation: FarmIntegrationAPIOperation<any, any, any, any>,\n property: string,\n options: IntegrationClientOptions,\n) {\n if (operation.isServer === true) {\n return async () => {\n throw new Error(\n `Integration method \"${property}\" is registered with isServer: true and is only available from a server integration client.`,\n );\n };\n }\n\n return async (\n input: Record<string, unknown> = {},\n requestOptions?: IntegrationClientRequestOptions,\n ) => {\n if (typeof window === \"undefined\") {\n throw new Error(\n \"Client integration API cannot be called on the server. Pass { isServer: true } to createIntegrationClient(...) during server rendering, or provide { isServer: true, request } outside it.\",\n );\n }\n\n return executeClientOperation(operation, input, options, requestOptions);\n };\n}\n\nfunction createServerOperationCaller(\n operation: FarmIntegrationAPIOperation<any, any, any, any>,\n options: IntegrationServerClientOptions,\n integrationKey: string,\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n) {\n return async (\n input: Record<string, unknown> = {},\n requestOptions?: IntegrationServerClientRequestOptions,\n ) => {\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"Server integration API cannot be called in the browser. Remove { isServer: true } and create a client integration API instead.\",\n );\n }\n\n return executeServerOperation(\n operation,\n input,\n options,\n requestOptions,\n integrationKey,\n source,\n );\n };\n}\n\nfunction createNamespaceProxy(api: FarmIntegrationAPI, options: IntegrationClientOptions) {\n const cache = new Map<string, any>();\n const directOperation = resolveSingleNamespaceOperation(api);\n const target = directOperation\n ? createClientOperationCaller(directOperation, directOperation.method.toLowerCase(), options)\n : {};\n\n return new Proxy(target, {\n get(targetObject, property, receiver) {\n if (typeof property !== \"string\") {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (cache.has(property)) {\n return cache.get(property);\n }\n\n const value = (api as Record<string, unknown>)[property];\n if (!value) {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (isOperation(value)) {\n const caller = createClientOperationCaller(value, property, options);\n cache.set(property, caller);\n return caller;\n }\n\n const namespace = createNamespaceProxy(value as FarmIntegrationAPI, options);\n cache.set(property, namespace);\n return namespace;\n },\n });\n}\n\nfunction createServerNamespaceProxy(\n integrationKey: string,\n source: FarmIntegrationDefinition | FarmIntegrationAPI,\n api: FarmIntegrationAPI,\n options: IntegrationServerClientOptions,\n) {\n const cache = new Map<string, any>();\n const directOperation = resolveSingleNamespaceOperation(api);\n const target = directOperation\n ? createServerOperationCaller(directOperation, options, integrationKey, source)\n : {};\n\n return new Proxy(target, {\n get(targetObject, property, receiver) {\n if (typeof property !== \"string\") {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (cache.has(property)) {\n return cache.get(property);\n }\n\n const value = (api as Record<string, unknown>)[property];\n if (!value) {\n return Reflect.get(targetObject, property, receiver);\n }\n\n if (isOperation(value)) {\n const caller = createServerOperationCaller(value, options, integrationKey, source);\n cache.set(property, caller);\n return caller;\n }\n\n const namespace = createServerNamespaceProxy(\n integrationKey,\n source,\n value as FarmIntegrationAPI,\n options,\n );\n cache.set(property, namespace);\n return namespace;\n },\n });\n}\n","/// <reference lib=\"es2021.weakref\" />\nimport { createRouteDataCacheKey, type RouteDataCacheKey } from \"./cache\";\nimport { subscribeFarmCacheInvalidation } from \"./cache-invalidation\";\n\nexport type FarmClientCacheKey = RouteDataCacheKey;\n\nexport type FarmClientCacheStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport type FarmClientCacheEntry<TData = unknown> = {\n data: TData;\n updatedAt: number;\n staleAt: number;\n gcAt?: number;\n invalidatedAt?: number;\n status?: FarmClientCacheStatus;\n error?: Error | null;\n fetching?: boolean;\n /** Marks an entry the persistence layer may write to its adapter. */\n persist?: boolean;\n};\n\n/** @internal Observation seam for the client cache persistence engine. */\nexport type FarmClientCachePersistenceSink = {\n onSet(key: string, entry: FarmClientCacheEntry): void;\n onDelete(key: string): void;\n onClear(): void;\n};\n\ntype FarmClientCacheListener = (event?: \"invalidate\") => void;\n\nconst invalidationTrackers = new WeakMap<FarmClientDataCache, Set<Set<string>>>();\n\n/** Internal request-lifetime tracking, including keys learned only from a response. */\nexport function trackFarmClientCacheInvalidations(cache: FarmClientDataCache) {\n let trackers = invalidationTrackers.get(cache);\n if (!trackers) {\n trackers = new Set();\n invalidationTrackers.set(cache, trackers);\n }\n const keys = new Set<string>();\n trackers.add(keys);\n return {\n has(key: string) {\n const resolved = cache.resolveKey(key);\n for (const invalidated of keys) {\n if (cache.resolveKey(invalidated) === resolved) return true;\n }\n return false;\n },\n dispose() {\n if (!trackers.delete(keys)) return;\n keys.clear();\n if (trackers.size === 0) invalidationTrackers.delete(cache);\n },\n };\n}\n\nconst cacheFinalizer =\n typeof FinalizationRegistry === \"function\"\n ? new FinalizationRegistry<() => void>((unsubscribe) => unsubscribe())\n : undefined;\n\n// This closure must only capture a weak reference, never the cache itself.\nfunction subscribeWeakCache(reference: WeakRef<FarmClientDataCache>): () => void {\n const unsubscribe = subscribeFarmCacheInvalidation((key) => {\n const cache = reference.deref();\n if (cache) cache.invalidate(key);\n else dispose();\n });\n function dispose() {\n unsubscribe();\n cacheFinalizer?.unregister(reference);\n }\n return dispose;\n}\n\nconst DEFAULT_GC_SWEEP_INTERVAL_MS = 30_000;\n\nexport class FarmClientDataCache {\n private entries = new Map<string, FarmClientCacheEntry>();\n private aliases = new Map<string, string>();\n private invalidatedAt = new Map<string, number>();\n private listeners = new Map<string, Set<FarmClientCacheListener>>();\n private inflight = new Map<string, Promise<unknown>>();\n private unsubscribeInvalidation: (() => void) | undefined;\n private gcTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly gcSweepIntervalMs: number | false;\n private persistence: FarmClientCachePersistenceSink | undefined;\n\n constructor(\n options: { subscribeToInvalidation?: boolean; gcSweepIntervalMs?: number | false } = {},\n ) {\n this.gcSweepIntervalMs = options.gcSweepIntervalMs ?? DEFAULT_GC_SWEEP_INTERVAL_MS;\n if (options.subscribeToInvalidation !== false) {\n if (typeof WeakRef === \"function\") {\n const reference = new WeakRef(this);\n const unsubscribe = subscribeWeakCache(reference);\n cacheFinalizer?.register(this, unsubscribe, reference);\n this.unsubscribeInvalidation = unsubscribe;\n } else {\n // Keep invalidation working on older runtimes without weak references.\n this.unsubscribeInvalidation = subscribeFarmCacheInvalidation((key) =>\n this.invalidate(key),\n );\n }\n }\n }\n\n get size(): number {\n return this.entries.size;\n }\n\n /** @internal Attach or detach the persistence engine's observation sink. */\n attachPersistence(sink: FarmClientCachePersistenceSink | undefined): void {\n this.persistence = sink;\n }\n\n resolveKey(key: string): string {\n let resolved = key;\n const seen = new Set<string>();\n\n while (this.aliases.has(resolved) && !seen.has(resolved)) {\n seen.add(resolved);\n resolved = this.aliases.get(resolved)!;\n }\n\n return resolved;\n }\n\n get<TData = unknown>(key: string, now = Date.now()): FarmClientCacheEntry<TData> | undefined {\n const resolved = this.resolveKey(key);\n const entry = this.entries.get(resolved) as FarmClientCacheEntry<TData> | undefined;\n if (!entry) return undefined;\n\n if (entry.gcAt !== undefined && now >= entry.gcAt) {\n this.entries.delete(resolved);\n this.persistence?.onDelete(resolved);\n this.emit(resolved);\n return undefined;\n }\n\n return entry;\n }\n\n set<TData>(key: string, entry: FarmClientCacheEntry<TData>): this {\n const resolved = this.resolveKey(key);\n const invalidatedAt = this.invalidatedAt.get(resolved);\n const nextEntry =\n invalidatedAt !== undefined && invalidatedAt > entry.updatedAt\n ? { ...entry, staleAt: 0, invalidatedAt }\n : { ...entry, invalidatedAt: undefined };\n\n if (invalidatedAt === undefined || entry.updatedAt >= invalidatedAt) {\n this.invalidatedAt.delete(resolved);\n }\n\n this.entries.set(resolved, nextEntry);\n if (nextEntry.gcAt !== undefined) this.scheduleGcSweep();\n this.persistence?.onSet(resolved, nextEntry);\n this.emit(resolved);\n return this;\n }\n\n delete(key: string): boolean {\n const resolved = this.resolveKey(key);\n const deleted = this.entries.delete(resolved);\n this.inflight.delete(resolved);\n if (deleted) this.persistence?.onDelete(resolved);\n this.emit(resolved);\n return deleted;\n }\n\n clear(): void {\n const keys = new Set([...this.entries.keys(), ...this.listeners.keys()]);\n this.entries.clear();\n this.aliases.clear();\n this.invalidatedAt.clear();\n this.inflight.clear();\n this.persistence?.onClear();\n for (const key of keys) this.emit(key);\n }\n\n dispose(): void {\n this.unsubscribeInvalidation?.();\n this.unsubscribeInvalidation = undefined;\n if (this.gcTimer !== undefined) {\n clearTimeout(this.gcTimer);\n this.gcTimer = undefined;\n }\n this.clear();\n }\n\n isStale(key: string, now = Date.now()): boolean {\n const entry = this.get(key, now);\n return !entry || entry.invalidatedAt !== undefined || now >= entry.staleAt;\n }\n\n invalidate(key: string, now = Date.now()): void {\n const resolved = this.resolveKey(key);\n for (const keys of invalidationTrackers.get(this) ?? []) keys.add(resolved);\n this.invalidatedAt.set(resolved, now);\n\n const entry = this.entries.get(resolved);\n if (entry) {\n this.entries.set(resolved, {\n ...entry,\n staleAt: 0,\n invalidatedAt: now,\n });\n }\n\n this.emit(resolved, \"invalidate\");\n }\n\n alias(alias: string, key: string): void {\n const resolved = this.resolveKey(key);\n if (alias === resolved) return;\n\n const aliasEntry = this.entries.get(alias);\n const aliasInvalidatedAt = this.invalidatedAt.get(alias) ?? aliasEntry?.invalidatedAt;\n const resolvedInvalidatedAt = this.invalidatedAt.get(resolved);\n if (aliasEntry && !this.entries.has(resolved)) {\n this.entries.set(resolved, aliasEntry);\n this.persistence?.onSet(resolved, aliasEntry);\n }\n\n if (this.entries.delete(alias)) this.persistence?.onDelete(alias);\n this.invalidatedAt.delete(alias);\n const invalidatedAt = [aliasInvalidatedAt, resolvedInvalidatedAt].reduce<number | undefined>(\n (latest, value) =>\n value === undefined ? latest : latest === undefined ? value : Math.max(latest, value),\n undefined,\n );\n const resolvedEntry = this.entries.get(resolved);\n if (\n invalidatedAt !== undefined &&\n (!resolvedEntry || invalidatedAt > resolvedEntry.updatedAt)\n ) {\n this.invalidatedAt.set(resolved, invalidatedAt);\n if (resolvedEntry) {\n this.entries.set(resolved, {\n ...resolvedEntry,\n staleAt: 0,\n invalidatedAt,\n });\n }\n } else if (invalidatedAt !== undefined) {\n this.invalidatedAt.delete(resolved);\n if (resolvedEntry?.invalidatedAt !== undefined) {\n this.entries.set(resolved, { ...resolvedEntry, invalidatedAt: undefined });\n }\n }\n\n const aliasInflight = this.inflight.get(alias);\n if (aliasInflight && !this.inflight.has(resolved)) {\n this.inflight.set(resolved, aliasInflight);\n }\n this.inflight.delete(alias);\n this.aliases.set(alias, resolved);\n this.emit(alias);\n this.emit(resolved, this.invalidatedAt.has(resolved) ? \"invalidate\" : undefined);\n }\n\n subscribe(key: string, listener: FarmClientCacheListener): () => void {\n let listeners = this.listeners.get(key);\n if (!listeners) {\n listeners = new Set();\n this.listeners.set(key, listeners);\n }\n\n listeners.add(listener);\n return () => {\n listeners!.delete(listener);\n // Only drop the map entry if it still holds this exact set. A repeated or\n // stale unsubscribe (called after the key was drained and resubscribed)\n // must not evict a newer subscriber's live listener set.\n if (listeners!.size === 0 && this.listeners.get(key) === listeners) {\n this.listeners.delete(key);\n }\n };\n }\n\n getInflight<TData>(key: string): Promise<TData> | undefined {\n return this.inflight.get(this.resolveKey(key)) as Promise<TData> | undefined;\n }\n\n setInflight<TData>(key: string, promise: Promise<TData>): void {\n this.inflight.set(this.resolveKey(key), promise);\n }\n\n deleteInflight(key: string): void {\n this.inflight.delete(this.resolveKey(key));\n }\n\n private scheduleGcSweep(): void {\n if (this.gcSweepIntervalMs === false || this.gcTimer !== undefined) return;\n const timer = setTimeout(() => {\n this.gcTimer = undefined;\n this.sweepExpiredEntries();\n }, this.gcSweepIntervalMs);\n // Cache cleanup must never keep a Node.js process (SSR, tests) alive.\n (timer as unknown as { unref?: () => void }).unref?.();\n this.gcTimer = timer;\n }\n\n private sweepExpiredEntries(now = Date.now()): void {\n const watched = new Set<string>();\n for (const key of this.listeners.keys()) watched.add(this.resolveKey(key));\n\n let remaining = false;\n const swept = new Set<string>();\n for (const [key, entry] of this.entries) {\n if (entry.gcAt === undefined) continue;\n if (now < entry.gcAt || entry.fetching || this.inflight.has(key) || watched.has(key)) {\n remaining = true;\n continue;\n }\n // Only unwatched entries are swept, so eviction is unobservable: a read\n // of this key would already evict it lazily before returning data.\n this.entries.delete(key);\n this.persistence?.onDelete(key);\n swept.add(key);\n }\n\n if (swept.size > 0) this.sweepEntryMetadata(swept);\n if (remaining) this.scheduleGcSweep();\n }\n\n /**\n * Entry eviction alone leaves the per-key metadata behind. `invalidatedAt`\n * marks and provisional aliases are created per query invocation, so with\n * dynamic keys they accumulate for the lifetime of the page even though the\n * entries they describe are long gone.\n */\n private sweepEntryMetadata(swept: Set<string>): void {\n for (const key of swept) this.invalidatedAt.delete(key);\n\n for (const [alias, target] of this.aliases) {\n // Keep any alias that is still addressable: one that has its own entry,\n // that something is subscribed to, or whose target is still live.\n if (this.entries.has(alias) || this.listeners.has(alias)) continue;\n const resolved = this.resolveKey(target);\n if (!swept.has(resolved)) continue;\n if (this.entries.has(resolved) || this.listeners.has(resolved)) continue;\n this.aliases.delete(alias);\n this.invalidatedAt.delete(alias);\n }\n }\n\n private emit(key: string, event?: \"invalidate\"): void {\n this.notifyListeners(key, event);\n for (const [alias, target] of this.aliases) {\n if (this.resolveKey(target) === key) {\n this.notifyListeners(alias, event);\n }\n }\n }\n\n private notifyListeners(key: string, event?: \"invalidate\"): void {\n for (const listener of this.listeners.get(key) ?? []) {\n // One subscriber must not be able to break the others, or to make an\n // ordinary cache write or invalidation throw in its caller. This matches\n // the isolation the global invalidation bus already provides.\n try {\n listener(event);\n } catch (error) {\n const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);\n console.warn(`[farm:client-cache] cache listener failed: ${detail}`);\n }\n }\n }\n}\n\nconst FARM_CLIENT_DATA_CACHE = Symbol.for(\"farm.clientDataCache\");\nconst clientCacheGlobal = globalThis as typeof globalThis & {\n [FARM_CLIENT_DATA_CACHE]?: FarmClientDataCache;\n};\nconst sharedFarmClientDataCache = (clientCacheGlobal[FARM_CLIENT_DATA_CACHE] ??=\n new FarmClientDataCache());\n\nexport function getFarmClientDataCache(): FarmClientDataCache {\n return sharedFarmClientDataCache;\n}\n\nexport function normalizeFarmClientCacheKey(key: FarmClientCacheKey): string {\n return typeof key === \"string\" ? key : createRouteDataCacheKey(key);\n}\n","import {\n integrationsClient,\n integrationsServer,\n type IntegrationClientOptions,\n type IntegrationClientRoot,\n type IntegrationServerClientOptions,\n type IntegrationServerClientRoot,\n} from \"../integration-client\";\nimport {\n FarmClientDataCache,\n getFarmClientDataCache,\n normalizeFarmClientCacheKey,\n type FarmClientCacheEntry,\n type FarmClientCacheKey,\n} from \"../client-cache\";\nimport {\n applyFarmCacheInvalidations,\n decodeFarmCacheInvalidations,\n FARM_CACHE_INVALIDATION_HEADER,\n} from \"../cache-invalidation\";\nimport type { DefinedCacheKey, InferCacheKeyData, RouteDataCacheKey } from \"../cache\";\nimport { getFarmAPIBaseURL, resolveFarmAPIRequestURL } from \"./config\";\nimport { ClientRouteManifest, type APIRouteManifest, type BoundRouteParams } from \"./client-routes\";\nimport type { RoutePathParams } from \"./route\";\nimport { _resolveCurrentRequest } from \"../server/request-bridge\";\nimport { resolveClientHeaders, type ClientHeaders } from \"../client-headers\";\nimport { createClientCancellation } from \"../client-cancellation\";\nimport { notifyClientObserver, type ClientLifecycleHooks } from \"../client-observers\";\nimport { resolveAPIRequestRuntime, type APIRequestRuntime } from \"./server-client-bridge\";\nexport type { APIRouteManifest } from \"./client-routes\";\nimport {\n isFarmAPIStream,\n isJSONStreamResponse,\n readJSONStream,\n type FarmAPIStream,\n} from \"./transport\";\n\nexport const FARM_API_ROUTE_REF_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-ref\") as any;\nexport const FARM_API_ROUTE_META_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-meta\") as any;\n\nexport type APIRouteRefMetadata = {\n path: string;\n method: string;\n baseURL: string;\n sameOrigin: boolean;\n};\n\nexport type APIClientOptions = ClientLifecycleHooks & {\n /** Generated path/method metadata required for dynamic shorthand and $params scopes. */\n routes?: APIRouteManifest;\n baseURL?: string;\n headers?: ClientHeaders;\n credentials?: RequestCredentials;\n /** Whole-call deadline in milliseconds. 0 (default) disables it. */\n timeoutMs?: number;\n /** HTTP transport only; local server dispatch does not use it. */\n fetch?: typeof globalThis.fetch;\n cacheDefaults?: CacheOptions;\n integrations?: IntegrationClientOptions;\n};\n\nexport type APIClientWithoutIntegrationsOptions = Omit<APIClientOptions, \"integrations\"> & {\n integrations: false;\n};\n\nexport type ServerAPIClientOptions = {\n integrations?: Omit<IntegrationServerClientOptions, \"isServer\">;\n};\n\nexport type ServerAPIClientWithoutIntegrationsOptions = Omit<\n ServerAPIClientOptions,\n \"integrations\"\n> & {\n integrations: false;\n};\n\nexport type StatusPhase = \"idle\" | \"pending\" | \"success\" | \"error\" | \"revalidating\" | \"invalidated\";\n\nexport type StatusEvent<TData = unknown, TError = unknown> = {\n phase: StatusPhase;\n requestId: string;\n method: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n key: string;\n input?: unknown;\n data?: TData;\n error?: TError;\n isBackground?: boolean;\n timestamp: number;\n};\n\nexport type CacheKey<TData = unknown> = string & {\n readonly __farmCacheData?: TData;\n};\n\nexport type APIResult<TData = unknown, TError = Error> = {\n data: TData | undefined;\n error: TError | null;\n key: CacheKey<TData>;\n};\n\nexport class APIClientError<\n TCode extends string = string,\n TData = unknown,\n TStatus extends number = number,\n> extends Error {\n readonly code: TCode;\n readonly data: TData;\n readonly status: TStatus;\n readonly response?: Response;\n\n constructor(\n code: TCode,\n data: TData,\n options: {\n status: TStatus;\n message: string;\n response?: Response;\n },\n ) {\n super(options.message);\n this.name = \"APIClientError\";\n this.code = code;\n this.data = data;\n this.status = options.status;\n this.response = options.response;\n }\n}\n\nexport type APIClientSystemError =\n | APIClientError<\"http_error\", unknown, number>\n | APIClientError<\"aborted\" | \"timeout\", unknown, 0>\n | APIClientError<\"network_error\", unknown, 0>;\n\nexport type RequestEvent = {\n requestId: string;\n method: StatusEvent[\"method\"];\n key: string;\n path: string;\n input?: unknown;\n attempt: number;\n timestamp: number;\n};\n\nexport type ResponseEvent<TData = unknown, TError = Error> = {\n requestId: string;\n method: StatusEvent[\"method\"];\n key: string;\n path: string;\n input?: unknown;\n attempt: number;\n timestamp: number;\n response?: Response;\n data?: TData;\n error?: TError;\n ok?: boolean;\n status?: number;\n};\n\nexport type CachePolicy = \"cache-first\" | \"network-only\" | \"stale-while-revalidate\";\nexport type CacheScope = \"client\" | \"shared\";\n\nexport type CacheOptions = {\n key?: FarmClientCacheKey;\n policy?: CachePolicy;\n /** Select client-local or public shared storage. Identity-carrying requests always stay local. */\n scope?: CacheScope;\n staleTime?: number;\n gcTime?: number;\n dedupeMs?: number;\n /** Allow the configured client cache persistence adapter to store this read. */\n persist?: boolean;\n};\n\nexport type RetryOptions = {\n count?: number;\n delay?: number | ((attempt: number) => number);\n};\n\nexport type InvalidateTarget =\n | FarmClientCacheKey\n | {\n key: FarmClientCacheKey;\n }\n | {\n path: string;\n method?: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n input?: unknown;\n }\n | [CallableRouteRef<any>, unknown?];\n\nexport type InvalidateOptions =\n | InvalidateTarget[]\n | {\n targets: InvalidateTarget[];\n refetch?: boolean;\n };\n\nexport type OptimisticUpdate =\n | [CallableRouteRef<any>, unknown, (prev: any) => any]\n | [CacheKey<any> | DefinedCacheKey<any> | string, (prev: any) => any];\n\nexport type OptimisticOptions<TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]> = {\n update: TUpdates & NormalizeOptimisticUpdates<TUpdates>;\n rollbackOnError?: boolean;\n};\n\nexport type ClientOptions<\n TData = unknown,\n TError = unknown,\n TUpdates extends readonly unknown[] = readonly OptimisticUpdate[],\n> = {\n key?: CacheKey<TData> | FarmClientCacheKey;\n signal?: AbortSignal;\n /** Override the instance deadline; 0 disables it for this call. */\n timeoutMs?: number;\n cache?: CacheOptions;\n retry?: RetryOptions;\n invalidate?: InvalidateOptions;\n optimistic?: OptimisticOptions<TUpdates>;\n onRequest?: (event: RequestEvent) => void;\n onResponse?: (\n data: TData | undefined,\n error: TError | null,\n event: ResponseEvent<TData, TError>,\n ) => void;\n onSuccess?: (data: TData) => void;\n onError?: (err: TError) => void;\n onSettled?: (data?: TData, err?: TError | null) => void;\n onStatus?: (event: StatusEvent<TData, TError>) => void;\n};\n\ntype AnyRouteRef = (...args: any[]) => any;\ntype RouteRef<TData = any, TInput = any> = {\n readonly __farmRouteInput: TInput;\n readonly __farmRouteData: TData;\n};\ntype CallableRouteRef<TData = any, TInput = any> = AnyRouteRef & RouteRef<TData, TInput>;\n\ntype InferRouteInput<TRoute> = TRoute extends { readonly __farmRouteInput: infer TInput }\n ? TInput\n : never;\ntype InferRouteData<TRoute> = TRoute extends { readonly __farmRouteData: infer TData }\n ? TData\n : never;\n\ntype NormalizeOptimisticUpdate<TUpdate> = TUpdate extends readonly [\n infer TRoute,\n unknown,\n (prev: any) => any,\n]\n ? TRoute extends RouteRef<any, any>\n ? [\n TRoute,\n InferRouteInput<TRoute> | undefined,\n (prev: InferRouteData<TRoute> | undefined) => InferRouteData<TRoute>,\n ]\n : never\n : TUpdate extends readonly [infer TKey, (prev: any) => any]\n ? TKey extends DefinedCacheKey<any, RouteDataCacheKey>\n ? [TKey, (prev: InferCacheKeyData<TKey> | undefined) => InferCacheKeyData<TKey>]\n : TKey extends CacheKey<infer TData>\n ? [TKey, (prev: TData | undefined) => TData]\n : TKey extends string\n ? [TKey, (prev: unknown) => unknown]\n : never\n : never;\n\ntype NormalizeOptimisticUpdates<TUpdates extends readonly unknown[]> = {\n [K in keyof TUpdates]: NormalizeOptimisticUpdate<TUpdates[K]>;\n};\n\ntype TypedEndpointLike = {\n __types: {\n body: any;\n query: any;\n response: any;\n errors?: any;\n };\n};\n\ntype Simplify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\ntype IsNever<T> = [T] extends [never] ? true : false;\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype RequiredKeys<T> = T extends object\n ? {\n [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n }[keyof T]\n : never;\n\ntype BodyInputProp<TValue> =\n IsNever<TValue> extends true\n ? {}\n : IsAny<TValue> extends true\n ? { body?: TValue }\n : undefined extends TValue\n ? { body?: TValue }\n : { body: TValue };\n\ntype QueryInputProp<TValue> =\n IsNever<TValue> extends true\n ? {}\n : IsAny<TValue> extends true\n ? { query?: TValue }\n : undefined extends TValue\n ? { query?: TValue }\n : RequiredKeys<TValue> extends never\n ? { query?: TValue }\n : { query: TValue };\n\ntype HasRequiredKeys<T> = RequiredKeys<T> extends never ? false : true;\n\n// Type utilities to extract endpoint input/output types from TypedEndpoint\ntype InferEndpointBody<T> = T extends {\n __types: {\n inputBody: infer TInputBody;\n };\n}\n ? TInputBody\n : T extends {\n __types: {\n body: infer TBody;\n };\n }\n ? TBody\n : never;\n\ntype InferEndpointInput<T> = T extends {\n __types: {\n query: infer TQuery;\n };\n}\n ? Simplify<\n BodyInputProp<InferEndpointBody<T>> &\n QueryInputProp<T extends { __types: { inputQuery: infer I } } ? I : TQuery> &\n (T extends { __routeParams: infer P }\n ? keyof P extends never\n ? { params?: never }\n : { params: P }\n : {}) &\n (T extends { __types: { inputHeaders: infer H } }\n ? IsNever<H> extends true\n ? {}\n : RequiredKeys<H> extends never\n ? { headers?: H }\n : { headers: H }\n : {})\n >\n : T extends { __routeParams: infer P }\n ? keyof P extends never\n ? { params?: never }\n : { params: P }\n : {};\n\ntype InferEndpointOutput<T> = T extends {\n __types: {\n response: infer R;\n };\n}\n ? R extends { readonly __farmStreamItem: infer TItem }\n ? FarmAPIStream<TItem>\n : R\n : any;\n\ntype InferEndpointError<T> = T extends {\n __types: {\n errors: infer TErrors;\n };\n}\n ? keyof TErrors extends never\n ? Error\n :\n | {\n [TCode in keyof TErrors]: TErrors[TCode] extends {\n data: infer TData;\n status: infer TStatus extends number;\n }\n ? APIClientError<TCode & string, TData, TStatus>\n : never;\n }[keyof TErrors]\n | APIClientSystemError\n : Error;\n\n// Type for a single endpoint method\ntype EndpointCall<T = any> = <TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]>(\n ...args: HasRequiredKeys<InferEndpointInput<T>> extends true\n ? [\n options: InferEndpointInput<T>,\n clientOptions?: ClientOptions<InferEndpointOutput<T>, InferEndpointError<T>, TUpdates>,\n ]\n : [\n options?: InferEndpointInput<T>,\n clientOptions?: ClientOptions<InferEndpointOutput<T>, InferEndpointError<T>, TUpdates>,\n ]\n) => Promise<APIResult<InferEndpointOutput<T>, InferEndpointError<T>>>;\ntype EndpointMethod<T = any> = EndpointCall<T> &\n RouteRef<InferEndpointOutput<T>, InferEndpointInput<T>>;\n\ntype DynamicKeys<T> = Extract<keyof T, `[${string}]`>;\ntype MethodKeys = \"get\" | \"head\" | \"query\" | \"post\" | \"put\" | \"patch\" | \"delete\" | \"options\";\ntype OwnMethodKeys<T> = {\n [K in Extract<keyof T, MethodKeys>]: T[K] extends TypedEndpointLike | ((...args: any[]) => any)\n ? K\n : never;\n}[Extract<keyof T, MethodKeys>];\ntype WithRouteParams<T, P> = T & { __routeParams: P };\ntype UnionToIntersection<U> = (U extends unknown ? (v: U) => void : never) extends (\n v: infer I,\n) => void\n ? I\n : never;\ntype ChildMethods<T> = { [K in DynamicKeys<T>]: OwnMethodKeys<T[K]> }[DynamicKeys<T>];\ntype MethodEndpoints<T, M extends PropertyKey, P> =\n | (M extends OwnMethodKeys<T> ? WithRouteParams<T[M], P> : never)\n | {\n [K in DynamicKeys<T>]: M extends keyof T[K]\n ? WithRouteParams<T[K][M], P & RoutePathParams<K>>\n : never;\n }[DynamicKeys<T>];\ntype DistributedCall<T> = T extends unknown ? EndpointCall<T> : never;\ntype ScopedMethod<T> = UnionToIntersection<DistributedCall<T>> &\n EndpointCall<T> &\n RouteRef<InferEndpointOutput<T>, InferEndpointInput<T>>;\n\n// Keep bracket access for compatibility; explicit binding preserves intermediate segments.\ntype RouterToClient<T, P = {}> = {\n [K in Exclude<keyof T, OwnMethodKeys<T>>]: T[K] extends TypedEndpointLike\n ? EndpointMethod<WithRouteParams<T[K], P>>\n : T[K] extends Record<string, any>\n ? RouterToClient<T[K], P & (K extends string ? RoutePathParams<K> : {})>\n : EndpointMethod<WithRouteParams<T[K], P>>;\n} & {\n [M in OwnMethodKeys<T> | ChildMethods<T>]: M extends ChildMethods<T>\n ? ScopedMethod<MethodEndpoints<T, M, P>>\n : M extends keyof T\n ? EndpointMethod<WithRouteParams<T[M], P>>\n : never;\n} & ([DynamicKeys<T>] extends [never]\n ? {}\n : {\n $params: UnionToIntersection<\n {\n [K in DynamicKeys<T>]: (params: RoutePathParams<K>) => RouterToClient<T[K], P>;\n }[DynamicKeys<T>]\n >;\n });\n\nexport type RouteAPIClient<TRouter extends Record<string, any>> = RouterToClient<TRouter>;\n\nexport type APIClient<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n> = RouteAPIClient<TRouter> & IntegrationClientRoot<TIntegrations>;\n\nexport type ServerAPIClient<\n TEndpoints extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n> = TEndpoints & IntegrationServerClientRoot<TIntegrations>;\n\nexport type ApiClients<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n> = {\n api: RouteAPIClient<TRouter> & IntegrationServerClientRoot<TIntegrations>;\n apiClient: APIClient<TRouter, TIntegrations>;\n};\n\n/**\n * Define one shared pair of typed callers. Import only generated route metadata\n * here, not endpoint modules. `api` dispatches locally during a Farm request;\n * `apiClient` uses HTTP. Both return the same app-route APIResult shape.\n */\nexport function createApiClients<TRouter extends Record<string, any>>(\n options: APIClientWithoutIntegrationsOptions,\n): { api: RouteAPIClient<TRouter>; apiClient: RouteAPIClient<TRouter> };\nexport function createApiClients<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(options?: APIClientOptions): ApiClients<TRouter, TIntegrations>;\nexport function createApiClients<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n): ApiClients<TRouter, TIntegrations> {\n // A module-level pair is safe across requests. No cache, credentials, or\n // dispatcher from one request is retained by another request's caller.\n const localScopes = new WeakMap<APIRequestRuntime, WeakMap<Request, { request: APICall }>>();\n const routeMeta = new WeakMap<AnyRouteRef, RouteMeta>();\n const api = createNestedProxy(\n [],\n async (path: string, method: string, input: any, clientOptions?: ClientOptions<any, any>) => {\n if (typeof window !== \"undefined\") {\n throw new Error(\n \"api is server-only. Use apiClient from createApiClients() in the browser.\",\n );\n }\n const currentRequest = _resolveCurrentRequest();\n const runtime = resolveAPIRequestRuntime();\n if (!currentRequest || !runtime) {\n throw new Error(\n \"api requires an active Farm server request. Call it from a server page, query, action, or API handler; use apiClient with an absolute baseURL for standalone HTTP calls.\",\n );\n }\n let localClients = localScopes.get(runtime);\n if (!localClients) {\n localClients = new WeakMap();\n localScopes.set(runtime, localClients);\n }\n let local = localClients.get(currentRequest);\n if (!local) {\n const origin = new URL(currentRequest.url).origin;\n const headers = new Headers();\n // Only identity/content negotiation headers are inherited. In\n // particular, never copy the outer request's body or hop-by-hop fields.\n for (const name of [\"cookie\", \"authorization\", \"accept-language\"]) {\n const value = currentRequest.headers.get(name);\n if (value !== null) headers.set(name, value);\n }\n local = createAPIClientRuntime(\n {\n ...options,\n integrations: false,\n baseURL: new URL(runtime.basePath, origin).toString(),\n },\n {\n headers,\n signal: currentRequest.signal,\n cache: new FarmClientDataCache({ subscribeToInvalidation: false }),\n routeMeta,\n fetch: (url, init) => {\n if (new URL(url).origin !== origin) {\n throw new Error(\n \"api can only dispatch to this Farm app. Use apiClient for HTTP calls.\",\n );\n }\n currentRequest.signal.throwIfAborted();\n return runtime.dispatch(new Request(url, init));\n },\n },\n );\n localClients.set(currentRequest, local);\n }\n return local.request(path, method, input, clientOptions);\n },\n routeMeta,\n \"/api\",\n true,\n options.integrations === false\n ? undefined\n : {\n integrations: integrationsServer<TIntegrations>({\n baseURL: options.baseURL,\n headers: options.headers,\n credentials: options.credentials,\n timeoutMs: options.timeoutMs,\n fetch: options.fetch,\n onRequest: options.onRequest,\n onResponse: options.onResponse,\n onError: options.onError,\n ...options.integrations,\n }),\n },\n options.routes ? new ClientRouteManifest(options.routes) : undefined,\n );\n return {\n api: api as ApiClients<TRouter, TIntegrations>[\"api\"],\n apiClient: createAPIClient<TRouter, TIntegrations>(options as APIClientOptions),\n };\n}\n\n/**\n * Create a typed RPC client for Farm.js API routes\n *\n * Returns a nested proxy that supports:\n * - api.hello.get({ query: { name: 'World' } })\n * - api['auth/login'].post({ body: { email: '...', password: '...' } })\n * - api.users.get({ query: { limit: '10' } })\n * - api.integrations.billing.checkout({ body: { priceId: 'price_...' } })\n *\n * @example\n * ```typescript\n * import { createAPIClient } from 'farm/client';\n * import type { APIRouter } from '@/api';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createAPIClient<APIRouter, AppIntegrations>();\n *\n * // Use it (nested property access)\n * const result = await api.hello.get({ query: { name: 'World' } });\n * if (result.error) console.error(result.error);\n * else console.log(result.data);\n *\n * // Or with string keys for nested paths\n * const result = await api['auth/login'].post({\n * body: { email: 'test@example.com', password: 'pass123' }\n * });\n *\n * // Integration APIs live under a reserved namespace.\n * const checkout = await api.integrations.billing.checkout({\n * body: { priceId: 'price_123' }\n * });\n * ```\n */\nexport function createAPIClient<TRouter extends Record<string, any>>(\n options: APIClientWithoutIntegrationsOptions,\n): RouteAPIClient<TRouter>;\nexport function createAPIClient<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(options?: APIClientOptions): APIClient<TRouter, TIntegrations>;\nexport function createAPIClient<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n): RouteAPIClient<TRouter> | APIClient<TRouter, TIntegrations> {\n return createAPIClientRuntime<TRouter, TIntegrations>(options).client;\n}\n\ntype APICall = (\n path: string,\n method: string,\n input?: any,\n options?: ClientOptions<any, any>,\n) => Promise<APIResult<any, Error>>;\n\nfunction createAPIClientRuntime<\n TRouter extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n transport?: {\n headers?: HeadersInit;\n signal?: AbortSignal;\n fetch(url: string, init: RequestInit): Promise<Response>;\n cache: FarmClientDataCache;\n routeMeta: WeakMap<AnyRouteRef, RouteMeta>;\n },\n): { client: APIClient<TRouter, TIntegrations>; request: APICall } {\n options ??= {};\n const baseURL = options.baseURL || getFarmAPIBaseURL();\n const httpFetch = options.fetch;\n const integrationOptions =\n options.integrations === false\n ? false\n : {\n baseURL: options.baseURL,\n headers: options.headers,\n credentials: options.credentials,\n timeoutMs: options.timeoutMs,\n fetch: httpFetch,\n onRequest: options.onRequest,\n onResponse: options.onResponse,\n onError: options.onError,\n ...(typeof options.integrations === \"object\" ? options.integrations : {}),\n };\n const rootAliases =\n integrationOptions === false\n ? undefined\n : {\n integrations: integrationsClient<TIntegrations>(integrationOptions),\n };\n\n const sharedCacheState = transport?.cache ?? getFarmClientDataCache();\n const localCaches = transport ? new Set([sharedCacheState]) : undefined;\n const sharedInflightState = new Map<string, InflightEntry>();\n let scopedRequestState: ScopedRequestState | undefined;\n const routeMeta = transport?.routeMeta ?? new WeakMap<AnyRouteRef, RouteMeta>();\n let requestCounter = 0;\n\n // Create a simple fetch-based client (browser compatible)\n const fetchClient = async (\n path: string,\n requestOptions: any,\n defaultHeaders: Headers,\n cancellation: ReturnType<typeof createClientCancellation>,\n ) => {\n const url = resolveFarmAPIRequestURL(path, baseURL);\n const method = String(requestOptions.method || \"GET\").toUpperCase();\n\n // Handle query parameters\n if (requestOptions.query) {\n Object.entries(requestOptions.query).forEach(([key, value]) => {\n if (value === undefined || value === null) return;\n url.searchParams.delete(key);\n const values = Array.isArray(value) ? value : [value];\n for (const item of values) {\n if (item !== undefined && item !== null) url.searchParams.append(key, String(item));\n }\n });\n }\n\n // Prepare fetch options\n const headers = new Headers(defaultHeaders);\n new Headers(requestOptions.headers).forEach((value, key) => headers.set(key, value));\n const fetchOptions: RequestInit = {\n method,\n headers,\n credentials: options.credentials,\n signal: cancellation.signal,\n };\n if (method === \"QUERY\" && !headers.has(\"content-type\")) {\n headers.set(\"content-type\", \"application/json\");\n }\n\n // Handle body\n if (requestOptions.body !== undefined) {\n if (isFormData(requestOptions.body)) {\n headers.delete(\"content-type\");\n fetchOptions.body = requestOptions.body;\n } else {\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n fetchOptions.body = JSON.stringify(requestOptions.body);\n }\n }\n\n cancellation.check();\n const response = await (transport?.fetch ?? httpFetch ?? fetch)(url.toString(), fetchOptions);\n cancellation.check();\n const invalidations = decodeFarmCacheInvalidations(\n response.headers?.get?.(FARM_CACHE_INVALIDATION_HEADER),\n );\n if (transport) {\n for (const cache of localCaches!) {\n for (const key of invalidations) cache.invalidate(key);\n }\n } else {\n applyFarmCacheInvalidations(invalidations);\n }\n let data: unknown;\n try {\n data = await readAPIResponseData(response, method);\n cancellation.check();\n } catch (decodeError) {\n if (!(decodeError instanceof APIResponseDecodeError)) throw decodeError;\n if (response.ok) throw decodeError.cause;\n return { response, data: undefined, decodeError: decodeError.cause };\n }\n\n return { response, data };\n };\n\n const request = async (\n path: string,\n method: string,\n input: any = {},\n clientOptions?: ClientOptions<any, any>,\n ): Promise<APIResult<any, Error>> => {\n const cancellation = createClientCancellation(\n clientOptions?.signal,\n clientOptions?.timeoutMs ?? options.timeoutMs,\n transport?.signal,\n );\n const normalizeCallError = (error: unknown): Error => {\n if (!cancellation.signal?.aborted) return normalizeError(error);\n const normalized = new APIClientError(\n cancellation.timedOut ? \"timeout\" : \"aborted\",\n undefined,\n {\n status: 0,\n message: cancellation.timedOut ? \"Client request timed out\" : \"Client request aborted\",\n },\n );\n (normalized as Error & { cause?: unknown }).cause = cancellation.signal.reason;\n return normalized;\n };\n try {\n const methodUpper = method.toUpperCase() as StatusEvent[\"method\"];\n const requestId = `${Date.now()}-${++requestCounter}`;\n const defaultHeaders = new Headers(transport?.headers);\n let requestContextError: Error | undefined;\n try {\n cancellation.check();\n const resolved = resolveClientHeaders(options.headers);\n const headers =\n resolved instanceof Headers ? resolved : await cancellation.run(() => resolved);\n cancellation.check();\n headers.forEach((value, name) => defaultHeaders.set(name, value));\n } catch (error) {\n requestContextError = normalizeCallError(error);\n }\n const cacheOptions = clientOptions?.cache\n ? {\n ...options.cacheDefaults,\n ...clientOptions.cache,\n }\n : undefined;\n const configuredCacheKey = clientOptions?.key ?? cacheOptions?.key;\n const cacheKey = normalizeFarmClientCacheKey(\n configuredCacheKey ?? buildCacheKey(methodUpper, path, input, baseURL, defaultHeaders),\n ) as CacheKey<any>;\n const now = Date.now();\n\n const emitStatus = (phase: StatusPhase, payload?: Partial<StatusEvent>) => {\n clientOptions?.onStatus?.({\n phase,\n requestId,\n method: methodUpper,\n key: cacheKey,\n input,\n timestamp: Date.now(),\n ...payload,\n });\n };\n\n const policy = cacheOptions?.policy ?? (cacheOptions ? \"cache-first\" : \"network-only\");\n const staleTime = cacheOptions?.staleTime ?? 0;\n const hasReliableDefaultCacheKey =\n methodUpper !== \"QUERY\" || !isFormData(input?.body) || configuredCacheKey !== undefined;\n const isCacheEnabled =\n Boolean(cacheOptions) &&\n (methodUpper === \"GET\" || methodUpper === \"QUERY\") &&\n hasReliableDefaultCacheKey;\n const needsCacheState =\n isCacheEnabled ||\n Boolean(clientOptions?.optimistic?.update?.length) ||\n Boolean(clientOptions?.invalidate);\n let requestCacheContext = requestContextError ? `invalid:${requestId}` : undefined;\n if (needsCacheState && !requestContextError) {\n try {\n requestCacheContext = getRequestCacheContext(\n { headers: defaultHeaders, credentials: options.credentials },\n input,\n // Custom transports can inject an identity outside visible headers.\n // Never share their cached data with other client instances.\n httpFetch ? \"client\" : cacheOptions?.scope,\n );\n } catch (error) {\n requestCacheContext = `invalid:${requestId}`;\n requestContextError = normalizeError(error);\n }\n }\n\n let cacheState = sharedCacheState;\n let inflightState = sharedInflightState;\n let requestScopedState: ScopedRequestState | undefined;\n if (requestCacheContext !== undefined) {\n if (scopedRequestState && scopedRequestState.context !== requestCacheContext) {\n scopedRequestState.retired = true;\n if (scopedRequestState.inflight.size === 0) scopedRequestState.cache.dispose();\n scopedRequestState = undefined;\n }\n scopedRequestState ??= {\n context: requestCacheContext,\n cache: new FarmClientDataCache({ subscribeToInvalidation: !transport }),\n inflight: new Map(),\n retired: false,\n };\n requestScopedState = scopedRequestState;\n cacheState = requestScopedState.cache;\n localCaches?.add(cacheState);\n inflightState = requestScopedState.inflight;\n }\n const optimisticState = getOptimisticState(cacheState);\n\n const entry = getValidCacheEntry(cacheState, cacheKey, now);\n const isStale = entry ? isEntryStale(entry, now) : true;\n\n const applyOptimisticUpdates = () => {\n if (!clientOptions?.optimistic?.update?.length) return [] as OptimisticSnapshot[];\n\n const snapshots = new Map<string, OptimisticSnapshot>();\n for (const update of clientOptions.optimistic.update) {\n const [target, targetInput, updater] =\n update.length === 2\n ? [update[0], undefined, update[1]]\n : [update[0], update[1], update[2]];\n const targetKey = resolveTargetKey(\n routeMeta,\n target,\n targetInput,\n baseURL,\n defaultHeaders,\n transport ? baseURL : undefined,\n );\n if (!targetKey) continue;\n\n const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n const currentEntry = cacheState.get(targetKey);\n let stack = optimisticState.get(targetKey);\n if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {\n stack = undefined;\n }\n if (!stack) {\n stack = {\n entry: targetEntry ? { ...targetEntry } : undefined,\n layers: [],\n renderedEntry: currentEntry,\n };\n optimisticState.set(targetKey, stack);\n }\n\n let snapshot = snapshots.get(targetKey);\n if (!snapshot) {\n const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;\n const layer: OptimisticLayer = {\n updaters: [],\n updatedAt: now,\n staleAt:\n targetEntry?.staleAt ??\n now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),\n gcAt:\n targetEntry?.gcAt ??\n getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime),\n };\n stack.layers.push(layer);\n snapshot = {\n key: targetKey,\n stack,\n layer,\n };\n snapshots.set(targetKey, snapshot);\n snapshot.layer.updaters.push(updater);\n const nextEntry = applyOptimisticLayer(previousEntry, {\n ...snapshot.layer,\n updaters: [updater],\n });\n storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n continue;\n }\n snapshot.layer.updaters.push(updater);\n const nextEntry = applyOptimisticLayer(stack.renderedEntry, {\n ...snapshot.layer,\n updaters: [updater],\n });\n storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n }\n\n return Array.from(snapshots.values());\n };\n\n const rollbackOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n if (!clientOptions?.optimistic?.rollbackOnError) return;\n settleOptimisticUpdates(cacheState, optimisticState, snapshots, \"rollback\");\n };\n\n const invalidateUncommittedOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n if (clientOptions?.optimistic?.rollbackOnError) return;\n for (const key of settleOptimisticUpdates(\n cacheState,\n optimisticState,\n snapshots,\n \"invalidate\",\n )) {\n emitStatus(\"invalidated\", { key });\n }\n };\n\n const executeNetwork = async (opts?: { isBackground?: boolean; callCallbacks?: boolean }) => {\n const release = cancellation.hold();\n let unsubscribeInvalidation: (() => void) | undefined;\n let readOwners: Map<string, object> | undefined;\n let readOwner: object | undefined;\n const resolvedCacheKey = cacheState.resolveKey(cacheKey);\n try {\n const dedupeMs = cacheOptions?.dedupeMs ?? 0;\n const inflight = inflightState.get(cacheKey);\n const allowDedupe =\n isCacheEnabled && dedupeMs > 0 && !cancellation.signal && !requestContextError;\n\n if (\n allowDedupe &&\n inflight &&\n !inflight.cancellable &&\n now - inflight.startedAt < dedupeMs\n ) {\n emitStatus(\"pending\", { isBackground: opts?.isBackground, data: entry?.data });\n const result = await inflight.promise;\n\n if (result.error) {\n emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n notifyClientObserver(options.onError, [result.error]);\n if (opts?.callCallbacks !== false) {\n clientOptions?.onError?.(result.error);\n }\n } else {\n emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n if (opts?.callCallbacks !== false) {\n clientOptions?.onSuccess?.(result.data as any);\n }\n }\n\n return result;\n }\n\n // Observe ordering, not wall-clock timestamps: invalidation can happen in the\n // same millisecond, or be cleared by another client's newer cache write.\n let invalidatedDuringRequest = false;\n if (isCacheEnabled) {\n // Transport deduplication is caller-local, but cache ownership must\n // span every caller writing to the same cache instance.\n readOwners = getCacheReadOwners(cacheState);\n readOwner = {};\n readOwners.set(resolvedCacheKey, readOwner);\n unsubscribeInvalidation = cacheState.subscribe(cacheKey, (event) => {\n if (event === \"invalidate\") invalidatedDuringRequest = true;\n });\n }\n emitStatus(opts?.isBackground ? \"revalidating\" : \"pending\", {\n isBackground: opts?.isBackground,\n });\n\n const promise = (async () => {\n const maxRetries = Math.max(0, clientOptions?.retry?.count ?? 0);\n let attempt = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (options.onRequest || clientOptions?.onRequest) {\n const requestEvent: RequestEvent = {\n requestId,\n method: methodUpper,\n key: cacheKey,\n path,\n input,\n attempt,\n timestamp: Date.now(),\n };\n notifyClientObserver(options.onRequest, [requestEvent]);\n clientOptions?.onRequest?.(requestEvent);\n }\n\n try {\n if (requestContextError) throw requestContextError;\n const { response, data, decodeError } = await cancellation.run(() =>\n fetchClient(\n path,\n {\n ...input,\n method: methodUpper,\n },\n defaultHeaders,\n cancellation,\n ),\n );\n\n const error = response.ok ? null : createResponseError(response, data, decodeError);\n\n const responseEvent: ResponseEvent<any, Error> = {\n requestId,\n method: methodUpper,\n key: cacheKey,\n path,\n input,\n attempt,\n timestamp: Date.now(),\n response,\n data: response.ok ? data : undefined,\n error: error ?? undefined,\n ok: response.ok,\n status: response.status,\n };\n\n notifyClientObserver(options.onResponse, [\n response.ok ? data : undefined,\n error,\n responseEvent,\n ]);\n notifyResponseObserver(\n clientOptions?.onResponse,\n response.ok ? data : undefined,\n error,\n responseEvent,\n );\n\n if (!error) {\n return { data, error: null, key: cacheKey } as APIResult<any, Error>;\n }\n\n if (attempt >= maxRetries) {\n return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n }\n } catch (err: any) {\n const error = normalizeCallError(err);\n const responseEvent: ResponseEvent<any, Error> = {\n requestId,\n method: methodUpper,\n key: cacheKey,\n path,\n input,\n attempt,\n timestamp: Date.now(),\n error,\n ok: false,\n };\n\n notifyClientObserver(options.onResponse, [undefined, error, responseEvent]);\n notifyResponseObserver(clientOptions?.onResponse, undefined, error, responseEvent);\n\n if (attempt >= maxRetries || requestContextError || cancellation.signal?.aborted) {\n return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n }\n }\n\n attempt += 1;\n const delay =\n typeof clientOptions?.retry?.delay === \"function\"\n ? clientOptions.retry.delay(attempt)\n : (clientOptions?.retry?.delay ?? 0);\n\n if (delay > 0) {\n try {\n await cancellation.delay(delay);\n } catch (error) {\n return { data: undefined, error: normalizeCallError(error), key: cacheKey };\n }\n }\n }\n })();\n\n const inflightEntry = {\n promise,\n startedAt: now,\n cancellable: !!cancellation.signal || !!requestContextError,\n };\n inflightState.set(cacheKey, inflightEntry);\n\n try {\n const result = await promise;\n\n if (\n inflightState.get(cacheKey) === inflightEntry &&\n readOwners?.get(resolvedCacheKey) === readOwner &&\n !invalidatedDuringRequest &&\n !result.error &&\n isCacheEnabled &&\n !isFarmAPIStream(result.data)\n ) {\n const updatedAt = Date.now();\n const cached: CacheEntry = {\n data: result.data,\n updatedAt,\n staleAt: updatedAt + staleTime,\n gcAt: getGcAt(updatedAt, cacheOptions?.gcTime),\n invalidatedAt: undefined,\n persist: cacheOptions?.persist === true ? true : undefined,\n [API_CACHE_REFETCH]: createCacheRefetch(\n request,\n path,\n method,\n input,\n cacheKey,\n cacheOptions!,\n clientOptions,\n options.onError,\n ),\n };\n cacheState.set(cacheKey, cached);\n }\n\n if (result.error) {\n emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n notifyClientObserver(options.onError, [result.error]);\n if (opts?.callCallbacks !== false) {\n clientOptions?.onError?.(result.error);\n }\n } else {\n emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n if (opts?.callCallbacks !== false) {\n clientOptions?.onSuccess?.(result.data as any);\n }\n }\n\n return result;\n } finally {\n if (inflightState.get(cacheKey) === inflightEntry) {\n inflightState.delete(cacheKey);\n }\n if (requestContextError && requestScopedState) {\n requestScopedState.retired = true;\n if (scopedRequestState === requestScopedState) scopedRequestState = undefined;\n }\n if (requestScopedState?.retired && requestScopedState.inflight.size === 0) {\n requestScopedState.cache.dispose();\n }\n }\n } finally {\n if (readOwner && readOwners?.get(resolvedCacheKey) === readOwner) {\n readOwners.delete(resolvedCacheKey);\n }\n unsubscribeInvalidation?.();\n release();\n }\n };\n\n const invalidateTargets = async () => {\n if (!clientOptions?.invalidate) return;\n\n const invalidateOptions = Array.isArray(clientOptions.invalidate)\n ? { targets: clientOptions.invalidate, refetch: false }\n : {\n targets: clientOptions.invalidate.targets,\n refetch: clientOptions.invalidate.refetch ?? false,\n };\n\n const refetches = new Set<() => void>();\n for (const target of invalidateOptions.targets) {\n const targetKey = resolveTargetKey(\n routeMeta,\n target,\n undefined,\n baseURL,\n defaultHeaders,\n transport ? baseURL : undefined,\n );\n if (!targetKey) continue;\n\n const existing = cacheState.get(targetKey);\n const invalidatedAt = Date.now();\n // The first read may still be in flight with no stored entry yet.\n // Notify its invalidation listener before it can cache an old result.\n cacheState.invalidate(targetKey, invalidatedAt);\n if (existing) {\n const stack = optimisticState.get(targetKey);\n if (stack?.renderedEntry === existing) {\n stack.invalidatedAt = invalidatedAt;\n stack.renderedEntry = cacheState.get(targetKey);\n }\n }\n\n emitStatus(\"invalidated\", { key: targetKey });\n\n const refetch = (existing as CacheEntry | undefined)?.[API_CACHE_REFETCH];\n if (invalidateOptions.refetch && refetch) {\n refetches.add(refetch);\n }\n }\n // Invalidate every alias before starting work; never replay this mutation.\n for (const refetch of refetches) refetch();\n };\n\n const optimisticSnapshots = requestContextError ? [] : applyOptimisticUpdates();\n\n if (isCacheEnabled && !requestContextError && !cancellation.signal?.aborted) {\n if (entry && !isStale && policy !== \"network-only\") {\n emitStatus(\"success\", { data: entry.data });\n clientOptions?.onSuccess?.(entry.data);\n clientOptions?.onSettled?.(entry.data, null);\n return { data: entry.data, error: null, key: cacheKey };\n }\n\n if (entry && isStale && policy === \"stale-while-revalidate\") {\n emitStatus(\"success\", { data: entry.data });\n clientOptions?.onSuccess?.(entry.data);\n clientOptions?.onSettled?.(entry.data, null);\n\n void executeNetwork({ isBackground: true, callCallbacks: false });\n return { data: entry.data, error: null, key: cacheKey };\n }\n }\n\n const result = await executeNetwork();\n if (result.error) {\n if (cancellation.signal?.aborted) {\n settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, \"rollback\");\n } else {\n rollbackOptimisticUpdates(optimisticSnapshots);\n invalidateUncommittedOptimisticUpdates(optimisticSnapshots);\n }\n } else {\n settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, \"commit\");\n await invalidateTargets();\n }\n clientOptions?.onSettled?.(result.data, result.error);\n return result;\n } finally {\n cancellation.dispose();\n }\n };\n\n // Return nested proxy (starts with empty path, user adds to it)\n const client = createNestedProxy(\n [],\n request,\n routeMeta,\n baseURL,\n isSameOriginAPIBaseURL(baseURL),\n rootAliases,\n options.routes ? new ClientRouteManifest(options.routes) : undefined,\n ) as APIClient<TRouter, TIntegrations>;\n return { client, request };\n}\n\nasync function readAPIResponseData(response: Response, method: string): Promise<unknown> {\n if (\n method === \"HEAD\" ||\n response.status === 204 ||\n response.status === 205 ||\n response.status === 304\n ) {\n return undefined;\n }\n\n // Keep lightweight fetch-compatible adapters working when they expose the\n // traditional json() contract without a complete Web Response implementation.\n if (!response.headers?.get && typeof response.json === \"function\") {\n return readResponseJSON(response);\n }\n\n if (response.body === null) return undefined;\n\n if (isJSONStreamResponse(response)) {\n return readJSONStream(response);\n }\n\n const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n if (typeof response.arrayBuffer === \"function\") {\n const data = await response.arrayBuffer();\n if (data.byteLength === 0) return undefined;\n\n if (!contentType || contentType === \"application/json\" || contentType.endsWith(\"+json\")) {\n return parseResponseJSON(new TextDecoder().decode(data));\n }\n\n if (\n contentType.startsWith(\"text/\") ||\n contentType === \"application/xml\" ||\n contentType === \"application/xhtml+xml\" ||\n contentType === \"application/graphql\"\n ) {\n return new TextDecoder().decode(data);\n }\n\n return data;\n }\n\n if (\n (!contentType || contentType === \"application/json\" || contentType.endsWith(\"+json\")) &&\n typeof response.json === \"function\"\n ) {\n return readResponseJSON(response);\n }\n\n if (\n (contentType?.startsWith(\"text/\") ||\n contentType === \"application/xml\" ||\n contentType === \"application/xhtml+xml\" ||\n contentType === \"application/graphql\") &&\n typeof response.text === \"function\"\n ) {\n return response.text();\n }\n\n // Some fetch-compatible adapters expose headers but still only implement\n // the traditional json() reader.\n if (typeof response.json === \"function\") {\n return readResponseJSON(response);\n }\n\n return undefined;\n}\n\nclass APIResponseDecodeError extends Error {\n readonly cause: unknown;\n\n constructor(cause: unknown) {\n super(cause instanceof Error ? cause.message : \"Failed to decode JSON response\");\n this.name = \"APIResponseDecodeError\";\n this.cause = cause;\n }\n}\n\nfunction parseResponseJSON(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch (error) {\n throw new APIResponseDecodeError(error);\n }\n}\n\nasync function readResponseJSON(response: Pick<Response, \"json\">): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n if (error instanceof SyntaxError) throw new APIResponseDecodeError(error);\n throw error;\n }\n}\n\n/**\n * Create a nested proxy that builds up the path\n *\n * Flow:\n * 1. api.hello -> Proxy(['hello'])\n * 2. api.hello.get -> Proxy(['hello', 'get'])\n * 3. api.hello.get({ query: {...} })\n * -> fetch('/api/hello', { method: 'GET', ... })\n *\n * For routes with single method:\n * 1. api.hello -> Proxy(['hello'])\n * 2. api.hello({ query: {...} })\n * -> fetch('/api/hello', ...)\n */\nfunction createNestedProxy(\n path: string[],\n client: any,\n routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n baseURL: string,\n sameOrigin: boolean,\n rootAliases?: Record<string, unknown>,\n manifest?: ClientRouteManifest,\n bound: BoundRouteParams = {},\n): any {\n const target = () => {};\n const proxy = new Proxy(target, {\n // When accessing a property (api.hello)\n get(_target, prop: string | symbol) {\n if (prop === \"$params\") {\n return (params: unknown) => {\n if (!manifest)\n throw new TypeError(\n \"$params requires createAPIClient({ routes: apiRoutes }) from the generated API manifest.\",\n );\n const scope = manifest.bind(buildProxyRoutePath(path), params);\n return createNestedProxy(\n [...path, scope.segment],\n client,\n routeMeta,\n baseURL,\n sameOrigin,\n rootAliases,\n manifest,\n Object.freeze({ ...bound, ...scope.params }),\n );\n };\n }\n if (prop === FARM_API_ROUTE_REF_SYMBOL) {\n return path.length > 0;\n }\n if (prop === FARM_API_ROUTE_META_SYMBOL) {\n let metadata;\n try {\n metadata = resolveRouteMeta({ path, baseURL, manifest, bound });\n } catch {\n return null;\n } // An unbound/overloaded route has no single URL yet.\n const requestURL = resolveFarmAPIRequestURL(metadata.routePath, baseURL);\n return Object.freeze({\n path: `${requestURL.pathname}${requestURL.search}${requestURL.hash}`,\n method: metadata.method,\n baseURL: requestURL.origin,\n sameOrigin,\n });\n }\n\n if (path.length === 0 && typeof prop === \"string\" && rootAliases && prop in rootAliases) {\n return rootAliases[prop];\n }\n\n if (typeof prop !== \"string\") {\n return Reflect.get(_target, prop);\n }\n\n // Add prop to path and return new proxy\n return createNestedProxy(\n [...path, prop],\n client,\n routeMeta,\n baseURL,\n sameOrigin,\n rootAliases,\n manifest,\n bound,\n );\n },\n\n // When calling as a function\n apply(_target, _thisArg, args) {\n // Check if the last part is an HTTP method\n const lastPart = path[path.length - 1];\n const httpMethods = [\"get\", \"head\", \"query\", \"post\", \"put\", \"delete\", \"patch\", \"options\"];\n\n if (httpMethods.includes(lastPart)) {\n // Method is explicitly called: api.users.get() or api['auth/login'].post()\n // Remove the method from path and use it as the HTTP method\n const routePath = buildProxyRoutePath(path.slice(0, -1));\n const method = lastPart.toUpperCase();\n\n // Extract options from arguments\n const [options, clientOptions] = args;\n\n // Call fetch client with explicit method\n const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;\n if (!manifest && options?.params)\n throw new TypeError(\"Dynamic params require the generated routes manifest.\");\n return client(resolved, method, options, clientOptions);\n } else {\n // Direct call without method: api.hello()\n // Use the full path and let the server determine the method (usually GET)\n const routePath = buildProxyRoutePath(path);\n\n // Extract options from arguments\n const [options, clientOptions] = args;\n\n // Call fetch client (default method will be GET)\n const method = options?.method || \"GET\";\n const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;\n return client(resolved, method, options, clientOptions);\n }\n },\n });\n\n routeMeta.set(proxy, { path: [...path], baseURL, manifest, bound });\n return proxy;\n}\n\nfunction buildProxyRoutePath(path: string[]): string {\n return \"/api/\" + path.join(\"/\").replace(/^\\/+/, \"\");\n}\n\nexport function isAPIRouteRef(value: unknown): value is CallableRouteRef {\n return (\n typeof value === \"function\" &&\n (value as { [FARM_API_ROUTE_REF_SYMBOL]?: unknown })[FARM_API_ROUTE_REF_SYMBOL] === true\n );\n}\n\nexport function getAPIRouteRefMetadata(value: unknown): APIRouteRefMetadata | null {\n if (!isAPIRouteRef(value)) return null;\n const metadata = (value as { [FARM_API_ROUTE_META_SYMBOL]?: unknown })[\n FARM_API_ROUTE_META_SYMBOL\n ];\n if (!metadata || typeof metadata !== \"object\") return null;\n\n const candidate = metadata as Partial<APIRouteRefMetadata>;\n if (\n typeof candidate.path !== \"string\" ||\n typeof candidate.method !== \"string\" ||\n typeof candidate.baseURL !== \"string\" ||\n typeof candidate.sameOrigin !== \"boolean\"\n ) {\n return null;\n }\n\n return {\n path: candidate.path,\n method: candidate.method,\n baseURL: candidate.baseURL,\n sameOrigin: candidate.sameOrigin,\n };\n}\n\n/**\n * Server-side API client that calls endpoints directly as functions\n * No HTTP overhead for app endpoints, and registered integration routes can be exposed at\n * api.integrations.* where Farm can dispatch them directly to the integration handler.\n *\n * @example\n * ```typescript\n * import { createServerAPIClient } from 'farm/client';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createServerAPIClient<{}, AppIntegrations>({});\n *\n * const result = await api.integrations.billing.status();\n * ```\n */\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n endpoints: TEndpoints,\n): TEndpoints;\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n endpoints: TEndpoints,\n options: ServerAPIClientWithoutIntegrationsOptions,\n): TEndpoints;\nexport function createServerAPIClient<\n TEndpoints extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n endpoints: TEndpoints,\n options?: ServerAPIClientOptions,\n): ServerAPIClient<TEndpoints, TIntegrations>;\nexport function createServerAPIClient<\n TEndpoints extends Record<string, any>,\n TIntegrations extends Record<string, any> = {},\n>(\n endpoints: TEndpoints,\n options: ServerAPIClientOptions | ServerAPIClientWithoutIntegrationsOptions = {},\n): TEndpoints | ServerAPIClient<TEndpoints, TIntegrations> {\n if (\n options.integrations === false ||\n Object.prototype.hasOwnProperty.call(endpoints, \"integrations\")\n ) {\n return endpoints;\n }\n\n Object.defineProperty(endpoints, \"integrations\", {\n get() {\n return integrationsServer<TIntegrations>(\n typeof options.integrations === \"object\" ? options.integrations : {},\n );\n },\n enumerable: false,\n configurable: true,\n });\n\n return endpoints as ServerAPIClient<TEndpoints, TIntegrations>;\n}\n\nconst API_CACHE_REFETCH = Symbol.for(\"farm.api.cache-refetch\");\ntype CacheEntry = FarmClientCacheEntry<any> & {\n [API_CACHE_REFETCH]?: () => void;\n};\n\n// Keep the read recipe on its cache entry, so deletion/GC also releases it.\n// This separate closure must not retain the original request's entry or signal.\nfunction createCacheRefetch(\n request: APICall,\n path: string,\n method: string,\n input: unknown,\n key: string,\n cache: CacheOptions,\n options: ClientOptions<any, any> | undefined,\n onError: APIClientOptions[\"onError\"],\n): () => void {\n const readOptions: ClientOptions<any, any> = {\n cache: { ...cache, key, policy: \"network-only\", dedupeMs: 0 },\n retry: options?.retry,\n timeoutMs: options?.timeoutMs,\n };\n return () => {\n // A new call resolves current defaults and owns a fresh deadline. Do not\n // retain prior signals, mutation options, or per-call completion callbacks.\n void request(path, method, input, readOptions).catch((error) => {\n notifyClientObserver(onError, [normalizeError(error)]);\n });\n };\n}\n\ntype InflightEntry = {\n cancellable?: boolean;\n promise: Promise<APIResult<any, Error>>;\n startedAt: number;\n};\n\ntype ScopedRequestState = {\n context: string;\n cache: FarmClientDataCache;\n inflight: Map<string, InflightEntry>;\n retired: boolean;\n};\n\ntype RouteMeta = {\n path: string[];\n baseURL: string;\n manifest?: ClientRouteManifest;\n bound?: BoundRouteParams;\n};\n\ntype OptimisticSnapshot = {\n key: string;\n stack: OptimisticStack;\n layer: OptimisticLayer;\n};\n\ntype OptimisticStack = {\n entry?: CacheEntry;\n layers: OptimisticLayer[];\n renderedEntry?: CacheEntry;\n invalidatedAt?: number;\n};\n\ntype OptimisticLayer = {\n updaters: Array<(prev: any) => any>;\n updatedAt: number;\n staleAt: number;\n gcAt?: number;\n committed?: boolean;\n};\n\nconst optimisticStates = new WeakMap<FarmClientDataCache, Map<string, OptimisticStack>>();\nconst cacheReadOwners = new WeakMap<FarmClientDataCache, Map<string, object>>();\n\nfunction getCacheReadOwners(cache: FarmClientDataCache): Map<string, object> {\n let owners = cacheReadOwners.get(cache);\n if (!owners) {\n owners = new Map();\n cacheReadOwners.set(cache, owners);\n }\n return owners;\n}\n\nfunction getOptimisticState(cache: FarmClientDataCache): Map<string, OptimisticStack> {\n let state = optimisticStates.get(cache);\n if (!state) {\n state = new Map();\n optimisticStates.set(cache, state);\n }\n return state;\n}\n\nfunction applyOptimisticLayer(entry: CacheEntry | undefined, layer: OptimisticLayer): CacheEntry {\n let data = entry?.data;\n for (const updater of layer.updaters) data = updater(data);\n\n return {\n data,\n updatedAt: layer.updatedAt,\n staleAt: entry?.staleAt ?? layer.staleAt,\n gcAt: entry?.gcAt ?? layer.gcAt,\n invalidatedAt: entry?.invalidatedAt,\n [API_CACHE_REFETCH]: entry?.[API_CACHE_REFETCH],\n };\n}\n\nfunction storeOptimisticEntry(\n cacheState: FarmClientDataCache,\n key: string,\n stack: OptimisticStack,\n entry: CacheEntry | undefined,\n): void {\n if (!entry) {\n cacheState.delete(key);\n stack.renderedEntry = undefined;\n return;\n }\n\n cacheState.set(key, entry);\n if (stack.invalidatedAt !== undefined) {\n cacheState.invalidate(key, stack.invalidatedAt);\n }\n stack.renderedEntry = cacheState.get(key);\n}\n\nfunction reconcileOptimisticInvalidation(\n cacheState: FarmClientDataCache,\n key: string,\n stack: OptimisticStack,\n): boolean {\n const current = cacheState.get(key);\n const rendered = stack.renderedEntry;\n if (current === rendered) return true;\n if (\n !current ||\n !rendered ||\n current.data !== rendered.data ||\n current.updatedAt !== rendered.updatedAt ||\n current.gcAt !== rendered.gcAt ||\n current.status !== rendered.status ||\n current.error !== rendered.error ||\n current.fetching !== rendered.fetching ||\n current.staleAt !== 0 ||\n current.invalidatedAt === undefined\n ) {\n return false;\n }\n\n stack.invalidatedAt = current.invalidatedAt;\n stack.renderedEntry = current;\n return true;\n}\n\nfunction renderOptimisticStack(\n cacheState: FarmClientDataCache,\n key: string,\n stack: OptimisticStack,\n): void {\n let entry = stack.entry ? { ...stack.entry } : undefined;\n for (const layer of stack.layers) entry = applyOptimisticLayer(entry, layer);\n storeOptimisticEntry(cacheState, key, stack, entry);\n}\n\nfunction settleOptimisticUpdates(\n cacheState: FarmClientDataCache,\n optimisticState: Map<string, OptimisticStack>,\n snapshots: OptimisticSnapshot[],\n outcome: \"commit\" | \"rollback\" | \"invalidate\",\n): string[] {\n const settledKeys: string[] = [];\n for (const snapshot of snapshots) {\n const stack = optimisticState.get(snapshot.key);\n if (stack !== snapshot.stack) continue;\n if (!reconcileOptimisticInvalidation(cacheState, snapshot.key, stack)) {\n optimisticState.delete(snapshot.key);\n continue;\n }\n\n if (outcome === \"rollback\") {\n stack.layers = stack.layers.filter((layer) => layer !== snapshot.layer);\n } else {\n snapshot.layer.committed = true;\n if (outcome === \"invalidate\") stack.invalidatedAt = Date.now();\n }\n\n while (stack.layers[0]?.committed) {\n stack.entry = applyOptimisticLayer(stack.entry, stack.layers.shift()!);\n }\n\n renderOptimisticStack(cacheState, snapshot.key, stack);\n if (stack.layers.length === 0) optimisticState.delete(snapshot.key);\n settledKeys.push(snapshot.key);\n }\n return settledKeys;\n}\n\n/**\n * @internal Apply key-targeted optimistic updates to the shared client cache\n * for a server-function mutation. Route-reference update tuples need an API\n * caller's route metadata and are skipped here; use structured cache keys.\n */\nexport function applyServerFnOptimisticUpdates(\n updates: readonly OptimisticUpdate[],\n now = Date.now(),\n): OptimisticSnapshot[] {\n const cacheState = getFarmClientDataCache();\n const optimisticState = getOptimisticState(cacheState);\n const snapshots = new Map<string, OptimisticSnapshot>();\n\n for (const update of updates) {\n if (update.length !== 2) continue;\n const [target, updater] = update;\n if (typeof updater !== \"function\") continue;\n const targetKey =\n typeof target === \"string\" || Array.isArray(target)\n ? normalizeFarmClientCacheKey(target as FarmClientCacheKey)\n : null;\n if (!targetKey) continue;\n\n const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n const currentEntry = cacheState.get(targetKey);\n let stack = optimisticState.get(targetKey);\n if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {\n stack = undefined;\n }\n if (!stack) {\n stack = {\n entry: targetEntry ? { ...targetEntry } : undefined,\n layers: [],\n renderedEntry: currentEntry,\n };\n optimisticState.set(targetKey, stack);\n }\n\n let snapshot = snapshots.get(targetKey);\n if (!snapshot) {\n const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;\n const layer: OptimisticLayer = {\n updaters: [],\n updatedAt: now,\n // A server function has no cache policy of its own; preserve the\n // target read's freshness metadata when it exists.\n staleAt: targetEntry?.staleAt ?? now,\n gcAt: targetEntry?.gcAt,\n };\n stack.layers.push(layer);\n snapshot = { key: targetKey, stack, layer };\n snapshots.set(targetKey, snapshot);\n snapshot.layer.updaters.push(updater);\n const nextEntry = applyOptimisticLayer(previousEntry, {\n ...snapshot.layer,\n updaters: [updater],\n });\n storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n continue;\n }\n snapshot.layer.updaters.push(updater);\n const nextEntry = applyOptimisticLayer(stack.renderedEntry, {\n ...snapshot.layer,\n updaters: [updater],\n });\n storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n }\n\n return Array.from(snapshots.values());\n}\n\n/**\n * @internal Settle a server-function mutation's optimistic snapshots with the\n * API client's semantics: commit on success, rollback on failure with\n * `rollbackOnError`, and mark-stale on failure without it.\n */\nexport function settleServerFnOptimisticUpdates(\n snapshots: OptimisticSnapshot[],\n outcome: \"commit\" | \"rollback\" | \"invalidate\",\n): void {\n if (snapshots.length === 0) return;\n const cacheState = getFarmClientDataCache();\n settleOptimisticUpdates(cacheState, getOptimisticState(cacheState), snapshots, outcome);\n}\n\n/**\n * @internal Resolve a server-function mutation's invalidate targets to cache\n * keys. Route-reference and path targets need an API caller's identity and are\n * skipped; use structured cache keys. Keys are applied through the shared\n * invalidation bus, matching server-declared `invalidates`.\n */\nexport function resolveServerFnInvalidateTargets(invalidate: InvalidateOptions): string[] {\n const targets = Array.isArray(invalidate) ? invalidate : invalidate.targets;\n const keys: string[] = [];\n for (const target of targets) {\n if (typeof target === \"string\" || Array.isArray(target)) {\n if (Array.isArray(target) && typeof target[0] === \"function\") continue;\n keys.push(normalizeFarmClientCacheKey(target as FarmClientCacheKey));\n } else if (target && typeof target === \"object\" && \"key\" in target) {\n keys.push(normalizeFarmClientCacheKey(target.key));\n }\n }\n return keys;\n}\n\nfunction buildCacheKey(\n method: string,\n path: string,\n input: any,\n baseURL: string,\n defaultHeaders?: HeadersInit,\n): string {\n const keyInput =\n input && typeof input === \"object\"\n ? {\n query: input.query,\n body: input.body,\n ...(method === \"QUERY\"\n ? {\n contentType:\n getHeader(input.headers, \"content-type\") ??\n getHeader(defaultHeaders, \"content-type\") ??\n \"application/json\",\n contentEncoding:\n getHeader(input.headers, \"content-encoding\") ??\n getHeader(defaultHeaders, \"content-encoding\"),\n }\n : {}),\n }\n : input;\n const url = resolveFarmAPIRequestURL(path, baseURL);\n return `${method}:${url.origin}${url.pathname}:${stableStringify(keyInput ?? {})}`;\n}\n\nfunction isSameOriginAPIBaseURL(baseURL: string): boolean {\n if (typeof window === \"undefined\") return baseURL.startsWith(\"/\");\n return resolveFarmAPIRequestURL(\"/api\", baseURL).origin === window.location.origin;\n}\n\nfunction stableStringify(value: any): string {\n if (value === null || value === undefined) return String(value);\n if (value instanceof Date) return value.toISOString();\n if (typeof value !== \"object\") return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n\n const keys = Object.keys(value).sort();\n const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);\n return `{${entries.join(\",\")}}`;\n}\n\nfunction getHeader(headers: unknown, name: string): string | undefined {\n if (!headers || typeof headers !== \"object\") return undefined;\n\n if (typeof Headers !== \"undefined\" && headers instanceof Headers) {\n return headers.get(name) ?? undefined;\n }\n\n const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);\n return entry?.[1] === undefined ? undefined : String(entry[1]);\n}\n\nfunction getRequestCacheContext(\n options: { headers?: HeadersInit; credentials?: RequestCredentials },\n input: unknown,\n scope: CacheScope | undefined,\n): string | undefined {\n const credentials = options.credentials ?? \"same-origin\";\n const headers = new Headers(options.headers);\n const requestHeaders =\n input && typeof input === \"object\" && \"headers\" in input ? input.headers : undefined;\n\n if (requestHeaders) {\n new Headers(requestHeaders as HeadersInit).forEach((value, key) => headers.set(key, value));\n }\n\n const carriesBrowserIdentity = credentials !== \"omit\" || [...headers].length > 0;\n if (scope !== \"client\" && !carriesBrowserIdentity) return undefined;\n\n return stableStringify({\n credentials,\n headers: [...headers].sort(([left], [right]) => left.localeCompare(right)),\n });\n}\n\nfunction getGcAt(now: number, gcTime?: number): number | undefined {\n if (gcTime === undefined) return undefined;\n if (!Number.isFinite(gcTime) || gcTime <= 0) return now;\n return now + gcTime;\n}\n\nfunction getValidCacheEntry(\n cacheState: FarmClientDataCache,\n key: string,\n now: number,\n): CacheEntry | undefined {\n const entry = cacheState.get(key);\n if (!entry) return undefined;\n\n if (entry.gcAt !== undefined && now >= entry.gcAt) {\n cacheState.delete(key);\n return undefined;\n }\n\n return entry;\n}\n\nfunction isEntryStale(entry: CacheEntry, now: number): boolean {\n if (entry.invalidatedAt !== undefined) return true;\n return now >= entry.staleAt;\n}\n\nfunction resolveTargetKey(\n routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n target: InvalidateTarget | AnyRouteRef,\n input?: unknown,\n baseURL = \"http://localhost:3000\",\n defaultHeaders?: HeadersInit,\n localBaseURL?: string,\n): string | null {\n if (!target) return null;\n\n if (typeof target === \"string\") return target;\n\n if (typeof target === \"function\") {\n const meta = routeMeta.get(target);\n if (!meta) return null;\n\n const { method, routePath } = resolveRouteMeta(meta, input);\n return buildCacheKey(\n method,\n routePath,\n input ?? {},\n localBaseURL ?? meta.baseURL,\n defaultHeaders,\n );\n }\n\n if (Array.isArray(target)) {\n const [route, routeInput] = target;\n if (typeof route === \"function\") {\n return resolveTargetKey(routeMeta, route, routeInput, baseURL, defaultHeaders, localBaseURL);\n }\n return normalizeFarmClientCacheKey(target);\n }\n\n if (\"key\" in target) return normalizeFarmClientCacheKey(target.key);\n\n if (\"path\" in target) {\n const method = target.method ?? \"GET\";\n return buildCacheKey(method, target.path, target.input ?? {}, baseURL, defaultHeaders);\n }\n\n return null;\n}\n\nfunction resolveRouteMeta(meta: RouteMeta, input?: any): { routePath: string; method: string } {\n const httpMethods = [\"get\", \"head\", \"query\", \"post\", \"put\", \"delete\", \"patch\", \"options\"];\n const lastPart = meta.path[meta.path.length - 1];\n if (lastPart && httpMethods.includes(lastPart)) {\n return {\n routePath: meta.manifest\n ? meta.manifest.resolve(\n buildProxyRoutePath(meta.path.slice(0, -1)),\n lastPart.toUpperCase(),\n meta.bound ?? {},\n input,\n )\n : buildProxyRoutePath(meta.path.slice(0, -1)),\n method: lastPart.toUpperCase(),\n };\n }\n\n return {\n routePath: meta.manifest\n ? meta.manifest.resolve(buildProxyRoutePath(meta.path), \"GET\", meta.bound ?? {}, input)\n : buildProxyRoutePath(meta.path),\n method: \"GET\",\n };\n}\n\nfunction normalizeError(error: unknown): Error {\n if (error instanceof APIClientError) return error;\n\n const normalized = new APIClientError(\"network_error\", undefined, {\n status: 0,\n message:\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"Network request failed\",\n });\n (normalized as Error & { cause?: unknown }).cause = error;\n return normalized;\n}\n\nfunction notifyResponseObserver(\n observer: ClientOptions<any, any>[\"onResponse\"],\n data: unknown,\n error: unknown,\n event: ResponseEvent<any, any>,\n): void {\n notifyClientObserver(observer, [data, error, event], \"API client onResponse\");\n}\n\nfunction isFormData(value: unknown): value is FormData {\n return (\n typeof value === \"object\" &&\n value !== null &&\n ((typeof FormData !== \"undefined\" && value instanceof FormData) ||\n (Object.prototype.toString.call(value) === \"[object FormData]\" &&\n typeof (value as { entries?: unknown }).entries === \"function\"))\n );\n}\n\nfunction createResponseError(response: Response, data: any, cause?: unknown): Error {\n const expected = readEndpointErrorEnvelope(data);\n if (expected) {\n return new APIClientError(expected.code, expected.data, {\n status: response.status,\n message: expected.message,\n response,\n });\n }\n\n const error = new APIClientError(\"http_error\", data, {\n status: response.status,\n message: `HTTP ${response.status}: ${response.statusText}`,\n response,\n });\n if (cause !== undefined) (error as Error & { cause?: unknown }).cause = cause;\n return error;\n}\n\nfunction readEndpointErrorEnvelope(data: unknown): {\n code: string;\n message: string;\n data: unknown;\n} | null {\n if (!data || typeof data !== \"object\") return null;\n const error = (data as { error?: unknown }).error;\n if (!error || typeof error !== \"object\") return null;\n\n const code = (error as { code?: unknown }).code;\n const message = (error as { message?: unknown }).message;\n if (typeof code !== \"string\" || typeof message !== \"string\") return null;\n\n return {\n code,\n message,\n data: (error as { data?: unknown }).data,\n };\n}\n","import { matchAPIRoute, parseDynamicSegment } from \"./route-pattern\";\n\nexport type APIRouteManifest = readonly {\n readonly path: string;\n readonly methods: readonly string[];\n}[];\nexport type BoundRouteParams = Readonly<Record<string, string | readonly string[]>>;\n\n/** A schema-free lookup shared by every immutable scope of one API client. */\nexport class ClientRouteManifest {\n readonly routes: Map<string, APIRouteManifest[number]>;\n constructor(routes: APIRouteManifest) {\n this.routes = new Map(\n routes.map((route) => [\n route.path.replace(/\\/$/, \"\"),\n {\n path: route.path.replace(/\\/$/, \"\"),\n methods: [...route.methods],\n },\n ]),\n );\n }\n\n bind(path: string, input: unknown): { segment: string; params: BoundRouteParams } {\n const params = readParams(input);\n const prefix = `${path.replace(/\\/$/, \"\")}/`;\n const candidates = new Set(\n [...this.routes.keys()]\n .filter((route) => route.startsWith(prefix))\n .map((route) => route.slice(prefix.length).split(\"/\")[0])\n .filter((segment) => {\n const dynamic = parseDynamicSegment(segment);\n return (\n dynamic &&\n Object.keys(params).every((key) => key === dynamic.name) &&\n (Object.prototype.hasOwnProperty.call(params, dynamic.name) || dynamic.optional)\n );\n }),\n );\n if (candidates.size !== 1)\n throw new TypeError(\n `Cannot bind route params at ${path}: supply exactly the next dynamic segment's parameter.`,\n );\n const segment = [...candidates][0]!;\n const dynamic = parseDynamicSegment(segment)!;\n encodeParameter(dynamic, params[dynamic.name]);\n return {\n segment,\n params: Object.freeze(\n Object.fromEntries(\n Object.entries(params).map(([key, value]) => [\n key,\n Array.isArray(value) ? Object.freeze([...value]) : value,\n ]),\n ),\n ),\n };\n }\n\n resolve(\n path: string,\n method: string,\n bound: BoundRouteParams,\n input?: { params?: unknown },\n ): string {\n const normalized = path.replace(/\\/$/, \"\");\n const supplied = readParams(input?.params);\n const candidates = [...this.routes.values()].filter((route) => {\n if (route.path === normalized) return true;\n if (!route.path.startsWith(`${normalized}/`)) return false;\n const tail = route.path.slice(normalized.length + 1);\n return (\n !tail.includes(\"/\") && Boolean(parseDynamicSegment(tail)) && input?.params !== undefined\n );\n });\n const selected = candidates.filter((route) => {\n const unbound = route.path\n .split(\"/\")\n .map(parseDynamicSegment)\n .filter((part) => part && !Object.prototype.hasOwnProperty.call(bound, part.name));\n return (\n Object.keys(supplied).every((key) => unbound.some((part) => part!.name === key)) &&\n unbound.every(\n (part) => part!.optional || Object.prototype.hasOwnProperty.call(supplied, part!.name),\n )\n );\n });\n if (selected.length !== 1)\n throw new TypeError(\n `Cannot resolve ${method} ${normalized}: missing, unexpected, or ambiguous route params.`,\n );\n const route = selected[0]!;\n if (!route.methods.includes(method) && !(method === \"HEAD\" && route.methods.includes(\"GET\"))) {\n throw new TypeError(`${method} is not registered for ${route.path}.`);\n }\n const params = { ...bound, ...supplied };\n const resolved = route.path\n .split(\"/\")\n .map((segment) => {\n const dynamic = parseDynamicSegment(segment);\n return dynamic ? encodeParameter(dynamic, params[dynamic.name]) : segment;\n })\n .filter(Boolean)\n .join(\"/\");\n const pathname = `/${resolved}`;\n const winner = matchAPIRoute(this.routes, pathname);\n if (winner?.route.path !== route.path) {\n throw new TypeError(\n `Route ${route.path} resolves to ${pathname}, which is shadowed by ${winner?.route.path ?? \"another route\"}.`,\n );\n }\n return pathname;\n }\n}\n\nfunction readParams(input: unknown): Record<string, string | readonly string[]> {\n if (input === undefined) return {};\n if (\n !input ||\n typeof input !== \"object\" ||\n Array.isArray(input) ||\n ![Object.prototype, null].includes(Object.getPrototypeOf(input))\n ) {\n throw new TypeError(\"Route params must be a plain object.\");\n }\n for (const key of Object.keys(input)) {\n if ([\"__proto__\", \"constructor\", \"prototype\"].includes(key))\n throw new TypeError(`Unsafe route parameter ${key}.`);\n }\n return input as Record<string, string | readonly string[]>;\n}\n\nfunction encodeParameter(\n parameter: { name: string; catchAll: boolean; optional: boolean },\n value: unknown,\n): string {\n if (parameter.optional && value === undefined) return \"\";\n const parts = parameter.catchAll ? value : [value];\n if (!Array.isArray(parts) || (!parts.length && !parameter.optional)) {\n throw new TypeError(\n `Route parameter ${parameter.name} must be ${parameter.catchAll ? \"a non-empty array of strings\" : \"a string\"}.`,\n );\n }\n return Array.from(parts, (part) => {\n if (\n typeof part !== \"string\" ||\n !part ||\n part === \".\" ||\n part === \"..\" ||\n Array.from(part).some(\n (character) =>\n character.charCodeAt(0) <= 31 ||\n (character.charCodeAt(0) >= 127 && character.charCodeAt(0) <= 159),\n )\n ) {\n throw new TypeError(`Invalid value for route parameter ${parameter.name}.`);\n }\n return encodeURIComponent(part);\n }).join(\"/\");\n}\n","/** Browser-safe bridge: neither handlers nor Node.js imports cross this boundary. */\nexport interface APIRequestRuntime {\n basePath: string;\n dispatch(request: Request): Promise<Response>;\n}\n\nconst API_RUNTIME_RESOLVER = Symbol.for(\"farm.apiRequestRuntimeResolver\");\ntype RuntimeGlobal = typeof globalThis & {\n [API_RUNTIME_RESOLVER]?: () => APIRequestRuntime | undefined;\n};\n\nexport function setAPIRequestRuntimeResolver(resolver: () => APIRequestRuntime | undefined): void {\n (globalThis as RuntimeGlobal)[API_RUNTIME_RESOLVER] = resolver;\n}\n\nexport function resolveAPIRequestRuntime(): APIRequestRuntime | undefined {\n return (globalThis as RuntimeGlobal)[API_RUNTIME_RESOLVER]?.();\n}\n","import type { ServerResponse } from \"node:http\";\n\ninterface ResponseEventWatcher<T> {\n promise: Promise<T>;\n dispose(): void;\n}\n\n/**\n * Watch a real Node response without requiring every Node-compatible response\n * adapter or test double to extend EventEmitter. The framework only needs\n * disconnect handling when the response exposes both halves of the listener\n * lifecycle; otherwise callers can still send ordinary non-blocked bodies.\n */\nfunction watchResponseEvent<T>(\n res: ServerResponse,\n events: ReadonlyArray<readonly [event: string, value: T]>,\n): ResponseEventWatcher<T> | null {\n if (typeof res.once !== \"function\" || typeof res.removeListener !== \"function\") {\n return null;\n }\n\n let settled = false;\n const listeners = events.map(([event, value]) => {\n const listener = () => {\n if (settled) return;\n settled = true;\n dispose();\n resolvePromise(value);\n };\n return { event, listener };\n });\n let resolvePromise!: (value: T) => void;\n const promise = new Promise<T>((resolve) => {\n resolvePromise = resolve;\n for (const { event, listener } of listeners) {\n res.once(event, listener);\n }\n });\n const dispose = () => {\n for (const { event, listener } of listeners) {\n res.removeListener(event, listener);\n }\n };\n\n return { promise, dispose };\n}\n\n/**\n * Waits until the response can accept more writes. Resolves false when the\n * client is gone (close or error): a disconnected socket never emits drain,\n * so waiting on drain alone leaks the pending handler, its reader lock, and\n * the response body for the life of the process.\n */\nasync function waitForWritable(res: ServerResponse): Promise<boolean> {\n if (res.writableEnded || res.destroyed) {\n return false;\n }\n\n const watcher = watchResponseEvent(res, [\n [\"drain\", true],\n [\"close\", false],\n [\"error\", false],\n ]);\n if (!watcher) {\n return false;\n }\n\n try {\n return await watcher.promise;\n } finally {\n watcher.dispose();\n }\n}\n\n/**\n * Older Fetch implementations expose repeated Set-Cookie fields as one\n * comma-joined value. Split only at a comma followed by another cookie-pair;\n * commas inside Expires dates remain part of the current cookie. RFC cookie\n * values exclude commas, so a comma followed by a cookie-pair is unambiguous\n * for valid Set-Cookie syntax once the original field boundaries are lost.\n */\nfunction splitSetCookieHeader(value: string): string[] {\n const cookies: string[] = [];\n let start = 0;\n\n for (let index = 0; index < value.length; index += 1) {\n if (value[index] !== \",\") continue;\n\n let next = index + 1;\n while (value[next] === \" \" || value[next] === \"\\t\") next += 1;\n\n const equals = value.indexOf(\"=\", next);\n if (equals === -1) continue;\n\n const separator = value.slice(next, equals);\n if (separator.length === 0 || /[;,\\s]/.test(separator)) continue;\n\n cookies.push(value.slice(start, index).trim());\n start = next;\n index = next - 1;\n }\n\n cookies.push(value.slice(start).trim());\n return cookies.filter(Boolean);\n}\n\nexport function applyWebResponseHeaders(\n res: Pick<ServerResponse, \"setHeader\"> & Partial<Pick<ServerResponse, \"getHeader\">>,\n headers: Headers,\n options: { appendSetCookie?: boolean } = {},\n): void {\n const responseHeaders = headers as Headers & {\n getSetCookie?: () => string[];\n raw?: () => Record<string, string[]>;\n };\n const rawSetCookies = responseHeaders.raw?.()[\"set-cookie\"];\n const setCookies = responseHeaders.getSetCookie?.() || rawSetCookies || [];\n const existing =\n options.appendSetCookie && typeof res.getHeader === \"function\"\n ? res.getHeader(\"Set-Cookie\")\n : undefined;\n const existingCookies = Array.isArray(existing)\n ? existing.map(String)\n : existing === undefined\n ? []\n : [String(existing)];\n\n let fallbackSetCookie = \"\";\n headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\") {\n fallbackSetCookie = value;\n return;\n }\n res.setHeader(key, value);\n });\n\n const cookies =\n setCookies.length > 0\n ? setCookies\n : fallbackSetCookie\n ? splitSetCookieHeader(fallbackSetCookie)\n : [];\n if (cookies.length > 0) {\n res.setHeader(\"Set-Cookie\", [...existingCookies, ...cookies]);\n }\n}\n\nexport async function sendWebResponse(res: ServerResponse, response: Response): Promise<void> {\n res.statusCode = response.status;\n applyWebResponseHeaders(res, response.headers, { appendSetCookie: true });\n\n if (!response.body) {\n res.end();\n return;\n }\n\n if (typeof res.write !== \"function\") {\n const body = await response.arrayBuffer();\n res.end(Buffer.from(body));\n return;\n }\n\n const reader = response.body.getReader();\n const disconnectWatcher = watchResponseEvent(res, [\n [\"close\", true],\n [\"error\", true],\n ]);\n\n try {\n while (true) {\n if (res.destroyed) {\n // The client disconnected mid-response; drop the rest of the body so\n // the handler can return.\n void reader.cancel().catch(() => {});\n return;\n }\n\n const read = reader.read().then((result) => ({ type: \"read\" as const, result }));\n const next = disconnectWatcher\n ? await Promise.race([\n read,\n disconnectWatcher.promise.then(() => ({ type: \"disconnect\" as const })),\n ])\n : await read;\n if (next.type === \"disconnect\") {\n void reader.cancel().catch(() => {});\n return;\n }\n\n const { done, value } = next.result;\n if (done) {\n break;\n }\n\n if (!value || value.byteLength === 0) {\n continue;\n }\n\n if (!res.write(value)) {\n if (!(await waitForWritable(res))) {\n void reader.cancel().catch(() => {});\n return;\n }\n }\n }\n\n res.end();\n } catch (error) {\n // Releasing the lock does not stop the producer. Cancel it when the\n // downstream write fails, without waiting on app-owned cleanup or letting\n // a cancellation failure replace the original error.\n void reader.cancel(error).catch(() => {});\n if (!res.writableEnded) {\n const responseError = error instanceof Error ? error : new Error(String(error));\n if (typeof res.destroy === \"function\") {\n res.destroy(responseError);\n } else {\n res.end();\n }\n }\n throw error;\n } finally {\n disconnectWatcher?.dispose();\n try {\n reader.releaseLock();\n } catch {\n // A disconnect can win the race with a pending read. Cancelling the\n // reader settles it asynchronously, so there may be no lock to release\n // synchronously here.\n }\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nexport type AfterCallback = () => void | Promise<void>;\n\n/** Runtime hooks supplied by a deployment adapter. */\nexport interface FarmAfterPlatformContext {\n /** Keep a serverless invocation alive until the scheduled work settles. */\n waitUntil?: (promise: Promise<void>) => void;\n /** Register a callback that runs once the response has finished. */\n onResponseFinished?: (callback: () => void) => void;\n}\n\ninterface AfterTask {\n result: Promise<void>;\n start: () => void;\n}\n\ninterface AfterRequestState {\n completion: Promise<void>;\n finishResponse: () => void;\n phase: \"open\" | \"running\" | \"closed\";\n reportError: (error: unknown) => void;\n tasks: AfterTask[];\n}\n\nconst AFTER_STORAGE = Symbol.for(\"@farm.js/core/after-storage\");\n\nfunction getAfterStorage(): AsyncLocalStorage<AfterRequestState> {\n const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n const existing = runtime[AFTER_STORAGE];\n if (existing instanceof AsyncLocalStorage) {\n return existing as AsyncLocalStorage<AfterRequestState>;\n }\n\n const storage = new AsyncLocalStorage<AfterRequestState>();\n runtime[AFTER_STORAGE] = storage;\n return storage;\n}\n\nconst afterStorage = getAfterStorage();\n\nfunction defaultAfterErrorReporter(error: unknown): void {\n console.error(\"[Farm.js] after() callback failed:\", error);\n}\n\nfunction reportAfterError(state: AfterRequestState, error: unknown): void {\n try {\n state.reportError(error);\n } catch {\n // Error reporting must never interrupt the remaining post-response work.\n }\n}\n\nfunction createAfterRequestState(\n reportError: (error: unknown) => void = defaultAfterErrorReporter,\n): AfterRequestState {\n let resolveResponseFinished!: () => void;\n let responseFinished = false;\n const responseFinishedPromise = new Promise<void>((resolve) => {\n resolveResponseFinished = resolve;\n });\n\n const state: AfterRequestState = {\n completion: Promise.resolve(),\n finishResponse: () => {\n if (responseFinished) return;\n responseFinished = true;\n resolveResponseFinished();\n },\n phase: \"open\",\n reportError,\n tasks: [],\n };\n\n state.completion = responseFinishedPromise.then(() =>\n afterStorage.run(state, async () => {\n state.phase = \"running\";\n\n for (let index = 0; index < state.tasks.length; index++) {\n const task = state.tasks[index];\n task.start();\n try {\n await task.result;\n } catch (error) {\n reportAfterError(state, error);\n }\n }\n\n state.phase = \"closed\";\n }),\n );\n\n return state;\n}\n\nfunction registerPlatformLifetime(\n state: AfterRequestState,\n context: FarmAfterPlatformContext | undefined,\n): void {\n if (!context?.waitUntil) return;\n\n try {\n context.waitUntil(state.completion);\n } catch (error) {\n reportAfterError(state, error);\n }\n}\n\nfunction registerResponseFinishedHook(\n state: AfterRequestState,\n context: FarmAfterPlatformContext | undefined,\n): boolean {\n if (!context?.onResponseFinished) return false;\n\n try {\n context.onResponseFinished(state.finishResponse);\n return true;\n } catch (error) {\n reportAfterError(state, error);\n return false;\n }\n}\n\nfunction finishSoon(state: AfterRequestState): void {\n setTimeout(state.finishResponse, 0);\n}\n\nfunction wrapResponseBody(\n response: Response,\n request: Request,\n state: AfterRequestState,\n): Response {\n if (\n request.method === \"HEAD\" ||\n response.status < 200 ||\n response.status > 599 ||\n !response.body ||\n response.bodyUsed ||\n response.body.locked\n ) {\n finishSoon(state);\n return response;\n }\n\n const reader = response.body.getReader();\n let released = false;\n const releaseReader = () => {\n if (released) return;\n released = true;\n reader.releaseLock();\n };\n\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const chunk = await reader.read();\n if (chunk.done) {\n releaseReader();\n controller.close();\n finishSoon(state);\n return;\n }\n controller.enqueue(chunk.value);\n } catch (error) {\n releaseReader();\n controller.error(error);\n finishSoon(state);\n }\n },\n cancel(reason) {\n try {\n // Preserve the caller's cleanup promise, but response completion must\n // not depend on whether producer-owned cancellation ever settles.\n return reader.cancel(reason);\n } finally {\n releaseReader();\n finishSoon(state);\n }\n },\n });\n\n return new Response(body, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\n/**\n * Schedule non-blocking work for after the current response finishes.\n *\n * Callbacks run in registration order. A callback failure is reported without\n * changing the response or preventing later callbacks from running.\n */\nexport function after(callback: AfterCallback): void {\n if (typeof callback !== \"function\") {\n throw new TypeError(\"after() expects a callback function.\");\n }\n\n const state = afterStorage.getStore();\n if (!state) {\n throw new Error(\"after() can only be used while Farm is handling a server request.\");\n }\n if (state.phase === \"closed\") {\n throw new Error(\"after() cannot schedule work after the request lifecycle has completed.\");\n }\n\n let start!: () => void;\n const ready = new Promise<void>((resolve) => {\n start = resolve;\n });\n\n // Registering the continuation here preserves every request AsyncLocalStorage\n // context that is active at the after() call site.\n const result = ready.then(callback);\n state.tasks.push({ result, start });\n}\n\n/** @internal Run a Web Request handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterRequest(\n request: Request,\n handler: () => Response | Promise<Response>,\n context?: FarmAfterPlatformContext,\n): Promise<Response> {\n if (afterStorage.getStore()) {\n return await handler();\n }\n\n const state = createAfterRequestState();\n registerPlatformLifetime(state, context);\n const hasResponseHook = registerResponseFinishedHook(state, context);\n\n try {\n const response = await afterStorage.run(state, handler);\n return hasResponseHook ? response : wrapResponseBody(response, request, state);\n } catch (error) {\n // The handler threw, so there is no successful response for a\n // response-finished hook to fire on. Run the after-lifecycle now regardless\n // of the hook; otherwise a spec-compliant adapter (whose hook only fires on\n // a real response) never runs the registered after() callbacks and\n // waitUntil(state.completion) hangs forever. finishResponse is idempotent,\n // so a later hook firing (e.g. a Node error response's close) is a no-op.\n finishSoon(state);\n throw error;\n }\n}\n\n/** @internal Run a Node response handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterNodeResponse<T>(\n response: ServerResponse,\n handler: () => T | Promise<T>,\n context?: Pick<FarmAfterPlatformContext, \"waitUntil\">,\n): Promise<T> {\n if (afterStorage.getStore()) {\n return await handler();\n }\n\n const state = createAfterRequestState();\n let finished = false;\n const finish = () => {\n if (finished) return;\n finished = true;\n response.off(\"finish\", finish);\n response.off(\"close\", finish);\n state.finishResponse();\n };\n\n response.once(\"finish\", finish);\n response.once(\"close\", finish);\n if (response.writableEnded) finishSoon(state);\n registerPlatformLifetime(state, context);\n\n return await afterStorage.run(state, handler);\n}\n\n/** @internal Add Farm's post-response lifecycle to a Node middleware. */\nexport function _withAfterNodeMiddleware(\n handler: (\n request: IncomingMessage,\n response: ServerResponse,\n next: (error?: unknown) => void,\n ) => void | Promise<void>,\n): (\n request: IncomingMessage,\n response: ServerResponse,\n next: (error?: unknown) => void,\n) => Promise<void> {\n return async (request, response, next) => {\n await _runWithAfterNodeResponse(response, () => handler(request, response, next));\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { setAPIRequestRuntimeResolver, type APIRequestRuntime } from \"./server-client-bridge\";\n\nconst API_RUNTIME_STORAGE = Symbol.for(\"@farm.js/core/api-request-storage\");\nconst runtimeGlobal = globalThis as typeof globalThis & {\n [API_RUNTIME_STORAGE]?: AsyncLocalStorage<APIRequestRuntime>;\n};\nconst storage = (runtimeGlobal[API_RUNTIME_STORAGE] ??= new AsyncLocalStorage<APIRequestRuntime>());\nsetAPIRequestRuntimeResolver(() => storage.getStore());\n\n/** Bind the owning app's live route dispatcher, never a process-wide route table. */\nexport function _runWithAPIRequestRuntime<T>(runtime: APIRequestRuntime, run: () => T): T {\n return storage.run(runtime, run);\n}\n","/**\n * Farm.js API Routes Vite Plugin\n *\n * Standalone API route support that works with any Vite setup.\n * Discovers and handles route.ts files in the api directory.\n * Also supports root routes.ts for custom route definitions.\n *\n * @example\n * ```ts\n * import { farmApiPlugin } from '@farm.js/core'\n *\n * export default defineConfig({\n * plugins: [farmApiPlugin({ srcDir: 'src' })],\n * })\n * ```\n */\n\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport {\n APIRouteConflictError,\n API_ROUTE_METHODS,\n getAllowedAPIRouteMethods,\n invokeAPIRouteEndpoint,\n resolveAPIRouteEndpoint,\n} from \"./route-manager\";\nimport { matchAPIRouteAtBasePath } from \"./runtime\";\nimport { sendWebResponse } from \"../server/response\";\nimport { isFarmAPIRouteFileName } from \"./route-files\";\nimport { _withAfterNodeMiddleware } from \"../after\";\nimport { _runWithAPIRequestRuntime } from \"./server-context\";\nimport { isProgrammaticRoutesFileName } from \"../routes-shared\";\nimport { findProgrammaticRouteFilesInDir } from \"../routes.server\";\nimport { toPosixPath, toViteModuleId } from \"../utils\";\nimport {\n createFarmRequestBodyErrorResponse,\n readNodeRequestBody,\n resolveFarmServerConfig,\n} from \"../server-http\";\nimport { createCliColors } from \"../cli-colors\";\nimport {\n AmbiguousRouteError,\n assertUniqueRouteParameters,\n getRoutePatternShape,\n} from \"../routing/specificity\";\n\nexport interface FarmApiPluginOptions {\n /** Source directory containing the api folder (default: 'src') */\n srcDir?: string;\n /** Enable debug logging */\n debug?: boolean;\n /** Maximum request body size, for example `\"10mb\"`. */\n bodySizeLimit?: number | string;\n /** Same-origin path where canonical `/api` routes are served. @default \"/api\" */\n basePath?: string;\n}\n\nexport interface ApiRoute {\n path: string;\n filePath: string;\n methods: string[];\n endpoints: Record<string, any>;\n}\n\n/**\n * Farm.js API Routes Vite Plugin\n */\nexport function farmApiPlugin(options: FarmApiPluginOptions = {}): Plugin {\n const srcDir = options.srcDir ?? \"src\";\n const debug = options.debug ?? false;\n const bodySizeLimit = resolveFarmServerConfig({\n bodySizeLimit: options.bodySizeLimit,\n }).bodySizeLimit;\n const basePath = options.basePath;\n\n // API routes cache\n let apiRoutesCache: Map<string, ApiRoute> = new Map();\n let apiRouterHandler: ((req: Request) => Promise<Response>) | null = null;\n let discoveryComplete = false;\n let discoveryPromise: Promise<void> | null = null;\n let discoveryError: unknown;\n let recoverFailedDiscovery: (() => Promise<boolean>) | undefined;\n const endpointSources = new Map<string, Map<string, string>>();\n const routeShapes = new Map<string, { routePath: string; filePath: string }>();\n\n const log = (_message: string) => {};\n const logResponse = (method: string, urlPath: string, status: number, duration: number) => {\n const pc = createCliColors();\n let statusColor = pc.green;\n if (status >= 500) statusColor = pc.red;\n else if (status >= 400) statusColor = pc.yellow;\n else if (status >= 300) statusColor = pc.cyan;\n\n const logMsg = [\n pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.cyan(\"API\")) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n pc.gray(urlPath),\n pc.dim(\"-\"),\n statusColor(status.toString()),\n pc.dim(`(${duration}ms)`),\n ].join(\" \");\n console.log(logMsg);\n };\n\n const registerRouteShape = (routePath: string, filePath: string): void => {\n assertUniqueRouteParameters(routePath, \"api\");\n const shape = getRoutePatternShape(routePath, \"api\");\n const existing = routeShapes.get(shape);\n if (existing && existing.routePath !== routePath) {\n throw new AmbiguousRouteError(\n `Ambiguous API routes \"${existing.routePath}\" and \"${routePath}\" match the same URLs. Found ${existing.filePath} and ${filePath}. Keep only one route for this URL shape.`,\n );\n }\n routeShapes.set(shape, { routePath, filePath });\n };\n\n const addEndpoint = (\n routePath: string,\n filePath: string,\n method: string,\n endpoint: any,\n ): void => {\n registerRouteShape(routePath, filePath);\n const normalizedMethod = method.toUpperCase();\n const existing = apiRoutesCache.get(routePath);\n const existingFile = endpointSources.get(routePath)?.get(normalizedMethod);\n\n if (existingFile) {\n throw new APIRouteConflictError(routePath, normalizedMethod, existingFile, filePath);\n }\n\n if (existing) {\n if (!existing.methods.includes(normalizedMethod)) {\n existing.methods.push(normalizedMethod);\n }\n existing.endpoints[normalizedMethod] = endpoint;\n const sources = endpointSources.get(routePath) ?? new Map();\n sources.set(normalizedMethod, filePath);\n endpointSources.set(routePath, sources);\n return;\n }\n\n apiRoutesCache.set(routePath, {\n path: routePath,\n filePath,\n methods: [normalizedMethod],\n endpoints: { [normalizedMethod]: endpoint },\n });\n endpointSources.set(routePath, new Map([[normalizedMethod, filePath]]));\n };\n\n const removeEndpointsFromFile = (filePath: string): void => {\n for (const [routePath, sources] of endpointSources) {\n const route = apiRoutesCache.get(routePath);\n if (!route) continue;\n\n for (const [method, sourceFile] of sources) {\n if (sourceFile !== filePath) continue;\n sources.delete(method);\n route.methods = route.methods.filter((candidate) => candidate !== method);\n delete route.endpoints[method];\n }\n\n if (route.methods.length === 0) {\n apiRoutesCache.delete(routePath);\n endpointSources.delete(routePath);\n routeShapes.delete(getRoutePatternShape(routePath, \"api\"));\n } else {\n const currentSource = sources.values().next().value;\n if (route.filePath === filePath && currentSource) {\n route.filePath = currentSource;\n }\n routeShapes.set(getRoutePatternShape(routePath, \"api\"), {\n routePath,\n filePath: currentSource ?? route.filePath,\n });\n }\n }\n };\n\n const snapshotRouteState = () => ({\n routes: new Map(\n [...apiRoutesCache].map(([routePath, route]) => [\n routePath,\n {\n ...route,\n methods: [...route.methods],\n endpoints: { ...route.endpoints },\n },\n ]),\n ),\n sources: new Map(\n [...endpointSources].map(([routePath, sources]) => [routePath, new Map(sources)]),\n ),\n shapes: new Map(routeShapes),\n });\n\n const restoreRouteState = (snapshot: ReturnType<typeof snapshotRouteState>): void => {\n apiRoutesCache = snapshot.routes;\n endpointSources.clear();\n for (const [routePath, sources] of snapshot.sources) {\n endpointSources.set(routePath, sources);\n }\n routeShapes.clear();\n for (const [shape, route] of snapshot.shapes) {\n routeShapes.set(shape, route);\n }\n };\n\n // Create API router handler\n const createRouter = async (): Promise<void> => {\n const totalEndpoints = Array.from(apiRoutesCache.values()).reduce(\n (sum, route) => sum + route.methods.length,\n 0,\n );\n\n apiRouterHandler = null;\n\n if (totalEndpoints > 0) {\n apiRouterHandler = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const method = request.method.toUpperCase();\n const pathname = url.pathname;\n\n const match = matchAPIRouteAtBasePath(apiRoutesCache, pathname, basePath);\n if (!match) {\n return new Response(JSON.stringify({ error: \"Not Found\" }), {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n const { route, params } = match;\n const endpoint = resolveAPIRouteEndpoint(route, method);\n if (!endpoint) {\n return new Response(JSON.stringify({ error: \"Method Not Allowed\" }), {\n status: 405,\n headers: {\n Allow: getAllowedAPIRouteMethods(route).join(\", \"),\n \"Content-Type\": \"application/json\",\n },\n });\n }\n\n try {\n return await invokeAPIRouteEndpoint(endpoint, request, params, bodySizeLimit);\n } catch (error: any) {\n return new Response(JSON.stringify({ error: error.message || \"Internal Server Error\" }), {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n };\n\n log(`API router created with ${totalEndpoints} endpoints`);\n }\n };\n\n return {\n name: \"@farm.js/core:api\",\n enforce: \"pre\",\n\n configureServer(server: ViteDevServer) {\n // Discover API routes in /api directory\n const discoverFileRoutes = async (apiDir: string): Promise<void> => {\n const fs = await import(\"fs\");\n const path = await import(\"path\");\n\n if (!fs.existsSync(apiDir)) {\n log(\"No api directory found\");\n return;\n }\n\n const findRouteFiles = (dir: string): string[] => {\n const files: string[] = [];\n if (!fs.existsSync(dir)) return files;\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...findRouteFiles(fullPath));\n } else if (isFarmAPIRouteFileName(entry.name)) {\n files.push(fullPath);\n }\n }\n return files;\n };\n\n const routeFiles = findRouteFiles(apiDir);\n apiRoutesCache.clear();\n endpointSources.clear();\n routeShapes.clear();\n\n for (const filePath of routeFiles) {\n try {\n const relativePath = path.relative(apiDir, path.dirname(filePath));\n const routePath =\n \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n\n const routeModule = await server.ssrLoadModule(filePath);\n const endpoints: Record<string, any> = {};\n const availableMethods: string[] = [];\n\n for (const method of API_ROUTE_METHODS) {\n if (routeModule[method]) {\n availableMethods.push(method);\n endpoints[method] = routeModule[method];\n }\n }\n\n if (availableMethods.length > 0) {\n for (const method of availableMethods) {\n addEndpoint(routePath, filePath, method, endpoints[method]);\n }\n log(`API route discovered: ${availableMethods.join(\", \")} ${routePath}`);\n }\n } catch (e: any) {\n if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n log(`API route load failed at ${filePath}: ${e.message}`);\n }\n }\n };\n\n // Discover routes from root routes.ts file\n const discoverRootRoutes = async (): Promise<void> => {\n const fs = await import(\"fs\");\n const path = await import(\"path\");\n\n const routesFiles = [\n path.join(server.config.root, srcDir, \"routes.ts\"),\n path.join(server.config.root, srcDir, \"routes.tsx\"),\n path.join(server.config.root, srcDir, \"routes.js\"),\n ];\n\n for (const routesFile of routesFiles) {\n if (fs.existsSync(routesFile)) {\n try {\n const routesModule = await server.ssrLoadModule(routesFile);\n\n for (const [exportName, exportValue] of Object.entries(routesModule)) {\n const endpoint = exportValue as any;\n\n if (endpoint && endpoint.__path) {\n const routePath = endpoint.__path;\n const method = String(endpoint.__method || \"GET\").toUpperCase();\n\n addEndpoint(routePath, routesFile, method, endpoint);\n log(`Root route discovered: ${method} ${routePath}`);\n }\n }\n } catch (e: any) {\n if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n log(`Root routes.ts load failed: ${e.message}`);\n }\n break;\n }\n }\n };\n\n const discoverProgrammaticRoutes = async (): Promise<void> => {\n const path = await import(\"path\");\n const srcRoot = path.join(server.config.root, srcDir);\n const routeFiles = findProgrammaticRouteFilesInDir(srcRoot);\n if (routeFiles.length === 0) return;\n const { getProgrammaticRouteManifest } = await import(\"../routes\");\n\n for (const routeFile of routeFiles) {\n try {\n const routesModule = await server.ssrLoadModule(\n toViteModuleId(routeFile, server.config.root),\n );\n const manifest = getProgrammaticRouteManifest(routesModule);\n if (!manifest) continue;\n\n for (const definition of manifest.routes) {\n if (definition.kind !== \"api\") continue;\n\n for (const [method, endpoint] of Object.entries(definition.methods)) {\n if (endpoint) {\n addEndpoint(definition.path, routeFile, method, endpoint);\n log(`Programmatic route discovered: ${method} ${definition.path}`);\n }\n }\n }\n } catch (e: any) {\n if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n log(`Programmatic routes file load failed at ${routeFile}: ${e.message}`);\n }\n }\n };\n\n // Initialize discovery\n const initializeDiscovery = async () => {\n const path = await import(\"path\");\n const apiDir = path.join(server.config.root, srcDir, \"api\");\n log(`Discovering API routes in: ${apiDir}`);\n\n await discoverFileRoutes(apiDir);\n await discoverRootRoutes();\n await discoverProgrammaticRoutes();\n await createRouter();\n\n discoveryComplete = true;\n log(`API discovery complete: ${apiRoutesCache.size} routes found`);\n };\n\n discoveryPromise = initializeDiscovery().catch((e) => {\n discoveryError = e;\n console.error(\"[FARM] API discovery error:\", e);\n });\n\n const waitForDiscovery = async () => {\n await discoveryPromise;\n if (discoveryError) throw discoveryError;\n };\n\n recoverFailedDiscovery = async (): Promise<boolean> => {\n if (!discoveryError) return false;\n\n const previousState = snapshotRouteState();\n try {\n await initializeDiscovery();\n discoveryError = undefined;\n discoveryPromise = Promise.resolve();\n } catch (error) {\n restoreRouteState(previousState);\n discoveryError = error;\n discoveryComplete = false;\n discoveryPromise = Promise.resolve();\n throw error;\n }\n\n return true;\n };\n\n // Expose API router for other plugins\n (server as any).__farmApi__ = {\n getHandler: () => apiRouterHandler,\n getRoutes: () => apiRoutesCache,\n isReady: () => discoveryComplete,\n waitForDiscovery,\n };\n\n // Add middleware to handle API requests\n return () => {\n const apiMiddleware = _withAfterNodeMiddleware(async (req, res, next) => {\n const url = req.url || \"/\";\n const pathname = url.split(\"?\")[0];\n const method = req.method || \"GET\";\n\n if (discoveryPromise) await waitForDiscovery();\n\n if (!matchAPIRouteAtBasePath(apiRoutesCache, pathname, basePath)) {\n return next();\n }\n\n if (!apiRouterHandler) {\n return next();\n }\n\n const startTime = Date.now();\n\n try {\n // Execute middleware if available\n const farmMiddleware = (server as any).__farmMiddleware__;\n if (farmMiddleware) {\n await farmMiddleware.waitForDiscovery?.();\n const middlewareData = new Map<string, any>();\n const handled = await farmMiddleware.execute(req, res, pathname, middlewareData);\n if (handled) {\n const duration = Date.now() - startTime;\n logResponse(method, pathname, res.statusCode || 200, duration);\n return;\n }\n }\n\n // ctx.rewrite() mutates req.url; dispatch from the current\n // value so dev matches production, where the rewritten request\n // reaches the API router.\n const currentUrl = req.url || url;\n const currentPathname = currentUrl.split(\"?\")[0];\n if (\n currentPathname !== pathname &&\n !matchAPIRouteAtBasePath(apiRoutesCache, currentPathname, basePath)\n ) {\n // Rewritten off the API surface; let the page pipeline serve it.\n return next();\n }\n\n // Convert Node request to Web Request\n const fullUrl = `http://${req.headers.host || \"localhost:3000\"}${currentUrl}`;\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n\n let body: Buffer | undefined;\n if (method !== \"GET\" && method !== \"HEAD\") {\n body = await readNodeRequestBody(req as any, bodySizeLimit);\n }\n\n const request = new Request(fullUrl, {\n method,\n headers,\n body: body\n ? (body.buffer.slice(\n body.byteOffset,\n body.byteOffset + body.byteLength,\n ) as ArrayBuffer)\n : undefined,\n });\n\n const response = await apiRouterHandler(request);\n\n const duration = Date.now() - startTime;\n logResponse(method, currentPathname, response.status, duration);\n\n await sendWebResponse(res, response);\n } catch (error: any) {\n const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n if (bodyErrorResponse) {\n await sendWebResponse(res, bodyErrorResponse);\n return;\n }\n const duration = Date.now() - startTime;\n logResponse(method, pathname, 500, duration);\n console.error(\"[FARM] API error:\", error);\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal server error\" }));\n }\n });\n server.middlewares.use((req, res, next) =>\n _runWithAPIRequestRuntime(\n {\n basePath: basePath ?? \"/api\",\n dispatch: async (request) =>\n apiRouterHandler\n ? apiRouterHandler(request)\n : Response.json({ error: \"Not Found\" }, { status: 404 }),\n },\n () => apiMiddleware(req, res, next),\n ),\n );\n };\n },\n\n async handleHotUpdate({ file, server, modules }) {\n const normalizedFile = toPosixPath(file);\n const fileName = normalizedFile.split(\"/\").pop() || \"\";\n\n // Handle root routes.ts updates\n if (\n fileName === \"routes.ts\" ||\n fileName === \"routes.tsx\" ||\n fileName === \"routes.js\" ||\n isProgrammaticRoutesFileName(fileName)\n ) {\n log(`Root routes file updated: ${fileName}`);\n\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n if (await recoverFailedDiscovery?.()) return [];\n\n const previousState = snapshotRouteState();\n\n try {\n const routesModule = await server.ssrLoadModule(file);\n removeEndpointsFromFile(file);\n\n for (const [exportName, exportValue] of Object.entries(routesModule)) {\n const endpoint = exportValue as any;\n\n if (endpoint && endpoint.__path) {\n const routePath = endpoint.__path;\n const method = String(endpoint.__method || \"GET\").toUpperCase();\n\n addEndpoint(routePath, file, method, endpoint);\n log(`Root route reloaded: ${method} ${routePath}`);\n }\n }\n\n const { getProgrammaticRouteManifest } = await import(\"../routes\");\n const manifest = getProgrammaticRouteManifest(routesModule);\n if (manifest) {\n for (const definition of manifest.routes) {\n if (definition.kind !== \"api\") continue;\n\n for (const [method, endpoint] of Object.entries(definition.methods)) {\n if (endpoint) {\n addEndpoint(definition.path, file, method, endpoint);\n log(`Programmatic route reloaded: ${method} ${definition.path}`);\n }\n }\n }\n }\n\n await createRouter();\n log(`API router recreated`);\n } catch (e: any) {\n restoreRouteState(previousState);\n if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n log(`Root routes.ts HMR failed: ${e.message}`);\n }\n\n return [];\n }\n\n // Handle file-based route updates\n if (normalizedFile.includes(\"/api/\") && fileName.startsWith(\"route.\")) {\n const shortPath = normalizedFile.split(\"/api/\")[1] || normalizedFile;\n log(`API route updated: ${shortPath}`);\n\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n if (await recoverFailedDiscovery?.()) return [];\n\n const previousState = snapshotRouteState();\n try {\n const path = await import(\"path\");\n const apiDir = path.join(server.config.root, srcDir, \"api\");\n const relativePath = path.relative(apiDir, path.dirname(file));\n const routePath =\n \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n const fs = await import(\"fs\");\n if (!fs.existsSync(file)) {\n removeEndpointsFromFile(file);\n await createRouter();\n log(`API route file removed: ${routePath}`);\n return [];\n }\n const routeModule = await server.ssrLoadModule(file);\n\n removeEndpointsFromFile(file);\n const availableMethods: string[] = [];\n for (const method of API_ROUTE_METHODS) {\n if (!routeModule[method]) continue;\n availableMethods.push(method);\n addEndpoint(routePath, file, method, routeModule[method]);\n }\n\n await createRouter();\n log(`API route reloaded: ${availableMethods.join(\", \")} ${routePath}`);\n log(`API router recreated`);\n } catch (e: any) {\n restoreRouteState(previousState);\n if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n log(`API route HMR failed: ${e.message}`);\n }\n\n return [];\n }\n },\n };\n}\n","import picocolors from \"picocolors\";\n\n/**\n * Create colors for Farm's terminal output.\n *\n * Some interactive terminal hosts advertise a limited TERM value or set\n * NO_COLOR for captured subprocess output even though they render ANSI styles.\n * Prefer the actual stream type so the dev server remains colored in a TTY,\n * while redirected output stays plain.\n */\nexport function createCliColors(interactive = process.stdout.isTTY === true) {\n return picocolors.createColors(interactive);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FO,SAAS,2BACd,QAC2B;AAC3B,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,IAAI,IAAI,cAAc;AAAA,MAC7B,cAAc;AAAA,MACd,YAAY,CAAC;AAAA,MACb,aAAa;AAAA,IACf;AAAA,EACF;AAEA,MAAI,WAAW,MAAM;AACnB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO,IAAI,IAAI,cAAc;AAAA,MAC7B,cAAc;AAAA,MACd,YAAY,CAAC;AAAA,MACb,aAAa;AAAA,IACf;AAAA,EACF;AAEA,SAAO;AAAA,IACL,SAAS,OAAO,WAAW;AAAA,IAC3B,OAAO,IAAI,IAAI,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M,gBAAgB,mBAAmB;AACzC,YAAI;AACF,gBAAMD,QAAO,MAAM,OAAO,MAAM;AAChC,gBAAM,SAASA,MAAK,KAAK,OAAO,OAAO,MAAM,QAAQ,KAAK;AAC1D,gBAAM,eAAeA,MAAK,SAAS,QAAQA,MAAK,QAAQ,IAAI,CAAC;AAC7D,gBAAM,YACJ,WAAW,iBAAiB,MAAM,KAAK,aAAa,QAAQ,OAAO,GAAG;AACxE,gBAAMD,MAAK,MAAM,OAAO,IAAI;AAC5B,cAAI,CAACA,IAAG,WAAW,IAAI,GAAG;AACxB,oCAAwB,IAAI;AAC5B,kBAAM,aAAa;AACnB,gBAAI,2BAA2B,SAAS,EAAE;AAC1C,mBAAO,CAAC;AAAA,UACV;AACA,gBAAM,cAAc,MAAM,OAAO,cAAc,IAAI;AAEnD,kCAAwB,IAAI;AAC5B,gBAAM,mBAA6B,CAAC;AACpC,qBAAW,UAAU,mBAAmB;AACtC,gBAAI,CAAC,YAAY,MAAM,EAAG;AAC1B,6BAAiB,KAAK,MAAM;AAC5B,wBAAY,WAAW,MAAM,QAAQ,YAAY,MAAM,CAAC;AAAA,UAC1D;AAEA,gBAAM,aAAa;AACnB,cAAI,uBAAuB,iBAAiB,KAAK,IAAI,CAAC,IAAI,SAAS,EAAE;AACrE,cAAI,sBAAsB;AAAA,QAC5B,SAAS,GAAQ;AACf,4BAAkB,aAAa;AAC/B,cAAI,aAAa,yBAAyB,aAAa,oBAAqB,OAAM;AAClF,cAAI,yBAAyB,EAAE,OAAO,EAAE;AAAA,QAC1C;AAEA,eAAO,CAAC;AAAA,MACV;AAAA,IACF;AAAA,EACF;AACF;AAnlBgB;","names":["PROGRAMMATIC_ROUTE_FILE_NAMES","createProgrammaticRouteModuleId","isProgrammaticRoutesFileName","parseProgrammaticRoutePath","scanProgrammaticPagePaths","path","FarmProgrammaticPageContent","FarmProgrammaticPage","context","action","path","betterCallEndpoint","context","result","path","path","path","path","import_path","import_node_async_hooks","getRequestStore","storage","path","context","url","path","response","searchParamsToObject","getProgrammaticRouteManifest","CURRENT_REQUEST_RESOLVER_KEY","globalState","CURRENT_REQUEST_RESOLVER_KEY","api","body","api","path","segment","dynamic","route","api","path","nextEntry","result","createResponseError","delay","invalidate","import_node_async_hooks","storage","context","context","import_node_async_hooks","picocolors","fs","path","getProgrammaticRouteManifest","duration"]}