{"version":3,"sources":["../../src/api-client.ts","../../src/api/config.ts","../../src/client-headers.ts","../../src/client-cancellation.ts","../../src/client-observers.ts","../../src/integration-client.ts","../../src/tracing.ts","../../src/observability.ts","../../src/cache-invalidation.ts","../../src/cache.ts","../../src/client-cache.ts","../../src/routing/specificity.ts","../../src/api/route-pattern.ts","../../src/api/client-routes.ts","../../src/server/request-bridge.ts","../../src/api/server-client-bridge.ts","../../src/api/transport.ts","../../src/api/client.ts"],"sourcesContent":["export {\n  APIClientError,\n  createApiClients,\n  createAPIClient,\n  createServerAPIClient,\n} from \"./api/client\";\nexport type {\n  ApiClients,\n  APIClient,\n  APIClientOptions,\n  APIClientSystemError,\n  APIClientWithoutIntegrationsOptions,\n  RouteAPIClient,\n  ServerAPIClient,\n  ServerAPIClientOptions,\n  ServerAPIClientWithoutIntegrationsOptions,\n} from \"./api/client\";\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","/** 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","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 { 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 serializeCanonicalStringEntries(\n  entries: Iterable<readonly [string, string]>,\n  seen: WeakSet<object>,\n): string {\n  const valuesByKey = new Map<string, string[]>();\n  for (const [key, item] of entries) {\n    const values = valuesByKey.get(key);\n    if (values) values.push(item);\n    else valuesByKey.set(key, [item]);\n  }\n\n  return Array.from(valuesByKey.keys())\n    .sort(compareCodepoint)\n    .flatMap((key) =>\n      valuesByKey\n        .get(key)!\n        .map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`),\n    )\n    .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    // URLSearchParams and Headers keep their contents internally, so\n    // Object.entries is empty for both (same rationale as Set/Map above).\n    // Canonicalize key order while preserving the order of repeated values for\n    // each key. URLSearchParams treats `a=1&a=2` and `a=2&a=1` as observably\n    // different inputs, while `b=2&a=1` and `a=1&b=2` should still share a key.\n    if (value instanceof URLSearchParams) {\n      const serialized = serializeCanonicalStringEntries(value, seen);\n      seen.delete(value);\n      return `urlsearchparams:[${serialized}]`;\n    }\n    if (value instanceof Headers) {\n      const serialized = serializeCanonicalStringEntries(value, seen);\n      seen.delete(value);\n      return `headers:[${serialized}]`;\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","/// <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","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 { 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","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","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","/** 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","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  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 RetryAttemptContext = {\n  /** Zero-based index of the attempt that just failed. */\n  attempt: number;\n  /** Upper-case HTTP method of the request. */\n  method: string;\n  /** Response status, or undefined when the request never produced a response. */\n  status?: number;\n  error: Error;\n};\n\nexport type RetryOptions = {\n  count?: number;\n  delay?: number | ((attempt: number) => number);\n  /**\n   * Decide whether a failed attempt should be retried.\n   *\n   * Defaults to transient failures of idempotent requests only: replaying a\n   * POST or PATCH whose response was lost duplicates the write it performed.\n   * Supply this to opt a specific call in or out.\n   */\n  shouldRetry?: (context: RetryAttemptContext) => boolean;\n};\n\n/**\n * Methods whose replay has the same effect as a single call, so a retry cannot\n * duplicate work: the idempotent set from RFC 9110, plus QUERY, which Farm\n * supports as a read that carries a body.\n */\nconst FARM_IDEMPOTENT_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\", \"QUERY\"]);\n\n/** Statuses that represent a transient condition worth another attempt. */\nconst FARM_RETRYABLE_STATUSES = new Set([408, 425, 429]);\n\nfunction isFarmRetryableFailure(context: RetryAttemptContext): boolean {\n  // A non-idempotent request may already have been applied by the server even\n  // when the client never saw the response, so it is never retried by default.\n  if (!FARM_IDEMPOTENT_METHODS.has(context.method)) return false;\n  // No response at all: a transport failure, which is the transient case retries\n  // exist for.\n  if (context.status === undefined) return true;\n  return context.status >= 500 || FARM_RETRYABLE_STATUSES.has(context.status);\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: string | undefined = 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          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            const shouldRetryFailure = clientOptions?.retry?.shouldRetry ?? isFarmRetryableFailure;\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 (\n                  attempt >= maxRetries ||\n                  !shouldRetryFailure({\n                    attempt,\n                    method: methodUpper,\n                    status: response.status,\n                    error,\n                  })\n                ) {\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 (\n                  attempt >= maxRetries ||\n                  requestContextError ||\n                  cancellation.signal?.aborted ||\n                  !shouldRetryFailure({ attempt, method: methodUpper, error })\n                ) {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,6BAA6B;AAiJnC,SAAS,oBAA4B;AAC1C,MAAI,OAAO,0BAA0B,eAAe,uBAAuB;AACzE,WAAO;AAAA,EACT;AACA,SAAO;AACT;AALgB;AAQT,SAAS,yBACd,WACA,UAAU,kBAAkB,GAC5B,iBAAiB,iBAAiB,GAC7B;AACL,QAAM,OA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","serialized","segment","dynamic","route","CURRENT_REQUEST_RESOLVER_KEY","CURRENT_REQUEST_RESOLVER_KEY","context","nextEntry","result","createResponseError","delay","createResponseError"]}