{"version":3,"sources":["../src/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/i18n/bridge.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","../src/mutation-client.ts","../src/client-network-status.ts","../src/mutation-retry.ts","../src/fetcher-client.tsx","../src/server-fn-client.ts","../src/server-query-client.ts","../src/client-revalidation.ts","../src/server-query-runtime.ts","../src/cache-invalidation-broadcast.ts","../src/client-cache-persistence.ts","../src/integration-api.ts","../src/store.ts","../src/theme/client.tsx","../src/theme/bridge.ts","../src/theme/runtime.ts","../src/client/link.tsx","../src/router.ts","../src/client/navigation-url.ts","../src/i18n/client-runtime.ts","../src/base-path.ts","../src/i18n/routing.ts","../src/trailing-slash.ts","../src/provider.tsx","../src/client/router.ts","../src/deferred.ts","../src/client/history-sync.ts","../src/deployment.ts","../src/client/hash-target.ts","../src/agent-config.ts","../src/metadata.ts","../src/client/metadata-reconciler.ts","../src/client/spa-router.ts","../src/client/chunk-recovery.ts","../src/client/runtime-error-overlay.ts","../src/components/error-styles.ts","../package.json","../src/version.ts","../src/client/plugin.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\";\nexport type { FarmAPIStream } from \"./api/transport\";\nexport type { ClientHeaders } from \"./client-headers\";\nexport type {\n  ClientLifecycleHooks,\n  ClientRequestEvent,\n  ClientResponseEvent,\n} from \"./client-observers\";\nexport { useMutation } from \"./mutation-client\";\nexport type {\n  AnyMutationTarget,\n  InferMutationData,\n  InferMutationError,\n  InferMutationVariables,\n  MutationAsync,\n  MutationOptimisticContext,\n  MutationNetworkMode,\n  MutationStatus,\n  MutationTrigger,\n  UseMutationOptions,\n  UseMutationReturn,\n} from \"./mutation-client\";\nexport { useFetcher, FetcherInputError } from \"./fetcher-client\";\nexport type {\n  FetcherFormDataContext,\n  FetcherFormProps,\n  FetcherState,\n  FetcherSubmit,\n  FetcherSubmitAsync,\n  UseFetcherOptions,\n  UseFetcherReturn,\n} from \"./fetcher-client\";\nexport { useAction } from \"./server-fn-client\";\nexport type {\n  RouteActionTarget,\n  UseActionFormProps,\n  UseActionReturn,\n  UseServerFnOptions,\n} from \"./server-fn-client\";\nexport { fetchServerQuery, prefetchServerQuery, useServerQuery } from \"./server-query-client\";\nexport type {\n  ServerQueryFetchOptions,\n  UseServerQueryOptions,\n  UseServerQueryResult,\n} from \"./server-query-client\";\nexport {\n  enableCrossTabCacheInvalidation,\n  FARM_CACHE_INVALIDATION_CHANNEL,\n} from \"./cache-invalidation-broadcast\";\nexport type { CrossTabCacheInvalidationOptions } from \"./cache-invalidation-broadcast\";\nexport {\n  clearPersistedCache,\n  defineClientCacheAdapter,\n  FARM_CLIENT_CACHE_PERSIST_VERSION,\n  // The generated client entry imports this by name when `cache.client.adapter`\n  // is configured, so it has to be reachable from this entry point.\n  initConfiguredClientCachePersistence,\n  initPersistedClientCache,\n  storageClientCacheAdapter,\n} from \"./client-cache-persistence\";\n// The shared browser store. Features that keep their own rows (for example\n// `@farm.js/sync`) persist through it rather than opening a second store.\nexport { getFarmClientDataCache, normalizeFarmClientCacheKey } from \"./client-cache\";\nexport type {\n  FarmClientCacheEntry,\n  FarmClientCacheKey,\n  FarmClientCacheStatus,\n} from \"./client-cache\";\nexport type {\n  ClientCachePersistenceOptions,\n  FarmClientCacheAdapter,\n  FarmClientCacheStorage,\n  PersistedEntry,\n} from \"./client-cache-persistence\";\nexport {\n  api,\n  endpoint,\n  defineIntegrationAPI,\n  defineIntegrationAPIOperation,\n} from \"./integration-api\";\nexport type {\n  FarmIntegrationAPI,\n  FarmIntegrationAPIBodyFormat,\n  FarmIntegrationAPIMethod,\n  FarmIntegrationAPIOperation,\n  FarmIntegrationAPIResponseFormat,\n} from \"./integration-api\";\nexport { createIntegrationClient, IntegrationClientError } from \"./integration-client\";\nexport {\n  createIntegrationApi,\n  createIntegrationClients,\n  createIntegrations,\n  createIntegrationServerClient,\n  getIntegrationAPIManifest,\n  integrationClients,\n  integrationsClient,\n  integrationsServer,\n} from \"./integration-client\";\nexport type {\n  IntegrationClient,\n  IntegrationClientAliases,\n  IntegrationClientRoot,\n  IntegrationClientOptions,\n  IntegrationClientRequestOptions,\n  IntegrationAPI,\n  IntegrationClients,\n  IntegrationClientData,\n  IntegrationOperationResult,\n  InferIntegrationOperationBody,\n  InferIntegrationOperationQuery,\n  InferIntegrationOperationResponse,\n  IntegrationServerClient,\n  IntegrationServerClientAliases,\n  IntegrationServerClientOptions,\n  IntegrationServerClientRequestOptions,\n  IntegrationServerClientRoot,\n  IntegrationServerRequestLike,\n} from \"./integration-client\";\nexport { createStore } from \"./store\";\nexport { getTheme, setTheme, toggleTheme, useTheme } from \"./theme/client\";\nexport type { UseThemeResult } from \"./theme/client\";\nexport type {\n  Store,\n  StoreApi,\n  StoreFields,\n  StoreListener,\n  StoreKeyListener,\n  StoreKeysListener,\n  StorePatch,\n  StoreState,\n  StoreValueUpdater,\n} from \"./store\";\n\n// SPA Navigation exports\nexport { Link } from \"./client/link\";\nexport {\n  useBlocker,\n  useNavigation,\n  usePageState,\n  useRouter,\n  useScrollRestoration,\n} from \"./client/router\";\nexport {\n  SPARouter,\n  getRouter,\n  navigateTo,\n  prefetch,\n  pushState,\n  readPageState,\n  replaceState,\n} from \"./client/spa-router\";\nexport { installChunkErrorRecovery, isChunkLoadError } from \"./client/chunk-recovery\";\nexport { createClientPluginManager, FarmClientPluginManager } from \"./client/plugin\";\nexport type {\n  LinkProps,\n  PrefetchBehavior,\n  LinkDefaultRoute,\n  DefaultRoutePath,\n  DefaultRoutePattern,\n  DefaultRouteHref,\n  ExternalHref,\n  LinkExternalUriSchemes,\n  RouteHref,\n  RouteParamValue,\n  RouteOptionalParamValue,\n  RouteParams,\n} from \"./client/link\";\nexport type { FarmChunkRecoveryOptions } from \"./client/chunk-recovery\";\nexport type {\n  FarmClientHydrationCompleteEvent,\n  FarmClientHydrationEvent,\n  FarmClientHydrationMode,\n  FarmClientHydrationSession,\n  FarmClientLocation,\n  FarmClientNavigationAction,\n  FarmClientNavigationErrorEvent,\n  FarmClientNavigationEvent,\n  FarmClientNavigationLoadedEvent,\n  FarmClientNavigationResolvedEvent,\n  FarmClientNavigationSession,\n  FarmClientPerformanceEvent,\n  FarmClientPlugin,\n  FarmClientPluginCloseEvent,\n  FarmClientPluginEnforce,\n  FarmClientPluginErrorEvent,\n  FarmClientPluginErrorPhase,\n  FarmClientPluginManagerOptions,\n  FarmClientPluginMetadata,\n  FarmClientPluginRegistration,\n  FarmClientPluginRouter,\n  FarmClientPluginSetupEvent,\n  FarmClientPluginStateEvent,\n} from \"./client/plugin\";\nexport type { UseBlockerOptions, UseBlockerReturn, UseRouterOptions } from \"./client/router\";\nexport type {\n  FarmNavigateOptions,\n  FarmNavigationBlocker,\n  FarmNavigationBlockerContext,\n  FarmNavigationListener,\n  FarmNavigationLocation,\n  FarmNavigationState,\n  FarmViewTransitionMode,\n} from \"./client/spa-router\";\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 type { FarmI18nClientSnapshot } from \"./types\";\n\ntype SnapshotResolver = () => FarmI18nClientSnapshot | undefined;\n\nconst FARM_I18N_SNAPSHOT_RESOLVER = Symbol.for(\"farm.i18n.snapshotResolver\");\ntype GlobalWithI18nResolver = typeof globalThis & {\n  [FARM_I18N_SNAPSHOT_RESOLVER]?: SnapshotResolver;\n};\n\nexport function _setFarmI18nSnapshotResolver(resolver: SnapshotResolver | undefined): void {\n  (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER] = resolver;\n}\n\nexport function getActiveFarmI18nSnapshot(): FarmI18nClientSnapshot | undefined {\n  if (typeof window !== \"undefined\" && window.__FARM_I18N__) {\n    return window.__FARM_I18N__;\n  }\n  return (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER]?.();\n}\n","import { emitFarmEvent } from \"./observability\";\nimport { notifyFarmCacheInvalidation, notifyFarmCacheTask } from \"./cache-invalidation\";\nimport { getActiveFarmI18nSnapshot } from \"./i18n/bridge\";\n\nexport { applyFarmCacheInvalidations } from \"./cache-invalidation\";\n\nexport type RevalidateTagProfile =\n  | \"max\"\n  | \"default\"\n  | \"seconds\"\n  | \"minutes\"\n  | \"hours\"\n  | \"days\"\n  | \"weeks\"\n  | \"months\"\n  | { expire?: number };\n\nexport interface FarmCacheOptions {\n  /**\n   * Tag cached data so it can be invalidated with revalidateTag/updateTag.\n   */\n  tags?: readonly string[];\n  /**\n   * Path tags let revalidatePath invalidate data tied to a route.\n   */\n  paths?: readonly string[];\n  /**\n   * Time in seconds before the entry becomes stale. False means no TTL.\n   */\n  revalidate?: number | false;\n}\n\nexport interface FarmCacheSetOptions extends FarmCacheOptions {\n  createdAt?: number;\n}\n\nexport type RouteDataCacheKey = string | readonly unknown[];\n\nexport type FarmCacheInvalidationTarget =\n  | { key: RouteDataCacheKey }\n  | { path: string }\n  | { tag: string };\n\ndeclare const FARM_DEFINED_CACHE_KEY_DATA: unique symbol;\n\n/**\n * A regular Farm cache key carrying the data shape stored under that key.\n *\n * The brand exists only in TypeScript. At runtime the value remains the\n * original string or structured array, so all existing cache APIs continue to\n * accept untyped keys.\n */\nexport type DefinedCacheKey<TData, TKey extends RouteDataCacheKey = RouteDataCacheKey> = TKey & {\n  readonly [FARM_DEFINED_CACHE_KEY_DATA]: TData;\n};\n\nexport type CacheKeyFactory<\n  TData,\n  TArguments extends readonly unknown[],\n  TKey extends RouteDataCacheKey = RouteDataCacheKey,\n> = (...args: TArguments) => DefinedCacheKey<TData, TKey>;\n\nexport type InferCacheKeyData<TKey> =\n  TKey extends DefinedCacheKey<infer TData, RouteDataCacheKey> ? TData : unknown;\n\n/**\n * Optionally add a data type to an existing string/array cache-key factory.\n *\n * This helper does not introduce a new runtime key representation. Calling the\n * returned factory produces the exact key returned by `factory`.\n */\nexport function defineCacheKey<TData>() {\n  return <const TArguments extends readonly unknown[], const TKey extends RouteDataCacheKey>(\n    factory: (...args: TArguments) => TKey,\n  ): CacheKeyFactory<TData, TArguments, TKey> => {\n    if (typeof factory !== \"function\") {\n      throw new TypeError(\"defineCacheKey expects a key factory function.\");\n    }\n\n    return ((...args: TArguments) => {\n      const key = factory(...args);\n      if (typeof key !== \"string\" && !Array.isArray(key)) {\n        throw new TypeError(\n          \"A defined cache key factory must return a string or structured array.\",\n        );\n      }\n      return key as DefinedCacheKey<TData, TKey>;\n    }) as CacheKeyFactory<TData, TArguments, TKey>;\n  };\n}\n\nexport interface FarmCacheEntry<T = unknown> {\n  key: string;\n  value: T;\n  tags: readonly string[];\n  /**\n   * Adapter tag versions captured before the cached value was produced.\n   * A later version makes the entry stale across every server instance.\n   */\n  tagVersions?: Readonly<Record<string, number>>;\n  createdAt: number;\n  createdVersion?: number;\n  revalidate?: number | false;\n}\n\ninterface InternalFarmCacheEntry<T = unknown> {\n  key: string;\n  value: T;\n  tags: Set<string>;\n  tagVersions?: Readonly<Record<string, number>>;\n  createdAt: number;\n  createdVersion: number;\n  revalidate?: number | false;\n}\n\n/**\n * Asynchronous persistence contract used by distributed Farm caches.\n *\n * Implementations are responsible for serializing cache entries and making\n * tag version updates atomic when the backing service supports it.\n */\nexport interface FarmCacheAdapter {\n  readonly name?: string;\n  get<T = unknown>(key: string): Promise<FarmCacheEntry<T> | null | undefined>;\n  set<T = unknown>(key: string, entry: FarmCacheEntry<T>): Promise<void>;\n  delete(key: string): Promise<void>;\n  clear?(): Promise<void>;\n  getTagVersions?(tags: readonly string[]): Promise<Readonly<Record<string, number>>>;\n  invalidateTags?(tags: readonly string[]): Promise<void>;\n  /** Atomically acquire a short-lived regeneration lease. */\n  acquireLease?(key: string, ttlMs: number): Promise<string | null | undefined>;\n  /** Release the lease only when the supplied ownership token still matches. */\n  releaseLease?(key: string, token: string): Promise<void>;\n}\n\nexport interface FarmClientCacheUserConfig {\n  /**\n   * Module path, relative to the project root, whose default export is a\n   * client cache adapter (`defineClientCacheAdapter`). The module is bundled\n   * into the browser entry; the server never imports it.\n   */\n  adapter?: string;\n  /** Extra version salt, typically a build or deploy id; entries persisted under another salt are dropped. */\n  version?: string;\n  /** Debounce for persisted write-behind flushes, in milliseconds. */\n  flushDelayMs?: number;\n}\n\nexport interface FarmCacheUserConfig {\n  /** Shared cache implementation, for example a Redis-backed adapter. */\n  adapter?: FarmCacheAdapter;\n  /** Prefix isolating applications and deployments sharing one adapter. */\n  namespace?: string;\n  /** Browser cache persistence; see the client cache adapter documentation. */\n  client?: FarmClientCacheUserConfig;\n  /**\n   * Coordinate cache fills across processes when the adapter implements\n   * acquireLease/releaseLease. Set false to disable.\n   */\n  lease?:\n    | false\n    | {\n        ttlMs?: number;\n        waitTimeoutMs?: number;\n        pollIntervalMs?: number;\n      };\n}\n\nexport interface FarmCacheStorage {\n  getItem<T = unknown>(key: string): Promise<T | null>;\n  setItem<T = unknown>(key: string, value: T): Promise<unknown>;\n  removeItem(key: string): Promise<unknown>;\n  clear?(base?: string): Promise<unknown>;\n}\n\nexport interface StorageFarmCacheAdapterOptions {\n  /** Prefix used inside the supplied storage client. */\n  base?: string;\n}\n\n/**\n * Adapt a Farm/unstorage-compatible key-value client to the cache contract.\n *\n * This is a portable baseline adapter. Provider-specific adapters should use\n * their atomic increment/transaction primitives for tag invalidation.\n */\nexport function storageCacheAdapter(\n  storage: FarmCacheStorage,\n  options: StorageFarmCacheAdapterOptions = {},\n): FarmCacheAdapter {\n  if (!storage || typeof storage.getItem !== \"function\" || typeof storage.setItem !== \"function\") {\n    throw new TypeError(\"storageCacheAdapter expects a compatible storage client.\");\n  }\n\n  const base = normalizeCacheNamespace(options.base || \"farm-cache\");\n  const entryKey = (key: string) => `${base}:entry:${key}`;\n  const tagKey = (tag: string) => `${base}:tag:${tag}`;\n\n  return {\n    name: \"storage\",\n    get: <T>(key: string) => storage.getItem<FarmCacheEntry<T>>(entryKey(key)),\n    set: async <T>(key: string, entry: FarmCacheEntry<T>) => {\n      await storage.setItem(entryKey(key), entry);\n    },\n    delete: async (key: string) => {\n      await storage.removeItem(entryKey(key));\n    },\n    clear: storage.clear\n      ? async () => {\n          await storage.clear!(base);\n        }\n      : undefined,\n    getTagVersions: async (tags) => {\n      const versions = await Promise.all(\n        tags.map(async (tag) => {\n          const value = await storage.getItem<number>(tagKey(tag));\n          return [tag, normalizeAdapterVersion(value)] as const;\n        }),\n      );\n      return Object.fromEntries(versions);\n    },\n    invalidateTags: async (tags) => {\n      await Promise.all(\n        tags.map(async (tag) => {\n          const key = tagKey(tag);\n          const current = normalizeAdapterVersion(await storage.getItem<number>(key));\n          await storage.setItem(key, Math.max(Date.now(), current + 1));\n        }),\n      );\n    },\n  };\n}\n\nexport interface GetFarmCacheEntryOptions {\n  allowStale?: boolean;\n  now?: number;\n}\n\ninterface FarmCacheStaleEntry {\n  tags: Iterable<string>;\n  createdAt: number;\n  createdVersion?: number;\n  revalidate?: number | false;\n}\n\nexport class FarmDataCache {\n  private entries = new Map<string, InternalFarmCacheEntry>();\n  private inflight = new Map<string, Promise<unknown>>();\n  private invalidatedTagVersions = new Map<string, number>();\n  private version = 0;\n  private generation = 0;\n  private adapter?: FarmCacheAdapter;\n  private namespace = \"farm\";\n  private local = true;\n  private lease = {\n    enabled: true,\n    ttlMs: 10_000,\n    waitTimeoutMs: 10_000,\n    pollIntervalMs: 25,\n  };\n\n  constructor(config: FarmCacheUserConfig = {}) {\n    this.configure(config);\n  }\n\n  configure(config: FarmCacheUserConfig = {}): void {\n    this.generation++;\n    this.entries.clear();\n    this.inflight.clear();\n    this.invalidatedTagVersions.clear();\n    this.version = 0;\n    this.adapter = config.adapter;\n    this.namespace = normalizeCacheNamespace(config.namespace || \"farm\");\n    this.local = !config.adapter;\n    this.lease =\n      config.lease === false\n        ? { ...this.lease, enabled: false }\n        : {\n            enabled: true,\n            ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 10_000, \"cache.lease.ttlMs\"),\n            waitTimeoutMs: normalizePositiveDuration(\n              config.lease?.waitTimeoutMs,\n              10_000,\n              \"cache.lease.waitTimeoutMs\",\n            ),\n            pollIntervalMs: normalizePositiveDuration(\n              config.lease?.pollIntervalMs,\n              25,\n              \"cache.lease.pollIntervalMs\",\n            ),\n          };\n  }\n\n  get adapterName(): string {\n    return this.adapter?.name || (this.adapter ? \"custom\" : \"memory\");\n  }\n\n  get hasAdapter(): boolean {\n    return this.adapter !== undefined;\n  }\n\n  get size(): number {\n    return this.entries.size;\n  }\n\n  get<T>(key: string, options: GetFarmCacheEntryOptions = {}): T | undefined {\n    return this.getEntry<T>(key, options)?.value;\n  }\n\n  getEntry<T = unknown>(\n    key: string,\n    options: GetFarmCacheEntryOptions = {},\n  ): FarmCacheEntry<T> | undefined {\n    const entry = this.entries.get(key) as InternalFarmCacheEntry<T> | undefined;\n    if (!entry) {\n      emitFarmEvent({ type: \"cache.miss\", key });\n      return undefined;\n    }\n\n    const stale = this.isStale(entry, options.now);\n    if (stale) {\n      emitFarmEvent({\n        type: \"cache.stale\",\n        key,\n        tags: Array.from(entry.tags),\n        revalidate: entry.revalidate,\n      });\n    }\n\n    if (!options.allowStale && stale) {\n      emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n      return undefined;\n    }\n\n    emitFarmEvent({\n      type: \"cache.hit\",\n      key,\n      tags: Array.from(entry.tags),\n      revalidate: entry.revalidate,\n      stale,\n    });\n\n    return this.toPublicEntry(entry);\n  }\n\n  async getEntryAsync<T = unknown>(\n    key: string,\n    options: GetFarmCacheEntryOptions = {},\n  ): Promise<FarmCacheEntry<T> | undefined> {\n    if (this.local) {\n      const localEntry = this.getEntry<T>(key, options);\n      if (localEntry) return localEntry;\n    }\n\n    if (!this.adapter) {\n      return this.local ? undefined : this.getEntry<T>(key, options);\n    }\n\n    const generation = this.generation;\n    const adapter = this.adapter;\n    const namespace = this.namespace;\n    const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n    if (generation !== this.generation) return undefined;\n    if (!entry) {\n      emitFarmEvent({ type: \"cache.miss\", key });\n      return undefined;\n    }\n\n    assertFarmCacheEntry(entry, key);\n    const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);\n    if (generation !== this.generation) return undefined;\n    if (stale) {\n      emitFarmEvent({\n        type: \"cache.stale\",\n        key,\n        tags: [...entry.tags],\n        revalidate: entry.revalidate,\n      });\n      if (!options.allowStale) {\n        emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n        return undefined;\n      }\n    }\n\n    emitFarmEvent({\n      type: \"cache.hit\",\n      key,\n      tags: [...entry.tags],\n      revalidate: entry.revalidate,\n      stale,\n    });\n\n    if (this.local && !stale) {\n      this.hydrateLocalEntry(entry);\n    }\n    return { ...entry, key };\n  }\n\n  set<T>(key: string, value: T, options: FarmCacheSetOptions = {}): FarmCacheEntry<T> {\n    const tags = new Set<string>();\n    for (const tag of options.tags ?? []) {\n      tags.add(normalizeCacheTag(tag));\n    }\n    for (const routePath of options.paths ?? []) {\n      tags.add(createPathCacheTag(routePath));\n    }\n\n    const entry: InternalFarmCacheEntry<T> = {\n      key,\n      value,\n      tags,\n      tagVersions: undefined,\n      createdAt: options.createdAt ?? Date.now(),\n      createdVersion: ++this.version,\n      revalidate: normalizeRevalidate(options.revalidate),\n    };\n\n    this.entries.set(key, entry);\n    emitFarmEvent({\n      type: \"cache.set\",\n      key,\n      tags: Array.from(tags),\n      revalidate: entry.revalidate,\n    });\n    return this.toPublicEntry(entry);\n  }\n\n  async setAsync<T>(\n    key: string,\n    value: T,\n    options: FarmCacheSetOptions = {},\n    tagVersions?: Readonly<Record<string, number>>,\n  ): Promise<FarmCacheEntry<T>> {\n    return this.writeAsync(key, value, options, tagVersions);\n  }\n\n  private async writeAsync<T>(\n    key: string,\n    value: T,\n    options: FarmCacheSetOptions,\n    tagVersions?: Readonly<Record<string, number>>,\n    createdVersion?: number,\n  ): Promise<FarmCacheEntry<T>> {\n    const tags = normalizeCacheOptionsTags(options);\n    const capturedVersions =\n      tagVersions ?? (await this.getAdapterTagVersions(Array.from(tags.values())));\n    const entry: FarmCacheEntry<T> = {\n      key,\n      value,\n      tags: Array.from(tags),\n      tagVersions: capturedVersions,\n      createdAt: options.createdAt ?? Date.now(),\n      createdVersion: createdVersion ?? ++this.version,\n      revalidate: normalizeRevalidate(options.revalidate),\n    };\n\n    if (this.local) {\n      this.hydrateLocalEntry(entry);\n    }\n    if (this.adapter) {\n      await this.adapter.set(this.createAdapterKey(key), entry);\n    }\n\n    emitFarmEvent({\n      type: \"cache.set\",\n      key,\n      tags: [...entry.tags],\n      revalidate: entry.revalidate,\n    });\n    return entry;\n  }\n\n  delete(key: string): boolean {\n    const deleted = this.entries.delete(key);\n    emitFarmEvent({ type: \"cache.delete\", key, deleted });\n    return deleted;\n  }\n\n  async deleteAsync(key: string): Promise<boolean> {\n    const deleted = this.entries.delete(key);\n    if (this.adapter) {\n      await this.adapter.delete(this.createAdapterKey(key));\n    }\n    emitFarmEvent({ type: \"cache.delete\", key, deleted: this.adapter ? true : deleted });\n    return this.adapter ? true : deleted;\n  }\n\n  clear(): void {\n    const count = this.entries.size;\n    this.generation++;\n    this.entries.clear();\n    this.inflight.clear();\n    this.invalidatedTagVersions.clear();\n    this.version = 0;\n    emitFarmEvent({ type: \"cache.clear\", count });\n  }\n\n  async clearAsync(): Promise<void> {\n    this.clear();\n    await this.adapter?.clear?.();\n  }\n\n  isStale(entry: FarmCacheStaleEntry, now = Date.now()): boolean {\n    if (\n      typeof entry.revalidate === \"number\" &&\n      entry.revalidate >= 0 &&\n      now - entry.createdAt >= entry.revalidate * 1000\n    ) {\n      return true;\n    }\n\n    for (const tag of entry.tags) {\n      const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));\n      if (\n        typeof invalidatedVersion === \"number\" &&\n        typeof entry.createdVersion === \"number\" &&\n        invalidatedVersion > entry.createdVersion\n      ) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  async isStaleAsync(entry: FarmCacheEntry, now = Date.now()): Promise<boolean> {\n    if (this.adapter) {\n      return this.isAdapterEntryStale(entry, now);\n    }\n    return this.isStale(entry, now);\n  }\n\n  revalidateTag(\n    tag: string,\n    options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n  ): number {\n    const normalized = normalizeCacheTag(tag);\n    const count = this.invalidateTag(normalized);\n    emitFarmEvent(\n      options.source === \"updateTag\"\n        ? { type: \"cache.updateTag\", tag: normalized, count }\n        : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n    );\n    return count;\n  }\n\n  async revalidateTagAsync(\n    tag: string,\n    options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n  ): Promise<number> {\n    const normalized = normalizeCacheTag(tag);\n    const count = this.invalidateTag(normalized);\n    await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);\n    emitFarmEvent(\n      options.source === \"updateTag\"\n        ? { type: \"cache.updateTag\", tag: normalized, count }\n        : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n    );\n    return count;\n  }\n\n  revalidatePath(routePath: string): number {\n    const normalizedPath = normalizeRevalidatePath(routePath);\n    const pathTag = createPathCacheTag(normalizedPath);\n    const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n    const count = this.invalidateTag(pathTag);\n    emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n    if (pprCount > 0) {\n      emitFarmEvent({\n        type: \"ppr.shell.invalidated\",\n        route: normalizedPath,\n        reason: \"revalidatePath\",\n        count: pprCount,\n      });\n    }\n\n    return count;\n  }\n\n  async revalidatePathAsync(routePath: string): Promise<number> {\n    const normalizedPath = normalizeRevalidatePath(routePath);\n    const pathTag = createPathCacheTag(normalizedPath);\n    const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n    const count = this.invalidateTag(pathTag);\n    await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);\n    emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n    if (pprCount > 0) {\n      emitFarmEvent({\n        type: \"ppr.shell.invalidated\",\n        route: normalizedPath,\n        reason: \"revalidatePath\",\n        count: pprCount,\n      });\n    }\n\n    return count;\n  }\n\n  async getOrSet<T>(\n    key: string,\n    producer: () => Promise<T> | T,\n    options: FarmCacheOptions = {},\n  ): Promise<T> {\n    const cached = await this.getEntryAsync<T>(key);\n    if (cached) {\n      return cached.value;\n    }\n\n    const inflight = this.inflight.get(key) as Promise<T> | undefined;\n    if (inflight) {\n      emitFarmEvent({ type: \"cache.dedupe\", key });\n      return inflight;\n    }\n\n    const tags = Array.from(normalizeCacheOptionsTags(options));\n    const generation = this.generation;\n    const promise = this.fillCacheEntry(key, producer, options, tags, generation)\n      .catch((error) => {\n        emitFarmEvent({ type: \"cache.error\", key, operation: \"set\", error });\n        throw error;\n      })\n      .finally(() => {\n        if (this.inflight.get(key) === promise) {\n          this.inflight.delete(key);\n        }\n      });\n\n    this.inflight.set(key, promise);\n    return promise;\n  }\n\n  private async fillCacheEntry<T>(\n    key: string,\n    producer: () => Promise<T> | T,\n    options: FarmCacheOptions,\n    tags: readonly string[],\n    generation: number,\n  ): Promise<T> {\n    const adapter = this.adapter;\n    const namespace = this.namespace;\n    const lease = { ...this.lease };\n    const leaseKey = `${namespace}:lease:${key}`;\n    let leaseToken: string | null | undefined;\n\n    if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {\n      leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n      if (!leaseToken) {\n        const shared = await this.waitForAdapterEntry<T>(\n          key,\n          adapter,\n          namespace,\n          lease,\n          generation,\n        );\n        if (shared) {\n          emitFarmEvent({ type: \"cache.dedupe\", key });\n          return shared.value;\n        }\n        if (generation === this.generation) {\n          leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n        }\n      }\n    }\n\n    try {\n      const initialCreatedVersion = this.version;\n      const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);\n      const value = await producer();\n      if (generation === this.generation) {\n        await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);\n      }\n      return value;\n    } finally {\n      if (leaseToken && adapter?.releaseLease) {\n        await adapter.releaseLease(leaseKey, leaseToken);\n      }\n    }\n  }\n\n  private async waitForAdapterEntry<T>(\n    key: string,\n    adapter: FarmCacheAdapter,\n    namespace: string,\n    lease: typeof this.lease,\n    generation: number,\n  ): Promise<FarmCacheEntry<T> | undefined> {\n    const deadline = Date.now() + lease.waitTimeoutMs;\n    while (Date.now() < deadline) {\n      await delay(lease.pollIntervalMs);\n      if (generation !== this.generation) return undefined;\n      const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n      if (generation !== this.generation) return undefined;\n      if (!entry) {\n        emitFarmEvent({ type: \"cache.miss\", key });\n        continue;\n      }\n      assertFarmCacheEntry(entry, key);\n      const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);\n      if (generation !== this.generation) return undefined;\n      if (stale) {\n        emitFarmEvent({\n          type: \"cache.stale\",\n          key,\n          tags: [...entry.tags],\n          revalidate: entry.revalidate,\n        });\n        emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n      } else {\n        emitFarmEvent({\n          type: \"cache.hit\",\n          key,\n          tags: [...entry.tags],\n          revalidate: entry.revalidate,\n          stale: false,\n        });\n        return { ...entry, key };\n      }\n    }\n    return undefined;\n  }\n\n  private countEntriesForTag(tag: string): number {\n    let count = 0;\n    for (const entry of this.entries.values()) {\n      if (entry.tags.has(tag)) {\n        count++;\n      }\n    }\n    return count;\n  }\n\n  private countEntriesForTags(tags: readonly string[]): number {\n    let count = 0;\n    for (const entry of this.entries.values()) {\n      if (tags.every((tag) => entry.tags.has(tag))) {\n        count++;\n      }\n    }\n    return count;\n  }\n\n  private invalidateTag(normalizedTag: string): number {\n    this.invalidatedTagVersions.set(normalizedTag, ++this.version);\n    return this.countEntriesForTag(normalizedTag);\n  }\n\n  private toPublicEntry<T>(entry: InternalFarmCacheEntry<T>): FarmCacheEntry<T> {\n    return {\n      key: entry.key,\n      value: entry.value,\n      tags: Array.from(entry.tags),\n      tagVersions: entry.tagVersions,\n      createdAt: entry.createdAt,\n      createdVersion: entry.createdVersion,\n      revalidate: entry.revalidate,\n    };\n  }\n\n  private hydrateLocalEntry<T>(entry: FarmCacheEntry<T>): void {\n    this.entries.set(entry.key, {\n      key: entry.key,\n      value: entry.value,\n      tags: new Set(entry.tags.map(normalizeCacheTag)),\n      tagVersions: entry.tagVersions,\n      createdAt: entry.createdAt,\n      createdVersion: entry.createdVersion ?? ++this.version,\n      revalidate: normalizeRevalidate(entry.revalidate),\n    });\n  }\n\n  private createAdapterKey(key: string): string {\n    return `${this.namespace}:entry:${key}`;\n  }\n\n  private createAdapterTag(tag: string): string {\n    return `${this.namespace}:tag:${tag}`;\n  }\n\n  private async getAdapterTagVersions(\n    tags: readonly string[],\n    adapter = this.adapter,\n    namespace = this.namespace,\n  ): Promise<Readonly<Record<string, number>>> {\n    if (!adapter?.getTagVersions || tags.length === 0) return {};\n\n    const normalized = tags.map(normalizeCacheTag);\n    const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);\n    const versions = await adapter.getTagVersions(physicalTags);\n    return Object.fromEntries(\n      normalized.map((tag, index) => [\n        tag,\n        normalizeAdapterVersion(versions[physicalTags[index]!]),\n      ]),\n    );\n  }\n\n  private async isAdapterEntryStale(\n    entry: FarmCacheEntry,\n    now = Date.now(),\n    adapter = this.adapter,\n    namespace = this.namespace,\n  ): Promise<boolean> {\n    if (\n      typeof entry.revalidate === \"number\" &&\n      entry.revalidate >= 0 &&\n      now - entry.createdAt >= entry.revalidate * 1000\n    ) {\n      return true;\n    }\n\n    const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);\n    for (const tag of entry.tags) {\n      if (\n        normalizeAdapterVersion(currentVersions[tag]) >\n        normalizeAdapterVersion(entry.tagVersions?.[tag])\n      ) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n\nconst FARM_DATA_CACHE_SYMBOL = Symbol.for(\"farm.dataCache\");\nconst farmDataCacheGlobal = globalThis as typeof globalThis & {\n  [FARM_DATA_CACHE_SYMBOL]?: FarmDataCache;\n};\nconst sharedFarmDataCache = (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ??= new FarmDataCache());\n\nexport function getFarmDataCache(): FarmDataCache {\n  return sharedFarmDataCache;\n}\n\nexport function configureFarmCache(config: FarmCacheUserConfig | undefined): void {\n  sharedFarmDataCache.configure(config);\n}\n\n/**\n * Wrap an async function so its results are cached and shared across requests,\n * processes, and restarts.\n *\n * The cache key is built from the wrapped function's identity (its name and a\n * hash of its source), the active locale, `keyParts`, and the call arguments.\n * Deriving identity from the source — rather than the closure instance — is\n * deliberate: it keeps the key stable across processes and restarts so a\n * distributed cache adapter can share entries between server instances.\n *\n * The consequence is that two closures with **identical source text but\n * different captured variables** produce the same identity. Pass those captured\n * values in `keyParts` so they take part in the key; otherwise the closures\n * share a cache entry and return each other's data:\n *\n * ```ts\n * // Collides: both closures have identical source, and `table` is captured,\n * // not an argument, so it never reaches the key.\n * const makeLoader = (table: string) =>\n *   unstable_cache(async (id: number) => db.get(table, id));\n *\n * // Correct: the captured value disambiguates the two closures.\n * const makeLoader = (table: string) =>\n *   unstable_cache(async (id: number) => db.get(table, id), [table]);\n * ```\n *\n * Values passed as call arguments already participate in the key and do not\n * need to be repeated in `keyParts`.\n *\n * @param fn The async function to memoize.\n * @param keyParts Extra values that identify this call site. Include every\n *   variable the function closes over that is not one of its arguments.\n * @param options Tags, paths, and revalidation settings for the cached entry.\n */\nexport function unstable_cache<Args extends unknown[], Result>(\n  fn: (...args: Args) => Result | Promise<Result>,\n  keyParts: readonly unknown[] = [],\n  options: FarmCacheOptions = {},\n): (...args: Args) => Promise<Result> {\n  return async (...args: Args): Promise<Result> => {\n    const locale = getActiveFarmI18nSnapshot()?.locale;\n    const key = createFarmCacheKey([\n      \"unstable_cache\",\n      getFunctionCacheIdentity(fn),\n      locale ? [\"locale\", locale] : null,\n      keyParts,\n      args,\n    ]);\n    return getFarmDataCache().getOrSet<Result>(key, () => fn(...args), options);\n  };\n}\n\n/**\n * Invalidate every cache entry carrying `tag`.\n *\n * Observability note: the `count` on the emitted `cache.revalidateTag` event is\n * derived from Farm's process-local entry tracking. With a shared `cache.adapter`\n * configured, entries live in the adapter rather than in local memory, so the\n * count can read as `0` even though the invalidation is still propagated to the\n * adapter and applied. Treat it as a best-effort signal, not a distributed count.\n */\nexport function revalidateTag(_tag: string, _profile?: RevalidateTagProfile): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache\n      .revalidateTagAsync(_tag, {\n        source: \"revalidateTag\",\n        profile: _profile,\n      })\n      .then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidateTag(_tag, {\n    source: \"revalidateTag\",\n    profile: _profile,\n  });\n}\n\nexport function updateTag(tag: string): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache.revalidateTagAsync(tag, { source: \"updateTag\" }).then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidateTag(tag, { source: \"updateTag\" });\n}\n\n/**\n * Invalidate cached data for a route path (and its PPR shell, if any).\n *\n * Observability note: the `count` on the emitted `cache.revalidatePath` event and\n * the `ppr.shell.invalidated` event are derived from process-local entry tracking.\n * With a shared `cache.adapter`, PPR shells live in the adapter rather than in\n * local memory, so the count can read as `0` and `ppr.shell.invalidated` may not\n * be emitted even though the invalidation is still propagated to the adapter and\n * applied.\n */\nexport function revalidatePath(routePath: string): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache.revalidatePathAsync(routePath).then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidatePath(routePath);\n}\n\nexport function invalidate(key: RouteDataCacheKey): void | Promise<void> {\n  const clientKey = createRouteDataCacheKey(key);\n  const task = updateTag(createRouteDataCacheTag(key));\n  notifyFarmCacheInvalidation(clientKey);\n  return task;\n}\n\nexport function invalidateRouteData(key: RouteDataCacheKey): void | Promise<void> {\n  return invalidate(key);\n}\n\n/**\n * Apply a normalized set of invalidation targets and return browser cache keys\n * that should be carried with an action/endpoint response.\n */\nexport async function applyFarmCacheInvalidationTargets(\n  targets: readonly FarmCacheInvalidationTarget[],\n): Promise<readonly string[]> {\n  if (!Array.isArray(targets)) {\n    throw new TypeError(\"Cache invalidations must resolve to an array of targets.\");\n  }\n\n  const clientKeys: string[] = [];\n  for (const target of targets) {\n    assertFarmCacheInvalidationTarget(target);\n    if (\"key\" in target) {\n      await invalidate(target.key);\n      clientKeys.push(createRouteDataCacheKey(target.key));\n    } else if (\"path\" in target) {\n      await revalidatePath(target.path);\n    } else {\n      await updateTag(target.tag);\n    }\n  }\n  return Array.from(new Set(clientKeys));\n}\n\nexport function createPathCacheTag(routePath: string): string {\n  return `path:${normalizeRevalidatePath(routePath)}`;\n}\n\nexport function createRouteDataCacheTag(key: RouteDataCacheKey): string {\n  return `route-data:${createRouteDataCacheKey(key)}`;\n}\n\nexport function createRouteDataCacheKey(key: RouteDataCacheKey): string {\n  return createFarmCacheKey(Array.isArray(key) ? key : [key]);\n}\n\nexport function normalizeRevalidatePath(routePath: string): string {\n  if (typeof routePath !== \"string\") {\n    throw new TypeError(\"revalidatePath expects a path string.\");\n  }\n\n  let normalized = routePath.trim();\n  if (!normalized) {\n    throw new Error(\"revalidatePath expects a non-empty path.\");\n  }\n\n  try {\n    if (/^https?:\\/\\//i.test(normalized)) {\n      normalized = new URL(normalized).pathname;\n    }\n  } catch {\n    // Keep the original path if URL parsing fails.\n  }\n\n  normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;\n  normalized = normalized.startsWith(\"/\") ? normalized : `/${normalized}`;\n  normalized = normalized.replace(/\\/{2,}/g, \"/\");\n  if (normalized.length > 1) {\n    normalized = normalized.replace(/\\/+$/, \"\");\n  }\n  return normalized || \"/\";\n}\n\nexport function createFarmCacheKey(parts: readonly unknown[]): string {\n  return stableSerialize(parts);\n}\n\nfunction normalizeRevalidate(revalidate: number | false | undefined): number | false | undefined {\n  if (revalidate === false || revalidate === undefined) {\n    return revalidate;\n  }\n  if (!Number.isFinite(revalidate) || revalidate < 0) {\n    return undefined;\n  }\n  // 0 is meaningful: the entry is stale immediately, i.e. always re-produced.\n  return revalidate;\n}\n\nfunction normalizeCacheTag(tag: string): string {\n  if (typeof tag !== \"string\") {\n    throw new TypeError(\"Cache tags must be strings.\");\n  }\n  const normalized = tag.trim();\n  if (!normalized) {\n    throw new Error(\"Cache tags cannot be empty.\");\n  }\n  return normalized;\n}\n\nfunction normalizeCacheNamespace(namespace: string): string {\n  if (typeof namespace !== \"string\") {\n    throw new TypeError(\"Cache namespace must be a string.\");\n  }\n  const normalized = namespace.trim().replace(/:+$/g, \"\");\n  if (!normalized) {\n    throw new Error(\"Cache namespace cannot be empty.\");\n  }\n  return normalized;\n}\n\nfunction normalizeAdapterVersion(value: unknown): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\n}\n\nfunction normalizePositiveDuration(\n  value: number | undefined,\n  fallback: number,\n  name: string,\n): number {\n  if (value === undefined) return fallback;\n  if (!Number.isFinite(value) || value <= 0) {\n    throw new TypeError(`${name} must be a positive number of milliseconds.`);\n  }\n  return Math.floor(value);\n}\n\nfunction delay(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction normalizeCacheOptionsTags(options: FarmCacheOptions): Set<string> {\n  const tags = new Set<string>();\n  for (const tag of options.tags ?? []) {\n    tags.add(normalizeCacheTag(tag));\n  }\n  for (const routePath of options.paths ?? []) {\n    tags.add(createPathCacheTag(routePath));\n  }\n  return tags;\n}\n\nfunction assertFarmCacheEntry(\n  entry: FarmCacheEntry,\n  expectedKey: string,\n): asserts entry is FarmCacheEntry {\n  if (\n    !entry ||\n    typeof entry !== \"object\" ||\n    entry.key !== expectedKey ||\n    !Array.isArray(entry.tags) ||\n    typeof entry.createdAt !== \"number\"\n  ) {\n    throw new TypeError(\n      `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`,\n    );\n  }\n}\n\nfunction assertFarmCacheInvalidationTarget(\n  target: unknown,\n): asserts target is FarmCacheInvalidationTarget {\n  if (!target || typeof target !== \"object\") {\n    throw new TypeError(\"Cache invalidation targets must be { key }, { path }, or { tag }.\");\n  }\n\n  if (\"key\" in target) {\n    const key = (target as { key?: unknown }).key;\n    if (typeof key === \"string\" || Array.isArray(key)) return;\n  } else if (\"path\" in target && typeof (target as { path?: unknown }).path === \"string\") {\n    return;\n  } else if (\"tag\" in target && typeof (target as { tag?: unknown }).tag === \"string\") {\n    return;\n  }\n\n  throw new TypeError(\"Cache invalidation targets must contain a string/array key, path, or tag.\");\n}\n\nfunction getFunctionCacheIdentity(fn: Function): string {\n  // The name alone collides across modules — two different functions both\n  // named getUser would share cache entries. Include a hash of the source so\n  // only genuinely identical functions share, and the identity stays stable\n  // across processes and restarts.\n  const name = fn.name || \"anonymous\";\n  return `${name}:${hashFunctionSource(String(fn))}`;\n}\n\nfunction hashFunctionSource(source: string): string {\n  // FNV-1a, 32-bit.\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < source.length; index++) {\n    hash ^= source.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(36);\n}\n\nfunction compareCodepoint(a: string, b: string): number {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction serializeBinaryBytes(bytes: Uint8Array): string {\n  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction 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","\"use client\";\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n  applyServerFnOptimisticUpdates,\n  isAPIRouteRef,\n  resolveServerFnInvalidateTargets,\n  settleServerFnOptimisticUpdates,\n  type APIResult,\n  type ClientOptions,\n} from \"./api/client\";\nimport { notifyFarmCacheInvalidation } from \"./cache-invalidation\";\nimport { isNavigatorOnline, subscribeOnline } from \"./client-network-status\";\nimport { notifyClientObserver } from \"./client-observers\";\nimport { invokeMutationWithRetry } from \"./mutation-retry\";\n\nexport type MutationStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport type AnyMutationTarget = (...args: any[]) => Promise<any>;\n\nexport type InferMutationVariables<TTarget extends AnyMutationTarget> =\n  Parameters<TTarget> extends [] ? undefined : Parameters<TTarget>[0];\n\nexport type InferMutationData<TTarget extends AnyMutationTarget> = TTarget extends {\n  readonly __farmRouteData: infer TData;\n}\n  ? TData\n  : Awaited<ReturnType<TTarget>>;\n\nexport type InferMutationError<TTarget extends AnyMutationTarget> = TTarget extends {\n  readonly __farmServerFnError: infer TError;\n}\n  ? TError\n  : TTarget extends (...args: any[]) => Promise<APIResult<any, infer TError>>\n    ? TError\n    : Error;\n\nexport type MutationOptimisticContext<TVariables, TData> = {\n  variables: TVariables | undefined;\n  current: TData | null;\n};\n\nexport type MutationNetworkMode = \"always\" | \"online\";\n\nexport type UseMutationOptions<TVariables, TData, TError = Error> = {\n  initialData?: TData | null;\n  resetOnMutate?: boolean;\n  /**\n   * `\"always\"` (default) dispatches regardless of connectivity, preserving\n   * existing behavior. `\"online\"` pauses a submission while the browser is\n   * offline — including one whose dispatch failed while offline — and resumes\n   * it on the `online` event instead of failing it.\n   */\n  networkMode?: MutationNetworkMode;\n  optimistic?: (context: MutationOptimisticContext<TVariables, TData>) => TData | null | undefined;\n  rollbackOnError?: boolean;\n  /**\n   * Options forwarded to generated `api.route.method` clients.\n   * Server-function targets honor `request.retry`, key-targeted\n   * `request.optimistic` updates, and key-targeted `request.invalidate`;\n   * the remaining request options apply to API routes only.\n   */\n  request?: ClientOptions<TData, TError>;\n  onSuccess?: (data: TData, variables: TVariables | undefined) => void;\n  onError?: (error: TError, variables: TVariables | undefined) => void;\n  onSettled?: (data: TData | null, error: TError | null, variables: TVariables | undefined) => void;\n};\n\ntype MutationInput<TTarget extends AnyMutationTarget> = InferMutationVariables<TTarget>;\n\ntype MutationData<TTarget extends AnyMutationTarget> = InferMutationData<TTarget>;\n\ntype MutationError<TTarget extends AnyMutationTarget> = InferMutationError<TTarget>;\n\nexport type MutationAsync<TTarget extends AnyMutationTarget, TData = MutationData<TTarget>> =\n  [] extends Parameters<TTarget>\n    ? (variables?: MutationInput<TTarget>) => Promise<TData>\n    : (variables: MutationInput<TTarget>) => Promise<TData>;\n\nexport type MutationTrigger<TTarget extends AnyMutationTarget> =\n  [] extends Parameters<TTarget>\n    ? (variables?: MutationInput<TTarget>) => void\n    : (variables: MutationInput<TTarget>) => void;\n\nexport type UseMutationReturn<\n  TTarget extends AnyMutationTarget,\n  TData = MutationData<TTarget>,\n  TError = MutationError<TTarget>,\n> = {\n  pending: boolean;\n  /** True while a submission is waiting for the browser to come back online. */\n  paused: boolean;\n  status: MutationStatus;\n  data: TData | null;\n  error: TError | null;\n  variables: MutationInput<TTarget> | undefined;\n  mutate: MutationTrigger<TTarget>;\n  mutateAsync: MutationAsync<TTarget, TData>;\n  reset: () => void;\n};\n\ntype MutationState<TVariables, TData, TError> = {\n  pendingCount: number;\n  pausedCount: number;\n  status: MutationStatus;\n  data: TData | null;\n  error: TError | null;\n  variables: TVariables | undefined;\n};\n\n/**\n * Track a generated API route mutation or a Farm server function with one\n * React lifecycle.\n *\n * API routes keep using their existing fetch transport and request options.\n * Server functions keep using their configured server-function transport.\n */\nexport function useMutation<TTarget extends AnyMutationTarget>(\n  target: TTarget,\n  options: UseMutationOptions<\n    MutationInput<TTarget>,\n    MutationData<TTarget>,\n    MutationError<TTarget>\n  > = {},\n): UseMutationReturn<TTarget> {\n  return useMutationLifecycle(target, options).mutation;\n}\n\n/** Internal shared lifecycle: fetchers prepare form input before dispatch. */\nexport function useMutationLifecycle<\n  TTarget extends AnyMutationTarget,\n  TError = MutationError<TTarget>,\n>(\n  target: TTarget,\n  options: Omit<\n    UseMutationOptions<MutationInput<TTarget>, MutationData<TTarget>, TError>,\n    \"request\"\n  > & {\n    request?: ClientOptions<MutationData<TTarget>, MutationError<TTarget>>;\n  } = {},\n) {\n  type TVariables = MutationInput<TTarget>;\n  type TData = MutationData<TTarget>;\n\n  const initialData = options.initialData ?? null;\n  const optionsRef = useRef(options);\n  const targetRef = useRef(target);\n  const requestIdRef = useRef(0);\n  const lastResetIdRef = useRef(0);\n  const initialState: MutationState<TVariables, TData, TError> = {\n    pendingCount: 0,\n    pausedCount: 0,\n    status: \"idle\",\n    data: initialData,\n    error: null,\n    variables: undefined,\n  };\n  const stateRef = useRef(initialState);\n  const resetWakersRef = useRef(new Set<() => void>());\n  const [state, setState] = useState<MutationState<TVariables, TData, TError>>(initialState);\n\n  optionsRef.current = options;\n  targetRef.current = target;\n\n  const setMutationState = useCallback(\n    (\n      value:\n        | MutationState<TVariables, TData, TError>\n        | ((\n            current: MutationState<TVariables, TData, TError>,\n          ) => MutationState<TVariables, TData, TError>),\n    ) => {\n      // Advance the authoritative snapshot before React processes its queue.\n      // A second submission in this batch must see the preceding transition.\n      const next = typeof value === \"function\" ? value(stateRef.current) : value;\n      stateRef.current = next;\n      setState(next);\n    },\n    [],\n  );\n\n  const waitForReconnect = useCallback(\n    async (requestId: number) => {\n      while (!isNavigatorOnline()) {\n        if (requestId < lastResetIdRef.current) return;\n        setMutationState((current) => ({ ...current, pausedCount: current.pausedCount + 1 }));\n        try {\n          await new Promise<void>((resolve) => {\n            const wake = () => {\n              unsubscribe();\n              resetWakersRef.current.delete(wake);\n              resolve();\n            };\n            const unsubscribe = subscribeOnline(wake);\n            resetWakersRef.current.add(wake);\n          });\n        } finally {\n          setMutationState((current) => ({\n            ...current,\n            pausedCount: Math.max(0, current.pausedCount - 1),\n          }));\n        }\n      }\n    },\n    [setMutationState],\n  );\n\n  const mutatePreparedAsync = useCallback(\n    async (prepare: () => TVariables | undefined) => {\n      const requestId = ++requestIdRef.current;\n      const currentOptions = optionsRef.current;\n      const previousData = stateRef.current.data;\n      let variables: TVariables | undefined;\n      let preparationFailed = false;\n      let preparationError: unknown;\n      try {\n        variables = prepare();\n      } catch (error) {\n        preparationFailed = true;\n        preparationError = error;\n      }\n      const optimisticData = preparationFailed\n        ? undefined\n        : currentOptions.optimistic?.({ variables, current: previousData });\n      const hasOptimisticData = optimisticData !== undefined;\n\n      setMutationState((current) => {\n        // Preparation is app code and may reset or submit again synchronously.\n        if (requestId < lastResetIdRef.current) return current;\n        const pendingCount = current.pendingCount + 1;\n        if (requestId !== requestIdRef.current) return { ...current, pendingCount };\n        return {\n          pendingCount,\n          pausedCount: current.pausedCount,\n          status: \"pending\",\n          data: hasOptimisticData\n            ? optimisticData\n            : currentOptions.resetOnMutate === false\n              ? current.data\n              : null,\n          error: null,\n          variables,\n        };\n      });\n\n      const mutationTarget = targetRef.current;\n      const isAPITarget = isAPIRouteRef(mutationTarget);\n      // API routes run their own cache-layered optimistic engine; server\n      // functions apply key-targeted updates to the shared cache here.\n      const sharedOptimistic =\n        !preparationFailed && !isAPITarget ? currentOptions.request?.optimistic : undefined;\n      const sharedSnapshots = sharedOptimistic?.update?.length\n        ? applyServerFnOptimisticUpdates(sharedOptimistic.update)\n        : [];\n\n      try {\n        if (preparationFailed) throw preparationError;\n        let data!: TData;\n        while (true) {\n          if (currentOptions.networkMode === \"online\") {\n            await waitForReconnect(requestId);\n            if (requestId < lastResetIdRef.current) {\n              throw new Error(\"Mutation reset while waiting for reconnection\");\n            }\n          }\n          try {\n            const rawResult = isAPITarget\n              ? await mutationTarget(variables, currentOptions.request)\n              : await invokeMutationWithRetry(\n                  () => targetRef.current(variables),\n                  currentOptions.request?.retry,\n                  // A reset disowns this submission; stop scheduling retries then.\n                  () => requestId >= lastResetIdRef.current,\n                );\n            data = unwrapMutationResult<TData, TError>(rawResult, isAPITarget);\n            break;\n          } catch (cause) {\n            // A dispatch that failed *because of connectivity* while offline\n            // pauses and rides the next reconnect. An application error (a\n            // typed business failure from a request that reached the server)\n            // must surface instead, or it would be swallowed and the payload\n            // silently re-submitted on reconnect, duplicating a non-idempotent\n            // write.\n            if (\n              currentOptions.networkMode === \"online\" &&\n              !isNavigatorOnline() &&\n              requestId >= lastResetIdRef.current &&\n              isConnectivityFailure(cause)\n            ) {\n              continue;\n            }\n            throw cause;\n          }\n        }\n\n        settleServerFnOptimisticUpdates(sharedSnapshots, \"commit\");\n        if (!isAPITarget && currentOptions.request?.invalidate) {\n          // Server-function invalidations travel the shared bus, matching\n          // server-declared `invalidates`, so every subscribed cache observes them.\n          for (const key of resolveServerFnInvalidateTargets(currentOptions.request.invalidate)) {\n            notifyFarmCacheInvalidation(key);\n          }\n        }\n\n        const isLatestRequest = requestId === requestIdRef.current;\n\n        setMutationState((current) => {\n          if (requestId < lastResetIdRef.current) return current;\n          const pendingCount = Math.max(0, current.pendingCount - 1);\n          if (!isLatestRequest) {\n            return {\n              ...current,\n              pendingCount,\n            };\n          }\n\n          return {\n            pendingCount,\n            pausedCount: current.pausedCount,\n            status: \"success\",\n            data,\n            error: null,\n            variables,\n          };\n        });\n\n        if (isLatestRequest) {\n          notifyClientObserver(currentOptions.onSuccess, [data, variables], \"Mutation onSuccess\");\n          if (requestId === requestIdRef.current) {\n            notifyClientObserver(\n              currentOptions.onSettled,\n              [data, null, variables],\n              \"Mutation onSettled\",\n            );\n          }\n        }\n\n        return data;\n      } catch (cause) {\n        settleServerFnOptimisticUpdates(\n          sharedSnapshots,\n          sharedOptimistic?.rollbackOnError ? \"rollback\" : \"invalidate\",\n        );\n        const error = normalizeMutationError(cause) as TError;\n        const isLatestRequest = requestId === requestIdRef.current;\n\n        setMutationState((current) => {\n          if (requestId < lastResetIdRef.current) return current;\n          const pendingCount = Math.max(0, current.pendingCount - 1);\n          if (!isLatestRequest) {\n            return {\n              ...current,\n              pendingCount,\n            };\n          }\n\n          return {\n            pendingCount,\n            pausedCount: current.pausedCount,\n            status: \"error\",\n            data:\n              hasOptimisticData && currentOptions.rollbackOnError\n                ? previousData\n                : currentOptions.resetOnMutate === false\n                  ? current.data\n                  : null,\n            error,\n            variables,\n          };\n        });\n\n        if (isLatestRequest) {\n          notifyClientObserver(currentOptions.onError, [error, variables], \"Mutation onError\");\n          if (requestId === requestIdRef.current) {\n            notifyClientObserver(\n              currentOptions.onSettled,\n              [null, error, variables],\n              \"Mutation onSettled\",\n            );\n          }\n        }\n\n        throw error;\n      }\n    },\n    [setMutationState, waitForReconnect],\n  );\n\n  const mutateAsync = useCallback(\n    (variables?: TVariables) => mutatePreparedAsync(() => variables),\n    [mutatePreparedAsync],\n  ) as MutationAsync<TTarget, TData>;\n\n  const mutate = useCallback(\n    (variables?: TVariables) => {\n      void mutateAsync(variables as never).catch(() => {});\n    },\n    [mutateAsync],\n  ) as MutationTrigger<TTarget>;\n\n  const reset = useCallback(() => {\n    // Pre-reset requests no longer own any of the current pending count.\n    lastResetIdRef.current = ++requestIdRef.current;\n    setMutationState({\n      pendingCount: 0,\n      pausedCount: 0,\n      status: \"idle\",\n      data: optionsRef.current.initialData ?? null,\n      error: null,\n      variables: undefined,\n    });\n    // Wake paused submissions so they reject instead of waiting for `online`.\n    const wakers = Array.from(resetWakersRef.current);\n    resetWakersRef.current.clear();\n    for (const wake of wakers) wake();\n  }, [setMutationState]);\n\n  const mutation: UseMutationReturn<TTarget, TData, TError> = useMemo(\n    () => ({\n      pending: state.pendingCount > 0,\n      paused: state.pausedCount > 0,\n      status: state.status,\n      data: state.data,\n      error: state.error,\n      variables: state.variables,\n      mutate,\n      mutateAsync,\n      reset,\n    }),\n    [\n      mutate,\n      mutateAsync,\n      reset,\n      state.data,\n      state.error,\n      state.pausedCount,\n      state.pendingCount,\n      state.status,\n      state.variables,\n    ],\n  );\n  return { mutation, mutatePreparedAsync };\n}\n\n/**\n * Whether a thrown value represents a connectivity failure (as opposed to an\n * application/business error). Only connectivity failures are safe to pause and\n * retry on reconnect; an application error means the request reached the server\n * and produced a real result. The client tags transport failures with an\n * `APIClientError` code of `network_error` or `timeout`; a raw fetch/transport\n * failure surfaces as a `TypeError`.\n */\nfunction isConnectivityFailure(error: unknown): boolean {\n  if (error instanceof TypeError) return true;\n  const code = (error as { code?: unknown } | null | undefined)?.code;\n  return code === \"network_error\" || code === \"timeout\";\n}\n\nfunction unwrapMutationResult<TData, TError>(result: unknown, apiRoute: boolean): TData {\n  if (!apiRoute) return result as TData;\n\n  const apiResult = result as APIResult<TData, TError>;\n  if (apiResult.error) {\n    throw apiResult.error;\n  }\n\n  return apiResult.data as TData;\n}\n\nfunction normalizeMutationError(error: unknown): Error {\n  if (error instanceof Error) return error;\n\n  const normalized = new Error(typeof error === \"string\" ? error : \"Mutation failed\");\n  (normalized as Error & { cause?: unknown }).cause = error;\n  return normalized;\n}\n","/**\n * Connectivity observation for the client data layer. Environments without a\n * navigator (server rendering, tests) report online so nothing ever pauses\n * there.\n */\nexport function isNavigatorOnline(): boolean {\n  if (typeof navigator === \"undefined\" || typeof navigator.onLine !== \"boolean\") return true;\n  return navigator.onLine;\n}\n\n/** Subscribe to the browser `online` event. Returns a disposer; no-op outside the browser. */\nexport function subscribeOnline(listener: () => void): () => void {\n  if (typeof window === \"undefined\") return () => {};\n  window.addEventListener(\"online\", listener);\n  return () => window.removeEventListener(\"online\", listener);\n}\n","import type { RetryOptions } from \"./api/client\";\n\n/**\n * Retry a server-function mutation with the API client's retry shape.\n *\n * Attempts run until success, until `count` retries are exhausted, or until\n * `shouldContinue` reports that the owning lifecycle was reset. The delay\n * callback receives the upcoming attempt number starting at 1, matching the\n * API client. Defaults to zero retries so existing behavior is unchanged.\n */\nexport async function invokeMutationWithRetry<T>(\n  invoke: () => Promise<T>,\n  retry: RetryOptions | undefined,\n  shouldContinue: () => boolean,\n): Promise<T> {\n  const maxRetries = Math.max(0, retry?.count ?? 0);\n  let attempt = 0;\n\n  while (true) {\n    try {\n      return await invoke();\n    } catch (error) {\n      if (attempt >= maxRetries || !shouldContinue()) throw error;\n\n      attempt += 1;\n      const delay = typeof retry?.delay === \"function\" ? retry.delay(attempt) : (retry?.delay ?? 0);\n      if (delay > 0) {\n        await new Promise<void>((resolve) => setTimeout(resolve, delay));\n        // The lifecycle may have been reset while this attempt waited.\n        if (!shouldContinue()) throw error;\n      }\n    }\n  }\n}\n","\"use client\";\n\nimport {\n  createElement,\n  useCallback,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentType,\n  type FormEvent,\n  type FormHTMLAttributes,\n} from \"react\";\nimport { getAPIRouteRefMetadata, isAPIRouteRef } from \"./api/client\";\nimport {\n  useMutationLifecycle,\n  type AnyMutationTarget,\n  type InferMutationData,\n  type InferMutationError,\n  type InferMutationVariables,\n  type MutationStatus,\n  type UseMutationOptions,\n} from \"./mutation-client\";\n\nexport type FetcherState = \"idle\" | \"submitting\";\n\n/** Local form conversion failed before the target was called. */\nexport class FetcherInputError extends Error {\n  readonly name = \"FetcherInputError\" as const;\n  readonly code = \"input_error\" as const;\n  readonly status = 0 as const;\n  readonly data = undefined;\n  readonly cause: unknown;\n\n  constructor(cause: unknown) {\n    super(\n      cause instanceof Error\n        ? cause.message\n        : typeof cause === \"string\"\n          ? cause\n          : \"Could not prepare form input\",\n    );\n    this.cause = cause;\n  }\n}\n\nexport type FetcherFormDataContext = {\n  form: HTMLFormElement | null;\n  submitter: HTMLElement | null;\n};\n\nexport type UseFetcherOptions<TTarget extends AnyMutationTarget> = Omit<\n  UseMutationOptions<\n    InferMutationVariables<TTarget>,\n    InferMutationData<TTarget>,\n    InferMutationError<TTarget> | FetcherInputError\n  >,\n  \"request\"\n> & {\n  request?: UseMutationOptions<\n    InferMutationVariables<TTarget>,\n    InferMutationData<TTarget>,\n    InferMutationError<TTarget>\n  >[\"request\"];\n  /**\n   * Convert browser FormData into the target's typed variables.\n   *\n   * Generated API routes preserve multipart forms and file values as a FormData\n   * body; text-only submissions default to a JSON object (or query for GET/HEAD).\n   * Server functions receive FormData directly. This mapper overrides defaults.\n   */\n  mapFormData?: (\n    formData: FormData,\n    context: FetcherFormDataContext,\n  ) => InferMutationVariables<TTarget>;\n};\n\nexport type FetcherFormProps = Omit<FormHTMLAttributes<HTMLFormElement>, \"action\" | \"onSubmit\"> & {\n  /**\n   * Override the native form fallback. By default server functions remain the\n   * action and generated GET/POST API routes use their real URL.\n   */\n  action?: string | ((formData: FormData) => void | Promise<void>);\n  onSubmit?: (event: FormEvent<HTMLFormElement>) => void;\n};\n\ntype FetcherInput<TTarget extends AnyMutationTarget> = InferMutationVariables<TTarget> | FormData;\n\nexport type FetcherSubmitAsync<TTarget extends AnyMutationTarget> =\n  [] extends Parameters<TTarget>\n    ? (input?: FetcherInput<TTarget>) => Promise<InferMutationData<TTarget>>\n    : (input: FetcherInput<TTarget>) => Promise<InferMutationData<TTarget>>;\n\nexport type FetcherSubmit<TTarget extends AnyMutationTarget> =\n  [] extends Parameters<TTarget>\n    ? (input?: FetcherInput<TTarget>) => void\n    : (input: FetcherInput<TTarget>) => void;\n\nexport type UseFetcherReturn<TTarget extends AnyMutationTarget> = {\n  state: FetcherState;\n  status: MutationStatus;\n  pending: boolean;\n  /** True while a submission is waiting for the browser to come back online. */\n  paused: boolean;\n  data: InferMutationData<TTarget> | null;\n  error: InferMutationError<TTarget> | FetcherInputError | null;\n  variables: InferMutationVariables<TTarget> | undefined;\n  formData: FormData | null;\n  submit: FetcherSubmit<TTarget>;\n  submitAsync: FetcherSubmitAsync<TTarget>;\n  Form: ComponentType<FetcherFormProps>;\n  reset: () => void;\n};\n\nconst formDataContexts = new WeakMap<FormData, FetcherFormDataContext>();\n\n/**\n * Run a typed server function or generated API operation without navigating.\n *\n * `fetcher.Form` progressively keeps a server function as the native form\n * action, while hydration intercepts submissions into this fetcher lifecycle.\n */\nexport function useFetcher<TTarget extends AnyMutationTarget>(\n  target: TTarget,\n  options: UseFetcherOptions<TTarget> = {},\n): UseFetcherReturn<TTarget> {\n  const targetRef = useRef(target);\n  const optionsRef = useRef(options);\n  const submissionIdRef = useRef(0);\n  const [formData, setFormData] = useState<FormData | null>(null);\n  const { mutation, mutatePreparedAsync } = useMutationLifecycle<\n    TTarget,\n    InferMutationError<TTarget> | FetcherInputError\n  >(target, options);\n\n  targetRef.current = target;\n  optionsRef.current = options;\n\n  const submitAsync = useCallback(\n    async (input?: FetcherInput<TTarget>) => {\n      const submissionId = ++submissionIdRef.current;\n      const submittedFormData = isFormData(input) ? input : null;\n      setFormData(submittedFormData);\n\n      try {\n        return await mutatePreparedAsync(() => {\n          try {\n            return (\n              submittedFormData\n                ? mapFetcherFormData(targetRef.current, submittedFormData, optionsRef.current)\n                : input\n            ) as InferMutationVariables<TTarget>;\n          } catch (error) {\n            throw new FetcherInputError(error);\n          }\n        });\n      } finally {\n        if (submissionId === submissionIdRef.current) {\n          setFormData(null);\n        }\n      }\n    },\n    [mutatePreparedAsync],\n  ) as FetcherSubmitAsync<TTarget>;\n\n  const submit = useCallback(\n    (input?: FetcherInput<TTarget>) => {\n      void submitAsync(input as never).catch(() => {});\n    },\n    [submitAsync],\n  ) as FetcherSubmit<TTarget>;\n\n  const Form = useMemo(() => {\n    const FetcherForm = ({ action, method, encType, onSubmit, ...props }: FetcherFormProps) => {\n      const targetValue = targetRef.current;\n      const metadata = getAPIRouteRefMetadata(targetValue);\n      const nativeAction = action ?? resolveFetcherFormAction(targetValue, metadata);\n      const nativeMethod =\n        method ??\n        (metadata && (metadata.method === \"GET\" || metadata.method === \"POST\")\n          ? metadata.method.toLowerCase()\n          : metadata\n            ? \"post\"\n            : undefined);\n      const functionAction = typeof nativeAction === \"function\";\n\n      const handleSubmit = (event: FormEvent<HTMLFormElement>) => {\n        onSubmit?.(event);\n        if (event.defaultPrevented) return;\n\n        event.preventDefault();\n        const submitter = getSubmitter(event);\n        const nextFormData = createSubmitterFormData(event.currentTarget, submitter);\n        formDataContexts.set(nextFormData, {\n          form: event.currentTarget,\n          submitter,\n        });\n        void submitAsync(nextFormData as never).catch(() => {});\n      };\n\n      return createElement(\"form\", {\n        ...props,\n        action: nativeAction as FormHTMLAttributes<HTMLFormElement>[\"action\"],\n        method: functionAction ? undefined : nativeMethod,\n        encType: functionAction ? undefined : encType,\n        onSubmit: handleSubmit,\n      });\n    };\n\n    FetcherForm.displayName = \"FetcherForm\";\n    return FetcherForm;\n  }, [submitAsync]);\n\n  const reset = useCallback(() => {\n    submissionIdRef.current += 1;\n    setFormData(null);\n    mutation.reset();\n  }, [mutation.reset]);\n\n  return useMemo(\n    () => ({\n      state: mutation.pending ? \"submitting\" : \"idle\",\n      status: mutation.status,\n      pending: mutation.pending,\n      paused: mutation.paused,\n      data: mutation.data,\n      error: mutation.error,\n      variables: mutation.variables,\n      formData,\n      submit,\n      submitAsync,\n      Form,\n      reset,\n    }),\n    [\n      Form,\n      formData,\n      mutation.data,\n      mutation.error,\n      mutation.paused,\n      mutation.pending,\n      mutation.status,\n      mutation.variables,\n      reset,\n      submit,\n      submitAsync,\n    ],\n  );\n}\n\nfunction mapFetcherFormData<TTarget extends AnyMutationTarget>(\n  target: TTarget,\n  formData: FormData,\n  options: UseFetcherOptions<TTarget>,\n): InferMutationVariables<TTarget> | FormData {\n  const context = formDataContexts.get(formData) ?? { form: null, submitter: null };\n  if (options.mapFormData) {\n    return options.mapFormData(formData, context);\n  }\n  if (!isAPIRouteRef(target)) {\n    return formData;\n  }\n\n  const method = getAPIRouteRefMetadata(target)?.method;\n  const query = method === \"GET\" || method === \"HEAD\";\n  const encoding = context.submitter?.getAttribute(\"formenctype\") ?? context.form?.enctype;\n  if (\n    !query &&\n    (encoding?.toLowerCase() === \"multipart/form-data\" ||\n      Array.from(formData.values()).some((value) => typeof value !== \"string\"))\n  ) {\n    // Keep files and duplicate fields intact without changing the caller's input\n    // or bypassing the unsafe-key filtering used by the JSON mapping path.\n    const body = new FormData();\n    for (const [key, value] of formData) {\n      if (!isUnsafeFormKey(key)) body.append(key, value);\n    }\n    return { body } as InferMutationVariables<TTarget>;\n  }\n\n  const values = formDataToObject(formData);\n  return (query ? { query: values } : { body: values }) as InferMutationVariables<TTarget>;\n}\n\nfunction resolveFetcherFormAction(\n  target: AnyMutationTarget,\n  metadata: ReturnType<typeof getAPIRouteRefMetadata>,\n): string | AnyMutationTarget | undefined {\n  if (!metadata) return isProgressiveFormAction(target) ? target : undefined;\n  if (metadata.sameOrigin) return metadata.path;\n\n  return new URL(metadata.path, metadata.baseURL).href;\n}\n\nfunction formDataToObject(\n  formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n  const output: Record<string, FormDataEntryValue | FormDataEntryValue[]> = Object.create(null);\n  for (const [key, value] of formData.entries()) {\n    if (isUnsafeFormKey(key)) continue;\n    const current = output[key];\n    if (current === undefined) {\n      output[key] = value;\n    } else if (Array.isArray(current)) {\n      current.push(value);\n    } else {\n      output[key] = [current, value];\n    }\n  }\n  return output;\n}\n\nfunction isUnsafeFormKey(key: string): boolean {\n  return key === \"__proto__\" || key === \"constructor\" || key === \"prototype\";\n}\n\nfunction createSubmitterFormData(form: HTMLFormElement, submitter: HTMLElement | null): FormData {\n  try {\n    return new FormData(form, submitter as HTMLElement | undefined);\n  } catch {\n    const formData = new FormData(form);\n    const candidate = submitter as\n      | (HTMLElement & { disabled?: boolean; name?: string; value?: string })\n      | null;\n    if (candidate && !candidate.disabled && candidate.name) {\n      formData.append(candidate.name, candidate.value ?? \"\");\n    }\n    return formData;\n  }\n}\n\nfunction getSubmitter(event: FormEvent<HTMLFormElement>): HTMLElement | null {\n  const nativeEvent = event.nativeEvent as SubmitEvent;\n  return nativeEvent.submitter instanceof HTMLElement ? nativeEvent.submitter : null;\n}\n\nfunction isProgressiveFormAction(target: AnyMutationTarget): boolean {\n  const candidate = target as AnyMutationTarget & {\n    __farmServerFn?: unknown;\n    $$FORM_ACTION?: unknown;\n    $$typeof?: unknown;\n  };\n  return (\n    candidate.__farmServerFn === true ||\n    typeof candidate.$$FORM_ACTION === \"function\" ||\n    candidate.$$typeof === Symbol.for(\"react.server.reference\")\n  );\n}\n\nfunction isFormData(value: unknown): value is FormData {\n  if (!value || typeof value !== \"object\") return false;\n  return (\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","\"use client\";\n\nimport {\n  createElement,\n  useCallback,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentType,\n  type FormHTMLAttributes,\n} from \"react\";\nimport type { ServerFn } from \"./server-fn\";\nimport type { RetryOptions } from \"./api/client\";\nimport { notifyClientObserver } from \"./client-observers\";\nimport { invokeMutationWithRetry } from \"./mutation-retry\";\n\nexport type ServerFnActionStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport type ServerFnSubmit<TInput, TResult> = [unknown] extends [TInput]\n  ? (input?: TInput | FormData) => Promise<TResult>\n  : (input: TInput | FormData) => Promise<TResult>;\n\nexport type ServerFnOptimisticContext<TInput, TResult> = {\n  input: TInput | FormData | undefined;\n  formData?: FormData;\n  current: TResult | null;\n};\n\nexport type UseServerFnOptions<TResult, TError extends Error = Error, TInput = unknown> = {\n  initialResult?: TResult | null;\n  resetOnSubmit?: boolean;\n  throwOnFormError?: boolean;\n  optimistic?: (context: ServerFnOptimisticContext<TInput, TResult>) => TResult | null | undefined;\n  rollbackOnError?: boolean;\n  /** Retry failed submissions with the API client's retry shape. Defaults to no retries. */\n  retry?: RetryOptions;\n  onSuccess?: (result: TResult) => void;\n  onError?: (error: TError) => void;\n  onSettled?: (result: TResult | null, error: TError | null) => void;\n};\n\nexport type UseServerFnReturn<TInput, TResult, TError extends Error = Error> = {\n  pending: boolean;\n  status: ServerFnActionStatus;\n  result: TResult | null;\n  error: TError | null;\n  submit: ServerFnSubmit<TInput, TResult>;\n  formAction: (formData: FormData) => Promise<void>;\n  reset: () => void;\n};\n\nexport type UseActionFormProps = Omit<FormHTMLAttributes<HTMLFormElement>, \"action\">;\n\nexport type RouteActionTarget<TServerFn extends ServerFn<any, any, any>> = {\n  readonly action: TServerFn;\n};\n\nexport type UseActionReturn<TInput, TResult, TError extends Error = Error> = ServerFnSubmit<\n  TInput,\n  TResult\n> & {\n  pending: boolean;\n  status: ServerFnActionStatus;\n  data: TResult | null;\n  result: TResult | null;\n  error: TError | null;\n  formAction: (formData: FormData) => Promise<void>;\n  Form: ComponentType<UseActionFormProps>;\n  reset: () => void;\n};\n\ntype ServerFnActionState<TResult, TError extends Error> = {\n  pendingCount: number;\n  status: ServerFnActionStatus;\n  result: TResult | null;\n  error: TError | null;\n};\n\ntype ServerFnActionCallbacks<TResult, TError extends Error> = Pick<\n  UseServerFnOptions<TResult, TError, unknown>,\n  \"onError\" | \"onSettled\" | \"onSuccess\" | \"throwOnFormError\"\n>;\n\nexport function useServerFn<TInput, TResult, TError extends Error = Error>(\n  serverFn: ServerFn<TInput, TResult, TError>,\n  options: UseServerFnOptions<TResult, TError, TInput> = {},\n): UseServerFnReturn<TInput, TResult, TError> {\n  const { initialResult = null, resetOnSubmit = true } = options;\n  const callbacksRef = useRef<ServerFnActionCallbacks<TResult, TError>>({});\n  const requestIdRef = useRef(0);\n  const lastResetIdRef = useRef(0);\n  const initialState: ServerFnActionState<TResult, TError> = {\n    pendingCount: 0,\n    status: \"idle\",\n    result: initialResult,\n    error: null,\n  };\n  const stateRef = useRef<ServerFnActionState<TResult, TError>>(initialState);\n  const [state, setState] = useState<ServerFnActionState<TResult, TError>>(initialState);\n  const setActionState = useCallback(\n    (\n      value:\n        | ServerFnActionState<TResult, TError>\n        | ((current: ServerFnActionState<TResult, TError>) => ServerFnActionState<TResult, TError>),\n    ) => {\n      // Later submissions in the same React batch must see this transition.\n      const next = typeof value === \"function\" ? value(stateRef.current) : value;\n      stateRef.current = next;\n      setState(next);\n    },\n    [],\n  );\n\n  callbacksRef.current = {\n    onError: options.onError,\n    onSettled: options.onSettled,\n    onSuccess: options.onSuccess,\n    throwOnFormError: options.throwOnFormError,\n  };\n\n  const submit = useCallback(\n    async (input?: TInput | FormData) => {\n      const requestId = ++requestIdRef.current;\n      const formData = isFormData(input) ? input : undefined;\n      const previousResult = stateRef.current.result;\n      const optimisticResult = options.optimistic?.({\n        input,\n        formData,\n        current: previousResult,\n      });\n      const hasOptimisticResult = optimisticResult !== undefined;\n\n      setActionState((current) => {\n        // Optimistic callbacks are app code and may reset or submit again.\n        if (requestId < lastResetIdRef.current) return current;\n        const pendingCount = current.pendingCount + 1;\n        if (requestId !== requestIdRef.current) return { ...current, pendingCount };\n        return {\n          pendingCount,\n          status: \"pending\",\n          result: hasOptimisticResult ? optimisticResult : resetOnSubmit ? null : current.result,\n          error: null,\n        };\n      });\n\n      try {\n        const result = await invokeMutationWithRetry(\n          () => serverFn(input as TInput | FormData),\n          options.retry,\n          // A reset disowns this submission; stop scheduling retries then.\n          () => requestId >= lastResetIdRef.current,\n        );\n        const isLatestRequest = requestId === requestIdRef.current;\n\n        setActionState((current) => {\n          // Reset starts a new pending-count generation, not just a new result.\n          if (requestId < lastResetIdRef.current) return current;\n          const pendingCount = Math.max(0, current.pendingCount - 1);\n\n          if (!isLatestRequest) {\n            return {\n              ...current,\n              pendingCount,\n            };\n          }\n\n          return {\n            pendingCount,\n            status: \"success\",\n            result,\n            error: null,\n          };\n        });\n\n        if (isLatestRequest) {\n          notifyClientObserver(callbacksRef.current.onSuccess, [result], \"Action onSuccess\");\n          if (requestId === requestIdRef.current) {\n            notifyClientObserver(\n              callbacksRef.current.onSettled,\n              [result, null],\n              \"Action onSettled\",\n            );\n          }\n        }\n\n        return result;\n      } catch (cause) {\n        const error = normalizeServerFnError(cause) as TError;\n        const isLatestRequest = requestId === requestIdRef.current;\n\n        setActionState((current) => {\n          if (requestId < lastResetIdRef.current) return current;\n          const pendingCount = Math.max(0, current.pendingCount - 1);\n\n          if (!isLatestRequest) {\n            return {\n              ...current,\n              pendingCount,\n            };\n          }\n\n          return {\n            pendingCount,\n            status: \"error\",\n            result:\n              hasOptimisticResult && options.rollbackOnError\n                ? previousResult\n                : resetOnSubmit\n                  ? null\n                  : current.result,\n            error,\n          };\n        });\n\n        if (isLatestRequest) {\n          notifyClientObserver(callbacksRef.current.onError, [error], \"Action onError\");\n          if (requestId === requestIdRef.current) {\n            notifyClientObserver(callbacksRef.current.onSettled, [null, error], \"Action onSettled\");\n          }\n        }\n\n        throw error;\n      }\n    },\n    [\n      options.optimistic,\n      options.retry,\n      options.rollbackOnError,\n      resetOnSubmit,\n      serverFn,\n      setActionState,\n    ],\n  ) as ServerFnSubmit<TInput, TResult>;\n\n  const formAction = useCallback(\n    async (formData: FormData) => {\n      try {\n        await submit(formData as TInput | FormData);\n      } catch (error) {\n        if (callbacksRef.current.throwOnFormError) {\n          throw error;\n        }\n      }\n    },\n    [submit],\n  );\n\n  const reset = useCallback(() => {\n    lastResetIdRef.current = ++requestIdRef.current;\n    setActionState({\n      pendingCount: 0,\n      status: \"idle\",\n      result: initialResult,\n      error: null,\n    });\n  }, [initialResult, setActionState]);\n\n  return useMemo(\n    () => ({\n      pending: state.pendingCount > 0,\n      status: state.status,\n      result: state.result,\n      error: state.error,\n      submit,\n      formAction,\n      reset,\n    }),\n    [formAction, reset, state.error, state.pendingCount, state.result, state.status, submit],\n  );\n}\n\n/**\n * Wrap a server function, or a route's default server function, as a callable\n * RPC with React mutation state.\n */\nexport function useAction<TInput, TResult, TError extends Error = Error>(\n  route: RouteActionTarget<ServerFn<TInput, TResult, TError>>,\n  options?: UseServerFnOptions<TResult, TError, TInput>,\n): UseActionReturn<TInput, TResult, TError>;\nexport function useAction<TInput, TResult, TError extends Error = Error>(\n  serverFn: ServerFn<TInput, TResult, TError>,\n  options?: UseServerFnOptions<TResult, TError, TInput>,\n): UseActionReturn<TInput, TResult, TError>;\nexport function useAction<TInput, TResult, TError extends Error = Error>(\n  target: ServerFn<TInput, TResult, TError> | RouteActionTarget<ServerFn<TInput, TResult, TError>>,\n  options: UseServerFnOptions<TResult, TError, TInput> = {},\n): UseActionReturn<TInput, TResult, TError> {\n  const serverFn = resolveServerFnTarget(target);\n  const action = useServerFn(serverFn, options);\n  const formActionRef = useRef(action.formAction);\n  formActionRef.current = action.formAction;\n\n  const Form = useMemo(() => {\n    // Keep both the component and its action stable, even when a parent caches\n    // the form element. Resolve the latest target/options at submission time.\n    const submitForm = (formData: FormData) => formActionRef.current(formData);\n    const ActionForm = (props: UseActionFormProps) =>\n      createElement(\"form\", {\n        ...props,\n        action: submitForm,\n      });\n\n    ActionForm.displayName = \"FarmActionForm\";\n    return ActionForm;\n  }, []);\n\n  return useMemo(() => {\n    const call = ((input?: TInput | FormData) =>\n      action.submit(input as TInput | FormData)) as ServerFnSubmit<TInput, TResult>;\n\n    return Object.assign(call, {\n      pending: action.pending,\n      status: action.status,\n      data: action.result,\n      result: action.result,\n      error: action.error,\n      formAction: action.formAction,\n      Form,\n      reset: action.reset,\n    });\n  }, [\n    Form,\n    action.error,\n    action.formAction,\n    action.pending,\n    action.reset,\n    action.result,\n    action.status,\n    action.submit,\n  ]);\n}\n\nfunction resolveServerFnTarget<TInput, TResult, TError extends Error>(\n  target: ServerFn<TInput, TResult, TError> | RouteActionTarget<ServerFn<TInput, TResult, TError>>,\n): ServerFn<TInput, TResult, TError> {\n  if (typeof target === \"function\") return target;\n  if (target && typeof target.action === \"function\") return target.action;\n\n  throw new TypeError(\n    \"useAction requires a server function or a route with at least one declared action\",\n  );\n}\n\nfunction normalizeServerFnError(error: unknown) {\n  if (error instanceof Error) return error;\n\n  const normalized = new Error(typeof error === \"string\" ? error : \"Server function failed\");\n  (normalized as Error & { cause?: unknown }).cause = error;\n  return normalized;\n}\n\nfunction isFormData(value: unknown): value is FormData {\n  if (!value || typeof value !== \"object\") return false;\n\n  if (typeof FormData !== \"undefined\" && value instanceof FormData) {\n    return true;\n  }\n\n  return (\n    Object.prototype.toString.call(value) === \"[object FormData]\" &&\n    typeof (value as { entries?: unknown }).entries === \"function\"\n  );\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\nimport { getFarmClientDataCache, type FarmClientCacheStatus } from \"./client-cache\";\nimport { attachRevalidationListeners } from \"./client-revalidation\";\nimport type { ServerQuery } from \"./server-query\";\nimport {\n  createServerQueryCallKey,\n  fetchServerQuery,\n  type ServerQueryFetchOptions,\n} from \"./server-query-runtime\";\n\nexport {\n  beginFarmServerQueryAction,\n  completeFarmServerQueryAction,\n  fetchServerQuery,\n  prefetchServerQuery,\n  shouldApplyFarmServerQueryActionResult,\n} from \"./server-query-runtime\";\nexport type {\n  FarmServerQueryActionInvocation,\n  ServerQueryFetchOptions,\n} from \"./server-query-runtime\";\n\nexport type UseServerQueryOptions = ServerQueryFetchOptions & {\n  enabled?: boolean;\n  refetchOnWindowFocus?: boolean;\n  refetchOnReconnect?: boolean;\n};\n\nexport type UseServerQueryResult<TData> = {\n  data: TData | undefined;\n  error: Error | null;\n  status: FarmClientCacheStatus;\n  pending: boolean;\n  fetching: boolean;\n  stale: boolean;\n  refetch: () => Promise<TData>;\n};\n\nexport function useServerQuery<TInput, TData>(\n  query: ServerQuery<TInput, TData>,\n  input: TInput,\n  options: UseServerQueryOptions = {},\n): UseServerQueryResult<TData> {\n  const cache = getFarmClientDataCache();\n  const key = createServerQueryCallKey(query, input);\n  const inputRef = useRef(input);\n  const optionsRef = useRef(options);\n  const mountedKeyRef = useRef<string | undefined>(undefined);\n  const pendingInvalidationRef = useRef(false);\n  inputRef.current = input;\n  optionsRef.current = options;\n\n  const subscribe = useCallback(\n    (listener: () => void) =>\n      cache.subscribe(key, (event) => {\n        if (event === \"invalidate\") pendingInvalidationRef.current = true;\n        else if (cache.get(key)?.fetching) {\n          // A shared read consumes this invalidation for every subscriber, even\n          // when React batches its pending and error snapshots into one render.\n          pendingInvalidationRef.current = false;\n        }\n        listener();\n      }),\n    [cache, key],\n  );\n  const getSnapshot = useCallback(() => cache.get<TData>(key), [cache, key]);\n  const entry = useSyncExternalStore(subscribe, getSnapshot, () => undefined);\n\n  const run = useCallback(\n    (force = false) => {\n      pendingInvalidationRef.current = false;\n      return fetchServerQuery(query, inputRef.current, {\n        ...optionsRef.current,\n        force,\n      });\n    },\n    [query],\n  );\n\n  useEffect(() => {\n    if (options.enabled === false) {\n      // Re-enabling is a new read, even when the query/input key is unchanged.\n      mountedKeyRef.current = undefined;\n      return;\n    }\n\n    const firstReadForKey = mountedKeyRef.current !== key;\n    if (firstReadForKey) mountedKeyRef.current = key;\n    if (\n      (firstReadForKey && (!entry || cache.isStale(key))) ||\n      (pendingInvalidationRef.current && entry?.invalidatedAt !== undefined && !entry.fetching)\n    ) {\n      void run().catch(() => undefined);\n    }\n  }, [cache, entry, key, options.enabled, run]);\n\n  useEffect(() => {\n    if (options.enabled === false) return;\n\n    return attachRevalidationListeners(\n      () => {\n        if (cache.isStale(key)) void run().catch(() => undefined);\n      },\n      {\n        refetchOnWindowFocus: options.refetchOnWindowFocus,\n        refetchOnReconnect: options.refetchOnReconnect,\n      },\n    );\n  }, [cache, key, options.enabled, options.refetchOnReconnect, options.refetchOnWindowFocus, run]);\n\n  const status = entry?.status ?? (entry ? \"success\" : \"idle\");\n  const fetching = entry?.fetching ?? false;\n\n  return {\n    data: entry?.data,\n    error: entry?.error ?? null,\n    status,\n    pending: status === \"pending\" && (entry?.updatedAt ?? 0) === 0,\n    fetching,\n    stale: cache.isStale(key),\n    refetch: () => run(true),\n  };\n}\n","export type FarmRevalidationListenerOptions = {\n  refetchOnWindowFocus?: boolean;\n  refetchOnReconnect?: boolean;\n};\n\n/**\n * Attach the shared window focus/reconnect revalidation listeners used by every\n * query consumer (React `useServerQuery` and the renderer-neutral\n * `createRendererQuery`). Connectivity-driven refresh behavior must live here\n * so all renderers observe the same triggers.\n *\n * Returns a disposer; a no-op outside the browser.\n */\nexport function attachRevalidationListeners(\n  refresh: () => void,\n  options: FarmRevalidationListenerOptions = {},\n): () => void {\n  if (typeof window === \"undefined\") return () => {};\n\n  const onFocus = options.refetchOnWindowFocus === false ? undefined : refresh;\n  const onOnline = options.refetchOnReconnect === false ? undefined : refresh;\n\n  if (onFocus) window.addEventListener(\"focus\", onFocus);\n  if (onOnline) window.addEventListener(\"online\", onOnline);\n  return () => {\n    if (onFocus) window.removeEventListener(\"focus\", onFocus);\n    if (onOnline) window.removeEventListener(\"online\", onOnline);\n  };\n}\n","\"use client\";\n\nimport { createFarmCacheKey } from \"./cache\";\nimport { getFarmClientDataCache, trackFarmClientCacheInvalidations } from \"./client-cache\";\nimport type { ServerQuery } from \"./server-query\";\nimport { isFarmServerQueryResult, type FarmServerQueryResult } from \"./server-query-protocol\";\n\nexport type ServerQueryFetchOptions = {\n  /** Used only when a non-Farm transport returns plain data. Farm transports use the declaration. */\n  staleTime?: number | false;\n  /** Return stale data immediately while refreshing it in the background. Default true. */\n  swr?: boolean;\n  /** Always wait for a new result. */\n  force?: boolean;\n};\n\nexport type FarmServerQueryActionInvocation = {\n  actionId: string;\n  args: readonly unknown[];\n  provisionalKey?: string;\n  owner?: object;\n};\n\ntype ActiveServerQueryInvocation = {\n  provisionalKey: string;\n  owner: object;\n};\n\ntype ServerQueryOwner = {\n  invalidations: ReturnType<typeof trackFarmClientCacheInvalidations>;\n  supersededKeys: Set<string>;\n};\n\ntype ServerQueryClientState = {\n  functionIds: WeakMap<Function, number>;\n  nextFunctionId: number;\n  active: ActiveServerQueryInvocation[];\n  latestOwners: Map<string, object>;\n  owners: Set<ServerQueryOwner>;\n};\n\nconst FARM_SERVER_QUERY_CLIENT_STATE = Symbol.for(\"farm.serverQueryClientState\");\nconst serverQueryClientGlobal = globalThis as typeof globalThis & {\n  [FARM_SERVER_QUERY_CLIENT_STATE]?: ServerQueryClientState;\n};\nconst serverQueryClientState: ServerQueryClientState = (serverQueryClientGlobal[\n  FARM_SERVER_QUERY_CLIENT_STATE\n] ??= {\n  functionIds: new WeakMap(),\n  nextFunctionId: 0,\n  active: [],\n  latestOwners: new Map(),\n  owners: new Set(),\n});\nserverQueryClientState.latestOwners ??= new Map();\nserverQueryClientState.owners ??= new Set();\n\nfunction isServerQueryOwnerSuperseded(owner: ServerQueryOwner, key: string): boolean {\n  const cache = getFarmClientDataCache();\n  const resolved = cache.resolveKey(key);\n  for (const superseded of owner.supersededKeys ?? []) {\n    if (cache.resolveKey(superseded) === resolved) return true;\n  }\n  return false;\n}\n\nfunction claimServerQueryKey(owner: ServerQueryOwner, key: string): boolean {\n  if (isServerQueryOwnerSuperseded(owner, key)) return false;\n  const resolved = getFarmClientDataCache().resolveKey(key);\n  // Set iteration follows request start order, not response timestamps. Record\n  // the claim on older live requests so it survives this owner's completion,\n  // even when an older reference only learns its canonical key afterward.\n  for (const older of serverQueryClientState.owners) {\n    if (older === owner) break;\n    older.supersededKeys.add(resolved);\n  }\n  return true;\n}\n\n// Global symbol registry key set on raw server query implementations by\n// createServerQuery. Referenced via Symbol.for instead of importing\n// server-query.ts, which would pull the server handler pipeline into the\n// client bundle.\nconst RAW_SERVER_QUERY_SYMBOL = Symbol.for(\"farm.server-query\");\n\n/**\n * A query reaching the browser should be a transformed server reference. The\n * raw implementation carries the server query symbol; executing it here would\n * run the server handler in the browser (#408). During SSR the raw\n * implementation is expected and runs directly.\n */\nfunction assertNotRawServerQueryInBrowser(query: unknown): void {\n  if (typeof window === \"undefined\" || typeof document === \"undefined\") return;\n  if (!(query as Record<symbol, unknown> | null)?.[RAW_SERVER_QUERY_SYMBOL]) return;\n  throw new Error(\n    [\n      \"useServerQuery received a raw server query implementation in the browser.\",\n      \"Server query handlers run only on the server. Enable the server-function transform (add @farm.js/plugin/rsc and set experimental.serverActions: true in farm.config.ts) so client imports become server references,\",\n      \"or call the query from server code / an API route (createAPIClient) instead.\",\n    ].join(\"\\n\"),\n  );\n}\n\nexport function beginFarmServerQueryAction(\n  actionId: string,\n  args: readonly unknown[],\n): FarmServerQueryActionInvocation {\n  const active = serverQueryClientState.active.at(-1);\n  return {\n    actionId,\n    args,\n    provisionalKey: active?.provisionalKey,\n    owner: active?.owner,\n  };\n}\n\nexport function completeFarmServerQueryAction<TData>(\n  invocation: FarmServerQueryActionInvocation,\n  value: TData | FarmServerQueryResult<TData>,\n): TData {\n  if (!isFarmServerQueryResult(value)) return value as TData;\n\n  const cache = getFarmClientDataCache();\n  const metadata = value.__farmServerQuery;\n  if (!shouldApplyFarmServerQueryActionResult(invocation)) {\n    return value.data as TData;\n  }\n  if (invocation.provisionalKey) {\n    cache.alias(invocation.provisionalKey, metadata.key);\n  }\n  const owner = invocation.owner as ServerQueryOwner | undefined;\n  if (\n    owner &&\n    serverQueryClientState.owners.has(owner) &&\n    !claimServerQueryKey(owner, metadata.key)\n  ) {\n    return value.data as TData;\n  }\n  const invalidated = (invocation.owner as ServerQueryOwner | undefined)?.invalidations?.has(\n    metadata.key,\n  );\n\n  cache.set(metadata.key, {\n    data: value.data,\n    updatedAt: metadata.updatedAt,\n    staleAt: invalidated\n      ? 0\n      : metadata.staleTime === false\n        ? Number.POSITIVE_INFINITY\n        : metadata.updatedAt + metadata.staleTime,\n    status: \"success\",\n    error: null,\n    fetching: false,\n    persist: metadata.persist === true ? true : undefined,\n  });\n\n  return value.data as TData;\n}\n\nexport function shouldApplyFarmServerQueryActionResult(\n  invocation: FarmServerQueryActionInvocation,\n): boolean {\n  if (!invocation.provisionalKey || !invocation.owner) return true;\n  return isCurrentServerQueryOwner(invocation.provisionalKey, invocation.owner);\n}\n\nfunction isCurrentServerQueryOwner(provisionalKey: string, owner: object): boolean {\n  return (\n    serverQueryClientState.latestOwners.get(provisionalKey) === owner &&\n    !isServerQueryOwnerSuperseded(owner as ServerQueryOwner, provisionalKey)\n  );\n}\n\nexport function createServerQueryCallKey<TInput, TData>(\n  query: ServerQuery<TInput, TData>,\n  input: TInput,\n): string {\n  let id = serverQueryClientState.functionIds.get(query);\n  if (!id) {\n    id = ++serverQueryClientState.nextFunctionId;\n    serverQueryClientState.functionIds.set(query, id);\n  }\n  return createFarmCacheKey([\"server-query-call\", id, input]);\n}\n\nexport async function fetchServerQuery<TInput, TData>(\n  query: ServerQuery<TInput, TData>,\n  input: TInput,\n  options: ServerQueryFetchOptions = {},\n): Promise<TData> {\n  const cache = getFarmClientDataCache();\n  const provisionalKey = createServerQueryCallKey(query, input);\n  const entry = cache.get<TData>(provisionalKey);\n  const stale = cache.isStale(provisionalKey);\n  const inflight = cache.getInflight<TData>(provisionalKey);\n\n  if (\n    !options.force &&\n    entry &&\n    stale &&\n    (entry.status !== \"pending\" || entry.updatedAt !== 0) &&\n    entry.status !== \"error\" &&\n    (options.swr ?? true)\n  ) {\n    // Every SWR reader can use the previous value, including while another\n    // reader owns the refresh. Initial pending reads still wait below.\n    if (!inflight) {\n      void executeServerQuery(query, input, provisionalKey, options).catch(() => undefined);\n    }\n    return entry.data;\n  }\n\n  if (inflight && !options.force) return inflight;\n  if (!options.force && entry && !stale && entry.status !== \"error\") return entry.data;\n\n  return executeServerQuery(query, input, provisionalKey, options);\n}\n\nexport function prefetchServerQuery<TInput, TData>(\n  query: ServerQuery<TInput, TData>,\n  input: TInput,\n  options: Omit<ServerQueryFetchOptions, \"force\"> = {},\n): Promise<TData> {\n  return fetchServerQuery(query, input, options);\n}\n\nasync function executeServerQuery<TInput, TData>(\n  query: ServerQuery<TInput, TData>,\n  input: TInput,\n  provisionalKey: string,\n  options: ServerQueryFetchOptions,\n): Promise<TData> {\n  assertNotRawServerQueryInBrowser(query);\n  const cache = getFarmClientDataCache();\n  const inflight = cache.getInflight<TData>(provisionalKey);\n  if (inflight && !options.force) return inflight;\n\n  const owner: ServerQueryOwner = {\n    invalidations: trackFarmClientCacheInvalidations(cache),\n    supersededKeys: new Set(),\n  };\n  serverQueryClientState.latestOwners.set(provisionalKey, owner);\n  serverQueryClientState.owners.add(owner);\n  claimServerQueryKey(owner, provisionalKey);\n\n  const previous = cache.get<TData>(provisionalKey);\n  cache.set(provisionalKey, {\n    data: previous?.data as TData,\n    updatedAt: previous?.updatedAt ?? 0,\n    staleAt: previous?.staleAt ?? 0,\n    gcAt: previous?.gcAt,\n    invalidatedAt: previous?.invalidatedAt,\n    status: \"pending\",\n    error: null,\n    fetching: true,\n  });\n\n  let promise!: Promise<TData>;\n  promise = (async () => {\n    // Let the promise be assigned and registered before a query implementation\n    // can throw synchronously and enter the cleanup path.\n    await Promise.resolve();\n    try {\n      serverQueryClientState.active.push({ provisionalKey, owner });\n      let pending: Promise<TData>;\n      try {\n        pending = query(input);\n      } finally {\n        serverQueryClientState.active.pop();\n      }\n\n      const data = await pending;\n      const transported = cache.get<TData>(provisionalKey);\n      if (\n        isCurrentServerQueryOwner(provisionalKey, owner) &&\n        (!transported || transported.fetching)\n      ) {\n        const updatedAt = Date.now();\n        cache.set(provisionalKey, {\n          data,\n          updatedAt,\n          staleAt: owner.invalidations.has(provisionalKey)\n            ? 0\n            : options.staleTime === false\n              ? Number.POSITIVE_INFINITY\n              : updatedAt + (options.staleTime ?? 0),\n          status: \"success\",\n          error: null,\n          fetching: false,\n        });\n      }\n      return data;\n    } catch (cause) {\n      const error = normalizeServerQueryError(cause);\n      if (isCurrentServerQueryOwner(provisionalKey, owner)) {\n        const current = cache.get<TData>(provisionalKey);\n        cache.set(provisionalKey, {\n          data: current?.data as TData,\n          updatedAt: current?.updatedAt ?? 0,\n          staleAt: current?.staleAt ?? 0,\n          gcAt: current?.gcAt,\n          invalidatedAt: current?.invalidatedAt,\n          status: \"error\",\n          error,\n          fetching: false,\n        });\n      }\n      throw error;\n    } finally {\n      const invalidated =\n        isCurrentServerQueryOwner(provisionalKey, owner) && owner.invalidations.has(provisionalKey);\n      owner.invalidations.dispose();\n      serverQueryClientState.owners.delete(owner);\n      owner.supersededKeys.clear();\n      if (cache.getInflight(provisionalKey) === promise) {\n        cache.deleteInflight(provisionalKey);\n      }\n      if (serverQueryClientState.latestOwners.get(provisionalKey) === owner) {\n        serverQueryClientState.latestOwners.delete(provisionalKey);\n      }\n      // Notify only after retiring old work: mounted consumers must start a new\n      // read, not rejoin the promise whose result has just been invalidated.\n      if (invalidated) cache.invalidate(provisionalKey);\n    }\n  })();\n\n  cache.setInflight(provisionalKey, promise);\n  return promise;\n}\n\nfunction normalizeServerQueryError(cause: unknown): Error {\n  if (cause instanceof Error) return cause;\n  const error = new Error(typeof cause === \"string\" ? cause : \"Server query failed\");\n  (error as Error & { cause?: unknown }).cause = cause;\n  return error;\n}\n","import {\n  decodeFarmCacheInvalidations,\n  encodeFarmCacheInvalidations,\n  notifyFarmCacheInvalidation,\n  subscribeFarmCacheInvalidation,\n} from \"./cache-invalidation\";\n\nexport const FARM_CACHE_INVALIDATION_CHANNEL = \"farm:cache-invalidation\";\n\nexport type CrossTabCacheInvalidationOptions = {\n  /** Override the BroadcastChannel name, e.g. to isolate multiple apps on one origin. */\n  channelName?: string;\n};\n\ntype ActiveBridge = {\n  channelName: string;\n  refCount: number;\n  teardown: () => void;\n};\n\n// One bridge per tab regardless of how many callers enable it: a second\n// BroadcastChannel in the same tab would receive this tab's own posts and\n// re-apply every local invalidation as if it were remote.\n//\n// The guard lives on globalThis under the same registry the invalidation bus\n// uses, so duplicate copies of this module share it. A module-local guard only\n// protects the copy that declares it, while the bus underneath is global, so a\n// second copy would build its own bridge and the two would echo one local\n// invalidation between them without end (each bridge's applyingRemote flag is\n// private to its own closure and cannot suppress the other's replay).\nconst FARM_CACHE_INVALIDATION_BRIDGE = Symbol.for(\"farm.cacheInvalidationBridge\");\nconst bridgeGlobal = globalThis as typeof globalThis & {\n  [FARM_CACHE_INVALIDATION_BRIDGE]?: ActiveBridge;\n};\n\n/**\n * Bridge the cache invalidation bus across tabs of the same origin.\n *\n * Local invalidations are posted to a BroadcastChannel and applied in every\n * other tab through the normal invalidation path, so mounted stale queries\n * there refetch on their own. Only invalidation keys cross the channel, never\n * cached data, which keeps private and credentialed cache scoping untouched.\n *\n * Opt-in and idempotent. Returns a disposer; a no-op where BroadcastChannel\n * is unavailable (server rendering, older browsers).\n */\nexport function enableCrossTabCacheInvalidation(\n  options: CrossTabCacheInvalidationOptions = {},\n): () => void {\n  if (typeof BroadcastChannel !== \"function\") return () => {};\n\n  const channelName = options.channelName ?? FARM_CACHE_INVALIDATION_CHANNEL;\n  const existing = bridgeGlobal[FARM_CACHE_INVALIDATION_BRIDGE];\n  let bridge: ActiveBridge;\n  if (existing) {\n    if (existing.channelName !== channelName) {\n      throw new Error(\n        `Cross-tab cache invalidation is already enabled on channel \"${existing.channelName}\".`,\n      );\n    }\n    existing.refCount += 1;\n    bridge = existing;\n  } else {\n    bridge = createBridge(channelName);\n    bridgeGlobal[FARM_CACHE_INVALIDATION_BRIDGE] = bridge;\n  }\n\n  let disposed = false;\n  return () => {\n    if (disposed) return;\n    disposed = true;\n    // Release the bridge this caller actually claimed, so a disposer that\n    // outlives a teardown/re-enable cycle cannot decrement a later bridge.\n    bridge.refCount -= 1;\n    if (bridge.refCount === 0) {\n      bridge.teardown();\n      if (bridgeGlobal[FARM_CACHE_INVALIDATION_BRIDGE] === bridge) {\n        bridgeGlobal[FARM_CACHE_INVALIDATION_BRIDGE] = undefined;\n      }\n    }\n  };\n}\n\nfunction createBridge(channelName: string): ActiveBridge {\n  const channel = new BroadcastChannel(channelName);\n  let applyingRemote = false;\n  let pending: string[] = [];\n  let flushScheduled = false;\n  let closed = false;\n\n  const flush = () => {\n    flushScheduled = false;\n    if (closed || pending.length === 0) return;\n    const encoded = encodeFarmCacheInvalidations(pending);\n    pending = [];\n    if (encoded !== null) channel.postMessage(encoded);\n  };\n\n  const unsubscribe = subscribeFarmCacheInvalidation((key) => {\n    if (applyingRemote || closed) return;\n    // A mutation can invalidate several keys back to back; batch them into\n    // one message per microtask instead of one post per key.\n    pending.push(key);\n    if (!flushScheduled) {\n      flushScheduled = true;\n      queueMicrotask(flush);\n    }\n  });\n\n  channel.onmessage = (event: MessageEvent) => {\n    const keys = decodeFarmCacheInvalidations(\n      typeof event.data === \"string\" ? event.data : undefined,\n    );\n    if (keys.length === 0) return;\n    applyingRemote = true;\n    try {\n      for (const key of keys) notifyFarmCacheInvalidation(key);\n    } finally {\n      applyingRemote = false;\n    }\n  };\n\n  return {\n    channelName,\n    refCount: 1,\n    teardown() {\n      closed = true;\n      pending = [];\n      unsubscribe();\n      channel.onmessage = null;\n      channel.close();\n    },\n  };\n}\n","import {\n  getFarmClientDataCache,\n  type FarmClientCacheEntry,\n  type FarmClientCachePersistenceSink,\n  type FarmClientDataCache,\n} from \"./client-cache\";\n\n/**\n * Protocol version stamped into every persisted entry. Bump when the\n * persisted shape changes; mismatched entries are dropped on load.\n */\nexport const FARM_CLIENT_CACHE_PERSIST_VERSION = \"1\";\n\n/** Snapshot of a confirmed cache entry as stored by an adapter. */\nexport type PersistedEntry = {\n  data: unknown;\n  updatedAt: number;\n  staleAt: number;\n  gcAt?: number;\n  version: string;\n};\n\n/**\n * Storage contract for client cache persistence. Implement these callbacks\n * over any storage: IndexedDB, localStorage, OPFS, a native bridge. Farm owns\n * every policy decision (what, when, and whether to persist); the adapter is\n * plain keyed storage. `set` is an upsert.\n */\nexport type FarmClientCacheAdapter = {\n  keys(): Promise<string[]>;\n  get(key: string): Promise<PersistedEntry | null>;\n  set(key: string, entry: PersistedEntry): Promise<void>;\n  delete(key: string): Promise<void>;\n  clear(): Promise<void>;\n  /** Optional batch fast paths; the engine prefers them when present. */\n  getMany?(keys: string[]): Promise<Array<PersistedEntry | null>>;\n  setMany?(entries: Array<[string, PersistedEntry]>): Promise<void>;\n};\n\n/** Key-value client shape accepted by {@link storageClientCacheAdapter}. */\nexport type FarmClientCacheStorage = {\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  getKeys?(base?: string): Promise<string[]>;\n  keys?(base?: string): Promise<string[]>;\n  clear?(base?: string): Promise<unknown>;\n};\n\nexport type ClientCachePersistenceOptions = {\n  /**\n   * Extra version salt, typically an app build or deploy id. Entries written\n   * under a different value are dropped on load.\n   */\n  version?: string;\n  /** Coarse additional filter on top of per-declaration `persist: true`. */\n  persistKey?: (key: string) => boolean;\n  /** Debounce for write-behind flushes. */\n  flushDelayMs?: number;\n};\n\n/**\n * Validate and type an adapter definition. Identity at runtime beyond shape\n * checking, mirroring `defineConfig`-style helpers.\n */\nexport function defineClientCacheAdapter(adapter: FarmClientCacheAdapter): FarmClientCacheAdapter {\n  for (const method of [\"keys\", \"get\", \"set\", \"delete\", \"clear\"] as const) {\n    if (typeof adapter?.[method] !== \"function\") {\n      throw new TypeError(\n        `defineClientCacheAdapter expects a \"${method}\" method. ` +\n          \"Implement keys/get/set/delete/clear over your storage.\",\n      );\n    }\n  }\n  return adapter;\n}\n\n/**\n * Adapt any Farm/unstorage-compatible key-value client to the client cache\n * adapter contract, mirroring the server's `storageCacheAdapter`. Without a\n * key enumeration method the adapter still persists but cannot warm-start.\n */\nexport function storageClientCacheAdapter(\n  storage: FarmClientCacheStorage,\n  options: { base?: string } = {},\n): FarmClientCacheAdapter {\n  if (\n    !storage ||\n    typeof storage.getItem !== \"function\" ||\n    typeof storage.setItem !== \"function\" ||\n    typeof storage.removeItem !== \"function\"\n  ) {\n    throw new TypeError(\"storageClientCacheAdapter expects a compatible key-value client.\");\n  }\n\n  const base = options.base ?? \"farm-client-cache\";\n  const entryKey = (key: string) => `${base}:${key}`;\n  const enumerate = storage.getKeys?.bind(storage) ?? storage.keys?.bind(storage);\n\n  return {\n    async keys() {\n      if (!enumerate) return [];\n      const keys = await enumerate(base);\n      const prefix = `${base}:`;\n      return keys.filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length));\n    },\n    async get(key) {\n      return (await storage.getItem<PersistedEntry>(entryKey(key))) ?? null;\n    },\n    async set(key, entry) {\n      await storage.setItem(entryKey(key), entry);\n    },\n    async delete(key) {\n      await storage.removeItem(entryKey(key));\n    },\n    async clear() {\n      if (storage.clear) {\n        await storage.clear(base);\n        return;\n      }\n      if (!enumerate) return;\n      const prefix = `${base}:`;\n      for (const key of await enumerate(base)) {\n        if (key.startsWith(prefix)) await storage.removeItem(key);\n      }\n    },\n  };\n}\n\ntype PersistenceEngine = {\n  adapter: FarmClientCacheAdapter;\n  cache: FarmClientDataCache;\n  version: string;\n  persistKey?: (key: string) => boolean;\n  flushDelayMs: number;\n  pendingSets: Map<string, PersistedEntry>;\n  pendingDeletes: Set<string>;\n  flushTimer: ReturnType<typeof setTimeout> | undefined;\n  hydrating: boolean;\n  disabled: boolean;\n  clearing: boolean;\n  /** The in-flight flush, so overlapping flushes serialize instead of racing. */\n  flushing: Promise<void> | undefined;\n};\n\nlet activeEngine: PersistenceEngine | undefined;\n\nfunction reportPersistenceFailure(error: unknown): void {\n  const report =\n    typeof reportError === \"function\" ? reportError : (console.error as (value: unknown) => void);\n  if (error instanceof Error) {\n    report(error);\n    return;\n  }\n  const normalized = new Error(\"Client cache persistence failed\");\n  (normalized as Error & { cause?: unknown }).cause = error;\n  report(normalized);\n}\n\nfunction disableEngine(engine: PersistenceEngine, error: unknown): void {\n  if (engine.disabled) return;\n  // The cache is disposable: on any adapter failure fall back to memory-only\n  // for the rest of the session instead of failing reads or writes.\n  engine.disabled = true;\n  engine.pendingSets.clear();\n  engine.pendingDeletes.clear();\n  if (engine.flushTimer !== undefined) {\n    clearTimeout(engine.flushTimer);\n    engine.flushTimer = undefined;\n  }\n  reportPersistenceFailure(error);\n}\n\nfunction scheduleFlush(engine: PersistenceEngine): void {\n  if (engine.disabled || engine.flushTimer !== undefined) return;\n  const timer = setTimeout(() => {\n    engine.flushTimer = undefined;\n    void flushEngine(engine);\n  }, engine.flushDelayMs);\n  (timer as unknown as { unref?: () => void }).unref?.();\n  engine.flushTimer = timer;\n}\n\nasync function flushEngine(engine: PersistenceEngine): Promise<void> {\n  // Serialize: a second flush scheduled while one is mid-await must not run its\n  // own adapter writes in parallel, or the two can resolve out of order and\n  // persist a stale value over a fresher one. Await the in-flight flush instead;\n  // its drain loop picks up whatever this caller queued.\n  if (engine.flushing) return engine.flushing;\n  if (engine.disabled || engine.clearing) return;\n  if (engine.pendingSets.size === 0 && engine.pendingDeletes.size === 0) return;\n\n  const run = (async () => {\n    // Drain until empty so entries queued during an await still flush, without a\n    // second concurrent loop. Re-check disabled/clearing after every await: a\n    // clear() that started mid-flush must stop further writes.\n    while (\n      !engine.disabled &&\n      !engine.clearing &&\n      (engine.pendingSets.size > 0 || engine.pendingDeletes.size > 0)\n    ) {\n      const sets = Array.from(engine.pendingSets.entries());\n      const deletes = Array.from(engine.pendingDeletes);\n      engine.pendingSets.clear();\n      engine.pendingDeletes.clear();\n      try {\n        if (sets.length > 0) {\n          if (engine.adapter.setMany) await engine.adapter.setMany(sets);\n          else for (const [key, entry] of sets) await engine.adapter.set(key, entry);\n        }\n        for (const key of deletes) await engine.adapter.delete(key);\n      } catch (error) {\n        disableEngine(engine, error);\n        return;\n      }\n    }\n  })();\n  engine.flushing = run;\n  try {\n    await run;\n  } finally {\n    engine.flushing = undefined;\n  }\n}\n\nasync function hydrateEngine(engine: PersistenceEngine): Promise<void> {\n  const now = Date.now();\n  const keys = await engine.adapter.keys();\n  if (keys.length === 0) return;\n\n  const persisted = engine.adapter.getMany\n    ? await engine.adapter.getMany(keys)\n    : await Promise.all(keys.map((key) => engine.adapter.get(key)));\n\n  engine.hydrating = true;\n  try {\n    for (let index = 0; index < keys.length; index += 1) {\n      const key = keys[index]!;\n      const entry = persisted[index];\n      if (engine.disabled) return;\n\n      if (\n        !entry ||\n        entry.version !== engine.version ||\n        (entry.gcAt !== undefined && now >= entry.gcAt)\n      ) {\n        engine.pendingDeletes.add(key);\n        continue;\n      }\n\n      // A live entry came from this session's server work and always wins.\n      if (engine.cache.get(key, now)) continue;\n\n      // Stale-but-visible: render the persisted data immediately and let the\n      // normal SWR path revalidate it on first read.\n      engine.cache.set(key, {\n        data: entry.data,\n        updatedAt: entry.updatedAt,\n        staleAt: 0,\n        gcAt: entry.gcAt,\n        status: \"success\",\n        error: null,\n        persist: true,\n      });\n    }\n  } finally {\n    engine.hydrating = false;\n  }\n  if (engine.pendingDeletes.size > 0) scheduleFlush(engine);\n}\n\nfunction createSink(engine: PersistenceEngine): FarmClientCachePersistenceSink {\n  return {\n    onSet(key, entry: FarmClientCacheEntry) {\n      if (engine.disabled || engine.hydrating) return;\n      if (!entry.persist || entry.fetching || entry.error || entry.status === \"pending\") return;\n      if (engine.persistKey && !engine.persistKey(key)) return;\n      engine.pendingDeletes.delete(key);\n      engine.pendingSets.set(key, {\n        data: entry.data,\n        updatedAt: entry.updatedAt,\n        staleAt: entry.staleAt,\n        gcAt: entry.gcAt,\n        version: engine.version,\n      });\n      scheduleFlush(engine);\n    },\n    onDelete(key) {\n      if (engine.disabled) return;\n      engine.pendingSets.delete(key);\n      engine.pendingDeletes.add(key);\n      scheduleFlush(engine);\n    },\n    onClear() {\n      // clearPersistedCache awaits the adapter itself; skip the fire-and-forget\n      // clear so one logout does not race two clears (and two error reports).\n      if (engine.disabled || engine.clearing) return;\n      engine.pendingSets.clear();\n      engine.pendingDeletes.clear();\n      void engine.adapter.clear().catch((error) => disableEngine(engine, error));\n    },\n  };\n}\n\n/**\n * @internal Wire an adapter to the shared client cache. Called by the\n * generated client entry from the `cache.client.adapter` configuration; not\n * part of the public API. Returns a disposer.\n */\nexport function initPersistedClientCache(\n  adapter: FarmClientCacheAdapter,\n  options: ClientCachePersistenceOptions = {},\n): () => void {\n  defineClientCacheAdapter(adapter);\n  disposePersistedClientCache();\n\n  const engine: PersistenceEngine = {\n    adapter,\n    cache: getFarmClientDataCache(),\n    version: options.version\n      ? `${FARM_CLIENT_CACHE_PERSIST_VERSION}:${options.version}`\n      : FARM_CLIENT_CACHE_PERSIST_VERSION,\n    persistKey: options.persistKey,\n    flushDelayMs: options.flushDelayMs ?? 300,\n    pendingSets: new Map(),\n    pendingDeletes: new Set(),\n    flushTimer: undefined,\n    hydrating: false,\n    disabled: false,\n    clearing: false,\n    flushing: undefined,\n  };\n\n  activeEngine = engine;\n  engine.cache.attachPersistence(createSink(engine));\n  void hydrateEngine(engine).catch((error) => disableEngine(engine, error));\n\n  return () => {\n    if (activeEngine !== engine) return;\n    disposePersistedClientCache();\n  };\n}\n\n/**\n * @internal Entry point used by the generated client entries for the\n * `cache.client.adapter` configuration. Accepts the imported module namespace\n * and reports a misconfigured adapter without breaking application startup:\n * persistence is optional capability and must never block hydration.\n */\nexport function initConfiguredClientCachePersistence(\n  adapterModule: unknown,\n  options: ClientCachePersistenceOptions = {},\n): void {\n  try {\n    const adapter = (adapterModule as { default?: unknown } | null | undefined)?.default;\n    if (!adapter) {\n      throw new Error(\n        \"cache.client.adapter must default-export an adapter. \" +\n          \"Export defineClientCacheAdapter({ keys, get, set, delete, clear }) as the module default.\",\n      );\n    }\n    initPersistedClientCache(adapter as FarmClientCacheAdapter, options);\n  } catch (error) {\n    reportPersistenceFailure(error);\n  }\n}\n\n/** @internal Detach the active engine, flushing nothing further. */\nexport function disposePersistedClientCache(): void {\n  const engine = activeEngine;\n  if (!engine) return;\n  activeEngine = undefined;\n  // Hydration is asynchronous and may already be parked on an adapter read.\n  // Marking the engine disabled makes that in-flight pass stop before it writes,\n  // so a disposed engine cannot repopulate the shared cache after logout — or\n  // push the previous user's entries into whichever adapter is attached next.\n  engine.disabled = true;\n  engine.cache.attachPersistence(undefined);\n  if (engine.flushTimer !== undefined) {\n    clearTimeout(engine.flushTimer);\n    engine.flushTimer = undefined;\n  }\n  engine.pendingSets.clear();\n  engine.pendingDeletes.clear();\n}\n\n/**\n * Remove every persisted cache entry. Call on logout or any session change so\n * the next visitor on this device cannot warm-start into another user's data.\n * Safe to call when persistence is not configured.\n */\nexport async function clearPersistedCache(): Promise<void> {\n  const engine = activeEngine;\n  if (!engine) {\n    // Persistence is optional, but logout must mean the same thing with or\n    // without an adapter: the previous session's data stops being readable.\n    getFarmClientDataCache().clear();\n    return;\n  }\n  // Hold `clearing` for the whole operation. It both suppresses re-persist from\n  // the in-memory cache.clear() below and makes flushEngine bail, so no flush\n  // scheduled during the clear can write the signed-out user's data back.\n  engine.clearing = true;\n  try {\n    engine.pendingSets.clear();\n    engine.pendingDeletes.clear();\n    // Clearing the persisted copy alone leaves the in-memory cache holding the\n    // signed-out user's data, which a single-page app keeps serving to whoever\n    // uses the tab next. Drop both.\n    engine.cache.clear();\n    engine.pendingSets.clear();\n    engine.pendingDeletes.clear();\n    // Let an in-flight flush finish its current adapter write before wiping.\n    // Otherwise a write parked in `await adapter.set(...)` resolves after\n    // adapter.clear() and resurrects the data for the next visitor.\n    await engine.flushing;\n    engine.pendingSets.clear();\n    engine.pendingDeletes.clear();\n    await engine.adapter.clear();\n  } catch (error) {\n    disableEngine(engine, error);\n  } finally {\n    engine.clearing = false;\n  }\n}\n\n/** @internal Test hook: flush pending writes immediately. */\nexport async function flushPersistedClientCache(): Promise<void> {\n  const engine = activeEngine;\n  if (!engine) return;\n  if (engine.flushTimer !== undefined) {\n    clearTimeout(engine.flushTimer);\n    engine.flushTimer = undefined;\n  }\n  await flushEngine(engine);\n}\n","export type FarmIntegrationAPIMethod =\n  | \"GET\"\n  | \"QUERY\"\n  | \"POST\"\n  | \"PUT\"\n  | \"PATCH\"\n  | \"DELETE\"\n  | \"OPTIONS\"\n  | \"HEAD\";\n\nexport type FarmIntegrationAPIBodyFormat = \"json\" | \"form\" | \"none\";\nexport type FarmIntegrationAPIResponseFormat = \"json\" | \"text\" | \"response\";\n\nexport interface FarmIntegrationAPIOperation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n> {\n  readonly kind: \"farm-integration-api-operation\";\n  path: string;\n  method: TMethod;\n  bodyFormat?: FarmIntegrationAPIBodyFormat;\n  responseFormat?: FarmIntegrationAPIResponseFormat;\n  headers?: Record<string, string>;\n  credentials?: RequestCredentials;\n  isServer?: TServer;\n  __pathless?: boolean;\n  __types?: {\n    body: TBody;\n    query: TQuery;\n    response: TResponse;\n  };\n}\n\nexport type FarmIntegrationAPI = {\n  [key: string]: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nexport type FarmIntegrationRouteOperationCarrier<\n  TPath extends string = string,\n  TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any> =\n    FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = {\n  path: TPath;\n  __operation: TOperation;\n};\n\ntype IntegrationAPIBuilderOptions<TServer extends boolean = false> = Omit<\n  FarmIntegrationAPIOperation<any, any, any, TServer>,\n  \"kind\" | \"method\" | \"path\" | \"__pathless\" | \"__types\"\n>;\n\nexport function defineIntegrationAPIOperation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n  operation: Omit<\n    FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>,\n    \"kind\" | \"__types\"\n  >,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n  return {\n    kind: \"farm-integration-api-operation\",\n    ...operation,\n  };\n}\n\nexport function defineIntegrationAPI<TAPI extends FarmIntegrationAPI>(api: TAPI): TAPI {\n  return api;\n}\n\nfunction operation<\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n  method: TMethod,\n  pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n  maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n  const hasExplicitPath = typeof pathOrOptions === \"string\";\n  const path = hasExplicitPath ? pathOrOptions : \"\";\n  const options = (\n    hasExplicitPath\n      ? maybeOptions\n      : {\n          ...maybeOptions,\n          ...pathOrOptions,\n        }\n  ) as IntegrationAPIBuilderOptions<TServer>;\n\n  return defineIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>({\n    path,\n    method,\n    __pathless: !hasExplicitPath,\n    ...options,\n  });\n}\n\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n  path: string,\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n  path: string,\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n  options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get(\n  pathOrOptions?: string | IntegrationAPIBuilderOptions<boolean>,\n  maybeOptions: IntegrationAPIBuilderOptions<boolean> = {} as IntegrationAPIBuilderOptions<boolean>,\n) {\n  return operation<never, any, any, boolean>(\"GET\", pathOrOptions, maybeOptions);\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 bindRoutePath<TAPI extends FarmIntegrationAPI>(path: string, api: TAPI): TAPI {\n  const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n    if (isOperation(value)) {\n      return [\n        key,\n        {\n          ...value,\n          path,\n          __pathless: false,\n        },\n      ];\n    }\n\n    if (value && typeof value === \"object\") {\n      return [key, bindRoutePath(path, value as FarmIntegrationAPI)];\n    }\n\n    return [key, value];\n  });\n\n  return Object.fromEntries(entries) as TAPI;\n}\n\ntype RouteOperationsToAPI<\n  TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[],\n> = {\n  [TMethod in Lowercase<TOperations[number][\"method\"] & string>]: Extract<\n    TOperations[number],\n    { method: Uppercase<TMethod> }\n  >;\n};\n\ntype StripRouteClientPrefix<TPath extends string> = TPath extends `/api/${string}/${infer TRest}`\n  ? TRest\n  : TPath extends `/${string}/${infer TRest}`\n    ? TRest\n    : TPath extends `/${infer TRest}`\n      ? TRest\n      : TPath;\n\ntype NormalizeRouteSegment<TSegment extends string> = TSegment extends `[...${infer TName}]`\n  ? TName\n  : TSegment extends `[${infer TName}]`\n    ? TName\n    : TSegment extends `${infer TName}(${string}`\n      ? TName\n      : CamelCaseRouteSegment<TSegment>;\n\ntype CamelCaseRouteSegment<TSegment extends string> =\n  TSegment extends `${infer THead}-${infer TTail}`\n    ? `${THead}${Capitalize<CamelCaseRouteSegment<TTail>>}`\n    : TSegment;\n\ntype RouteNamespaceFromPath<\n  TPath extends string,\n  TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = TPath extends `${infer THead}/${infer TTail}`\n  ? {\n      [TKey in NormalizeRouteSegment<THead>]: RouteNamespaceFromPath<TTail, TOperation>;\n    }\n  : {\n      [TKey in NormalizeRouteSegment<TPath>]: {\n        [TMethod in Lowercase<TOperation[\"method\"] & string>]: TOperation;\n      };\n    };\n\ntype UnionToIntersection<TUnion> = (\n  TUnion extends unknown ? (value: TUnion) => void : never\n) extends (value: infer TIntersection) => void\n  ? TIntersection\n  : never;\n\ntype ExpandRecursively<TValue> = TValue extends (...args: any[]) => any\n  ? TValue\n  : TValue extends object\n    ? { [TKey in keyof TValue]: ExpandRecursively<TValue[TKey]> }\n    : TValue;\n\ntype RoutesToAPI<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]> =\n  ExpandRecursively<\n    UnionToIntersection<\n      TRoutes[number] extends FarmIntegrationRouteOperationCarrier<infer TPath, infer TOperation>\n        ? RouteNamespaceFromPath<StripRouteClientPrefix<TPath>, TOperation>\n        : never\n    >\n  >;\n\nexport type InferIntegrationAPIFromRoutes<\n  TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[],\n> = RoutesToAPI<TRoutes>;\n\nfunction route<TAPI extends FarmIntegrationAPI>(path: string, definition: TAPI): TAPI;\nfunction route<TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]>(\n  path: string,\n  ...operations: TOperations\n): RouteOperationsToAPI<TOperations>;\nfunction route(\n  path: string,\n  definitionOrOperation: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>,\n  ...operations: readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]\n) {\n  if (isOperation(definitionOrOperation)) {\n    const allOperations = [definitionOrOperation, ...operations];\n    return Object.fromEntries(\n      allOperations.map((operation) => [\n        operation.method.toLowerCase(),\n        {\n          ...operation,\n          path,\n          __pathless: false,\n        },\n      ]),\n    );\n  }\n\n  return bindRoutePath(path, definitionOrOperation as FarmIntegrationAPI);\n}\n\nfunction normalizeRouteSegment(segment: string): string {\n  if (!segment) {\n    return \"index\";\n  }\n\n  if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n    return segment.slice(4, -1) || \"index\";\n  }\n\n  if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n    return segment.slice(1, -1) || \"index\";\n  }\n\n  const matcherIndex = segment.indexOf(\"(\");\n  if (matcherIndex > 0) {\n    return segment.slice(0, matcherIndex);\n  }\n\n  return camelCaseRouteSegment(segment);\n}\n\nfunction camelCaseRouteSegment(segment: string): string {\n  return segment.replace(/-([a-zA-Z0-9])/g, (_match, value: string) => value.toUpperCase());\n}\n\nfunction getRouteClientSegments(path: string): string[] {\n  const segments = path.split(\"/\").filter(Boolean);\n  if (segments.length === 0) {\n    return [\"index\"];\n  }\n\n  const stripped =\n    segments[0] === \"api\" && segments.length > 2\n      ? segments.slice(2)\n      : segments.length > 1\n        ? segments.slice(1)\n        : [segments[segments.length - 1]];\n\n  return stripped.map(normalizeRouteSegment).filter(Boolean);\n}\n\nfunction setRouteOperation(\n  target: Record<string, unknown>,\n  pathSegments: string[],\n  operation: FarmIntegrationAPIOperation<any, any, any, any, any>,\n) {\n  const [head, ...tail] = pathSegments;\n  if (!head) {\n    return;\n  }\n\n  if (tail.length === 0) {\n    const leaf = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n      string,\n      unknown\n    >;\n    leaf[operation.method.toLowerCase()] = {\n      ...operation,\n      path: operation.path,\n      __pathless: false,\n    };\n    target[head] = leaf;\n    return;\n  }\n\n  const branch = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n    string,\n    unknown\n  >;\n  target[head] = branch;\n  setRouteOperation(branch, tail, operation);\n}\n\nfunction fromRoutes<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]>(\n  routes: TRoutes,\n): RoutesToAPI<TRoutes> {\n  const definition: Record<string, unknown> = {};\n\n  for (const route of routes) {\n    if (!isOperation(route.__operation)) {\n      continue;\n    }\n\n    setRouteOperation(definition, getRouteClientSegments(route.path), {\n      ...route.__operation,\n      path: route.path,\n      __pathless: false,\n    });\n  }\n\n  return definition as RoutesToAPI<TRoutes>;\n}\n\nexport const api = {\n  get,\n  route,\n  fromRoutes,\n  query<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"QUERY\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"QUERY\">(\"QUERY\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n    return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n      bodyFormat: \"json\",\n      ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n    });\n  },\n  options<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"OPTIONS\"> {\n    return operation<never, TQuery, TResponse, TServer, \"OPTIONS\">(\n      \"OPTIONS\",\n      pathOrOptions,\n      maybeOptions,\n    );\n  },\n  head<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n    maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n  ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"HEAD\"> {\n    return operation<never, TQuery, TResponse, TServer, \"HEAD\">(\n      \"HEAD\",\n      pathOrOptions,\n      maybeOptions,\n    );\n  },\n  form: {\n    query<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"QUERY\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"QUERY\">(\"QUERY\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n    delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n      maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n    ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n      return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n        bodyFormat: \"form\",\n        ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n      });\n    },\n  },\n};\n\nexport const endpoint = api;\n","import { useSyncExternalStore } from \"react\";\n\nexport type StoreState = Record<string, any>;\nexport type StoreValueUpdater<T> = T | ((previous: T) => T);\nexport type StorePatch<T extends StoreState> = Partial<T> | ((state: T) => Partial<T>);\nexport type StoreListener<T extends StoreState> = (state: T, previousState: T) => void;\nexport type StoreKeyListener<T extends StoreState, K extends keyof T> = (\n  value: T[K],\n  previousValue: T[K],\n) => void;\nexport type StoreKeysListener<T extends StoreState, K extends keyof T> = (\n  value: Pick<T, K>,\n  previousValue: Pick<T, K>,\n) => void;\n\ntype StoreSubscription<T extends StoreState> = {\n  keys: readonly PropertyKey[] | null;\n  notify: (state: T, previousState: T) => void;\n};\n\ntype ReservedStoreKey = \"use\" | \"get\" | \"set\" | \"replace\" | \"reset\" | \"subscribe\";\n\ntype FieldAccessor<T extends StoreState, K extends keyof T> = {\n  (): T[K];\n  get(): T[K];\n  set(value: StoreValueUpdater<T[K]>): T[K];\n  subscribe(listener: StoreKeyListener<T, K>): () => void;\n};\n\nexport type StoreFields<T extends StoreState> = {\n  [K in keyof T]: FieldAccessor<T, K>;\n};\n\nexport interface StoreApi<T extends StoreState> {\n  use(): T;\n  use<K extends keyof T>(key: K): T[K];\n  use<K extends keyof T>(keys: readonly K[]): Pick<T, K>;\n  get(): T;\n  get<K extends keyof T>(key: K): T[K];\n  set<K extends keyof T>(key: K, value: StoreValueUpdater<T[K]>): T[K];\n  set(patch: StorePatch<T>): T;\n  replace(nextState: T | ((state: T) => T)): T;\n  reset(): T;\n  subscribe(listener: StoreListener<T>): () => void;\n  subscribe<K extends keyof T>(key: K, listener: StoreKeyListener<T, K>): () => void;\n  subscribe<K extends keyof T>(keys: readonly K[], listener: StoreKeysListener<T, K>): () => void;\n}\n\nexport type Store<T extends StoreState, TMethods extends Record<string, any> = {}> = StoreApi<T> &\n  StoreFields<T> &\n  TMethods;\n\nconst RESERVED_STORE_KEYS = new Set<ReservedStoreKey>([\n  \"use\",\n  \"get\",\n  \"set\",\n  \"replace\",\n  \"reset\",\n  \"subscribe\",\n]);\n\nfunction cloneState<T extends StoreState>(state: T): T {\n  return { ...state };\n}\n\nfunction pickState<T extends StoreState, K extends keyof T>(\n  state: T,\n  keys: readonly K[],\n): Pick<T, K> {\n  const slice = {} as Pick<T, K>;\n\n  for (const key of keys) {\n    slice[key] = state[key];\n  }\n\n  return slice;\n}\n\nfunction getEnumerableKeys<T extends StoreState>(state: T): (keyof T)[] {\n  return Reflect.ownKeys(state).filter((key) =>\n    Object.prototype.propertyIsEnumerable.call(state, key),\n  ) as (keyof T)[];\n}\n\nfunction getChangedKeys<T extends StoreState>(state: T, previousState: T): (keyof T)[] {\n  const keys = new Set<keyof T>([...getEnumerableKeys(state), ...getEnumerableKeys(previousState)]);\n\n  return [...keys].filter((key) => !Object.is(state[key], previousState[key]));\n}\n\nfunction normalizeKeys<T extends StoreState, K extends keyof T>(keys: readonly K[]): readonly K[] {\n  return Array.from(new Set(keys));\n}\n\nfunction resolveValue<T>(value: StoreValueUpdater<T>, previousValue: T): T {\n  return typeof value === \"function\" ? (value as (previousValue: T) => T)(previousValue) : value;\n}\n\nfunction isStoreKey(value: unknown): value is string | number | symbol {\n  return typeof value === \"string\" || typeof value === \"number\" || typeof value === \"symbol\";\n}\n\nexport function createStore<T extends StoreState, TMethods extends Record<string, any> = {}>(\n  initialState: T,\n  extend?: (store: Store<T>) => TMethods,\n): Store<T, TMethods> {\n  const initialSnapshot = cloneState(initialState);\n  let state = cloneState(initialState);\n  const subscriptions = new Set<StoreSubscription<T>>();\n\n  const addSubscription = (\n    keys: readonly (keyof T)[] | null,\n    notify: (state: T, previousState: T) => void,\n  ) => {\n    const subscription: StoreSubscription<T> = {\n      // Object property enumeration returns numeric keys as strings.\n      keys: keys?.map((key) => (typeof key === \"number\" ? String(key) : key)) ?? null,\n      notify,\n    };\n    subscriptions.add(subscription);\n    return () => {\n      subscriptions.delete(subscription);\n    };\n  };\n\n  const emit = (nextState: T, previousState: T) => {\n    const changedKeys = getChangedKeys(nextState, previousState);\n\n    if (changedKeys.length === 0) {\n      return;\n    }\n\n    const changedKeySet = new Set<PropertyKey>(changedKeys);\n\n    for (const subscription of subscriptions) {\n      if (subscription.keys === null || subscription.keys.some((key) => changedKeySet.has(key))) {\n        subscription.notify(nextState, previousState);\n      }\n    }\n  };\n\n  const getState = (key?: keyof T) => {\n    return key === undefined ? state : state[key];\n  };\n\n  const replaceState = (nextState: T | ((state: T) => T)) => {\n    const previousState = state;\n    const resolvedState =\n      typeof nextState === \"function\" ? (nextState as (state: T) => T)(previousState) : nextState;\n    state = resolvedState;\n    emit(state, previousState);\n    return state;\n  };\n\n  const setState = (keyOrPatch: keyof T | StorePatch<T>, value?: StoreValueUpdater<T[keyof T]>) => {\n    const previousState = state;\n    let nextState: T;\n\n    if (isStoreKey(keyOrPatch)) {\n      const key = keyOrPatch as keyof T;\n      const nextValue = resolveValue(value as StoreValueUpdater<T[keyof T]>, previousState[key]);\n\n      if (Object.is(previousState[key], nextValue)) {\n        return nextValue;\n      }\n\n      nextState = {\n        ...previousState,\n        [key]: nextValue,\n      };\n      state = nextState;\n      emit(nextState, previousState);\n      return nextValue;\n    }\n\n    const patch: Partial<T> =\n      typeof keyOrPatch === \"function\"\n        ? (keyOrPatch as (state: T) => Partial<T>)(previousState)\n        : (keyOrPatch as Partial<T>);\n\n    nextState = {\n      ...previousState,\n      ...patch,\n    };\n    state = nextState;\n    emit(nextState, previousState);\n    return nextState;\n  };\n\n  const subscribeState = (\n    keyOrListener: keyof T | readonly (keyof T)[] | StoreListener<T>,\n    listener?: StoreKeyListener<T, keyof T> | StoreKeysListener<T, keyof T>,\n  ) => {\n    if (typeof keyOrListener === \"function\") {\n      return addSubscription(null, (nextState, previousState) => {\n        (keyOrListener as StoreListener<T>)(nextState, previousState);\n      });\n    }\n\n    if (Array.isArray(keyOrListener)) {\n      const keys = normalizeKeys(keyOrListener);\n      return addSubscription(keys, (nextState, previousState) => {\n        (listener as StoreKeysListener<T, keyof T>)(\n          pickState(nextState, keys),\n          pickState(previousState, keys),\n        );\n      });\n    }\n\n    const key = keyOrListener as keyof T;\n    return addSubscription([key], (nextState, previousState) => {\n      (listener as StoreKeyListener<T, keyof T>)(nextState[key], previousState[key]);\n    });\n  };\n\n  const useStateValue = <K extends keyof T>(keyOrKeys?: K | readonly K[]) => {\n    if (Array.isArray(keyOrKeys)) {\n      const keys = normalizeKeys(keyOrKeys);\n      let lastState = state;\n      let lastSlice = pickState(state, keys);\n      const getSnapshot = () => {\n        if (lastState !== state) {\n          lastState = state;\n          lastSlice = pickState(state, keys);\n        }\n\n        return lastSlice;\n      };\n\n      return useSyncExternalStore(\n        (notify) => addSubscription(keys, () => notify()),\n        getSnapshot,\n        getSnapshot,\n      );\n    }\n\n    if (isStoreKey(keyOrKeys)) {\n      return useSyncExternalStore(\n        (notify) => addSubscription([keyOrKeys], () => notify()),\n        () => state[keyOrKeys],\n        () => state[keyOrKeys],\n      );\n    }\n\n    return useSyncExternalStore(\n      (notify) => addSubscription(null, () => notify()),\n      () => state,\n      () => state,\n    );\n  };\n\n  const store = {\n    use: useStateValue,\n    get: getState,\n    set: setState,\n    replace: replaceState,\n    reset: () => replaceState(cloneState(initialSnapshot)),\n    subscribe: subscribeState,\n  } as Store<T>;\n\n  for (const key of getEnumerableKeys(initialSnapshot)) {\n    if (RESERVED_STORE_KEYS.has(key as ReservedStoreKey)) {\n      throw new Error(\n        `createStore does not allow the reserved key \"${String(key)}\" in the initial state.`,\n      );\n    }\n\n    const field = (() => useStateValue(key)) as FieldAccessor<T, typeof key>;\n    field.get = () => state[key];\n    field.set = (value) => setState(key, value) as T[typeof key];\n    field.subscribe = (listener) => subscribeState(key, listener as StoreKeyListener<T, keyof T>);\n\n    Object.defineProperty(store, key, {\n      configurable: false,\n      enumerable: true,\n      value: field,\n      writable: false,\n    });\n  }\n\n  if (extend) {\n    const methods = extend(store);\n\n    for (const [name, method] of Object.entries(methods)) {\n      if (name in store) {\n        throw new Error(\n          `createStore cannot attach the method \"${name}\" because it already exists.`,\n        );\n      }\n\n      Object.defineProperty(store, name, {\n        configurable: false,\n        enumerable: true,\n        value: method,\n        writable: false,\n      });\n    }\n  }\n\n  return store as Store<T, TMethods>;\n}\n","\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\nimport { getFarmThemeServerSnapshot } from \"./bridge\";\nimport { getTheme, setTheme, subscribeTheme, toggleTheme } from \"./runtime\";\nimport type { FarmThemePreference, FarmThemeSnapshot, FarmResolvedTheme } from \"./types\";\n\nexport { getTheme, setTheme, toggleTheme } from \"./runtime\";\n\nfunction getHydrationSnapshot(): FarmThemeSnapshot {\n  if (typeof window !== \"undefined\" && window.__FARM_THEME__?.serverSnapshot) {\n    return window.__FARM_THEME__.serverSnapshot;\n  }\n  return getFarmThemeServerSnapshot();\n}\n\nexport interface UseThemeResult extends FarmThemeSnapshot {\n  setTheme(theme: FarmThemePreference): void;\n  toggleTheme(): FarmResolvedTheme;\n}\n\nexport function useTheme(): UseThemeResult {\n  const snapshot = useSyncExternalStore(subscribeTheme, getTheme, getHydrationSnapshot);\n  return {\n    ...snapshot,\n    setTheme,\n    toggleTheme,\n  };\n}\n","import type { FarmThemeSnapshot } from \"./types\";\n\nconst FALLBACK_SERVER_SNAPSHOT: FarmThemeSnapshot = Object.freeze({\n  theme: \"system\",\n  resolvedTheme: undefined,\n  mounted: false,\n});\n\nconst FARM_THEME_SERVER_SNAPSHOT_RESOLVER = Symbol.for(\"farm.js.theme.server-snapshot-resolver\");\n\ntype FarmThemeBridgeGlobal = typeof globalThis & {\n  [FARM_THEME_SERVER_SNAPSHOT_RESOLVER]?: () => FarmThemeSnapshot;\n};\n\nexport function _setFarmThemeServerSnapshotResolver(resolver: () => FarmThemeSnapshot): void {\n  (globalThis as FarmThemeBridgeGlobal)[FARM_THEME_SERVER_SNAPSHOT_RESOLVER] = resolver;\n}\n\nexport function getFarmThemeServerSnapshot(): FarmThemeSnapshot {\n  return (\n    (globalThis as FarmThemeBridgeGlobal)[FARM_THEME_SERVER_SNAPSHOT_RESOLVER]?.() ??\n    FALLBACK_SERVER_SNAPSHOT\n  );\n}\n","\"use client\";\n\nimport type {\n  FarmResolvedTheme,\n  FarmThemePreference,\n  FarmThemeRuntime,\n  FarmThemeSnapshot,\n} from \"./types\";\n\ndeclare global {\n  interface Window {\n    __FARM_THEME__?: FarmThemeRuntime;\n  }\n}\n\nconst FALLBACK_CLIENT_SNAPSHOT: FarmThemeSnapshot = Object.freeze({\n  theme: \"system\",\n  resolvedTheme: \"light\",\n  mounted: true,\n});\n\nlet cachedClientSnapshot = FALLBACK_CLIENT_SNAPSHOT;\n\nfunction snapshotsMatch(left: FarmThemeSnapshot, right: FarmThemeSnapshot): boolean {\n  return (\n    left.theme === right.theme &&\n    left.resolvedTheme === right.resolvedTheme &&\n    left.mounted === right.mounted\n  );\n}\n\nexport function getTheme(): FarmThemeSnapshot {\n  const next =\n    typeof window === \"undefined\" ? FALLBACK_CLIENT_SNAPSHOT : window.__FARM_THEME__?.snapshot;\n  if (!next) return cachedClientSnapshot;\n  if (!snapshotsMatch(cachedClientSnapshot, next)) cachedClientSnapshot = next;\n  return cachedClientSnapshot;\n}\n\nexport function setTheme(theme: FarmThemePreference): void {\n  const runtime = typeof window === \"undefined\" ? undefined : window.__FARM_THEME__;\n  if (!runtime) {\n    throw new Error(\"The FARMJS theme runtime is not enabled. Add `theme` to farm.config.ts.\");\n  }\n  runtime.setTheme(theme);\n}\n\nexport function toggleTheme(): FarmResolvedTheme {\n  const next = getTheme().resolvedTheme === \"dark\" ? \"light\" : \"dark\";\n  setTheme(next);\n  return next;\n}\n\nexport function subscribeTheme(listener: () => void): () => void {\n  if (typeof window === \"undefined\") return () => {};\n  const handleThemeChange = () => {\n    getTheme();\n    listener();\n  };\n  window.addEventListener(\"farm:themechange\", handleThemeChange);\n  return () => window.removeEventListener(\"farm:themechange\", handleThemeChange);\n}\n","\"use client\";\n\nimport type React from \"react\";\nimport { forwardRef, useEffect, useRef, useCallback, type AnchorHTMLAttributes } from \"react\";\nimport {\n  buildFarmRoutePath,\n  type FarmRouterBuildOptions,\n  type FarmRouterPathParam,\n  type FarmRouterPathParams,\n} from \"../router\";\nimport { resolveFarmNavigationURL } from \"./navigation-url\";\nimport type { FarmViewTransitionMode } from \"./spa-router\";\nimport { isFarmLocaleChangeHref, localizeActiveFarmHref } from \"../i18n/client-runtime\";\nimport type { FarmI18nLocale } from \"../i18n/types\";\nimport { getFarmTrailingSlashPreference } from \"../trailing-slash\";\nimport { applyFarmBasePath, getFarmBasePath } from \"../base-path\";\nimport { useOptionalFarm } from \"../provider\";\n\n/**\n * Prefetch strategy (TanStack Router–style):\n * - \"intent\": prefetch on hover and touchstart (with prefetchDelay)\n * - \"viewport\": prefetch when link enters viewport (IntersectionObserver)\n * - \"render\": prefetch as soon as the link is mounted\n * - \"none\" | false: no prefetch\n */\nexport type PrefetchBehavior = false | \"intent\" | \"viewport\" | \"render\" | \"none\";\n\n/** @internal Legacy prefetch mode for backward compatibility */\ntype PrefetchLegacy = boolean | \"hover\" | \"viewport\" | \"none\";\n\n/**\n * Augment this interface via the generated farm.d.ts so Link href is typed\n * without passing a generic. Defaults to string when not augmented.\n */\nexport interface LinkDefaultRoute {}\n\nexport type DefaultRoutePath = LinkDefaultRoute extends { _: infer TRoute extends string }\n  ? TRoute\n  : string;\n\nexport type DefaultRoutePattern = LinkDefaultRoute extends {\n  pattern: infer TRoute extends string;\n}\n  ? TRoute\n  : DefaultRoutePath;\n\nexport type DefaultRouteHref = DefaultRoutePath | DefaultRoutePattern;\n\nexport type RouteHref<TRoute extends string> =\n  | TRoute\n  | `${TRoute}?${string}`\n  | `${TRoute}#${string}`\n  | `${TRoute}?${string}#${string}`;\n\n/** A generated route with params already filled into its pathname. */\nexport type ResolvedRouteHref = RouteHref<DefaultRoutePath>;\n\nexport type RouteParamValue = Exclude<FarmRouterPathParam, null | undefined>;\nexport type RouteOptionalParamValue = FarmRouterPathParam;\nexport type RouteParams<TRoute extends string> = string extends TRoute\n  ? FarmRouterPathParams\n  : ExtractRouteParams<StripRouteSuffix<TRoute>>;\n\n/** URI schemes recognized as typed external Link targets. Apps may augment this interface. */\nexport interface LinkExternalUriSchemes {\n  about: true;\n  blob: true;\n  data: true;\n  file: true;\n  ftp: true;\n  ftps: true;\n  geo: true;\n  git: true;\n  http: true;\n  https: true;\n  im: true;\n  intent: true;\n  irc: true;\n  ircs: true;\n  magnet: true;\n  mailto: true;\n  market: true;\n  sms: true;\n  ssh: true;\n  tel: true;\n  urn: true;\n  vscode: true;\n  webcal: true;\n  ws: true;\n  wss: true;\n}\n\ntype ExternalUriScheme = Extract<keyof LinkExternalUriSchemes, string>;\n\ntype UriSchemeLetter =\n  | \"a\"\n  | \"b\"\n  | \"c\"\n  | \"d\"\n  | \"e\"\n  | \"f\"\n  | \"g\"\n  | \"h\"\n  | \"i\"\n  | \"j\"\n  | \"k\"\n  | \"l\"\n  | \"m\"\n  | \"n\"\n  | \"o\"\n  | \"p\"\n  | \"q\"\n  | \"r\"\n  | \"s\"\n  | \"t\"\n  | \"u\"\n  | \"v\"\n  | \"w\"\n  | \"x\"\n  | \"y\"\n  | \"z\";\ntype UriSchemeStart = UriSchemeLetter | Uppercase<UriSchemeLetter>;\ntype UriSchemeCharacter =\n  | UriSchemeStart\n  | \"0\"\n  | \"1\"\n  | \"2\"\n  | \"3\"\n  | \"4\"\n  | \"5\"\n  | \"6\"\n  | \"7\"\n  | \"8\"\n  | \"9\"\n  | \"+\"\n  | \"-\"\n  | \".\";\ntype IsUriSchemeTail<TValue extends string> = TValue extends \"\"\n  ? true\n  : TValue extends `${infer First}${infer Rest}`\n    ? First extends UriSchemeCharacter\n      ? IsUriSchemeTail<Rest>\n      : false\n    : false;\ntype IsUriScheme<TValue extends string> = TValue extends `${infer First}${infer Rest}`\n  ? First extends UriSchemeStart\n    ? IsUriSchemeTail<Rest>\n    : false\n  : false;\n\ntype KnownExternalHref = `//${string}` | `${ExternalUriScheme}:${string}`;\n\n/** External URLs; these are never type-checked as routes. */\nexport type ExternalHref<THref extends string = string> = string extends THref\n  ? KnownExternalHref\n  : THref extends `//${string}`\n    ? THref\n    : THref extends `${infer Scheme}:${string}`\n      ? IsUriScheme<Scheme> extends true\n        ? THref\n        : never\n      : never;\n\ntype StripRouteSuffix<TRoute extends string> = TRoute extends `${infer Path}?${string}`\n  ? StripRouteSuffix<Path>\n  : TRoute extends `${infer Path}#${string}`\n    ? StripRouteSuffix<Path>\n    : TRoute;\n\ntype ExtractRouteParams<TRoute extends string> = Simplify<\n  ExtractOptionalCatchAllParams<TRoute> &\n    ExtractCatchAllParams<TRoute> &\n    ExtractDynamicParams<TRoute>\n>;\n\ntype ExtractOptionalCatchAllParams<TRoute extends string> =\n  TRoute extends `${string}[[...${infer Param}]]${infer Rest}`\n    ? { [Key in Param]?: RouteOptionalParamValue } & ExtractOptionalCatchAllParams<Rest>\n    : {};\n\ntype ExtractCatchAllParams<TRoute extends string> =\n  TRoute extends `${string}[...${infer Param}]${infer Rest}`\n    ? Param extends `[...${string}`\n      ? ExtractCatchAllParams<Rest>\n      : { [Key in Param]: RouteParamValue } & ExtractCatchAllParams<Rest>\n    : {};\n\ntype ExtractDynamicParams<TRoute extends string> =\n  TRoute extends `${string}[${infer Param}]${infer Rest}`\n    ? Param extends `...${string}` | `[...${string}`\n      ? ExtractDynamicParams<Rest>\n      : { [Key in Param]: RouteParamValue } & ExtractDynamicParams<Rest>\n    : {};\n\ntype Simplify<T> = { [Key in keyof T]: T[Key] } & {};\n\ntype HasRouteParams<TRoute extends string> = keyof RouteParams<TRoute> extends never ? false : true;\n\ntype RoutesWithRequiredParams<TRoute extends string> = TRoute extends string\n  ? HasRouteParams<TRoute> extends true\n    ? TRoute\n    : never\n  : never;\n\ntype LinkRouteParamsProps<TRoute extends string> = string extends TRoute\n  ? { params?: FarmRouterPathParams }\n  : HasRouteParams<TRoute> extends true\n    ? { params: RouteParams<TRoute> }\n    : { params?: FarmRouterPathParams };\n\ntype LinkRouteTargetProps<TRoute extends string> = [RoutesWithRequiredParams<TRoute>] extends [\n  never,\n]\n  ? {\n      /** Internal route path with all params already resolved. */\n      href: RouteHref<TRoute>;\n      params?: FarmRouterPathParams;\n    }\n  : TRoute extends string\n    ? {\n        /** Internal route path or route pattern. */\n        href: RouteHref<TRoute>;\n      } & LinkRouteParamsProps<TRoute>\n    : never;\n\ntype LinkExternalTargetProps<THref extends string = string> = {\n  /** External URL; these are never type-checked as app routes. */\n  href: ExternalHref<THref>;\n  params?: never;\n};\n\ntype LinkTargetProps<TRoute extends string, THref extends string> =\n  | LinkExternalTargetProps<THref>\n  | LinkRouteTargetProps<TRoute>;\n\nexport type LinkProps<\n  TRoute extends string = DefaultRouteHref,\n  THref extends string = string,\n> = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> &\n  LinkTargetProps<TRoute, THref> & {\n    /**\n     * When to prefetch. TanStack-style: \"intent\" (hover+touch), \"viewport\", \"render\", or \"none\".\n     * Legacy: true (intent+viewport), \"hover\" (intent), \"viewport\", false/\"none\".\n     */\n    prefetch?: PrefetchBehavior | PrefetchLegacy;\n    /** Search params appended after route params are resolved. */\n    query?: FarmRouterBuildOptions[\"query\"];\n    /** Hash appended after route params and search params are resolved. */\n    hash?: string;\n    /** Add a trailing slash to the generated internal href. */\n    trailingSlash?: boolean;\n    /** Delay in ms before intent-based prefetch (hover/touch). Default 50. */\n    prefetchDelay?: number;\n    /** Replace current history entry instead of pushing */\n    replace?: boolean;\n    /** Scroll to top after navigation (default: true) */\n    scroll?: boolean;\n    /** Wrap this SPA navigation in a browser View Transition when supported. */\n    viewTransition?: FarmViewTransitionMode;\n    /** Preserve the active locale by default, or navigate using this locale. */\n    locale?: FarmI18nLocale;\n  };\n\nfunction isModifierEvent(e: React.MouseEvent): boolean {\n  return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);\n}\n\nfunction isExternalUrl(href: string): boolean {\n  return href.startsWith(\"//\") || /^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(href);\n}\n\nfunction getRouter(): {\n  prefetch(href: string): Promise<void>;\n  observeForPrefetch(el: HTMLAnchorElement): void;\n  unobserveForPrefetch(el: HTMLAnchorElement): void;\n  navigate(\n    href: string,\n    opts: { replace?: boolean; scroll?: boolean; viewTransition?: FarmViewTransitionMode },\n  ): void;\n} | null {\n  if (typeof window !== \"undefined\" && (window as any).__FARM_SPA_ROUTER__) {\n    return (window as any).__FARM_SPA_ROUTER__;\n  }\n  return null;\n}\n\nfunction normalizePrefetch(prefetch: LinkProps[\"prefetch\"]): {\n  intent: boolean;\n  viewport: boolean;\n  render: boolean;\n} {\n  if (prefetch === false || prefetch === \"none\") {\n    return { intent: false, viewport: false, render: false };\n  }\n  if (prefetch === true) {\n    return { intent: true, viewport: true, render: false };\n  }\n  if (prefetch === \"hover\") {\n    return { intent: true, viewport: false, render: false };\n  }\n  if (prefetch === \"intent\") {\n    return { intent: true, viewport: false, render: false };\n  }\n  if (prefetch === \"viewport\") {\n    return { intent: false, viewport: true, render: false };\n  }\n  if (prefetch === \"render\") {\n    return { intent: false, viewport: false, render: true };\n  }\n  return { intent: false, viewport: false, render: false };\n}\n\nfunction LinkInner<TRoute extends string = DefaultRouteHref, THref extends string = string>(\n  {\n    href,\n    params,\n    query,\n    hash,\n    trailingSlash,\n    prefetch = true,\n    prefetchDelay = 50,\n    replace = false,\n    scroll = true,\n    viewTransition = false,\n    locale,\n    onClick,\n    target,\n    onMouseEnter,\n    onMouseLeave,\n    onFocus,\n    onBlur,\n    onTouchStart,\n    ...props\n  }: LinkProps<TRoute, THref>,\n  ref: React.ForwardedRef<HTMLAnchorElement>,\n) {\n  const elementRef = useRef<HTMLAnchorElement | null>(null);\n  const intentTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const activePrefetch = useRef<symbol | null>(null);\n  const farm = useOptionalFarm();\n\n  const { intent, viewport, render } = normalizePrefetch(prefetch);\n  const baseHref = resolveLinkHref(href, params, {\n    query,\n    hash,\n    trailingSlash: trailingSlash ?? getFarmTrailingSlashPreference(),\n  });\n  const localizedHref = localizeActiveFarmHref(baseHref, locale);\n  const resolvedHref = isExternalUrl(localizedHref)\n    ? localizedHref\n    : applyFarmBasePath(localizedHref, farm?.basePath ?? getFarmBasePath());\n  const isExternal = isExternalUrl(resolvedHref);\n\n  const doPrefetch = useCallback(() => {\n    if (isExternal || activePrefetch.current) return;\n    const router = getRouter();\n    if (!router) return;\n    const token = Symbol(resolvedHref);\n    activePrefetch.current = token;\n    const reset = () => {\n      if (activePrefetch.current === token) activePrefetch.current = null;\n    };\n    try {\n      void router.prefetch(resolvedHref).then(reset, reset);\n    } catch {\n      reset();\n    }\n  }, [resolvedHref, isExternal]);\n\n  useEffect(() => {\n    activePrefetch.current = null;\n  }, [resolvedHref]);\n\n  useEffect(() => {\n    const element = elementRef.current;\n    if (!element || isExternal) return;\n\n    const router = getRouter();\n    if (!router) return;\n\n    if (viewport) {\n      router.observeForPrefetch(element);\n      return () => router.unobserveForPrefetch(element);\n    }\n  }, [resolvedHref, viewport, isExternal]);\n\n  useEffect(() => {\n    if (!render || isExternal) return;\n\n    let cancelled = false;\n    let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n    const tryRenderPrefetch = () => {\n      if (cancelled || activePrefetch.current) return;\n\n      const router = getRouter();\n      if (!router) {\n        timeoutId = setTimeout(tryRenderPrefetch, 30);\n        return;\n      }\n\n      doPrefetch();\n    };\n\n    tryRenderPrefetch();\n\n    return () => {\n      cancelled = true;\n      if (timeoutId) {\n        clearTimeout(timeoutId);\n      }\n    };\n  }, [render, isExternal, resolvedHref, doPrefetch]);\n\n  useEffect(() => {\n    return () => {\n      if (intentTimeoutRef.current) {\n        clearTimeout(intentTimeoutRef.current);\n        intentTimeoutRef.current = null;\n      }\n    };\n  }, []);\n\n  const cancelIntent = useCallback(() => {\n    if (intentTimeoutRef.current) {\n      clearTimeout(intentTimeoutRef.current);\n      intentTimeoutRef.current = null;\n    }\n  }, []);\n\n  const scheduleIntentPrefetch = useCallback(() => {\n    if (isExternal || !intent || activePrefetch.current) return;\n    cancelIntent();\n    intentTimeoutRef.current = setTimeout(() => {\n      intentTimeoutRef.current = null;\n      doPrefetch();\n    }, prefetchDelay);\n  }, [intent, isExternal, prefetchDelay, doPrefetch, cancelIntent]);\n\n  const handleMouseEnter = useCallback(\n    (event: React.MouseEvent<HTMLAnchorElement>) => {\n      onMouseEnter?.(event);\n      scheduleIntentPrefetch();\n    },\n    [onMouseEnter, scheduleIntentPrefetch],\n  );\n\n  const handleMouseLeave = useCallback(\n    (event: React.MouseEvent<HTMLAnchorElement>) => {\n      onMouseLeave?.(event);\n      cancelIntent();\n    },\n    [onMouseLeave, cancelIntent],\n  );\n\n  const handleTouchStart = useCallback(\n    (event: React.TouchEvent<HTMLAnchorElement>) => {\n      onTouchStart?.(event);\n      scheduleIntentPrefetch();\n    },\n    [onTouchStart, scheduleIntentPrefetch],\n  );\n\n  const handleFocus = useCallback(\n    (event: React.FocusEvent<HTMLAnchorElement>) => {\n      onFocus?.(event);\n      scheduleIntentPrefetch();\n    },\n    [onFocus, scheduleIntentPrefetch],\n  );\n\n  const handleBlur = useCallback(\n    (event: React.FocusEvent<HTMLAnchorElement>) => {\n      onBlur?.(event);\n      cancelIntent();\n    },\n    [onBlur, cancelIntent],\n  );\n\n  const handleClick = useCallback(\n    (event: React.MouseEvent<HTMLAnchorElement>) => {\n      onClick?.(event);\n      if (event.defaultPrevented) return;\n      if (isExternal) return;\n      if (event.currentTarget.hasAttribute(\"download\")) return;\n      if (target && target !== \"_self\") return;\n      if (isModifierEvent(event)) return;\n      if (event.button !== 0) return;\n\n      if (typeof window !== \"undefined\") {\n        event.preventDefault();\n        if (isFarmLocaleChangeHref(localizedHref)) {\n          window.location.assign(resolvedHref);\n          return;\n        }\n        const router = getRouter();\n        if (router) {\n          router.navigate(resolvedHref, { replace, scroll, viewTransition });\n        } else {\n          if (replace) window.location.replace(resolvedHref);\n          else window.location.href = resolvedHref;\n        }\n      }\n    },\n    [localizedHref, resolvedHref, replace, scroll, viewTransition, target, isExternal, onClick],\n  );\n\n  const setRefs = useCallback(\n    (node: HTMLAnchorElement | null) => {\n      elementRef.current = node;\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) (ref as React.MutableRefObject<HTMLAnchorElement | null>).current = node;\n    },\n    [ref],\n  );\n\n  return (\n    <a\n      ref={setRefs}\n      href={resolvedHref}\n      target={target}\n      onClick={handleClick}\n      onMouseEnter={handleMouseEnter}\n      onMouseLeave={handleMouseLeave}\n      onFocus={handleFocus}\n      onBlur={handleBlur}\n      onTouchStart={handleTouchStart}\n      {...props}\n      data-farm-link=\"\"\n      data-replace={replace ? \"\" : undefined}\n      data-no-scroll={!scroll ? \"\" : undefined}\n      data-view-transition={\n        viewTransition === \"auto\" ? \"auto\" : viewTransition ? \"true\" : undefined\n      }\n    />\n  );\n}\n\nconst LinkWithRef = forwardRef(LinkInner);\nLinkWithRef.displayName = \"Link\";\n\ntype LinkComponentType = <TRoute extends string = DefaultRouteHref, THref extends string = string>(\n  props: LinkProps<TRoute, THref> & { ref?: React.ForwardedRef<HTMLAnchorElement> },\n) => React.ReactElement;\n\nexport const Link = LinkWithRef as unknown as LinkComponentType;\n\nfunction resolveLinkHref(\n  href: string,\n  params: FarmRouterPathParams | undefined,\n  options: FarmRouterBuildOptions,\n) {\n  if (isExternalUrl(href)) return href;\n\n  const { pathname, query, hash } = splitInternalHref(href);\n\n  const resolvedHref = buildFarmRoutePath(pathname, params, {\n    query: mergeQueryParams(query, options.query),\n    hash: options.hash ?? hash,\n    trailingSlash: options.trailingSlash,\n  });\n\n  return applyPreservedSearchParams(resolvedHref);\n}\n\nfunction splitInternalHref(href: string) {\n  try {\n    const url = new URL(href, \"http://farm.local\");\n    return {\n      pathname: url.pathname || \"/\",\n      query: url.searchParams,\n      hash: url.hash ? url.hash.slice(1) : undefined,\n    };\n  } catch {\n    const [withoutHash, rawHash] = href.split(\"#\", 2);\n    const [pathname, rawQuery] = withoutHash.split(\"?\", 2);\n    return {\n      pathname: pathname || \"/\",\n      query: new URLSearchParams(rawQuery || \"\"),\n      hash: rawHash,\n    };\n  }\n}\n\nfunction mergeQueryParams(\n  current: URLSearchParams,\n  next: FarmRouterBuildOptions[\"query\"],\n): URLSearchParams | undefined {\n  const merged = new URLSearchParams(current);\n\n  if (next instanceof URLSearchParams) {\n    for (const [key, value] of next.entries()) {\n      merged.append(key, value);\n    }\n  } else if (next) {\n    for (const [key, value] of Object.entries(next)) {\n      const values = Array.isArray(value) ? value : [value];\n      for (const item of values) {\n        if (item == null) continue;\n        merged.append(key, String(item));\n      }\n    }\n  }\n\n  return merged.toString() ? merged : undefined;\n}\n\nfunction applyPreservedSearchParams(href: string): string {\n  if (typeof window === \"undefined\") return href;\n\n  const manifest = (window as any).__FARM_MANIFEST__;\n  const routes =\n    manifest?.routes && typeof manifest.routes === \"object\" ? Object.values(manifest.routes) : [];\n  if (routes.length === 0) return href;\n\n  const url = resolveFarmNavigationURL(href, window.location.href);\n  const route = routes.find((candidate: any) => matchManifestRoute(url.pathname, candidate));\n  const preserve = Array.isArray((route as any)?.search?.preserve)\n    ? ((route as any).search.preserve as string[])\n    : [];\n  if (preserve.length === 0) return href;\n\n  const current = new URLSearchParams(window.location.search);\n  let changed = false;\n\n  for (const key of preserve) {\n    if (url.searchParams.has(key) || !current.has(key)) continue;\n    for (const value of current.getAll(key)) {\n      url.searchParams.append(key, value);\n      changed = true;\n    }\n  }\n\n  if (!changed) return href;\n  return `${url.pathname}${url.search}${url.hash}`;\n}\n\nfunction matchManifestRoute(pathname: string, route: any): boolean {\n  if (!route || !Array.isArray(route.segments)) return false;\n  const routeSegments = route.segments;\n  const normalized = pathname === \"/\" ? \"\" : pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  const pathSegments = normalized ? normalized.split(\"/\") : [];\n  const hasCatchAll = routeSegments.some((segment: any) => segment.isCatchAll);\n\n  if (!hasCatchAll && pathSegments.length !== routeSegments.length) {\n    return false;\n  }\n\n  for (let index = 0; index < routeSegments.length; index++) {\n    const routeSegment = routeSegments[index];\n    const pathSegment = pathSegments[index];\n\n    if (routeSegment.isCatchAll) {\n      return true;\n    }\n\n    if (pathSegment === undefined) {\n      if (routeSegment.isOptional) continue;\n      return false;\n    }\n\n    if (!routeSegment.isDynamic && routeSegment.segment !== pathSegment) {\n      return false;\n    }\n  }\n\n  return pathSegments.length === routeSegments.length || hasCatchAll;\n}\n","import {\n  AmbiguousRouteError,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n  compareRouteSpecificity,\n  getRoutePatternShape,\n  type RouteSegmentSpecificity,\n} from \"./routing/specificity\";\n\nexport type FarmRouterPrimitiveParam = string | number | boolean;\nexport type FarmRouterPathParam =\n  | FarmRouterPrimitiveParam\n  | readonly FarmRouterPrimitiveParam[]\n  | null\n  | undefined;\nexport type FarmRouterPathParams = Record<string, FarmRouterPathParam>;\nexport type FarmRouterParams = Record<string, string>;\n\nexport interface FarmRouterRoute<TMeta = unknown> {\n  path: string;\n  name?: string;\n  meta?: TMeta;\n}\n\nexport type FarmRouterRouteInput<TMeta = unknown> = string | FarmRouterRoute<TMeta>;\n\nexport interface FarmRouterMatch<TMeta = unknown> {\n  route: FarmRouterRoute<TMeta>;\n  pathname: string;\n  params: FarmRouterParams;\n}\n\nexport type FarmRouterQueryValue =\n  | FarmRouterPrimitiveParam\n  | readonly FarmRouterPrimitiveParam[]\n  | null\n  | undefined;\n\nexport interface FarmRouterBuildOptions {\n  query?: URLSearchParams | Record<string, FarmRouterQueryValue>;\n  hash?: string;\n  trailingSlash?: boolean;\n}\n\nexport interface FarmRouterActiveOptions {\n  exact?: boolean;\n}\n\nexport interface FarmRouter<TMeta = unknown> {\n  routes: FarmRouterRoute<TMeta>[];\n  match(pathname: string): FarmRouterMatch<TMeta> | null;\n  build(pattern: string, params?: FarmRouterPathParams, options?: FarmRouterBuildOptions): string;\n  isActive(pattern: string, pathname: string, options?: FarmRouterActiveOptions): boolean;\n}\n\ntype RouterSegment =\n  | {\n      type: \"static\";\n      value: string;\n    }\n  | {\n      type: \"dynamic\";\n      name: string;\n      catchAll: boolean;\n      optional: boolean;\n    };\n\ninterface NormalizedRouterRoute<TMeta> {\n  route: FarmRouterRoute<TMeta>;\n  segments: RouterSegment[];\n  specificity: RouteSegmentSpecificity[];\n  index: number;\n}\n\nexport function createFarmRouter<TMeta = unknown>(\n  routes: FarmRouterRouteInput<TMeta>[],\n): FarmRouter<TMeta> {\n  const normalizedRoutes = routes.map(normalizeRouteInput);\n  const patternsByShape = new Map<string, string>();\n  for (const entry of normalizedRoutes) {\n    const shape = getRoutePatternShape(entry.route.path, \"router\");\n    const existingPattern = patternsByShape.get(shape);\n    if (existingPattern) {\n      throw new AmbiguousRouteError(\n        `Ambiguous route patterns \"${existingPattern}\" and \"${entry.route.path}\" match the same URLs. Keep only one route for this URL shape.`,\n      );\n    }\n    patternsByShape.set(shape, entry.route.path);\n  }\n  normalizedRoutes.sort(compareRoutes);\n\n  return {\n    routes: normalizedRoutes.map((entry) => entry.route),\n    match(pathname) {\n      const normalizedPathname = normalizePathname(pathname);\n\n      for (const entry of normalizedRoutes) {\n        const params = matchSegments(entry.segments, normalizedPathname);\n        if (params) {\n          return {\n            route: entry.route,\n            pathname: normalizedPathname,\n            params,\n          };\n        }\n      }\n\n      return null;\n    },\n    build: buildFarmRoutePath,\n    isActive: isFarmRouteActive,\n  };\n}\n\nexport function matchFarmRoute(pattern: string, pathname: string): FarmRouterParams | null {\n  return matchSegments(parseRoutePattern(pattern), normalizePathname(pathname));\n}\n\nexport function buildFarmRoutePath(\n  pattern: string,\n  params: FarmRouterPathParams = {},\n  options: FarmRouterBuildOptions = {},\n): string {\n  const parts: string[] = [];\n\n  for (const segment of parseRoutePattern(pattern)) {\n    if (segment.type === \"static\") {\n      parts.push(encodePathSegment(segment.value));\n      continue;\n    }\n\n    const value = params[segment.name];\n    const values = Array.isArray(value) ? value : value == null ? [] : [value];\n\n    if (values.length === 0) {\n      if (segment.optional) continue;\n      throw new Error(`Missing route param \"${segment.name}\" for ${pattern}.`);\n    }\n\n    if (!segment.catchAll && values.length > 1) {\n      throw new Error(`Route param \"${segment.name}\" for ${pattern} expects a single value.`);\n    }\n\n    const encodedValues = values.map((item) => {\n      const value = String(item);\n      if (!value) {\n        throw new Error(\n          `Route param \"${segment.name}\" for ${pattern} cannot contain an empty path segment.`,\n        );\n      }\n      return encodePathSegment(value);\n    });\n    parts.push(...encodedValues);\n  }\n\n  let pathname = parts.length ? `/${parts.join(\"/\")}` : \"/\";\n\n  if (options.trailingSlash && pathname !== \"/\") {\n    pathname = `${pathname}/`;\n  }\n\n  return appendQueryAndHash(pathname, options);\n}\n\nexport function isFarmRouteActive(\n  pattern: string,\n  pathname: string,\n  options: FarmRouterActiveOptions = {},\n): boolean {\n  const normalizedPathname = normalizePathname(pathname);\n  if (matchFarmRoute(pattern, normalizedPathname)) return true;\n  if (options.exact !== false) return false;\n\n  const segments = parseRoutePattern(pattern);\n  if (segments.length === 0) return normalizedPathname === \"/\";\n  return matchSegments(segments, normalizedPathname, true) !== null;\n}\n\nfunction normalizeRouteInput<TMeta>(\n  input: FarmRouterRouteInput<TMeta>,\n  index: number,\n): NormalizedRouterRoute<TMeta> {\n  const route = typeof input === \"string\" ? { path: input } : input;\n  const path = normalizeRoutePattern(route.path);\n  const segments = parseRoutePattern(path);\n\n  return {\n    route: {\n      ...route,\n      path,\n    },\n    segments,\n    specificity: segments.map(getRouterSegmentSpecificity),\n    index,\n  };\n}\n\nfunction parseRoutePattern(pattern: string): RouterSegment[] {\n  assertTerminalCatchAll(pattern, \"router\");\n  assertUniqueRouteParameters(pattern, \"router\");\n  return splitRoutePattern(pattern)\n    .filter((part) => !isRouteGroup(part))\n    .map((part) => {\n      const optionalCatchAll = part.match(/^\\[\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]\\]$/);\n      if (optionalCatchAll) {\n        return {\n          type: \"dynamic\",\n          name: optionalCatchAll[1],\n          catchAll: true,\n          optional: true,\n        };\n      }\n\n      const catchAll = part.match(/^\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]$/);\n      if (catchAll) {\n        return {\n          type: \"dynamic\",\n          name: catchAll[1],\n          catchAll: true,\n          optional: false,\n        };\n      }\n\n      const dynamic = part.match(/^\\[([A-Za-z0-9_$-]+)\\]$/) || part.match(/^:([A-Za-z0-9_$-]+)$/);\n      if (dynamic) {\n        return {\n          type: \"dynamic\",\n          name: dynamic[1],\n          catchAll: false,\n          optional: false,\n        };\n      }\n\n      const star = part.match(/^\\*([A-Za-z0-9_$-]+)(\\?)?$/);\n      if (star) {\n        return {\n          type: \"dynamic\",\n          name: star[1],\n          catchAll: true,\n          optional: !!star[2],\n        };\n      }\n\n      return {\n        type: \"static\",\n        value: decodePathSegment(part),\n      };\n    });\n}\n\nfunction matchSegments(\n  segments: RouterSegment[],\n  pathname: string,\n  allowTrailingSegments = false,\n): FarmRouterParams | null {\n  const parts = splitPathname(pathname);\n  const params: FarmRouterParams = {};\n\n  if (segments.length === 0) {\n    return parts.length === 0 ? params : null;\n  }\n\n  let pathIndex = 0;\n\n  for (const segment of segments) {\n    if (segment.type === \"static\") {\n      if (decodePathSegment(parts[pathIndex] || \"\") !== segment.value) return null;\n      pathIndex++;\n      continue;\n    }\n\n    if (segment.catchAll) {\n      const remaining = parts.slice(pathIndex).map(decodePathSegment);\n      if (remaining.length === 0 && !segment.optional) return null;\n      params[segment.name] = remaining.join(\"/\");\n      pathIndex = parts.length;\n      continue;\n    }\n\n    const value = parts[pathIndex];\n    if (!value) return null;\n    params[segment.name] = decodePathSegment(value);\n    pathIndex++;\n  }\n\n  return allowTrailingSegments || pathIndex === parts.length ? params : null;\n}\n\nfunction compareRoutes<TMeta>(\n  left: NormalizedRouterRoute<TMeta>,\n  right: NormalizedRouterRoute<TMeta>,\n) {\n  const specificity = compareRouteSpecificity(left.specificity, right.specificity);\n  if (specificity !== 0) return specificity;\n  return left.index - right.index;\n}\n\nfunction getRouterSegmentSpecificity(segment: RouterSegment): RouteSegmentSpecificity {\n  if (segment.type === \"static\") return \"static\";\n  if (!segment.catchAll) return \"dynamic\";\n  return segment.optional ? \"optional-catch-all\" : \"catch-all\";\n}\n\nfunction normalizePathname(value: string) {\n  const raw = value || \"/\";\n  let pathname = raw;\n\n  try {\n    pathname = new URL(raw, \"http://farm.local\").pathname;\n  } catch {\n    pathname = raw.split(/[?#]/, 1)[0] || \"/\";\n  }\n\n  pathname = pathname.replace(/\\\\/g, \"/\").replace(/\\/+/g, \"/\");\n  if (!pathname.startsWith(\"/\")) pathname = `/${pathname}`;\n  if (pathname.length > 1) pathname = pathname.replace(/\\/+$/, \"\");\n  return pathname || \"/\";\n}\n\nfunction splitPathname(pathname: string) {\n  return normalizePathname(pathname).split(\"/\").filter(Boolean);\n}\n\nfunction normalizeRoutePattern(value: string) {\n  let pathname = (value || \"/\").replace(/\\\\/g, \"/\").replace(/\\/+/g, \"/\");\n  if (!pathname.startsWith(\"/\")) pathname = `/${pathname}`;\n  if (pathname.length > 1) pathname = pathname.replace(/\\/+$/, \"\");\n  return pathname || \"/\";\n}\n\nfunction splitRoutePattern(pattern: string) {\n  return normalizeRoutePattern(pattern).split(\"/\").filter(Boolean);\n}\n\nfunction isRouteGroup(part: string) {\n  return part.startsWith(\"(\") && part.endsWith(\")\");\n}\n\nfunction decodePathSegment(value: string) {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return value;\n  }\n}\n\nfunction encodePathSegment(value: string) {\n  return encodeURIComponent(value);\n}\n\nfunction appendQueryAndHash(pathname: string, options: FarmRouterBuildOptions) {\n  const search = createSearchParams(options.query);\n  const hash = options.hash ? `#${options.hash.replace(/^#/, \"\")}` : \"\";\n  const query = search.toString();\n  return `${pathname}${query ? `?${query}` : \"\"}${hash}`;\n}\n\nfunction createSearchParams(query: FarmRouterBuildOptions[\"query\"]) {\n  if (query instanceof URLSearchParams) return query;\n\n  const search = new URLSearchParams();\n  if (!query) return search;\n\n  for (const [key, value] of Object.entries(query)) {\n    const values = Array.isArray(value) ? value : [value];\n    for (const item of values) {\n      if (item == null) continue;\n      search.append(key, String(item));\n    }\n  }\n\n  return search;\n}\n","export function isFarmExternalNavigationURL(url: URL, currentOrigin: string): boolean {\n  return (url.protocol !== \"http:\" && url.protocol !== \"https:\") || url.origin !== currentOrigin;\n}\n\n/**\n * Resolve a navigation target the way the platform does.\n *\n * Relative references resolve against the *document's* URL, not the origin.\n * Basing on the origin turns `?tab=2` into `/?tab=2` and `details` into\n * `/details`, discarding the directory the user is actually on, so every\n * navigation entry point has to resolve through here.\n *\n * Absolute paths and absolute URLs are unaffected by the choice of base.\n */\nexport function resolveFarmNavigationURL(href: string, documentUrl: string): URL {\n  return new URL(href, documentUrl);\n}\n","import IntlMessageFormat from \"intl-messageformat\";\nimport { getActiveFarmI18nSnapshot } from \"./bridge\";\nimport { localizeFarmHref, resolveFarmLocalePath } from \"./routing\";\nimport type {\n  FarmI18nClientSnapshot,\n  FarmI18nLocale,\n  FarmI18nMessageArgs,\n  FarmI18nMessageKey,\n  FarmTranslator,\n} from \"./types\";\n\ntype Listener = () => void;\n\nconst listeners = new Set<Listener>();\nconst compiled = new Map<string, IntlMessageFormat>();\nlet currentSnapshot: FarmI18nClientSnapshot | undefined;\n\nexport function getFarmI18nClientState(): FarmI18nClientSnapshot | undefined {\n  return currentSnapshot || getActiveFarmI18nSnapshot();\n}\n\nexport function subscribeFarmI18n(listener: Listener): () => void {\n  listeners.add(listener);\n  return () => listeners.delete(listener);\n}\n\nexport function _hydrateFarmI18n(snapshot: FarmI18nClientSnapshot | undefined): void {\n  if (!snapshot) return;\n  const changed = currentSnapshot?.locale !== snapshot.locale;\n  currentSnapshot = snapshot;\n  if (typeof window !== \"undefined\") window.__FARM_I18N__ = snapshot;\n  if (typeof document !== \"undefined\") {\n    document.documentElement.lang = snapshot.locale;\n    document.documentElement.dir = snapshot.direction;\n  }\n  if (changed) compiled.clear();\n  for (const listener of listeners) listener();\n}\n\n// Only own catalog entries count. `snapshot.messages` is a spread object that\n// inherits Object.prototype, so a bare lookup for a key like \"toString\" or\n// \"constructor\" would resolve to a native method. The server side guards the\n// same way (readOwnMessage), so without this the client diverges: the server\n// renders the literal key while the client feeds a function to IntlMessageFormat\n// and throws during hydration.\nconst readOwnMessage = (messages: Record<string, string>, key: string): string | undefined =>\n  Object.prototype.hasOwnProperty.call(messages, key) ? messages[key] : undefined;\n\nconst translate = (key: string, values?: Record<string, unknown>, rich = false): unknown => {\n  const snapshot = requireSnapshot();\n  const message = readOwnMessage(snapshot.messages, key);\n  if (message === undefined) return key;\n  const cacheKey = `${snapshot.locale}\\u0000${key}\\u0000${message}`;\n  let formatter = compiled.get(cacheKey);\n  if (!formatter) {\n    formatter = new IntlMessageFormat(message, snapshot.locale);\n    compiled.set(cacheKey, formatter);\n  }\n  const result = formatter.format(values as any);\n  if (rich) return Array.isArray(result) && result.length === 1 ? result[0] : result;\n  if (Array.isArray(result) && result.some((part) => typeof part !== \"string\")) {\n    throw new Error(`Farm i18n message \"${key}\" contains rich content. Render it with t.rich().`);\n  }\n  return Array.isArray(result) ? result.join(\"\") : String(result);\n};\n\nexport const t = ((key: string, values?: Record<string, unknown>) =>\n  translate(key, values)) as FarmTranslator;\nt.rich = (key: string, values?: Record<string, unknown>) => translate(key, values, true);\nt.raw = (key: string) => readOwnMessage(requireSnapshot().messages, key) ?? key;\nt.has = (key: string) => Object.prototype.hasOwnProperty.call(requireSnapshot().messages, key);\n\nexport function localizeActiveFarmHref(href: string, locale?: FarmI18nLocale): string {\n  const snapshot = getFarmI18nClientState();\n  if (!snapshot) return href;\n  return localizeFarmHref(href, locale || snapshot.locale, snapshot);\n}\n\nexport function isFarmLocaleChangeHref(href: string): boolean {\n  const snapshot = getFarmI18nClientState();\n  if (!snapshot || typeof window === \"undefined\") return false;\n  if (snapshot.routing === \"none\") return false;\n  const target = new URL(href, window.location.origin);\n  const match = resolveFarmLocalePath(target.pathname, snapshot);\n  const targetLocale = match.locale || snapshot.defaultLocale;\n  return targetLocale !== snapshot.locale;\n}\n\nexport function createFarmClientTranslator(): FarmTranslator {\n  return (<TKey extends FarmI18nMessageKey>(key: TKey, ...args: FarmI18nMessageArgs<TKey>) =>\n    t(key, ...args)) as FarmTranslator;\n}\n\nfunction requireSnapshot(): FarmI18nClientSnapshot {\n  const snapshot = getFarmI18nClientState();\n  if (!snapshot) {\n    throw new Error(\"Farm i18n is not configured or has not been hydrated.\");\n  }\n  return snapshot;\n}\n","const FARM_BASE_PATH = Symbol.for(\"farm.basePath\");\n\nfunction getFarmGlobalState(): Record<PropertyKey, unknown> {\n  return globalThis as unknown as Record<PropertyKey, unknown>;\n}\n\n/** @internal Configure the app-wide base path for framework link rendering. */\nexport function setFarmBasePath(basePath: string | undefined): void {\n  getFarmGlobalState()[FARM_BASE_PATH] = normalizeFarmBasePath(basePath);\n}\n\n/** @internal Read the app-wide base path used by framework links. */\nexport function getFarmBasePath(): string {\n  return (getFarmGlobalState()[FARM_BASE_PATH] as string | undefined) ?? \"\";\n}\n\nexport function applyFarmBasePath(href: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath || !href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n  const canonicalHref = canonicalizeAppRelativeHref(href);\n  if (\n    canonicalHref === normalizedBasePath ||\n    canonicalHref.startsWith(`${normalizedBasePath}/`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}?`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}#`)\n  ) {\n    return canonicalHref;\n  }\n  return `${normalizedBasePath}${canonicalHref}`;\n}\n\nfunction canonicalizeAppRelativeHref(href: string): string {\n  const origin = \"http://farm.local\";\n  const resolved = new URL(href, origin);\n  if (resolved.origin !== origin) {\n    throw new Error(\"Farm app-relative href cannot change the URL origin.\");\n  }\n  return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nexport function stripFarmBasePath(pathname: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath) return pathname || \"/\";\n  if (pathname === normalizedBasePath) return \"/\";\n  if (!pathname.startsWith(`${normalizedBasePath}/`)) return pathname || \"/\";\n  return pathname.slice(normalizedBasePath.length) || \"/\";\n}\n\nexport function normalizeFarmBasePath(basePath: string | undefined): string {\n  if (!basePath || basePath === \"/\") return \"\";\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(basePath)) {\n    throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n  }\n\n  const pathname = basePath.trim();\n  if (!pathname || pathname === \"/\") return \"\";\n  if (pathname.includes(\"?\") || pathname.includes(\"#\")) {\n    throw new Error(\"Farm basePath cannot contain a query string or hash.\");\n  }\n  if (pathname.startsWith(\"//\") || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(pathname)) {\n    throw new Error('Farm basePath must be a pathname such as \"/docs\", not a URL.');\n  }\n\n  for (const segment of pathname.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal in URL pathnames and cannot be dot segments.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"Farm basePath cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('Farm basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  return `/${pathname}`.replace(/\\/{2,}/g, \"/\").replace(/\\/+$/, \"\");\n}\n\n/** Normalize a configured application base path while preserving `/` for root. */\nexport function normalizeFarmConfigBasePath(basePath: string | undefined): string {\n  return normalizeFarmBasePath(basePath) || \"/\";\n}\n","import { applyFarmBasePath, stripFarmBasePath } from \"../base-path\";\nimport type { FarmI18nDirection, FarmI18nRouting, ResolvedFarmI18nConfig } from \"./types\";\n\nexport interface FarmLocalePathConfig {\n  locales: readonly string[];\n  defaultLocale: string;\n  routing: FarmI18nRouting;\n  basePath?: string;\n}\n\nexport interface FarmLocalePathMatch {\n  locale?: string;\n  pathname: string;\n  explicit: boolean;\n}\n\nconst RTL_LANGUAGES = new Set([\n  \"ar\",\n  \"arc\",\n  \"ckb\",\n  \"dv\",\n  \"fa\",\n  \"he\",\n  \"ku\",\n  \"nqo\",\n  \"ps\",\n  \"sd\",\n  \"syr\",\n  \"ug\",\n  \"ur\",\n  \"yi\",\n]);\n\nexport function resolveFarmLocalePath(\n  pathname: string,\n  config: FarmLocalePathConfig,\n): FarmLocalePathMatch {\n  const normalized = normalizePathname(stripFarmBasePath(pathname, config.basePath));\n  if (config.routing === \"none\") {\n    return { pathname: normalized, explicit: false };\n  }\n\n  const segments = normalized.split(\"/\").filter(Boolean);\n  const firstSegment = segments[0];\n  const locale = config.locales.find(\n    (candidate) => candidate.toLowerCase() === firstSegment?.toLowerCase(),\n  );\n  if (!locale) {\n    return { pathname: normalized, explicit: false };\n  }\n\n  const remaining = segments.slice(1);\n  return {\n    locale,\n    pathname: remaining.length > 0 ? `/${remaining.join(\"/\")}` : \"/\",\n    explicit: true,\n  };\n}\n\nexport function stripFarmLocaleFromPathname(\n  pathname: string,\n  config: FarmLocalePathConfig,\n): string {\n  return resolveFarmLocalePath(pathname, config).pathname;\n}\n\nexport function localizeFarmPathname(\n  pathname: string,\n  locale: string,\n  config: FarmLocalePathConfig,\n): string {\n  const internalPathname = resolveFarmLocalePath(pathname, config).pathname;\n  let localizedPathname = internalPathname;\n  if (config.routing === \"none\") {\n    return applyFarmBasePath(localizedPathname, config.basePath);\n  }\n  if (config.routing === \"prefix-except-default\" && locale === config.defaultLocale) {\n    return applyFarmBasePath(localizedPathname, config.basePath);\n  }\n  localizedPathname = internalPathname === \"/\" ? `/${locale}` : `/${locale}${internalPathname}`;\n  return applyFarmBasePath(localizedPathname, config.basePath);\n}\n\nexport function localizeFarmHref(\n  href: string,\n  locale: string,\n  config: FarmLocalePathConfig,\n): string {\n  if (!href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n  const url = new URL(href, \"http://farm.local\");\n  url.pathname = localizeFarmPathname(url.pathname, locale, config);\n  return `${url.pathname}${url.search}${url.hash}`;\n}\n\nexport function getFarmLocaleDirection(\n  locale: string,\n  direction: ResolvedFarmI18nConfig[\"direction\"] | undefined,\n): FarmI18nDirection {\n  const configured = direction?.[locale];\n  if (configured) return configured;\n  const language = locale.split(\"-\")[0]?.toLowerCase() || locale.toLowerCase();\n  return RTL_LANGUAGES.has(language) ? \"rtl\" : \"ltr\";\n}\n\nfunction normalizePathname(pathname: string): string {\n  const withLeadingSlash = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n  if (withLeadingSlash === \"/\") return \"/\";\n  return withLeadingSlash.replace(/\\/{2,}/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n}\n","const FARM_TRAILING_SLASH_PREFERENCE = Symbol.for(\"farm.trailingSlashPreference\");\n\nfunction getFarmGlobalState(): Record<PropertyKey, unknown> {\n  return globalThis as unknown as Record<PropertyKey, unknown>;\n}\n\n/** @internal Configure the app-wide URL preference for framework link rendering. */\nexport function setFarmTrailingSlashPreference(enabled: boolean | undefined): void {\n  getFarmGlobalState()[FARM_TRAILING_SLASH_PREFERENCE] = enabled === true;\n}\n\n/** @internal Read the app-wide URL preference used by framework links. */\nexport function getFarmTrailingSlashPreference(): boolean {\n  return getFarmGlobalState()[FARM_TRAILING_SLASH_PREFERENCE] === true;\n}\n\nexport function normalizeFarmTrailingSlashPathname(pathname: string, enabled: boolean): string {\n  if (pathname === \"/\") return pathname;\n  if (enabled) return pathname.endsWith(\"/\") ? pathname : `${pathname}/`;\n  return pathname.replace(/\\/+$/, \"\") || \"/\";\n}\n\nexport function resolveFarmTrailingSlashRedirect(url: URL, enabled: boolean): string | null {\n  const pathname = normalizeFarmTrailingSlashPathname(url.pathname, enabled);\n  return pathname === url.pathname ? null : `${pathname}${url.search}`;\n}\n","import React, { createContext, useContext, type ReactNode } from \"react\";\nimport type { FarmConfig } from \"./types\";\nimport { normalizeFarmBasePath } from \"./base-path\";\n\ninterface FarmContextValue {\n  config: FarmConfig;\n  basePath: string;\n}\n\nconst FarmContext = createContext<FarmContextValue | null>(null);\n\ninterface FarmProviderProps {\n  children: ReactNode;\n  config: FarmConfig;\n}\n\n/**\n * Farm.js context provider for client-side components\n */\nexport function FarmProvider({ children, config }: FarmProviderProps) {\n  const value: FarmContextValue = {\n    config,\n    basePath: normalizeFarmBasePath(config.basePath),\n  };\n\n  return <FarmContext.Provider value={value}>{children}</FarmContext.Provider>;\n}\n\n/**\n * Hook to access Farm.js configuration and utilities\n */\nexport function useFarm(): FarmContextValue {\n  const context = useContext(FarmContext);\n\n  if (!context) {\n    throw new Error(\"useFarm must be used within a FarmProvider\");\n  }\n\n  return context;\n}\n\n/** @internal Read Farm context when a component can also use a runtime fallback. */\nexport function useOptionalFarm(): FarmContextValue | null {\n  return useContext(FarmContext);\n}\n\n/**\n * Hook to get the current base path\n */\nexport function useBasePath(): string {\n  const { basePath } = useFarm();\n  return basePath;\n}\n","import { useEffect, useMemo, useRef, useState, type RefObject } from \"react\";\nimport { createFarmRouter, type FarmRouter, type FarmRouterRouteInput } from \"../router\";\nimport {\n  getInstalledFarmSPARouter,\n  getRouter as getSPARouter,\n  readPageState,\n  type FarmNavigationBlockerContext,\n  type FarmNavigationState,\n} from \"./spa-router\";\nimport { notifyHistoryChange, subscribeHistoryChange } from \"./history-sync\";\nimport { getFarmI18nClientState } from \"../i18n/client-runtime\";\nimport { _resolveCurrentRequest } from \"../server/request-bridge\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\nimport {\n  applyFarmBasePath,\n  getFarmBasePath,\n  normalizeFarmBasePath,\n  stripFarmBasePath,\n} from \"../base-path\";\n\ninterface RouterState {\n  pathname: string;\n  searchParams: URLSearchParams;\n  params: Record<string, string>;\n  pageState: unknown;\n}\n\nexport interface UseRouterOptions {\n  basePath?: string;\n  routes?: FarmRouterRouteInput[];\n}\n\nexport interface UseBlockerOptions {\n  when: boolean | ((context: FarmNavigationBlockerContext) => boolean);\n  message?: string;\n  shouldBlock?: (context: FarmNavigationBlockerContext) => boolean | Promise<boolean>;\n}\n\nexport interface UseBlockerReturn {\n  active: boolean;\n}\n\nfunction shouldBlockUnload(options: UseBlockerOptions): boolean {\n  const path = window.location.pathname + window.location.search;\n  const context: FarmNavigationBlockerContext = {\n    from: path,\n    to: path,\n    action: \"replace\",\n  };\n  const when = typeof options.when === \"function\" ? options.when(context) : options.when;\n  if (!when) return false;\n  if (!options.shouldBlock) return true;\n\n  try {\n    const result = options.shouldBlock(context);\n    if (typeof result === \"boolean\") return result;\n    void result.catch(() => undefined);\n    return true;\n  } catch {\n    return true;\n  }\n}\n\n/**\n * Hook for accessing router state and navigation\n */\n/**\n * Imperative navigation for useRouter. Delegates to the installed SPA router\n * so blockers run before the URL changes, history state is written by the\n * router, and the action is labelled push/replace rather than pop. Without a\n * Farm router (embedded usage) the URL is written directly and announced on\n * the shared history channel, whose no-router fallback is the nuqs-style\n * synthetic popstate this code previously hand-rolled.\n */\nfunction navigateViaRouter(href: string, basePath: string, replace: boolean): void {\n  if (typeof window === \"undefined\") return;\n\n  const url = applyFarmBasePath(href, basePath);\n  const spaRouter = getInstalledFarmSPARouter();\n  if (spaRouter) {\n    void spaRouter.navigate(url, { replace });\n    return;\n  }\n\n  if (replace) {\n    window.history.replaceState(null, \"\", url);\n  } else {\n    window.history.pushState(null, \"\", url);\n  }\n  notifyHistoryChange(\"url-search\");\n}\n\nexport function useRouter(options: UseRouterOptions = {}) {\n  const basePath =\n    options.basePath === undefined ? getFarmBasePath() : normalizeFarmBasePath(options.basePath);\n  const routes = options.routes;\n  const routeKey =\n    routes?.map((route) => (typeof route === \"string\" ? route : route.path)).join(\"\\n\") || \"\";\n  const routeMatcher = useMemo(\n    () => (routeKey ? createFarmRouter(routeKey.split(\"\\n\")) : null),\n    [routeKey],\n  );\n  const [state, setState] = useState<RouterState>(() => {\n    return readRouterState(basePath, routeMatcher);\n  });\n\n  useEffect(() => {\n    if (typeof window === \"undefined\") return;\n\n    const handlePopState = () => {\n      setState(readRouterState(basePath, routeMatcher));\n    };\n\n    handlePopState();\n    const unsubscribe = subscribeHistoryChange(handlePopState);\n    return unsubscribe;\n  }, [basePath, routeMatcher]);\n\n  const push = (href: string) => {\n    navigateViaRouter(href, basePath, false);\n  };\n\n  const replace = (href: string) => {\n    navigateViaRouter(href, basePath, true);\n  };\n\n  const pushState = <TState>(pageState: TState, href?: string) => {\n    if (typeof window === \"undefined\") return;\n    getSPARouter().pushState(pageState, resolveClientHref(href, basePath));\n  };\n\n  const replaceState = <TState>(pageState: TState, href?: string) => {\n    if (typeof window === \"undefined\") return;\n    getSPARouter().replaceState(pageState, resolveClientHref(href, basePath));\n  };\n\n  const back = () => {\n    if (typeof window !== \"undefined\") {\n      window.history.back();\n    }\n  };\n\n  const forward = () => {\n    if (typeof window !== \"undefined\") {\n      window.history.forward();\n    }\n  };\n\n  return {\n    ...state,\n    push,\n    replace,\n    pushState,\n    replaceState,\n    back,\n    forward,\n  };\n}\n\nexport function usePageState<TState = unknown>(): TState | null {\n  const [state, setState] = useState<TState | null>(() => readPageState<TState>());\n\n  useEffect(() => {\n    if (typeof window === \"undefined\") return;\n\n    const handlePopState = () => {\n      setState(readPageState<TState>());\n    };\n\n    handlePopState();\n    return subscribeHistoryChange(handlePopState);\n  }, []);\n\n  return state;\n}\n\nexport function useNavigation(): FarmNavigationState {\n  const [state, setState] = useState<FarmNavigationState>(() =>\n    getSPARouter().getNavigationState(),\n  );\n\n  useEffect(() => {\n    if (typeof window === \"undefined\") return;\n    return getSPARouter().subscribeNavigation(setState);\n  }, []);\n\n  return state;\n}\n\nexport function useBlocker(options: UseBlockerOptions): UseBlockerReturn {\n  const optionsRef = useRef(options);\n  optionsRef.current = options;\n  const active = Boolean(options.when);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !active) {\n      return;\n    }\n\n    return getSPARouter().addBlocker(\n      async (context) => {\n        const current = optionsRef.current;\n        const when = typeof current.when === \"function\" ? current.when(context) : current.when;\n\n        if (!when) return false;\n\n        if (current.shouldBlock && !(await current.shouldBlock(context))) {\n          return false;\n        }\n\n        if (current.message && typeof window.confirm === \"function\") {\n          return !window.confirm(current.message);\n        }\n\n        return true;\n      },\n      () => shouldBlockUnload(optionsRef.current),\n    );\n  }, [active]);\n\n  return { active };\n}\n\nexport function useScrollRestoration<TElement extends HTMLElement = HTMLElement>(\n  key: string,\n): RefObject<TElement | null> {\n  const ref = useRef<TElement>(null);\n\n  useEffect(() => {\n    const element = ref.current;\n    if (!element) return;\n    return getSPARouter().registerScrollElement(key, element);\n  }, [key]);\n\n  return ref;\n}\n\nfunction readRouterState(basePath: string, routeMatcher: FarmRouter | null): RouterState {\n  const url = readCurrentUrl();\n  if (!url) {\n    return {\n      pathname: \"/\",\n      searchParams: new URLSearchParams(),\n      params: {},\n      pageState: null,\n    };\n  }\n\n  const pathname = normalizeClientPathname(url.pathname, basePath);\n  const i18n = getFarmI18nClientState();\n  const routePathname = i18n ? stripFarmLocaleFromPathname(pathname, i18n) : pathname;\n  return {\n    pathname,\n    searchParams: url.searchParams,\n    params: routeMatcher?.match(routePathname)?.params || {},\n    pageState: typeof window === \"undefined\" ? null : readPageState(),\n  };\n}\n\n/**\n * The URL being rendered, on either side of hydration.\n *\n * On the server this came back as `/` with no search params, so a component\n * reading the path or the query string rendered one thing on the server and\n * another in the browser, which React reports as a hydration mismatch and\n * leaves the route without useful server rendered markup.\n */\nfunction readCurrentUrl(): URL | undefined {\n  if (typeof window !== \"undefined\") {\n    try {\n      return new URL(window.location.href);\n    } catch {\n      return undefined;\n    }\n  }\n\n  const request = _resolveCurrentRequest();\n  if (!request) return undefined;\n  try {\n    return new URL(request.url);\n  } catch {\n    return undefined;\n  }\n}\n\nfunction normalizeClientPathname(pathname: string, basePath: string) {\n  return stripFarmBasePath(pathname, basePath);\n}\n\nfunction resolveClientHref(href: string | undefined, basePath: string): string | undefined {\n  if (!href) return undefined;\n  return applyFarmBasePath(href, basePath);\n}\n","export const FARM_DEFERRED_CONTENT_TYPE = \"application/x-farm-deferred+json\";\nexport const FARM_DEFERRED_ERROR_CODE = \"FARM_DEFERRED_DATA_ERROR\";\nexport const FARM_DEFERRED_BRAND: unique symbol = Symbol.for(\n  \"farm.deferred\",\n) as typeof FARM_DEFERRED_BRAND;\n\nconst FARM_DEFERRED_MARKER = \"$farmDeferred\";\n\ntype DeferredState<T = unknown> =\n  | { status: \"pending\" }\n  | { status: \"fulfilled\"; value: T }\n  | { status: \"rejected\"; reason: unknown };\n\nexport interface Deferred<T> extends Promise<T> {\n  readonly [FARM_DEFERRED_BRAND]: true;\n}\n\nexport interface PreparedDeferredData {\n  data: unknown;\n  records: readonly DeferredRecord[];\n}\n\nexport interface DeferredRecord {\n  id: string;\n  promise: Deferred<unknown>;\n}\n\nexport type DeferredSettlement =\n  | { status: \"fulfilled\"; value: unknown }\n  | { status: \"rejected\"; error: { code: typeof FARM_DEFERRED_ERROR_CODE; message: string } };\n\nexport type DeferredSettlements = Record<string, DeferredSettlement>;\n\nexport interface DeferredDataResponseOptions {\n  onError?: (error: unknown, id: string) => void;\n}\n\nexport class DeferredDataError extends Error {\n  readonly name = \"DeferredDataError\";\n  readonly code = FARM_DEFERRED_ERROR_CODE;\n\n  constructor(message = \"Deferred route data failed to load\") {\n    super(message);\n  }\n}\n\nconst deferredStates = new WeakMap<object, DeferredState>();\n\nexport function defer<T>(value: PromiseLike<T>): Deferred<Awaited<T>> {\n  if (isDeferred(value)) {\n    return value as Deferred<Awaited<T>>;\n  }\n\n  const promise = Promise.resolve(value) as Deferred<Awaited<T>>;\n  Object.defineProperty(promise, FARM_DEFERRED_BRAND, {\n    configurable: false,\n    enumerable: false,\n    value: true,\n    writable: false,\n  });\n  deferredStates.set(promise, { status: \"pending\" });\n  promise.then(\n    (resolved) => deferredStates.set(promise, { status: \"fulfilled\", value: resolved }),\n    (reason) => deferredStates.set(promise, { status: \"rejected\", reason }),\n  );\n  return promise;\n}\n\nexport function isDeferred<T = unknown>(value: unknown): value is Deferred<T> {\n  return Boolean(\n    value &&\n    (typeof value === \"object\" || typeof value === \"function\") &&\n    (value as Record<PropertyKey, unknown>)[FARM_DEFERRED_BRAND] === true,\n  );\n}\n\nexport function prepareDeferredData(value: unknown): PreparedDeferredData {\n  const context = createEncodingContext();\n  return {\n    data: encodeDeferredValue(value, context, new WeakSet()),\n    records: context.records,\n  };\n}\n\nexport function snapshotDeferredData(records: readonly DeferredRecord[]): DeferredSettlements {\n  const context = createEncodingContext(records);\n  const settlements: DeferredSettlements = {};\n\n  for (let index = 0; index < context.records.length; index++) {\n    const record = context.records[index]!;\n    const state = readDeferredState(record.promise);\n\n    if (state.status === \"fulfilled\") {\n      try {\n        settlements[record.id] = {\n          status: \"fulfilled\",\n          value: encodeDeferredValue(state.value, context, new WeakSet()),\n        };\n      } catch {\n        settlements[record.id] = createRejectedSettlement();\n      }\n    } else {\n      settlements[record.id] = createRejectedSettlement();\n    }\n  }\n\n  return settlements;\n}\n\nexport function reviveDeferredData<T>(value: T, settlements: DeferredSettlements): T {\n  return reviveDeferredValue(value, new Map(), settlements) as T;\n}\n\nexport function createDeferredDataResponse(\n  value: unknown,\n  init: ResponseInit = {},\n  options: DeferredDataResponseOptions = {},\n): Response {\n  const context = createEncodingContext();\n  const data = encodeDeferredValue(value, context, new WeakSet());\n  const headers = new Headers(init.headers);\n\n  if (context.records.length === 0) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n    return new Response(JSON.stringify(data), { ...init, headers });\n  }\n\n  headers.set(\"Content-Type\", `${FARM_DEFERRED_CONTENT_TYPE}; charset=utf-8`);\n  headers.set(\"Cache-Control\", headers.get(\"Cache-Control\") || \"private, max-age=0\");\n  const initialLine = encodeDeferredMessage({ type: \"data\", data });\n  const encoder = new TextEncoder();\n  let cancelled = false;\n\n  const stream = new ReadableStream<Uint8Array>({\n    start(controller) {\n      controller.enqueue(encoder.encode(initialLine));\n      let pending = context.records.length;\n\n      const finishRecord = () => {\n        pending--;\n        if (!cancelled && pending === 0) controller.close();\n      };\n\n      const schedule = (record: DeferredRecord) => {\n        record.promise\n          .then(\n            (resolved) => {\n              if (cancelled) return;\n              try {\n                const previousLength = context.records.length;\n                const encoded = encodeDeferredValue(resolved, context, new WeakSet());\n                const nestedRecords = context.records.slice(previousLength);\n                pending += nestedRecords.length;\n                controller.enqueue(\n                  encoder.encode(\n                    encodeDeferredMessage({ type: \"resolve\", id: record.id, data: encoded }),\n                  ),\n                );\n                for (const nestedRecord of nestedRecords) schedule(nestedRecord);\n              } catch (error) {\n                reportDeferredError(options, error, record.id);\n                controller.enqueue(\n                  encoder.encode(\n                    encodeDeferredMessage({\n                      type: \"reject\",\n                      id: record.id,\n                      error: createDeferredPublicError(),\n                    }),\n                  ),\n                );\n              }\n            },\n            (error) => {\n              if (cancelled) return;\n              reportDeferredError(options, error, record.id);\n              controller.enqueue(\n                encoder.encode(\n                  encodeDeferredMessage({\n                    type: \"reject\",\n                    id: record.id,\n                    error: createDeferredPublicError(),\n                  }),\n                ),\n              );\n            },\n          )\n          .finally(finishRecord);\n      };\n\n      const initialRecords = context.records.slice();\n      for (const record of initialRecords) schedule(record);\n    },\n    cancel() {\n      cancelled = true;\n    },\n  });\n\n  return new Response(stream, { ...init, headers });\n}\n\nexport async function readDeferredDataResponse<T>(response: Response): Promise<T> {\n  const contentType = response.headers.get(\"Content-Type\") || \"\";\n  if (!contentType.toLowerCase().startsWith(FARM_DEFERRED_CONTENT_TYPE)) {\n    return (await response.json()) as T;\n  }\n  if (!response.body) {\n    throw new DeferredDataError(\"Deferred route data response has no body\");\n  }\n\n  const reader = response.body.getReader();\n  const decoder = new TextDecoder();\n  const controllers = new Map<string, ControlledDeferred>();\n  let buffer = \"\";\n  let complete = false;\n\n  const readLine = async (): Promise<string | undefined> => {\n    while (true) {\n      const newline = buffer.indexOf(\"\\n\");\n      if (newline >= 0) {\n        const line = buffer.slice(0, newline);\n        buffer = buffer.slice(newline + 1);\n        return line;\n      }\n      if (complete) {\n        if (!buffer) return undefined;\n        const line = buffer;\n        buffer = \"\";\n        return line;\n      }\n\n      const chunk = await reader.read();\n      complete = chunk.done;\n      if (chunk.value) buffer += decoder.decode(chunk.value, { stream: !chunk.done });\n      if (chunk.done) buffer += decoder.decode();\n    }\n  };\n\n  const firstLine = await readLine();\n  if (!firstLine) {\n    reader.releaseLock();\n    throw new DeferredDataError(\"Deferred route data response is empty\");\n  }\n\n  const initial = parseDeferredMessage(firstLine);\n  if (initial.type !== \"data\") {\n    reader.releaseLock();\n    throw new DeferredDataError(\"Deferred route data response is invalid\");\n  }\n  const data = reviveDeferredValue(initial.data, controllers) as T;\n\n  void (async () => {\n    try {\n      for (let line = await readLine(); line !== undefined; line = await readLine()) {\n        if (!line) continue;\n        const message = parseDeferredMessage(line);\n        if (message.type === \"resolve\") {\n          const controller = getControlledDeferred(message.id, controllers);\n          controller.resolve(reviveDeferredValue(message.data, controllers));\n        } else if (message.type === \"reject\") {\n          getControlledDeferred(message.id, controllers).reject(\n            new DeferredDataError(message.error?.message),\n          );\n        }\n      }\n      rejectPendingDeferred(controllers, \"Deferred route data stream ended before completion\");\n    } catch {\n      rejectPendingDeferred(controllers, \"Deferred route data stream could not be read\");\n    } finally {\n      reader.releaseLock();\n    }\n  })();\n\n  return data;\n}\n\ninterface EncodingContext {\n  records: DeferredRecord[];\n  ids: Map<Deferred<unknown>, string>;\n  nextId: number;\n}\n\ninterface ControlledDeferred {\n  promise: Promise<unknown> & {\n    status?: \"pending\" | \"fulfilled\" | \"rejected\";\n    value?: unknown;\n    reason?: unknown;\n  };\n  resolve(value: unknown): void;\n  reject(error: unknown): void;\n}\n\nfunction createEncodingContext(records: readonly DeferredRecord[] = []): EncodingContext {\n  return {\n    records: [...records],\n    ids: new Map(records.map((record) => [record.promise, record.id])),\n    nextId: records.reduce((highest, record) => {\n      const value = Number(record.id.replace(/^d/, \"\"));\n      return Number.isFinite(value) ? Math.max(highest, value + 1) : highest;\n    }, records.length),\n  };\n}\n\nfunction encodeDeferredValue(\n  value: unknown,\n  context: EncodingContext,\n  ancestors: WeakSet<object>,\n): unknown {\n  if (isDeferred(value)) {\n    let id = context.ids.get(value);\n    if (!id) {\n      id = `d${context.nextId++}`;\n      context.ids.set(value, id);\n      context.records.push({ id, promise: value as Deferred<unknown> });\n    }\n    return { [FARM_DEFERRED_MARKER]: id };\n  }\n  if (!value || typeof value !== \"object\") return value;\n  if (Array.isArray(value)) {\n    assertNotCircular(value, ancestors);\n    const output = value.map((item) => encodeDeferredValue(item, context, ancestors));\n    ancestors.delete(value);\n    return output;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) return value;\n\n  assertNotCircular(value, ancestors);\n  const output: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    defineDataProperty(output, key, encodeDeferredValue(item, context, ancestors));\n  }\n  ancestors.delete(value);\n  // User data that happens to have the marker shape must not be revived as a\n  // deferred reference. Real ids never start with \"!\", so prefix-escape the\n  // value; revive strips one \"!\" back off.\n  if (isDeferredMarker(output)) {\n    return { [FARM_DEFERRED_MARKER]: `!${output[FARM_DEFERRED_MARKER]}` };\n  }\n  return output;\n}\n\nfunction reviveDeferredValue(\n  value: unknown,\n  controllers: Map<string, ControlledDeferred>,\n  settlements?: DeferredSettlements,\n  applyingSettlements = new Set<string>(),\n): unknown {\n  if (isDeferredMarker(value)) {\n    const id = value[FARM_DEFERRED_MARKER];\n    // Escaped user data, not a deferred reference — restore the original.\n    if (id.startsWith(\"!\")) {\n      return { [FARM_DEFERRED_MARKER]: id.slice(1) };\n    }\n    const controller = getControlledDeferred(id, controllers);\n    const settlement = settlements?.[id];\n    if (settlement && controller.promise.status === \"pending\") {\n      if (applyingSettlements.has(id)) return controller.promise;\n      applyingSettlements.add(id);\n      if (settlement.status === \"fulfilled\") {\n        controller.resolve(\n          reviveDeferredValue(settlement.value, controllers, settlements, applyingSettlements),\n        );\n      } else {\n        controller.reject(new DeferredDataError(settlement.error.message));\n      }\n      applyingSettlements.delete(id);\n    } else if (settlements && controller.promise.status === \"pending\") {\n      controller.reject(new DeferredDataError(\"Deferred route data was not resolved\"));\n    }\n    return controller.promise;\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) =>\n      reviveDeferredValue(item, controllers, settlements, applyingSettlements),\n    );\n  }\n  if (!value || typeof value !== \"object\") return value;\n\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) return value;\n  const output: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    defineDataProperty(\n      output,\n      key,\n      reviveDeferredValue(item, controllers, settlements, applyingSettlements),\n    );\n  }\n  return output;\n}\n\n// Assign an own key preserving its data. A plain `output[key] = value` runs the\n// `Object.prototype.__proto__` setter when `key` is the string \"__proto__\" (the\n// shape JSON.parse of external input produces), which silently drops the entry\n// and mutates the object's prototype instead of storing the value. Defining the\n// property sidesteps the accessor for that one key; other keys keep the fast path.\nfunction defineDataProperty(output: Record<string, unknown>, key: string, value: unknown): void {\n  if (key === \"__proto__\") {\n    Object.defineProperty(output, key, {\n      value,\n      enumerable: true,\n      writable: true,\n      configurable: true,\n    });\n  } else {\n    output[key] = value;\n  }\n}\n\nfunction getControlledDeferred(\n  id: string,\n  controllers: Map<string, ControlledDeferred>,\n): ControlledDeferred {\n  const existing = controllers.get(id);\n  if (existing) return existing;\n\n  let nativeResolve!: (value: unknown) => void;\n  let nativeReject!: (error: unknown) => void;\n  const promise = new Promise<unknown>((resolve, reject) => {\n    nativeResolve = resolve;\n    nativeReject = reject;\n  }) as ControlledDeferred[\"promise\"];\n  promise.status = \"pending\";\n  promise.catch(() => undefined);\n\n  const controlled: ControlledDeferred = {\n    promise,\n    resolve(value) {\n      if (promise.status !== \"pending\") return;\n      promise.status = \"fulfilled\";\n      promise.value = value;\n      nativeResolve(value);\n    },\n    reject(error) {\n      if (promise.status !== \"pending\") return;\n      promise.status = \"rejected\";\n      promise.reason = error;\n      nativeReject(error);\n    },\n  };\n  controllers.set(id, controlled);\n  return controlled;\n}\n\nfunction readDeferredState(promise: Deferred<unknown>): DeferredState {\n  const tracked = deferredStates.get(promise);\n  if (tracked && tracked.status !== \"pending\") return tracked;\n\n  const reactState = promise as Deferred<unknown> & {\n    status?: string;\n    value?: unknown;\n    reason?: unknown;\n  };\n  if (reactState.status === \"fulfilled\") {\n    return { status: \"fulfilled\", value: reactState.value };\n  }\n  if (reactState.status === \"rejected\") {\n    return { status: \"rejected\", reason: reactState.reason };\n  }\n  return tracked || { status: \"pending\" };\n}\n\nfunction isDeferredMarker(value: unknown): value is { [FARM_DEFERRED_MARKER]: string } {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    Object.keys(value).length === 1 &&\n    typeof (value as Record<string, unknown>)[FARM_DEFERRED_MARKER] === \"string\",\n  );\n}\n\nfunction assertNotCircular(value: object, ancestors: WeakSet<object>): void {\n  if (ancestors.has(value)) {\n    throw new TypeError(\"Deferred route data must be JSON-serializable and cannot be circular\");\n  }\n  ancestors.add(value);\n}\n\nfunction createDeferredPublicError() {\n  return {\n    code: FARM_DEFERRED_ERROR_CODE,\n    message: \"Deferred route data failed to load\",\n  } as const;\n}\n\nfunction createRejectedSettlement(): DeferredSettlement {\n  return { status: \"rejected\", error: createDeferredPublicError() };\n}\n\nfunction reportDeferredError(\n  options: DeferredDataResponseOptions,\n  error: unknown,\n  id: string,\n): void {\n  try {\n    options.onError?.(error, id);\n  } catch {\n    // Error reporting must not break the response stream.\n  }\n}\n\nfunction encodeDeferredMessage(message: Record<string, unknown>): string {\n  return `${JSON.stringify(message)}\\n`;\n}\n\nfunction parseDeferredMessage(line: string): any {\n  try {\n    return JSON.parse(line);\n  } catch {\n    throw new DeferredDataError(\"Deferred route data response contains invalid JSON\");\n  }\n}\n\nfunction rejectPendingDeferred(\n  controllers: Map<string, ControlledDeferred>,\n  message: string,\n): void {\n  for (const controller of controllers.values()) {\n    if (controller.promise.status === \"pending\") {\n      controller.reject(new DeferredDataError(message));\n    }\n  }\n}\n","import { getInstalledFarmSPARouter, type SPARouter } from \"./spa-router\";\n\n/** Fired after programmatic history writes that must not start a navigation. */\nexport const FARM_HISTORY_CHANGE_EVENT = \"farm:historychange\";\n\nexport type FarmHistoryChangeKind = \"url-search\" | \"page-state\";\n\nexport interface FarmHistoryChangeDetail {\n  kind: FarmHistoryChangeKind;\n}\n\n/** Write shallow URL history through the installed SPA router when available. */\nexport function writeFarmURLSearchHistory(action: \"push\" | \"replace\", href: string): boolean {\n  const router = getInstalledFarmSPARouter();\n  if (!router) return false;\n  const writeURLSearch = (router as { writeURLSearch?: SPARouter[\"writeURLSearch\"] })\n    .writeURLSearch;\n  if (typeof writeURLSearch !== \"function\") return false;\n  if (window.history.state !== null && typeof window.history.state !== \"object\") return false;\n  writeURLSearch.call(router, action, href);\n  return true;\n}\n\nfunction dispatchHistoryChange(kind: FarmHistoryChangeKind): void {\n  window.dispatchEvent(\n    new CustomEvent<FarmHistoryChangeDetail>(FARM_HISTORY_CHANGE_EVENT, {\n      detail: { kind },\n    }),\n  );\n}\n\n/**\n * Notify history observers after pushState/replaceState.\n *\n * Farm's SPA router treats `popstate` as real back/forward navigation, so a\n * dedicated event is used instead. `url-search` keeps the nuqs-style synthetic\n * `popstate` when no Farm router is installed, so standalone `useQueryState`\n * consumers still resync; `page-state` is Farm-internal and never falls back.\n */\nexport function notifyHistoryChange(kind: FarmHistoryChangeKind): void {\n  if (typeof window === \"undefined\") return;\n\n  setTimeout(() => {\n    if (kind === \"url-search\" && !getInstalledFarmSPARouter()) {\n      window.dispatchEvent(new PopStateEvent(\"popstate\"));\n      return;\n    }\n\n    dispatchHistoryChange(kind);\n  }, 0);\n}\n\n/** Notify observers after a Farm router commit without simulating traversal. */\nexport function notifyRouterHistoryChange(): void {\n  if (typeof window === \"undefined\") return;\n  setTimeout(() => dispatchHistoryChange(\"url-search\"), 0);\n}\n\nexport function subscribeHistoryChange(listener: () => void): () => void {\n  if (typeof window === \"undefined\") return () => {};\n\n  window.addEventListener(\"popstate\", listener);\n  window.addEventListener(FARM_HISTORY_CHANGE_EVENT, listener);\n\n  return () => {\n    window.removeEventListener(\"popstate\", listener);\n    window.removeEventListener(FARM_HISTORY_CHANGE_EVENT, listener);\n  };\n}\n","export const FARM_DEPLOYMENT_ID_HEADER = \"x-farm-deployment-id\";\nexport const FARM_DEPLOYMENT_MISMATCH_HEADER = \"x-farm-deployment-mismatch\";\nexport const FARM_DEPLOYMENT_COOKIE = \"__farm_deployment\";\nexport const FARM_DEPLOYMENT_MISMATCH_CODE = \"FARM_DEPLOYMENT_MISMATCH\";\nexport const FARM_DEPLOYMENT_MISMATCH_STATUS = 409;\n\nexport type FarmPresetRuntime = \"node\" | \"edge\" | \"unknown\";\n\nexport function getFarmPresetRuntime(preset: string): FarmPresetRuntime {\n  if (\n    preset === \"cloudflare\" ||\n    preset === \"cloudflare-pages\" ||\n    preset === \"cloudflare-module\" ||\n    preset === \"netlify-edge\" ||\n    preset === \"vercel-edge\" ||\n    preset === \"deno\"\n  ) {\n    return \"edge\";\n  }\n\n  if (\n    preset === \"node-server\" ||\n    preset === \"vercel\" ||\n    preset === \"netlify\" ||\n    preset === \"aws-lambda\" ||\n    preset === \"azure\" ||\n    preset === \"firebase\" ||\n    preset === \"bun\" ||\n    preset === \"self-host\" ||\n    preset === \"farm\"\n  ) {\n    return \"node\";\n  }\n\n  return \"unknown\";\n}\n\nexport interface FarmDeploymentMismatch {\n  clientDeploymentId: string;\n  serverDeploymentId: string;\n}\n\nexport interface FarmDeploymentResponseOptions {\n  setCookie?: boolean;\n  cookiePath?: string;\n  secureCookie?: boolean;\n}\n\nexport class FarmDeploymentMismatchError extends Error {\n  readonly name = \"FarmDeploymentMismatchError\";\n  readonly code = FARM_DEPLOYMENT_MISMATCH_CODE;\n  readonly retryable = false;\n\n  constructor(\n    readonly clientDeploymentId: string,\n    readonly serverDeploymentId: string,\n  ) {\n    super(\"The application was updated while this page was open. Refresh before trying again.\");\n  }\n}\n\nexport function normalizeFarmDeploymentId(value: unknown): string {\n  if (typeof value !== \"string\" || value.trim() === \"\") {\n    throw new TypeError(\"Farm deploymentId must be a non-empty string\");\n  }\n\n  const normalized = value.trim();\n  if (normalized.length > 200 || /[\\u0000-\\u001f\\u007f]/.test(normalized)) {\n    throw new TypeError(\"Farm deploymentId must be at most 200 characters without control bytes\");\n  }\n\n  return normalized;\n}\n\nexport function createFarmDeploymentRequestHeaders(\n  deploymentId: string | undefined,\n  init?: HeadersInit,\n): Headers {\n  const headers = new Headers(init);\n  if (deploymentId) {\n    headers.set(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n  }\n  return headers;\n}\n\nexport function getFarmRequestDeploymentId(\n  request: Pick<Request, \"headers\" | \"method\">,\n): string | undefined {\n  const headerValue = request.headers.get(FARM_DEPLOYMENT_ID_HEADER)?.trim();\n  if (headerValue) return headerValue;\n\n  if (isSafeRequestMethod(request.method)) return undefined;\n  return readCookie(request.headers.get(\"cookie\"), FARM_DEPLOYMENT_COOKIE);\n}\n\nexport function getFarmDeploymentMismatch(\n  request: Pick<Request, \"headers\" | \"method\">,\n  serverDeploymentId: string | undefined,\n): FarmDeploymentMismatch | null {\n  if (!serverDeploymentId) return null;\n\n  const clientDeploymentId = getFarmRequestDeploymentId(request);\n  if (!clientDeploymentId || clientDeploymentId === serverDeploymentId) return null;\n\n  return { clientDeploymentId, serverDeploymentId };\n}\n\nexport function createFarmDeploymentMismatchResponse(mismatch: FarmDeploymentMismatch): Response {\n  return new Response(\n    JSON.stringify({\n      error: FARM_DEPLOYMENT_MISMATCH_CODE,\n      message: \"The application deployment changed. Refresh before retrying this request.\",\n    }),\n    {\n      status: FARM_DEPLOYMENT_MISMATCH_STATUS,\n      headers: {\n        \"Cache-Control\": \"no-store\",\n        \"Content-Type\": \"application/json; charset=utf-8\",\n        [FARM_DEPLOYMENT_ID_HEADER]: mismatch.serverDeploymentId,\n        [FARM_DEPLOYMENT_MISMATCH_HEADER]: \"1\",\n      },\n    },\n  );\n}\n\nexport function withFarmDeploymentResponse(\n  response: Response,\n  deploymentId: string | undefined,\n  options: FarmDeploymentResponseOptions = {},\n): Response {\n  if (!deploymentId) return response;\n\n  const headers = new Headers(response.headers);\n  headers.set(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n  if (options.setCookie) {\n    headers.append(\n      \"Set-Cookie\",\n      createFarmDeploymentCookie(\n        deploymentId,\n        options.cookiePath ?? \"/\",\n        options.secureCookie ?? false,\n      ),\n    );\n  }\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function getFarmResponseDeploymentId(\n  response: Pick<Response, \"headers\">,\n): string | undefined {\n  return response.headers.get(FARM_DEPLOYMENT_ID_HEADER)?.trim() || undefined;\n}\n\nexport function isFarmDeploymentMismatchResponse(\n  response: Pick<Response, \"headers\" | \"status\">,\n  clientDeploymentId: string | undefined,\n): boolean {\n  const serverDeploymentId = getFarmResponseDeploymentId(response);\n  if (clientDeploymentId && serverDeploymentId && clientDeploymentId !== serverDeploymentId) {\n    return true;\n  }\n\n  return (\n    response.status === FARM_DEPLOYMENT_MISMATCH_STATUS &&\n    response.headers.get(FARM_DEPLOYMENT_MISMATCH_HEADER) === \"1\"\n  );\n}\n\nexport function createFarmDeploymentMismatchError(\n  response: Pick<Response, \"headers\">,\n  clientDeploymentId: string,\n): FarmDeploymentMismatchError {\n  return new FarmDeploymentMismatchError(\n    clientDeploymentId,\n    getFarmResponseDeploymentId(response) || \"unknown\",\n  );\n}\n\nexport function createFarmDeploymentCookie(\n  deploymentId: string,\n  path = \"/\",\n  secure = false,\n): string {\n  const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n  return [\n    `${FARM_DEPLOYMENT_COOKIE}=${encodeURIComponent(deploymentId)}`,\n    `Path=${normalizedPath}`,\n    \"HttpOnly\",\n    \"SameSite=Lax\",\n    secure ? \"Secure\" : \"\",\n  ]\n    .filter(Boolean)\n    .join(\"; \");\n}\n\nfunction readCookie(cookieHeader: string | null, name: string): string | undefined {\n  if (!cookieHeader) return undefined;\n\n  for (const part of cookieHeader.split(\";\")) {\n    const separator = part.indexOf(\"=\");\n    if (separator === -1 || part.slice(0, separator).trim() !== name) continue;\n\n    const value = part.slice(separator + 1).trim();\n    try {\n      return decodeURIComponent(value);\n    } catch {\n      return value;\n    }\n  }\n\n  return undefined;\n}\n\nfunction isSafeRequestMethod(method: string): boolean {\n  return [\"GET\", \"HEAD\", \"OPTIONS\", \"QUERY\"].includes(method.toUpperCase());\n}\n","export function getHashTargetElement(hash: string): Element | null {\n  // A fragment is not a CSS selector. Match by decoded id, raw id, then the\n  // legacy anchor name so SPA navigation follows native browser semantics.\n  const fragment = hash.startsWith(\"#\") ? hash.slice(1) : hash;\n  if (!fragment) return null;\n\n  let decoded = fragment;\n  try {\n    decoded = decodeURIComponent(fragment);\n  } catch {\n    // Keep the raw fragment when its percent-encoding is malformed.\n  }\n\n  return (\n    document.getElementById(decoded) ||\n    document.getElementById(fragment) ||\n    document.getElementsByName(decoded)[0] ||\n    null\n  );\n}\n","/**\n * Agent-readiness configuration: opt-in primitives that make a Farm site easier\n * for AI agents and crawlers to discover, resolve, and use. Off by default so\n * sites that do not want agent exposure (internal tools, private dashboards) are\n * unaffected.\n */\n\n/** schema.org JSON-LD emitted in the document head to identify the site. */\nexport interface FarmAgentJsonLd {\n  /**\n   * schema.org `@type`. Common values: `\"Organization\"` for a company or\n   * project, `\"SoftwareApplication\"` for a product, `\"WebSite\"`, `\"Person\"`.\n   *\n   * @default \"Organization\"\n   */\n  type?: string;\n  /** Entity name. Defaults to the site's Open Graph site name or page title. */\n  name?: string;\n  /** Canonical URL for the entity. Defaults to the configured `metadataBase`. */\n  url?: string;\n  /** Short description. Defaults to the page/site metadata description. */\n  description?: string;\n  /** Logo URL. */\n  logo?: string;\n  /** URLs that also represent this entity (social profiles, repos) — schema.org `sameAs`. */\n  sameAs?: string[];\n  /** Additional schema.org properties merged into the emitted object. */\n  properties?: Record<string, unknown>;\n}\n\nexport interface FarmAgentUserConfig {\n  /**\n   * Emit schema.org JSON-LD in the document head so agents and crawlers can\n   * resolve the site's identity. `true` emits an `Organization` built from the\n   * site's metadata; an object customizes the type and fields.\n   *\n   * @default false\n   */\n  jsonLd?: boolean | FarmAgentJsonLd;\n}\n\nexport interface ResolvedFarmAgentConfig {\n  jsonLd: FarmAgentJsonLd | false;\n}\n\nexport function resolveFarmAgentConfig(\n  input: FarmAgentUserConfig | undefined,\n): ResolvedFarmAgentConfig {\n  const jsonLd = input?.jsonLd;\n  if (!jsonLd) return { jsonLd: false };\n  return { jsonLd: jsonLd === true ? {} : jsonLd };\n}\n\nexport interface FarmAgentJsonLdContext {\n  metadataBase?: string;\n  siteName?: string;\n  title?: string;\n  description?: string;\n}\n\nfunction pruneUndefined(object: Record<string, unknown>): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(object)) {\n    if (value !== undefined && value !== null && value !== \"\") result[key] = value;\n  }\n  return result;\n}\n\n/**\n * Serialize a JSON-LD object for inline `<script>` embedding, escaping `<` so a\n * value containing `</script>` cannot break out of the tag.\n */\nfunction serializeJsonLd(value: unknown): string {\n  return JSON.stringify(value).replace(/</g, \"\\\\u003c\");\n}\n\n/**\n * Build a JSON-LD `<script>` tag for the site identity, or an empty string when\n * there is not enough information to emit meaningful structured data.\n */\nexport function renderFarmAgentJsonLd(\n  config: FarmAgentJsonLd,\n  context: FarmAgentJsonLdContext,\n): string {\n  const base = pruneUndefined({\n    name: config.name ?? context.siteName ?? context.title,\n    url: config.url ?? context.metadataBase,\n    description: config.description ?? context.description,\n    logo: config.logo,\n    sameAs: config.sameAs && config.sameAs.length > 0 ? config.sameAs : undefined,\n  });\n\n  const object = {\n    \"@context\": \"https://schema.org\",\n    \"@type\": config.type || \"Organization\",\n    ...base,\n    ...(config.properties || {}),\n  };\n\n  // Nothing beyond @context/@type and no custom properties: not worth emitting.\n  if (Object.keys(object).length <= 2 && !config.properties) {\n    return \"\";\n  }\n\n  return `<script type=\"application/ld+json\">${serializeJsonLd(object)}</script>`;\n}\n","import type { Metadata } from \"./types\";\nimport { renderFarmAgentJsonLd, type FarmAgentJsonLd } from \"./agent-config\";\n\nexport type MetadataImageKind = \"opengraph\" | \"twitter\";\n\nexport interface FarmMetadataImageReference {\n  kind: MetadataImageKind;\n  href: string;\n  alt?: string;\n  width?: number;\n  height?: number;\n  contentType?: string;\n}\n\nexport interface RenderedMetadataHead {\n  title: string;\n  tags: string;\n  hasFavicon: boolean;\n  /** False when the title is the framework fallback rather than configured. */\n  hasExplicitTitle: boolean;\n}\n\ntype MetadataRecord = Metadata & Record<string, any>;\n\nexport function mergeMetadata(\n  base: MetadataRecord | undefined,\n  next: MetadataRecord | undefined,\n): MetadataRecord {\n  if (!base) return next ? { ...next } : {};\n  if (!next) return { ...base };\n\n  return {\n    ...base,\n    ...next,\n    title: mergeMetadataTitle(base.title, next.title),\n    openGraph: mergeNestedMetadata(base.openGraph, next.openGraph),\n    twitter: mergeNestedMetadata(base.twitter, next.twitter),\n    alternates: mergeNestedMetadata((base as any).alternates, (next as any).alternates),\n    icons: mergeNestedMetadata((base as any).icons, (next as any).icons),\n  };\n}\n\nfunction mergeMetadataTitle(base: Metadata[\"title\"], next: Metadata[\"title\"]): Metadata[\"title\"] {\n  if (next === undefined) return base;\n\n  const parentTemplate = isRecord(base) ? normalizeContent(base.template) : undefined;\n  if (typeof next === \"string\") {\n    return parentTemplate ? applyTitleTemplate(parentTemplate, next) : next;\n  }\n\n  if (!isRecord(next)) return next;\n\n  const defaultTitle = normalizeContent(next.default) ?? resolveMetadataTitle(base);\n  return {\n    ...next,\n    default:\n      defaultTitle && parentTemplate\n        ? applyTitleTemplate(parentTemplate, defaultTitle)\n        : defaultTitle,\n  };\n}\n\nfunction applyTitleTemplate(template: string, title: string): string {\n  return template.split(\"%s\").join(title);\n}\n\nexport function addMetadataImageReference(\n  metadata: MetadataRecord,\n  reference: FarmMetadataImageReference,\n): MetadataRecord {\n  if (reference.kind === \"opengraph\") {\n    const openGraph = { ...metadata.openGraph };\n    if (!hasMetadataImages(openGraph.images) && !hasMetadataImages((openGraph as any).image)) {\n      openGraph.images = [\n        {\n          url: reference.href,\n          width: reference.width,\n          height: reference.height,\n          alt: reference.alt,\n          type: reference.contentType,\n        },\n      ];\n    }\n\n    return {\n      ...metadata,\n      openGraph,\n    };\n  }\n\n  const twitter = { ...metadata.twitter };\n  if (!hasMetadataImages(twitter.images)) {\n    twitter.images = [reference.href];\n    twitter.card = twitter.card || \"summary_large_image\";\n  }\n\n  return {\n    ...metadata,\n    twitter,\n  };\n}\n\nexport interface RenderMetadataHeadOptions {\n  /**\n   * Current request pathname. Used to emit a default `<link rel=\"canonical\">`\n   * when the route does not set one, so agents and crawlers can resolve the\n   * page's identity. Combined with `metadataBase` into an absolute URL when a\n   * base is configured; otherwise emitted as a self-referential path.\n   */\n  pathname?: string;\n  /**\n   * Agent JSON-LD config. When truthy, a schema.org JSON-LD script is emitted in\n   * the head, built from this config and the page/site metadata. `true` uses the\n   * defaults; `false`/omitted (the default) emits nothing.\n   */\n  jsonLd?: FarmAgentJsonLd | boolean;\n}\n\nexport function renderMetadataHead(\n  metadata: MetadataRecord | undefined,\n  options: RenderMetadataHeadOptions = {},\n): RenderedMetadataHead {\n  const resolvedMetadata = metadata || {};\n  const metadataBase = resolveMetadataBase(resolvedMetadata);\n  const explicitTitle = resolveMetadataTitle(resolvedMetadata.title);\n  const title = explicitTitle || \"Farm.js App\";\n  const tags: string[] = [];\n\n  appendMetaName(tags, \"description\", resolvedMetadata.description);\n  appendMetaName(tags, \"keywords\", normalizeKeywords(resolvedMetadata.keywords));\n  appendMetaName(tags, \"author\", (resolvedMetadata as any).author);\n\n  if (Array.isArray(resolvedMetadata.authors)) {\n    for (const author of resolvedMetadata.authors) {\n      appendMetaName(tags, \"author\", author?.name);\n      if (author?.url) {\n        appendLink(tags, \"author\", resolveMetadataUrl(author.url, metadataBase));\n      }\n    }\n  }\n\n  appendMetaName(tags, \"creator\", resolvedMetadata.creator);\n  appendMetaName(tags, \"publisher\", resolvedMetadata.publisher);\n  appendMetaName(tags, \"robots\", normalizeRobots(resolvedMetadata.robots));\n\n  const alternates = (resolvedMetadata as any).alternates;\n  const explicitCanonical = isRecord(alternates) ? alternates.canonical : undefined;\n  // Default the canonical link to the current path when the route does not set\n  // one. This is a self-referential canonical (absolute when `metadataBase` is\n  // configured), which is safe for every page and gives agents/crawlers a\n  // stable identity for the URL.\n  const canonicalHref =\n    explicitCanonical != null\n      ? resolveMetadataUrl(explicitCanonical, metadataBase)\n      : options.pathname\n        ? resolveMetadataUrl(sanitizeSelfCanonicalPathname(options.pathname), metadataBase)\n        : undefined;\n  if (canonicalHref) {\n    appendLink(tags, \"canonical\", canonicalHref);\n  }\n\n  if (isRecord(alternates) && isRecord(alternates.languages)) {\n    for (const [language, href] of Object.entries(alternates.languages)) {\n      appendLink(tags, \"alternate\", resolveMetadataUrl(href, metadataBase), {\n        hreflang: language,\n      });\n    }\n  }\n\n  const hasFavicon = appendIcons(tags, (resolvedMetadata as any).icons, metadataBase);\n\n  if ((resolvedMetadata as any).manifest) {\n    appendLink(\n      tags,\n      \"manifest\",\n      resolveMetadataUrl((resolvedMetadata as any).manifest, metadataBase),\n    );\n  }\n\n  appendOpenGraph(tags, resolvedMetadata.openGraph, metadataBase);\n  appendTwitter(tags, resolvedMetadata.twitter, metadataBase);\n\n  if (options.jsonLd) {\n    const jsonLdConfig = options.jsonLd === true ? {} : options.jsonLd;\n    const jsonLdScript = renderFarmAgentJsonLd(jsonLdConfig, {\n      metadataBase,\n      siteName: isRecord(resolvedMetadata.openGraph)\n        ? normalizeContent(resolvedMetadata.openGraph.siteName)\n        : undefined,\n      title: explicitTitle,\n      description: normalizeContent(resolvedMetadata.description),\n    });\n    if (jsonLdScript) tags.push(jsonLdScript);\n  }\n\n  return {\n    title: escapeText(title),\n    tags: tags.length > 0 ? `\\n  ${tags.join(\"\\n  \")}` : \"\",\n    hasFavicon,\n    hasExplicitTitle: Boolean(explicitTitle),\n  };\n}\n\nfunction mergeNestedMetadata(base: unknown, next: unknown): any {\n  if (isRecord(base) && isRecord(next)) {\n    return {\n      ...base,\n      ...next,\n    };\n  }\n\n  return next ?? base;\n}\n\nfunction appendOpenGraph(tags: string[], openGraph: Metadata[\"openGraph\"], metadataBase?: string) {\n  if (!isRecord(openGraph)) return;\n\n  appendMetaProperty(tags, \"og:title\", openGraph.title);\n  appendMetaProperty(tags, \"og:description\", openGraph.description);\n  appendMetaProperty(tags, \"og:url\", resolveMetadataUrl(openGraph.url, metadataBase));\n  appendMetaProperty(tags, \"og:site_name\", openGraph.siteName);\n  // Default og:type so a route that sets Open Graph data without a type still\n  // emits a valid entity type for agents and social crawlers.\n  appendMetaProperty(tags, \"og:type\", openGraph.type ?? \"website\");\n  appendMetaProperty(tags, \"og:locale\", (openGraph as any).locale);\n\n  const images = normalizeMetadataImages(\n    openGraph.images ?? (openGraph as any).image,\n    metadataBase,\n  );\n  for (const image of images) {\n    appendMetaProperty(tags, \"og:image\", image.url);\n    appendMetaProperty(tags, \"og:image:width\", image.width);\n    appendMetaProperty(tags, \"og:image:height\", image.height);\n    appendMetaProperty(tags, \"og:image:alt\", image.alt);\n    appendMetaProperty(tags, \"og:image:type\", image.type);\n  }\n}\n\nfunction appendTwitter(tags: string[], twitter: Metadata[\"twitter\"], metadataBase?: string) {\n  if (!isRecord(twitter)) return;\n\n  appendMetaName(tags, \"twitter:card\", twitter.card);\n  appendMetaName(tags, \"twitter:site\", twitter.site);\n  appendMetaName(tags, \"twitter:creator\", twitter.creator);\n  appendMetaName(tags, \"twitter:title\", twitter.title);\n  appendMetaName(tags, \"twitter:description\", twitter.description);\n\n  for (const image of normalizeMetadataImages(twitter.images, metadataBase)) {\n    appendMetaName(tags, \"twitter:image\", image.url);\n    appendMetaName(tags, \"twitter:image:alt\", image.alt);\n  }\n}\n\nfunction appendIcons(tags: string[], icons: unknown, metadataBase?: string): boolean {\n  if (!icons) return false;\n\n  if (typeof icons === \"string\") {\n    const initialTagCount = tags.length;\n    appendLink(tags, \"icon\", resolveMetadataUrl(icons, metadataBase));\n    return tags.length > initialTagCount;\n  }\n\n  if (!isRecord(icons)) return false;\n\n  const initialTagCount = tags.length;\n  appendIconList(tags, \"icon\", icons.icon, metadataBase);\n  appendIconList(tags, \"shortcut icon\", icons.shortcut, metadataBase);\n  const hasFavicon = tags.length > initialTagCount;\n  appendIconList(tags, \"apple-touch-icon\", icons.apple, metadataBase);\n  return hasFavicon;\n}\n\nfunction appendIconList(tags: string[], rel: string, value: unknown, metadataBase?: string) {\n  for (const icon of normalizeArray(value)) {\n    if (typeof icon === \"string\") {\n      appendLink(tags, rel, resolveMetadataUrl(icon, metadataBase));\n      continue;\n    }\n\n    if (!isRecord(icon)) continue;\n    appendLink(tags, rel, resolveMetadataUrl(icon.url, metadataBase), {\n      sizes: icon.sizes,\n      type: icon.type,\n    });\n  }\n}\n\nfunction appendMetaName(tags: string[], name: string, content: unknown) {\n  const normalized = normalizeContent(content);\n  if (!normalized) return;\n  tags.push(`<meta name=\"${escapeAttribute(name)}\" content=\"${escapeAttribute(normalized)}\">`);\n}\n\nfunction appendMetaProperty(tags: string[], property: string, content: unknown) {\n  const normalized = normalizeContent(content);\n  if (!normalized) return;\n  tags.push(\n    `<meta property=\"${escapeAttribute(property)}\" content=\"${escapeAttribute(normalized)}\">`,\n  );\n}\n\nfunction appendLink(\n  tags: string[],\n  rel: string,\n  href: unknown,\n  attrs: Record<string, unknown> = {},\n) {\n  const normalizedHref = normalizeContent(href);\n  if (!normalizedHref) return;\n\n  const attrText = Object.entries(attrs)\n    .map(([key, value]) => {\n      const normalized = normalizeContent(value);\n      return normalized ? ` ${key}=\"${escapeAttribute(normalized)}\"` : \"\";\n    })\n    .join(\"\");\n\n  tags.push(\n    `<link rel=\"${escapeAttribute(rel)}\" href=\"${escapeAttribute(normalizedHref)}\"${attrText}>`,\n  );\n}\n\nfunction normalizeMetadataImages(\n  value: unknown,\n  metadataBase?: string,\n): Array<{\n  url: string;\n  width?: number;\n  height?: number;\n  alt?: string;\n  type?: string;\n}> {\n  return normalizeArray(value)\n    .map((item) => {\n      if (typeof item === \"string\") {\n        return { url: resolveMetadataUrl(item, metadataBase) || item };\n      }\n\n      if (!isRecord(item)) return null;\n      const rawUrl = item.url || item.src;\n      const url = resolveMetadataUrl(rawUrl, metadataBase);\n      if (!url) return null;\n\n      return {\n        url,\n        width: normalizeNumber(item.width),\n        height: normalizeNumber(item.height),\n        alt: typeof item.alt === \"string\" ? item.alt : undefined,\n        type: typeof item.type === \"string\" ? item.type : undefined,\n      };\n    })\n    .filter((item): item is NonNullable<typeof item> => item !== null);\n}\n\nfunction normalizeArray(value: unknown): unknown[] {\n  if (value == null) return [];\n  return Array.isArray(value) ? value : [value];\n}\n\nfunction hasMetadataImages(value: unknown): boolean {\n  return normalizeMetadataImages(value).length > 0;\n}\n\n/**\n * Resolve a metadata title into displayable text. Exported so client-side\n * navigation resolves the object form the same way SSR does instead of\n * stringifying it into \"[object Object]\".\n */\nexport function resolveMetadataTitle(title: Metadata[\"title\"]): string | undefined {\n  if (typeof title === \"string\") return title;\n  if (isRecord(title)) {\n    return normalizeContent(title.default);\n  }\n  return undefined;\n}\n\nfunction normalizeKeywords(keywords: Metadata[\"keywords\"]): string | undefined {\n  if (Array.isArray(keywords)) return keywords.filter(Boolean).join(\", \");\n  return keywords;\n}\n\nfunction normalizeRobots(robots: Metadata[\"robots\"]): string | undefined {\n  if (typeof robots === \"string\") return robots;\n  if (!isRecord(robots)) return undefined;\n\n  const values: string[] = [];\n  if (typeof robots.index === \"boolean\") values.push(robots.index ? \"index\" : \"noindex\");\n  if (typeof robots.follow === \"boolean\") values.push(robots.follow ? \"follow\" : \"nofollow\");\n  return values.join(\", \") || undefined;\n}\n\nfunction resolveMetadataBase(metadata: MetadataRecord): string | undefined {\n  const base = metadata.metadataBase;\n  if (!base) return undefined;\n  return String(base);\n}\n\n/**\n * Keep the defaulted self-canonical on this origin. The pathname comes straight\n * from the request URL, and forms like `//evil.com` or `/\\evil.com` resolve to a\n * cross-origin URL through `new URL()` (and browsers treat `\\` as `/`), which\n * would advertise an attacker's domain as the page's canonical identity. Any\n * request path introducing an authority is collapsed to a single leading slash\n * so the canonical stays same-origin. Developer-supplied `alternates.canonical`\n * is trusted and does not pass through here.\n */\nfunction sanitizeSelfCanonicalPathname(pathname: string): string {\n  if (typeof pathname !== \"string\" || pathname.length === 0) return \"/\";\n  const collapsed = pathname.replace(/^[/\\\\]+/, \"/\");\n  return collapsed.startsWith(\"/\") ? collapsed : `/${collapsed}`;\n}\n\nfunction resolveMetadataUrl(value: unknown, metadataBase?: string): string | undefined {\n  const normalized = normalizeContent(value);\n  if (!normalized) return undefined;\n  if (!metadataBase) return normalized;\n\n  try {\n    return new URL(normalized, metadataBase).toString();\n  } catch {\n    return normalized;\n  }\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n  if (typeof value === \"number\" && Number.isFinite(value)) return value;\n  if (typeof value === \"string\") {\n    const parsed = Number(value);\n    return Number.isFinite(parsed) ? parsed : undefined;\n  }\n  return undefined;\n}\n\nfunction normalizeContent(value: unknown): string | undefined {\n  if (value == null) return undefined;\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n  if (value instanceof URL) return value.toString();\n  return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction escapeText(value: string): string {\n  return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction escapeAttribute(value: string): string {\n  return escapeText(value).replace(/\"/g, \"&quot;\");\n}\n","import { renderMetadataHead, resolveMetadataTitle } from \"../metadata\";\nimport type { Metadata } from \"../types\";\n\nexport type NavigationMetadata = (Metadata & Record<string, any>) | undefined;\n\n/** Marks head elements this reconciler inserted, so they can be replaced. */\nconst MANAGED_ATTRIBUTE = \"data-farm-metadata\";\n\n/**\n * Head tags the metadata system owns outright. These are swept on every\n * navigation whether or not they carry the managed marker, because the tags\n * rendered by the server for the first page have no marker and must not\n * survive into the next page's head.\n */\nconst OWNED_SELECTORS = [\n  'meta[name=\"description\"]',\n  'meta[name=\"keywords\"]',\n  'meta[name=\"author\"]',\n  'meta[name=\"creator\"]',\n  'meta[name=\"publisher\"]',\n  'meta[name=\"robots\"]',\n  'link[rel=\"author\"]',\n  'link[rel=\"canonical\"]',\n  'link[rel=\"alternate\"]',\n  'meta[property^=\"og:\"]',\n  'meta[name^=\"twitter:\"]',\n].join(\", \");\n\n/**\n * Icons and the web-app manifest have document-level defaults that exist\n * outside page metadata (the default favicon, a discovered manifest route), so\n * an absent value means \"keep what the document has\", not \"remove it\". They\n * are only swept when the next page defines its own.\n */\nconst ICON_SELECTORS = [\n  'link[rel=\"icon\"]',\n  'link[rel=\"shortcut icon\"]',\n  'link[rel=\"apple-touch-icon\"]',\n].join(\", \");\nconst MANIFEST_SELECTOR = 'link[rel=\"manifest\"]';\n\nfunction removeAll(selector: string): void {\n  for (const element of Array.from(document.head.querySelectorAll(selector))) {\n    element.remove();\n  }\n}\n\n/**\n * Make the document head for a client-side navigation match what a full-page\n * load of the target route renders: same title resolution and the same managed\n * tag set, produced by the same `renderMetadataHead` the server uses.\n *\n * JSON-LD is deliberately untouched: the agent JSON-LD script is site identity\n * rather than page metadata, and sweeping ld+json scripts could remove ones the\n * application authored itself.\n */\nexport function applyFarmMetadataToDocument(metadata: NavigationMetadata, pathname: string): void {\n  document.title = resolveMetadataTitle(metadata?.title) || \"Farm.js App\";\n\n  const rendered = renderMetadataHead(metadata, { pathname });\n  const template = document.createElement(\"template\");\n  template.innerHTML = rendered.tags;\n\n  removeAll(OWNED_SELECTORS);\n  if (metadata?.icons) removeAll(ICON_SELECTORS);\n  if (metadata?.manifest) removeAll(MANIFEST_SELECTOR);\n\n  for (const element of Array.from(template.content.children)) {\n    element.setAttribute(MANAGED_ATTRIBUTE, \"\");\n    document.head.appendChild(element);\n  }\n}\n","\"use client\";\n\nimport { readDeferredDataResponse } from \"../deferred\";\nimport { notifyHistoryChange, notifyRouterHistoryChange } from \"./history-sync\";\nimport {\n  createFarmDeploymentMismatchError,\n  createFarmDeploymentRequestHeaders,\n  isFarmDeploymentMismatchResponse,\n} from \"../deployment\";\nimport { getHashTargetElement } from \"./hash-target\";\nimport { isFarmExternalNavigationURL, resolveFarmNavigationURL } from \"./navigation-url\";\nimport { applyFarmMetadataToDocument, type NavigationMetadata } from \"./metadata-reconciler\";\nimport type { FarmClientNavigationSession, FarmClientPluginManager } from \"./plugin\";\nimport { _hydrateFarmI18n, isFarmLocaleChangeHref } from \"../i18n/client-runtime\";\nimport type { FarmI18nClientSnapshot } from \"../i18n/types\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport type { FarmRouteRenderPlan } from \"../navigation/render-plan\";\n\nexport { getHashTargetElement } from \"./hash-target\";\nexport { isFarmExternalNavigationURL } from \"./navigation-url\";\n\n/**\n * Farm.js SPA Router\n *\n * Provides client-side navigation without full page reloads.\n * Features:\n * - Prefetch on viewport intersection\n * - Prefetch on hover\n * - Page caching\n * - History API integration\n * - Scroll restoration\n */\n\ninterface PageData {\n  props: Record<string, any>;\n  modulePath: string;\n  loadingModulePath?: string | null;\n  canonicalPath?: string;\n  isClientComponent?: boolean;\n  shouldHydrate?: boolean;\n  islandStrategy?: FarmIslandStrategy | null;\n  renderPlan?: FarmRouteRenderPlan;\n  fragment?: {\n    html: string;\n    layoutPatterns: string[];\n  };\n  metadata?: NavigationMetadata;\n  layoutModules?: string[];\n  routeSlots?: RouteSlotPageData[];\n  interception?: {\n    from?: string;\n    slots: string[];\n  };\n  i18n?: FarmI18nClientSnapshot;\n}\n\ninterface RouteSlotPageData {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  interception: boolean;\n  fallback: boolean;\n  modulePath: string;\n  isClientComponent: boolean;\n  shouldHydrate: boolean;\n  props: Record<string, any>;\n}\n\nexport interface RouterOptions {\n  prefetchTimeout?: number;\n  cacheMaxAge?: number;\n  scrollRestoration?: boolean;\n  shouldUseDocumentNavigation?: (pathname: string) => boolean;\n  deploymentId?: string;\n}\n\ninterface CacheEntry {\n  data: PageData;\n  timestamp: number;\n}\n\nexport interface FarmNavigationBlockerContext {\n  from: string;\n  to: string;\n  action: \"push\" | \"replace\" | \"pop\";\n}\n\nexport type FarmNavigationBlocker = (\n  context: FarmNavigationBlockerContext,\n) => boolean | void | Promise<boolean | void>;\n\nexport type FarmViewTransitionMode = boolean | \"auto\";\n\nexport interface FarmNavigateOptions {\n  replace?: boolean;\n  scroll?: boolean;\n  state?: unknown;\n  viewTransition?: FarmViewTransitionMode;\n  /** Re-fetch the current route even when its URL has not changed. */\n  refresh?: boolean;\n}\n\nexport interface FarmNavigationLocation {\n  href: string;\n  pathname: string;\n  search: string;\n  hash: string;\n}\n\nexport interface FarmNavigationState {\n  state: \"idle\" | \"loading\";\n  pending: boolean;\n  from: string | null;\n  to: FarmNavigationLocation | null;\n  action: FarmNavigationBlockerContext[\"action\"] | null;\n  startedAt: number | null;\n}\n\nexport type FarmNavigationListener = (state: FarmNavigationState) => void;\n\nconst FARM_PAGE_STATE_KEY = \"__farmPageState\";\nconst FARM_INTERCEPT_FROM_KEY = \"__farmInterceptFrom\";\nconst FARM_HISTORY_INDEX_KEY = \"__farmHistoryIndex\";\n\nfunction readHistoryIndex(state: unknown): number | null {\n  if (!state || typeof state !== \"object\") return null;\n  const value = (state as Record<string, unknown>)[FARM_HISTORY_INDEX_KEY];\n  return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\nconst IDLE_NAVIGATION_STATE: FarmNavigationState = {\n  state: \"idle\",\n  pending: false,\n  from: null,\n  to: null,\n  action: null,\n  startedAt: null,\n};\n\nfunction getActiveLayoutChainHeader(): string | undefined {\n  if (typeof document === \"undefined\") return undefined;\n  const patterns = Array.from(\n    document.querySelectorAll<HTMLElement>('[data-farm-layout-boundary=\"true\"]'),\n  )\n    .map((element) => element.dataset.farmLayoutPattern)\n    .filter((pattern): pattern is string => Boolean(pattern));\n  return patterns.length > 0 ? JSON.stringify(patterns) : undefined;\n}\n\n// Global router instance\nlet routerInstance: SPARouter | null = null;\n\nexport class SPARouter {\n  private cache: Map<string, CacheEntry> = new Map();\n  private prefetchingUrls: Set<string> = new Set();\n  private observers: Map<Element, IntersectionObserver> = new Map();\n  private prefetchTimers: Map<Element, ReturnType<typeof setTimeout>> = new Map();\n  private blockers: Set<FarmNavigationBlocker> = new Set();\n  private unloadBlockers: Map<FarmNavigationBlocker, () => boolean> = new Map();\n  private navigationListeners: Set<FarmNavigationListener> = new Set();\n  private navigationState: FarmNavigationState = IDLE_NAVIGATION_STATE;\n  private currentHistoryPath: string | null = null;\n  private currentHistoryIndex: number | null = null;\n  private suppressNextPopState = false;\n  private navigationSequence = 0;\n  private activeNavigation?: {\n    id: number;\n    controller: AbortController;\n  };\n  private scrollElements: Map<string, HTMLElement> = new Map();\n  private options: Required<Omit<RouterOptions, \"deploymentId\">> &\n    Pick<RouterOptions, \"deploymentId\">;\n  private onNavigate?: (data: PageData) => Promise<void>;\n  private clientPlugins?: Pick<\n    FarmClientPluginManager,\n    | \"beginNavigation\"\n    | \"markNavigationLoaded\"\n    | \"resolveNavigation\"\n    | \"scheduleNavigationRendered\"\n    | \"failNavigation\"\n  >;\n\n  private readonly onPopState = (event: PopStateEvent) => {\n    void this.handlePopState(event);\n  };\n\n  private readonly onBeforeUnload = (event: BeforeUnloadEvent) => {\n    if (this.shouldBlockUnload()) {\n      event.preventDefault();\n      event.returnValue = \"\";\n    }\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n  };\n\n  constructor(options: RouterOptions = {}) {\n    this.options = {\n      prefetchTimeout: options.prefetchTimeout ?? 100,\n      cacheMaxAge: options.cacheMaxAge ?? 30000, // 30 seconds\n      scrollRestoration: options.scrollRestoration ?? true,\n      shouldUseDocumentNavigation: options.shouldUseDocumentNavigation ?? (() => false),\n      deploymentId: options.deploymentId ?? readBrowserDeploymentId(),\n    };\n\n    if (typeof window !== \"undefined\") {\n      // Listen for popstate (back/forward navigation)\n      window.addEventListener(\"popstate\", this.onPopState);\n\n      // Save scroll position before unload\n      window.addEventListener(\"beforeunload\", this.onBeforeUnload);\n\n      // Track the rendered location and its position in the history stack so\n      // popstate can report a real `from` and revert blocked traversals.\n      this.currentHistoryPath = window.location.pathname + window.location.search;\n      const existingIndex = readHistoryIndex(window.history.state);\n      if (existingIndex == null) {\n        try {\n          window.history.replaceState(\n            {\n              ...((window.history.state as object | null) ?? {}),\n              [FARM_HISTORY_INDEX_KEY]: 0,\n            },\n            \"\",\n            window.location.href,\n          );\n          this.currentHistoryIndex = 0;\n        } catch {\n          this.currentHistoryIndex = null;\n        }\n      } else {\n        this.currentHistoryIndex = existingIndex;\n      }\n    }\n  }\n\n  /** Remove global listeners. Intended for tests and teardown. */\n  destroy(): void {\n    if (typeof window === \"undefined\") return;\n    this.cancelActiveNavigation();\n    for (const observer of this.observers.values()) observer.disconnect();\n    for (const timer of this.prefetchTimers.values()) clearTimeout(timer);\n    this.observers.clear();\n    this.prefetchTimers.clear();\n    window.removeEventListener(\"popstate\", this.onPopState);\n    window.removeEventListener(\"beforeunload\", this.onBeforeUnload);\n  }\n\n  /**\n   * Set the navigation handler that updates React\n   */\n  setNavigationHandler(handler: (data: PageData) => Promise<void>) {\n    this.onNavigate = handler;\n  }\n\n  /**\n   * Connect Farm's browser plugin lifecycle to SPA navigation.\n   */\n  setClientPluginManager(manager: FarmClientPluginManager) {\n    this.clientPlugins = manager;\n  }\n\n  /**\n   * Navigate to a new URL\n   */\n  async navigate(href: string, options: FarmNavigateOptions = {}): Promise<void> {\n    const {\n      replace = false,\n      scroll = true,\n      state,\n      viewTransition = false,\n      refresh = false,\n    } = options;\n\n    // Relative targets resolve against the current document, not the origin.\n    const url = resolveFarmNavigationURL(href, window.location.href);\n    const pathname = url.pathname;\n    const search = url.search;\n    const fullPath = pathname + search;\n\n    if (\n      isFarmExternalNavigationURL(url, window.location.origin) ||\n      isFarmLocaleChangeHref(url.toString()) ||\n      this.options.shouldUseDocumentNavigation(pathname)\n    ) {\n      this.cancelActiveNavigation();\n      if (replace) window.location.replace(url.toString());\n      else window.location.assign(url.toString());\n      return;\n    }\n\n    // Same page navigation - update fragment history without fetching route data.\n    if (!refresh && pathname === window.location.pathname && search === window.location.search) {\n      this.cancelActiveNavigation();\n      if (url.hash === window.location.hash) return;\n\n      this.writePageState(\n        replace ? \"replace\" : \"push\",\n        state === undefined ? readPageState() : state,\n        url.toString(),\n      );\n      if (scroll) {\n        if (url.hash) {\n          getHashTargetElement(url.hash)?.scrollIntoView();\n        } else {\n          window.scrollTo(0, 0);\n        }\n      }\n      return;\n    }\n\n    const from = window.location.pathname + window.location.search;\n    if (\n      await this.shouldBlockNavigation({\n        from,\n        to: fullPath,\n        action: replace ? \"replace\" : \"push\",\n      })\n    ) {\n      return;\n    }\n\n    // Save current scroll position\n    if (this.options.scrollRestoration) {\n      this.saveScrollPosition(window.location.pathname + window.location.search);\n    }\n\n    const navigation = this.startNavigation({\n      from,\n      to: createNavigationLocation(url),\n      action: replace ? \"replace\" : \"push\",\n    });\n\n    let clientNavigation: FarmClientNavigationSession | undefined;\n    try {\n      clientNavigation = await this.clientPlugins?.beginNavigation({\n        from,\n        to: url,\n        action: replace ? \"replace\" : \"push\",\n      });\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      // Fetch page data (from cache or server)\n      const pageData = await this.fetchPageData(\n        fullPath,\n        true,\n        from,\n        refresh,\n        navigation.controller.signal,\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);\n      }\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      await this.runViewTransition(viewTransition, () =>\n        this.isCurrentNavigation(navigation, clientNavigation)\n          ? this.commitNavigation({\n              fullPath,\n              pageData,\n              pathname,\n              replace,\n              scroll,\n              state,\n              url,\n            })\n          : Promise.resolve(),\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      if (clientNavigation) {\n        await this.clientPlugins?.resolveNavigation(clientNavigation);\n        void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);\n      }\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      console.error(\"[Farm.js] Navigation error:\", error);\n      // Fall back to full page navigation\n      window.location.href = href;\n    }\n  }\n\n  /**\n   * Re-render the active route from the server while preserving the document,\n   * shared layouts, client runtime, and browser history entry.\n   */\n  refresh(options: Omit<FarmNavigateOptions, \"replace\" | \"refresh\"> = {}): Promise<void> {\n    return this.navigate(window.location.href, {\n      ...options,\n      replace: true,\n      refresh: true,\n      scroll: options.scroll ?? false,\n    });\n  }\n\n  /**\n   * Prefetch a URL\n   */\n  async prefetch(href: string): Promise<void> {\n    if (isFarmLocaleChangeHref(href)) return;\n    const url = resolveFarmNavigationURL(href, window.location.href);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) return;\n    if (this.options.shouldUseDocumentNavigation(url.pathname)) return;\n    const fullPath = url.pathname + url.search;\n    const interceptFrom = window.location.pathname + window.location.search;\n\n    // Skip if already prefetching or cached\n    if (this.prefetchingUrls.has(fullPath)) return;\n    if (this.isCached(fullPath, interceptFrom)) return;\n\n    this.prefetchingUrls.add(fullPath);\n\n    try {\n      await this.fetchPageData(fullPath, false, interceptFrom);\n    } catch (error) {\n      console.warn(\"[Farm.js] Prefetch failed:\", href, error);\n    } finally {\n      this.prefetchingUrls.delete(fullPath);\n    }\n  }\n\n  /**\n   * Observe an element for viewport intersection (prefetch when visible)\n   */\n  observeForPrefetch(element: HTMLAnchorElement): void {\n    if (typeof IntersectionObserver === \"undefined\") return;\n\n    const href = element.getAttribute(\"href\");\n    if (!href || this.isExternalUrl(href)) return;\n    this.unobserveForPrefetch(element);\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) {\n          if (entry.isIntersecting) {\n            if (this.observers.get(element) !== observer) continue;\n            // Delay prefetch slightly to avoid prefetching during scroll\n            const timer = setTimeout(() => {\n              if (this.prefetchTimers.get(element) !== timer) return;\n              this.prefetchTimers.delete(element);\n              void this.prefetch(href);\n            }, this.options.prefetchTimeout);\n            this.prefetchTimers.set(element, timer);\n\n            // Stop observing after first intersection\n            observer.unobserve(element);\n            this.observers.delete(element);\n          }\n        }\n      },\n      { rootMargin: \"200px\" }, // Start prefetching when 200px from viewport\n    );\n\n    observer.observe(element);\n    this.observers.set(element, observer);\n  }\n\n  /**\n   * Stop observing an element\n   */\n  unobserveForPrefetch(element: HTMLAnchorElement): void {\n    const observer = this.observers.get(element);\n    if (observer) {\n      observer.unobserve(element);\n      this.observers.delete(element);\n    }\n    const timer = this.prefetchTimers.get(element);\n    if (timer !== undefined) {\n      clearTimeout(timer);\n      this.prefetchTimers.delete(element);\n    }\n  }\n\n  addBlocker(blocker: FarmNavigationBlocker, shouldBlockUnload?: () => boolean): () => void {\n    this.blockers.add(blocker);\n    this.unloadBlockers.set(\n      blocker,\n      shouldBlockUnload ?? (() => this.evaluateBlockerForUnload(blocker)),\n    );\n    return () => {\n      this.blockers.delete(blocker);\n      this.unloadBlockers.delete(blocker);\n    };\n  }\n\n  getNavigationState(): FarmNavigationState {\n    return this.navigationState;\n  }\n\n  subscribeNavigation(listener: FarmNavigationListener): () => void {\n    this.navigationListeners.add(listener);\n    listener(this.navigationState);\n    return () => {\n      this.navigationListeners.delete(listener);\n    };\n  }\n\n  registerScrollElement(key: string, element: HTMLElement): () => void {\n    this.scrollElements.set(key, element);\n    this.restoreScrollElement(window.location.pathname + window.location.search, key, element);\n    return () => {\n      if (this.scrollElements.get(key) === element) {\n        this.scrollElements.delete(key);\n      }\n    };\n  }\n\n  pushState(state: unknown, href?: string): void {\n    this.writePageState(\"push\", state, href);\n  }\n\n  replaceState(state: unknown, href?: string): void {\n    this.writePageState(\"replace\", state, href);\n  }\n\n  /** @internal Keep shallow URL-search writes inside the router's history bookkeeping. */\n  writeURLSearch(action: \"push\" | \"replace\", href: string): void {\n    this.writePageState(action, readPageState(), href, false);\n  }\n\n  private async commitNavigation(options: {\n    fullPath: string;\n    pageData: PageData;\n    pathname: string;\n    replace: boolean;\n    scroll: boolean;\n    state: unknown;\n    url: URL;\n  }): Promise<void> {\n    const historyUrl = resolveFarmNavigationURL(\n      options.pageData.canonicalPath || options.fullPath,\n      window.location.href,\n    );\n    historyUrl.hash = options.url.hash;\n    const historyPath = historyUrl.pathname + historyUrl.search + historyUrl.hash;\n    const historyState = createHistoryState(\n      historyPath,\n      options.state,\n      options.replace ? window.history.state : undefined,\n      options.pageData.interception?.from ?? null,\n    ) as Record<string, unknown>;\n    const nextHistoryIndex =\n      this.currentHistoryIndex == null\n        ? null\n        : options.replace\n          ? this.currentHistoryIndex\n          : this.currentHistoryIndex + 1;\n    if (nextHistoryIndex != null) {\n      historyState[FARM_HISTORY_INDEX_KEY] = nextHistoryIndex;\n    }\n    if (options.replace) {\n      window.history.replaceState(historyState, \"\", historyPath);\n    } else {\n      window.history.pushState(historyState, \"\", historyPath);\n    }\n    this.currentHistoryIndex = nextHistoryIndex;\n    const resolvedHistoryUrl = resolveFarmNavigationURL(historyPath, window.location.href);\n    this.currentHistoryPath = resolvedHistoryUrl.pathname + resolvedHistoryUrl.search;\n    notifyRouterHistoryChange();\n\n    this.updateDocumentMetadata(options.pageData.metadata);\n\n    _hydrateFarmI18n(options.pageData.i18n);\n\n    if (this.onNavigate) {\n      await this.onNavigate(options.pageData);\n    }\n\n    if (options.scroll) {\n      if (options.url.hash) {\n        const element = getHashTargetElement(options.url.hash);\n        if (element) {\n          element.scrollIntoView();\n        }\n      } else {\n        window.scrollTo(0, 0);\n      }\n    } else if (this.options.scrollRestoration) {\n      const restorePath = this.currentHistoryPath ?? options.fullPath;\n      this.restoreWindowScroll(restorePath);\n      this.restoreScrollElements(restorePath);\n    }\n  }\n\n  private async runViewTransition(\n    mode: FarmViewTransitionMode,\n    callback: () => Promise<void>,\n  ): Promise<void> {\n    if (!mode || typeof document === \"undefined\") {\n      await callback();\n      return;\n    }\n\n    const startViewTransition = (document as any).startViewTransition;\n    if (typeof startViewTransition !== \"function\") {\n      await callback();\n      return;\n    }\n\n    const transition = startViewTransition.call(document, () => callback());\n    const updateDone = transition?.updateCallbackDone || transition?.ready;\n    if (updateDone && typeof updateDone.then === \"function\") {\n      await updateDone;\n    }\n    transition?.finished?.catch?.(() => undefined);\n  }\n\n  /**\n   * Fetch page data from cache or server\n   */\n  private async fetchPageData(\n    path: string,\n    recover = true,\n    interceptFrom?: string,\n    fresh = false,\n    signal?: AbortSignal,\n  ): Promise<PageData> {\n    const cacheKey = getPageDataCacheKey(path, interceptFrom);\n    // Check cache first\n    const cached = fresh ? undefined : this.cache.get(cacheKey);\n    if (cached && Date.now() - cached.timestamp < this.options.cacheMaxAge) {\n      return cached.data;\n    }\n\n    // Fetch from server. The active layout chain lets the server omit shared\n    // shell HTML from the fragment without inspecting component source.\n    const activeLayoutChain = getActiveLayoutChainHeader();\n    const response = await fetch(`/__farm/page-data?path=${encodeURIComponent(path)}`, {\n      signal,\n      headers: createFarmDeploymentRequestHeaders(this.options.deploymentId, {\n        Accept: \"application/x-farm-deferred+json, application/json\",\n        \"X-Farm-SPA\": \"1\",\n        ...(activeLayoutChain ? { \"X-Farm-Layout-Chain\": activeLayoutChain } : {}),\n        ...(interceptFrom ? { \"X-Farm-Intercept-From\": interceptFrom } : {}),\n      }),\n    });\n\n    if (isFarmDeploymentMismatchResponse(response, this.options.deploymentId)) {\n      const error = createFarmDeploymentMismatchError(\n        response,\n        this.options.deploymentId || \"unknown\",\n      );\n      dispatchDeploymentMismatch(error);\n      if (recover) {\n        window.location.assign(path);\n      }\n      throw error;\n    }\n\n    if (!response.ok) {\n      throw new Error(`Failed to fetch page data: ${response.status}`);\n    }\n\n    const data = await readDeferredDataResponse<PageData>(response);\n\n    // Cache the result. Expiry was previously only consulted on read, so a\n    // long-lived tab that navigates or prefetches many distinct routes grew\n    // this map without bound; sweeping on write bounds it to entries touched\n    // within the cacheMaxAge window.\n    const now = Date.now();\n    for (const [key, entry] of this.cache) {\n      if (now - entry.timestamp >= this.options.cacheMaxAge) this.cache.delete(key);\n    }\n    this.cache.set(cacheKey, {\n      data,\n      timestamp: now,\n    });\n\n    return data;\n  }\n\n  /**\n   * Put the browser URL back on the rendered page after a blocked pop. When\n   * both entries carry a Farm history index the traversal is reversed\n   * exactly; otherwise the current path is pushed again, which restores the\n   * address bar at the cost of one extra history entry.\n   */\n  private revertBlockedPopState(event: PopStateEvent, from: string): void {\n    const eventIndex = readHistoryIndex(event.state);\n    if (eventIndex != null && this.currentHistoryIndex != null) {\n      const delta = eventIndex - this.currentHistoryIndex;\n      if (delta !== 0) {\n        this.suppressNextPopState = true;\n        window.history.go(-delta);\n        return;\n      }\n    }\n\n    try {\n      const restoredState: Record<string, unknown> = {\n        path: from,\n      };\n      if (this.currentHistoryIndex != null && eventIndex != null) {\n        restoredState[FARM_HISTORY_INDEX_KEY] = eventIndex + 1;\n        this.currentHistoryIndex = eventIndex + 1;\n      }\n      window.history.pushState(restoredState, \"\", from);\n    } catch {\n      // Leave the URL as-is if the history API rejects the write; the\n      // rendered page is still the blocked-from page.\n    }\n  }\n\n  /**\n   * Handle browser back/forward navigation\n   */\n  private async handlePopState(event: PopStateEvent): Promise<void> {\n    if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n\n    if (this.suppressNextPopState) {\n      // This traversal is our own revert of a blocked pop; the rendered page\n      // never changed.\n      this.suppressNextPopState = false;\n      return;\n    }\n\n    const path = window.location.pathname + window.location.search;\n    // The browser has already moved to the destination entry, so its state\n    // describes `to`; the page still rendered is the tracked current path.\n    const from = this.currentHistoryPath ?? path;\n\n    if (\n      await this.shouldBlockNavigation({\n        from,\n        to: path,\n        action: \"pop\",\n      })\n    ) {\n      this.revertBlockedPopState(event, from);\n      return;\n    }\n\n    this.currentHistoryPath = path;\n    this.currentHistoryIndex = readHistoryIndex(event.state);\n\n    const navigation = this.startNavigation({\n      from,\n      to: createNavigationLocation(new URL(window.location.href)),\n      action: \"pop\",\n    });\n\n    let clientNavigation: FarmClientNavigationSession | undefined;\n    try {\n      clientNavigation = await this.clientPlugins?.beginNavigation({\n        from: null,\n        to: window.location.href,\n        action: \"pop\",\n      });\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      const interceptFrom =\n        typeof event.state?.[FARM_INTERCEPT_FROM_KEY] === \"string\"\n          ? event.state[FARM_INTERCEPT_FROM_KEY]\n          : undefined;\n      const pageData = await this.fetchPageData(\n        path,\n        true,\n        interceptFrom,\n        false,\n        navigation.controller.signal,\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);\n      }\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      this.updateDocumentMetadata(pageData.metadata);\n\n      _hydrateFarmI18n(pageData.i18n);\n\n      // Call the navigation handler to update React\n      if (this.onNavigate) {\n        await this.onNavigate(pageData);\n      }\n\n      // A fragment in the destination URL is an explicit scroll target for the\n      // window and takes precedence over the saved *window* scroll position,\n      // matching forward navigation and native browser back/forward. Element\n      // scroll positions are keyed without the hash (see\n      // getScrollElementStorageKey), so registered scroll containers are\n      // restored regardless of whether a fragment is present, even when the\n      // anchor resolves, so a persistent-layout scroll element is not left at\n      // the prior route's offset on a hash-destination popstate.\n      const destinationPath = window.location.pathname + window.location.search;\n      if (window.location.hash) {\n        const target = getHashTargetElement(window.location.hash);\n        if (target) {\n          target.scrollIntoView();\n        } else if (this.options.scrollRestoration) {\n          this.restoreWindowScroll(destinationPath);\n        }\n      } else if (this.options.scrollRestoration) {\n        this.restoreWindowScroll(destinationPath);\n      }\n      if (this.options.scrollRestoration) {\n        this.restoreScrollElements(destinationPath);\n      }\n\n      if (clientNavigation) {\n        await this.clientPlugins?.resolveNavigation(clientNavigation);\n        void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);\n      }\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      console.error(\"[Farm.js] Popstate navigation error:\", error);\n      // Reload the page as fallback\n      window.location.reload();\n    }\n  }\n\n  /**\n   * Check if URL is cached\n   */\n  private isCached(path: string, interceptFrom?: string): boolean {\n    const cached = this.cache.get(getPageDataCacheKey(path, interceptFrom));\n    return cached !== undefined && Date.now() - cached.timestamp < this.options.cacheMaxAge;\n  }\n\n  /**\n   * Check if URL is external\n   */\n  private isExternalUrl(href: string): boolean {\n    return href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\");\n  }\n\n  private async shouldBlockNavigation(context: FarmNavigationBlockerContext): Promise<boolean> {\n    for (const blocker of this.blockers) {\n      if (await blocker(context)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private evaluateBlockerForUnload(blocker: FarmNavigationBlocker): boolean {\n    const path = window.location.pathname + window.location.search;\n    const result = blocker({ from: path, to: path, action: \"replace\" });\n    if (result && typeof result !== \"boolean\") {\n      void result.catch(() => undefined);\n      return true;\n    }\n    return result === true;\n  }\n\n  private shouldBlockUnload(): boolean {\n    for (const blocker of this.blockers) {\n      try {\n        if (this.unloadBlockers.get(blocker)?.()) return true;\n      } catch {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private updateDocumentMetadata(metadata: PageData[\"metadata\"]): void {\n    // Both call sites run after the history entry is committed, so the current\n    // pathname is the navigated-to page and drives the default canonical.\n    applyFarmMetadataToDocument(metadata, window.location.pathname);\n  }\n\n  private startNavigation(options: {\n    from: string;\n    to: FarmNavigationLocation;\n    action: FarmNavigationBlockerContext[\"action\"];\n  }): { id: number; controller: AbortController } {\n    this.activeNavigation?.controller.abort(\"superseded\");\n    const navigation = {\n      id: ++this.navigationSequence,\n      controller: new AbortController(),\n    };\n    this.activeNavigation = navigation;\n    this.setNavigationState({\n      state: \"loading\",\n      pending: true,\n      from: options.from,\n      to: options.to,\n      action: options.action,\n      startedAt: Date.now(),\n    });\n    return navigation;\n  }\n\n  private isCurrentNavigation(\n    navigation: { id: number; controller: AbortController },\n    clientNavigation?: FarmClientNavigationSession,\n  ): boolean {\n    return (\n      this.activeNavigation?.id === navigation.id &&\n      !navigation.controller.signal.aborted &&\n      !clientNavigation?.signal.aborted\n    );\n  }\n\n  private finishNavigation(navigation: { id: number; controller: AbortController }): void {\n    if (this.activeNavigation?.id !== navigation.id) return;\n    this.activeNavigation = undefined;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  }\n\n  private cancelActiveNavigation(): void {\n    if (!this.activeNavigation) return;\n    this.activeNavigation.controller.abort(\"superseded\");\n    this.activeNavigation = undefined;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  }\n\n  private setNavigationState(state: FarmNavigationState): void {\n    this.navigationState = state;\n    for (const listener of this.navigationListeners) {\n      listener(state);\n    }\n  }\n\n  private writePageState(\n    action: \"push\" | \"replace\",\n    state: unknown,\n    href?: string,\n    notify = true,\n  ): void {\n    if (typeof window === \"undefined\") return;\n\n    const url = href\n      ? resolveFarmNavigationURL(href, window.location.href).toString()\n      : window.location.href;\n    const parsedUrl = new URL(url);\n    const nextPath = parsedUrl.pathname + parsedUrl.search;\n    const historyPath = nextPath + parsedUrl.hash;\n    const nextState = createHistoryState(historyPath, state, window.history.state) as Record<\n      string,\n      unknown\n    >;\n\n    if (action === \"replace\") {\n      window.history.replaceState(nextState, \"\", url);\n    } else {\n      if (this.currentHistoryIndex != null) {\n        nextState[FARM_HISTORY_INDEX_KEY] = this.currentHistoryIndex + 1;\n      }\n      window.history.pushState(nextState, \"\", url);\n      this.currentHistoryIndex =\n        this.currentHistoryIndex == null ? null : this.currentHistoryIndex + 1;\n    }\n    this.currentHistoryPath = nextPath;\n\n    if (notify) notifyHistoryChange(\"page-state\");\n  }\n\n  /**\n   * Save scroll position for a path\n   */\n  private saveScrollPosition(path: string): void {\n    try {\n      sessionStorage.setItem(\n        `farm-scroll-${path}`,\n        JSON.stringify({ x: window.scrollX, y: window.scrollY }),\n      );\n      for (const [key, element] of this.scrollElements) {\n        sessionStorage.setItem(\n          getScrollElementStorageKey(path, key),\n          JSON.stringify({ x: element.scrollLeft, y: element.scrollTop }),\n        );\n      }\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  /**\n   * Restore the saved window scroll position for a path.\n   */\n  private restoreWindowScroll(path: string): void {\n    try {\n      const saved = sessionStorage.getItem(`farm-scroll-${path}`);\n      if (saved) {\n        const { x, y } = JSON.parse(saved);\n        setTimeout(() => window.scrollTo(x, y), 0);\n      }\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  /**\n   * Restore saved scroll positions for every registered scroll element. Keys\n   * are hash-stripped (see getScrollElementStorageKey), so this runs regardless\n   * of whether the destination URL carries a fragment.\n   */\n  private restoreScrollElements(path: string): void {\n    try {\n      for (const [key, element] of this.scrollElements) {\n        this.restoreScrollElement(path, key, element);\n      }\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  private restoreScrollElement(path: string, key: string, element: HTMLElement): void {\n    try {\n      const saved = sessionStorage.getItem(getScrollElementStorageKey(path, key));\n      if (!saved) return;\n      const { x, y } = JSON.parse(saved);\n      setTimeout(() => {\n        element.scrollLeft = x;\n        element.scrollTop = y;\n      }, 0);\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  /**\n   * Clear the page cache\n   */\n  clearCache(): void {\n    this.cache.clear();\n  }\n}\n\nfunction readBrowserDeploymentId(): string | undefined {\n  if (typeof window === \"undefined\") return undefined;\n\n  const runtimeId = (window as Window & { __FARM_DEPLOYMENT_ID__?: unknown })\n    .__FARM_DEPLOYMENT_ID__;\n  if (typeof runtimeId === \"string\" && runtimeId) return runtimeId;\n\n  return document.querySelector<HTMLMetaElement>('meta[name=\"farm-deployment-id\"]')?.content;\n}\n\nfunction dispatchDeploymentMismatch(error: Error): void {\n  if (typeof window === \"undefined\" || typeof CustomEvent === \"undefined\") return;\n  window.dispatchEvent(new CustomEvent(\"farm:deployment-mismatch\", { detail: error }));\n}\n\n/**\n * Get or create the global router instance\n */\nexport function getInstalledFarmSPARouter(): SPARouter | undefined {\n  if (typeof window === \"undefined\") return undefined;\n  return (window as Window & { __FARM_SPA_ROUTER__?: SPARouter }).__FARM_SPA_ROUTER__;\n}\n\nexport function getRouter(): SPARouter {\n  if (typeof window === \"undefined\") {\n    // Return a no-op router for SSR\n    return new SPARouter();\n  }\n\n  const installedRouter = getInstalledFarmSPARouter();\n  if (installedRouter) {\n    routerInstance = installedRouter;\n    return installedRouter;\n  }\n\n  if (!routerInstance) {\n    routerInstance = new SPARouter();\n  }\n\n  return routerInstance;\n}\n\n/**\n * Navigate to a URL using the SPA router\n */\nexport function navigateTo(href: string, options?: FarmNavigateOptions): Promise<void> {\n  return getRouter().navigate(href, options);\n}\n\n/**\n * Prefetch a URL\n */\nexport function prefetch(href: string): Promise<void> {\n  return getRouter().prefetch(href);\n}\n\nexport function pushState(state: unknown, href?: string): void {\n  getRouter().pushState(state, href);\n}\n\nexport function replaceState(state: unknown, href?: string): void {\n  getRouter().replaceState(state, href);\n}\n\nexport function readPageState<TState = unknown>(): TState | null {\n  if (typeof window === \"undefined\") return null;\n  const state = window.history.state;\n  if (!state || typeof state !== \"object\") return null;\n  return ((state as Record<string, unknown>)[FARM_PAGE_STATE_KEY] as TState | undefined) ?? null;\n}\n\nfunction createHistoryState(\n  path: string,\n  pageState: unknown,\n  currentState?: unknown,\n  interceptFrom?: string | null,\n) {\n  const base =\n    currentState && typeof currentState === \"object\" ? { ...(currentState as object) } : {};\n  const nextState: Record<string, unknown> = {\n    ...base,\n    path,\n    [FARM_PAGE_STATE_KEY]: pageState,\n  };\n  if (interceptFrom === null) {\n    delete nextState[FARM_INTERCEPT_FROM_KEY];\n  } else if (interceptFrom) {\n    nextState[FARM_INTERCEPT_FROM_KEY] = interceptFrom;\n  }\n  return nextState;\n}\n\nfunction getPageDataCacheKey(path: string, interceptFrom?: string): string {\n  return interceptFrom ? `${path}\\nintercept:${interceptFrom}` : path;\n}\n\nfunction createNavigationLocation(url: URL): FarmNavigationLocation {\n  return {\n    href: url.href,\n    pathname: url.pathname,\n    search: url.search,\n    hash: url.hash,\n  };\n}\n\nfunction getScrollElementStorageKey(path: string, key: string): string {\n  return `farm-scroll-${path}:${key}`;\n}\n","\"use client\";\n\nexport interface FarmChunkRecoveryOptions {\n  /**\n   * How long a page is considered already recovered before another chunk\n   * failure may trigger a reload. Defaults to 30 seconds.\n   */\n  maxAgeMs?: number;\n  /**\n   * Override the storage key. Mostly useful for tests and embedded runtimes.\n   */\n  storageKey?: string;\n  /**\n   * Called right before Farm reloads the page.\n   */\n  onRecover?: (error: unknown) => void;\n  /**\n   * Test hooks for browser globals.\n   */\n  reload?: () => void;\n  storage?: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | null;\n  location?: Pick<Location, \"pathname\" | \"search\" | \"reload\">;\n  now?: () => number;\n}\n\nconst DEFAULT_MAX_AGE_MS = 30_000;\nconst STORAGE_KEY_PREFIX = \"farm:chunk-recovery:\";\nconst CHUNK_ERROR_PATTERNS = [\n  /ChunkLoadError/i,\n  /Loading chunk [\\w-]+ failed/i,\n  /Loading CSS chunk [\\w-]+ failed/i,\n  /CSS_CHUNK_LOAD_FAILED/i,\n  /failed to fetch dynamically imported module/i,\n  /error loading dynamically imported module/i,\n  /importing a module script failed/i,\n  /unable to preload CSS/i,\n  /module script failed/i,\n];\n\nexport function isChunkLoadError(errorLike: unknown): boolean {\n  const values = collectErrorText(errorLike);\n  if (values.some((value) => CHUNK_ERROR_PATTERNS.some((pattern) => pattern.test(value)))) {\n    return true;\n  }\n\n  // Only treat same-origin script/style failures as chunk errors. A blocked\n  // or missing third-party asset (analytics, embeds) is not fixable by\n  // reloading, and reloading for it would loop for as long as it keeps\n  // failing.\n  const targetUrl = getEventTargetAssetUrl(errorLike);\n  return Boolean(\n    targetUrl && /\\.(?:m?js|css)(?:[?#].*)?$/i.test(targetUrl) && isSameOriginAssetUrl(targetUrl),\n  );\n}\n\nfunction isSameOriginAssetUrl(url: string): boolean {\n  if (typeof window === \"undefined\" || !window.location) {\n    return false;\n  }\n\n  try {\n    return new URL(url, window.location.href).origin === window.location.origin;\n  } catch {\n    return false;\n  }\n}\n\nexport function installChunkErrorRecovery(options: FarmChunkRecoveryOptions = {}): () => void {\n  if (typeof window === \"undefined\") {\n    return () => {};\n  }\n\n  const recover = (errorLike: unknown) => {\n    if (!isChunkLoadError(errorLike)) {\n      return;\n    }\n    if (!markRecovered(options)) {\n      return;\n    }\n\n    options.onRecover?.(errorLike);\n    getReload(options)();\n  };\n\n  const onError = (event: Event | ErrorEvent) => {\n    recover(getErrorEventPayload(event));\n  };\n  const onUnhandledRejection = (event: PromiseRejectionEvent) => {\n    recover(event.reason);\n  };\n\n  window.addEventListener(\"error\", onError, true);\n  window.addEventListener(\"unhandledrejection\", onUnhandledRejection);\n\n  return () => {\n    window.removeEventListener(\"error\", onError, true);\n    window.removeEventListener(\"unhandledrejection\", onUnhandledRejection);\n  };\n}\n\nfunction markRecovered(options: FarmChunkRecoveryOptions): boolean {\n  const now = getNow(options);\n  const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n  const storage = getStorage(options);\n  const key = getStorageKey(options);\n\n  if (!storage) {\n    return false;\n  }\n\n  try {\n    const previous = Number(storage.getItem(key));\n    if (Number.isFinite(previous) && previous > 0 && now - previous < maxAgeMs) {\n      return false;\n    }\n    storage.setItem(key, String(now));\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nfunction getErrorEventPayload(event: Event | ErrorEvent): unknown {\n  if (\"error\" in event && event.error) {\n    return event.error;\n  }\n  if (\"message\" in event && event.message) {\n    return event.message;\n  }\n  return event;\n}\n\nfunction collectErrorText(value: unknown, seen = new Set<unknown>()): string[] {\n  if (value == null || seen.has(value)) {\n    return [];\n  }\n  seen.add(value);\n\n  if (typeof value === \"string\") {\n    return [value];\n  }\n  if (typeof value === \"number\" || typeof value === \"boolean\") {\n    return [String(value)];\n  }\n  if (typeof value !== \"object\") {\n    return [];\n  }\n\n  const record = value as Record<string, unknown>;\n  const output: string[] = [];\n\n  for (const key of [\"name\", \"message\", \"code\", \"type\", \"request\", \"src\", \"href\"]) {\n    const candidate = record[key];\n    if (typeof candidate === \"string\") {\n      output.push(candidate);\n    }\n  }\n\n  if (\"reason\" in record) {\n    output.push(...collectErrorText(record.reason, seen));\n  }\n  if (\"error\" in record) {\n    output.push(...collectErrorText(record.error, seen));\n  }\n\n  return output;\n}\n\nfunction getEventTargetAssetUrl(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n\n  const target = (value as Event).target as\n    | (EventTarget & { src?: string; href?: string; tagName?: string })\n    | null\n    | undefined;\n  if (!target || typeof target !== \"object\") {\n    return undefined;\n  }\n\n  const tagName = typeof target.tagName === \"string\" ? target.tagName.toLowerCase() : \"\";\n  if (tagName !== \"script\" && tagName !== \"link\") {\n    return undefined;\n  }\n\n  return typeof target.src === \"string\" && target.src\n    ? target.src\n    : typeof target.href === \"string\" && target.href\n      ? target.href\n      : undefined;\n}\n\nfunction getStorage(options: FarmChunkRecoveryOptions) {\n  if (\"storage\" in options) {\n    return options.storage;\n  }\n\n  try {\n    return window.sessionStorage;\n  } catch {\n    return null;\n  }\n}\n\nfunction getStorageKey(options: FarmChunkRecoveryOptions): string {\n  if (options.storageKey) {\n    return options.storageKey;\n  }\n\n  const location = getLocation(options);\n  return `${STORAGE_KEY_PREFIX}${location.pathname}${location.search}`;\n}\n\nfunction getLocation(options: FarmChunkRecoveryOptions) {\n  return options.location ?? window.location;\n}\n\nfunction getReload(options: FarmChunkRecoveryOptions): () => void {\n  if (options.reload) {\n    return options.reload;\n  }\n\n  const location = getLocation(options);\n  return () => location.reload();\n}\n\nfunction getNow(options: FarmChunkRecoveryOptions): number {\n  return options.now ? options.now() : Date.now();\n}\n","\"use client\";\n\nimport {\n  originalPositionFor,\n  sourceContentFor,\n  TraceMap,\n  type SourceMapInput,\n} from \"@jridgewell/trace-mapping\";\nimport { DEFAULT_ERROR_STYLES } from \"../components/error-styles\";\nimport { FARM_VERSION } from \"../version\";\nimport { isChunkLoadError } from \"./chunk-recovery\";\n\nexport interface FarmRuntimeErrorLocation {\n  href: string;\n  pathname: string;\n  search: string;\n  hash: string;\n}\n\nexport interface FarmRuntimeErrorOverlayContext {\n  phase: string;\n  location: FarmRuntimeErrorLocation;\n  sourceEvent?: Event;\n}\n\nexport interface FarmRuntimeErrorOverlayOptions {\n  window: Window;\n  farmVersion?: string;\n  reload?: () => void;\n  fetch?: typeof fetch;\n}\n\nexport interface FarmRuntimeErrorOverlay {\n  show(error: unknown, context: FarmRuntimeErrorOverlayContext): void;\n  dismiss(): void;\n  destroy(): void;\n}\n\ninterface NormalizedRuntimeError {\n  name: string;\n  message: string;\n  stack?: string;\n}\n\ninterface BrowserSourceLocation {\n  url: string;\n  displayPath: string;\n  line: number;\n  column: number;\n  stackLine?: string;\n}\n\ninterface BrowserSourceLine {\n  number?: number;\n  content: string;\n  highlight?: boolean;\n}\n\ninterface BrowserSourceFrame {\n  path: string;\n  line?: number;\n  column?: number;\n  lines: BrowserSourceLine[];\n  unavailable?: boolean;\n}\n\ninterface RuntimeErrorRecord {\n  error: NormalizedRuntimeError;\n  context: FarmRuntimeErrorOverlayContext;\n  fingerprint: string;\n  occurrences: number;\n  sourceLocation?: BrowserSourceLocation;\n  sourceFrame: BrowserSourceFrame;\n}\n\nconst OVERLAY_STYLES = `\n:host {\n  position: fixed;\n  inset: 0;\n  z-index: 2147483647;\n  display: block;\n  width: 100%;\n  height: 100%;\n  /* Owned by the overlay: the default error page's source marker is a neutral\n     accent, but the overlay uses this to mark the expression that threw. */\n  --farm-runtime-error-inline-code: #f87171;\n}\n\n@media (prefers-color-scheme: light) {\n  :host {\n    --farm-runtime-error-inline-code: #b91c1c;\n  }\n}\n\n:host([hidden]) {\n  display: none;\n}\n\n.farm-runtime-error__viewport {\n  width: 100%;\n  height: 100%;\n  overflow: auto;\n  overscroll-behavior: contain;\n}\n\n.farm-runtime-error__viewport .farm-default-error {\n  min-height: 100%;\n  padding: clamp(22px, 4vh, 36px) 24px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__code {\n  font-size: clamp(96px, 10vw, 120px);\n  line-height: 0.92;\n}\n\n.farm-runtime-error__viewport .farm-default-error__eyebrow {\n  margin-top: 22px;\n  margin-bottom: 18px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__summary {\n  margin-bottom: 20px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__row {\n  min-height: 48px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__details {\n  padding-top: 16px;\n  padding-bottom: 14px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__details-header {\n  margin-bottom: 8px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__source-path {\n  padding-top: 9px;\n  padding-bottom: 9px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__source-code {\n  padding-top: 6px;\n  padding-bottom: 6px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__meta {\n  margin-top: 10px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__actions {\n  margin-top: 20px;\n}\n\n.farm-runtime-error__occurrences {\n  display: inline-flex;\n  align-items: center;\n  min-height: 24px;\n  margin-right: auto;\n  padding: 0 8px;\n  border: 1px solid var(--farm-error-line);\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 10px;\n  font-weight: 600;\n  letter-spacing: 0.08em;\n  text-transform: uppercase;\n}\n\n.farm-runtime-error__occurrences[hidden],\n.farm-runtime-error__action[hidden] {\n  display: none;\n}\n\n.farm-runtime-error__copy {\n  min-width: 166px;\n}\n\n.farm-runtime-error__action:focus {\n  outline: 1px solid var(--farm-error-fg);\n  outline-offset: 2px;\n}\n\n.farm-runtime-error__viewport .farm-default-error__panel {\n  border: 0;\n  box-shadow: inset 0 0 0 0.5px var(--farm-error-line-strong);\n}\n\n.farm-runtime-error__github-icon {\n  display: block;\n  width: 18px;\n  height: 18px;\n  flex: 0 0 auto;\n  margin-right: 10px;\n  color: currentColor;\n}\n\n.farm-runtime-error__message-value {\n  font-family: var(--farm-error-font-sans);\n}\n\n.farm-runtime-error__inline-code {\n  color: var(--farm-runtime-error-inline-code);\n  font-family: var(--farm-error-font-mono);\n  font-size: 0.94em;\n  font-weight: 600;\n  line-height: inherit;\n  overflow-wrap: anywhere;\n}\n\n@media (max-width: 620px) {\n  .farm-runtime-error__occurrences {\n    margin-right: 0;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__content,\n  .farm-runtime-error__viewport .farm-default-error__panel,\n  .farm-runtime-error__viewport .farm-default-error__details,\n  .farm-runtime-error__viewport .farm-default-error__source,\n  .farm-runtime-error__viewport .farm-default-error__actions {\n    min-width: 0;\n    max-width: 100%;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__actions {\n    width: 100%;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__action {\n    min-width: 0;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__code {\n    font-size: 80px;\n  }\n}\n\n@media (max-height: 760px) {\n  .farm-runtime-error__viewport .farm-default-error {\n    place-items: start center;\n    padding-top: 12px;\n    padding-bottom: 12px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__code {\n    font-size: 88px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__eyebrow {\n    margin-top: 14px;\n    margin-bottom: 12px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__summary {\n    margin-bottom: 14px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__row {\n    min-height: 42px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__details {\n    padding-top: 12px;\n    padding-bottom: 10px;\n  }\n\n  .farm-runtime-error__viewport .farm-default-error__actions {\n    /* The redesigned page is taller than a short window. Rather than shrink it\n       until it is unreadable, keep the recovery controls pinned to the bottom\n       so they stay reachable while the rest of the report scrolls under them. */\n    position: sticky;\n    bottom: 0;\n    z-index: 1;\n    margin-top: 10px;\n    padding: 10px 0;\n    background: var(--farm-error-bg);\n  }\n}\n`;\n\nconst OVERLAY_MARKUP = `\n<div class=\"farm-runtime-error__viewport\" data-farm-runtime-error-viewport>\n  <main class=\"farm-default-error\" data-farm-runtime-error role=\"alertdialog\" aria-modal=\"true\" aria-labelledby=\"farm-runtime-error-title\" aria-describedby=\"farm-runtime-error-description\">\n    <div class=\"farm-default-error__content\">\n      <p class=\"farm-default-error__code\" aria-hidden=\"true\">500</p>\n      <p class=\"farm-default-error__eyebrow\">Runtime error</p>\n      <header class=\"farm-default-error__summary\">\n        <h1 id=\"farm-runtime-error-title\" class=\"farm-default-error__title\">Application failed in the browser</h1>\n      </header>\n      <section class=\"farm-default-error__panel\" aria-label=\"Error information\">\n        <div class=\"farm-default-error__row\">\n          <span class=\"farm-default-error__label\">Error type</span>\n          <span class=\"farm-default-error__value\" data-farm-runtime-error-type></span>\n        </div>\n        <div class=\"farm-default-error__row\">\n          <span class=\"farm-default-error__label\">Error message</span>\n          <span id=\"farm-runtime-error-description\" class=\"farm-default-error__value farm-runtime-error__message-value\" data-farm-runtime-error-message></span>\n        </div>\n        <div class=\"farm-default-error__row\">\n          <span class=\"farm-default-error__label\">Location</span>\n          <span class=\"farm-default-error__value\" data-farm-runtime-error-location></span>\n        </div>\n        <section class=\"farm-default-error__details\" aria-labelledby=\"farm-runtime-error-details-title\">\n          <div class=\"farm-default-error__details-header\">\n            <h2 id=\"farm-runtime-error-details-title\" class=\"farm-default-error__details-title\">Details</h2>\n            <span class=\"farm-runtime-error__occurrences\" data-farm-runtime-error-occurrences hidden></span>\n            <button class=\"farm-default-error__copy farm-runtime-error__copy\" type=\"button\" data-farm-runtime-error-copy>\n              <span data-farm-runtime-error-copy-label>Copy debug report</span>\n              <span class=\"farm-default-error__sr-only\" aria-live=\"polite\" data-farm-runtime-error-copy-status></span>\n            </button>\n          </div>\n          <div data-farm-runtime-error-source></div>\n          <p class=\"farm-default-error__meta\" data-farm-runtime-error-meta></p>\n        </section>\n      </section>\n      <div class=\"farm-default-error__actions\">\n        <a class=\"farm-default-error__action farm-default-error__action--primary farm-runtime-error__action\" data-farm-runtime-error-issue target=\"_blank\" rel=\"noopener noreferrer\"><svg class=\"farm-runtime-error__github-icon\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M12 .7a11.5 11.5 0 0 0-3.64 22.41c.58.1.79-.25.79-.56v-2.23c-3.22.7-3.9-1.37-3.9-1.37-.52-1.34-1.28-1.69-1.28-1.69-1.05-.72.08-.7.08-.7 1.16.08 1.77 1.19 1.77 1.19 1.03 1.77 2.7 1.26 3.36.96.1-.75.4-1.26.73-1.55-2.57-.29-5.27-1.29-5.27-5.68 0-1.26.45-2.28 1.18-3.09-.12-.29-.51-1.47.11-3.05 0 0 .96-.31 3.16 1.18A10.95 10.95 0 0 1 12 6.1c.98 0 1.95.13 2.87.39 2.2-1.49 3.16-1.18 3.16-1.18.62 1.58.23 2.76.11 3.05.74.81 1.18 1.83 1.18 3.09 0 4.4-2.71 5.38-5.29 5.67.42.36.79 1.07.79 2.16v3.27c0 .31.21.67.8.56A11.5 11.5 0 0 0 12 .7Z\" /></svg><span>Open GitHub issue</span></a>\n        <button class=\"farm-default-error__action farm-runtime-error__action\" type=\"button\" data-farm-runtime-error-reload>Reload page</button>\n        <button class=\"farm-default-error__action farm-runtime-error__action\" type=\"button\" data-farm-runtime-error-dismiss>Dismiss</button>\n      </div>\n    </div>\n  </main>\n</div>\n`;\n\nclass DefaultFarmRuntimeErrorOverlay implements FarmRuntimeErrorOverlay {\n  private readonly options: FarmRuntimeErrorOverlayOptions;\n  private readonly document: Document;\n  private readonly host: HTMLDivElement;\n  private readonly shadow: ShadowRoot;\n  private readonly dismissedFingerprints = new Set<string>();\n  private readonly themeObserver: MutationObserver;\n  private readonly colorSchemeQuery?: MediaQueryList;\n  private current?: RuntimeErrorRecord;\n  private previousFocus?: Element | null;\n  private renderSequence = 0;\n  private copyResetTimer?: number;\n  private destroyed = false;\n\n  constructor(options: FarmRuntimeErrorOverlayOptions) {\n    this.options = options;\n    this.document = options.window.document;\n    this.host = this.document.createElement(\"div\");\n    this.host.dataset.farmRuntimeErrorOverlay = \"\";\n    this.host.hidden = true;\n    this.shadow = this.host.attachShadow({ mode: \"open\" });\n    this.shadow.innerHTML = `<style>${DEFAULT_ERROR_STYLES}${OVERLAY_STYLES}</style>${OVERLAY_MARKUP}`;\n\n    this.getElement<HTMLButtonElement>(\"[data-farm-runtime-error-reload]\").addEventListener(\n      \"click\",\n      this.handleReload,\n    );\n    this.getElement<HTMLButtonElement>(\"[data-farm-runtime-error-dismiss]\").addEventListener(\n      \"click\",\n      this.handleDismiss,\n    );\n    this.getElement<HTMLButtonElement>(\"[data-farm-runtime-error-copy]\").addEventListener(\n      \"click\",\n      this.handleCopy,\n    );\n    this.shadow.addEventListener(\"keydown\", this.handleKeyDown);\n\n    this.themeObserver = new MutationObserver(this.updateTheme);\n    this.themeObserver.observe(this.document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"class\", \"data-theme\", \"data-color-scheme\", \"style\"],\n    });\n    if (this.document.body) {\n      this.themeObserver.observe(this.document.body, {\n        attributes: true,\n        attributeFilter: [\"class\", \"data-theme\", \"data-color-scheme\", \"style\"],\n      });\n    }\n\n    this.colorSchemeQuery = options.window.matchMedia?.(\"(prefers-color-scheme: dark)\");\n    this.colorSchemeQuery?.addEventListener?.(\"change\", this.updateTheme);\n    this.updateTheme();\n  }\n\n  show(errorLike: unknown, context: FarmRuntimeErrorOverlayContext): void {\n    if (this.destroyed || isChunkLoadError(errorLike) || isChunkLoadError(context.sourceEvent)) {\n      return;\n    }\n\n    const error = normalizeRuntimeError(errorLike);\n    const sourceLocation = resolveBrowserSourceLocation(\n      error,\n      context.sourceEvent,\n      this.options.window,\n    );\n    if (sourceLocation && isBrowserExtensionUrl(sourceLocation.url)) return;\n    if (isRecoverableReactHydrationError(error, context, sourceLocation)) return;\n\n    const fingerprint = createErrorFingerprint(error, context, sourceLocation);\n    if (this.dismissedFingerprints.has(fingerprint)) return;\n\n    if (this.current?.fingerprint === fingerprint) {\n      this.current.occurrences += 1;\n      this.renderOccurrences(this.current.occurrences);\n      return;\n    }\n\n    const record: RuntimeErrorRecord = {\n      error,\n      context,\n      fingerprint,\n      occurrences: 1,\n      sourceLocation,\n      sourceFrame: createFallbackSourceFrame(error, sourceLocation),\n    };\n    this.current = record;\n    const sequence = ++this.renderSequence;\n    this.render(record);\n    this.mount();\n\n    if (sourceLocation) {\n      void loadBrowserSourceFrame(sourceLocation, this.options)\n        .then((sourceFrame) => {\n          if (\n            !sourceFrame ||\n            this.destroyed ||\n            sequence !== this.renderSequence ||\n            this.current !== record\n          ) {\n            return;\n          }\n          record.sourceFrame = sourceFrame;\n          this.renderSourceFrame(sourceFrame);\n          this.renderIssueLink(record);\n        })\n        .catch(() => {});\n    }\n  }\n\n  dismiss(): void {\n    if (this.destroyed || this.host.hidden) return;\n    if (this.current) this.dismissedFingerprints.add(this.current.fingerprint);\n    this.host.hidden = true;\n    this.renderSequence += 1;\n    if (this.previousFocus instanceof HTMLElement && this.previousFocus.isConnected) {\n      this.previousFocus.focus();\n    }\n    this.previousFocus = undefined;\n  }\n\n  destroy(): void {\n    if (this.destroyed) return;\n    this.destroyed = true;\n    this.renderSequence += 1;\n    this.themeObserver.disconnect();\n    this.colorSchemeQuery?.removeEventListener?.(\"change\", this.updateTheme);\n    this.shadow.removeEventListener(\"keydown\", this.handleKeyDown);\n    if (this.copyResetTimer !== undefined) {\n      this.options.window.clearTimeout(this.copyResetTimer);\n    }\n    this.host.remove();\n    this.current = undefined;\n  }\n\n  private mount(): void {\n    if (!this.host.isConnected) {\n      (this.document.body || this.document.documentElement).appendChild(this.host);\n    }\n    const wasHidden = this.host.hidden;\n    this.host.hidden = false;\n    if (wasHidden) {\n      this.previousFocus = this.document.activeElement;\n      this.options.window.setTimeout(() => {\n        if (!this.host.hidden && !this.destroyed) {\n          this.getElement<HTMLAnchorElement>(\"[data-farm-runtime-error-issue]\").focus({\n            preventScroll: true,\n          });\n        }\n      }, 0);\n    }\n  }\n\n  private render(record: RuntimeErrorRecord): void {\n    this.getElement(\"[data-farm-runtime-error-type]\").textContent = formatErrorType(\n      record.error,\n      record.context.phase,\n    );\n    renderErrorMessage(\n      this.getElement(\"[data-farm-runtime-error-message]\"),\n      record.error.message,\n      this.document,\n    );\n    this.getElement(\"[data-farm-runtime-error-location]\").textContent =\n      `${record.context.location.pathname}${record.context.location.search}` || \"/\";\n    this.getElement(\"[data-farm-runtime-error-meta]\").textContent =\n      `Farm.js v${this.options.farmVersion || FARM_VERSION} · development · browser`;\n    this.renderIssueLink(record);\n    this.renderOccurrences(record.occurrences);\n    this.renderSourceFrame(record.sourceFrame);\n    this.resetCopyStatus();\n  }\n\n  private renderOccurrences(occurrences: number): void {\n    const badge = this.getElement<HTMLElement>(\"[data-farm-runtime-error-occurrences]\");\n    badge.hidden = occurrences < 2;\n    badge.textContent = occurrences < 2 ? \"\" : `Repeated ×${occurrences}`;\n  }\n\n  private renderIssueLink(record: RuntimeErrorRecord): void {\n    this.getElement<HTMLAnchorElement>(\"[data-farm-runtime-error-issue]\").href =\n      createGithubIssueUrl(record, this.options.window, this.options.farmVersion || FARM_VERSION);\n  }\n\n  private renderSourceFrame(sourceFrame: BrowserSourceFrame): void {\n    const container = this.getElement<HTMLElement>(\"[data-farm-runtime-error-source]\");\n    container.replaceChildren();\n\n    const source = this.document.createElement(\"div\");\n    source.className = \"farm-default-error__source\";\n\n    const path = this.document.createElement(\"p\");\n    path.className = \"farm-default-error__source-path\";\n    path.textContent = formatSourcePath(sourceFrame);\n    source.appendChild(path);\n\n    const pre = this.document.createElement(\"pre\");\n    pre.className = \"farm-default-error__source-code\";\n    pre.tabIndex = 0;\n    const code = this.document.createElement(\"code\");\n    for (const line of sourceFrame.lines) {\n      const row = this.document.createElement(\"span\");\n      row.className = `farm-default-error__source-line${line.highlight ? \" farm-default-error__source-line--active\" : \"\"}`;\n\n      const gutter = this.document.createElement(\"span\");\n      gutter.className = \"farm-default-error__source-gutter\";\n      gutter.textContent = `${line.highlight ? \">\" : \" \"} ${line.number ?? \"\"}`;\n\n      const text = this.document.createElement(\"span\");\n      text.className = \"farm-default-error__source-text\";\n      text.textContent = line.content || \" \";\n\n      row.append(gutter, text);\n      code.appendChild(row);\n    }\n    pre.appendChild(code);\n    source.appendChild(pre);\n    container.appendChild(source);\n  }\n\n  private readonly handleReload = () => {\n    (this.options.reload || (() => this.options.window.location.reload()))();\n  };\n\n  private readonly handleDismiss = () => {\n    this.dismiss();\n  };\n\n  private readonly handleCopy = async () => {\n    if (!this.current) return;\n    const report = createFarmRuntimeErrorDebugReport(\n      this.current,\n      this.options.window,\n      this.options.farmVersion || FARM_VERSION,\n    );\n    const label = this.getElement<HTMLElement>(\"[data-farm-runtime-error-copy-label]\");\n    const status = this.getElement<HTMLElement>(\"[data-farm-runtime-error-copy-status]\");\n\n    try {\n      await copyText(report, this.options.window, this.document);\n      label.textContent = \"Copied\";\n      status.textContent = \"Debug report copied\";\n      if (this.copyResetTimer !== undefined) {\n        this.options.window.clearTimeout(this.copyResetTimer);\n      }\n      this.copyResetTimer = this.options.window.setTimeout(() => this.resetCopyStatus(), 1800);\n    } catch {\n      status.textContent = \"Unable to copy the debug report\";\n    }\n  };\n\n  private readonly handleKeyDown = (event: Event) => {\n    const keyboardEvent = event as KeyboardEvent;\n    if (keyboardEvent.key === \"Escape\") {\n      keyboardEvent.preventDefault();\n      this.dismiss();\n      return;\n    }\n    if (keyboardEvent.key !== \"Tab\") return;\n\n    const controls = Array.from(\n      this.shadow.querySelectorAll<HTMLElement>(\"a[href], button:not([hidden]):not([disabled])\"),\n    );\n    if (controls.length === 0) return;\n    const first = controls[0];\n    const last = controls[controls.length - 1];\n    const active = this.shadow.activeElement;\n\n    if (keyboardEvent.shiftKey && active === first) {\n      keyboardEvent.preventDefault();\n      last.focus();\n    } else if (!keyboardEvent.shiftKey && active === last) {\n      keyboardEvent.preventDefault();\n      first.focus();\n    }\n  };\n\n  private readonly updateTheme = () => {\n    this.getElement<HTMLElement>(\"[data-farm-runtime-error-viewport]\").dataset.theme =\n      resolveDocumentTheme(this.document, this.options.window);\n  };\n\n  private resetCopyStatus(): void {\n    this.getElement(\"[data-farm-runtime-error-copy-label]\").textContent = \"Copy debug report\";\n    this.getElement(\"[data-farm-runtime-error-copy-status]\").textContent = \"\";\n  }\n\n  private getElement<T extends Element = HTMLElement>(selector: string): T {\n    const element = this.shadow.querySelector<T>(selector);\n    if (!element) throw new Error(`Farm runtime error overlay is missing ${selector}`);\n    return element;\n  }\n}\n\nexport function createFarmRuntimeErrorOverlay(\n  options: FarmRuntimeErrorOverlayOptions,\n): FarmRuntimeErrorOverlay {\n  return new DefaultFarmRuntimeErrorOverlay(options);\n}\n\nfunction normalizeRuntimeError(errorLike: unknown): NormalizedRuntimeError {\n  if (errorLike instanceof Error) {\n    return {\n      name: errorLike.name || \"Error\",\n      message: errorLike.message || \"An unknown browser error occurred.\",\n      stack: errorLike.stack,\n    };\n  }\n\n  if (errorLike && typeof errorLike === \"object\") {\n    const error = errorLike as Record<string, unknown>;\n    const name = typeof error.name === \"string\" && error.name ? error.name : \"Error\";\n    const message =\n      typeof error.message === \"string\" && error.message\n        ? error.message\n        : typeof error.reason === \"string\" && error.reason\n          ? error.reason\n          : stringifyUnknown(errorLike);\n    return {\n      name,\n      message: message || \"An unknown browser error occurred.\",\n      stack: typeof error.stack === \"string\" ? error.stack : undefined,\n    };\n  }\n\n  return {\n    name: \"Error\",\n    message: stringifyUnknown(errorLike) || \"An unknown browser error occurred.\",\n  };\n}\n\nfunction stringifyUnknown(value: unknown): string {\n  if (typeof value === \"string\") return value;\n  if (value == null) return \"\";\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n\nfunction resolveBrowserSourceLocation(\n  error: NormalizedRuntimeError,\n  sourceEvent: Event | undefined,\n  clientWindow: Window,\n): BrowserSourceLocation | undefined {\n  if (sourceEvent && \"filename\" in sourceEvent) {\n    const event = sourceEvent as ErrorEvent;\n    if (event.filename && event.lineno) {\n      return createSourceLocation(event.filename, event.lineno, event.colno || 1, clientWindow);\n    }\n  }\n\n  if (!error.stack) return undefined;\n  for (const stackLine of error.stack.split(\"\\n\").slice(1)) {\n    const match = stackLine\n      .trim()\n      .match(/\\(?((?:[a-z][a-z\\d+.-]*):\\/\\/[^)\\s]+|\\/[^)\\s]+):(\\d+):(\\d+)\\)?$/i);\n    if (!match) continue;\n    return {\n      ...createSourceLocation(match[1], Number(match[2]), Number(match[3]), clientWindow),\n      stackLine: stackLine.trim(),\n    };\n  }\n  return undefined;\n}\n\nfunction createSourceLocation(\n  url: string,\n  line: number,\n  column: number,\n  clientWindow: Window,\n): BrowserSourceLocation {\n  let displayPath = url;\n  try {\n    const parsed = new URL(url, clientWindow.location.href);\n    displayPath = parsed.origin === clientWindow.location.origin ? parsed.pathname : parsed.href;\n  } catch {}\n\n  return { url, displayPath, line, column };\n}\n\nfunction createFallbackSourceFrame(\n  error: NormalizedRuntimeError,\n  location?: BrowserSourceLocation,\n): BrowserSourceFrame {\n  const firstStackLine =\n    location?.stackLine || error.stack?.split(\"\\n\").find((line) => line.trim().startsWith(\"at \"));\n  return {\n    path: location?.displayPath || \"Browser stack\",\n    line: location?.line,\n    column: location?.column,\n    unavailable: true,\n    lines: [\n      {\n        number: location?.line,\n        content: firstStackLine?.trim() || error.message,\n        highlight: true,\n      },\n    ],\n  };\n}\n\nasync function loadBrowserSourceFrame(\n  location: BrowserSourceLocation,\n  options: FarmRuntimeErrorOverlayOptions,\n): Promise<BrowserSourceFrame | undefined> {\n  const request = options.fetch || options.window.fetch?.bind(options.window);\n  if (!request) return undefined;\n\n  let sourceUrl: URL;\n  try {\n    sourceUrl = new URL(location.url, options.window.location.href);\n  } catch {\n    return undefined;\n  }\n  if (\n    sourceUrl.origin !== options.window.location.origin ||\n    (sourceUrl.protocol !== \"http:\" && sourceUrl.protocol !== \"https:\")\n  ) {\n    return undefined;\n  }\n\n  try {\n    const response = await request(sourceUrl.href, {\n      headers: { Accept: \"text/plain, application/javascript\" },\n    });\n    if (!response.ok) return undefined;\n    const source = await response.text();\n    if (source.length > 1_000_000) return undefined;\n\n    const mappedFrame = await createMappedSourceFrame(\n      source,\n      sourceUrl,\n      location,\n      request,\n      options.window,\n    );\n    if (mappedFrame) return mappedFrame;\n\n    return createSourceFrame(source, location.displayPath, location.line, location.column);\n  } catch {\n    return undefined;\n  }\n}\n\nasync function createMappedSourceFrame(\n  generatedSource: string,\n  generatedUrl: URL,\n  location: BrowserSourceLocation,\n  request: typeof fetch,\n  clientWindow: Window,\n): Promise<BrowserSourceFrame | undefined> {\n  const traceMap = await loadTraceMap(generatedSource, generatedUrl, request, clientWindow);\n  if (!traceMap) return undefined;\n\n  const original = originalPositionFor(traceMap, {\n    line: location.line,\n    column: Math.max(0, location.column - 1),\n  });\n  if (!original.source || original.line == null) return undefined;\n\n  const originalSource = sourceContentFor(traceMap, original.source);\n  if (originalSource == null) return undefined;\n\n  const originalLines = originalSource.split(/\\r?\\n/);\n  const generatedLine = generatedSource.split(/\\r?\\n/)[location.line - 1] || \"\";\n  const line = refineOriginalLine(generatedLine, originalLines, original.line);\n  const lineContent = originalLines[line - 1] || \"\";\n  const trimmedGeneratedLine = generatedLine.trim();\n  const column =\n    line !== original.line && trimmedGeneratedLine && lineContent.includes(trimmedGeneratedLine)\n      ? lineContent.indexOf(trimmedGeneratedLine) + 1\n      : (original.column ?? 0) + 1;\n\n  return createSourceFrame(\n    originalSource,\n    formatDisplaySourceUrl(original.source, clientWindow),\n    line,\n    column,\n  );\n}\n\nasync function loadTraceMap(\n  generatedSource: string,\n  generatedUrl: URL,\n  request: typeof fetch,\n  clientWindow: Window,\n): Promise<TraceMap | undefined> {\n  const matches = Array.from(generatedSource.matchAll(/\\/\\/[#@]\\s*sourceMappingURL=([^\\s]+)/g));\n  const reference = matches[matches.length - 1]?.[1];\n  if (!reference) return undefined;\n\n  let sourceMapJson: string;\n  if (reference.startsWith(\"data:\")) {\n    sourceMapJson = decodeSourceMapDataUrl(reference, clientWindow);\n  } else {\n    const sourceMapUrl = new URL(reference, generatedUrl);\n    if (sourceMapUrl.origin !== clientWindow.location.origin) return undefined;\n    const response = await request(sourceMapUrl.href, {\n      headers: { Accept: \"application/json, text/plain\" },\n    });\n    if (!response.ok) return undefined;\n    sourceMapJson = await response.text();\n    if (sourceMapJson.length > 2_000_000) return undefined;\n  }\n\n  return new TraceMap(JSON.parse(sourceMapJson) as SourceMapInput, generatedUrl.href);\n}\n\nfunction decodeSourceMapDataUrl(value: string, clientWindow: Window): string {\n  const separator = value.indexOf(\",\");\n  if (separator < 0) throw new Error(\"Invalid inline source map\");\n  const metadata = value.slice(0, separator);\n  const payload = value.slice(separator + 1);\n  if (!metadata.includes(\";base64\")) return decodeURIComponent(payload);\n\n  const binary = clientWindow.atob(payload);\n  const bytes = new Uint8Array(binary.length);\n  for (let index = 0; index < binary.length; index += 1) {\n    bytes[index] = binary.charCodeAt(index);\n  }\n  return new TextDecoder().decode(bytes);\n}\n\nfunction refineOriginalLine(\n  generatedLine: string,\n  originalLines: string[],\n  mappedLine: number,\n): number {\n  const normalizedGeneratedLine = normalizeSourceLine(generatedLine);\n  if (normalizedGeneratedLine.length < 8) return mappedLine;\n\n  let bestMatch = mappedLine;\n  let bestDistance = Number.POSITIVE_INFINITY;\n  for (let index = 0; index < originalLines.length; index += 1) {\n    if (normalizeSourceLine(originalLines[index]) !== normalizedGeneratedLine) continue;\n    const line = index + 1;\n    const distance = Math.abs(line - mappedLine);\n    if (distance < bestDistance) {\n      bestMatch = line;\n      bestDistance = distance;\n    }\n  }\n  return bestMatch;\n}\n\nfunction normalizeSourceLine(value: string): string {\n  return value.trim().replace(/\\s+/g, \" \");\n}\n\nfunction createSourceFrame(\n  source: string,\n  path: string,\n  line: number,\n  column: number,\n): BrowserSourceFrame | undefined {\n  const lines = source.split(/\\r?\\n/);\n  if (line < 1 || line > lines.length) return undefined;\n  const start = Math.max(1, line - 2);\n  const end = Math.min(lines.length, line + 2);\n  const frameLines: BrowserSourceLine[] = [];\n  for (let number = start; number <= end; number += 1) {\n    frameLines.push({\n      number,\n      content: lines[number - 1] || \" \",\n      highlight: number === line,\n    });\n  }\n\n  return { path, line, column, lines: frameLines };\n}\n\nfunction formatDisplaySourceUrl(url: string, clientWindow: Window): string {\n  try {\n    const parsed = new URL(url, clientWindow.location.href);\n    return parsed.origin === clientWindow.location.origin ? parsed.pathname : parsed.href;\n  } catch {\n    return url.replace(/[?#].*$/, \"\");\n  }\n}\n\nfunction isBrowserExtensionUrl(url: string): boolean {\n  try {\n    return [\n      \"chrome-extension:\",\n      \"moz-extension:\",\n      \"safari-web-extension:\",\n      \"ms-browser-extension:\",\n    ].includes(new URL(url).protocol);\n  } catch {\n    return /^(?:chrome|moz|safari-web|ms-browser)-extension:\\/\\//i.test(url);\n  }\n}\n\nfunction isRecoverableReactHydrationError(\n  error: NormalizedRuntimeError,\n  context: FarmRuntimeErrorOverlayContext,\n  location?: BrowserSourceLocation,\n): boolean {\n  if (context.phase !== \"window\") return false;\n\n  const isKnownRecoverableMessage = [\n    /^Hydration failed because the server rendered (?:text|HTML) didn't match the client\\b/i,\n    /^Text content does not match server-rendered HTML\\b/i,\n    /^There was an error while hydrating but React was able to recover\\b/i,\n  ].some((pattern) => pattern.test(error.message));\n  if (!isKnownRecoverableMessage) return false;\n\n  return /(?:react-dom(?:_client)?(?:\\.development)?\\.js|react-dom\\/|throwOnHydrationMismatch|onRecoverableError)/i.test(\n    `${location?.url || \"\"}\\n${error.stack || \"\"}`,\n  );\n}\n\nfunction renderErrorMessage(container: Element, message: string, document: Document): void {\n  const fragments: Node[] = [];\n  const codePattern = /`([^`\\n]+)`|\\b[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*){2,}\\b/g;\n  let offset = 0;\n\n  for (const match of message.matchAll(codePattern)) {\n    const index = match.index ?? 0;\n    if (index > offset) fragments.push(document.createTextNode(message.slice(offset, index)));\n\n    const code = document.createElement(\"code\");\n    code.className = \"farm-runtime-error__inline-code\";\n    code.textContent = match[1] || match[0];\n    fragments.push(code);\n    offset = index + match[0].length;\n  }\n\n  if (offset < message.length) fragments.push(document.createTextNode(message.slice(offset)));\n  container.replaceChildren(...fragments);\n}\n\nfunction createErrorFingerprint(\n  error: NormalizedRuntimeError,\n  context: FarmRuntimeErrorOverlayContext,\n  location?: BrowserSourceLocation,\n): string {\n  return [\n    context.phase,\n    context.location.pathname,\n    error.name,\n    error.message,\n    location?.displayPath || \"\",\n    location?.line || \"\",\n    error.stack?.split(\"\\n\")[1]?.trim() || \"\",\n  ].join(\"\\u0000\");\n}\n\nfunction formatPhase(phase: string): string {\n  return phase\n    .replace(/^plugin:/, \"Plugin · \")\n    .replace(/-/g, \" \")\n    .replace(/\\b\\w/g, (character) => character.toUpperCase());\n}\n\nfunction formatErrorType(error: NormalizedRuntimeError, phase: string): string {\n  const category =\n    phase === \"hydration\"\n      ? \"Hydration\"\n      : phase === \"navigation\"\n        ? \"Navigation\"\n        : phase === \"setup\" || phase.startsWith(\"plugin:\")\n          ? \"Plugin\"\n          : phase === \"performance\"\n            ? \"Performance\"\n            : \"Runtime\";\n  const name = error.name.trim() || \"Error\";\n  return `${category} ${name}`;\n}\n\nfunction formatSourcePath(sourceFrame: BrowserSourceFrame): string {\n  if (!sourceFrame.line) return sourceFrame.path;\n  return `${sourceFrame.path}:${sourceFrame.line}:${sourceFrame.column || 1}${\n    sourceFrame.unavailable ? \" · source preview unavailable\" : \"\"\n  }`;\n}\n\nfunction resolveDocumentTheme(document: Document, clientWindow: Window): \"light\" | \"dark\" {\n  for (const element of [document.documentElement, document.body]) {\n    if (!element) continue;\n    const explicit =\n      element.getAttribute(\"data-theme\") || element.getAttribute(\"data-color-scheme\");\n    if (explicit === \"dark\" || element.classList.contains(\"dark\")) return \"dark\";\n    if (explicit === \"light\" || element.classList.contains(\"light\")) return \"light\";\n  }\n\n  const colorScheme = clientWindow.getComputedStyle?.(document.documentElement).colorScheme;\n  if (colorScheme?.includes(\"dark\") && !colorScheme.includes(\"light\")) return \"dark\";\n  return clientWindow.matchMedia?.(\"(prefers-color-scheme: dark)\").matches ? \"dark\" : \"light\";\n}\n\nfunction createFarmRuntimeErrorDebugReport(\n  record: RuntimeErrorRecord,\n  clientWindow: Window,\n  farmVersion: string,\n): string {\n  const source = record.sourceFrame.lines\n    .map(\n      (line) =>\n        `${line.highlight ? \">\" : \" \"} ${line.number ? String(line.number).padStart(4, \" \") : \"    \"} | ${line.content}`,\n    )\n    .join(\"\\n\");\n  const viewport = `${clientWindow.innerWidth}×${clientWindow.innerHeight}`;\n\n  return [\n    \"# Farm.js client runtime debug report\",\n    \"\",\n    \"## Error\",\n    `- Type: ${formatErrorType(record.error, record.context.phase)}`,\n    `- Message: ${record.error.message}`,\n    `- Phase: ${formatPhase(record.context.phase)}`,\n    `- Page: ${record.context.location.href}`,\n    `- Occurrences: ${record.occurrences}`,\n    \"\",\n    \"## Browser runtime\",\n    `- Farm.js: ${farmVersion}`,\n    `- User agent: ${clientWindow.navigator.userAgent}`,\n    `- Viewport: ${viewport}`,\n    `- Online: ${clientWindow.navigator.onLine === false ? \"no\" : \"yes\"}`,\n    \"\",\n    \"## Source\",\n    `\\`${formatSourcePath(record.sourceFrame)}\\``,\n    \"\",\n    \"```text\",\n    source,\n    \"```\",\n    \"\",\n    \"## Stack trace\",\n    \"```text\",\n    record.error.stack || \"Stack trace unavailable.\",\n    \"```\",\n    \"\",\n    \"## Diagnostic request\",\n    \"Identify the most likely root cause from the message, source frame, and stack trace. Explain the smallest safe fix and how to verify it.\",\n  ].join(\"\\n\");\n}\n\nfunction createGithubIssueUrl(\n  record: RuntimeErrorRecord,\n  clientWindow: Window,\n  farmVersion: string,\n): string {\n  const source = record.sourceFrame.lines\n    .map(\n      (line) =>\n        `${line.highlight ? \">\" : \" \"} ${line.number ? String(line.number).padStart(4, \" \") : \"    \"} | ${line.content}`,\n    )\n    .join(\"\\n\");\n  const body = truncateText(\n    [\n      \"## Runtime error report\",\n      \"\",\n      \"> This report was prefilled by the Farm.js development error overlay. Review it and remove sensitive information before submitting.\",\n      \"\",\n      \"### Error\",\n      `- Type: ${formatErrorType(record.error, record.context.phase)}`,\n      `- Message: ${record.error.message}`,\n      `- Phase: ${formatPhase(record.context.phase)}`,\n      `- Page path: ${record.context.location.pathname}`,\n      `- Occurrences: ${record.occurrences}`,\n      `- Farm.js: ${farmVersion}`,\n      `- Browser: ${clientWindow.navigator.userAgent}`,\n      `- Viewport: ${clientWindow.innerWidth}×${clientWindow.innerHeight}`,\n      `- Online: ${clientWindow.navigator.onLine === false ? \"no\" : \"yes\"}`,\n      \"\",\n      \"### Source\",\n      `\\`${formatSourcePath(record.sourceFrame)}\\``,\n      \"\",\n      \"```text\",\n      source,\n      \"```\",\n      \"\",\n      \"### Stack trace\",\n      \"```text\",\n      record.error.stack || \"Stack trace unavailable.\",\n      \"```\",\n      \"\",\n      \"### Expected behavior\",\n      \"Describe what you expected to happen and the steps needed to reproduce the failure.\",\n      \"\",\n      \"### Diagnostic request\",\n      \"Identify the most likely root cause from the message, source frame, and stack trace. Explain the smallest safe fix and how to verify it.\",\n    ].join(\"\\n\"),\n    6_000,\n  );\n  const issueUrl = new URL(\"https://github.com/farming-labs/farm.js/issues/new\");\n  issueUrl.searchParams.set(\"title\", truncateText(`[runtime error] ${record.error.message}`, 120));\n  issueUrl.searchParams.set(\"body\", body);\n  return issueUrl.href;\n}\n\nfunction truncateText(value: string, maxLength: number): string {\n  if (value.length <= maxLength) return value;\n  return `${value.slice(0, maxLength - 24)}\\n\\n[report truncated]`;\n}\n\nasync function copyText(value: string, clientWindow: Window, document: Document): Promise<void> {\n  if (clientWindow.navigator.clipboard && clientWindow.isSecureContext) {\n    await clientWindow.navigator.clipboard.writeText(value);\n    return;\n  }\n\n  const area = document.createElement(\"textarea\");\n  area.value = value;\n  area.readOnly = true;\n  area.style.position = \"fixed\";\n  area.style.opacity = \"0\";\n  document.body.appendChild(area);\n  area.select();\n  const copied = document.execCommand(\"copy\");\n  area.remove();\n  if (!copied) throw new Error(\"Copy command was rejected\");\n}\n","/**\n * Shared styles for Farm's default HTTP error page.\n *\n * Kept framework-agnostic so the same fallback can be used by the development\n * renderer and generated production runtimes.\n */\nexport const DEFAULT_ERROR_STYLES = `\nbody {\n  margin: 0;\n  background: #080808;\n}\n\n.farm-default-error {\n  --farm-error-bg: #080808;\n  --farm-error-panel: #0d0d0d;\n  --farm-error-fg: #f3f3f3;\n  --farm-error-muted: #9a9a9a;\n  --farm-error-subtle: #6f6f6f;\n  --farm-error-line: rgba(255, 255, 255, 0.1);\n  --farm-error-line-strong: rgba(255, 255, 255, 0.2);\n  --farm-error-button-bg: #f1f1f1;\n  --farm-error-button-fg: #0a0a0a;\n  --farm-error-source-line: rgba(255, 255, 255, 0.055);\n  --farm-error-source-marker: #f3f3f3;\n  --farm-error-font-sans: \"Geist Variable\", \"Geist Sans\", Geist, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  --farm-error-font-mono: \"Geist Mono Variable\", \"Geist Mono\", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  color: var(--farm-error-fg);\n  background: var(--farm-error-bg);\n  font-family: var(--farm-error-font-sans);\n  font-synthesis: none;\n  color-scheme: dark;\n  text-rendering: optimizeLegibility;\n}\n\n.farm-default-error,\n.farm-default-error * {\n  box-sizing: border-box;\n}\n\n.farm-default-error__frame {\n  width: min(100%, 1180px);\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  grid-template-rows: auto minmax(0, 1fr) auto;\n  margin: 0 auto;\n  padding: clamp(24px, 4vw, 52px);\n}\n\n.farm-default-error__brand {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 11px;\n  font-weight: 520;\n  line-height: 1;\n  letter-spacing: 0.08em;\n}\n\n.farm-default-error__brand > span:first-child {\n  color: var(--farm-error-fg);\n}\n\n.farm-default-error__brand-divider,\n.farm-default-error__status-divider,\n.farm-default-error__footer-divider {\n  color: var(--farm-error-subtle);\n}\n\n.farm-default-error__content {\n  width: min(100%, 680px);\n  min-width: 0;\n  align-self: center;\n  margin: 0 auto;\n  padding: clamp(64px, 10vh, 112px) 0;\n}\n\n.farm-default-error--development .farm-default-error__content {\n  width: min(100%, 900px);\n}\n\n.farm-default-error > .farm-default-error__content {\n  align-self: center;\n  padding-right: 24px;\n  padding-left: 24px;\n}\n\n.farm-default-error__status,\n.farm-default-error__eyebrow {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin: 0 0 24px;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  font-weight: 520;\n  line-height: 1.4;\n  letter-spacing: 0.055em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__status-mark {\n  width: 6px;\n  height: 6px;\n  flex: 0 0 auto;\n  background: var(--farm-error-fg);\n}\n\n.farm-default-error__code {\n  margin: 0 0 18px;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-mono);\n  font-size: clamp(48px, 8vw, 72px);\n  font-weight: 540;\n  line-height: 0.95;\n  letter-spacing: -0.055em;\n}\n\n.farm-default-error__summary {\n  margin: 0;\n}\n\n.farm-default-error__title {\n  max-width: 680px;\n  margin: 0;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-sans);\n  font-size: clamp(36px, 5.2vw, 56px);\n  font-weight: 560;\n  line-height: 1.04;\n  letter-spacing: -0.052em;\n  text-wrap: balance;\n}\n\n.farm-default-error__message {\n  max-width: 590px;\n  margin: 18px 0 0;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-sans);\n  font-size: clamp(16px, 2vw, 19px);\n  line-height: 1.55;\n  letter-spacing: -0.012em;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__actions {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 10px;\n  margin-top: 30px;\n}\n\n.farm-default-error__action {\n  min-height: 44px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 17px;\n  border: 1px solid var(--farm-error-line-strong);\n  border-radius: 7px;\n  color: var(--farm-error-fg);\n  background: transparent;\n  font: inherit;\n  font-family: var(--farm-error-font-mono);\n  font-size: 13px;\n  font-weight: 560;\n  line-height: 1;\n  letter-spacing: 0.015em;\n  text-decoration: none;\n  cursor: pointer;\n  transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out, transform 100ms ease-out;\n}\n\n.farm-default-error__action--primary {\n  border-color: var(--farm-error-button-bg);\n  color: var(--farm-error-button-fg);\n  background: var(--farm-error-button-bg);\n}\n\n.farm-default-error__panel {\n  margin-top: 42px;\n  border-top: 1px solid var(--farm-error-line-strong);\n}\n\n.farm-default-error__row {\n  min-height: 45px;\n  display: grid;\n  grid-template-columns: 92px minmax(0, 1fr);\n  align-items: center;\n  border-bottom: 1px solid var(--farm-error-line);\n}\n\n.farm-default-error__label,\n.farm-default-error__value,\n.farm-default-error__details-title,\n.farm-default-error__source-path,\n.farm-default-error__meta,\n.farm-default-error__footer-action {\n  font-family: var(--farm-error-font-mono);\n}\n\n.farm-default-error__label {\n  color: var(--farm-error-subtle);\n  font-size: 10px;\n  font-weight: 560;\n  letter-spacing: 0.09em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__value {\n  min-width: 0;\n  padding: 11px 0;\n  color: var(--farm-error-muted);\n  font-size: 12px;\n  line-height: 1.55;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__details {\n  padding: 24px 0 0;\n  border-bottom: 1px solid var(--farm-error-line);\n}\n\n.farm-default-error__details-header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 16px;\n  margin-bottom: 12px;\n}\n\n.farm-default-error__details-title {\n  margin: 0;\n  color: var(--farm-error-muted);\n  font-size: 10px;\n  font-weight: 560;\n  line-height: 1;\n  letter-spacing: 0.09em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__copy {\n  min-height: 32px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 10px;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 6px;\n  color: var(--farm-error-muted);\n  background: transparent;\n  font: inherit;\n  font-size: 11px;\n  cursor: pointer;\n  transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out;\n}\n\n.farm-default-error__source {\n  overflow: hidden;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 7px;\n  background: var(--farm-error-panel);\n}\n\n.farm-default-error__source-path {\n  margin: 0;\n  padding: 10px 13px;\n  border-bottom: 1px solid var(--farm-error-line);\n  color: var(--farm-error-muted);\n  font-size: 11px;\n  line-height: 1.45;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__source-code {\n  margin: 0;\n  padding: 8px 0;\n  overflow-x: auto;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  line-height: 1.75;\n  tab-size: 2;\n}\n\n.farm-default-error__source-line {\n  min-width: max-content;\n  display: grid;\n  grid-template-columns: 68px minmax(0, 1fr);\n  padding: 0 14px 0 0;\n  border-left: 1px solid transparent;\n}\n\n.farm-default-error__source-line--active {\n  border-left-color: var(--farm-error-source-marker);\n  background: var(--farm-error-source-line);\n}\n\n.farm-default-error__source-gutter {\n  padding-right: 14px;\n  color: var(--farm-error-subtle);\n  text-align: right;\n  user-select: none;\n}\n\n.farm-default-error__source-line--active .farm-default-error__source-gutter {\n  color: var(--farm-error-source-marker);\n}\n\n.farm-default-error__source-text {\n  white-space: pre;\n}\n\n.farm-default-error__details-empty {\n  margin: 0;\n  padding: 14px;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 7px;\n  color: var(--farm-error-muted);\n  background: var(--farm-error-panel);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  line-height: 1.5;\n}\n\n.farm-default-error__meta {\n  margin: 12px 0 20px;\n  color: var(--farm-error-subtle);\n  font-size: 10px;\n  line-height: 1.5;\n  letter-spacing: 0.035em;\n}\n\n.farm-default-error__footer {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: center;\n  gap: 12px;\n  padding-top: 24px;\n}\n\n.farm-default-error__footer-action {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  padding: 0;\n  border: 0;\n  color: var(--farm-error-muted);\n  background: transparent;\n  font-size: 10px;\n  font-weight: 540;\n  line-height: 1.4;\n  letter-spacing: 0.065em;\n  text-decoration: none;\n  cursor: pointer;\n  transition: color 150ms ease-out;\n}\n\n.farm-default-error__docs-icon {\n  width: 14px;\n  height: 14px;\n  flex: 0 0 auto;\n  stroke: currentColor;\n  stroke-width: 1.25;\n  stroke-linecap: round;\n  stroke-linejoin: round;\n}\n\n.farm-default-error__sr-only {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  padding: 0;\n  margin: -1px;\n  overflow: hidden;\n  clip: rect(0, 0, 0, 0);\n  white-space: nowrap;\n  border: 0;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  .farm-default-error__action:hover {\n    border-color: var(--farm-error-fg);\n    background: var(--farm-error-source-line);\n  }\n\n  .farm-default-error__action--primary:hover {\n    border-color: var(--farm-error-muted);\n    background: var(--farm-error-muted);\n  }\n\n  .farm-default-error__copy:hover {\n    border-color: var(--farm-error-line-strong);\n    color: var(--farm-error-fg);\n    background: var(--farm-error-source-line);\n  }\n\n  .farm-default-error__footer-action:hover {\n    color: var(--farm-error-fg);\n  }\n}\n\n.farm-default-error__copy:active,\n.farm-default-error__action:active {\n  transform: translateY(1px);\n}\n\n.farm-default-error__copy:focus-visible,\n.farm-default-error__action:focus-visible,\n.farm-default-error__footer-action:focus-visible {\n  outline: 2px solid var(--farm-error-fg);\n  outline-offset: 3px;\n}\n\n@media (max-width: 620px) {\n  .farm-default-error__frame {\n    padding: 22px 18px 26px;\n  }\n\n  .farm-default-error__content {\n    padding: 56px 0 68px;\n  }\n\n  .farm-default-error > .farm-default-error__content {\n    padding: 48px 18px;\n  }\n\n  .farm-default-error__title {\n    font-size: clamp(34px, 11vw, 44px);\n  }\n\n  .farm-default-error__message {\n    margin-top: 15px;\n  }\n\n  .farm-default-error__actions {\n    display: grid;\n    grid-template-columns: 1fr;\n  }\n\n  .farm-default-error__action {\n    width: 100%;\n  }\n\n  .farm-default-error__row {\n    grid-template-columns: 1fr;\n    gap: 2px;\n    padding: 11px 0;\n  }\n\n  .farm-default-error__value {\n    padding: 0;\n  }\n\n  .farm-default-error__details-header {\n    align-items: flex-start;\n    flex-direction: column;\n  }\n\n  .farm-default-error__copy {\n    width: 100%;\n  }\n\n  .farm-default-error__source-line {\n    grid-template-columns: 54px minmax(0, 1fr);\n  }\n}\n\n@media (prefers-color-scheme: light) {\n  .farm-default-error {\n    --farm-error-bg: #f7f7f5;\n    --farm-error-panel: #ffffff;\n    --farm-error-fg: #141414;\n    --farm-error-muted: #666666;\n    --farm-error-subtle: #8a8a8a;\n    --farm-error-line: rgba(0, 0, 0, 0.1);\n    --farm-error-line-strong: rgba(0, 0, 0, 0.19);\n    --farm-error-button-bg: #141414;\n    --farm-error-button-fg: #ffffff;\n    --farm-error-source-line: rgba(0, 0, 0, 0.045);\n    --farm-error-source-marker: #141414;\n    color-scheme: light;\n  }\n}\n\n.dark .farm-default-error,\n[data-theme=\"dark\"] .farm-default-error,\n[data-color-scheme=\"dark\"] .farm-default-error {\n  --farm-error-bg: #080808;\n  --farm-error-panel: #0d0d0d;\n  --farm-error-fg: #f3f3f3;\n  --farm-error-muted: #9a9a9a;\n  --farm-error-subtle: #6f6f6f;\n  --farm-error-line: rgba(255, 255, 255, 0.1);\n  --farm-error-line-strong: rgba(255, 255, 255, 0.2);\n  --farm-error-button-bg: #f1f1f1;\n  --farm-error-button-fg: #0a0a0a;\n  --farm-error-source-line: rgba(255, 255, 255, 0.055);\n  --farm-error-source-marker: #f3f3f3;\n  color-scheme: dark;\n}\n\n.light .farm-default-error,\n[data-theme=\"light\"] .farm-default-error,\n[data-color-scheme=\"light\"] .farm-default-error {\n  --farm-error-bg: #f7f7f5;\n  --farm-error-panel: #ffffff;\n  --farm-error-fg: #141414;\n  --farm-error-muted: #666666;\n  --farm-error-subtle: #8a8a8a;\n  --farm-error-line: rgba(0, 0, 0, 0.1);\n  --farm-error-line-strong: rgba(0, 0, 0, 0.19);\n  --farm-error-button-bg: #141414;\n  --farm-error-button-fg: #ffffff;\n  --farm-error-source-line: rgba(0, 0, 0, 0.045);\n  --farm-error-source-marker: #141414;\n  color-scheme: light;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .farm-default-error__copy,\n  .farm-default-error__action,\n  .farm-default-error__footer-action {\n    transition: none;\n  }\n\n  .farm-default-error__copy:active,\n  .farm-default-error__action:active {\n    transform: none;\n  }\n}\n`;\n","{\n  \"name\": \"@farm.js/core\",\n  \"version\": \"0.1.0-beta.102\",\n  \"description\": \"Core Farm.js framework for modern integrated apps\",\n  \"keywords\": [\n    \"@farm.js/core\",\n    \"framework\",\n    \"react\",\n    \"rsc\",\n    \"server-components\",\n    \"ssr\",\n    \"vite\"\n  ],\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/farming-labs/farm.js\",\n    \"directory\": \"packages/farm\"\n  },\n  \"files\": [\n    \"dist\",\n    \"types\"\n  ],\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.mjs\",\n  \"types\": \"./dist/index.d.ts\",\n  \"typesVersions\": {\n    \"*\": {\n      \"middleware\": [\n        \"./types/middleware.d.ts\",\n        \"./dist/middleware.d.ts\"\n      ],\n      \"version\": [\n        \"./dist/version.d.ts\"\n      ],\n      \"router\": [\n        \"./dist/router.d.ts\"\n      ],\n      \"routes\": [\n        \"./dist/routes.d.ts\"\n      ],\n      \"storage\": [\n        \"./dist/storage.d.ts\"\n      ],\n      \"integrations\": [\n        \"./dist/integrations.d.ts\"\n      ],\n      \"schema\": [\n        \"./dist/schema.d.ts\"\n      ],\n      \"cache\": [\n        \"./dist/cache.d.ts\"\n      ],\n      \"deferred\": [\n        \"./dist/deferred.d.ts\"\n      ],\n      \"after\": [\n        \"./dist/after.d.ts\"\n      ],\n      \"navigation\": [\n        \"./dist/navigation.d.ts\"\n      ],\n      \"headers\": [\n        \"./dist/headers.d.ts\"\n      ],\n      \"theme\": [\n        \"./dist/theme/index.d.ts\"\n      ],\n      \"theme/client\": [\n        \"./dist/theme/client.d.ts\"\n      ],\n      \"theme/runtime\": [\n        \"./dist/theme/runtime.d.ts\"\n      ],\n      \"theme/server\": [\n        \"./dist/theme/server.d.ts\"\n      ],\n      \"docs\": [\n        \"./dist/docs.d.ts\"\n      ],\n      \"markdown\": [\n        \"./dist/markdown.d.ts\"\n      ],\n      \"app-markdown\": [\n        \"./dist/app-markdown.d.ts\"\n      ],\n      \"observability\": [\n        \"./dist/observability.d.ts\"\n      ],\n      \"instrumentation\": [\n        \"./dist/instrumentation.d.ts\"\n      ],\n      \"workflows\": [\n        \"./dist/workflows.d.ts\"\n      ],\n      \"cron\": [\n        \"./dist/cron.d.ts\"\n      ],\n      \"server-fn\": [\n        \"./dist/server-fn.d.ts\"\n      ],\n      \"server-fn/client\": [\n        \"./dist/server-fn-client.d.ts\"\n      ],\n      \"server-query\": [\n        \"./dist/server-query.d.ts\"\n      ],\n      \"server-query/client\": [\n        \"./dist/server-query-client.d.ts\"\n      ],\n      \"server-action-security\": [\n        \"./dist/server-action-security.d.ts\"\n      ],\n      \"deployment\": [\n        \"./dist/deployment.d.ts\"\n      ],\n      \"env\": [\n        \"./dist/env.d.ts\"\n      ],\n      \"env-types\": [\n        \"./dist/env-types.d.ts\"\n      ],\n      \"environment\": [\n        \"./dist/environment.d.ts\"\n      ],\n      \"environment/vite\": [\n        \"./dist/environment/vite.d.ts\"\n      ],\n      \"font\": [\n        \"./dist/font.d.ts\"\n      ],\n      \"testing\": [\n        \"./dist/testing.d.ts\"\n      ],\n      \"agent-runtime\": [\n        \"./dist/agent-runtime.d.ts\"\n      ],\n      \"css\": [\n        \"./types/css.d.ts\"\n      ],\n      \"image\": [\n        \"./types/image.d.ts\",\n        \"./dist/image.d.ts\"\n      ],\n      \"image/server\": [\n        \"./dist/image/server.d.ts\"\n      ],\n      \"image/sharp\": [\n        \"./dist/image/sharp.d.ts\"\n      ],\n      \"i18n\": [\n        \"./dist/i18n/index.d.ts\"\n      ],\n      \"i18n/server\": [\n        \"./dist/i18n/server.d.ts\"\n      ],\n      \"i18n/client\": [\n        \"./dist/i18n/client.d.ts\"\n      ],\n      \"internal/production-runtime\": [\n        \"./dist/internal/production-runtime.d.ts\"\n      ],\n      \"internal/product-telemetry-runtime\": [\n        \"./dist/internal/product-telemetry-runtime.d.ts\"\n      ],\n      \"internal/metadata-image-runtime\": [\n        \"./dist/internal/metadata-image-runtime.d.ts\"\n      ],\n      \"internal/client-runtime\": [\n        \"./dist/internal/client-runtime.d.ts\"\n      ],\n      \"internal/isolated-boundary\": [\n        \"./dist/internal/isolated-boundary.d.ts\"\n      ],\n      \"internal/build-runtime\": [\n        \"./dist/internal/build-runtime.d.ts\"\n      ],\n      \"internal/config-runtime\": [\n        \"./dist/internal/config-runtime.d.ts\"\n      ],\n      \"internal/production-node-env\": [\n        \"./dist/internal/production-node-env.d.ts\"\n      ],\n      \"config\": [\n        \"./dist/config.d.ts\"\n      ],\n      \"renderer\": [\n        \"./dist/renderer.d.ts\"\n      ],\n      \"renderer-client\": [\n        \"./dist/renderer-client.d.ts\"\n      ],\n      \"api\": [\n        \"./types/api.d.ts\",\n        \"./dist/api.d.ts\"\n      ],\n      \"api/client\": [\n        \"./dist/api/client.d.ts\"\n      ],\n      \"api/route-manager\": [\n        \"./dist/api/route-manager.d.ts\"\n      ],\n      \"api/runtime\": [\n        \"./dist/api/runtime.d.ts\"\n      ],\n      \"request\": [\n        \"./dist/request.d.ts\"\n      ],\n      \"client\": [\n        \"./types/client.d.ts\",\n        \"./dist/client.d.ts\"\n      ],\n      \"client/lifecycle\": [\n        \"./dist/client/lifecycle.d.ts\"\n      ],\n      \"server\": [\n        \"./dist/server.d.ts\"\n      ],\n      \"vite\": [\n        \"./dist/vite.d.ts\"\n      ],\n      \"plugin\": [\n        \"./dist/plugin.d.ts\"\n      ],\n      \"query\": [\n        \"./dist/query/index.d.ts\"\n      ],\n      \"*\": [\n        \"./dist/*.d.ts\"\n      ]\n    }\n  },\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.mjs\",\n      \"require\": \"./dist/index.cjs\",\n      \"default\": \"./dist/index.mjs\"\n    },\n    \"./version\": {\n      \"types\": \"./dist/version.d.ts\",\n      \"import\": \"./dist/version.mjs\",\n      \"require\": \"./dist/version.cjs\"\n    },\n    \"./config\": {\n      \"types\": \"./dist/config.d.ts\",\n      \"import\": \"./dist/config.mjs\",\n      \"require\": \"./dist/config.cjs\"\n    },\n    \"./renderer\": {\n      \"types\": \"./dist/renderer.d.ts\",\n      \"import\": \"./dist/renderer.mjs\",\n      \"require\": \"./dist/renderer.cjs\"\n    },\n    \"./renderer-client\": {\n      \"types\": \"./dist/renderer-client.d.ts\",\n      \"import\": \"./dist/renderer-client.mjs\",\n      \"require\": \"./dist/renderer-client.cjs\"\n    },\n    \"./renderer/react/server\": {\n      \"types\": \"./dist/renderer/react/server.d.ts\",\n      \"import\": \"./dist/renderer/react/server.mjs\",\n      \"require\": \"./dist/renderer/react/server.cjs\"\n    },\n    \"./renderer/react/client\": {\n      \"types\": \"./dist/renderer/react/client.d.ts\",\n      \"import\": \"./dist/renderer/react/client.mjs\",\n      \"require\": \"./dist/renderer/react/client.cjs\"\n    },\n    \"./renderer/react/vite\": {\n      \"types\": \"./dist/renderer/react/vite.d.ts\",\n      \"import\": \"./dist/renderer/react/vite.mjs\",\n      \"require\": \"./dist/renderer/react/vite.cjs\"\n    },\n    \"./server\": {\n      \"types\": \"./dist/server.d.ts\",\n      \"import\": \"./dist/server.mjs\",\n      \"require\": \"./dist/server.cjs\"\n    },\n    \"./client\": {\n      \"types\": \"./types/client.d.ts\",\n      \"import\": \"./dist/client.mjs\",\n      \"require\": \"./dist/client.cjs\"\n    },\n    \"./client/lifecycle\": {\n      \"types\": \"./dist/client/lifecycle.d.ts\",\n      \"import\": \"./dist/client/lifecycle.mjs\",\n      \"require\": \"./dist/client/lifecycle.cjs\"\n    },\n    \"./storage\": {\n      \"types\": \"./dist/storage.d.ts\",\n      \"import\": \"./dist/storage.mjs\",\n      \"require\": \"./dist/storage.cjs\"\n    },\n    \"./integrations\": {\n      \"types\": \"./dist/integrations.d.ts\",\n      \"import\": \"./dist/integrations.mjs\",\n      \"require\": \"./dist/integrations.cjs\"\n    },\n    \"./schema\": {\n      \"types\": \"./dist/schema.d.ts\",\n      \"import\": \"./dist/schema.mjs\",\n      \"require\": \"./dist/schema.cjs\"\n    },\n    \"./cache\": {\n      \"types\": \"./dist/cache.d.ts\",\n      \"import\": \"./dist/cache.mjs\",\n      \"require\": \"./dist/cache.cjs\"\n    },\n    \"./deferred\": {\n      \"types\": \"./dist/deferred.d.ts\",\n      \"import\": \"./dist/deferred.mjs\",\n      \"require\": \"./dist/deferred.cjs\"\n    },\n    \"./after\": {\n      \"types\": \"./dist/after.d.ts\",\n      \"import\": \"./dist/after.mjs\",\n      \"require\": \"./dist/after.cjs\"\n    },\n    \"./navigation\": {\n      \"types\": \"./dist/navigation.d.ts\",\n      \"import\": \"./dist/navigation.mjs\",\n      \"require\": \"./dist/navigation.cjs\"\n    },\n    \"./headers\": {\n      \"types\": \"./dist/headers.d.ts\",\n      \"import\": \"./dist/headers.mjs\",\n      \"require\": \"./dist/headers.cjs\"\n    },\n    \"./theme\": {\n      \"types\": \"./dist/theme/index.d.ts\",\n      \"import\": \"./dist/theme/index.mjs\",\n      \"require\": \"./dist/theme/index.cjs\"\n    },\n    \"./theme/client\": {\n      \"types\": \"./dist/theme/client.d.ts\",\n      \"import\": \"./dist/theme/client.mjs\",\n      \"require\": \"./dist/theme/client.cjs\"\n    },\n    \"./theme/runtime\": {\n      \"types\": \"./dist/theme/runtime.d.ts\",\n      \"import\": \"./dist/theme/runtime.mjs\",\n      \"require\": \"./dist/theme/runtime.cjs\"\n    },\n    \"./theme/server\": {\n      \"types\": \"./dist/theme/server.d.ts\",\n      \"import\": \"./dist/theme/server.mjs\",\n      \"require\": \"./dist/theme/server.cjs\"\n    },\n    \"./docs\": {\n      \"types\": \"./dist/docs.d.ts\",\n      \"import\": \"./dist/docs.mjs\",\n      \"require\": \"./dist/docs.cjs\"\n    },\n    \"./markdown\": {\n      \"types\": \"./dist/markdown.d.ts\",\n      \"import\": \"./dist/markdown.mjs\",\n      \"require\": \"./dist/markdown.cjs\"\n    },\n    \"./app-markdown\": {\n      \"types\": \"./dist/app-markdown.d.ts\",\n      \"import\": \"./dist/app-markdown.mjs\",\n      \"require\": \"./dist/app-markdown.cjs\"\n    },\n    \"./observability\": {\n      \"types\": \"./dist/observability.d.ts\",\n      \"import\": \"./dist/observability.mjs\",\n      \"require\": \"./dist/observability.cjs\"\n    },\n    \"./instrumentation\": {\n      \"types\": \"./dist/instrumentation.d.ts\",\n      \"import\": \"./dist/instrumentation.mjs\",\n      \"require\": \"./dist/instrumentation.cjs\"\n    },\n    \"./workflows\": {\n      \"types\": \"./dist/workflows.d.ts\",\n      \"import\": \"./dist/workflows.mjs\",\n      \"require\": \"./dist/workflows.cjs\"\n    },\n    \"./cron\": {\n      \"types\": \"./dist/cron.d.ts\",\n      \"import\": \"./dist/cron.mjs\",\n      \"require\": \"./dist/cron.cjs\"\n    },\n    \"./server-fn\": {\n      \"types\": \"./dist/server-fn.d.ts\",\n      \"import\": \"./dist/server-fn.mjs\",\n      \"require\": \"./dist/server-fn.cjs\"\n    },\n    \"./server-fn/client\": {\n      \"types\": \"./dist/server-fn-client.d.ts\",\n      \"import\": \"./dist/server-fn-client.mjs\",\n      \"require\": \"./dist/server-fn-client.cjs\"\n    },\n    \"./server-query\": {\n      \"types\": \"./dist/server-query.d.ts\",\n      \"import\": \"./dist/server-query.mjs\",\n      \"require\": \"./dist/server-query.cjs\"\n    },\n    \"./server-query/client\": {\n      \"types\": \"./dist/server-query-client.d.ts\",\n      \"import\": \"./dist/server-query-client.mjs\",\n      \"require\": \"./dist/server-query-client.cjs\"\n    },\n    \"./server-action-security\": {\n      \"types\": \"./dist/server-action-security.d.ts\",\n      \"import\": \"./dist/server-action-security.mjs\",\n      \"require\": \"./dist/server-action-security.cjs\"\n    },\n    \"./deployment\": {\n      \"types\": \"./dist/deployment.d.ts\",\n      \"import\": \"./dist/deployment.mjs\",\n      \"require\": \"./dist/deployment.cjs\"\n    },\n    \"./env\": {\n      \"types\": \"./dist/env.d.ts\",\n      \"import\": \"./dist/env.mjs\",\n      \"require\": \"./dist/env.cjs\"\n    },\n    \"./env-types\": {\n      \"types\": \"./dist/env-types.d.ts\",\n      \"import\": \"./dist/env-types.mjs\",\n      \"require\": \"./dist/env-types.cjs\"\n    },\n    \"./environment\": {\n      \"types\": \"./dist/environment.d.ts\",\n      \"import\": \"./dist/environment.mjs\",\n      \"require\": \"./dist/environment.cjs\"\n    },\n    \"./environment/vite\": {\n      \"types\": \"./dist/environment/vite.d.ts\",\n      \"import\": \"./dist/environment/vite.mjs\",\n      \"require\": \"./dist/environment/vite.cjs\"\n    },\n    \"./font\": {\n      \"types\": \"./dist/font.d.ts\",\n      \"import\": \"./dist/font.mjs\",\n      \"require\": \"./dist/font.cjs\"\n    },\n    \"./vite\": {\n      \"types\": \"./dist/vite.d.ts\",\n      \"import\": \"./dist/vite.mjs\",\n      \"require\": \"./dist/vite.cjs\"\n    },\n    \"./plugin\": {\n      \"types\": \"./dist/plugin.d.ts\",\n      \"import\": \"./dist/plugin.mjs\",\n      \"require\": \"./dist/plugin.cjs\"\n    },\n    \"./plugin/server\": {\n      \"types\": \"./dist/server-plugins.d.ts\",\n      \"import\": \"./dist/server-plugins.mjs\",\n      \"require\": \"./dist/server-plugins.cjs\"\n    },\n    \"./plugin/client\": {\n      \"types\": \"./dist/client-plugins.d.ts\",\n      \"import\": \"./dist/client-plugins.mjs\",\n      \"require\": \"./dist/client-plugins.cjs\"\n    },\n    \"./query\": {\n      \"types\": \"./dist/query/index.d.ts\",\n      \"import\": \"./dist/query/index.mjs\",\n      \"require\": \"./dist/query/index.cjs\"\n    },\n    \"./query/parsers\": {\n      \"types\": \"./dist/query/parsers.d.ts\",\n      \"import\": \"./dist/query/parsers.mjs\",\n      \"require\": \"./dist/query/parsers.cjs\"\n    },\n    \"./query/client\": {\n      \"types\": \"./dist/query/client.d.ts\",\n      \"import\": \"./dist/query/client.mjs\",\n      \"require\": \"./dist/query/client.cjs\"\n    },\n    \"./query/server\": {\n      \"types\": \"./dist/query/server.d.ts\",\n      \"import\": \"./dist/query/server.mjs\",\n      \"require\": \"./dist/query/server.cjs\"\n    },\n    \"./middleware\": {\n      \"types\": \"./dist/middleware.d.ts\",\n      \"import\": \"./dist/middleware.mjs\",\n      \"require\": \"./dist/middleware.cjs\"\n    },\n    \"./api\": {\n      \"types\": \"./dist/api.d.ts\",\n      \"import\": \"./dist/api.mjs\",\n      \"require\": \"./dist/api.cjs\"\n    },\n    \"./api/client\": {\n      \"types\": \"./dist/api/client.d.ts\",\n      \"import\": \"./dist/api/client.mjs\",\n      \"require\": \"./dist/api/client.cjs\"\n    },\n    \"./api/route-manager\": {\n      \"types\": \"./dist/api/route-manager.d.ts\",\n      \"import\": \"./dist/api/route-manager.mjs\",\n      \"require\": \"./dist/api/route-manager.cjs\"\n    },\n    \"./api/runtime\": {\n      \"types\": \"./dist/api/runtime.d.ts\",\n      \"import\": \"./dist/api/runtime.mjs\",\n      \"require\": \"./dist/api/runtime.cjs\"\n    },\n    \"./request\": {\n      \"types\": \"./dist/request.d.ts\",\n      \"import\": \"./dist/request.mjs\",\n      \"require\": \"./dist/request.cjs\"\n    },\n    \"./router\": {\n      \"types\": \"./dist/router.d.ts\",\n      \"import\": \"./dist/router.mjs\",\n      \"require\": \"./dist/router.cjs\"\n    },\n    \"./routes\": {\n      \"types\": \"./dist/routes.d.ts\",\n      \"import\": \"./dist/routes.mjs\",\n      \"require\": \"./dist/routes.cjs\"\n    },\n    \"./testing\": {\n      \"types\": \"./dist/testing.d.ts\",\n      \"import\": \"./dist/testing.mjs\",\n      \"require\": \"./dist/testing.cjs\"\n    },\n    \"./agent-runtime\": {\n      \"types\": \"./dist/agent-runtime.d.ts\",\n      \"import\": \"./dist/agent-runtime.mjs\",\n      \"require\": \"./dist/agent-runtime.cjs\"\n    },\n    \"./css\": {\n      \"types\": \"./types/css.d.ts\"\n    },\n    \"./image\": {\n      \"types\": \"./types/image.d.ts\",\n      \"import\": \"./dist/image.mjs\",\n      \"require\": \"./dist/image.cjs\"\n    },\n    \"./image/server\": {\n      \"types\": \"./dist/image/server.d.ts\",\n      \"import\": \"./dist/image/server.mjs\",\n      \"require\": \"./dist/image/server.cjs\"\n    },\n    \"./image/sharp\": {\n      \"types\": \"./dist/image/sharp.d.ts\",\n      \"import\": \"./dist/image/sharp.mjs\",\n      \"require\": \"./dist/image/sharp.cjs\"\n    },\n    \"./i18n\": {\n      \"types\": \"./dist/i18n/index.d.ts\",\n      \"import\": \"./dist/i18n/index.mjs\",\n      \"require\": \"./dist/i18n/index.cjs\"\n    },\n    \"./i18n/server\": {\n      \"types\": \"./dist/i18n/server.d.ts\",\n      \"import\": \"./dist/i18n/server.mjs\",\n      \"require\": \"./dist/i18n/server.cjs\"\n    },\n    \"./i18n/client\": {\n      \"types\": \"./dist/i18n/client.d.ts\",\n      \"import\": \"./dist/i18n/client.mjs\",\n      \"require\": \"./dist/i18n/client.cjs\"\n    },\n    \"./internal/production-runtime\": {\n      \"types\": \"./dist/internal/production-runtime.d.ts\",\n      \"import\": \"./dist/internal/production-runtime.mjs\",\n      \"require\": \"./dist/internal/production-runtime.cjs\"\n    },\n    \"./internal/product-telemetry-runtime\": {\n      \"types\": \"./dist/internal/product-telemetry-runtime.d.ts\",\n      \"import\": \"./dist/internal/product-telemetry-runtime.mjs\",\n      \"require\": \"./dist/internal/product-telemetry-runtime.cjs\"\n    },\n    \"./internal/metadata-image-runtime\": {\n      \"types\": \"./dist/internal/metadata-image-runtime.d.ts\",\n      \"import\": \"./dist/internal/metadata-image-runtime.mjs\",\n      \"require\": \"./dist/internal/metadata-image-runtime.cjs\"\n    },\n    \"./internal/client-runtime\": {\n      \"types\": \"./dist/internal/client-runtime.d.ts\",\n      \"import\": \"./dist/internal/client-runtime.mjs\",\n      \"require\": \"./dist/internal/client-runtime.cjs\"\n    },\n    \"./internal/isolated-boundary\": {\n      \"types\": \"./dist/internal/isolated-boundary.d.ts\",\n      \"import\": \"./dist/internal/isolated-boundary.mjs\",\n      \"require\": \"./dist/internal/isolated-boundary.cjs\"\n    },\n    \"./internal/build-runtime\": {\n      \"types\": \"./dist/internal/build-runtime.d.ts\",\n      \"import\": \"./dist/internal/build-runtime.mjs\",\n      \"require\": \"./dist/internal/build-runtime.cjs\"\n    },\n    \"./internal/config-runtime\": {\n      \"types\": \"./dist/internal/config-runtime.d.ts\",\n      \"import\": \"./dist/internal/config-runtime.mjs\",\n      \"require\": \"./dist/internal/config-runtime.cjs\"\n    },\n    \"./internal/production-node-env\": {\n      \"types\": \"./dist/internal/production-node-env.d.ts\",\n      \"import\": \"./dist/internal/production-node-env.mjs\",\n      \"require\": \"./dist/internal/production-node-env.cjs\"\n    }\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"scripts\": {\n    \"build\": \"tsup\",\n    \"build:runtime\": \"tsup --config tsup.runtime.config.ts\",\n    \"dev\": \"tsup --watch\",\n    \"test\": \"vitest run\",\n    \"test:coverage\": \"vitest --coverage\",\n    \"lint\": \"biome lint .\",\n    \"lint:fix\": \"biome lint --write .\",\n    \"format\": \"biome format --write .\",\n    \"type-check\": \"tsc --noEmit\",\n    \"clean\": \"rm -rf dist\"\n  },\n  \"dependencies\": {\n    \"@farming-labs/docs\": \"^0.2.44\",\n    \"@farming-labs/orm\": \"0.0.62\",\n    \"@farming-labs/orm-runtime\": \"0.0.62\",\n    \"@formatjs/icu-messageformat-parser\": \"3.5.15\",\n    \"@jridgewell/trace-mapping\": \"0.3.31\",\n    \"@mdx-js/mdx\": \"^3.1.1\",\n    \"@opentelemetry/api\": \"1.9.1\",\n    \"@scalar/api-reference\": \"^1.38.1\",\n    \"@scalar/openapi-parser\": \"^0.22.3\",\n    \"@tailwindcss/vite\": \"4.1.18\",\n    \"@vercel/og\": \"0.11.1\",\n    \"@vitejs/plugin-react\": \"^4.2.1\",\n    \"better-call\": \"^1.0.19\",\n    \"db0\": \"^0.3.4\",\n    \"es-module-lexer\": \"2.0.0\",\n    \"esbuild\": \"^0.28.0\",\n    \"fast-glob\": \"^3.3.2\",\n    \"h3\": \"2.0.1-rc.5\",\n    \"image-size\": \"^2.0.2\",\n    \"intl-messageformat\": \"11.2.12\",\n    \"marked\": \"^12.0.2\",\n    \"nitro\": \"3.0.1-alpha.0\",\n    \"pg\": \"^8.20.0\",\n    \"picocolors\": \"^1.0.0\",\n    \"remark-gfm\": \"^4.0.1\",\n    \"sirv\": \"^2.0.4\",\n    \"sugar-high\": \"^0.9.5\",\n    \"supports-color\": \"^10.2.2\",\n    \"tailwindcss\": \"4.1.18\",\n    \"unstorage\": \"^2.0.0-alpha.3\",\n    \"vite\": \"^5.0.10\",\n    \"zod\": \"^4.1.12\"\n  },\n  \"devDependencies\": {\n    \"@clerk/react\": \"^6.1.0\",\n    \"@farm.js/otel\": \"workspace:*\",\n    \"@farm.js/renderer-tests\": \"workspace:*\",\n    \"@opentelemetry/sdk-node\": \"0.221.0\",\n    \"@opentelemetry/sdk-trace-base\": \"2.10.0\",\n    \"@types/react\": \"^18.2.45\",\n    \"@types/react-dom\": \"^18.2.18\",\n    \"@vitest/coverage-v8\": \"^3.2.7\",\n    \"jsdom\": \"^25.0.0\",\n    \"react\": \"19.2.8\",\n    \"react-dom\": \"19.2.8\",\n    \"tsup\": \"^8.3.5\",\n    \"typescript\": \"^5.3.3\",\n    \"vitest\": \"^3.2.7\"\n  },\n  \"peerDependencies\": {\n    \"react\": \"^18.2.0 || ^19.0.0\",\n    \"react-dom\": \"^18.2.0 || ^19.0.0\"\n  },\n  \"peerDependenciesMeta\": {\n    \"react\": {\n      \"optional\": true\n    },\n    \"react-dom\": {\n      \"optional\": true\n    }\n  },\n  \"optionalDependencies\": {\n    \"rolldown\": \"1.2.0\",\n    \"sharp\": \"^0.34.5\",\n    \"vite-rolldown\": \"npm:vite@8.1.5\"\n  },\n  \"engines\": {\n    \"node\": \">=22.13.0\"\n  }\n}\n","import { version } from \"../package.json\";\n\nexport const FARM_VERSION = version;\n","\"use client\";\n\nimport {\n  createFarmRuntimeErrorOverlay,\n  type FarmRuntimeErrorOverlay,\n} from \"./runtime-error-overlay\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type FarmClientPluginEnforce = \"pre\" | \"post\";\nexport type FarmClientNavigationAction = \"push\" | \"replace\" | \"pop\";\nexport type FarmClientHydrationMode = \"hydrate\" | \"render\";\n\nexport interface FarmClientLocation {\n  href: string;\n  pathname: string;\n  search: string;\n  hash: string;\n}\n\nexport interface FarmClientPluginRouter {\n  navigate(href: string, options?: Record<string, unknown>): MaybePromise<void>;\n  /** Re-render the current URL from fresh server data without replacing the document shell. */\n  refresh?(options?: Record<string, unknown>): MaybePromise<void>;\n  prefetch?(href: string): MaybePromise<void>;\n  clearCache?(): void;\n  getNavigationState?(): unknown;\n}\n\nexport interface FarmClientPluginMetadata {\n  name: string;\n  version?: string;\n}\n\nexport interface FarmClientPluginSetupEvent<TPublic = undefined> {\n  plugin: FarmClientPluginMetadata;\n  public: Readonly<TPublic>;\n  router: FarmClientPluginRouter;\n  isDev: boolean;\n  isProd: boolean;\n  deploymentId?: string;\n}\n\nexport interface FarmClientPluginStateEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginSetupEvent<TPublic> {\n  state: TState;\n}\n\nexport interface FarmClientHydrationSession {\n  container: Element;\n  location: FarmClientLocation;\n  mode: FarmClientHydrationMode;\n  startedAt: number;\n}\n\nexport interface FarmClientHydrationEvent<TState = unknown, TPublic = undefined>\n  extends FarmClientPluginStateEvent<TState, TPublic>, FarmClientHydrationSession {}\n\nexport interface FarmClientHydrationCompleteEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientHydrationEvent<TState, TPublic> {\n  durationMs: number;\n  recovered: boolean;\n}\n\nexport interface FarmClientNavigationSession {\n  id: string;\n  from: FarmClientLocation | null;\n  to: FarmClientLocation;\n  action: FarmClientNavigationAction;\n  signal: AbortSignal;\n  startedAt: number;\n  route?: {\n    pattern?: string | null;\n    params?: Record<string, string>;\n  };\n}\n\nexport interface FarmClientNavigationEvent<TState = unknown, TPublic = undefined>\n  extends FarmClientPluginStateEvent<TState, TPublic>, FarmClientNavigationSession {}\n\nexport interface FarmClientNavigationLoadedEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientNavigationEvent<TState, TPublic> {\n  durationMs: number;\n  data?: unknown;\n}\n\nexport interface FarmClientNavigationResolvedEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientNavigationEvent<TState, TPublic> {\n  durationMs: number;\n}\n\nexport interface FarmClientNavigationErrorEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientNavigationResolvedEvent<TState, TPublic> {\n  error: unknown;\n}\n\nexport type FarmClientPluginErrorPhase =\n  | \"setup\"\n  | \"hydration\"\n  | \"navigation\"\n  | \"window\"\n  | \"unhandled-rejection\"\n  | \"performance\"\n  | `plugin:${string}`\n  | (string & {});\n\nexport interface FarmClientPluginErrorEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginStateEvent<TState, TPublic> {\n  error: unknown;\n  phase: FarmClientPluginErrorPhase;\n  location: FarmClientLocation;\n  navigation?: FarmClientNavigationSession;\n}\n\nexport interface FarmClientPerformanceEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginStateEvent<TState, TPublic> {\n  entry: PerformanceEntry;\n  location: FarmClientLocation;\n}\n\nexport interface FarmClientPluginCloseEvent<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPluginStateEvent<TState, TPublic> {\n  reason: \"pagehide\" | \"hmr\" | \"manual\" | (string & {});\n}\n\nexport interface FarmClientPlugin<TState = unknown, TPublic = undefined> {\n  setup?(event: FarmClientPluginSetupEvent<TPublic>): MaybePromise<TState>;\n  hydration?: {\n    before?(event: FarmClientHydrationEvent<TState, TPublic>): MaybePromise<void>;\n    after?(event: FarmClientHydrationCompleteEvent<TState, TPublic>): MaybePromise<void>;\n  };\n  navigation?: {\n    before?(event: FarmClientNavigationEvent<TState, TPublic>): MaybePromise<void>;\n    loaded?(event: FarmClientNavigationLoadedEvent<TState, TPublic>): MaybePromise<void>;\n    resolved?(event: FarmClientNavigationResolvedEvent<TState, TPublic>): MaybePromise<void>;\n    rendered?(event: FarmClientNavigationResolvedEvent<TState, TPublic>): MaybePromise<void>;\n    error?(event: FarmClientNavigationErrorEvent<TState, TPublic>): MaybePromise<void>;\n  };\n  error?(event: FarmClientPluginErrorEvent<TState, TPublic>): MaybePromise<void>;\n  performance?(event: FarmClientPerformanceEvent<TState, TPublic>): MaybePromise<void>;\n  close?(event: FarmClientPluginCloseEvent<TState, TPublic>): MaybePromise<void>;\n}\n\nexport interface FarmClientPluginRegistration<TPublic = undefined> {\n  name: string;\n  version?: string;\n  enforce?: FarmClientPluginEnforce;\n  definition: FarmClientPlugin<any, TPublic>;\n  public?: TPublic;\n}\n\n/**\n * Define the lifecycle for an application's auto-discovered `src/client.ts`\n * entry. The identity helper preserves state inference while keeping the\n * module entirely in the browser bundle.\n */\nexport function defineClient<TState = unknown, TPublic = undefined>(\n  definition: FarmClientPlugin<TState, TPublic>,\n): FarmClientPlugin<TState, TPublic> {\n  return definition;\n}\n\nexport interface FarmClientPluginManagerOptions {\n  router: FarmClientPluginRouter;\n  isDev?: boolean;\n  isProd?: boolean;\n  deploymentId?: string;\n  window?: Window;\n}\n\ninterface FarmClientPluginInstance {\n  registration: FarmClientPluginRegistration<any>;\n  plugin: FarmClientPlugin<any, any>;\n  state: unknown;\n}\n\nconst PERFORMANCE_ENTRY_TYPES = [\n  \"navigation\",\n  \"paint\",\n  \"largest-contentful-paint\",\n  \"layout-shift\",\n  \"event\",\n];\n\nexport class FarmClientPluginManager {\n  private readonly registrations: FarmClientPluginRegistration[];\n  private readonly options: FarmClientPluginManagerOptions;\n  private readonly instances: FarmClientPluginInstance[] = [];\n  private readonly performanceObservers: PerformanceObserver[] = [];\n  private startPromise?: Promise<void>;\n  private closePromise?: Promise<void>;\n  private currentNavigation?: {\n    controller: AbortController;\n    session: FarmClientNavigationSession;\n  };\n  private navigationSequence = 0;\n  private starting = false;\n  private started = false;\n  private closed = false;\n  private readonly reportedErrors = new WeakSet<object>();\n  private readonly runtimeErrorOverlay?: FarmRuntimeErrorOverlay;\n\n  private readonly handleWindowError = (event: ErrorEvent) => {\n    const error = event.error ?? new Error(event.message || \"Unknown browser error\");\n    void this.reportError(error, \"window\", undefined, this.getLocation(), event);\n  };\n\n  private readonly handleUnhandledRejection = (event: PromiseRejectionEvent) => {\n    void this.reportError(\n      event.reason,\n      \"unhandled-rejection\",\n      undefined,\n      this.getLocation(),\n      event,\n    );\n  };\n\n  private readonly handlePageHide = (event: PageTransitionEvent) => {\n    // A persisted pagehide means the page is entering the back/forward cache and\n    // may be restored. close() is terminal — start() refuses to run again once\n    // closed — so tearing down here would hand the restored page dead scripts,\n    // PWA, and observability plugins with nothing able to revive them.\n    if (event.persisted) return;\n    void this.close(\"pagehide\");\n  };\n\n  constructor(\n    registrations: readonly FarmClientPluginRegistration[],\n    options: FarmClientPluginManagerOptions,\n  ) {\n    this.registrations = sortRegistrations(registrations);\n    this.options = {\n      ...options,\n      isDev: options.isDev ?? false,\n      isProd: options.isProd ?? !options.isDev,\n      window: options.window ?? (typeof window !== \"undefined\" ? window : undefined),\n    };\n    if (this.options.isDev && this.options.window) {\n      this.runtimeErrorOverlay = createFarmRuntimeErrorOverlay({\n        window: this.options.window,\n      });\n    }\n  }\n\n  start(): Promise<void> {\n    if (this.startPromise) return this.startPromise;\n\n    this.startPromise = Promise.resolve().then(() => this.startInternal());\n    return this.startPromise;\n  }\n\n  async beginHydration(input: {\n    container: Element;\n    mode: FarmClientHydrationMode;\n  }): Promise<FarmClientHydrationSession> {\n    await this.start();\n    const session: FarmClientHydrationSession = {\n      ...input,\n      location: this.getLocation(),\n      startedAt: now(),\n    };\n\n    await this.runHook(\"hydration.before\", (instance) =>\n      instance.plugin.hydration?.before?.({\n        ...this.createStateEvent(instance),\n        ...session,\n      }),\n    );\n\n    return session;\n  }\n\n  async completeHydration(\n    session: FarmClientHydrationSession,\n    options: { recovered?: boolean } = {},\n  ): Promise<void> {\n    await this.runHook(\"hydration.after\", (instance) =>\n      instance.plugin.hydration?.after?.({\n        ...this.createStateEvent(instance),\n        ...session,\n        durationMs: now() - session.startedAt,\n        recovered: options.recovered ?? false,\n      }),\n    );\n  }\n\n  async failHydration(session: FarmClientHydrationSession, error: unknown): Promise<void> {\n    await this.reportError(error, \"hydration\", undefined, session.location);\n  }\n\n  async beginNavigation(input: {\n    from?: string | URL | FarmClientLocation | null;\n    to: string | URL | FarmClientLocation;\n    action: FarmClientNavigationAction;\n    route?: FarmClientNavigationSession[\"route\"];\n  }): Promise<FarmClientNavigationSession> {\n    await this.start();\n    this.currentNavigation?.controller.abort(\"superseded\");\n\n    const controller = new AbortController();\n    const session: FarmClientNavigationSession = {\n      id: `navigation:${++this.navigationSequence}`,\n      from:\n        input.from === null\n          ? null\n          : toClientLocation(input.from ?? this.getLocation().href, this.getBaseUrl()),\n      to: toClientLocation(input.to, this.getBaseUrl()),\n      action: input.action,\n      signal: controller.signal,\n      startedAt: now(),\n      route: input.route,\n    };\n\n    this.currentNavigation = { controller, session };\n    await this.runHook(\"navigation.before\", (instance) =>\n      instance.plugin.navigation?.before?.({\n        ...this.createStateEvent(instance),\n        ...session,\n      }),\n    );\n\n    return session;\n  }\n\n  async markNavigationLoaded(session: FarmClientNavigationSession, data?: unknown): Promise<void> {\n    if (session.signal.aborted) return;\n    await this.runHook(\"navigation.loaded\", (instance) =>\n      instance.plugin.navigation?.loaded?.({\n        ...this.createStateEvent(instance),\n        ...session,\n        data,\n        durationMs: now() - session.startedAt,\n      }),\n    );\n  }\n\n  cancelNavigation(session?: FarmClientNavigationSession, reason: unknown = \"canceled\"): void {\n    const current = this.currentNavigation;\n    if (!current || (session && current.session !== session)) return;\n    current.controller.abort(reason);\n    this.currentNavigation = undefined;\n  }\n\n  async resolveNavigation(session: FarmClientNavigationSession): Promise<void> {\n    if (session.signal.aborted) return;\n    await this.runHook(\"navigation.resolved\", (instance) =>\n      instance.plugin.navigation?.resolved?.({\n        ...this.createStateEvent(instance),\n        ...session,\n        durationMs: now() - session.startedAt,\n      }),\n    );\n  }\n\n  scheduleNavigationRendered(session: FarmClientNavigationSession): Promise<void> {\n    if (session.signal.aborted) return Promise.resolve();\n    const clientWindow = this.options.window;\n    const schedule = clientWindow?.requestAnimationFrame\n      ? (callback: () => void) =>\n          clientWindow.requestAnimationFrame(() => clientWindow.requestAnimationFrame(callback))\n      : (callback: () => void) => setTimeout(callback, 0);\n\n    return new Promise((resolve) => {\n      schedule(() => {\n        if (session.signal.aborted || this.closed) {\n          resolve();\n          return;\n        }\n        void this.runHook(\"navigation.rendered\", (instance) =>\n          instance.plugin.navigation?.rendered?.({\n            ...this.createStateEvent(instance),\n            ...session,\n            durationMs: now() - session.startedAt,\n          }),\n        ).finally(() => {\n          if (this.currentNavigation?.session === session) {\n            this.currentNavigation = undefined;\n          }\n          resolve();\n        });\n      });\n    });\n  }\n\n  async failNavigation(session: FarmClientNavigationSession, error: unknown): Promise<void> {\n    if (!session.signal.aborted) {\n      await this.runHook(\"navigation.error\", (instance) =>\n        instance.plugin.navigation?.error?.({\n          ...this.createStateEvent(instance),\n          ...session,\n          durationMs: now() - session.startedAt,\n          error,\n        }),\n      );\n      await this.reportError(error, \"navigation\", session, session.to);\n    }\n\n    if (this.currentNavigation?.session === session) {\n      this.currentNavigation = undefined;\n    }\n  }\n\n  async reportError(\n    error: unknown,\n    phase: FarmClientPluginErrorPhase,\n    navigation?: FarmClientNavigationSession,\n    location = this.getLocation(),\n    sourceEvent?: Event,\n  ): Promise<void> {\n    if (this.closed) return;\n    if (isObject(error)) {\n      if (this.reportedErrors.has(error)) return;\n      this.reportedErrors.add(error);\n    }\n\n    if (!this.started && !this.starting) await this.start();\n    await this.runErrorHooks({ error, phase, navigation, location }, undefined, sourceEvent);\n  }\n\n  close(reason: FarmClientPluginCloseEvent[\"reason\"] = \"manual\"): Promise<void> {\n    if (this.closePromise) return this.closePromise;\n    this.closePromise = this.closeInternal(reason);\n    return this.closePromise;\n  }\n\n  getPlugins(): readonly FarmClientPluginMetadata[] {\n    return this.instances.map(({ registration }) => ({\n      name: registration.name,\n      version: registration.version,\n    }));\n  }\n\n  private async startInternal(): Promise<void> {\n    if (this.started || this.closed) return;\n    this.starting = true;\n\n    try {\n      for (const registration of this.registrations) {\n        try {\n          const definition = registration.definition;\n          if (!definition || typeof definition !== \"object\") {\n            throw new TypeError(\n              `Client plugin \"${registration.name}\" does not define a lifecycle object`,\n            );\n          }\n\n          const instance: FarmClientPluginInstance = {\n            registration,\n            plugin: definition,\n            state: undefined,\n          };\n          instance.state = await definition.setup?.(this.createSetupEvent(instance));\n          this.instances.push(instance);\n        } catch (error) {\n          this.logHookError(registration.name, \"setup\", error);\n          await this.runErrorHooks({\n            error,\n            phase: \"setup\",\n            location: this.getLocation(),\n          });\n        }\n      }\n\n      this.started = true;\n      this.installBrowserListeners();\n      this.installPerformanceObservers();\n    } finally {\n      this.starting = false;\n    }\n  }\n\n  private installBrowserListeners(): void {\n    const clientWindow = this.options.window;\n    if (!clientWindow) return;\n\n    if (this.runtimeErrorOverlay || this.instances.some(({ plugin }) => plugin.error)) {\n      clientWindow.addEventListener(\"error\", this.handleWindowError);\n      clientWindow.addEventListener(\"unhandledrejection\", this.handleUnhandledRejection);\n    }\n    // Not `once`: a persisted pagehide is ignored above, and the page can be\n    // restored and then genuinely unloaded later. close() is idempotent, so\n    // keeping the listener costs nothing and never disposes twice.\n    clientWindow.addEventListener(\"pagehide\", this.handlePageHide);\n  }\n\n  private installPerformanceObservers(): void {\n    if (!this.instances.some(({ plugin }) => plugin.performance)) return;\n    const Observer = typeof PerformanceObserver !== \"undefined\" ? PerformanceObserver : undefined;\n    if (!Observer) return;\n\n    const supported = new Set(Observer.supportedEntryTypes || []);\n    for (const type of PERFORMANCE_ENTRY_TYPES) {\n      if (!supported.has(type)) continue;\n      try {\n        const observer = new Observer((list: PerformanceObserverEntryList) => {\n          for (const entry of list.getEntries()) {\n            void this.runHook(\"performance\", (instance) =>\n              instance.plugin.performance?.({\n                ...this.createStateEvent(instance),\n                entry,\n                location: this.getLocation(),\n              }),\n            );\n          }\n        });\n        observer.observe({ type, buffered: true });\n        this.performanceObservers.push(observer);\n      } catch (error) {\n        void this.reportError(error, \"performance\");\n      }\n    }\n  }\n\n  private async closeInternal(reason: FarmClientPluginCloseEvent[\"reason\"]): Promise<void> {\n    if (this.closed) return;\n    if (this.startPromise) await this.startPromise;\n    this.closed = true;\n    this.currentNavigation?.controller.abort(reason);\n    this.currentNavigation = undefined;\n\n    const clientWindow = this.options.window;\n    clientWindow?.removeEventListener(\"error\", this.handleWindowError);\n    clientWindow?.removeEventListener(\"unhandledrejection\", this.handleUnhandledRejection);\n    clientWindow?.removeEventListener(\"pagehide\", this.handlePageHide);\n    for (const observer of this.performanceObservers) observer.disconnect();\n    this.performanceObservers.length = 0;\n    this.runtimeErrorOverlay?.destroy();\n\n    for (const instance of [...this.instances].reverse()) {\n      try {\n        await instance.plugin.close?.({\n          ...this.createStateEvent(instance),\n          reason,\n        });\n      } catch (error) {\n        this.logHookError(instance.registration.name, \"close\", error);\n      }\n    }\n  }\n\n  private async runHook(\n    hook: string,\n    invoke: (instance: FarmClientPluginInstance) => MaybePromise<void> | undefined,\n  ): Promise<void> {\n    for (const instance of this.instances) {\n      try {\n        await invoke(instance);\n      } catch (error) {\n        this.logHookError(instance.registration.name, hook, error);\n        await this.runErrorHooks(\n          {\n            error,\n            phase: `plugin:${hook}`,\n            location: this.getLocation(),\n          },\n          instance,\n        );\n      }\n    }\n  }\n\n  private async runErrorHooks(\n    event: Pick<FarmClientPluginErrorEvent, \"error\" | \"phase\" | \"location\" | \"navigation\">,\n    excluded?: FarmClientPluginInstance,\n    sourceEvent?: Event,\n  ): Promise<void> {\n    this.runtimeErrorOverlay?.show(event.error, {\n      phase: event.phase,\n      location: event.location,\n      sourceEvent,\n    });\n    for (const instance of this.instances) {\n      if (instance === excluded || !instance.plugin.error) continue;\n      try {\n        await instance.plugin.error({\n          ...this.createStateEvent(instance),\n          ...event,\n        });\n      } catch (error) {\n        this.logHookError(instance.registration.name, \"error\", error);\n      }\n    }\n  }\n\n  private createSetupEvent(\n    instance: Pick<FarmClientPluginInstance, \"registration\">,\n  ): FarmClientPluginSetupEvent<any> {\n    return {\n      plugin: {\n        name: instance.registration.name,\n        version: instance.registration.version,\n      },\n      public: readonlyPublicData(instance.registration.public),\n      router: this.options.router,\n      isDev: Boolean(this.options.isDev),\n      isProd: Boolean(this.options.isProd),\n      deploymentId: this.options.deploymentId,\n    };\n  }\n\n  private createStateEvent(\n    instance: FarmClientPluginInstance,\n  ): FarmClientPluginStateEvent<any, any> {\n    return {\n      ...this.createSetupEvent(instance),\n      state: instance.state,\n    };\n  }\n\n  private getLocation(): FarmClientLocation {\n    const href = this.options.window?.location.href ?? \"http://localhost/\";\n    return toClientLocation(href, href);\n  }\n\n  private getBaseUrl(): string {\n    return this.options.window?.location.href ?? \"http://localhost/\";\n  }\n\n  private logHookError(name: string, hook: string, error: unknown): void {\n    console.error(`[Farm.js] Client plugin \"${name}\" failed in ${hook}:`, error);\n  }\n}\n\nexport function createClientPluginManager(\n  registrations: readonly FarmClientPluginRegistration[],\n  options: FarmClientPluginManagerOptions,\n): FarmClientPluginManager {\n  return new FarmClientPluginManager(registrations, options);\n}\n\nfunction sortRegistrations(\n  registrations: readonly FarmClientPluginRegistration[],\n): FarmClientPluginRegistration[] {\n  const rank = (enforce?: FarmClientPluginEnforce) =>\n    enforce === \"pre\" ? 0 : enforce === \"post\" ? 2 : 1;\n  return registrations\n    .map((registration, index) => ({ registration, index }))\n    .sort(\n      (left, right) =>\n        rank(left.registration.enforce) - rank(right.registration.enforce) ||\n        left.index - right.index,\n    )\n    .map(({ registration }) => registration);\n}\n\nfunction toClientLocation(\n  input: string | URL | FarmClientLocation,\n  base: string,\n): FarmClientLocation {\n  if (typeof input === \"object\" && \"href\" in input && \"pathname\" in input) {\n    return {\n      href: input.href,\n      pathname: input.pathname,\n      search: input.search,\n      hash: input.hash,\n    };\n  }\n\n  const url = new URL(input, base);\n  return {\n    href: url.href,\n    pathname: url.pathname,\n    search: url.search,\n    hash: url.hash,\n  };\n}\n\nfunction readonlyPublicData<T>(value: T | undefined): Readonly<T> {\n  if (value && typeof value === \"object\") {\n    return Object.freeze(value);\n  }\n  return value as Readonly<T>;\n}\n\nfunction now(): number {\n  return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction isObject(value: unknown): value is object {\n  return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,OAAO,IAAI,IAAI,SAAS,cAAc;AAC5C,MAAI,KAAK,aAAa,KAAK;AACzB,WAAO,IAAI,IAAI,WAAW,IAAI;AAAA,EAChC;AAEA,QAAMC,SAAQ,IAAI,IAAI,WAAW,cAAc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AM,YAAY;AAC3C;AAbS;AAeT,SAAS,iBACP,OACA,MACoB;AACpB,MAAI,OAAO,UAAU,YAAY,UAAU,SAAS,cAAc,OAAO;AACvE,WAAO;AAAA,MACL,MAAM,MAAM;AAAA,MACZ,UAAU,MAAM;AAAA,MAChB,QAAQ,MAAM;AAAA,MACd,MAAM,MAAM;AAAA,IACd;AAAA,EACF;AAEA,QAAM,MAAM,IAAI,IAAI,OAAO,IAAI;AAC/B,SAAO;AAAA,IACL,MAAM,IAAI;AAAA,IACV,UAAU,IAAI;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ,MAAM,IAAI;AAAA,EACZ;AACF;AApBS;AAsBT,SAAS,mBAAsB,OAAmC;AAChE,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO,OAAO,KAAK;AAAA,EAC5B;AACA,SAAO;AACT;AALS;AAOT,SAAS,MAAc;AACrB,SAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AAFS;AAIT,SAAS,SAAS,OAAiC;AACjD,SAAQ,OAAO,UAAU,YAAY,UAAU,QAAS,OAAO,UAAU;AAC3E;AAFS;","names":["getRouter","route","reportError","globalState","api","operation","body","now","serialized","now","listeners","route","route","segment","dynamic","CURRENT_REQUEST_RESOLVER_KEY","CURRENT_REQUEST_RESOLVER_KEY","context","api","now","nextEntry","result","createResponseError","delay","route","delay","import_react","isFormData","context","import_react","isFormData","import_react","now","operation","api","isOperation","route","import_react","replaceState","import_react","import_react","normalizePathname","value","route","splitRoutePattern","decodePathSegment","normalizePathname","normalizePathname","IntlMessageFormat","getFarmGlobalState","getFarmGlobalState","import_react","import_jsx_runtime","prefetch","route","import_react","context","initialTagCount","shouldBlockUnload","now","context","getRouter","context","route","pushState","getRouter","replaceState","now","context","document"]}