{"version":3,"sources":["../src/renderer.ts","../src/routing/specificity.ts","../src/search-params.ts","../src/utils/decode.ts","../src/utils.ts","../src/storage/index.ts","../src/base-path.ts","../src/i18n/routing.ts","../src/plugins/route-pattern.ts","../src/request-origin.ts","../src/integration-request-security.ts","../src/integration-api.ts","../src/plugin-integration-context.ts","../src/request-context.ts","../src/server/response.ts","../src/server-http.ts","../src/integration-orm.ts","../src/integrations.ts","../src/app-markdown-config.ts","../src/markdown.ts","../src/utils/runtime-env.ts","../src/workflows.ts","../src/cron.ts","../src/tracing.ts","../src/observability.ts","../src/navigation-errors.ts","../src/route-runtime.ts","../src/route-rules.ts","../src/cache-invalidation.ts","../src/server-fn-error.ts","../src/server-action-security.ts","../src/image-config.ts","../src/layers.ts","../src/ssg.ts","../src/routes-shared.ts","../src/i18n/bridge.ts","../src/cache.ts","../src/route-context.ts","../src/routes.ts","../src/routes.server.ts","../src/app-markdown.ts","../src/island.ts","../src/utils/client-component.ts","../src/navigation/render-plan.ts","../src/static-metadata-image.ts","../src/redirect-query.ts","../src/routing/route-slots.ts","../src/routing/route-manager.ts","../src/server/dev-styles.ts","../src/server/full-document.ts","../src/middleware/server.ts","../src/server/request-bridge.ts","../src/server/request.ts","../src/not-found.ts","../src/agent-config.ts","../src/metadata.ts","../src/deferred.ts","../src/deployment.ts","../src/i18n/config.ts","../src/i18n/catalog.ts","../src/i18n/resolver.ts","../src/i18n/runtime.ts","../src/i18n/server.ts","../src/font-vite.ts","../src/response-body.ts","../src/metadata-image.ts","../src/metadata-route.ts","../src/trailing-slash.ts","../src/components/not-found-styles.ts","../src/components/error-styles.ts","../src/components/error-page.ts","../src/theme/config.ts","../src/theme/server-runtime.ts","../src/theme/bridge.ts","../src/theme/server.ts","../package.json","../src/version.ts","../src/server/error-diagnostics.ts","../src/client/isolated-boundary.ts","../src/renderer/react/server.ts","../src/server/renderer.ts","../src/devtools-config.ts","../src/dev-indicators.ts","../src/auth-config.ts","../src/preload.ts","../src/security.ts","../src/api/config.ts","../src/app.ts","../src/env.ts","../src/default-styles.ts","../src/client-plugin-build.ts","../src/client-cache-persistence-build.ts","../src/api/transport.ts","../src/api/endpoint.ts","../src/api/route.ts","../src/api/route-shape.ts","../src/api/plugin-route-runtime.ts","../src/api/server-path.ts","../src/api/route-schema.ts","../src/api/route-pattern.ts","../src/api/runtime.ts","../src/api/route-files.ts","../src/api/route-manager.ts","../src/middleware/cookie-header.ts","../src/middleware/context.ts","../src/middleware/module.ts","../src/cli-colors.ts","../src/middleware/path.ts","../src/middleware/manager.ts","../src/write-file-if-changed.ts","../src/type-generator.ts","../src/routing/generate-route-types.ts","../src/env-types.ts","../src/image-types.ts","../src/content-types.ts","../src/i18n/type-generator.ts","../src/type-artifacts.ts","../src/environment-vite.ts","../src/after.ts","../src/api/server-client-bridge.ts","../src/api/server-context.ts","../src/dev-static.ts","../src/server-query-boundary.ts","../src/client-boundary-env.ts","../src/image-vite.ts","../src/font.ts","../src/image-server.ts","../src/server/vite-config.ts","../src/docs/fonts.ts","../src/theme/vite.ts","../src/integration-provider-build.ts","../src/navigation/page-data-error.ts","../src/plugins/rewrites.ts","../src/openapi/dev-status.ts","../src/client/document-head.ts","../src/docs/last-modified.ts","../src/docs/search-client.ts","../src/docs/social-image.ts","../src/docs/handler.ts","../src/docs/adapter.ts","../src/docs/framework-detect.ts","../src/config-entry.ts","../src/config.ts","../src/docs/api.ts","../src/docs/index.ts","../src/openapi/generator.ts","../src/openapi/manager.ts","../src/devtools.ts","../src/devtools-ui.ts","../src/devtools-client.ts","../src/image-sharp.ts","../src/vite.ts","../src/plugin.ts","../src/nitro/index.ts","../src/index.ts","../src/provider.tsx","../src/hmr.ts","../src/plugins/redirects.ts","../src/plugins/headers.ts","../src/plugins/index.ts","../src/plugins/env.ts","../src/plugins/compression.ts","../src/plugins/logger.ts","../src/api/index.ts","../src/integration-client.ts","../src/client-headers.ts","../src/client-cancellation.ts","../src/client-observers.ts","../src/client-cache.ts","../src/api/client.ts","../src/api/client-routes.ts","../src/api/vite-plugin.ts","../src/openapi/index.ts","../src/openapi/scalar-component.tsx","../src/openapi/docs-route.tsx","../src/query/parsers.ts","../src/query/params.ts","../src/middleware/chain.ts","../src/middleware/index.ts","../src/middleware/helpers.ts","../src/middleware/production-runtime.ts","../src/middleware/vite-plugin.ts","../src/router.ts","../src/theme/index.ts","../src/environment.ts","../src/server-fn.ts","../src/server-fn-client.ts","../src/mutation-retry.ts","../src/server-query.ts","../src/server-query-protocol.ts","../src/server-query-client.ts","../src/client-revalidation.ts","../src/server-query-runtime.ts","../src/build/index.ts","../src/nitro/universal-build.ts","../src/nitro/client-css-href.ts","../src/route-runtime-manifest.ts","../src/nitro/vercel-route-runtime.ts","../src/nitro/vercel-assets.ts","../src/nitro/node-server-entry.ts","../src/build/production-vite.ts","../src/build/vite-plugin-compat.ts","../src/instrumentation.ts","../src/build/production-node-env.ts","../src/mutation-client.ts","../src/client-network-status.ts","../src/fetcher-client.tsx","../src/cache-invalidation-broadcast.ts","../src/client-cache-persistence.ts","../src/client.ts","../src/store.ts","../src/theme/client.tsx","../src/theme/runtime.ts","../src/client/link.tsx","../src/i18n/client-runtime.ts","../src/client/router.ts","../src/client/spa-router.ts","../src/client/history-sync.ts","../src/client/hash-target.ts","../src/client/navigation-url.ts","../src/client/chunk-recovery.ts","../src/client/runtime-error-overlay.ts","../src/client/plugin.ts","../src/navigation.ts","../src/headers.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * A rendering-library integration used by Farm's compiler, server renderer,\n * and browser hydration runtime.\n *\n * Renderer descriptors intentionally contain module identifiers instead of\n * implementation functions. This keeps farm.config.ts serializable and lets\n * every module resolve from the application that selected the renderer.\n */\nexport interface FarmRenderer {\n  /** Stable public identifier used in diagnostics and generated manifests. */\n  name: string;\n  /** Module exporting the renderer's Vite plugin factory. */\n  vite: string;\n  /** Module exporting Farm's server-renderer compatibility contract. */\n  server: string;\n  /** Module exporting Farm's browser-renderer compatibility contract. */\n  client: string;\n  /** JSX import source written to generated TypeScript configuration. */\n  jsxImportSource?: string;\n  /** Additional file extensions used for renderer-owned route components. */\n  componentExtensions?: readonly string[];\n  /** Packages that must share one module instance in a Farm application. */\n  dedupe?: readonly string[];\n  /** Renderer packages seeded into Vite's dependency optimizer. */\n  optimizeDeps?: readonly string[];\n  /**\n   * Scheduling policy for the production client and SSR graphs.\n   *\n   * Most renderer plugins are safe to run in parallel. Renderers whose\n   * compiler plugins keep process-global mutable state can opt into serial\n   * builds so one graph cannot invalidate the other's transforms.\n   */\n  buildConcurrency?: \"parallel\" | \"serial\";\n  /** Runtime features this renderer intentionally supports. */\n  capabilities?: FarmRendererCapabilitiesInput;\n  /**\n   * Serializable options consumed by the renderer's Vite integration.\n   *\n   * Keeping renderer-owned configuration on the descriptor lets one rendering\n   * library expose multiple compiler modes without teaching Farm's core about\n   * each option.\n   */\n  options?: Readonly<Record<string, unknown>>;\n}\n\nexport interface FarmRendererStreamingCapabilities {\n  /** Supports Node.js writable streams through renderToPipeableStream(). */\n  node: boolean;\n  /** Supports WHATWG ReadableStream output through renderToReadableStream(). */\n  web: boolean;\n}\n\nexport interface FarmRendererCapabilities {\n  streaming: FarmRendererStreamingCapabilities;\n}\n\nexport interface FarmRendererCapabilitiesInput {\n  streaming?: Partial<FarmRendererStreamingCapabilities>;\n}\n\nconst DEFAULT_RENDERER_CAPABILITIES: Readonly<FarmRendererCapabilities> = Object.freeze({\n  streaming: Object.freeze({ node: false, web: false }),\n});\n\nexport function getFarmRendererCapabilities(\n  renderer?: Pick<FarmRenderer, \"capabilities\">,\n): FarmRendererCapabilities {\n  return {\n    streaming: {\n      node: renderer?.capabilities?.streaming?.node ?? DEFAULT_RENDERER_CAPABILITIES.streaming.node,\n      web: renderer?.capabilities?.streaming?.web ?? DEFAULT_RENDERER_CAPABILITIES.streaming.web,\n    },\n  };\n}\n\nexport const FARM_COMPONENT_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".jsx\"] as const;\n\nexport function resolveFarmComponentExtensions(extensions: readonly string[] = []): string[] {\n  return Array.from(\n    new Set(\n      [...FARM_COMPONENT_EXTENSIONS, ...extensions].map((extension) => {\n        const normalized = extension.trim().toLowerCase();\n        return normalized.startsWith(\".\") ? normalized : `.${normalized}`;\n      }),\n    ),\n  ).filter((extension) => extension.length > 1);\n}\n\nexport function getFarmRendererComponentExtensions(\n  renderer?: Pick<FarmRenderer, \"componentExtensions\">,\n): string[] {\n  return resolveFarmComponentExtensions(renderer?.componentExtensions);\n}\n\nexport interface FarmRendererViteModule {\n  createFarmRendererPlugin(options?: {\n    ssr?: boolean;\n    rendererOptions?: Readonly<Record<string, unknown>>;\n  }): unknown | readonly unknown[] | Promise<unknown | readonly unknown[]>;\n}\n\nexport interface FarmServerRendererRuntime {\n  readonly name: string;\n  readonly Fragment: unknown;\n  readonly Suspense: unknown;\n  createElement(type: unknown, props?: unknown, ...children: unknown[]): unknown;\n  isValidElement(value: unknown): boolean;\n  /** Wraps a route-owned client tree so compiled leaf boundaries stay inside that React root. */\n  wrapClientGraph?(element: unknown): unknown;\n  renderToString(element: unknown): string | Promise<string>;\n  /**\n   * Optional variant for renderers whose components emit document-head markup\n   * during render (e.g. <svelte:head>). `html` is the body markup exactly as\n   * renderToString would produce it; `head` is injected into the assembled\n   * document's <head>.\n   */\n  renderToStringWithHead?(\n    element: unknown,\n  ): { html: string; head: string } | Promise<{ html: string; head: string }>;\n  /** Optional runtime copy of the descriptor capabilities for diagnostics. */\n  readonly capabilities?: FarmRendererCapabilities;\n  /** Optional bootstrap required before this renderer hydrates server markup. */\n  generateHydrationScript?: () => string;\n  /** Optional component used to render route-level failures. */\n  ErrorBoundary?: unknown;\n  /** Optional streaming primitive. Renderers without one use buffered SSR. */\n  renderToPipeableStream?: (\n    element: unknown,\n    callbacks: {\n      onShellReady(): void;\n      onShellError(error: unknown): void;\n      onError(error: unknown): void;\n    },\n  ) => { pipe(destination: NodeJS.WritableStream): void };\n  /** WHATWG streaming primitive used by Web-stream-capable renderers. */\n  renderToReadableStream?: (\n    element: unknown,\n  ) => ReadableStream<Uint8Array | string> | Promise<ReadableStream<Uint8Array | string>>;\n}\n\nexport const REACT_RENDERER: Readonly<FarmRenderer> = Object.freeze({\n  name: \"react\",\n  vite: \"@farm.js/core/renderer/react/vite\",\n  server: \"@farm.js/core/renderer/react/server\",\n  client: \"@farm.js/core/renderer/react/client\",\n  jsxImportSource: \"react\",\n  dedupe: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n  optimizeDeps: [\n    \"react\",\n    \"react-dom\",\n    \"react-dom/client\",\n    \"react/jsx-runtime\",\n    \"react/jsx-dev-runtime\",\n  ],\n  capabilities: {\n    streaming: { node: true, web: false },\n  },\n});\n\nexport function defineRenderer<const TRenderer extends FarmRenderer>(\n  renderer: TRenderer,\n): TRenderer {\n  return renderer;\n}\n\nexport function resolveFarmRenderer(renderer?: FarmRenderer): FarmRenderer {\n  const resolved = renderer || REACT_RENDERER;\n  const fields = [\"name\", \"vite\", \"server\", \"client\"] as const;\n\n  for (const field of fields) {\n    if (typeof resolved[field] !== \"string\" || resolved[field].trim().length === 0) {\n      throw new TypeError(`Farm renderer \\`${field}\\` must be a non-empty string.`);\n    }\n  }\n\n  return {\n    ...resolved,\n    componentExtensions: [...(resolved.componentExtensions || [])],\n    dedupe: [...(resolved.dedupe || [])],\n    optimizeDeps: [...(resolved.optimizeDeps || [])],\n    buildConcurrency: resolved.buildConcurrency || \"parallel\",\n    capabilities: getFarmRendererCapabilities(resolved),\n    options: resolved.options ? { ...resolved.options } : undefined,\n  };\n}\n\nexport async function readFarmRendererWebStream(\n  stream: ReadableStream<Uint8Array | string>,\n): Promise<string> {\n  const reader = stream.getReader();\n  const decoder = new TextDecoder();\n  let html = \"\";\n\n  while (true) {\n    const { done, value } = await reader.read();\n    if (done) break;\n    html += typeof value === \"string\" ? value : decoder.decode(value, { stream: true });\n  }\n\n  return html + decoder.decode();\n}\n\nexport function isReactRenderer(renderer: Pick<FarmRenderer, \"name\"> | undefined): boolean {\n  return !renderer || renderer.name === \"react\";\n}\n\n/** Resolve an optional renderer module from the application's dependency graph. */\nexport function resolveFarmRendererModule(root: string, specifier: string): string {\n  const requireFromApp = createRequire(path.join(path.resolve(root), \"package.json\"));\n  return requireFromApp.resolve(specifier);\n}\n\nexport async function loadFarmRendererVitePlugins(\n  renderer: FarmRenderer,\n  root: string,\n  options: { ssr?: boolean } = {},\n): Promise<unknown[]> {\n  // React uses Vite's default automatic JSX transform today. Keep the legacy\n  // path dependency-free and avoid resolving Farm's own built package while\n  // running directly from source in the monorepo.\n  if (renderer.vite === REACT_RENDERER.vite) return [];\n\n  const modulePath = resolveFarmRendererModule(root, renderer.vite);\n  const rendererModule = (await import(pathToFileURL(modulePath).href)) as FarmRendererViteModule;\n\n  if (typeof rendererModule.createFarmRendererPlugin !== \"function\") {\n    throw new Error(\n      `Renderer \\`${renderer.name}\\` module ${renderer.vite} must export createFarmRendererPlugin().`,\n    );\n  }\n\n  const created = await rendererModule.createFarmRendererPlugin({\n    ...options,\n    rendererOptions: renderer.options,\n  });\n  if (!created) return [];\n  return Array.isArray(created) ? [...created] : [created];\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","/**\n * Convert URLSearchParams into the object handed to routes as `search` /\n * `searchParams`: single keys stay strings and repeated keys collect into\n * arrays, in order. The dev renderer, the production SSR entry, the SPA\n * page-data endpoint, and the generated client hydration runtime all share\n * this helper so every environment agrees on one representation.\n */\nexport function searchParamsToObject(\n  searchParams: URLSearchParams,\n): Record<string, string | string[] | undefined> {\n  const output: Record<string, string | string[] | undefined> = {};\n\n  searchParams.forEach((value, key) => {\n    // Keys come from the request URL. Writing \"__proto__\" onto a plain object\n    // replaces its prototype instead of adding an entry, so a crafted query\n    // string could reshape the object handed to pages and workflow handlers.\n    // The API route helper (entriesToObject in api/runtime.ts) already skips\n    // these names; keep both representations consistent.\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n    const existing = Object.prototype.hasOwnProperty.call(output, key) ? output[key] : undefined;\n    if (existing !== undefined) {\n      if (Array.isArray(existing)) {\n        existing.push(value);\n      } else {\n        output[key] = [existing, value];\n      }\n    } else {\n      output[key] = value;\n    }\n  });\n\n  return output;\n}\n","/**\n * Decode a percent-encoded path segment, falling back to the raw value.\n *\n * Request paths are not guaranteed to be validly percent-encoded, so\n * `decodeURIComponent` can throw on input that is still a legal URL: a\n * latin-1 escape such as `caf%E9` from an old link, or a truncated `%ZZ`\n * from a crawler. A malformed segment simply will not match a known route,\n * which is a 404, so it must not throw out of route matching.\n */\nexport function decodeRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n","import type { RouteSegment, ParsedRoute } from \"./types\";\nimport path from \"path\";\nimport {\n  assertBrowserStableRoutePath,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n} from \"./routing/specificity\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { decodeRouteSegment } from \"./utils/decode\";\n\nexport function parseRoutePath(filePath: string): ParsedRoute {\n  const segments: RouteSegment[] = [];\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  const pathParts = normalizedPath.split(\"/\").filter(Boolean);\n\n  const fileName = pathParts.pop() || \"\";\n  const fileType = getRouteType(fileName);\n  const routePath = `/${pathParts.join(\"/\")}`;\n  assertBrowserStableRoutePath(routePath);\n  assertTerminalCatchAll(routePath);\n  assertUniqueRouteParameters(routePath);\n\n  for (const part of pathParts) {\n    // Route groups like `(marketing)` organize files without adding URL\n    // segments. Mirrors isRouteGroup in router.ts for programmatic routes.\n    if (part.startsWith(\"(\") && part.endsWith(\")\")) continue;\n    if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n      let segment = part.slice(1, -1);\n      const isDynamic = true;\n      let isOptional = false;\n      let isCatchAll = false;\n\n      if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n        isOptional = true;\n        segment = segment.slice(1, -1);\n        if (segment.startsWith(\"...\")) {\n          segment = segment.slice(3);\n          isCatchAll = true;\n        }\n      } else if (segment.startsWith(\"...\")) {\n        segment = segment.slice(3);\n        isCatchAll = true;\n      }\n\n      segments.push({ segment, isDynamic, isOptional, isCatchAll });\n    } else {\n      segments.push({\n        segment: part,\n        isDynamic: false,\n        isOptional: false,\n        isCatchAll: false,\n      });\n    }\n  }\n\n  return {\n    segments,\n    filePath: normalizedPath,\n    type: fileType,\n  };\n}\n\nfunction getRouteType(fileName: string): ParsedRoute[\"type\"] {\n  const baseName = fileName.replace(/\\.(tsx?|jsx?|vue|svelte|mdx?|markdown)$/, \"\");\n\n  switch (baseName) {\n    case \"page\":\n      return \"page\";\n    case \"layout\":\n      return \"layout\";\n    case \"loading\":\n      return \"loading\";\n    case \"error\":\n      return \"error\";\n    case \"not-found\":\n      return \"not-found\";\n    default:\n      return \"page\";\n  }\n}\n\nexport function segmentsToPattern(segments: RouteSegment[]): string {\n  if (segments.length === 0) return \"/\";\n\n  return (\n    \"/\" +\n    segments\n      .map((segment) => {\n        if (!segment.isDynamic) return segment.segment;\n\n        if (segment.isCatchAll) {\n          return segment.isOptional ? `*${segment.segment}?` : `*${segment.segment}`;\n        }\n\n        return `:${segment.segment}`;\n      })\n      .join(\"/\")\n  );\n}\n\nexport function matchRoute(\n  url: string,\n  segments: RouteSegment[],\n): { params: Record<string, string>; matches: boolean } {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  const params: Record<string, string> = {};\n  if (segments.length === 0) {\n    return { params, matches: urlParts.length === 0 };\n  }\n\n  let urlIndex = 0;\n  let segmentIndex = 0;\n\n  while (segmentIndex < segments.length && urlIndex <= urlParts.length) {\n    const segment = segments[segmentIndex];\n\n    if (!segment.isDynamic) {\n      if (urlParts[urlIndex] !== segment.segment) {\n        return { params: {}, matches: false };\n      }\n      urlIndex++;\n      segmentIndex++;\n    } else if (segment.isCatchAll) {\n      const remainingParts = urlParts.slice(urlIndex);\n\n      if (remainingParts.length === 0 && !segment.isOptional) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = remainingParts.join(\"/\");\n      urlIndex = urlParts.length;\n      segmentIndex++;\n    } else {\n      if (urlIndex >= urlParts.length) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = urlParts[urlIndex];\n      urlIndex++;\n      segmentIndex++;\n    }\n  }\n\n  const matches = segmentIndex === segments.length && urlIndex === urlParts.length;\n\n  return { params, matches };\n}\n\n/** Match a route segment chain as an owner of the pathname or one of its descendants. */\nexport function matchRoutePrefix(url: string, segments: RouteSegment[]): boolean {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  let urlIndex = 0;\n\n  for (const segment of segments) {\n    if (segment.isCatchAll) {\n      return segment.isOptional || urlIndex < urlParts.length;\n    }\n\n    const urlPart = urlParts[urlIndex];\n    if (urlPart === undefined) return false;\n    if (!segment.isDynamic && segment.segment !== urlPart) return false;\n    urlIndex++;\n  }\n\n  return true;\n}\n\nexport function resolveAppPath(root: string, ...paths: string[]): string {\n  return path.resolve(root, ...paths);\n}\n\n/**\n * Convert an absolute module path inside the project root to a root-relative\n * URL path with forward slashes (e.g. `/src/app/page.tsx`), for values the\n * client passes to dynamic `import()`. On Windows the naive root-prefix slice\n * yields `\\src\\app\\page.tsx`, which is not a valid module specifier. Returns\n * undefined for paths outside the root so callers keep their own fallbacks.\n */\nexport function toRootRelativeUrlPath(\n  absolutePath: string,\n  projectRoot: string,\n): string | undefined {\n  if (absolutePath === projectRoot) return \"\";\n  if (absolutePath.startsWith(`${projectRoot}/`) || absolutePath.startsWith(`${projectRoot}\\\\`)) {\n    return absolutePath.slice(projectRoot.length).replace(/\\\\/g, \"/\");\n  }\n  return undefined;\n}\n\n/**\n * Normalize a filesystem path to forward slashes. Node's fs accepts these on\n * every platform, and module ids handed to bundlers (e.g. Nitro handler and\n * task entries) must not contain backslashes.\n */\nexport function toPosixPath(filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\");\n}\n\nexport function toViteModuleId(filePath: string, root: string): string {\n  if (!path.isAbsolute(filePath)) return filePath;\n\n  const relativePath = path.relative(root, filePath);\n  if (relativePath && !relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n    return `/${relativePath.split(path.sep).join(\"/\")}`;\n  }\n\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  return normalizedPath.startsWith(\"/\") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n  try {\n    const fs = await import(\"fs/promises\");\n    await fs.access(filePath);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function globFiles(pattern: string, cwd: string): Promise<string[]> {\n  const glob = await import(\"fast-glob\");\n  return glob.default(pattern, { cwd, absolute: false });\n}\n\nexport function parseSearchParams(\n  searchParams: URLSearchParams,\n): Record<string, string | string[]> {\n  return searchParamsToObject(searchParams) as Record<string, string | string[]>;\n}\n\nexport const logger = {\n  info: (message: string) => console.log(`[info] ${message}`),\n  success: (message: string) => console.log(`[success] ${message}`),\n  warn: (message: string) => console.warn(`⚠️  ${message}`),\n  error: (message: string) => console.error(`❌ ${message}`),\n  ready: (message: string) => console.log(`${message}`),\n  event: (message: string) => console.log(`  ${message}`),\n};\n","import { createStorage, prefixStorage, builtinDrivers, type BuiltinDriverName } from \"unstorage\";\nimport type { Driver, Storage, TransactionOptions } from \"unstorage\";\nimport type { Database } from \"db0\";\nimport memoryDriver from \"unstorage/drivers/memory\";\nimport type {\n  FarmStorageClient,\n  FarmStorageClientConfig,\n  FarmStorageConfigObject,\n  FarmStorageLocalDriverConfig,\n  FarmStorageDatabaseConfig,\n  FarmStorageDatabaseDriverMap,\n  FarmStorageDatabaseDriverName,\n  FarmStorageRuntimeClient,\n  FarmStorageMountConfig,\n  FarmStorageMounts,\n  FarmStorageUserConfig,\n} from \"./types\";\n\nexport type {\n  FarmStorageBuiltinDriverConfig,\n  FarmStorageClient,\n  FarmStorageClientConfig,\n  FarmStorageConfigObject,\n  FarmStorageCustomDriverConfig,\n  FarmStorageDatabaseConfig,\n  FarmStorageDatabaseDriverName,\n  FarmStorageLocalDriverConfig,\n  FarmStorageRuntimeClient,\n  FarmStorageMountConfig,\n  FarmStorageMounts,\n  FarmStorageUserConfig,\n} from \"./types\";\nexport type {\n  BuiltinDriverName,\n  BuiltinDriverOptions,\n  Driver,\n  Storage,\n  StorageMeta,\n  StorageValue,\n  TransactionOptions,\n} from \"unstorage\";\nexport type { ConnectorName, ConnectorOptions, Database } from \"db0\";\n\ntype DriverFactoryModule = {\n  default: (options?: Record<string, any>) => Driver;\n};\n\ntype DriverResolver = () => Driver | Promise<Driver>;\ntype ModuleLoader = <T = any>(specifier: string) => Promise<T>;\n\nconst loadModule: ModuleLoader = (specifier) => import(/* @vite-ignore */ specifier);\n\nconst DATABASE_CONNECTORS: {\n  [K in FarmStorageDatabaseDriverName]: {\n    connector: FarmStorageDatabaseDriverMap[K];\n    load: () => Promise<{ default: (options?: any) => any }>;\n  };\n} = {\n  sqlite: {\n    connector: \"node-sqlite\",\n    load: () => loadModule(\"db0/connectors/node-sqlite\"),\n  },\n  \"node-sqlite\": {\n    connector: \"node-sqlite\",\n    load: () => loadModule(\"db0/connectors/node-sqlite\"),\n  },\n  sqlite3: {\n    connector: \"sqlite3\",\n    load: () => loadModule(\"db0/connectors/sqlite3\"),\n  },\n  \"better-sqlite3\": {\n    connector: \"better-sqlite3\",\n    load: () => loadModule(\"db0/connectors/better-sqlite3\"),\n  },\n  postgres: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  postgresql: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  pg: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  mysql: {\n    connector: \"mysql2\",\n    load: () => loadModule(\"db0/connectors/mysql2\"),\n  },\n  mysql2: {\n    connector: \"mysql2\",\n    load: () => loadModule(\"db0/connectors/mysql2\"),\n  },\n  pglite: {\n    connector: \"pglite\",\n    load: () => loadModule(\"db0/connectors/pglite\"),\n  },\n  planetscale: {\n    connector: \"planetscale\",\n    load: () => loadModule(\"db0/connectors/planetscale\"),\n  },\n  libsql: {\n    connector: \"libsql\",\n    load: () => loadModule(\"db0/connectors/libsql/node\"),\n  },\n  \"libsql-node\": {\n    connector: \"libsql-node\",\n    load: () => loadModule(\"db0/connectors/libsql/node\"),\n  },\n  \"libsql-http\": {\n    connector: \"libsql-http\",\n    load: () => loadModule(\"db0/connectors/libsql/http\"),\n  },\n};\n\nfunction createMemoryStorage(): Storage {\n  return createStorage({\n    driver: memoryDriver(),\n  });\n}\n\nconst GLOBAL_STORAGE_KEY = Symbol.for(\"farmjs.storage.global\");\n\nfunction readGlobalStorage(): Storage | undefined {\n  return (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY];\n}\n\nfunction writeGlobalStorage(storage: Storage): Storage {\n  (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY] = storage;\n  return storage;\n}\n\nfunction getActiveGlobalStorage(): Storage {\n  const existing = readGlobalStorage();\n  if (existing) {\n    return existing;\n  }\n  return writeGlobalStorage(createMemoryStorage());\n}\n\nlet globalStorage = getActiveGlobalStorage();\n\nfunction normalizeMountKey(base?: string): string {\n  return (base || \"\")\n    .trim()\n    .replace(/^[:/\\\\]+|[:/\\\\]+$/g, \"\")\n    .replace(/[\\\\/]+/g, \":\");\n}\n\nfunction isDriverInstance(value: unknown): value is Driver {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as Driver).getItem === \"function\" &&\n    typeof (value as Driver).getKeys === \"function\"\n  );\n}\n\nfunction isStorageInstance(value: unknown): value is Storage {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as Storage).mount === \"function\" &&\n    typeof (value as Storage).getMount === \"function\"\n  );\n}\n\nfunction isStorageClient(value: unknown): value is FarmStorageClient {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (value as FarmStorageClient).kind === \"farm-storage-client\" &&\n    typeof (value as FarmStorageClient).resolveDriver === \"function\" &&\n    typeof (value as FarmStorageClient).createStorage === \"function\"\n  );\n}\n\nfunction isDatabaseDriverName(name: string): name is FarmStorageDatabaseDriverName {\n  return name in DATABASE_CONNECTORS;\n}\n\nfunction extractDriverOptions(config: FarmStorageClientConfig): Record<string, any> | undefined {\n  const source = config as Record<string, any>;\n  const {\n    client: _client,\n    driver: _driver,\n    mounts: _mounts,\n    options,\n    tableName: _tableName,\n    ...inlineOptions\n  } = source;\n  const hasInlineOptions = Object.keys(inlineOptions).length > 0;\n\n  if (options && typeof options === \"object\" && !Array.isArray(options)) {\n    return hasInlineOptions ? { ...inlineOptions, ...options } : options;\n  }\n\n  if (hasInlineOptions) {\n    return inlineOptions;\n  }\n\n  return options;\n}\n\nasync function loadBuiltinDriver(\n  name: BuiltinDriverName,\n  options?: Record<string, any>,\n): Promise<Driver> {\n  const modulePath = builtinDrivers[name];\n\n  if (!modulePath) {\n    throw new Error(`Unsupported storage driver \"${name}\".`);\n  }\n\n  const module = (await loadModule(modulePath)) as DriverFactoryModule;\n  return module.default(options);\n}\n\nasync function loadDatabaseDriver(config: FarmStorageDatabaseConfig): Promise<Driver> {\n  const connectorEntry = DATABASE_CONNECTORS[config.driver as FarmStorageDatabaseDriverName];\n  const [{ createDatabase }, connectorModule, db0DriverModule] = await Promise.all([\n    loadModule<typeof import(\"db0\")>(\"db0\"),\n    connectorEntry.load(),\n    loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\"),\n  ]);\n\n  const database = createDatabase(connectorModule.default(extractDriverOptions(config) || {}));\n  const driver = db0DriverModule.default({\n    database,\n    tableName: config.tableName,\n  });\n\n  // The db0 driver has no dispose, so this connection is Farm's to close. Databases\n  // handed to `databaseStorage` stay owned by the caller and are left open.\n  return {\n    ...driver,\n    async dispose() {\n      await driver.dispose?.();\n      await database.dispose();\n    },\n  };\n}\n\nasync function resolveDriver(config?: FarmStorageMountConfig): Promise<Driver> {\n  if (config && isStorageClient(config)) {\n    return config.resolveDriver();\n  }\n\n  const driverInput = config?.driver ?? \"memory\";\n\n  if (typeof driverInput === \"function\") {\n    return await driverInput();\n  }\n\n  if (isDriverInstance(driverInput)) {\n    return driverInput;\n  }\n\n  if (isDatabaseDriverName(driverInput)) {\n    return loadDatabaseDriver(config as FarmStorageDatabaseConfig);\n  }\n\n  if (driverInput === \"local\") {\n    return loadBuiltinDriver(\"fs-lite\", extractDriverOptions(config as FarmStorageMountConfig));\n  }\n\n  return loadBuiltinDriver(\n    driverInput as BuiltinDriverName,\n    extractDriverOptions(config as FarmStorageClientConfig),\n  );\n}\n\nfunction createStorageClientFromResolver(resolveDriver: DriverResolver): FarmStorageClient {\n  let driverPromise: Promise<Driver> | undefined;\n  let storagePromise: Promise<Storage> | undefined;\n\n  const ensureDriver = () => {\n    if (driverPromise) return driverPromise;\n\n    const pending = Promise.resolve().then(resolveDriver);\n    driverPromise = pending;\n    void pending.catch(() => {\n      if (driverPromise === pending) {\n        driverPromise = undefined;\n        storagePromise = undefined;\n      }\n    });\n    return pending;\n  };\n\n  const ensureStorage = () => {\n    if (storagePromise) return storagePromise;\n\n    const pending = ensureDriver().then((driver) =>\n      createStorage({\n        driver,\n      }),\n    );\n    storagePromise = pending;\n    void pending.catch(() => {\n      if (storagePromise === pending) storagePromise = undefined;\n    });\n    return pending;\n  };\n\n  const target = {\n    kind: \"farm-storage-client\" as const,\n    ready: ensureStorage,\n    createStorage: ensureStorage,\n    resolveDriver: ensureDriver,\n  };\n\n  return new Proxy(target as FarmStorageClient, {\n    get(currentTarget, prop, receiver) {\n      if (prop === \"then\") {\n        return undefined;\n      }\n\n      if (Reflect.has(currentTarget, prop)) {\n        return Reflect.get(currentTarget, prop, receiver);\n      }\n\n      return (...args: any[]) =>\n        ensureStorage().then(async (storage) => {\n          const member = Reflect.get(storage as object, prop);\n\n          if (typeof member !== \"function\") {\n            return member;\n          }\n\n          const result = Reflect.apply(member, storage, args);\n\n          if (prop === \"dispose\") {\n            return Promise.resolve(result).finally(() => {\n              // Disposing the storage also disposed the driver, so drop both\n              // cached promises: a later call must re-run the driver factory\n              // instead of rebuilding storage over the dead driver.\n              storagePromise = undefined;\n              driverPromise = undefined;\n            });\n          }\n\n          return result;\n        });\n    },\n  });\n}\n\nexport function defineStorageClient(resolveDriver: DriverResolver): FarmStorageClient {\n  return createStorageClientFromResolver(resolveDriver);\n}\n\nexport function createStorageClient(config: FarmStorageClientConfig): FarmStorageClient {\n  return defineStorageClient(() => resolveDriver(config));\n}\n\nexport function driverStorage(\n  driver: Driver | (() => Driver | Promise<Driver>),\n): FarmStorageClient {\n  return defineStorageClient(() => (typeof driver === \"function\" ? driver() : driver));\n}\n\nexport function databaseStorage(\n  database: Database,\n  options: { tableName?: string } = {},\n): FarmStorageClient {\n  return defineStorageClient(async () => {\n    const db0DriverModule =\n      await loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\");\n    return db0DriverModule.default({\n      database,\n      tableName: options.tableName,\n    });\n  });\n}\n\nexport function memoryStorage(): FarmStorageClient {\n  return createStorageClient({ driver: \"memory\" });\n}\n\nexport function localStorage(options: Omit<FarmStorageLocalDriverConfig, \"driver\"> = {}) {\n  return createStorageClient({\n    driver: \"local\",\n    ...options,\n  });\n}\n\nexport function sqliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"sqlite\",\n    ...options,\n  });\n}\n\nexport function mysqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"mysql\",\n    ...options,\n  });\n}\n\nexport function mysql2Storage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return mysqlStorage(options);\n}\n\nexport function postgresStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"postgres\",\n    ...options,\n  });\n}\n\nexport function pgStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return postgresStorage(options);\n}\n\nexport function pgliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"pglite\",\n    ...options,\n  });\n}\n\nexport function planetscaleStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"planetscale\",\n    ...options,\n  });\n}\n\nexport function libsqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"libsql\",\n    ...options,\n  });\n}\n\nexport function redisStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"redis\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"redis\",\n    ...options,\n  });\n}\n\nexport function s3Storage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"s3\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"s3\",\n    ...options,\n  });\n}\n\nexport function mongodbStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"mongodb\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"mongodb\",\n    ...options,\n  });\n}\n\nexport function upstashStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"upstash\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"upstash\",\n    ...options,\n  });\n}\n\nexport function netlifyBlobsStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"netlify-blobs\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"netlify-blobs\",\n    ...options,\n  });\n}\n\nexport function vercelKVStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-kv\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"vercel-kv\",\n    ...options,\n  });\n}\n\nexport function vercelBlobStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-blob\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"vercel-blob\",\n    ...options,\n  });\n}\n\nasync function mountNamespaces(storage: Storage, mounts?: FarmStorageMounts): Promise<void> {\n  if (!mounts) {\n    return;\n  }\n\n  for (const [base, config] of Object.entries(mounts)) {\n    storage.mount(normalizeMountKey(base), await resolveDriver(config));\n  }\n}\n\nexport async function createFarmStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n  if (isStorageInstance(config)) {\n    return config;\n  }\n\n  if (isStorageClient(config)) {\n    return config.createStorage();\n  }\n\n  const rootConfig = isStorageClient(config.client) ? config.client : config;\n  const storage = createStorage({\n    driver: await resolveDriver(rootConfig),\n  });\n\n  try {\n    await mountNamespaces(storage, config.mounts);\n  } catch (error) {\n    await storage.dispose().catch(() => {});\n    throw error;\n  }\n  return storage;\n}\n\nexport async function resolveStorageRuntimeClient(\n  config: FarmStorageUserConfig | undefined,\n): Promise<unknown | undefined> {\n  if (!config || isStorageInstance(config) || isStorageClient(config)) {\n    return undefined;\n  }\n\n  const client = config.client;\n  if (!client || isStorageInstance(client) || isStorageClient(client)) {\n    return undefined;\n  }\n\n  return typeof client === \"function\" ? await client() : client;\n}\n\nexport async function initStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n  globalStorage = getActiveGlobalStorage();\n  const nextStorage = await createFarmStorage(config);\n  const previousStorage = globalStorage;\n  globalStorage = writeGlobalStorage(nextStorage);\n\n  if (previousStorage !== nextStorage) {\n    await previousStorage.dispose().catch(() => {});\n  }\n\n  return globalStorage;\n}\n\nexport function getStorage(namespace?: string): Storage {\n  globalStorage = getActiveGlobalStorage();\n  const base = normalizeMountKey(namespace);\n  if (!base) {\n    return globalStorage;\n  }\n\n  const namespaced = prefixStorage(globalStorage, base);\n  return {\n    ...namespaced,\n    // Scope the wipe to the namespace instead of the whole storage, and keep\n    // the caller's base so `clear(\"sessions\")` cannot take unrelated keys with\n    // it. Dropping the argument silently widens a targeted clear into a\n    // namespace-wide delete.\n    async clear(base?: string, opts?: TransactionOptions) {\n      const keys = await namespaced.getKeys(base);\n      await Promise.all(keys.map((key) => namespaced.removeItem(key, opts)));\n    },\n  } as Storage;\n}\n\nexport async function disposeStorage(): Promise<void> {\n  globalStorage = getActiveGlobalStorage();\n  const previousStorage = globalStorage;\n  globalStorage = writeGlobalStorage(createMemoryStorage());\n  await previousStorage.dispose().catch(() => {});\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","import { localizeFarmHref, resolveFarmLocalePath } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { assertBrowserStableRoutePath } from \"../routing/specificity\";\n\ntype ConfigRoutePatternToken =\n  | { kind: \"param\"; name: string; captureIndex: number; catchAll: boolean }\n  | { kind: \"wildcard\"; captureIndex: number };\n\nexport interface CompiledConfigRoutePattern {\n  regex: RegExp;\n  tokens: ConfigRoutePatternToken[];\n}\n\nexport function validateConfigRouteSource(source: string, field = \"Config route source\"): string {\n  if (typeof source !== \"string\" || source.length === 0) {\n    throw new TypeError(`${field} must be a non-empty pathname pattern.`);\n  }\n  if (source.trim() !== source) {\n    throw new Error(`${field} cannot contain leading or trailing whitespace.`);\n  }\n  if (!source.startsWith(\"/\")) {\n    throw new Error(`${field} must start with \"/\".`);\n  }\n  if (source.includes(\"?\") || source.includes(\"#\")) {\n    throw new Error(`${field} must be a pathname without a query string or hash.`);\n  }\n  if (\n    source.includes(\"\\\\\") ||\n    Array.from(source).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  ) {\n    throw new Error(`${field} cannot contain backslashes or control characters.`);\n  }\n  assertBrowserStableRoutePath(source);\n  return source;\n}\n\nexport function resolveConfigRoutePathname(\n  pathname: string,\n  i18n?: ResolvedFarmI18nConfig,\n): { pathname: string; locale?: string } {\n  if (!i18n?.enabled) return { pathname };\n  const match = resolveFarmLocalePath(pathname, i18n);\n  return { pathname: match.pathname, locale: match.locale };\n}\n\nexport function localizeConfigRouteDestination(\n  destination: string,\n  locale: string | undefined,\n  i18n?: ResolvedFarmI18nConfig,\n): string {\n  return locale && i18n?.enabled ? localizeFarmHref(destination, locale, i18n) : destination;\n}\n\nfunction escapeRegexCharacter(character: string): string {\n  return /[\\\\^$.*+?()[\\]{}|]/.test(character) ? `\\\\${character}` : character;\n}\n\nexport function compileConfigRoutePattern(source: string): CompiledConfigRoutePattern {\n  validateConfigRouteSource(source);\n  const tokens: ConfigRoutePatternToken[] = [];\n  let pattern = \"\";\n  let captureIndex = 1;\n\n  for (let index = 0; index < source.length; ) {\n    const rest = source.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      tokens.push({\n        kind: \"param\",\n        name: parameter[1],\n        captureIndex,\n        catchAll: parameter[2] === \"*\",\n      });\n      pattern += parameter[2] ? \"(.*)\" : \"([^/]+)\";\n      captureIndex += 1;\n      index += parameter[0].length;\n      continue;\n    }\n\n    if (source[index] === \"*\") {\n      tokens.push({ kind: \"wildcard\", captureIndex });\n      pattern += \"(.*)\";\n      captureIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    pattern += escapeRegexCharacter(source[index]);\n    index += 1;\n  }\n\n  return { regex: new RegExp(`^${pattern}$`), tokens };\n}\n\nexport function interpolateConfigRouteDestination(\n  destination: string,\n  match: RegExpMatchArray,\n  tokens: readonly ConfigRoutePatternToken[],\n): string {\n  const namedCaptures = new Map<string, string>();\n  const wildcardCaptures: string[] = [];\n  const captures = new Map<number, string>();\n\n  for (const token of tokens) {\n    const value = normalizeConfigRouteCapture(\n      match[token.captureIndex] || \"\",\n      token.kind === \"wildcard\" || token.catchAll,\n    );\n    captures.set(token.captureIndex, value);\n    if (token.kind === \"param\") {\n      namedCaptures.set(token.name, value);\n    } else {\n      wildcardCaptures.push(value);\n    }\n  }\n\n  let result = \"\";\n  let wildcardIndex = 0;\n  for (let index = 0; index < destination.length; ) {\n    const rest = destination.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      const value = namedCaptures.get(parameter[1]);\n      result += value === undefined ? parameter[0] : value;\n      index += parameter[0].length;\n      continue;\n    }\n\n    const capture = rest.match(/^\\$(\\d+)/);\n    if (capture) {\n      result += captures.get(Number(capture[1])) ?? \"\";\n      index += capture[0].length;\n      continue;\n    }\n\n    if (destination[index] === \"*\") {\n      result += wildcardCaptures[wildcardIndex] || \"\";\n      wildcardIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    result += destination[index];\n    index += 1;\n  }\n\n  return result;\n}\n\nfunction normalizeConfigRouteCapture(value: string, catchAll: boolean): string {\n  const segments = catchAll ? value.split(\"/\").filter(Boolean) : [value];\n  return segments\n    .map((segment) => encodeConfigRouteSegment(decodeConfigRouteSegment(segment)))\n    .join(\"/\");\n}\n\nfunction decodeConfigRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction encodeConfigRouteSegment(segment: string): string {\n  return encodeURIComponent(segment).replace(\n    /[!'()*]/g,\n    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n}\n","/**\n * Shared request-origin primitives.\n *\n * Server actions and integration auth routes both need to decide whether a\n * state-changing request actually came from the app's own origin. The matching\n * rules (Origin/Referer resolution, Host fallback, wildcard subdomain patterns)\n * are security-sensitive and must not drift between the two, so they live here\n * and are consumed by both rather than reimplemented.\n *\n * These helpers never throw for untrusted input: callers map the failure\n * reasons onto their own error shapes.\n */\n\nexport type RequestOriginFailureReason = \"opaque-origin\" | \"invalid-origin\";\n\nexport type RequestSourceOriginResult =\n  /** `origin` is null when the request carried no Origin or Referer header. */\n  { ok: true; origin: string | null } | { ok: false; reason: RequestOriginFailureReason };\n\n/** Resolve the origin a request claims to come from, preferring Origin over Referer. */\nexport function getRequestSourceOrigin(request: Request): RequestSourceOriginResult {\n  const origin = request.headers.get(\"origin\")?.trim();\n  if (origin) {\n    return parseSourceOrigin(origin);\n  }\n\n  const referer = request.headers.get(\"referer\")?.trim();\n  if (referer) {\n    return parseSourceOrigin(referer);\n  }\n\n  return { ok: true, origin: null };\n}\n\nfunction parseSourceOrigin(value: string): RequestSourceOriginResult {\n  if (value === \"null\") {\n    return { ok: false, reason: \"opaque-origin\" };\n  }\n\n  try {\n    const parsed = new URL(value);\n    if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n      return { ok: false, reason: \"invalid-origin\" };\n    }\n    return { ok: true, origin: parsed.origin };\n  } catch {\n    return { ok: false, reason: \"invalid-origin\" };\n  }\n}\n\n/**\n * Accept a source origin that matches the Host header even when `request.url`\n * was rebuilt behind a proxy with a different visible origin.\n */\nexport function matchesHostHeader(sourceOrigin: string, request: Request): boolean {\n  const host = request.headers.get(\"host\")?.trim().toLowerCase();\n  if (!host) return false;\n\n  try {\n    const source = new URL(sourceOrigin);\n    const target = new URL(request.url);\n    return source.protocol === target.protocol && source.host.toLowerCase() === host;\n  } catch {\n    return false;\n  }\n}\n\nexport function matchesAllowedOrigin(sourceOrigin: string, pattern: string): boolean {\n  const source = new URL(sourceOrigin);\n  if (!pattern.includes(\"*\")) {\n    return pattern.includes(\"://\") ? source.origin === pattern : source.host === pattern;\n  }\n\n  const schemeEnd = pattern.indexOf(\"://\");\n  const scheme = schemeEnd === -1 ? null : pattern.slice(0, schemeEnd + 1);\n  const hostPattern = pattern.slice(schemeEnd === -1 ? 0 : schemeEnd + 3);\n  const [wildcardHost, port] = splitHostAndPort(hostPattern);\n  const baseHost = wildcardHost.slice(2);\n\n  if (scheme && source.protocol !== scheme) return false;\n  if (port && getEffectivePort(source) !== port) return false;\n  if (!port && source.port) return false;\n\n  return source.hostname.endsWith(`.${baseHost}`) && source.hostname !== baseHost;\n}\n\n/**\n * Validate and canonicalize a configured origin pattern. `label` names the\n * configuration field so the thrown message points at the user's own setting.\n */\nexport function normalizeAllowedOriginPattern(value: string, label: string): string {\n  const pattern = value.trim().toLowerCase();\n  if (!pattern) {\n    throw new TypeError(`${label} cannot contain empty values`);\n  }\n\n  if (pattern.includes(\"*\")) {\n    if (!/^(?:https?:\\/\\/)?\\*\\.[a-z0-9.-]+(?::\\d+)?$/.test(pattern)) {\n      throw new TypeError(`Invalid ${label} pattern: ${JSON.stringify(value)}`);\n    }\n    return pattern;\n  }\n\n  if (pattern.includes(\"://\")) {\n    let parsed: URL;\n    try {\n      parsed = new URL(pattern);\n    } catch {\n      throw new TypeError(`Invalid ${label} value: ${JSON.stringify(value)}`);\n    }\n\n    if (\n      (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n      parsed.username ||\n      parsed.password ||\n      parsed.pathname !== \"/\" ||\n      parsed.search ||\n      parsed.hash\n    ) {\n      throw new TypeError(`${label} must contain origins without paths: ${JSON.stringify(value)}`);\n    }\n    return parsed.origin;\n  }\n\n  if (/[/@?#]/.test(pattern)) {\n    throw new TypeError(`${label} must contain origins or hosts: ${JSON.stringify(value)}`);\n  }\n\n  try {\n    return new URL(`http://${pattern}`).host;\n  } catch {\n    throw new TypeError(`Invalid ${label} value: ${JSON.stringify(value)}`);\n  }\n}\n\nfunction splitHostAndPort(value: string): [string, string | null] {\n  const separator = value.lastIndexOf(\":\");\n  if (separator === -1) return [value, null];\n  return [value.slice(0, separator), value.slice(separator + 1)];\n}\n\nfunction getEffectivePort(url: URL): string {\n  if (url.port) return url.port;\n  if (url.protocol === \"https:\") return \"443\";\n  if (url.protocol === \"http:\") return \"80\";\n  return \"\";\n}\n","import {\n  getRequestSourceOrigin,\n  matchesAllowedOrigin,\n  matchesHostHeader,\n  normalizeAllowedOriginPattern,\n} from \"./request-origin\";\n\n/**\n * Integration auth routes accept ordinary form posts, which browsers send\n * cross-site without a CORS preflight. Without an origin check, a third-party\n * page can submit credentials to an app's own sign-in route and plant an\n * attacker-controlled session in the victim's browser (login CSRF), or drive a\n * forced sign-out. This mirrors the server-action origin contract so both\n * entry points reject the same requests.\n */\n\nexport type IntegrationOriginRejection =\n  | \"missing-origin\"\n  | \"opaque-origin\"\n  | \"invalid-origin\"\n  | \"cross-site\";\n\nexport type IntegrationOriginResult =\n  | { ok: true }\n  | { ok: false; reason: IntegrationOriginRejection };\n\nexport interface IntegrationOriginPolicy {\n  /** Extra trusted origins, using the `serverActions.allowedOrigins` pattern syntax. */\n  allowedOrigins?: readonly string[];\n  /**\n   * Whether a request carrying no origin metadata at all must be rejected.\n   *\n   * Form posts always carry an Origin header in supported browsers, so\n   * state-changing POSTs default to rejecting (`true`). Top-level GET\n   * navigations legitimately arrive with no Origin and no Referer — a typed\n   * URL or a bookmark — so GET callers pass `false` to avoid breaking them.\n   */\n  requireOriginMetadata?: boolean;\n}\n\n/**\n * Resolve configured origin patterns once, at integration construction, so an\n * invalid pattern fails loudly at startup instead of per request.\n */\nexport function resolveIntegrationAllowedOrigins(\n  values: readonly string[] | undefined,\n  label: string,\n): readonly string[] {\n  return Object.freeze((values ?? []).map((value) => normalizeAllowedOriginPattern(value, label)));\n}\n\nexport function validateIntegrationRequestOrigin(\n  request: Request,\n  policy: IntegrationOriginPolicy = {},\n): IntegrationOriginResult {\n  const allowedOrigins = policy.allowedOrigins ?? [];\n  const requireOriginMetadata = policy.requireOriginMetadata ?? true;\n  const fetchSite = request.headers.get(\"sec-fetch-site\")?.trim().toLowerCase();\n  const source = getRequestSourceOrigin(request);\n\n  if (!source.ok) {\n    return { ok: false, reason: source.reason };\n  }\n\n  if (source.origin === null) {\n    // No Origin and no Referer. `sec-fetch-site: same-origin` still proves the\n    // request is first-party.\n    if (fetchSite === \"same-origin\") {\n      return { ok: true };\n    }\n\n    // Strict mode (state-changing POSTs) has nothing left to verify against.\n    if (requireOriginMetadata) {\n      return { ok: false, reason: fetchSite === \"cross-site\" ? \"cross-site\" : \"missing-origin\" };\n    }\n\n    // Lenient mode still rejects a request the browser labelled cross-site.\n    // Everything else here is a direct navigation (`none`), a same-site\n    // navigation, or a client too old to send Sec-Fetch-Site at all.\n    return fetchSite === \"cross-site\" ? { ok: false, reason: \"cross-site\" } : { ok: true };\n  }\n\n  const requestUrl = new URL(request.url);\n  const matchesConfiguredOrigin = allowedOrigins.some((pattern) =>\n    matchesAllowedOrigin(source.origin as string, pattern),\n  );\n  const matchesRequest =\n    source.origin === requestUrl.origin || matchesHostHeader(source.origin, request);\n\n  if (!matchesRequest && !matchesConfiguredOrigin) {\n    return { ok: false, reason: \"cross-site\" };\n  }\n\n  if (fetchSite === \"cross-site\" && !matchesConfiguredOrigin) {\n    return { ok: false, reason: \"cross-site\" };\n  }\n\n  return { ok: true };\n}\n\nexport function describeIntegrationOriginRejection(reason: IntegrationOriginRejection): string {\n  switch (reason) {\n    case \"missing-origin\":\n      return \"Request is missing same-origin metadata.\";\n    case \"opaque-origin\":\n      return \"Opaque origins are not allowed.\";\n    case \"invalid-origin\":\n      return \"Invalid request origin.\";\n    case \"cross-site\":\n      return \"Cross-site request was rejected.\";\n  }\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 type { FarmPlugin, FarmPluginIntegrationContext } from \"./plugin\";\n\nconst FARM_PLUGIN_INTEGRATION_CONTEXT = Symbol.for(\"@farm.js/core/plugin-integration-context\");\n\nexport function setFarmPluginIntegrationContext(\n  plugin: FarmPlugin,\n  integration: Readonly<FarmPluginIntegrationContext>,\n): void {\n  Object.defineProperty(plugin, FARM_PLUGIN_INTEGRATION_CONTEXT, {\n    value: integration,\n  });\n}\n\nexport function getFarmPluginIntegrationContext(\n  plugin: FarmPlugin,\n): Readonly<FarmPluginIntegrationContext> | undefined {\n  const value = (plugin as FarmPlugin & Record<symbol, unknown>)[FARM_PLUGIN_INTEGRATION_CONTEXT];\n  return value && typeof value === \"object\"\n    ? (value as Readonly<FarmPluginIntegrationContext>)\n    : undefined;\n}\n","type RequestContextCarrier = object;\n\nexport interface SetRequestContextOptions {\n  exposeToPage?: boolean;\n}\n\nexport interface RequestContextSnapshotOptions {\n  exposedOnly?: boolean;\n}\n\ninterface RequestContextBucket {\n  privateData: Map<string, any>;\n  exposedData: Map<string, any>;\n}\n\nconst REQUEST_CONTEXT_STORE_KEY = Symbol.for(\"farm.requestContextStore\");\n\ntype GlobalWithRequestContextStore = typeof globalThis & {\n  [REQUEST_CONTEXT_STORE_KEY]?: WeakMap<RequestContextCarrier, RequestContextBucket>;\n};\n\nfunction getRequestContextStore() {\n  const globalState = globalThis as GlobalWithRequestContextStore;\n  if (!globalState[REQUEST_CONTEXT_STORE_KEY]) {\n    globalState[REQUEST_CONTEXT_STORE_KEY] = new WeakMap<\n      RequestContextCarrier,\n      RequestContextBucket\n    >();\n  }\n\n  return globalState[REQUEST_CONTEXT_STORE_KEY]!;\n}\n\nfunction getBucket(target: RequestContextCarrier): RequestContextBucket {\n  const requestContextStore = getRequestContextStore();\n  let bucket = requestContextStore.get(target);\n  if (!bucket) {\n    bucket = {\n      privateData: new Map<string, any>(),\n      exposedData: new Map<string, any>(),\n    };\n    requestContextStore.set(target, bucket);\n  }\n  return bucket;\n}\n\nexport function setRequestContext(\n  target: RequestContextCarrier,\n  key: string,\n  value: any,\n  options: SetRequestContextOptions = {},\n): void {\n  const bucket = getBucket(target);\n  bucket.privateData.set(key, value);\n  if (options.exposeToPage) {\n    bucket.exposedData.set(key, value);\n  }\n}\n\nexport function getRequestContext<T = any>(\n  target: RequestContextCarrier,\n  key: string,\n): T | undefined {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  return bucket?.privateData.get(key) as T | undefined;\n}\n\nexport function hasRequestContext(target: RequestContextCarrier, key: string): boolean {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  return bucket?.privateData.has(key) ?? false;\n}\n\nexport function deleteRequestContext(target: RequestContextCarrier, key: string): boolean {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return false;\n  const removedPrivate = bucket.privateData.delete(key);\n  bucket.exposedData.delete(key);\n  return removedPrivate;\n}\n\nexport function clearRequestContext(target: RequestContextCarrier): void {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return;\n  bucket.privateData.clear();\n  bucket.exposedData.clear();\n}\n\nexport function getRequestContextSnapshot(\n  target: RequestContextCarrier,\n  options: RequestContextSnapshotOptions = {},\n): Map<string, any> {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return new Map<string, any>();\n  if (options.exposedOnly) {\n    return new Map(bucket.exposedData);\n  }\n  return new Map(bucket.privateData);\n}\n","import type { ServerResponse } from \"node:http\";\n\ninterface ResponseEventWatcher<T> {\n  promise: Promise<T>;\n  dispose(): void;\n}\n\n/**\n * Watch a real Node response without requiring every Node-compatible response\n * adapter or test double to extend EventEmitter. The framework only needs\n * disconnect handling when the response exposes both halves of the listener\n * lifecycle; otherwise callers can still send ordinary non-blocked bodies.\n */\nfunction watchResponseEvent<T>(\n  res: ServerResponse,\n  events: ReadonlyArray<readonly [event: string, value: T]>,\n): ResponseEventWatcher<T> | null {\n  if (typeof res.once !== \"function\" || typeof res.removeListener !== \"function\") {\n    return null;\n  }\n\n  let settled = false;\n  const listeners = events.map(([event, value]) => {\n    const listener = () => {\n      if (settled) return;\n      settled = true;\n      dispose();\n      resolvePromise(value);\n    };\n    return { event, listener };\n  });\n  let resolvePromise!: (value: T) => void;\n  const promise = new Promise<T>((resolve) => {\n    resolvePromise = resolve;\n    for (const { event, listener } of listeners) {\n      res.once(event, listener);\n    }\n  });\n  const dispose = () => {\n    for (const { event, listener } of listeners) {\n      res.removeListener(event, listener);\n    }\n  };\n\n  return { promise, dispose };\n}\n\n/**\n * Waits until the response can accept more writes. Resolves false when the\n * client is gone (close or error): a disconnected socket never emits drain,\n * so waiting on drain alone leaks the pending handler, its reader lock, and\n * the response body for the life of the process.\n */\nasync function waitForWritable(res: ServerResponse): Promise<boolean> {\n  if (res.writableEnded || res.destroyed) {\n    return false;\n  }\n\n  const watcher = watchResponseEvent(res, [\n    [\"drain\", true],\n    [\"close\", false],\n    [\"error\", false],\n  ]);\n  if (!watcher) {\n    return false;\n  }\n\n  try {\n    return await watcher.promise;\n  } finally {\n    watcher.dispose();\n  }\n}\n\n/**\n * Older Fetch implementations expose repeated Set-Cookie fields as one\n * comma-joined value. Split only at a comma followed by another cookie-pair;\n * commas inside Expires dates remain part of the current cookie. RFC cookie\n * values exclude commas, so a comma followed by a cookie-pair is unambiguous\n * for valid Set-Cookie syntax once the original field boundaries are lost.\n */\nfunction splitSetCookieHeader(value: string): string[] {\n  const cookies: string[] = [];\n  let start = 0;\n\n  for (let index = 0; index < value.length; index += 1) {\n    if (value[index] !== \",\") continue;\n\n    let next = index + 1;\n    while (value[next] === \" \" || value[next] === \"\\t\") next += 1;\n\n    const equals = value.indexOf(\"=\", next);\n    if (equals === -1) continue;\n\n    const separator = value.slice(next, equals);\n    if (separator.length === 0 || /[;,\\s]/.test(separator)) continue;\n\n    cookies.push(value.slice(start, index).trim());\n    start = next;\n    index = next - 1;\n  }\n\n  cookies.push(value.slice(start).trim());\n  return cookies.filter(Boolean);\n}\n\nexport function applyWebResponseHeaders(\n  res: Pick<ServerResponse, \"setHeader\"> & Partial<Pick<ServerResponse, \"getHeader\">>,\n  headers: Headers,\n  options: { appendSetCookie?: boolean } = {},\n): void {\n  const responseHeaders = headers as Headers & {\n    getSetCookie?: () => string[];\n    raw?: () => Record<string, string[]>;\n  };\n  const rawSetCookies = responseHeaders.raw?.()[\"set-cookie\"];\n  const setCookies = responseHeaders.getSetCookie?.() || rawSetCookies || [];\n  const existing =\n    options.appendSetCookie && typeof res.getHeader === \"function\"\n      ? res.getHeader(\"Set-Cookie\")\n      : undefined;\n  const existingCookies = Array.isArray(existing)\n    ? existing.map(String)\n    : existing === undefined\n      ? []\n      : [String(existing)];\n\n  let fallbackSetCookie = \"\";\n  headers.forEach((value, key) => {\n    if (key.toLowerCase() === \"set-cookie\") {\n      fallbackSetCookie = value;\n      return;\n    }\n    res.setHeader(key, value);\n  });\n\n  const cookies =\n    setCookies.length > 0\n      ? setCookies\n      : fallbackSetCookie\n        ? splitSetCookieHeader(fallbackSetCookie)\n        : [];\n  if (cookies.length > 0) {\n    res.setHeader(\"Set-Cookie\", [...existingCookies, ...cookies]);\n  }\n}\n\nexport async function sendWebResponse(res: ServerResponse, response: Response): Promise<void> {\n  res.statusCode = response.status;\n  applyWebResponseHeaders(res, response.headers, { appendSetCookie: true });\n\n  if (!response.body) {\n    res.end();\n    return;\n  }\n\n  if (typeof res.write !== \"function\") {\n    const body = await response.arrayBuffer();\n    res.end(Buffer.from(body));\n    return;\n  }\n\n  const reader = response.body.getReader();\n  const disconnectWatcher = watchResponseEvent(res, [\n    [\"close\", true],\n    [\"error\", true],\n  ]);\n\n  try {\n    while (true) {\n      if (res.destroyed) {\n        // The client disconnected mid-response; drop the rest of the body so\n        // the handler can return.\n        void reader.cancel().catch(() => {});\n        return;\n      }\n\n      const read = reader.read().then((result) => ({ type: \"read\" as const, result }));\n      const next = disconnectWatcher\n        ? await Promise.race([\n            read,\n            disconnectWatcher.promise.then(() => ({ type: \"disconnect\" as const })),\n          ])\n        : await read;\n      if (next.type === \"disconnect\") {\n        void reader.cancel().catch(() => {});\n        return;\n      }\n\n      const { done, value } = next.result;\n      if (done) {\n        break;\n      }\n\n      if (!value || value.byteLength === 0) {\n        continue;\n      }\n\n      if (!res.write(value)) {\n        if (!(await waitForWritable(res))) {\n          void reader.cancel().catch(() => {});\n          return;\n        }\n      }\n    }\n\n    res.end();\n  } catch (error) {\n    // Releasing the lock does not stop the producer. Cancel it when the\n    // downstream write fails, without waiting on app-owned cleanup or letting\n    // a cancellation failure replace the original error.\n    void reader.cancel(error).catch(() => {});\n    if (!res.writableEnded) {\n      const responseError = error instanceof Error ? error : new Error(String(error));\n      if (typeof res.destroy === \"function\") {\n        res.destroy(responseError);\n      } else {\n        res.end();\n      }\n    }\n    throw error;\n  } finally {\n    disconnectWatcher?.dispose();\n    try {\n      reader.releaseLock();\n    } catch {\n      // A disconnect can win the race with a pending read. Cancelling the\n      // reader settles it asynchronously, so there may be no lock to release\n      // synchronously here.\n    }\n  }\n}\n","import { assertBrowserStableRoutePath } from \"./routing/specificity\";\n\ninterface FarmNodeAbortRequest {\n  aborted?: boolean;\n  once(event: \"aborted\", listener: () => void): unknown;\n  off(event: \"aborted\", listener: () => void): unknown;\n}\n\ninterface FarmNodeAbortResponse {\n  writableEnded: boolean;\n  once(event: \"close\" | \"finish\", listener: () => void): unknown;\n  off(event: \"close\" | \"finish\", listener: () => void): unknown;\n}\n\n/** Share disconnect semantics between development and production Node requests. */\nexport function createFarmNodeRequestAbortSignal(\n  req: FarmNodeAbortRequest,\n  res: FarmNodeAbortResponse,\n): AbortSignal {\n  const controller = new AbortController();\n  let disposed = false;\n  const dispose = () => {\n    if (disposed) return;\n    disposed = true;\n    req.off(\"aborted\", abort);\n    res.off(\"close\", abortOnEarlyClose);\n    res.off(\"finish\", dispose);\n    controller.signal.removeEventListener(\"abort\", dispose);\n  };\n  const abort = () => controller.abort();\n  const abortOnEarlyClose = () => {\n    if (!res.writableEnded) abort();\n    dispose();\n  };\n\n  if (req.aborted) {\n    controller.abort();\n    return controller.signal;\n  }\n\n  req.once(\"aborted\", abort);\n  res.once(\"close\", abortOnEarlyClose);\n  res.once(\"finish\", dispose);\n  controller.signal.addEventListener(\"abort\", dispose, { once: true });\n  return controller.signal;\n}\n\nexport const DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 10_000_000;\nexport const DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 60_000;\nexport const DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 300_000;\nexport const DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5_000;\nexport const DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 30_000;\nconst MAX_FARM_SERVER_TIMEOUT = 2_147_483_647;\n\nexport type FarmServerDuration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport interface FarmServerHealthConfig {\n  /** Liveness endpoint. It remains healthy while a production process drains. */\n  livenessPath?: string;\n  /** Readiness endpoint. It returns 503 until startup completes and while draining. */\n  readinessPath?: string;\n}\n\nexport interface ResolvedFarmServerHealthConfig {\n  enabled: boolean;\n  livenessPath: string;\n  readinessPath: string;\n}\n\nexport interface FarmServerConfig {\n  /** Maximum request body size for API routes, integrations, workflows, and uploads. */\n  bodySizeLimit?: number | string;\n  /** Trust proxy-provided client address and request authority headers. Enable only behind a trusted proxy. */\n  trustProxy?: boolean;\n  /** Maximum time for a Node client to send complete request headers. */\n  headersTimeout?: FarmServerDuration;\n  /** Maximum time for a Node client to send the complete request. */\n  requestTimeout?: FarmServerDuration;\n  /** How long an idle Node keep-alive connection remains open after a response. */\n  keepAliveTimeout?: FarmServerDuration;\n  /** Maximum time the Node adapter drains traffic before forcing shutdown. */\n  gracefulShutdownTimeout?: FarmServerDuration;\n  /** Production liveness and readiness endpoints. Set to false to disable them. */\n  health?: false | FarmServerHealthConfig;\n}\n\nexport interface ResolvedFarmServerConfig {\n  bodySizeLimit: number;\n  trustProxy: boolean;\n  headersTimeout: number;\n  requestTimeout: number;\n  keepAliveTimeout: number;\n  gracefulShutdownTimeout: number;\n  health: ResolvedFarmServerHealthConfig;\n}\n\nexport type FarmRequestBodyErrorCode = \"BODY_TOO_LARGE\" | \"INVALID_CONTENT_LENGTH\";\n\n/** Apply the weak entity-tag comparison required by If-None-Match. */\nexport function matchesFarmIfNoneMatch(\n  value: string | readonly string[] | null | undefined,\n  etag: string,\n): boolean {\n  const expected = parseEntityTag(trimOptionalWhitespace(etag));\n  if (!expected) return false;\n\n  const values = Array.isArray(value) ? value : [value];\n  const combined = values\n    .filter((header): header is string => typeof header === \"string\")\n    .join(\",\");\n  const fieldValue = trimOptionalWhitespace(combined);\n  if (!fieldValue) return false;\n  if (fieldValue === \"*\") return true;\n\n  let matched = false;\n  let hasEntityTag = false;\n  for (const candidate of splitEntityTags(fieldValue)) {\n    const token = trimOptionalWhitespace(candidate);\n    if (!token) continue;\n\n    const parsed = parseEntityTag(token);\n    if (!parsed) return false;\n    hasEntityTag = true;\n    if (parsed === expected) matched = true;\n  }\n\n  return hasEntityTag && matched;\n}\n\nfunction trimOptionalWhitespace(value: string): string {\n  return value.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n}\n\nfunction parseEntityTag(value: string): string | null {\n  const opaqueTag = value.startsWith(\"W/\") ? value.slice(2) : value;\n  if (opaqueTag.length < 2 || opaqueTag[0] !== '\"' || opaqueTag.at(-1) !== '\"') return null;\n\n  for (let index = 1; index < opaqueTag.length - 1; index++) {\n    const code = opaqueTag.charCodeAt(index);\n    if (code === 0x21 || (code >= 0x23 && code <= 0x7e) || code >= 0x80) continue;\n    return null;\n  }\n\n  return opaqueTag;\n}\n\nfunction splitEntityTags(value: string): string[] {\n  const tags: string[] = [];\n  let start = 0;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index++) {\n    const character = value[index];\n    if (character === '\"') {\n      quoted = !quoted;\n    } else if (character === \",\" && !quoted) {\n      tags.push(value.slice(start, index));\n      start = index + 1;\n    }\n  }\n\n  tags.push(value.slice(start));\n  return tags;\n}\n\nexport class FarmRequestBodyError extends Error {\n  readonly code: FarmRequestBodyErrorCode;\n  readonly status: number;\n\n  constructor(code: FarmRequestBodyErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"FarmRequestBodyError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\nexport function resolveFarmServerConfig(\n  config: FarmServerConfig | ResolvedFarmServerConfig | undefined,\n): ResolvedFarmServerConfig {\n  const headersTimeout = parseFarmServerDuration(\n    config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,\n    \"server.headersTimeout\",\n  );\n  const requestTimeout = parseFarmServerDuration(\n    config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,\n    \"server.requestTimeout\",\n  );\n  if (headersTimeout > requestTimeout) {\n    throw new TypeError(\"server.headersTimeout must not exceed server.requestTimeout\");\n  }\n\n  return Object.freeze({\n    bodySizeLimit: parseBodySizeLimit(\n      config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n      \"server.bodySizeLimit\",\n    ),\n    trustProxy: config?.trustProxy === true,\n    headersTimeout,\n    requestTimeout,\n    keepAliveTimeout: parseFarmServerDuration(\n      config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,\n      \"server.keepAliveTimeout\",\n    ),\n    gracefulShutdownTimeout: parseFarmServerDuration(\n      config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,\n      \"server.gracefulShutdownTimeout\",\n    ),\n    health: resolveFarmServerHealthConfig(config?.health),\n  });\n}\n\nexport function parseFarmServerDuration(\n  value: FarmServerDuration,\n  optionName = \"duration\",\n): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    if (value > MAX_FARM_SERVER_TIMEOUT) {\n      throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be milliseconds or a duration such as \"30s\" or \"2m\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2];\n  const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n  const milliseconds = Math.floor(amount * multiplier);\n  if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n  if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {\n    throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n  }\n  return milliseconds;\n}\n\nfunction resolveFarmServerHealthConfig(\n  config: false | FarmServerHealthConfig | ResolvedFarmServerHealthConfig | undefined,\n): ResolvedFarmServerHealthConfig {\n  if (config === false || (config && \"enabled\" in config && config.enabled === false)) {\n    return Object.freeze({\n      enabled: false,\n      livenessPath: \"/_farm/health/live\",\n      readinessPath: \"/_farm/health/ready\",\n    });\n  }\n\n  const livenessPath = normalizeHealthPath(\n    config?.livenessPath ?? \"/_farm/health/live\",\n    \"server.health.livenessPath\",\n  );\n  const readinessPath = normalizeHealthPath(\n    config?.readinessPath ?? \"/_farm/health/ready\",\n    \"server.health.readinessPath\",\n  );\n  if (livenessPath === readinessPath) {\n    throw new TypeError(\"server.health livenessPath and readinessPath must be different\");\n  }\n\n  return Object.freeze({ enabled: true, livenessPath, readinessPath });\n}\n\nfunction normalizeHealthPath(value: string, optionName: string): string {\n  const path = value.trim();\n  if (!path.startsWith(\"/\") || path.includes(\"?\") || path.includes(\"#\") || path.includes(\"*\")) {\n    throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);\n  }\n  const normalized = path.length > 1 ? path.replace(/\\/+$/, \"\") || \"/\" : path;\n  assertBrowserStableRoutePath(normalized);\n  return normalized;\n}\n\nexport function parseBodySizeLimit(value: number | string, optionName = \"bodySizeLimit\"): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)?$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be bytes or a size string such as \"500kb\" or \"10mb\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2] ?? \"b\";\n  const multiplier: Record<string, number> = {\n    b: 1,\n    kb: 1_000,\n    mb: 1_000_000,\n    gb: 1_000_000_000,\n    kib: 1_024,\n    mib: 1_048_576,\n    gib: 1_073_741_824,\n  };\n  const bytes = Math.floor(amount * multiplier[unit]);\n\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n\n  return bytes;\n}\n\nexport async function bufferFarmRequestBody(request: Request, limit: number): Promise<Request> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || request.body === null) {\n    return request;\n  }\n\n  const bytes = await readFarmRequestBody(request, limit);\n  const body = new Uint8Array(bytes.byteLength);\n  body.set(bytes);\n  return new Request(request, {\n    // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.\n    body: body.buffer,\n  });\n}\n\nexport async function readFarmRequestBody(request: Request, limit: number): Promise<Uint8Array> {\n  try {\n    validateContentLength(request.headers.get(\"content-length\"), limit);\n  } catch (error) {\n    // A cloned Request is a tee branch: its cancellation may wait for the\n    // untouched branch. Rejection must not wait for producer-owned cleanup.\n    void request.body?.cancel(error).catch(() => {});\n    throw error;\n  }\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      // Cancellation resolves a pending read as EOF, not necessarily an error.\n      throwIfAborted(request.signal);\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nexport async function readNodeRequestBody(\n  request: {\n    headers: Record<string, string | string[] | undefined>;\n    on(event: \"data\", listener: (chunk: unknown) => void): unknown;\n    on(event: \"end\", listener: () => void): unknown;\n    on(event: \"error\", listener: (error: Error) => void): unknown;\n    removeListener?(event: string, listener: (...args: any[]) => void): unknown;\n    resume?(): unknown;\n  },\n  limit: number,\n): Promise<Buffer> {\n  const rawContentLength = request.headers[\"content-length\"];\n  const contentLength = Array.isArray(rawContentLength) ? rawContentLength[0] : rawContentLength;\n  try {\n    validateContentLength(contentLength, limit);\n  } catch (error) {\n    request.resume?.();\n    throw error;\n  }\n\n  return await new Promise<Buffer>((resolve, reject) => {\n    const chunks: Buffer[] = [];\n    let total = 0;\n    let settled = false;\n\n    const cleanup = () => {\n      request.removeListener?.(\"data\", onData);\n      request.removeListener?.(\"end\", onEnd);\n      request.removeListener?.(\"error\", onError);\n    };\n    const rejectOnce = (error: Error) => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      request.resume?.();\n      reject(error);\n    };\n    const onData = (chunk: unknown) => {\n      const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as any);\n      total += bytes.byteLength;\n      if (total > limit) {\n        rejectOnce(new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\"));\n        return;\n      }\n      chunks.push(bytes);\n    };\n    const onEnd = () => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      resolve(Buffer.concat(chunks, total));\n    };\n    const onError = (error: Error) => rejectOnce(error);\n\n    request.on(\"data\", onData);\n    request.on(\"end\", onEnd);\n    request.on(\"error\", onError);\n  });\n}\n\nexport function createFarmRequestBodyErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof FarmRequestBodyError)) return null;\n\n  return new Response(error.status === 413 ? \"Payload Too Large\" : \"Bad Request\", {\n    status: error.status,\n    headers: {\n      \"cache-control\": \"no-store\",\n      \"content-type\": \"text/plain; charset=utf-8\",\n      \"x-content-type-options\": \"nosniff\",\n    },\n  });\n}\n\nfunction validateContentLength(value: string | null | undefined, limit: number): void {\n  const contentLength = value?.trim();\n  if (!contentLength) return;\n  if (!/^\\d+$/.test(contentLength)) {\n    throw new FarmRequestBodyError(\"INVALID_CONTENT_LENGTH\", 400, \"Invalid content-length header\");\n  }\n  if (Number(contentLength) > limit) {\n    throw new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","import type {\n  AnyFieldBuilder,\n  AnyModelDefinition,\n  FieldBuilder,\n  JsonValue,\n  ModelDefinition,\n  OrmClient,\n  SchemaDefinition,\n  SchemaModels,\n} from \"@farming-labs/orm\";\nimport type {\n  FarmIntegrationSchema,\n  FarmIntegrationSchemaField,\n  FarmIntegrationSchemaModel,\n} from \"./integrations\";\nimport { resolveStorageRuntimeClient } from \"./storage\";\nimport type { FarmStorageUserConfig } from \"./storage/types\";\nimport type { FarmConfig } from \"./types\";\n\ntype RuntimeClientFactory<TClient> = () => TClient | Promise<TClient>;\n\nexport type FarmIntegrationOrmSchema = SchemaDefinition<Record<string, AnyModelDefinition>>;\n\nexport type FarmIntegrationOrmClient<TSchema extends FarmIntegrationOrmSchema> = OrmClient<TSchema>;\n\ntype FarmIntegrationOrmFieldKind<TField extends FarmIntegrationSchemaField> = TField[\"type\"] extends\n  | \"id\"\n  | \"uuid\"\n  ? \"id\"\n  : TField[\"type\"] extends \"text\"\n    ? \"string\"\n    : TField[\"type\"] extends \"number\"\n      ? \"decimal\"\n      : Extract<TField[\"type\"], \"string\" | \"boolean\" | \"integer\" | \"datetime\" | \"json\" | \"enum\">;\n\ntype FarmIntegrationOrmFieldNullable<TField extends FarmIntegrationSchemaField> = TField extends {\n  nullable: true;\n}\n  ? true\n  : TField extends { required: false }\n    ? true\n    : false;\n\ntype FarmIntegrationOrmEnumValue<TField extends FarmIntegrationSchemaField> = TField extends {\n  values: readonly (infer TValue extends string)[];\n}\n  ? TValue\n  : string;\n\ntype FarmIntegrationOrmFieldValue<TField extends FarmIntegrationSchemaField> =\n  TField[\"type\"] extends \"id\" | \"uuid\" | \"string\" | \"text\"\n    ? string\n    : TField[\"type\"] extends \"boolean\"\n      ? boolean\n      : TField[\"type\"] extends \"integer\"\n        ? number\n        : TField[\"type\"] extends \"number\"\n          ? string\n          : TField[\"type\"] extends \"datetime\"\n            ? Date\n            : TField[\"type\"] extends \"json\"\n              ? JsonValue\n              : TField[\"type\"] extends \"enum\"\n                ? FarmIntegrationOrmEnumValue<TField>\n                : never;\n\nexport type InferFarmIntegrationOrmField<TField extends FarmIntegrationSchemaField> = FieldBuilder<\n  FarmIntegrationOrmFieldKind<TField>,\n  FarmIntegrationOrmFieldNullable<TField>,\n  FarmIntegrationOrmFieldValue<TField>\n>;\n\nexport type InferFarmIntegrationOrmFields<TModel extends FarmIntegrationSchemaModel> = {\n  [TFieldKey in keyof TModel[\"fields\"] & string]: InferFarmIntegrationOrmField<\n    Extract<TModel[\"fields\"][TFieldKey], FarmIntegrationSchemaField>\n  >;\n};\n\nexport type InferFarmIntegrationOrmSchema<TSchema extends FarmIntegrationSchema> =\n  SchemaDefinition<{\n    [TModelKey in keyof TSchema[\"models\"] & string]: ModelDefinition<\n      InferFarmIntegrationOrmFields<\n        Extract<TSchema[\"models\"][TModelKey], FarmIntegrationSchemaModel>\n      >,\n      {}\n    >;\n  }>;\n\nexport type InferFarmIntegrationOrmClient<TSchema extends FarmIntegrationSchema | undefined> =\n  TSchema extends FarmIntegrationSchema ? OrmClient<InferFarmIntegrationOrmSchema<TSchema>> : never;\n\nexport interface CreateIntegrationOrmOptions<\n  TClient = unknown,\n  TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n> {\n  schema: TSchema;\n  config?: Pick<FarmConfig, \"storage\">;\n  storage?: FarmStorageUserConfig;\n  client?: TClient | RuntimeClientFactory<TClient>;\n}\n\nexport async function createIntegrationOrm<\n  TClient = unknown,\n  TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n>(\n  options: CreateIntegrationOrmOptions<TClient, TSchema>,\n): Promise<InferFarmIntegrationOrmClient<TSchema>> {\n  const [schema, client] = await Promise.all([\n    farmIntegrationSchemaToOrmSchema(options.schema),\n    resolveIntegrationOrmRuntimeClient(options),\n  ]);\n\n  if (!client) {\n    throw new Error(\n      \"Schema-backed integration storage requires a runtime client at farm.config storage.client.\",\n    );\n  }\n\n  const { createOrmFromRuntime } = await import(\"@farming-labs/orm-runtime\");\n  return createOrmFromRuntime({\n    schema,\n    client,\n  }) as Promise<InferFarmIntegrationOrmClient<TSchema>>;\n}\n\nexport async function resolveIntegrationOrmRuntimeClient<TClient = unknown>(\n  options: Omit<CreateIntegrationOrmOptions<TClient>, \"schema\">,\n): Promise<TClient | unknown | undefined> {\n  if (options.client !== undefined) {\n    return typeof options.client === \"function\"\n      ? await (options.client as RuntimeClientFactory<TClient>)()\n      : options.client;\n  }\n\n  return resolveStorageRuntimeClient(options.storage ?? options.config?.storage);\n}\n\nexport async function farmIntegrationSchemaToOrmSchema(\n  schema: FarmIntegrationSchema,\n): Promise<FarmIntegrationOrmSchema> {\n  const orm = await import(\"@farming-labs/orm\");\n  const models: Record<string, AnyModelDefinition> = {};\n\n  for (const [modelKey, modelSchema] of Object.entries(schema.models)) {\n    models[modelKey] = orm.model({\n      table: modelSchema.name ?? modelKey,\n      fields: createOrmModelFields(orm, modelSchema),\n      constraints: createOrmModelConstraints(modelSchema),\n      description: modelSchema.description,\n    }) as AnyModelDefinition;\n  }\n\n  return orm.defineSchema(models) as FarmIntegrationOrmSchema;\n}\n\nfunction createOrmModelFields(\n  orm: typeof import(\"@farming-labs/orm\"),\n  modelSchema: FarmIntegrationSchemaModel,\n): Record<string, AnyFieldBuilder> {\n  return Object.fromEntries(\n    Object.entries(modelSchema.fields).map(([fieldKey, fieldSchema]) => [\n      fieldKey,\n      createOrmField(orm, fieldKey, fieldSchema),\n    ]),\n  );\n}\n\nfunction createOrmField(\n  orm: typeof import(\"@farming-labs/orm\"),\n  fieldKey: string,\n  field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n  let builder = createOrmFieldBuilder(orm, fieldKey, field) as AnyFieldBuilder;\n\n  if (field.unique) {\n    builder = builder.unique();\n  }\n\n  if (field.nullable || field.required === false) {\n    builder = builder.nullable();\n  }\n\n  if (field.default !== undefined) {\n    builder =\n      field.type === \"datetime\" && field.default === \"now\"\n        ? builder.defaultNow()\n        : builder.default(field.default as never);\n  }\n\n  if (field.reference) {\n    builder = builder.references(`${field.reference.model}.${field.reference.field}`);\n  }\n\n  if (field.name && field.name !== fieldKey) {\n    builder = builder.map(field.name);\n  }\n\n  if (field.description) {\n    builder = builder.describe(field.description);\n  }\n\n  return builder;\n}\n\nfunction createOrmFieldBuilder(\n  orm: typeof import(\"@farming-labs/orm\"),\n  fieldKey: string,\n  field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n  switch (field.type) {\n    case \"id\":\n    case \"uuid\":\n      return orm.id();\n    case \"string\":\n    case \"text\":\n      return orm.string();\n    case \"boolean\":\n      return orm.boolean();\n    case \"integer\":\n      return orm.integer();\n    case \"number\":\n      return orm.decimal();\n    case \"datetime\":\n      return orm.datetime();\n    case \"json\":\n      return orm.json();\n    case \"enum\": {\n      if (!field.values?.length) {\n        throw new Error(`Integration schema enum field \"${fieldKey}\" must define values.`);\n      }\n\n      return orm.enumeration(field.values as readonly [string, ...string[]]);\n    }\n    default:\n      throw new Error(\n        `Unsupported integration schema field type \"${field.type}\" for \"${fieldKey}\".`,\n      );\n  }\n}\n\nfunction createOrmModelConstraints(modelSchema: FarmIntegrationSchemaModel) {\n  const unique: Array<readonly [string, ...string[]]> = [];\n  const indexes: Array<readonly [string, ...string[]]> = [];\n\n  for (const constraint of modelSchema.constraints ?? []) {\n    if (!constraint.fields.length) {\n      continue;\n    }\n\n    const fields = constraint.fields as readonly [string, ...string[]];\n    if (constraint.type === \"unique\") {\n      unique.push(fields);\n    } else {\n      indexes.push(fields);\n    }\n  }\n\n  return {\n    unique,\n    indexes,\n  };\n}\n\nexport type IntegrationOrmModelNames<TSchema extends FarmIntegrationOrmSchema> =\n  keyof SchemaModels<TSchema> & string;\n","import { validateConfigRouteSource } from \"./plugins/route-pattern\";\n\n// Origin validation for integration auth routes is part of the integration\n// contract, so it is re-exported here alongside defineIntegration rather than\n// only from the package root.\nexport {\n  describeIntegrationOriginRejection,\n  resolveIntegrationAllowedOrigins,\n  validateIntegrationRequestOrigin,\n  type IntegrationOriginPolicy,\n  type IntegrationOriginRejection,\n  type IntegrationOriginResult,\n} from \"./integration-request-security\";\n\nimport type { ComponentType, ReactNode } from \"react\";\nimport { api as integrationApi, defineIntegrationAPIOperation } from \"./integration-api\";\nimport type {\n  FarmIntegrationAPI,\n  FarmIntegrationAPIBodyFormat,\n  FarmIntegrationAPIMethod,\n  FarmIntegrationAPIOperation,\n  FarmIntegrationAPIResponseFormat,\n  FarmIntegrationRouteOperationCarrier,\n  InferIntegrationAPIFromRoutes,\n} from \"./integration-api\";\nimport type { InferFarmIntegrationOrmClient } from \"./integration-orm\";\nimport { setFarmPluginIntegrationContext } from \"./plugin-integration-context\";\nimport { decodeRouteSegment } from \"./utils/decode\";\nimport {\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n  compareRouteSpecificity,\n  getRoutePatternSpecificity,\n} from \"./routing/specificity\";\nimport type {\n  FarmPlugin,\n  FarmPluginContext,\n  FarmPluginIntegrationContext,\n  FarmRequestStore,\n} from \"./plugin\";\nimport {\n  clearRequestContext,\n  deleteRequestContext,\n  getRequestContext,\n  getRequestContextSnapshot,\n  hasRequestContext,\n  setRequestContext,\n} from \"./request-context\";\nimport { sendWebResponse } from \"./server/response\";\nimport type { FarmRequest } from \"./types\";\nimport {\n  bufferFarmRequestBody,\n  createFarmRequestBodyErrorResponse,\n  readNodeRequestBody,\n  resolveFarmServerConfig,\n} from \"./server-http\";\n\nexport { api, defineIntegrationAPI, defineIntegrationAPIOperation } from \"./integration-api\";\nexport type {\n  FarmIntegrationAPI,\n  FarmIntegrationAPIBodyFormat,\n  FarmIntegrationAPIMethod,\n  FarmIntegrationAPIOperation,\n  FarmIntegrationAPIResponseFormat,\n} from \"./integration-api\";\n\nexport type FarmIntegrationCategory = \"auth\" | \"payment\" | \"monitoring\" | \"logging\" | (string & {});\n\n/** @deprecated Use FarmIntegrationCategory instead. */\nexport type FarmIntegrationSlot = FarmIntegrationCategory;\n\nexport type FarmIntegrationRouteParamValue = string | string[];\nexport type FarmIntegrationRouteParams = Record<string, FarmIntegrationRouteParamValue>;\nexport type FarmIntegrationRouteMethod =\n  | FarmIntegrationAPIMethod\n  | Lowercase<FarmIntegrationAPIMethod>\n  | \"ALL\"\n  | \"all\";\nexport type FarmIntegrationRouteInputSource = \"body\" | \"query\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type FarmIntegrationValidationPathSegment =\n  | PropertyKey\n  | {\n      readonly key: PropertyKey;\n    };\n\nexport interface FarmIntegrationRouteInput<TBody = unknown, TQuery = unknown> {\n  body?: TBody;\n  query?: TQuery;\n}\n\nexport interface FarmIntegrationValidationIssue {\n  source: FarmIntegrationRouteInputSource;\n  path?: readonly (string | number)[];\n  code?: string;\n  message: string;\n}\n\nexport interface FarmIntegrationValidationErrorLike {\n  issues?: readonly {\n    path?: readonly FarmIntegrationValidationPathSegment[];\n    code?: string;\n    message?: string;\n  }[];\n  message?: string;\n}\n\nexport type FarmIntegrationValidationResult<TValue> =\n  | {\n      success: true;\n      data: TValue;\n    }\n  | {\n      success: false;\n      error: FarmIntegrationValidationErrorLike;\n    };\n\nexport type FarmIntegrationStandardValidationResult<TValue> =\n  | {\n      value: TValue;\n    }\n  | {\n      issues: readonly {\n        path?: readonly FarmIntegrationValidationPathSegment[];\n        code?: string;\n        message: string;\n      }[];\n    };\n\nexport interface FarmIntegrationInputSchema<TValue = unknown> {\n  _output?: TValue;\n  parse?(value: unknown): MaybePromise<TValue>;\n  safeParse?(value: unknown): MaybePromise<FarmIntegrationValidationResult<TValue>>;\n  safeParseAsync?(value: unknown): Promise<FarmIntegrationValidationResult<TValue>>;\n  \"~standard\"?: {\n    validate(value: unknown): MaybePromise<FarmIntegrationStandardValidationResult<TValue>>;\n    types?: {\n      output: TValue;\n    };\n  };\n}\n\nexport interface FarmIntegrationRouteInputSchemas<TBody = unknown, TQuery = unknown> {\n  body?: FarmIntegrationInputSchema<TBody>;\n  query?: FarmIntegrationInputSchema<TQuery>;\n}\n\n/** @deprecated Use `FarmRequestStore` and access it through `ctx.req`. */\nexport type FarmIntegrationRequestContextStore = FarmRequestStore;\n\nexport const FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY = \"farm.integration.internalDispatch\";\n\nexport type FarmIntegrationRouteDb<TSchema extends FarmIntegrationSchema | undefined> =\n  InferFarmIntegrationOrmClient<TSchema>;\n\nexport interface FarmIntegrationRouteStorageArgs<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  getClient(): Promise<unknown | undefined>;\n  getOrm(): Promise<FarmIntegrationRouteDb<TSchema>>;\n}\n\nexport interface FarmIntegrationRouteArgs<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  db: FarmIntegrationRouteDb<TSchema>;\n  getDb(): Promise<FarmIntegrationRouteDb<TSchema>>;\n  storage: FarmIntegrationRouteStorageArgs<TSchema>;\n}\n\nexport interface FarmIntegrationConfigContext<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  key: string;\n  integration: FarmIntegration<TSchema, any>;\n  appConfig: FarmPluginContext[\"config\"];\n  /** Alias for appConfig. */\n  config: FarmPluginContext[\"config\"];\n  args: FarmIntegrationRouteArgs<TSchema>;\n  env: Record<string, string | undefined>;\n  isDev: boolean;\n  isProd: boolean;\n}\n\nexport interface FarmIntegrationConfigDefinition<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  schema?: FarmIntegrationInputSchema<TConfig>;\n  env?: Record<string, string | readonly string[]>;\n  defaults?:\n    | Partial<TConfig>\n    | ((context: FarmIntegrationConfigContext<TSchema>) => MaybePromise<Partial<TConfig>>);\n  input?:\n    | Partial<TConfig>\n    | ((context: FarmIntegrationConfigContext<TSchema>) => MaybePromise<Partial<TConfig>>);\n  resolve?(\n    context: FarmIntegrationConfigContext<TSchema>,\n  ): MaybePromise<TConfig | Partial<TConfig> | undefined>;\n}\n\nexport type FarmIntegrationConfigInput<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = FarmIntegrationInputSchema<TConfig> | FarmIntegrationConfigDefinition<TConfig, TSchema>;\n\nexport type FarmIntegrationLifecycleLogLevel = \"info\" | \"warn\" | \"error\";\n\nexport interface FarmIntegrationLifecycleLogger {\n  info(message: string, meta?: Record<string, unknown>): void;\n  warn(message: string, meta?: Record<string, unknown>): void;\n  error(message: string, meta?: Record<string, unknown>): void;\n}\n\nexport interface FarmIntegrationLifecycleContext<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationConfigContext<TSchema> {\n  integration: FarmIntegration<TSchema, TConfig>;\n  integrationConfig: TConfig;\n  log: FarmIntegrationLifecycleLogger;\n  reason?: string;\n  cleanup(callback?: () => MaybePromise<void>): Promise<void>;\n}\n\nexport type FarmIntegrationLifecycleHook<\n  TConfig = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (context: FarmIntegrationLifecycleContext<TConfig, TSchema>) => MaybePromise<void>;\n\n/**\n * Small per-call integration metadata. Values received over HTTP are\n * client-controlled and should be validated before authorization decisions.\n */\nexport type FarmIntegrationData = Record<string, unknown>;\n\nexport interface FarmIntegrationHandlerContext<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  request: Request;\n  requestId: string;\n  url: URL;\n  pathname: string;\n  method: string;\n  params: FarmIntegrationRouteParams;\n  input: FarmIntegrationRouteInput<TBody, TQuery>;\n  args: FarmIntegrationRouteArgs<TSchema>;\n  data: FarmIntegrationData;\n  integration: {\n    category: FarmIntegrationCategory;\n    /** @deprecated Use category instead. */\n    slot: FarmIntegrationCategory;\n    type: string;\n    instance: unknown;\n  };\n  route: {\n    kind: \"route\" | \"middleware\";\n    path: string;\n    methods: readonly string[];\n  };\n  req: FarmRequestStore;\n  /** @deprecated Use `req` instead. */\n  requestContext: FarmRequestStore;\n  config: FarmPluginContext[\"config\"];\n  isDev: boolean;\n  isProd: boolean;\n}\n\nexport interface FarmIntegrationRouteHookContext<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationHandlerContext<TBody, TQuery, TSchema> {\n  response?: Response;\n}\n\nexport type FarmIntegrationRouteHook<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = {\n  bivarianceHack(\n    request: Request,\n    context: FarmIntegrationRouteHookContext<TBody, TQuery, TSchema>,\n  ): Promise<Response | void> | Response | void;\n}[\"bivarianceHack\"];\n\nexport interface FarmIntegrationRoute<\n  TBody = unknown,\n  TQuery = unknown,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  path: string;\n  method?: FarmIntegrationRouteMethod;\n  methods?: readonly FarmIntegrationRouteMethod[];\n  middleware?: readonly FarmIntegrationRouteMiddleware<TSchema>[];\n  before?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  after?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  rawBody?: boolean;\n  bodyFormat?: FarmIntegrationAPIBodyFormat;\n  body?: FarmIntegrationInputSchema<TBody>;\n  query?: FarmIntegrationInputSchema<TQuery>;\n  input?: FarmIntegrationRouteInputSchemas<TBody, TQuery>;\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<TBody, TQuery, TSchema>,\n  ): Promise<Response> | Response;\n}\n\nexport interface FarmTypedIntegrationRoute<\n  TPath extends string = string,\n  TBody = never,\n  TQuery = never,\n  TResponse = unknown,\n  TServer extends boolean = false,\n  TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationRoute<TBody, TQuery, TSchema> {\n  path: TPath;\n  method: TMethod;\n  __operation: FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>;\n}\n\nexport interface FarmIntegrationRouteMiddleware<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<unknown, unknown, TSchema>,\n  ): Promise<Response | void> | Response | void;\n}\n\nexport interface FarmIntegrationMiddleware<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  matcher?: string | string[];\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<unknown, unknown, TSchema>,\n  ): Promise<Response | void> | Response | void;\n}\n\nexport interface FarmIntegrationProviderProps {\n  children: ReactNode;\n}\n\nexport interface FarmIntegrationProviderComponentReference {\n  /** Client-safe module specifier using `@/`, a path relative to the app root, or a package. */\n  module: string;\n  /** Named export to use. Defaults to the module's default export. */\n  export?: string;\n}\n\nexport interface FarmIntegrationProvider {\n  name: string;\n  type: string;\n  props?: Record<string, unknown>;\n  /**\n   * The provider can be instantiated independently around each isolated\n   * client root without relying on context or state owned by the route root.\n   * Providers are treated as route-wide unless they explicitly opt in.\n   */\n  supportsIsolatedHydration?: boolean;\n  component?:\n    | ComponentType<FarmIntegrationProviderProps>\n    | FarmIntegrationProviderComponentReference;\n}\n\nexport interface FarmIntegrationDocumentNavigation {\n  matcher: string | readonly string[];\n}\n\nexport type FarmIntegrationSchemaFieldType =\n  | \"id\"\n  | \"uuid\"\n  | \"string\"\n  | \"text\"\n  | \"boolean\"\n  | \"integer\"\n  | \"number\"\n  | \"datetime\"\n  | \"json\"\n  | \"enum\";\n\nexport interface FarmIntegrationSchemaReference {\n  model: string;\n  field: string;\n  relation?: \"belongsTo\" | \"hasOne\" | \"hasMany\";\n  onDelete?: \"cascade\" | \"restrict\" | \"setNull\" | \"noAction\";\n  enforced?: \"db\" | \"app\" | \"none\";\n}\n\nexport interface FarmIntegrationSchemaField {\n  type: FarmIntegrationSchemaFieldType;\n  name?: string;\n  description?: string;\n  required?: boolean;\n  nullable?: boolean;\n  primaryKey?: boolean;\n  unique?: boolean;\n  index?: boolean;\n  list?: boolean;\n  default?: unknown;\n  values?: readonly string[];\n  reference?: FarmIntegrationSchemaReference;\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaConstraint {\n  type: \"unique\" | \"index\";\n  fields: readonly string[];\n  name?: string;\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaModel {\n  name?: string;\n  description?: string;\n  fields: Record<string, FarmIntegrationSchemaField>;\n  constraints?: readonly FarmIntegrationSchemaConstraint[];\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaModelExtension {\n  name?: string;\n  description?: string;\n  fields?: Record<string, FarmIntegrationSchemaField>;\n  constraints?: readonly FarmIntegrationSchemaConstraint[];\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaModelOverride {\n  name?: string;\n  description?: string;\n  fields?: Record<string, Partial<FarmIntegrationSchemaField>>;\n  constraints?: readonly FarmIntegrationSchemaConstraint[];\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchema {\n  models: Record<string, FarmIntegrationSchemaModel>;\n  meta?: Record<string, unknown>;\n  extend?: Record<string, FarmIntegrationSchemaModelExtension>;\n  override?: Record<string, FarmIntegrationSchemaModelOverride>;\n}\n\nexport function defineIntegrationSchema<TSchema extends FarmIntegrationSchema>(\n  schema: TSchema,\n): TSchema {\n  return schema;\n}\n\nexport type FarmIntegrationLogPhase =\n  | \"registered\"\n  | \"validate\"\n  | \"setup\"\n  | \"ready\"\n  | \"dispose\"\n  | \"request:start\"\n  | \"request:end\"\n  | \"request:error\";\n\nexport interface FarmIntegrationLogEvent {\n  category: FarmIntegrationCategory;\n  /** @deprecated Use category instead. */\n  slot: FarmIntegrationCategory;\n  type: string;\n  phase: FarmIntegrationLogPhase;\n  route?: {\n    kind: \"route\" | \"middleware\";\n    path: string;\n    methods: readonly string[];\n  };\n  requestId?: string;\n  request?: Request;\n  response?: Response;\n  error?: unknown;\n  durationMs?: number;\n  level?: FarmIntegrationLifecycleLogLevel;\n  message?: string;\n  meta?: Record<string, unknown>;\n  context: Map<string, unknown>;\n}\n\nexport type FarmIntegrationLogger = (event: FarmIntegrationLogEvent) => void | Promise<void>;\n\nexport interface FarmIntegrationPluginOwner {\n  key: string;\n  category: FarmIntegrationCategory;\n  type: string;\n  source: \"lifecycle\" | \"contribution\";\n  serverRuntime: boolean;\n}\n\n/** A normal plugin or an integration-bound plugin compatible with the shared instance. */\nexport type FarmIntegrationContributedPlugin<TInstance = unknown> =\n  | FarmPlugin<any, any, any, any, unknown, false>\n  | FarmPlugin<any, any, any, any, TInstance, true>;\n\nexport interface FarmIntegration<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n  TConfig = unknown,\n  TInstance = unknown,\n> {\n  readonly kind: \"farm-integration\";\n  category: FarmIntegrationCategory;\n  /** @deprecated Use category instead. */\n  slot?: FarmIntegrationCategory;\n  type: string;\n  instance: TInstance;\n  /** Set to false when a platform adapter owns this integration's production routes. */\n  serverRuntime?: boolean;\n  api?: FarmIntegrationAPI;\n  schema?: TSchema;\n  config?: FarmIntegrationConfigInput<TConfig, TSchema>;\n  validate?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  setup?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  ready?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  dispose?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n  log?: FarmIntegrationLogger;\n  routes?: readonly FarmIntegrationRoute<any, any, TSchema>[];\n  endpoints?: FarmIntegrationEndpoints<TSchema>;\n  middleware?: readonly FarmIntegrationMiddleware<TSchema>[];\n  providers?: readonly FarmIntegrationProvider[];\n  documentNavigations?: readonly FarmIntegrationDocumentNavigation[];\n  /** Additional Farm plugins owned and configured by this integration. */\n  plugins?: readonly FarmIntegrationContributedPlugin<NoInfer<TInstance>>[];\n}\n\nexport type FarmIntegrationsUserConfig = Record<string, FarmIntegration<any, any, any> | undefined>;\n\nconst FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME = Symbol.for(\n  \"@farm.js/core/integration-plugin-server-runtime\",\n);\nconst FARM_INTEGRATION_PLUGIN_OWNER = Symbol.for(\"@farm.js/core/integration-plugin-owner\");\n\n/** @internal Identifies plugins owned by platform-managed integrations. */\nexport function getFarmIntegrationPluginServerRuntime(plugin: FarmPlugin): boolean | undefined {\n  const value = (plugin as FarmPlugin & Record<symbol, unknown>)[\n    FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME\n  ];\n  return typeof value === \"boolean\" ? value : undefined;\n}\n\n/** Returns the integration that contributed a normalized plugin, when applicable. */\nexport function getFarmIntegrationPluginOwner(\n  plugin: FarmPlugin,\n): Readonly<FarmIntegrationPluginOwner> | undefined {\n  const value = (plugin as FarmPlugin & Record<symbol, unknown>)[FARM_INTEGRATION_PLUGIN_OWNER];\n  return value && typeof value === \"object\"\n    ? (value as Readonly<FarmIntegrationPluginOwner>)\n    : undefined;\n}\n\ntype IntegrationRouteBuilderOptions<\n  TBody,\n  TQuery,\n  TServer extends boolean,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = {\n  middleware?: readonly FarmIntegrationRouteMiddleware<TSchema>[];\n  before?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  after?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n  rawBody?: boolean;\n  headers?: Record<string, string>;\n  credentials?: RequestCredentials;\n  bodyFormat?: FarmIntegrationAPIBodyFormat;\n  responseFormat?: FarmIntegrationAPIResponseFormat;\n  isServer?: TServer;\n  body?: FarmIntegrationInputSchema<TBody>;\n  query?: FarmIntegrationInputSchema<TQuery>;\n  input?: FarmIntegrationRouteInputSchemas<TBody, TQuery>;\n  handler(\n    request: Request,\n    context: FarmIntegrationHandlerContext<TBody, TQuery, TSchema>,\n  ): Promise<Response> | Response;\n};\n\nfunction defineTypedIntegrationRoute<\n  TPath extends string,\n  TBody,\n  TQuery,\n  TResponse,\n  TServer extends boolean,\n  TMethod extends FarmIntegrationAPIMethod,\n  TSchema extends FarmIntegrationSchema | undefined,\n>(\n  method: TMethod,\n  path: TPath,\n  input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, TMethod, TSchema> {\n  return {\n    path,\n    method,\n    middleware: input.middleware,\n    before: input.before,\n    after: input.after,\n    rawBody: input.rawBody,\n    bodyFormat: input.bodyFormat,\n    input: normalizeIntegrationRouteInputSchemas(input),\n    handler: input.handler,\n    __operation: defineIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>({\n      path,\n      method,\n      bodyFormat: input.bodyFormat,\n      responseFormat: input.responseFormat,\n      headers: input.headers,\n      credentials: input.credentials,\n      isServer: input.isServer,\n    }),\n  };\n}\n\nexport interface FarmIntegrationRouteFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  get<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    path: TPath,\n    input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n  ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"GET\", TSchema>;\n  post<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"POST\", TSchema>;\n  query<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"QUERY\", TSchema>;\n  put<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PUT\", TSchema>;\n  patch<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PATCH\", TSchema>;\n  delete<\n    TPath extends string,\n    TBody = never,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n  ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"DELETE\", TSchema>;\n  options<\n    TPath extends string,\n    TResponse = unknown,\n    TQuery = never,\n    TServer extends boolean = false,\n  >(\n    path: TPath,\n    input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n  ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"OPTIONS\", TSchema>;\n  head<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n    path: TPath,\n    input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n  ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"HEAD\", TSchema>;\n}\n\nexport interface FarmIntegrationRoutesFactoryContext<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n  route: FarmIntegrationRouteFactory<TSchema>;\n  integrationRoute: FarmIntegrationRouteFactory<TSchema>;\n}\n\nexport type FarmIntegrationRoutesFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (\n  context: FarmIntegrationRoutesFactoryContext<TSchema>,\n) => readonly FarmIntegrationRoute<any, any, TSchema>[];\n\nexport type FarmIntegrationEndpointValue<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> =\n  | FarmIntegrationRoute<any, any, TSchema>\n  | readonly FarmIntegrationEndpointValue<TSchema>[]\n  | {\n      readonly [key: string]: FarmIntegrationEndpointValue<TSchema> | undefined;\n    };\n\nexport type FarmIntegrationEndpoints<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = {\n  readonly [key: string]: FarmIntegrationEndpointValue<TSchema> | undefined;\n};\n\nexport interface FarmIntegrationEndpointsFactoryContext<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationRoutesFactoryContext<TSchema> {\n  endpoint: FarmIntegrationRouteFactory<TSchema>;\n}\n\nexport type FarmIntegrationEndpointsFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (context: FarmIntegrationEndpointsFactoryContext<TSchema>) => FarmIntegrationEndpoints<TSchema>;\n\nfunction createIntegrationRouteFactory<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n>(): FarmIntegrationRouteFactory<TSchema> {\n  return {\n    get<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n      path: TPath,\n      input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n    ) {\n      return defineTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"GET\", TSchema>(\n        \"GET\",\n        path,\n        input,\n      );\n    },\n    post<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"POST\", TSchema>(\n        \"POST\",\n        path,\n        {\n          bodyFormat: \"json\",\n          ...input,\n        },\n      );\n    },\n    query<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        TBody,\n        TQuery,\n        TResponse,\n        TServer,\n        \"QUERY\",\n        TSchema\n      >(\"QUERY\", path, {\n        bodyFormat: \"json\",\n        ...input,\n      });\n    },\n    put<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PUT\", TSchema>(\n        \"PUT\",\n        path,\n        {\n          bodyFormat: \"json\",\n          ...input,\n        },\n      );\n    },\n    patch<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        TBody,\n        TQuery,\n        TResponse,\n        TServer,\n        \"PATCH\",\n        TSchema\n      >(\"PATCH\", path, {\n        bodyFormat: \"json\",\n        ...input,\n      });\n    },\n    delete<\n      TPath extends string,\n      TBody = never,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        TBody,\n        TQuery,\n        TResponse,\n        TServer,\n        \"DELETE\",\n        TSchema\n      >(\"DELETE\", path, {\n        bodyFormat: \"json\",\n        ...input,\n      });\n    },\n    options<\n      TPath extends string,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(\n      path: TPath,\n      input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n    ) {\n      return defineTypedIntegrationRoute<\n        TPath,\n        never,\n        TQuery,\n        TResponse,\n        TServer,\n        \"OPTIONS\",\n        TSchema\n      >(\"OPTIONS\", path, input);\n    },\n    head<\n      TPath extends string,\n      TResponse = unknown,\n      TQuery = never,\n      TServer extends boolean = false,\n    >(\n      path: TPath,\n      input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n    ) {\n      return defineTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"HEAD\", TSchema>(\n        \"HEAD\",\n        path,\n        input,\n      );\n    },\n  };\n}\n\nexport function createIntegrationRoute<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n>(_schema?: TSchema): FarmIntegrationRouteFactory<TSchema> {\n  return createIntegrationRouteFactory<TSchema>();\n}\n\nexport const integrationRoute = createIntegrationRouteFactory<undefined>();\n\ntype RegisteredIntegrationRuntime = {\n  integration: FarmIntegration;\n  config: FarmPluginContext[\"config\"];\n  isDev: boolean;\n  isProd: boolean;\n};\n\nconst INTEGRATION_RUNTIME_REGISTRY_KEY = Symbol.for(\"farm.integrationRuntimeRegistry\");\nconst INTEGRATION_REQUEST_DISPATCHER_KEY = Symbol.for(\"farm.integrationRequestDispatcher\");\n\ntype IntegrationRequestDispatcher = (\n  runtime: RegisteredIntegrationRuntime,\n  request: Request,\n  options?: { currentRequest?: Request },\n) => Promise<Response | null>;\n\ntype GlobalWithIntegrationRuntimeRegistry = typeof globalThis & {\n  [INTEGRATION_RUNTIME_REGISTRY_KEY]?: Map<string, RegisteredIntegrationRuntime>;\n  [INTEGRATION_REQUEST_DISPATCHER_KEY]?: IntegrationRequestDispatcher;\n};\n\nfunction getIntegrationRuntimeRegistry() {\n  const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n  if (!globalState[INTEGRATION_RUNTIME_REGISTRY_KEY]) {\n    globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] = new Map<string, RegisteredIntegrationRuntime>();\n  }\n\n  return globalState[INTEGRATION_RUNTIME_REGISTRY_KEY]!;\n}\n\ntype FarmIntegrationRoutesInput<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = readonly FarmIntegrationRoute<any, any, TSchema>[] | FarmIntegrationRoutesFactory<TSchema>;\n\ntype FarmIntegrationEndpointsInput<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = FarmIntegrationEndpoints<TSchema> | FarmIntegrationEndpointsFactory<TSchema>;\n\ntype FarmIntegrationInput<\n  TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n  TConfig = unknown,\n  TInstance = unknown,\n> = Omit<\n  FarmIntegration<TSchema, TConfig, TInstance>,\n  \"kind\" | \"category\" | \"slot\" | \"instance\" | \"config\" | \"routes\" | \"endpoints\" | \"plugins\"\n> & {\n  instance: TInstance;\n  config?: FarmIntegrationConfigInput<TConfig, TSchema>;\n  routes?: FarmIntegrationRoutesInput<TSchema>;\n  endpoints?: FarmIntegrationEndpointsInput<TSchema>;\n  plugins?: readonly FarmIntegrationContributedPlugin<NoInfer<TInstance>>[];\n} & (\n    | {\n        category: FarmIntegrationCategory;\n        slot?: FarmIntegrationCategory;\n      }\n    | {\n        category?: FarmIntegrationCategory;\n        slot: FarmIntegrationCategory;\n      }\n  );\n\ntype FarmIntegrationCategoryInput =\n  | {\n      category: FarmIntegrationCategory;\n      slot?: FarmIntegrationCategory;\n    }\n  | {\n      category?: FarmIntegrationCategory;\n      slot: FarmIntegrationCategory;\n    };\n\ntype FarmIntegrationShapeForInference = FarmIntegrationCategoryInput & {\n  api?: FarmIntegrationAPI;\n  schema?: FarmIntegrationSchema;\n  config?: unknown;\n  routes?: unknown;\n  endpoints?: unknown;\n};\n\ntype ExtractIntegrationSchema<TIntegration> = TIntegration extends {\n  schema: infer TSchema extends FarmIntegrationSchema;\n}\n  ? TSchema\n  : undefined;\n\ntype ResolveIntegrationRoutesInput<TRoutes, TSchema extends FarmIntegrationSchema | undefined> =\n  TRoutes extends FarmIntegrationRoutesFactory<TSchema> ? ReturnType<TRoutes> : TRoutes;\n\ntype ResolveIntegrationEndpointsInput<\n  TEndpoints,\n  TSchema extends FarmIntegrationSchema | undefined,\n> =\n  TEndpoints extends FarmIntegrationEndpointsFactory<TSchema> ? ReturnType<TEndpoints> : TEndpoints;\n\ntype ExtractIntegrationRoutesFromRoutesInput<\n  TRoutes,\n  TSchema extends FarmIntegrationSchema | undefined,\n> =\n  ResolveIntegrationRoutesInput<TRoutes, TSchema> extends readonly (infer TRoute)[]\n    ? TRoute\n    : never;\n\ntype ExtractIntegrationRoutesFromEndpointValue<TValue> =\n  TValue extends FarmIntegrationRouteOperationCarrier<string, any>\n    ? TValue\n    : TValue extends readonly (infer TItem)[]\n      ? ExtractIntegrationRoutesFromEndpointValue<TItem>\n      : TValue extends object\n        ? ExtractIntegrationRoutesFromEndpointValue<TValue[keyof TValue]>\n        : never;\n\ntype ExtractIntegrationRoutesFromEndpointsInput<\n  TEndpoints,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = ExtractIntegrationRoutesFromEndpointValue<\n  ResolveIntegrationEndpointsInput<TEndpoints, TSchema>\n>;\n\ntype ExtractIntegrationRouteUnion<TIntegration, TSchema extends FarmIntegrationSchema | undefined> =\n  | (TIntegration extends { routes: infer TRoutes }\n      ? ExtractIntegrationRoutesFromRoutesInput<TRoutes, TSchema>\n      : never)\n  | (TIntegration extends { endpoints: infer TEndpoints }\n      ? ExtractIntegrationRoutesFromEndpointsInput<TEndpoints, TSchema>\n      : never);\n\ntype ExtractDefinedIntegrationRoutes<\n  TIntegration,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = [ExtractIntegrationRouteUnion<TIntegration, TSchema>] extends [never]\n  ? undefined\n  : readonly ExtractIntegrationRouteUnion<TIntegration, TSchema>[];\n\ntype ExtractDefinedIntegrationEndpoints<\n  TIntegration,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = TIntegration extends { endpoints: infer TEndpoints }\n  ? ResolveIntegrationEndpointsInput<TEndpoints, TSchema>\n  : undefined;\n\ntype ExtractIntegrationAPIRoutes<\n  TIntegration,\n  TSchema extends FarmIntegrationSchema | undefined,\n> = Extract<\n  ExtractIntegrationRouteUnion<TIntegration, TSchema>,\n  FarmIntegrationRouteOperationCarrier<string, any>\n>;\n\ntype ExtractIntegrationCategory<TIntegration extends FarmIntegrationCategoryInput> =\n  TIntegration extends {\n    category: infer TCategory extends FarmIntegrationCategory;\n  }\n    ? TCategory\n    : TIntegration extends { slot: infer TSlot extends FarmIntegrationCategory }\n      ? TSlot\n      : FarmIntegrationCategory;\n\ntype ExtractDerivedIntegrationAPI<\n  TIntegration extends FarmIntegrationShapeForInference,\n  TSchema extends FarmIntegrationSchema | undefined = ExtractIntegrationSchema<TIntegration>,\n> = TIntegration extends { api: infer TAPI extends FarmIntegrationAPI }\n  ? TAPI\n  : [ExtractIntegrationAPIRoutes<TIntegration, TSchema>] extends [never]\n    ? FarmIntegrationAPI | undefined\n    : InferIntegrationAPIFromRoutes<readonly ExtractIntegrationAPIRoutes<TIntegration, TSchema>[]>;\n\nexport type DefinedIntegration<\n  TIntegration extends FarmIntegrationShapeForInference,\n  TSchema extends FarmIntegrationSchema | undefined = ExtractIntegrationSchema<TIntegration>,\n> = Omit<TIntegration, \"kind\" | \"category\" | \"slot\" | \"api\" | \"routes\" | \"endpoints\"> & {\n  readonly kind: \"farm-integration\";\n  category: ExtractIntegrationCategory<TIntegration>;\n  slot: ExtractIntegrationCategory<TIntegration>;\n  routes: ExtractDefinedIntegrationRoutes<TIntegration, TSchema>;\n  endpoints: ExtractDefinedIntegrationEndpoints<TIntegration, TSchema>;\n  api: ExtractDerivedIntegrationAPI<TIntegration, TSchema>;\n};\n\nfunction isIntegrationEndpointRoute(value: unknown): value is FarmIntegrationRoute {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as { path?: unknown }).path === \"string\" &&\n    typeof (value as { handler?: unknown }).handler === \"function\"\n  );\n}\n\nfunction flattenIntegrationEndpoints(\n  endpoints: FarmIntegrationEndpointValue | FarmIntegrationEndpoints | undefined,\n): FarmIntegrationRoute[] {\n  if (!endpoints) {\n    return [];\n  }\n\n  if (Array.isArray(endpoints)) {\n    return endpoints.flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));\n  }\n\n  if (isIntegrationEndpointRoute(endpoints)) {\n    return [endpoints];\n  }\n\n  if (typeof endpoints === \"object\") {\n    return Object.values(endpoints).flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));\n  }\n\n  return [];\n}\n\nexport function defineIntegration<\n  const TSchema extends FarmIntegrationSchema | undefined,\n  const TConfig,\n  TIntegration extends FarmIntegrationInput<TSchema, TConfig, any>,\n>(\n  integration: TIntegration &\n    FarmIntegrationInput<TSchema, TConfig, NoInfer<TIntegration[\"instance\"]>>,\n): DefinedIntegration<TIntegration, TSchema>;\nexport function defineIntegration<\n  const TSchema extends FarmIntegrationSchema | undefined,\n  const TConfig,\n  TIntegration extends FarmIntegrationInput<TSchema, TConfig, any>,\n>(\n  integration: TIntegration &\n    FarmIntegrationInput<TSchema, TConfig, NoInfer<TIntegration[\"instance\"]>>,\n): DefinedIntegration<TIntegration, TSchema> {\n  const category = integration.category ?? integration.slot;\n\n  if (!category) {\n    throw new Error(\"Integration category is required.\");\n  }\n\n  if (integration.category && integration.slot && integration.category !== integration.slot) {\n    throw new Error(\"Integration category and slot must match when both are provided.\");\n  }\n\n  const routeFactory = createIntegrationRoute(integration.schema);\n  const routes =\n    typeof integration.routes === \"function\"\n      ? integration.routes({\n          route: routeFactory,\n          integrationRoute: routeFactory,\n        })\n      : integration.routes;\n  const endpoints =\n    typeof integration.endpoints === \"function\"\n      ? integration.endpoints({\n          endpoint: routeFactory,\n          route: routeFactory,\n          integrationRoute: routeFactory,\n        })\n      : integration.endpoints;\n  const endpointRoutes = flattenIntegrationEndpoints(endpoints);\n  const allRoutes =\n    routes?.length || endpointRoutes.length\n      ? ([...(routes || []), ...endpointRoutes] as readonly FarmIntegrationRoute[])\n      : undefined;\n\n  for (const route of allRoutes || []) {\n    assertUniqueRouteParameters(route.path, \"api\");\n    validateConfigRouteSource(route.path, `Integration route \"${route.path}\"`);\n    assertTerminalCatchAll(route.path, \"api\");\n  }\n\n  const derivedApi =\n    integration.api ||\n    (allRoutes?.length\n      ? integrationApi.fromRoutes(\n          allRoutes as unknown as ReadonlyArray<{\n            path: string;\n            __operation: FarmIntegrationAPIOperation<any, any, any, any, any>;\n          }>,\n        )\n      : undefined);\n\n  return {\n    kind: \"farm-integration\",\n    ...integration,\n    endpoints,\n    routes: allRoutes,\n    api: derivedApi,\n    category,\n    slot: category,\n  } as unknown as DefinedIntegration<TIntegration, TSchema>;\n}\n\nexport function isFarmIntegration(value: unknown): value is FarmIntegration {\n  return (\n    !!value && typeof value === \"object\" && (value as FarmIntegration).kind === \"farm-integration\"\n  );\n}\n\nexport function resolveIntegrationPlugins(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): FarmPlugin[] {\n  if (!integrations) {\n    return [];\n  }\n\n  const plugins: FarmPlugin[] = [];\n  for (const [key, integration] of Object.entries(integrations)) {\n    if (!integration || !isFarmIntegration(integration)) {\n      continue;\n    }\n\n    const owner = createIntegrationPluginOwner(key, integration, \"lifecycle\");\n    plugins.push(withIntegrationPluginOwner(createIntegrationPlugin(key, integration), owner));\n    plugins.push(...resolveIntegrationPluginContributions(key, integration));\n  }\n\n  return plugins;\n}\n\nfunction resolveIntegrationPluginContributions(\n  key: string,\n  integration: FarmIntegration<any, any>,\n): FarmPlugin[] {\n  const contributions = integration.plugins;\n  if (!contributions) return [];\n  if (!Array.isArray(contributions)) {\n    throw new TypeError(`Integration \"${key}\" plugins must be an array`);\n  }\n\n  const names = new Set<string>();\n  return contributions.map((plugin, index) => {\n    if (!plugin || typeof plugin !== \"object\" || typeof plugin.name !== \"string\") {\n      throw new TypeError(`Integration \"${key}\" plugin at index ${index} is invalid`);\n    }\n    const name = plugin.name.trim();\n    if (!name) {\n      throw new TypeError(`Integration \"${key}\" plugin at index ${index} requires a name`);\n    }\n    if (names.has(name)) {\n      throw new Error(`Integration \"${key}\" contributes duplicate plugin name \"${name}\"`);\n    }\n    names.add(name);\n\n    return withIntegrationPluginOwner(\n      plugin,\n      createIntegrationPluginOwner(key, integration, \"contribution\"),\n      createIntegrationPluginContext(key, integration),\n    );\n  });\n}\n\nfunction createIntegrationPluginOwner(\n  key: string,\n  integration: FarmIntegration<any, any>,\n  source: FarmIntegrationPluginOwner[\"source\"],\n): Readonly<FarmIntegrationPluginOwner> {\n  return Object.freeze({\n    key,\n    category: integration.category,\n    type: integration.type,\n    source,\n    serverRuntime: integration.serverRuntime !== false,\n  });\n}\n\nfunction createIntegrationPluginContext(\n  key: string,\n  integration: FarmIntegration<any, any>,\n): Readonly<FarmPluginIntegrationContext> {\n  return Object.freeze({\n    key,\n    category: integration.category,\n    type: integration.type,\n    instance: integration.instance,\n    serverRuntime: integration.serverRuntime !== false,\n  });\n}\n\nfunction withIntegrationPluginOwner(\n  plugin: FarmPlugin<any, any, any, any, any, boolean>,\n  owner: Readonly<FarmIntegrationPluginOwner>,\n  integration?: Readonly<FarmPluginIntegrationContext>,\n): FarmPlugin {\n  const descriptors = Object.getOwnPropertyDescriptors(plugin);\n  Reflect.deleteProperty(descriptors, FARM_INTEGRATION_PLUGIN_OWNER);\n  Reflect.deleteProperty(descriptors, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME);\n  const ownedPlugin = Object.create(Object.getPrototypeOf(plugin), descriptors) as FarmPlugin;\n  Object.defineProperty(ownedPlugin, FARM_INTEGRATION_PLUGIN_OWNER, { value: owner });\n  Object.defineProperty(ownedPlugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {\n    value: owner.serverRuntime,\n  });\n  if (integration) {\n    setFarmPluginIntegrationContext(ownedPlugin, integration);\n  }\n  return ownedPlugin;\n}\n\nexport function getIntegrationProviders(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): FarmIntegrationProvider[] {\n  if (!integrations) {\n    return [];\n  }\n\n  const providers: FarmIntegrationProvider[] = [];\n  for (const integration of Object.values(integrations)) {\n    if (!integration || !isFarmIntegration(integration) || !integration.providers?.length) {\n      continue;\n    }\n\n    for (const provider of integration.providers) {\n      providers.push({\n        name: provider.name,\n        type: provider.type,\n        props: provider.props,\n        supportsIsolatedHydration: provider.supportsIsolatedHydration,\n        component: provider.component,\n      });\n    }\n  }\n\n  return providers;\n}\n\nexport function isFarmIntegrationProviderComponentReference(\n  value: FarmIntegrationProvider[\"component\"],\n): value is FarmIntegrationProviderComponentReference {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    \"module\" in value &&\n    typeof value.module === \"string\" &&\n    value.module.length > 0,\n  );\n}\n\nexport function getIntegrationDocumentNavigationMatchers(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): string[] {\n  if (!integrations) {\n    return [];\n  }\n\n  const matchers: string[] = [];\n  for (const integration of Object.values(integrations)) {\n    if (\n      !integration ||\n      !isFarmIntegration(integration) ||\n      !integration.documentNavigations?.length\n    ) {\n      continue;\n    }\n\n    for (const navigation of integration.documentNavigations) {\n      const items = Array.isArray(navigation.matcher) ? navigation.matcher : [navigation.matcher];\n\n      for (const item of items) {\n        matchers.push(item);\n      }\n    }\n  }\n\n  return matchers;\n}\n\nexport function getIntegrationSchemas(\n  integrations: FarmIntegrationsUserConfig | undefined,\n): Record<string, FarmIntegrationSchema> {\n  if (!integrations) {\n    return {};\n  }\n\n  const schemaEntries = Object.entries(integrations)\n    .map(([key, integration]) => {\n      const schema = integration && isFarmIntegration(integration) ? integration.schema : undefined;\n      return schema ? ([key, schema] as const) : null;\n    })\n    .filter((value): value is readonly [string, FarmIntegrationSchema] => value !== null);\n\n  return Object.fromEntries(schemaEntries);\n}\n\nexport function getRegisteredIntegrationRuntime(\n  key: string,\n): RegisteredIntegrationRuntime | undefined {\n  return getIntegrationRuntimeRegistry().get(key);\n}\n\nexport function getRegisteredIntegrations(): Record<string, FarmIntegration> {\n  return Object.fromEntries(\n    Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [\n      key,\n      runtime.integration,\n    ]),\n  );\n}\n\nexport function getRegisteredIntegrationSchemas(): Record<string, FarmIntegrationSchema> {\n  return getIntegrationSchemas(getRegisteredIntegrations());\n}\n\nexport function matchIntegrationRoute(\n  integrations: FarmIntegrationsUserConfig | undefined,\n  input: {\n    pathname: string;\n    method?: string;\n  },\n): {\n  key: string;\n  integration: FarmIntegration;\n  route: {\n    path: string;\n    methods: readonly string[];\n  };\n  params: FarmIntegrationRouteParams;\n} | null {\n  if (!integrations) {\n    return null;\n  }\n\n  for (const [key, integration] of Object.entries(integrations)) {\n    if (!integration || !isFarmIntegration(integration)) {\n      continue;\n    }\n\n    const routes = normalizeIntegrationRoutes(integration.routes || []);\n\n    for (const route of routes) {\n      if (!matchesMethod(route.methods, input.method)) {\n        continue;\n      }\n\n      const params = extractPathParams(route.path, input.pathname);\n      if (!params) {\n        continue;\n      }\n\n      return {\n        key,\n        integration,\n        route: {\n          path: route.path,\n          methods: route.methods,\n        },\n        params,\n      };\n    }\n  }\n\n  return null;\n}\n\nexport function matchRegisteredIntegrationRoute(input: { pathname: string; method?: string }): {\n  key: string;\n  integration: FarmIntegration;\n  route: {\n    path: string;\n    methods: readonly string[];\n  };\n  params: FarmIntegrationRouteParams;\n} | null {\n  return matchIntegrationRoute(getRegisteredIntegrations(), input);\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 (\n      value &&\n      typeof value === \"object\" &&\n      (value as FarmIntegrationAPIOperation<any, any, any, any, any>).kind ===\n        \"farm-integration-api-operation\"\n    ) {\n      const operation = value as FarmIntegrationAPIOperation<any, any, any, any, any>;\n      return [\n        key,\n        defineIntegrationAPIOperation({\n          path: operation.path,\n          method: operation.method,\n          bodyFormat: operation.bodyFormat,\n          responseFormat: operation.responseFormat,\n          credentials: operation.credentials,\n          isServer: operation.isServer,\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 getRegisteredIntegrationAPIManifest(): Record<string, FarmIntegrationAPI> {\n  const manifestEntries = Object.entries(getRegisteredIntegrations())\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\ntype IntegrationLifecycleCleanup = () => MaybePromise<void>;\n\nfunction getIntegrationRuntimeEnv(): Record<string, string | undefined> {\n  return typeof process !== \"undefined\" ? process.env : {};\n}\n\nfunction isIntegrationConfigDefinition(\n  value: unknown,\n): value is FarmIntegrationConfigDefinition<unknown> {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (\"schema\" in value ||\n      \"env\" in value ||\n      \"defaults\" in value ||\n      \"input\" in value ||\n      \"resolve\" in value)\n  );\n}\n\nfunction mergeIntegrationConfigValue(current: unknown, next: unknown): unknown {\n  if (next === undefined) {\n    return current;\n  }\n\n  if (isPlainIntegrationConfigObject(current) && isPlainIntegrationConfigObject(next)) {\n    return {\n      ...current,\n      ...next,\n    };\n  }\n\n  return next;\n}\n\nfunction isPlainIntegrationConfigObject(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nasync function resolveIntegrationConfigPart<TValue>(\n  value: TValue | ((context: FarmIntegrationConfigContext) => MaybePromise<TValue>) | undefined,\n  context: FarmIntegrationConfigContext,\n): Promise<TValue | undefined> {\n  if (typeof value === \"function\") {\n    return (value as (context: FarmIntegrationConfigContext) => MaybePromise<TValue>)(context);\n  }\n\n  return value;\n}\n\nfunction resolveIntegrationEnvConfig(\n  env: Record<string, string | readonly string[]> | undefined,\n): Record<string, string> | undefined {\n  if (!env) {\n    return undefined;\n  }\n\n  const runtimeEnv = getIntegrationRuntimeEnv();\n  const config: Record<string, string> = {};\n\n  for (const [key, names] of Object.entries(env)) {\n    const envNames = Array.isArray(names) ? names : [names];\n    const value = envNames.map((name) => runtimeEnv[name]).find((entry) => entry !== undefined);\n    if (value !== undefined) {\n      config[key] = value;\n    }\n  }\n\n  return config;\n}\n\nasync function parseIntegrationConfigSchema<TConfig>(\n  integration: FarmIntegration<any, any>,\n  schema: FarmIntegrationInputSchema<TConfig>,\n  value: unknown,\n): Promise<TConfig> {\n  const parser = schema.safeParseAsync || schema.safeParse;\n  if (parser) {\n    const result = await parser.call(schema, value);\n    if (result.success) {\n      return result.data;\n    }\n\n    throw createIntegrationConfigValidationError(integration, result.error);\n  }\n\n  if (schema[\"~standard\"]?.validate) {\n    const result = await schema[\"~standard\"].validate(value);\n    if (\"value\" in result) {\n      return result.value;\n    }\n\n    throw createIntegrationConfigValidationError(integration, {\n      issues: result.issues,\n    });\n  }\n\n  if (schema.parse) {\n    try {\n      return await schema.parse(value);\n    } catch (error) {\n      throw createIntegrationConfigValidationError(\n        integration,\n        normalizeIntegrationValidationError(error),\n      );\n    }\n  }\n\n  throw new Error(\n    `Integration \"${integration.type}\" config schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.`,\n  );\n}\n\nfunction createIntegrationConfigValidationError(\n  integration: FarmIntegration<any, any>,\n  error: FarmIntegrationValidationErrorLike,\n) {\n  const issues =\n    Array.isArray(error.issues) && error.issues.length > 0\n      ? error.issues\n          .map((issue) => {\n            const normalizedPath = normalizeIntegrationValidationPath(issue.path);\n            const path = normalizedPath.length ? `${normalizedPath.join(\".\")}: ` : \"\";\n            return `${path}${issue.message || \"Invalid config\"}`;\n          })\n          .join(\"; \")\n      : error.message || \"Invalid config\";\n\n  return new Error(`Integration \"${integration.type}\" config validation failed: ${issues}`);\n}\n\nasync function resolveIntegrationConfig<TConfig>(\n  integration: FarmIntegration<any, TConfig>,\n  context: FarmIntegrationConfigContext,\n): Promise<TConfig> {\n  const config = integration.config;\n  if (!config) {\n    return undefined as TConfig;\n  }\n\n  if (!isIntegrationConfigDefinition(config)) {\n    return parseIntegrationConfigSchema(integration, config, {});\n  }\n\n  let value: unknown = {};\n  value = mergeIntegrationConfigValue(\n    value,\n    await resolveIntegrationConfigPart(config.defaults, context),\n  );\n  value = mergeIntegrationConfigValue(value, resolveIntegrationEnvConfig(config.env));\n  value = mergeIntegrationConfigValue(\n    value,\n    await resolveIntegrationConfigPart(config.input, context),\n  );\n  value = mergeIntegrationConfigValue(value, await config.resolve?.(context));\n\n  return config.schema\n    ? parseIntegrationConfigSchema(integration, config.schema, value)\n    : (value as TConfig);\n}\n\nfunction createIntegrationLifecycleLogger(\n  integration: FarmIntegration<any, any>,\n  phase: FarmIntegrationLogPhase,\n): FarmIntegrationLifecycleLogger {\n  const write = (\n    level: FarmIntegrationLifecycleLogLevel,\n    message: string,\n    meta?: Record<string, unknown>,\n  ) => {\n    if (!integration.log) {\n      return;\n    }\n\n    void Promise.resolve(\n      integration.log({\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase,\n        level,\n        message,\n        meta,\n        context: new Map(),\n      }),\n    ).catch(() => {});\n  };\n\n  return {\n    info(message, meta) {\n      write(\"info\", message, meta);\n    },\n    warn(message, meta) {\n      write(\"warn\", message, meta);\n    },\n    error(message, meta) {\n      write(\"error\", message, meta);\n    },\n  };\n}\n\nasync function emitIntegrationLog(\n  integration: FarmIntegration,\n  event: FarmIntegrationLogEvent,\n): Promise<void> {\n  try {\n    await integration.log?.(event);\n  } catch {\n    // Integration logging is optional observability. A failed sink must not\n    // block lifecycle startup, request handlers, responses, or cleanup.\n  }\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 isFarmIntegrationData(value: unknown): value is FarmIntegrationData {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isPlainIntegrationDataObject(value: unknown): value is Record<string, unknown> {\n  if (!isFarmIntegrationData(value)) {\n    return false;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction sanitizeIntegrationDataValue(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map((item) => sanitizeIntegrationDataValue(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] = sanitizeIntegrationDataValue(item);\n  }\n\n  return sanitized;\n}\n\nfunction normalizeIntegrationData(value: FarmIntegrationData | undefined): FarmIntegrationData {\n  if (!isFarmIntegrationData(value)) {\n    return {};\n  }\n\n  const sanitized = sanitizeIntegrationDataValue(value);\n  return isFarmIntegrationData(sanitized) ? sanitized : {};\n}\n\nfunction getIntegrationDataHeaderByteLength(value: string): number {\n  return new TextEncoder().encode(value).byteLength;\n}\n\nfunction parseIntegrationDataHeader(request: Request): FarmIntegrationData {\n  const raw = request.headers.get(INTEGRATION_DATA_HEADER);\n  if (!raw) {\n    return {};\n  }\n\n  if (getIntegrationDataHeaderByteLength(raw) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {\n    return {};\n  }\n\n  try {\n    const value = JSON.parse(raw);\n    return normalizeIntegrationData(value);\n  } catch {\n    return {};\n  }\n}\n\nfunction resolveIntegrationData(request: Request, data?: FarmIntegrationData): FarmIntegrationData {\n  return {\n    ...parseIntegrationDataHeader(request),\n    ...normalizeIntegrationData(data),\n  };\n}\n\nfunction createIntegrationPlugin(integrationKey: string, integration: FarmIntegration): FarmPlugin {\n  const routes = normalizeIntegrationRoutes(integration.routes || []);\n  const middleware = [...(integration.middleware || [])];\n  const cleanupCallbacks: IntegrationLifecycleCleanup[] = [];\n  let integrationConfigPromise: Promise<unknown> | undefined;\n\n  const runCleanup = async () => {\n    const callbacks = cleanupCallbacks.splice(0).reverse();\n    for (const callback of callbacks) {\n      await callback();\n    }\n  };\n\n  const createLifecycleContext = async (\n    context: FarmPluginContext,\n    phase: FarmIntegrationLogPhase,\n    options: { reason?: string } = {},\n  ): Promise<FarmIntegrationLifecycleContext> => {\n    const args = createIntegrationRouteArgs({\n      integration,\n      config: context.config,\n    });\n    const configContext: FarmIntegrationConfigContext = {\n      key: integrationKey,\n      integration,\n      appConfig: context.config,\n      config: context.config,\n      args,\n      env: getIntegrationRuntimeEnv(),\n      isDev: context.isDev,\n      isProd: context.isProd,\n    };\n    integrationConfigPromise ??= resolveIntegrationConfig(integration, configContext);\n\n    return {\n      ...configContext,\n      integrationConfig: await integrationConfigPromise,\n      log: createIntegrationLifecycleLogger(integration, phase),\n      reason: options.reason,\n      async cleanup(callback) {\n        if (callback) {\n          cleanupCallbacks.push(callback);\n          return;\n        }\n\n        await runCleanup();\n      },\n    };\n  };\n\n  const plugin: FarmPlugin = {\n    name: `farm:integration:${integration.category}:${integration.type}`,\n    enforce: \"pre\",\n\n    async init(context) {\n      getIntegrationRuntimeRegistry().set(integrationKey, {\n        integration,\n        config: context.config,\n        isDev: context.isDev,\n        isProd: context.isProd,\n      });\n\n      await createLifecycleContext(context, \"validate\");\n\n      if (integration.validate) {\n        await integration.validate(await createLifecycleContext(context, \"validate\"));\n      }\n\n      if (integration.setup) {\n        await integration.setup(await createLifecycleContext(context, \"setup\"));\n      }\n\n      if (!integration.log) {\n        return;\n      }\n\n      for (const route of routes) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"registered\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          context: new Map(),\n        });\n      }\n\n      for (const entry of middleware) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"registered\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          context: new Map(),\n        });\n      }\n    },\n\n    async ready(context) {\n      if (integration.ready) {\n        await integration.ready(await createLifecycleContext(context, \"ready\"));\n      }\n    },\n\n    async shutdown(payload, context) {\n      try {\n        if (integration.dispose) {\n          await integration.dispose(\n            await createLifecycleContext(context, \"dispose\", {\n              reason: payload.reason,\n            }),\n          );\n        }\n      } finally {\n        await runCleanup();\n      }\n    },\n\n    async beforeRequest(req, res, context) {\n      const fullUrl = `http://${req.headers.host || \"localhost\"}${req.url || \"/\"}`;\n      const url = new URL(fullUrl);\n      const pathname = url.pathname;\n      const requestId = getRequestId(req);\n      let bodyLoaded = false;\n      let requestBody: Buffer | undefined;\n\n      const getRequestBody = async () => {\n        if (!bodyLoaded) {\n          bodyLoaded = true;\n          if (req.method && req.method !== \"GET\" && req.method !== \"HEAD\") {\n            requestBody = await readNodeRequestBody(\n              req,\n              resolveFarmServerConfig(context.config.server).bodySizeLimit,\n            );\n          }\n        }\n\n        return requestBody;\n      };\n\n      const createHandlerRequest = async (): Promise<Request | null> => {\n        try {\n          return createWebRequest(req, fullUrl, await getRequestBody());\n        } catch (error) {\n          const response = createFarmRequestBodyErrorResponse(error);\n          if (!response) throw error;\n          await sendWebResponse(res, response);\n          return null;\n        }\n      };\n\n      for (const entry of middleware) {\n        const params = resolveMatcherParams(entry.matcher, pathname);\n        if (!params) {\n          continue;\n        }\n\n        const request = await createHandlerRequest();\n        if (!request) return;\n        const handlerContext = createIntegrationHandlerContext({\n          integration,\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          rawRequest: req,\n          params,\n          pathname,\n          requestId,\n          pluginContext: context,\n        });\n        const startedAt = Date.now();\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:start\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          requestId,\n          context: handlerContext.req.snapshot(),\n        });\n\n        try {\n          const response = await entry.handler(request, handlerContext);\n          if (response) {\n            await sendWebResponse(res, response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"middleware\",\n                path: normalizeMatcher(entry.matcher),\n                methods: [\"ALL\"],\n              },\n              request,\n              response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:end\",\n            route: {\n              kind: \"middleware\",\n              path: normalizeMatcher(entry.matcher),\n              methods: [\"ALL\"],\n            },\n            request,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            context: handlerContext.req.snapshot(),\n          });\n        } catch (error) {\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:error\",\n            route: {\n              kind: \"middleware\",\n              path: normalizeMatcher(entry.matcher),\n              methods: [\"ALL\"],\n            },\n            request,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            error,\n            context: handlerContext.req.snapshot(),\n          });\n          throw error;\n        }\n      }\n\n      for (const route of routes) {\n        const params = matchesMethod(route.methods, req.method)\n          ? extractPathParams(route.path, pathname)\n          : null;\n        if (!params) {\n          continue;\n        }\n\n        const request = await createHandlerRequest();\n        if (!request) return;\n        const handlerContext = createIntegrationHandlerContext({\n          integration,\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          rawRequest: req,\n          params,\n          pathname,\n          requestId,\n          pluginContext: context,\n        });\n        const startedAt = Date.now();\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:start\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          requestId,\n          context: handlerContext.req.snapshot(),\n        });\n\n        try {\n          const validation = await validateIntegrationRouteInput(route, request, url);\n          if (!validation.success) {\n            await sendWebResponse(res, validation.response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"route\",\n                path: route.path,\n                methods: route.methods,\n              },\n              request,\n              response: validation.response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n          handlerContext.input = validation.input;\n\n          for (const middlewareEntry of route.middleware || []) {\n            const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n            if (middlewareResponse) {\n              await sendWebResponse(res, middlewareResponse);\n              await emitIntegrationLog(integration, {\n                category: integration.category,\n                slot: integration.category,\n                type: integration.type,\n                phase: \"request:end\",\n                route: {\n                  kind: \"route\",\n                  path: route.path,\n                  methods: route.methods,\n                },\n                request,\n                response: middlewareResponse,\n                requestId,\n                durationMs: Date.now() - startedAt,\n                context: handlerContext.req.snapshot(),\n              });\n              return;\n            }\n          }\n\n          const beforeResponse = await runIntegrationRouteBeforeHooks(\n            route,\n            request,\n            handlerContext,\n          );\n          if (beforeResponse) {\n            const response = await runIntegrationRouteAfterHooks(\n              route,\n              request,\n              handlerContext,\n              beforeResponse,\n            );\n            await sendWebResponse(res, response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"route\",\n                path: route.path,\n                methods: route.methods,\n              },\n              request,\n              response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n\n          const handlerResponse = await route.handler(request, handlerContext);\n          const response = await runIntegrationRouteAfterHooks(\n            route,\n            request,\n            handlerContext,\n            handlerResponse,\n          );\n          await sendWebResponse(res, response);\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:end\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            response,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            context: handlerContext.req.snapshot(),\n          });\n          return;\n        } catch (error) {\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:error\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            error,\n            context: handlerContext.req.snapshot(),\n          });\n          throw error;\n        }\n      }\n    },\n  };\n\n  Object.defineProperty(plugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {\n    value: integration.serverRuntime !== false,\n  });\n\n  return plugin;\n}\n\nfunction createIntegrationHandlerContext(input: {\n  integration: FarmIntegration;\n  route: FarmIntegrationHandlerContext[\"route\"];\n  request: Request;\n  rawRequest: FarmRequest;\n  params: FarmIntegrationRouteParams;\n  pathname: string;\n  requestId: string;\n  pluginContext: FarmPluginContext;\n}): FarmIntegrationHandlerContext {\n  const req = createIntegrationRequestContextStore(\n    input.rawRequest,\n    input.request,\n    input.pluginContext,\n  );\n\n  return {\n    request: input.request,\n    requestId: input.requestId,\n    url: new URL(input.request.url),\n    pathname: input.pathname,\n    method: input.request.method,\n    params: input.params,\n    input: {},\n    args: createIntegrationRouteArgs({\n      integration: input.integration,\n      config: input.pluginContext.config,\n    }),\n    data: resolveIntegrationData(input.request),\n    integration: {\n      category: input.integration.category,\n      slot: input.integration.category,\n      type: input.integration.type,\n      instance: input.integration.instance,\n    },\n    route: input.route,\n    req,\n    requestContext: req,\n    config: input.pluginContext.config,\n    isDev: input.pluginContext.isDev,\n    isProd: input.pluginContext.isProd,\n  };\n}\n\ntype NormalizedIntegrationRoute = Omit<FarmIntegrationRoute, \"method\" | \"methods\"> & {\n  methods: readonly string[];\n  __operation?: FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nfunction normalizeIntegrationRoutes(\n  routes: readonly FarmIntegrationRoute[],\n): NormalizedIntegrationRoute[] {\n  return routes\n    .map((route, index) => {\n      // Raw FarmIntegration objects and direct dispatch also pass through here.\n      assertUniqueRouteParameters(route.path, \"api\");\n      return {\n        index,\n        route: {\n          ...route,\n          methods: normalizeIntegrationRouteMethods(route),\n          input: normalizeIntegrationRouteInputSchemas(route),\n        },\n        specificity: getRoutePatternSpecificity(route.path, \"api\"),\n      };\n    })\n    .sort(\n      (left, right) =>\n        compareRouteSpecificity(left.specificity, right.specificity) || left.index - right.index,\n    )\n    .map(({ route }) => route);\n}\n\nfunction normalizeIntegrationRouteMethods(route: Pick<FarmIntegrationRoute, \"method\" | \"methods\">) {\n  const input =\n    route.methods && route.methods.length > 0\n      ? [...route.methods]\n      : route.method\n        ? [route.method]\n        : [\"ALL\"];\n\n  return input.map((method) => String(method).toUpperCase());\n}\n\nfunction normalizeIntegrationRouteInputSchemas<TBody, TQuery>(\n  route: Pick<FarmIntegrationRoute<TBody, TQuery>, \"body\" | \"query\" | \"input\">,\n): FarmIntegrationRouteInputSchemas<TBody, TQuery> | undefined {\n  const input: FarmIntegrationRouteInputSchemas<TBody, TQuery> = {\n    ...route.input,\n  };\n\n  if (route.body) {\n    input.body = route.body;\n  }\n\n  if (route.query) {\n    input.query = route.query;\n  }\n\n  return input.body || input.query ? input : undefined;\n}\n\ntype IntegrationRouteInputValidationResult =\n  | {\n      success: true;\n      input: FarmIntegrationRouteInput;\n    }\n  | {\n      success: false;\n      response: Response;\n    };\n\nasync function validateIntegrationRouteInput(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  url: URL,\n): Promise<IntegrationRouteInputValidationResult> {\n  if (request.method.toUpperCase() === \"QUERY\" && !request.headers.has(\"content-type\")) {\n    return {\n      success: false,\n      response: Response.json(\n        {\n          error: \"Invalid QUERY request\",\n          message: \"QUERY requests must include a Content-Type header.\",\n        },\n        { status: 400 },\n      ),\n    };\n  }\n\n  const schemas = route.input;\n  if (!schemas?.body && !schemas?.query) {\n    return {\n      success: true,\n      input: {},\n    };\n  }\n\n  const input: FarmIntegrationRouteInput = {};\n  const issues: FarmIntegrationValidationIssue[] = [];\n\n  if (schemas.query) {\n    const queryResult = await parseIntegrationInputSchema(\n      \"query\",\n      schemas.query,\n      createQueryInput(url.searchParams),\n    );\n    if (queryResult.success) {\n      input.query = queryResult.data;\n    } else {\n      issues.push(...queryResult.issues);\n    }\n  }\n\n  if (schemas.body) {\n    const bodyInput = await readIntegrationValidationBody(\n      request,\n      getIntegrationRouteBodyFormat(route),\n    );\n\n    if (bodyInput.success) {\n      const bodyResult = await parseIntegrationInputSchema(\"body\", schemas.body, bodyInput.data);\n      if (bodyResult.success) {\n        input.body = bodyResult.data;\n      } else {\n        issues.push(...bodyResult.issues);\n      }\n    } else {\n      issues.push(bodyInput.issue);\n    }\n  }\n\n  if (issues.length > 0) {\n    return {\n      success: false,\n      response: createIntegrationValidationResponse(issues),\n    };\n  }\n\n  return {\n    success: true,\n    input,\n  };\n}\n\nasync function parseIntegrationInputSchema<TValue>(\n  source: FarmIntegrationRouteInputSource,\n  schema: FarmIntegrationInputSchema<TValue>,\n  value: unknown,\n): Promise<\n  | {\n      success: true;\n      data: TValue;\n    }\n  | {\n      success: false;\n      issues: FarmIntegrationValidationIssue[];\n    }\n> {\n  const parser = schema.safeParseAsync || schema.safeParse;\n  if (parser) {\n    const result = await parser.call(schema, value);\n    if (result.success) {\n      return {\n        success: true,\n        data: result.data,\n      };\n    }\n\n    return {\n      success: false,\n      issues: normalizeIntegrationValidationIssues(source, result.error),\n    };\n  }\n\n  if (schema[\"~standard\"]?.validate) {\n    const result = await schema[\"~standard\"].validate(value);\n    if (\"value\" in result) {\n      return {\n        success: true,\n        data: result.value,\n      };\n    }\n\n    return {\n      success: false,\n      issues: normalizeIntegrationValidationIssues(source, {\n        issues: result.issues,\n      }),\n    };\n  }\n\n  if (schema.parse) {\n    try {\n      return {\n        success: true,\n        data: await schema.parse(value),\n      };\n    } catch (error) {\n      return {\n        success: false,\n        issues: normalizeIntegrationValidationIssues(\n          source,\n          normalizeIntegrationValidationError(error),\n        ),\n      };\n    }\n  }\n\n  return {\n    success: false,\n    issues: [\n      {\n        source,\n        message:\n          \"Input schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.\",\n      },\n    ],\n  };\n}\n\nfunction createIntegrationValidationResponse(issues: readonly FarmIntegrationValidationIssue[]) {\n  return Response.json(\n    {\n      error: \"Integration route input validation failed\",\n      issues,\n    },\n    {\n      status: 400,\n    },\n  );\n}\n\nfunction normalizeIntegrationValidationIssues(\n  source: FarmIntegrationRouteInputSource,\n  error: FarmIntegrationValidationErrorLike,\n): FarmIntegrationValidationIssue[] {\n  if (Array.isArray(error.issues) && error.issues.length > 0) {\n    return error.issues.map((issue) => ({\n      source,\n      path: normalizeIntegrationValidationPath(issue.path),\n      code: issue.code,\n      message: issue.message || \"Invalid input\",\n    }));\n  }\n\n  return [\n    {\n      source,\n      path: [],\n      message: error.message || \"Invalid input\",\n    },\n  ];\n}\n\nfunction normalizeIntegrationValidationPath(\n  path: readonly FarmIntegrationValidationPathSegment[] | undefined,\n): (string | number)[] {\n  return (path || []).map((segment) => {\n    const key =\n      typeof segment === \"object\" && segment !== null && \"key\" in segment ? segment.key : segment;\n    return typeof key === \"symbol\" ? key.description || key.toString() : key;\n  });\n}\n\nfunction normalizeIntegrationValidationError(error: unknown): FarmIntegrationValidationErrorLike {\n  if (error && typeof error === \"object\") {\n    return error as FarmIntegrationValidationErrorLike;\n  }\n\n  return {\n    message: error instanceof Error ? error.message : String(error || \"Invalid input\"),\n  };\n}\n\nasync function readIntegrationValidationBody(\n  request: Request,\n  format: FarmIntegrationAPIBodyFormat,\n): Promise<\n  | {\n      success: true;\n      data: unknown;\n    }\n  | {\n      success: false;\n      issue: FarmIntegrationValidationIssue;\n    }\n> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || format === \"none\") {\n    return {\n      success: true,\n      data: undefined,\n    };\n  }\n\n  try {\n    if (format === \"form\") {\n      return {\n        success: true,\n        data: createFormInput(await request.clone().formData()),\n      };\n    }\n\n    const text = await request.clone().text();\n    if (text.trim().length === 0) {\n      return {\n        success: true,\n        data: undefined,\n      };\n    }\n\n    return {\n      success: true,\n      data: JSON.parse(text),\n    };\n  } catch (error) {\n    return {\n      success: false,\n      issue: {\n        source: \"body\",\n        path: [],\n        message:\n          format === \"json\"\n            ? \"Expected a valid JSON request body.\"\n            : error instanceof Error && error.message\n              ? error.message\n              : \"Could not parse request body.\",\n      },\n    };\n  }\n}\n\nfunction getIntegrationRouteBodyFormat(route: NormalizedIntegrationRoute) {\n  return route.bodyFormat || route.__operation?.bodyFormat || \"json\";\n}\n\nfunction createIntegrationRouteArgs(input: {\n  integration: FarmIntegration;\n  config: FarmPluginContext[\"config\"];\n}): FarmIntegrationRouteArgs {\n  let clientPromise: Promise<unknown | undefined> | undefined;\n  let ormPromise: Promise<unknown> | undefined;\n\n  const getClient = () => {\n    clientPromise ??= import(\"./storage\").then(({ resolveStorageRuntimeClient }) =>\n      resolveStorageRuntimeClient(input.config.storage),\n    );\n    return clientPromise;\n  };\n\n  const getOrm = () => {\n    if (!input.integration.schema) {\n      throw new Error(\n        `Integration \"${input.integration.type}\" does not define a schema for ctx.args.db.`,\n      );\n    }\n\n    ormPromise ??= import(\"./integration-orm\").then(({ createIntegrationOrm }) =>\n      createIntegrationOrm({\n        schema: input.integration.schema!,\n        config: input.config,\n      }),\n    );\n    return ormPromise;\n  };\n\n  return {\n    db: createLazyIntegrationOrmClient(getOrm) as never,\n    getDb: getOrm as never,\n    storage: {\n      getClient,\n      getOrm: getOrm as never,\n    },\n  };\n}\n\nfunction createLazyIntegrationOrmClient(resolveOrm: () => Promise<unknown>) {\n  const modelProxyCache = new Map<PropertyKey, unknown>();\n\n  return new Proxy(\n    {},\n    {\n      get(_target, prop) {\n        if (prop === \"then\") {\n          return undefined;\n        }\n\n        if (prop === \"transaction\" || prop === \"batch\") {\n          return async (...args: unknown[]) => {\n            const orm = (await resolveOrm()) as Record<PropertyKey, unknown>;\n            const member = orm[prop];\n            if (typeof member !== \"function\") {\n              throw new Error(`Integration ORM does not expose \"${String(prop)}\".`);\n            }\n            return member.apply(orm, args);\n          };\n        }\n\n        if (prop === \"$driver\") {\n          return undefined;\n        }\n\n        if (!modelProxyCache.has(prop)) {\n          modelProxyCache.set(prop, createLazyIntegrationOrmModel(resolveOrm, prop));\n        }\n\n        return modelProxyCache.get(prop);\n      },\n    },\n  );\n}\n\nfunction createLazyIntegrationOrmModel(resolveOrm: () => Promise<unknown>, modelName: PropertyKey) {\n  return new Proxy(\n    {},\n    {\n      get(_target, prop) {\n        if (prop === \"then\") {\n          return undefined;\n        }\n\n        return async (...args: unknown[]) => {\n          const orm = (await resolveOrm()) as Record<PropertyKey, Record<PropertyKey, unknown>>;\n          const model = orm[modelName];\n          const member = model?.[prop];\n          if (typeof member !== \"function\") {\n            throw new Error(\n              `Integration ORM model \"${String(modelName)}\" does not expose \"${String(prop)}\".`,\n            );\n          }\n          return member.apply(model, args);\n        };\n      },\n    },\n  );\n}\n\nasync function runIntegrationRouteBeforeHooks(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  context: FarmIntegrationHandlerContext,\n): Promise<Response | undefined> {\n  const hookContext = context as FarmIntegrationRouteHookContext;\n  hookContext.response = undefined;\n\n  for (const hook of route.before || []) {\n    const response = await hook(request, hookContext);\n    if (response) {\n      hookContext.response = response;\n      return response;\n    }\n\n    if (hookContext.response) {\n      return hookContext.response;\n    }\n  }\n\n  return undefined;\n}\n\nasync function runIntegrationRouteAfterHooks(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  context: FarmIntegrationHandlerContext,\n  response: Response,\n): Promise<Response> {\n  const hookContext = context as FarmIntegrationRouteHookContext;\n  let currentResponse = response;\n\n  for (const hook of route.after || []) {\n    hookContext.response = currentResponse;\n    const nextResponse = await hook(request, hookContext);\n    currentResponse = nextResponse || hookContext.response || currentResponse;\n  }\n\n  hookContext.response = currentResponse;\n  return currentResponse;\n}\n\nfunction createQueryInput(searchParams: URLSearchParams): Record<string, string | string[]> {\n  const input: Record<string, string | string[]> = {};\n  searchParams.forEach((value, key) => {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n\n    const existing = input[key];\n    if (existing === undefined) {\n      input[key] = value;\n      return;\n    }\n\n    input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n  });\n  return input;\n}\n\nfunction createFormInput(\n  formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n  const input: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n  formData.forEach((value, key) => {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n\n    const existing = input[key];\n    if (existing === undefined) {\n      input[key] = value;\n      return;\n    }\n\n    input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n  });\n  return input;\n}\n\nexport async function dispatchIntegrationRequest(\n  runtime: RegisteredIntegrationRuntime,\n  request: Request,\n  options: {\n    currentRequest?: Request;\n    data?: FarmIntegrationData;\n    internal?: boolean;\n  } = {},\n): Promise<Response | null> {\n  try {\n    request = await bufferFarmRequestBody(\n      request,\n      resolveFarmServerConfig(runtime.config.server).bodySizeLimit,\n    );\n  } catch (error) {\n    const response = createFarmRequestBodyErrorResponse(error);\n    if (response) return response;\n    throw error;\n  }\n\n  const integration = runtime.integration;\n  const url = new URL(request.url);\n  const pathname = url.pathname;\n  const requestId =\n    request.headers.get(\"x-request-id\") ||\n    options.currentRequest?.headers.get(\"x-request-id\") ||\n    String(Date.now());\n  const routes = normalizeIntegrationRoutes(integration.routes || []);\n  const middleware = [...(integration.middleware || [])];\n\n  for (const entry of middleware) {\n    const params = resolveMatcherParams(entry.matcher, pathname);\n    if (!params) {\n      continue;\n    }\n\n    const handlerContext = createServerIntegrationHandlerContext({\n      runtime,\n      route: {\n        kind: \"middleware\",\n        path: normalizeMatcher(entry.matcher),\n        methods: [\"ALL\"],\n      },\n      request,\n      params,\n      pathname,\n      requestId,\n      currentRequest: options.currentRequest,\n      data: options.data,\n      internal: options.internal === true,\n    });\n    const startedAt = Date.now();\n\n    await emitIntegrationLog(integration, {\n      category: integration.category,\n      slot: integration.category,\n      type: integration.type,\n      phase: \"request:start\",\n      route: {\n        kind: \"middleware\",\n        path: normalizeMatcher(entry.matcher),\n        methods: [\"ALL\"],\n      },\n      request,\n      requestId,\n      context: handlerContext.req.snapshot(),\n    });\n\n    try {\n      const response = await entry.handler(request, handlerContext);\n      if (response) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:end\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          response,\n          requestId,\n          durationMs: Date.now() - startedAt,\n          context: handlerContext.req.snapshot(),\n        });\n        return response;\n      }\n\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:end\",\n        route: {\n          kind: \"middleware\",\n          path: normalizeMatcher(entry.matcher),\n          methods: [\"ALL\"],\n        },\n        request,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        context: handlerContext.req.snapshot(),\n      });\n    } catch (error) {\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:error\",\n        route: {\n          kind: \"middleware\",\n          path: normalizeMatcher(entry.matcher),\n          methods: [\"ALL\"],\n        },\n        request,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        error,\n        context: handlerContext.req.snapshot(),\n      });\n      throw error;\n    }\n  }\n\n  for (const route of routes) {\n    const params = matchesMethod(route.methods, request.method)\n      ? extractPathParams(route.path, pathname)\n      : null;\n    if (!params) {\n      continue;\n    }\n\n    const handlerContext = createServerIntegrationHandlerContext({\n      runtime,\n      route: {\n        kind: \"route\",\n        path: route.path,\n        methods: route.methods,\n      },\n      request,\n      params,\n      pathname,\n      requestId,\n      currentRequest: options.currentRequest,\n      data: options.data,\n      internal: options.internal === true,\n    });\n    const startedAt = Date.now();\n\n    await emitIntegrationLog(integration, {\n      category: integration.category,\n      slot: integration.category,\n      type: integration.type,\n      phase: \"request:start\",\n      route: {\n        kind: \"route\",\n        path: route.path,\n        methods: route.methods,\n      },\n      request,\n      requestId,\n      context: handlerContext.req.snapshot(),\n    });\n\n    try {\n      const validation = await validateIntegrationRouteInput(route, request, url);\n      if (!validation.success) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:end\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          response: validation.response,\n          requestId,\n          durationMs: Date.now() - startedAt,\n          context: handlerContext.req.snapshot(),\n        });\n        return validation.response;\n      }\n      handlerContext.input = validation.input;\n\n      for (const middlewareEntry of route.middleware || []) {\n        const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n        if (middlewareResponse) {\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:end\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            response: middlewareResponse,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            context: handlerContext.req.snapshot(),\n          });\n          return middlewareResponse;\n        }\n      }\n\n      const beforeResponse = await runIntegrationRouteBeforeHooks(route, request, handlerContext);\n      if (beforeResponse) {\n        const response = await runIntegrationRouteAfterHooks(\n          route,\n          request,\n          handlerContext,\n          beforeResponse,\n        );\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:end\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          response,\n          requestId,\n          durationMs: Date.now() - startedAt,\n          context: handlerContext.req.snapshot(),\n        });\n        return response;\n      }\n\n      const handlerResponse = await route.handler(request, handlerContext);\n      const response = await runIntegrationRouteAfterHooks(\n        route,\n        request,\n        handlerContext,\n        handlerResponse,\n      );\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:end\",\n        route: {\n          kind: \"route\",\n          path: route.path,\n          methods: route.methods,\n        },\n        request,\n        response,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        context: handlerContext.req.snapshot(),\n      });\n      return response;\n    } catch (error) {\n      await emitIntegrationLog(integration, {\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase: \"request:error\",\n        route: {\n          kind: \"route\",\n          path: route.path,\n          methods: route.methods,\n        },\n        request,\n        requestId,\n        durationMs: Date.now() - startedAt,\n        error,\n        context: handlerContext.req.snapshot(),\n      });\n      throw error;\n    }\n  }\n\n  return null;\n}\n\n(globalThis as GlobalWithIntegrationRuntimeRegistry)[INTEGRATION_REQUEST_DISPATCHER_KEY] =\n  dispatchIntegrationRequest;\n\nfunction createIntegrationRequestContextStore(\n  rawRequest: FarmRequest,\n  request: Request,\n  pluginContext: FarmPluginContext,\n): FarmIntegrationRequestContextStore {\n  return {\n    get(key) {\n      const requestValue = pluginContext.requestContext.get(request, key);\n      if (requestValue !== undefined) {\n        return requestValue;\n      }\n\n      return pluginContext.requestContext.get(rawRequest, key);\n    },\n    set(key, value, options) {\n      pluginContext.requestContext.set(rawRequest, key, value, options);\n      pluginContext.requestContext.set(request, key, value, options);\n    },\n    has(key) {\n      return (\n        pluginContext.requestContext.has(request, key) ||\n        pluginContext.requestContext.has(rawRequest, key)\n      );\n    },\n    delete(key) {\n      const deletedRequest = pluginContext.requestContext.delete(request, key);\n      const deletedRaw = pluginContext.requestContext.delete(rawRequest, key);\n      return deletedRequest || deletedRaw;\n    },\n    clear() {\n      pluginContext.requestContext.clear(rawRequest);\n      pluginContext.requestContext.clear(request);\n    },\n    snapshot(options) {\n      const merged = pluginContext.requestContext.getAll(rawRequest, options);\n      const requestSnapshot = pluginContext.requestContext.getAll(request, options);\n      for (const [key, value] of requestSnapshot) {\n        merged.set(key, value);\n      }\n      return merged;\n    },\n  };\n}\n\nfunction createServerIntegrationHandlerContext(input: {\n  runtime: RegisteredIntegrationRuntime;\n  route: FarmIntegrationHandlerContext[\"route\"];\n  request: Request;\n  params: FarmIntegrationRouteParams;\n  pathname: string;\n  requestId: string;\n  currentRequest?: Request;\n  data?: FarmIntegrationData;\n  internal?: boolean;\n}): FarmIntegrationHandlerContext {\n  const req = createServerIntegrationRequestContextStore(input.request, input.currentRequest);\n\n  if (input.internal) {\n    req.set(FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY, true);\n  }\n\n  return {\n    request: input.request,\n    requestId: input.requestId,\n    url: new URL(input.request.url),\n    pathname: input.pathname,\n    method: input.request.method,\n    params: input.params,\n    input: {},\n    args: createIntegrationRouteArgs({\n      integration: input.runtime.integration,\n      config: input.runtime.config,\n    }),\n    data: resolveIntegrationData(input.request, input.data),\n    integration: {\n      category: input.runtime.integration.category,\n      slot: input.runtime.integration.category,\n      type: input.runtime.integration.type,\n      instance: input.runtime.integration.instance,\n    },\n    route: input.route,\n    req,\n    requestContext: req,\n    config: input.runtime.config,\n    isDev: input.runtime.isDev,\n    isProd: input.runtime.isProd,\n  };\n}\n\nfunction createServerIntegrationRequestContextStore(\n  request: Request,\n  currentRequest?: Request,\n): FarmIntegrationRequestContextStore {\n  return {\n    get(key) {\n      const requestValue = getRequestContext(request, key);\n      if (requestValue !== undefined) {\n        return requestValue;\n      }\n\n      if (currentRequest) {\n        return getRequestContext(currentRequest, key);\n      }\n\n      return undefined;\n    },\n    set(key, value, options) {\n      setRequestContext(request, key, value, options);\n      if (currentRequest) {\n        setRequestContext(currentRequest, key, value, options);\n      }\n    },\n    has(key) {\n      return (\n        hasRequestContext(request, key) ||\n        (!!currentRequest && hasRequestContext(currentRequest, key))\n      );\n    },\n    delete(key) {\n      const deletedRequest = deleteRequestContext(request, key);\n      const deletedCurrent = currentRequest ? deleteRequestContext(currentRequest, key) : false;\n      return deletedRequest || deletedCurrent;\n    },\n    clear() {\n      clearRequestContext(request);\n      if (currentRequest) {\n        clearRequestContext(currentRequest);\n      }\n    },\n    snapshot(options) {\n      const merged = currentRequest\n        ? getRequestContextSnapshot(currentRequest, options)\n        : new Map<string, unknown>();\n      const requestSnapshot = getRequestContextSnapshot(request, options);\n      for (const [key, value] of requestSnapshot) {\n        merged.set(key, value);\n      }\n      return merged;\n    },\n  };\n}\n\nfunction createWebRequest(req: FarmRequest, fullUrl: string, body?: Buffer): Request {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        headers.append(key, item);\n      }\n      continue;\n    }\n\n    headers.set(key, value);\n  }\n\n  return new Request(fullUrl, {\n    method: req.method,\n    headers,\n    body: body as BodyInit | undefined,\n  });\n}\n\nfunction matchesMethod(methods: readonly string[], method: string | undefined): boolean {\n  if (!method) {\n    return false;\n  }\n\n  const normalizedMethod = method.toUpperCase();\n  return methods.some((item) => {\n    const candidate = item.toUpperCase();\n    return candidate === \"ALL\" || candidate === normalizedMethod;\n  });\n}\n\nfunction matchesMatcher(\n  matcher: string | readonly string[] | undefined,\n  pathname: string,\n): boolean {\n  return resolveMatcherParams(matcher, pathname) !== null;\n}\n\nfunction resolveMatcherParams(\n  matcher: string | readonly string[] | undefined,\n  pathname: string,\n): FarmIntegrationRouteParams | null {\n  if (!matcher) {\n    return {};\n  }\n\n  const list = Array.isArray(matcher) ? matcher : [matcher];\n  for (const item of list) {\n    if (item === \"/(.*)\" || item === \"*\") {\n      return {};\n    }\n    if (item.endsWith(\"(.*)\")) {\n      const prefix = item.slice(0, -4);\n      if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n        return {};\n      }\n      continue;\n    }\n    const params = extractPathParams(item, pathname);\n    if (params) {\n      return params;\n    }\n  }\n\n  return null;\n}\n\nfunction matchesPath(pattern: string, pathname: string): boolean {\n  return extractPathParams(pattern, pathname) !== null;\n}\n\nfunction extractPathParams(pattern: string, pathname: string): FarmIntegrationRouteParams | null {\n  const routeSegments = splitPath(pattern);\n  const pathSegments = splitPath(pathname);\n  const params: FarmIntegrationRouteParams = {};\n\n  let routeIndex = 0;\n  let pathIndex = 0;\n\n  while (routeIndex < routeSegments.length && pathIndex < pathSegments.length) {\n    const routeSegment = routeSegments[routeIndex];\n    const pathSegment = pathSegments[pathIndex];\n\n    if (isCatchAllSegment(routeSegment)) {\n      params[getSegmentParamName(routeSegment)] = pathSegments\n        .slice(pathIndex)\n        .map((segment) => decodeRouteSegment(segment));\n      return params;\n    }\n\n    if (isDynamicSegment(routeSegment)) {\n      params[getSegmentParamName(routeSegment)] = decodeRouteSegment(pathSegment);\n      routeIndex += 1;\n      pathIndex += 1;\n      continue;\n    }\n\n    if (routeSegment !== pathSegment) {\n      return null;\n    }\n\n    routeIndex += 1;\n    pathIndex += 1;\n  }\n\n  if (routeIndex === routeSegments.length && pathIndex === pathSegments.length) {\n    return params;\n  }\n\n  if (routeIndex === routeSegments.length - 1 && isCatchAllSegment(routeSegments[routeIndex])) {\n    params[getSegmentParamName(routeSegments[routeIndex])] = [];\n    return params;\n  }\n\n  return null;\n}\n\nfunction splitPath(value: string): string[] {\n  return value.split(\"/\").filter(Boolean);\n}\n\nfunction isDynamicSegment(segment: string): boolean {\n  return segment.startsWith(\"[\") && segment.endsWith(\"]\");\n}\n\nfunction isCatchAllSegment(segment: string): boolean {\n  return segment.startsWith(\"[...\") && segment.endsWith(\"]\");\n}\n\nfunction getSegmentParamName(segment: string): string {\n  if (isCatchAllSegment(segment)) {\n    return segment.slice(4, -1);\n  }\n\n  return segment.slice(1, -1);\n}\n\nfunction getRequestId(req: FarmRequest): string {\n  const headerValue = req.headers[\"x-request-id\"];\n  if (Array.isArray(headerValue)) {\n    return headerValue[0] || String(Date.now());\n  }\n  return headerValue || String(Date.now());\n}\n\nfunction normalizeMatcher(matcher: string | readonly string[] | undefined): string {\n  if (!matcher) {\n    return \"/(.*)\";\n  }\n  return typeof matcher === \"string\" ? matcher : matcher.join(\", \");\n}\n","import type React from \"react\";\n\nexport type FarmMdxComponent = React.ComponentType<any> | keyof React.JSX.IntrinsicElements;\nexport type FarmMdxComponents = Record<string, FarmMdxComponent>;\n\nexport interface FarmMdxUserConfig {\n  /**\n   * Component map or module path that exports `components` or a default component map.\n   * Relative paths resolve from the project root.\n   */\n  components?: string | FarmMdxComponents;\n  /**\n   * Serve source-authored markdown pages at `/route.md`.\n   * Enabled by default for `page.md` and `page.mdx`.\n   */\n  markdownRoutes?: boolean;\n  /** Class name used for the wrapper around rendered markdown content. */\n  className?: string;\n}\n\nexport interface FarmMdxResolvedConfig {\n  components?: string | FarmMdxComponents;\n  markdownRoutes: boolean;\n  className: string;\n}\n\nexport function resolveMdxConfig(config: FarmMdxUserConfig | undefined): FarmMdxResolvedConfig {\n  return {\n    components: config?.components,\n    markdownRoutes: config?.markdownRoutes ?? true,\n    className: config?.className ?? \"farm-markdown\",\n  };\n}\n","export type FarmMarkdownRouteInput =\n  | string\n  | {\n      route: string;\n      title?: string;\n      cache?: number | false;\n    };\n\nexport interface FarmMarkdownUserConfig {\n  /**\n   * Enable generated markdown representations for React pages.\n   * @default true\n   */\n  enabled?: boolean;\n  /**\n   * Routes that may expose generated markdown. Every page is exposed by default.\n   */\n  expose?: boolean | FarmMarkdownRouteInput[];\n  /** @deprecated Use `expose`. */\n  routes?: FarmMarkdownRouteInput[];\n  cache?: number | false;\n  includeMetadata?: boolean;\n}\n\nexport interface FarmMarkdownResolvedRoute {\n  route: string;\n  title?: string;\n  cache?: number | false;\n}\n\nexport interface FarmMarkdownResolvedConfig {\n  enabled: boolean;\n  expose: true | FarmMarkdownResolvedRoute[];\n  cache: number | false;\n  includeMetadata: boolean;\n}\n\nexport interface FarmMarkdownMirrorTarget {\n  pathname: string;\n  route: FarmMarkdownResolvedRoute | null;\n}\n\nexport interface ResolveMarkdownMirrorTargetOptions {\n  accept?: string | null;\n}\n\nexport interface CreateMarkdownMirrorResponseOptions {\n  request: Request;\n  config?: FarmMarkdownResolvedConfig;\n  routeExists?: (pathname: string) => boolean;\n  renderPage: (request: Request) => Response | Promise<Response>;\n}\n\nexport interface ApplyMarkdownNegotiationHeadersOptions {\n  config?: FarmMarkdownResolvedConfig;\n  pathname: string;\n}\n\nexport function resolveMarkdownConfig(\n  config: FarmMarkdownUserConfig | boolean | undefined,\n): FarmMarkdownResolvedConfig {\n  if (config === false) {\n    return {\n      enabled: false,\n      expose: [],\n      cache: false,\n      includeMetadata: true,\n    };\n  }\n\n  if (config === true || config === undefined) {\n    return {\n      enabled: true,\n      expose: true,\n      cache: false,\n      includeMetadata: true,\n    };\n  }\n\n  const exposeInput = config.expose ?? config.routes ?? true;\n  const expose =\n    exposeInput === true\n      ? true\n      : Array.isArray(exposeInput)\n        ? exposeInput.map(normalizeMarkdownRouteInput)\n        : [];\n\n  return {\n    enabled: config.enabled !== false && (expose === true || expose.length > 0),\n    expose,\n    cache: config.cache ?? false,\n    includeMetadata: config.includeMetadata ?? true,\n  };\n}\n\nexport function resolveMarkdownMirrorTarget(\n  config: FarmMarkdownResolvedConfig | undefined,\n  pathname: string,\n  options: ResolveMarkdownMirrorTargetOptions = {},\n): FarmMarkdownMirrorTarget | null {\n  const hasMarkdownExtension = pathname.toLowerCase().endsWith(\".md\");\n  if (!config?.enabled || (!hasMarkdownExtension && !requestAcceptsMarkdown(options.accept))) {\n    return null;\n  }\n\n  const targetPathname = normalizeMarkdownRoute(\n    hasMarkdownExtension ? pathname.slice(0, -\".md\".length) || \"/\" : pathname,\n  );\n  const route = findExposedMarkdownRoute(config, targetPathname);\n  if (!route && config.expose !== true) {\n    return null;\n  }\n\n  return {\n    pathname: targetPathname,\n    route,\n  };\n}\n\nexport async function createMarkdownMirrorResponse(\n  options: CreateMarkdownMirrorResponseOptions,\n): Promise<Response | null> {\n  if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n    return null;\n  }\n\n  const requestUrl = new URL(options.request.url);\n  const hasMarkdownExtension = requestUrl.pathname.toLowerCase().endsWith(\".md\");\n  const target = resolveMarkdownMirrorTarget(options.config, requestUrl.pathname, {\n    accept: options.request.headers.get(\"accept\"),\n  });\n  if (!target) {\n    return null;\n  }\n\n  if (options.routeExists && !options.routeExists(target.pathname)) {\n    return null;\n  }\n\n  const pageUrl = new URL(options.request.url);\n  pageUrl.pathname = target.pathname;\n  const headers = new Headers(options.request.headers);\n  headers.set(\"accept\", \"text/html\");\n\n  const pageResponse = await options.renderPage(\n    new Request(pageUrl, {\n      method: \"GET\",\n      headers,\n    }),\n  );\n\n  if (!isHtmlResponse(pageResponse)) {\n    return null;\n  }\n\n  const html = await pageResponse.text();\n  const markdown = htmlToMarkdown(html, {\n    title: target.route?.title,\n    includeMetadata: options.config?.includeMetadata ?? true,\n    sourcePath: target.pathname,\n  });\n  const headersOut = new Headers({\n    \"Content-Type\": \"text/markdown; charset=utf-8\",\n    \"Content-Location\": target.pathname === \"/\" ? \"/index.md\" : `${target.pathname}.md`,\n    \"X-Farm-Markdown-Route\": target.pathname,\n  });\n  if (!hasMarkdownExtension) {\n    headersOut.set(\"Vary\", \"Accept\");\n  }\n  const cache = target.route?.cache ?? options.config?.cache ?? false;\n  headersOut.set(\"Cache-Control\", createMarkdownCacheHeader(cache));\n\n  return new Response(options.request.method === \"HEAD\" ? null : markdown, {\n    status: pageResponse.status,\n    headers: headersOut,\n  });\n}\n\nexport function applyMarkdownNegotiationHeaders(\n  response: Response,\n  options: ApplyMarkdownNegotiationHeadersOptions,\n): Response {\n  if (!isHtmlResponse(response)) {\n    return response;\n  }\n\n  const target = resolveMarkdownMirrorTarget(options.config, options.pathname, {\n    accept: \"text/markdown\",\n  });\n  if (!target) {\n    return response;\n  }\n\n  const alternatePath = getMarkdownAlternatePath(target.pathname);\n  const headers = new Headers(response.headers);\n  appendHeaderToken(headers, \"Vary\", \"Accept\");\n  headers.append(\"Link\", `<${alternatePath}>; rel=\"alternate\"; type=\"text/markdown\"`);\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function htmlToMarkdown(\n  html: string,\n  options: {\n    title?: string;\n    sourcePath?: string;\n    includeMetadata?: boolean;\n  } = {},\n): string {\n  const title = options.title ?? extractHtmlTitle(html);\n  let source = extractHtmlBody(html)\n    .replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\")\n    .replace(/<style\\b[^>]*>[\\s\\S]*?<\\/style>/gi, \"\")\n    .replace(/<noscript\\b[^>]*>[\\s\\S]*?<\\/noscript>/gi, \"\")\n    .replace(/<!--[\\s\\S]*?-->/g, \"\");\n\n  source = source.replace(/<pre\\b[^>]*><code\\b[^>]*>([\\s\\S]*?)<\\/code><\\/pre>/gi, (_, code) => {\n    return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n  });\n  source = source.replace(/<pre\\b[^>]*>([\\s\\S]*?)<\\/pre>/gi, (_, code) => {\n    return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n  });\n  source = source.replace(/<h([1-6])\\b[^>]*>([\\s\\S]*?)<\\/h\\1>/gi, (_, level, content) => {\n    return `\\n\\n${\"#\".repeat(Number(level))} ${toInlineMarkdown(content).trim()}\\n\\n`;\n  });\n  source = source.replace(/<p\\b[^>]*>([\\s\\S]*?)<\\/p>/gi, (_, content) => {\n    return `\\n\\n${toInlineMarkdown(content).trim()}\\n\\n`;\n  });\n  source = source.replace(/<blockquote\\b[^>]*>([\\s\\S]*?)<\\/blockquote>/gi, (_, content) => {\n    const quote = htmlToMarkdown(content, { includeMetadata: false })\n      .split(\"\\n\")\n      .filter((line) => line.trim().length > 0)\n      .map((line) => `> ${line}`)\n      .join(\"\\n\");\n    return `\\n\\n${quote}\\n\\n`;\n  });\n  source = source.replace(/<li\\b[^>]*>([\\s\\S]*?)<\\/li>/gi, (_, content) => {\n    return `\\n- ${toInlineMarkdown(content).trim()}`;\n  });\n  source = source\n    .replace(/<\\/?(ul|ol|main|section|article|header|footer|nav|aside|div)\\b[^>]*>/gi, \"\\n\")\n    .replace(/<br\\s*\\/?>/gi, \"\\n\")\n    .replace(/<hr\\s*\\/?>/gi, \"\\n\\n---\\n\\n\");\n\n  let markdown = stripTags(source)\n    .split(\"\\n\")\n    .map((line) => line.replace(/[ \\t]+$/g, \"\"))\n    .join(\"\\n\")\n    .replace(/\\n{3,}/g, \"\\n\\n\")\n    .trim();\n\n  if (options.includeMetadata !== false) {\n    const metadata: string[] = [];\n    if (title && !markdown.startsWith(\"# \")) {\n      metadata.push(`# ${title}`);\n    }\n    if (options.sourcePath) {\n      metadata.push(`Source: ${options.sourcePath}`);\n    }\n    if (metadata.length) {\n      markdown = `${metadata.join(\"\\n\\n\")}${markdown ? `\\n\\n${markdown}` : \"\"}`;\n    }\n  }\n\n  return `${markdown}\\n`;\n}\n\nfunction normalizeMarkdownRouteInput(input: FarmMarkdownRouteInput): FarmMarkdownResolvedRoute {\n  if (typeof input === \"string\") {\n    return {\n      route: normalizeMarkdownRoute(input),\n    };\n  }\n\n  return {\n    ...input,\n    route: normalizeMarkdownRoute(input.route),\n  };\n}\n\nfunction normalizeMarkdownRoute(route: string): string {\n  const withoutMarkdownExtension = route.toLowerCase().endsWith(\".md\") ? route.slice(0, -3) : route;\n  const withSlash = withoutMarkdownExtension.startsWith(\"/\")\n    ? withoutMarkdownExtension\n    : `/${withoutMarkdownExtension}`;\n  const normalized = withSlash.replace(/\\/+/g, \"/\").replace(/\\/$/g, \"\");\n  return normalized === \"\" || normalized === \"/index\" ? \"/\" : normalized;\n}\n\nexport function requestAcceptsMarkdown(accept: string | null | undefined): boolean {\n  if (!accept) {\n    return false;\n  }\n\n  return accept.split(\",\").some((entry) => {\n    const [mediaType, ...parameters] = entry\n      .trim()\n      .toLowerCase()\n      .split(\";\")\n      .map((part) => part.trim());\n    if (mediaType !== \"text/markdown\") {\n      return false;\n    }\n\n    const quality = parameters.find((parameter) => parameter.startsWith(\"q=\"));\n    return quality === undefined || Number(quality.slice(2)) > 0;\n  });\n}\n\nfunction getMarkdownAlternatePath(pathname: string): string {\n  return pathname === \"/\" ? \"/index.md\" : `${pathname}.md`;\n}\n\nfunction appendHeaderToken(headers: Headers, name: string, token: string): void {\n  const current = headers.get(name);\n  if (!current) {\n    headers.set(name, token);\n    return;\n  }\n\n  const tokens = current.split(\",\").map((value) => value.trim().toLowerCase());\n  if (!tokens.includes(token.toLowerCase())) {\n    headers.set(name, `${current}, ${token}`);\n  }\n}\n\nfunction findExposedMarkdownRoute(\n  config: FarmMarkdownResolvedConfig,\n  pathname: string,\n): FarmMarkdownResolvedRoute | null {\n  if (config.expose === true) {\n    return null;\n  }\n\n  return config.expose.find((route) => routeMatches(route.route, pathname)) ?? null;\n}\n\nfunction routeMatches(pattern: string, pathname: string): boolean {\n  if (pattern === pathname) {\n    return true;\n  }\n\n  const escaped = pattern\n    .split(\"/\")\n    .map((segment) => {\n      if (/^\\[\\.\\.\\.[^\\]]+\\]$/.test(segment)) {\n        return \".*\";\n      }\n      if (/^\\[[^\\]]+\\]$/.test(segment)) {\n        return \"[^/]+\";\n      }\n      return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n    })\n    .join(\"/\");\n\n  return new RegExp(`^${escaped}$`).test(pathname);\n}\n\nfunction isHtmlResponse(response: Response): boolean {\n  const contentType = response.headers.get(\"content-type\") ?? \"\";\n  return contentType.includes(\"text/html\");\n}\n\nfunction createMarkdownCacheHeader(cache: number | false): string {\n  if (cache === false || cache <= 0) {\n    return \"no-store\";\n  }\n\n  return `public, max-age=${cache}, s-maxage=${cache}`;\n}\n\nfunction extractHtmlTitle(html: string): string | undefined {\n  const match = html.match(/<title\\b[^>]*>([\\s\\S]*?)<\\/title>/i);\n  return match ? decodeHtml(stripTags(match[1])).trim() : undefined;\n}\n\nfunction extractHtmlBody(html: string): string {\n  const rootMatch = html.match(\n    /<div\\b[^>]*id=[\"']root[\"'][^>]*>([\\s\\S]*?)<\\/div>\\s*(?:<script|<\\/body>|$)/i,\n  );\n  const bodyMatch = html.match(/<body\\b[^>]*>([\\s\\S]*?)<\\/body>/i);\n  const body = rootMatch ? rootMatch[1] : bodyMatch ? bodyMatch[1] : html;\n  return extractFirstElementContent(body, [\"main\", \"article\"]) ?? body;\n}\n\nfunction extractFirstElementContent(html: string, tagNames: string[]): string | undefined {\n  for (const tagName of tagNames) {\n    const match = html.match(new RegExp(`<${tagName}\\\\b[^>]*>([\\\\s\\\\S]*?)<\\\\/${tagName}>`, \"i\"));\n    if (match) {\n      return match[1];\n    }\n  }\n\n  return undefined;\n}\n\nfunction toInlineMarkdown(html: string): string {\n  let source = html\n    .replace(/<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>([\\s\\S]*?)<\\/a>/gi, (_, href, text) => {\n      const label: string = toInlineMarkdown(text).trim() || href;\n      return `[${label}](${decodeHtml(href)})`;\n    })\n    .replace(\n      /<img\\b[^>]*src=[\"']([^\"']+)[\"'][^>]*alt=[\"']([^\"']*)[\"'][^>]*\\/?>/gi,\n      (_, src, alt) => {\n        return `![${decodeHtml(alt)}](${decodeHtml(src)})`;\n      },\n    )\n    .replace(/<strong\\b[^>]*>([\\s\\S]*?)<\\/strong>/gi, (_, content) => {\n      return `**${toInlineMarkdown(content).trim()}**`;\n    })\n    .replace(/<b\\b[^>]*>([\\s\\S]*?)<\\/b>/gi, (_, content) => {\n      return `**${toInlineMarkdown(content).trim()}**`;\n    })\n    .replace(/<em\\b[^>]*>([\\s\\S]*?)<\\/em>/gi, (_, content) => {\n      return `_${toInlineMarkdown(content).trim()}_`;\n    })\n    .replace(/<i\\b[^>]*>([\\s\\S]*?)<\\/i>/gi, (_, content) => {\n      return `_${toInlineMarkdown(content).trim()}_`;\n    })\n    .replace(/<code\\b[^>]*>([\\s\\S]*?)<\\/code>/gi, (_, content) => {\n      return `\\`${decodeHtml(stripTags(content)).trim()}\\``;\n    })\n    .replace(/<br\\s*\\/?>/gi, \"\\n\");\n\n  source = stripTags(source);\n  return decodeHtml(source).replace(/\\s+/g, \" \");\n}\n\nfunction stripTags(input: string): string {\n  return input.replace(/<[^>]+>/g, \"\");\n}\n\nfunction decodeHtml(input: string): string {\n  return input.replace(/&(?:nbsp|amp|lt|gt|quot|#39|#(?:x|X)[0-9a-fA-F]+|#[0-9]+);/g, (entity) => {\n    switch (entity) {\n      case \"&nbsp;\":\n        return \" \";\n      case \"&amp;\":\n        return \"&\";\n      case \"&lt;\":\n        return \"<\";\n      case \"&gt;\":\n        return \">\";\n      case \"&quot;\":\n        return '\"';\n      case \"&#39;\":\n        return \"'\";\n    }\n\n    const hexadecimal = entity[2] === \"x\" || entity[2] === \"X\";\n    const codePoint = Number.parseInt(entity.slice(hexadecimal ? 3 : 2, -1), hexadecimal ? 16 : 10);\n    return codePoint === 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)\n      ? \"\\uFFFD\"\n      : String.fromCodePoint(codePoint);\n  });\n}\n","/**\n * Environment access that works across the runtimes Farm targets.\n *\n * Serverless and edge runtimes (Cloudflare Workers in particular) expose\n * bindings on `globalThis.__env__` rather than `process.env`, so security\n * checks that read `process.env` directly see an empty value there and can\n * silently take an \"unconfigured\" code path in a deployed environment.\n */\nexport function getFarmRuntimeBindings(): Record<string, unknown> | undefined {\n  const runtimeBindings = (\n    globalThis as typeof globalThis & {\n      __env__?: Record<string, unknown>;\n    }\n  ).__env__;\n  return runtimeBindings && typeof runtimeBindings === \"object\" ? runtimeBindings : undefined;\n}\n\nexport function readFarmEnvironmentValue(name: string): string | undefined {\n  const runtimeValue = getFarmRuntimeBindings()?.[name];\n  if (typeof runtimeValue === \"string\") return runtimeValue;\n  return typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n}\n\n/**\n * True when the process looks like a deployed runtime rather than local\n * development: either NODE_ENV is production, or runtime bindings are present\n * (a deployed worker where NODE_ENV is frequently unset).\n */\nexport function isFarmDeployedRuntime(): boolean {\n  if (getFarmRuntimeBindings()) return true;\n  return readFarmEnvironmentValue(\"NODE_ENV\") === \"production\";\n}\n","import {\n  createFarmRequestBodyErrorResponse,\n  readFarmRequestBody,\n  resolveFarmServerConfig,\n  type FarmServerConfig,\n  type ResolvedFarmServerConfig,\n} from \"./server-http\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { isFarmDeployedRuntime, readFarmEnvironmentValue } from \"./utils/runtime-env\";\nimport { decodeRouteSegment } from \"./utils/decode\";\nimport { toPosixPath } from \"./utils\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  isAbsolute as isAbsolutePath,\n  normalize as normalizePath,\n  relative as relativeFilePath,\n  resolve as resolvePath,\n  sep as pathSeparator,\n} from \"node:path\";\n\nexport type FarmWorkflowSchedule = string | string[];\n\nexport interface FarmWorkflowsUserConfig {\n  /** Enable or disable Farm workflow discovery. Enabled by default. */\n  enabled?: boolean;\n  /** Directory or directories to scan for workflow modules. */\n  dir?: string | string[];\n  /** Alias for dir. */\n  dirs?: string[];\n  /** HTTP route used for manual and URL-based cron invocation. */\n  route?: string;\n  /** Environment variable that stores the optional runner secret. */\n  secretEnv?: string;\n  /** Inline runner secret. Prefer secretEnv for deployed apps. */\n  secret?: string;\n  /**\n   * Serve the workflow route without a secret in a deployed runtime.\n   * Defaults to false: without a secret the route is public, so production\n   * requests are rejected unless this is explicitly enabled.\n   */\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowsResolvedConfig {\n  enabled: boolean;\n  dirs: string[];\n  route: string;\n  secretEnv: string;\n  secret?: string;\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowLogger {\n  info: (...args: unknown[]) => void;\n  warn: (...args: unknown[]) => void;\n  error: (...args: unknown[]) => void;\n}\n\nexport interface FarmWorkflowRunContext<TPayload = unknown> {\n  id: string;\n  name: string;\n  payload: TPayload;\n  scheduledTime?: number | string;\n  request?: Request;\n  event?: unknown;\n  env: Record<string, string | undefined>;\n  data: Map<string, unknown>;\n  log: FarmWorkflowLogger;\n}\n\nexport interface FarmWorkflowDefinition<TPayload = unknown, TResult = unknown> {\n  kind?: \"farm-workflow\";\n  id?: string;\n  description?: string;\n  schedule?: FarmWorkflowSchedule;\n  timezone?: string;\n  run: (ctx: FarmWorkflowRunContext<TPayload>) => TResult | Promise<TResult>;\n}\n\nexport interface FarmCronDefinition<\n  TPayload = unknown,\n  TResult = unknown,\n> extends FarmWorkflowDefinition<TPayload, TResult> {\n  schedule: FarmWorkflowSchedule;\n}\n\nexport interface FarmDiscoveredWorkflow {\n  id: string;\n  filePath: string;\n  description?: string;\n  schedule: string[];\n  timezone?: string;\n  routePath: string;\n}\n\nexport interface PreparedFarmWorkflows {\n  workflows: FarmDiscoveredWorkflow[];\n  tasks: Record<string, { handler: string; description: string }>;\n  scheduledTasks: Record<string, string | string[]>;\n  handlerPath?: string;\n  manifestPath?: string;\n}\n\nexport interface FarmWorkflowHTTPHandlerOptions {\n  workflows: FarmDiscoveredWorkflow[];\n  config: FarmWorkflowsResolvedConfig;\n  loadModule: (workflow: FarmDiscoveredWorkflow) => Promise<Record<string, any>>;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}\n\nexport const DEFAULT_FARM_WORKFLOW_DIRS = [\"src/jobs\", \"src/workflows\", \"src/cron\"];\nexport const DEFAULT_FARM_WORKFLOW_ROUTE = \"/api/_farm/workflows\";\nexport const DEFAULT_FARM_WORKFLOW_SECRET_ENV = \"CRON_SECRET\";\nconst MISSING_FARM_WORKFLOW_SECRET_ERROR =\n  \"Workflow route requires a secret. Set the CRON_SECRET environment variable, configure workflows.secret, or set workflows.allowUnsecured to true.\";\n\nexport function defineWorkflow<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function defineTask<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return defineWorkflow(definition);\n}\n\n/**\n * @deprecated Configure `cron` in `farm.config.ts` and point it at an API route.\n */\nexport function defineCron<const TPayload = unknown, TResult = unknown>(\n  definition: FarmCronDefinition<TPayload, TResult>,\n): FarmCronDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function resolveWorkflowsConfig(\n  workflows: FarmWorkflowsUserConfig | boolean | undefined,\n): FarmWorkflowsResolvedConfig {\n  if (workflows === false) {\n    return {\n      enabled: false,\n      dirs: [...DEFAULT_FARM_WORKFLOW_DIRS],\n      route: DEFAULT_FARM_WORKFLOW_ROUTE,\n      secretEnv: DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    };\n  }\n\n  const options = workflows && typeof workflows === \"object\" ? workflows : {};\n  const dirs = normalizeWorkflowDirs(options);\n\n  return {\n    enabled: options.enabled ?? true,\n    dirs,\n    route: normalizeWorkflowRoute(options.route || DEFAULT_FARM_WORKFLOW_ROUTE),\n    secretEnv: options.secretEnv || DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    secret: options.secret,\n    allowUnsecured: options.allowUnsecured === true,\n  };\n}\n\nexport async function discoverFarmWorkflows(\n  config: {\n    root?: string;\n    workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  },\n  options: {\n    loadModule?: (filePath: string) => Promise<Record<string, any>>;\n  } = {},\n): Promise<FarmDiscoveredWorkflow[]> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  if (!workflowConfig.enabled) return [];\n\n  const root = config.root || process.cwd();\n  const files = await findWorkflowFiles(root, workflowConfig.dirs);\n  const workflows: FarmDiscoveredWorkflow[] = [];\n  const seenIds = new Map<string, string>();\n\n  for (const filePath of files) {\n    const module = options.loadModule\n      ? await options.loadModule(filePath)\n      : await loadWorkflowModule(filePath, root);\n    const definition = resolveWorkflowDefinition(module);\n    if (!definition) continue;\n\n    const id = normalizeWorkflowId(\n      definition.id || workflowIdFromFile(root, workflowConfig.dirs, filePath),\n    );\n    const previousPath = seenIds.get(id);\n    if (previousPath) {\n      throw new Error(\n        `Duplicate Farm workflow id \"${id}\" found in ${relativePath(root, previousPath)} and ${relativePath(root, filePath)}.`,\n      );\n    }\n    seenIds.set(id, filePath);\n\n    workflows.push({\n      id,\n      filePath,\n      description: definition.description,\n      schedule: normalizeSchedule(definition.schedule),\n      timezone: definition.timezone,\n      routePath: joinRoute(workflowConfig.route, encodeURIComponent(id)),\n    });\n  }\n\n  return workflows;\n}\n\nexport function createFarmWorkflowRequestHandler(options: FarmWorkflowHTTPHandlerOptions) {\n  const workflowsById = new Map(options.workflows.map((workflow) => [workflow.id, workflow]));\n\n  return async function handleFarmWorkflowRequest(request: Request): Promise<Response | null> {\n    const url = new URL(request.url);\n    const route = normalizeWorkflowRoute(options.config.route);\n    if (url.pathname !== route && !url.pathname.startsWith(`${route}/`)) {\n      return null;\n    }\n\n    if (url.pathname === route) {\n      const secretError = verifyWorkflowSecret(request, options.config);\n      if (secretError) return secretError;\n\n      return Response.json({\n        workflows: options.workflows.map(toWorkflowMetadata),\n      });\n    }\n\n    const id = decodeRouteSegment(url.pathname.slice(route.length + 1));\n    const workflow = workflowsById.get(id);\n    if (!workflow) {\n      return Response.json({ error: `Workflow \"${id}\" was not found.` }, { status: 404 });\n    }\n\n    const secretError = verifyWorkflowSecret(request, options.config);\n    if (secretError) return secretError;\n\n    let payload: unknown;\n    try {\n      payload = await readWorkflowPayload(\n        request,\n        resolveFarmServerConfig(options.server).bodySizeLimit,\n      );\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) {\n        return Response.json({ error: \"Invalid workflow request body.\" }, { status: 400 });\n      }\n      throw error;\n    }\n    const module = await options.loadModule(workflow);\n    const result = await runFarmWorkflowModule(module, {\n      id: workflow.id,\n      name: workflow.id,\n      payload,\n      request,\n      scheduledTime: readScheduledTime(payload),\n    });\n\n    return Response.json({\n      id: workflow.id,\n      ok: true,\n      result: result ?? null,\n    });\n  };\n}\n\nexport async function runFarmWorkflowModule(\n  module: Record<string, any>,\n  context: {\n    id: string;\n    name?: string;\n    payload?: unknown;\n    scheduledTime?: number | string;\n    request?: Request;\n    event?: unknown;\n    env?: Record<string, string | undefined>;\n  },\n): Promise<unknown> {\n  const definition = resolveWorkflowDefinition(module);\n  if (!definition) {\n    throw new Error(`Farm workflow \"${context.id}\" does not export a workflow definition.`);\n  }\n\n  return await definition.run({\n    id: context.id,\n    name: context.name || context.id,\n    payload: context.payload,\n    scheduledTime: context.scheduledTime,\n    request: context.request,\n    event: context.event,\n    env: context.env || process.env,\n    data: new Map<string, unknown>(),\n    log: console,\n  });\n}\n\nexport async function prepareFarmWorkflowsForNitro(config: {\n  root?: string;\n  distDir?: string;\n  workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}): Promise<PreparedFarmWorkflows> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  const root = config.root || process.cwd();\n  const distDir = config.distDir || \".farm\";\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const generatedDir = path.join(root, distDir, \".nitro\", \"farm-workflows\");\n  const workflows = await discoverFarmWorkflows({\n    root,\n    workflows: workflowConfig,\n  });\n\n  if (workflows.length === 0) {\n    await fs.rm(generatedDir, { recursive: true, force: true });\n    return {\n      workflows,\n      tasks: {},\n      scheduledTasks: {},\n    };\n  }\n\n  await fs.rm(generatedDir, { recursive: true, force: true });\n  await fs.mkdir(generatedDir, { recursive: true });\n\n  const tasks: PreparedFarmWorkflows[\"tasks\"] = {};\n  const scheduledTasks = createScheduledTasks(workflows);\n\n  const wrapperNames = resolveWorkflowWrapperFileNames(workflows.map((workflow) => workflow.id));\n  for (const workflow of workflows) {\n    const wrapperPath = toPosixPath(\n      path.join(generatedDir, `${wrapperNames.get(workflow.id)}.mjs`),\n    );\n    await fs.writeFile(wrapperPath, createNitroTaskWrapper(workflow), \"utf8\");\n    tasks[workflow.id] = {\n      handler: wrapperPath,\n      description: workflow.description || `Farm workflow ${workflow.id}`,\n    };\n  }\n\n  const handlerPath = toPosixPath(path.join(generatedDir, \"http-handler.mjs\"));\n  await fs.writeFile(\n    handlerPath,\n    createNitroWorkflowHTTPHandler(\n      workflowConfig,\n      workflows,\n      resolveFarmServerConfig(config.server),\n    ),\n    \"utf8\",\n  );\n\n  const manifestPath = path.join(generatedDir, \"manifest.json\");\n  await fs.writeFile(\n    manifestPath,\n    JSON.stringify(\n      {\n        route: workflowConfig.route,\n        secretEnv: workflowConfig.secretEnv,\n        trigger: {\n          method: \"GET\",\n          authorization: `Bearer $${workflowConfig.secretEnv}`,\n        },\n        workflows: workflows.map(toWorkflowMetadata),\n      },\n      null,\n      2,\n    ),\n    \"utf8\",\n  );\n\n  return {\n    workflows,\n    tasks,\n    scheduledTasks,\n    handlerPath,\n    manifestPath,\n  };\n}\n\nexport function createFarmWorkflowVercelCrons(\n  workflows: FarmDiscoveredWorkflow[],\n): Array<{ path: string; schedule: string }> {\n  return workflows.flatMap((workflow) =>\n    workflow.schedule.map((schedule) => ({\n      path: workflow.routePath,\n      schedule,\n    })),\n  );\n}\n\nexport function applyFarmWorkflowVercelCrons(\n  vercelConfig: Record<string, any>,\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, any> {\n  const crons = createFarmWorkflowVercelCrons(workflows);\n  if (crons.length === 0) return vercelConfig;\n\n  const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n  const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n  const nextCrons = [...existingCrons];\n  for (const cron of crons) {\n    const key = `${cron.path}:${cron.schedule}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    nextCrons.push(cron);\n  }\n  return {\n    ...vercelConfig,\n    crons: nextCrons,\n  };\n}\n\nfunction isResolvedWorkflowConfig(value: unknown): value is FarmWorkflowsResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"dirs\" in value &&\n    Array.isArray((value as FarmWorkflowsResolvedConfig).dirs) &&\n    typeof (value as FarmWorkflowsResolvedConfig).route === \"string\"\n  );\n}\n\nfunction normalizeWorkflowDirs(options: FarmWorkflowsUserConfig): string[] {\n  const rawDirs =\n    options.dirs ||\n    (Array.isArray(options.dir) ? options.dir : options.dir ? [options.dir] : undefined);\n  const dirs = rawDirs && rawDirs.length > 0 ? rawDirs : DEFAULT_FARM_WORKFLOW_DIRS;\n  return [...new Set(dirs.map(normalizeWorkflowDir).filter(Boolean))];\n}\n\nfunction normalizeWorkflowDir(value: string): string {\n  const dir = value.trim();\n  if (!dir) return \"\";\n  return isAbsolutePath(dir) ? normalizePath(dir) : trimSlashes(dir);\n}\n\nfunction normalizeWorkflowRoute(route: string): string {\n  const trimmed = route.trim();\n  if (!trimmed || trimmed === \"/\") return DEFAULT_FARM_WORKFLOW_ROUTE;\n  const normalized = `/${trimSlashes(trimmed)}`;\n  validateConfigRouteSource(normalized, \"workflows.route\");\n  return normalized;\n}\n\nfunction normalizeWorkflowId(id: string): string {\n  const normalized = id\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\")\n    .replace(/\\/index$/, \"\")\n    .replace(/[^a-zA-Z0-9._/-]+/g, \"-\")\n    .replace(/^\\/+|\\/+$/g, \"\")\n    .replace(/\\/+/g, \"/\");\n  return normalized || \"workflow\";\n}\n\nfunction normalizeSchedule(schedule: FarmWorkflowSchedule | undefined): string[] {\n  if (!schedule) return [];\n  return (Array.isArray(schedule) ? schedule : [schedule])\n    .map((value) => value.trim())\n    .filter(Boolean);\n}\n\nfunction resolveWorkflowDefinition(\n  module: Record<string, any>,\n): FarmWorkflowDefinition | FarmCronDefinition | null {\n  const candidates = [module.default, module.workflow, module.cron, module.task, module.job];\n  for (const candidate of candidates) {\n    if (candidate && typeof candidate === \"object\" && typeof candidate.run === \"function\") {\n      return candidate as FarmWorkflowDefinition;\n    }\n  }\n  return null;\n}\n\nasync function findWorkflowFiles(root: string, dirs: string[]): Promise<string[]> {\n  const path = await import(\"path\");\n  const files: string[] = [];\n\n  for (const dir of dirs) {\n    const absoluteDir = path.isAbsolute(dir) ? dir : path.join(root, dir);\n    if (!(await pathExists(absoluteDir))) continue;\n    await walkWorkflowDir(absoluteDir, files);\n  }\n\n  return files.sort();\n}\n\nasync function walkWorkflowDir(dir: string, files: string[]): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const entries = await fs.readdir(dir, { withFileTypes: true });\n  for (const entry of entries) {\n    const filePath = path.join(dir, entry.name);\n    if (entry.isDirectory()) {\n      if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n      await walkWorkflowDir(filePath, files);\n      continue;\n    }\n    if (isWorkflowFile(entry.name)) {\n      files.push(filePath);\n    }\n  }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n  const fs = await import(\"fs/promises\");\n  return fs\n    .access(filePath)\n    .then(() => true)\n    .catch(() => false);\n}\n\nfunction isWorkflowFile(fileName: string): boolean {\n  return /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(fileName) && !/\\.d\\.[cm]?ts$/.test(fileName);\n}\n\nasync function loadWorkflowModule(filePath: string, root: string): Promise<Record<string, any>> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const { pathToFileURL } = await import(\"url\");\n  const { build } = await import(\"esbuild\");\n  const outDir = path.join(root, \".farm\", \".workflow-loader\");\n  await fs.mkdir(outDir, { recursive: true });\n  const outfile = path.join(\n    outDir,\n    `workflow-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n  );\n\n  await build({\n    absWorkingDir: root,\n    entryPoints: [filePath],\n    outfile,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: `node${process.versions.node.split(\".\")[0]}`,\n    packages: \"external\",\n    external: [\"@farm.js/core\", \"@farm.js/core/*\", \"nitro\", \"nitro/*\"],\n    jsx: \"automatic\",\n    logLevel: \"silent\",\n    sourcemap: \"inline\",\n  });\n\n  try {\n    return await import(/* @vite-ignore */ `${pathToFileURL(outfile).href}?t=${Date.now()}`);\n  } finally {\n    await fs.unlink(outfile).catch(() => undefined);\n  }\n}\n\nfunction workflowIdFromFile(root: string, dirs: string[], filePath: string): string {\n  for (const dir of dirs) {\n    const scanRoot = isAbsolutePath(dir) ? dir : resolvePath(root, dir);\n    const candidate = relativeFilePath(scanRoot, filePath);\n    if (candidate && candidate !== \"..\" && !candidate.startsWith(`..${pathSeparator}`)) {\n      return normalizeWorkflowId(candidate);\n    }\n  }\n\n  return normalizeWorkflowId(relativeFilePath(root, filePath));\n}\n\nfunction createScheduledTasks(\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, string | string[]> {\n  const scheduleMap = new Map<string, string[]>();\n  for (const workflow of workflows) {\n    for (const schedule of workflow.schedule) {\n      const taskIds = scheduleMap.get(schedule) || [];\n      taskIds.push(workflow.id);\n      scheduleMap.set(schedule, taskIds);\n    }\n  }\n\n  return Object.fromEntries(\n    [...scheduleMap.entries()].map(([schedule, taskIds]) => [\n      schedule,\n      taskIds.length === 1 ? taskIds[0] : taskIds,\n    ]),\n  );\n}\n\nfunction createNitroTaskWrapper(workflow: FarmDiscoveredWorkflow): string {\n  const normalizedPath = workflow.filePath.replace(/\\\\/g, \"/\");\n  return `\nimport { defineTask } from \"nitro/runtime\";\nimport { runFarmWorkflowModule } from \"@farm.js/core/workflows\";\nimport * as workflowModule from ${JSON.stringify(normalizedPath)};\n\nexport default defineTask({\n  meta: {\n    description: ${JSON.stringify(workflow.description || `Farm workflow ${workflow.id}`)}\n  },\n  async run(event) {\n    const payload = event?.payload || {};\n    const env = event?.context?.cloudflare?.env || event?.context?.env || process.env;\n    return await runFarmWorkflowModule(workflowModule, {\n      id: ${JSON.stringify(workflow.id)},\n      name: event?.name || ${JSON.stringify(workflow.id)},\n      payload,\n      scheduledTime: payload.scheduledTime,\n      request: event?.context?.request,\n      event,\n      env\n    });\n  }\n});\n`.trim();\n}\n\nfunction createNitroWorkflowHTTPHandler(\n  config: FarmWorkflowsResolvedConfig,\n  workflows: FarmDiscoveredWorkflow[],\n  server: ResolvedFarmServerConfig,\n): string {\n  return `\nimport { H3 } from \"h3\";\nimport { runTask } from \"nitro/runtime\";\nimport {\n  createFarmRequestBodyErrorResponse,\n  readFarmRequestBody,\n  searchParamsToObject\n} from \"@farm.js/core/internal/production-runtime\";\n\nconst route = ${JSON.stringify(config.route)};\nconst secretEnv = ${JSON.stringify(config.secretEnv)};\nconst inlineSecret = ${JSON.stringify(config.secret || \"\")};\nconst allowUnsecured = ${JSON.stringify(config.allowUnsecured === true)};\nconst bodySizeLimit = ${JSON.stringify(server.bodySizeLimit)};\nconst workflows = ${JSON.stringify(workflows.map(toWorkflowMetadata))};\nconst workflowIds = new Set(workflows.map((workflow) => workflow.id));\n\nfunction json(value, status = 200) {\n  return new Response(JSON.stringify(value), {\n    status,\n    headers: { \"content-type\": \"application/json\" }\n  });\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction getHeader(event, name) {\n  return event.req.headers.get(name);\n}\n\nfunction getSecret() {\n  return inlineSecret || process.env[secretEnv] || \"\";\n}\n\nfunction verifySecret(event) {\n  const secret = getSecret();\n  if (!secret) {\n    if (allowUnsecured) return null;\n    return json({ error: ${JSON.stringify(MISSING_FARM_WORKFLOW_SECRET_ERROR)} }, 401);\n  }\n  const authorization = getHeader(event, \"authorization\") || \"\";\n  const headerSecret = getHeader(event, \"x-farm-workflow-secret\") || \"\";\n  const bearer = authorization.match(/^Bearer\\\\s+(.+)$/i)?.[1] || \"\";\n  if (headerSecret === secret || bearer === secret) return null;\n  return json({ error: \"Unauthorized workflow request.\" }, 401);\n}\n\nasync function readPayload(event) {\n  if (event.req.method === \"GET\" || event.req.method === \"HEAD\") {\n    return searchParamsToObject(event.url.searchParams);\n  }\n  const bytes = await readFarmRequestBody(event.req, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (getHeader(event, \"content-type\") || \"\").split(\";\", 1)[0].trim().toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n  return { text };\n}\n\nexport default new H3()\n  .get(route, (event) => {\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n    return { workflows };\n  })\n  .all(route + \"/:id\", async (event) => {\n    const id = decodeRouteSegment(event.context.params?.id || \"\");\n    if (!workflowIds.has(id)) {\n      return json({ error: \"Workflow \" + id + \" was not found.\" }, 404);\n    }\n\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n\n    let payload;\n    try {\n      payload = await readPayload(event);\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) return json({ error: \"Invalid workflow request body.\" }, 400);\n      throw error;\n    }\n    const result = await runTask(id, {\n      payload,\n      context: {\n        source: \"http\",\n        request: event.req,\n        route,\n        url: event.url.href,\n        method: event.req.method\n      }\n    });\n    return {\n      id,\n      ok: true,\n      result: result ?? null\n    };\n  });\n`.trim();\n}\n\nfunction toWorkflowMetadata(workflow: FarmDiscoveredWorkflow) {\n  return {\n    id: workflow.id,\n    description: workflow.description || null,\n    schedule: workflow.schedule,\n    timezone: workflow.timezone || null,\n    path: workflow.routePath,\n  };\n}\n\nasync function readWorkflowPayload(request: Request, bodySizeLimit: number): Promise<unknown> {\n  const url = new URL(request.url);\n  if (request.method === \"GET\" || request.method === \"HEAD\") {\n    return searchParamsToObject(url.searchParams);\n  }\n\n  const bytes = await readFarmRequestBody(request, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (request.headers.get(\"content-type\") || \"\")\n    .split(\";\", 1)[0]\n    .trim()\n    .toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n\n  return { text };\n}\n\nfunction readScheduledTime(payload: unknown): number | string | undefined {\n  return payload && typeof payload === \"object\" && \"scheduledTime\" in payload\n    ? (payload as { scheduledTime?: number | string }).scheduledTime\n    : undefined;\n}\n\nfunction verifyWorkflowSecret(\n  request: Request,\n  config: FarmWorkflowsResolvedConfig,\n): Response | null {\n  const secret = config.secret || readFarmEnvironmentValue(config.secretEnv) || \"\";\n  if (!secret) {\n    // No secret configured. Local development stays convenient, but a deployed\n    // runtime must not expose a route that lists and executes workflows to\n    // anonymous callers. Opt back in explicitly with .\n    if (config.allowUnsecured === true || !isFarmDeployedRuntime()) return null;\n    return Response.json(\n      {\n        error: MISSING_FARM_WORKFLOW_SECRET_ERROR,\n      },\n      { status: 401 },\n    );\n  }\n\n  const authorization = request.headers.get(\"authorization\") || \"\";\n  const bearer = authorization.match(/^Bearer\\s+(.+)$/i)?.[1] || \"\";\n  const headerSecret = request.headers.get(\"x-farm-workflow-secret\") || \"\";\n  if (bearer === secret || headerSecret === secret) return null;\n\n  return Response.json({ error: \"Unauthorized workflow request.\" }, { status: 401 });\n}\n\nfunction joinRoute(...parts: string[]): string {\n  return `/${parts\n    .map((part) => trimSlashes(part))\n    .filter(Boolean)\n    .join(\"/\")}`;\n}\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\n/**\n * Wrapper file names for a set of workflow ids.\n *\n * `safeFileName` is not injective: it maps `a/b` and `a-b` onto the same string,\n * and macOS and Windows additionally fold `Daily` onto `daily` on their default\n * case-insensitive filesystems. Two workflows would then share one generated\n * wrapper and both run whichever was written last. Only ids that actually\n * collide are disambiguated, so ordinary ids keep a readable wrapper; every id\n * in a colliding group gets a digest of the exact id appended, which keeps the\n * result independent of discovery order.\n */\nfunction resolveWorkflowWrapperFileNames(ids: readonly string[]): Map<string, string> {\n  const groups = new Map<string, number>();\n  for (const id of ids) {\n    const key = safeFileName(id).toLowerCase();\n    groups.set(key, (groups.get(key) ?? 0) + 1);\n  }\n\n  const resolved = new Map<string, string>();\n  const claimed = new Map<string, string>();\n  for (const id of ids) {\n    const base = safeFileName(id);\n    const key = base.toLowerCase();\n    const fileName = (groups.get(key) ?? 0) > 1 ? `${key}-${workflowIdFingerprint(id)}` : base;\n    const claimedBy = claimed.get(fileName.toLowerCase());\n    if (claimedBy !== undefined) {\n      throw new Error(\n        `Farm workflows ${JSON.stringify(claimedBy)} and ${JSON.stringify(id)} generate the same wrapper file ${JSON.stringify(`${fileName}.mjs`)}. Rename one of them.`,\n      );\n    }\n    claimed.set(fileName.toLowerCase(), id);\n    resolved.set(id, fileName);\n  }\n  return resolved;\n}\n\n/**\n * FNV-1a. This module is bundled into server runtimes that do not provide\n * node:crypto, and the digest only needs to separate file names.\n */\nfunction workflowIdFingerprint(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index += 1) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction safeFileName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"workflow\";\n}\n\nfunction relativePath(root: string, filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\").replace(`${root.replace(/\\\\/g, \"/\")}/`, \"\");\n}\n","import { toPosixPath } from \"./utils\";\nimport {\n  getFarmRuntimeBindings,\n  readFarmEnvironmentValue as readEnvironmentValue,\n} from \"./utils/runtime-env\";\n\nexport type FarmCronSchedule = string | string[];\n\nexport interface FarmCronJobConfig {\n  /** Portable five-field cron expression, or a list of expressions. */\n  schedule: FarmCronSchedule;\n  /** Farm API route invoked with GET when the schedule fires. */\n  path: string;\n  /** Human-readable purpose shown by local tooling and deployment manifests. */\n  description?: string;\n  /** Disable this schedule without removing its configuration. */\n  enabled?: boolean;\n}\n\nexport type FarmCronUserConfig = Record<string, FarmCronJobConfig>;\n\nexport interface FarmCronJob {\n  name: string;\n  schedule: string[];\n  path: string;\n  description?: string;\n}\n\nexport interface FarmCronResolvedConfig {\n  enabled: boolean;\n  secretEnv: typeof DEFAULT_FARM_CRON_SECRET_ENV;\n  jobs: FarmCronJob[];\n}\n\nexport interface PreparedFarmCron {\n  jobs: FarmCronJob[];\n  tasks: Record<string, { handler: string; description: string }>;\n  scheduledTasks: Record<string, string | string[]>;\n  manifestPath?: string;\n}\n\nexport interface FarmCronRouteOptions {\n  /** Environment variable containing the bearer token. */\n  secretEnv?: string;\n  /** Inline token, primarily useful in tests. Environment variables are preferred. */\n  secret?: string;\n  /** Allow a production route without a secret. Defaults to false. */\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmCronCloudflareConfig {\n  deployConfig: true;\n  wrangler: {\n    triggers: {\n      crons: string[];\n    };\n  };\n}\n\nexport const DEFAULT_FARM_CRON_SECRET_ENV = \"CRON_SECRET\";\nexport const FARM_CRON_MANIFEST = \"cron-manifest.json\";\n\nconst CRON_FIELD_RANGES = [\n  [0, 59, \"minute\"],\n  [0, 23, \"hour\"],\n  [1, 31, \"day of month\"],\n  [1, 12, \"month\"],\n  [0, 6, \"day of week\"],\n] as const;\n\nexport function resolveCronConfig(\n  cron: FarmCronResolvedConfig | FarmCronUserConfig | false | undefined,\n): FarmCronResolvedConfig {\n  if (isResolvedCronConfig(cron)) return cron;\n  if (!cron) {\n    return {\n      enabled: false,\n      secretEnv: DEFAULT_FARM_CRON_SECRET_ENV,\n      jobs: [],\n    };\n  }\n\n  const jobs: FarmCronJob[] = [];\n  for (const [name, job] of Object.entries(cron)) {\n    if (!job || typeof job !== \"object\" || Array.isArray(job)) {\n      throw new TypeError(`Farm cron ${JSON.stringify(name)} must be a configuration object.`);\n    }\n    if (job.enabled === false) continue;\n    jobs.push(normalizeCronJob(name, job));\n  }\n\n  return {\n    enabled: jobs.length > 0,\n    secretEnv: DEFAULT_FARM_CRON_SECRET_ENV,\n    jobs,\n  };\n}\n\nexport async function prepareFarmCronForNitro(config: {\n  root?: string;\n  distDir?: string;\n  cron?: FarmCronResolvedConfig | FarmCronUserConfig | false;\n}): Promise<PreparedFarmCron> {\n  const cron = isResolvedCronConfig(config.cron) ? config.cron : resolveCronConfig(config.cron);\n  const root = config.root || process.cwd();\n  const distDir = config.distDir || \".farm\";\n  const fs = await import(\"node:fs/promises\");\n  const path = await import(\"node:path\");\n  const manifestPath = path.join(root, distDir, FARM_CRON_MANIFEST);\n  const generatedDir = path.join(root, distDir, \".nitro\", \"farm-cron\");\n\n  if (!cron.enabled) {\n    await Promise.all([\n      fs.rm(manifestPath, { force: true }),\n      fs.rm(generatedDir, { recursive: true, force: true }),\n    ]);\n    return {\n      jobs: [],\n      tasks: {},\n      scheduledTasks: {},\n    };\n  }\n\n  await fs.rm(generatedDir, { recursive: true, force: true });\n  await fs.mkdir(generatedDir, { recursive: true });\n\n  const tasks: PreparedFarmCron[\"tasks\"] = {};\n  const wrapperNames = resolveCronWrapperFileNames(cron.jobs.map((job) => job.name));\n  for (const job of cron.jobs) {\n    const taskName = getFarmCronTaskName(job.name);\n    const wrapperPath = toPosixPath(path.join(generatedDir, `${wrapperNames.get(job.name)}.mjs`));\n    await fs.writeFile(wrapperPath, createNitroCronTaskWrapper(job, cron.secretEnv), \"utf8\");\n    tasks[taskName] = {\n      handler: wrapperPath,\n      description: job.description || `Farm cron ${job.name}`,\n    };\n  }\n\n  const manifest = createFarmCronManifest(cron);\n  await fs.mkdir(path.dirname(manifestPath), { recursive: true });\n  await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\n\n  return {\n    jobs: cron.jobs,\n    tasks,\n    scheduledTasks: createCronScheduledTasks(cron.jobs),\n    manifestPath,\n  };\n}\n\nexport function createFarmCronManifest(cron: FarmCronResolvedConfig) {\n  return {\n    schemaVersion: 1,\n    secretEnv: cron.secretEnv,\n    jobs: cron.jobs.map((job) => ({\n      name: job.name,\n      schedule: job.schedule,\n      path: job.path,\n      description: job.description || null,\n    })),\n  };\n}\n\nexport function createFarmCronVercelCrons(\n  jobs: FarmCronJob[],\n): Array<{ path: string; schedule: string }> {\n  return jobs.flatMap((job) =>\n    job.schedule.map((schedule) => ({\n      path: job.path,\n      schedule,\n    })),\n  );\n}\n\nexport function applyFarmCronVercelCrons(\n  vercelConfig: Record<string, any>,\n  jobs: FarmCronJob[],\n): Record<string, any> {\n  const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n  const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n  const crons = [...existingCrons];\n\n  for (const cron of createFarmCronVercelCrons(jobs)) {\n    const key = `${cron.path}:${cron.schedule}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    crons.push(cron);\n  }\n\n  return crons.length > 0 ? { ...vercelConfig, crons } : vercelConfig;\n}\n\nexport function createFarmCronCloudflareTriggers(jobs: FarmCronJob[]): string[] {\n  return [...new Set(jobs.flatMap((job) => job.schedule))];\n}\n\nexport function createFarmCronCloudflareConfig(\n  jobs: FarmCronJob[],\n): FarmCronCloudflareConfig | undefined {\n  const crons = createFarmCronCloudflareTriggers(jobs);\n  if (crons.length === 0) return undefined;\n\n  return {\n    deployConfig: true,\n    wrangler: {\n      triggers: { crons },\n    },\n  };\n}\n\nexport function mergeScheduledTasks(\n  ...maps: Array<Record<string, string | string[]> | undefined>\n): Record<string, string | string[]> {\n  const merged = new Map<string, string[]>();\n\n  for (const map of maps) {\n    for (const [schedule, taskNames] of Object.entries(map || {})) {\n      const current = merged.get(schedule) || [];\n      for (const taskName of Array.isArray(taskNames) ? taskNames : [taskNames]) {\n        if (!current.includes(taskName)) current.push(taskName);\n      }\n      merged.set(schedule, current);\n    }\n  }\n\n  return Object.fromEntries(\n    [...merged].map(([schedule, taskNames]) => [\n      schedule,\n      taskNames.length === 1 ? taskNames[0] : taskNames,\n    ]),\n  );\n}\n\nexport function isCronRequestAuthorized(\n  request: Request,\n  options: FarmCronRouteOptions = {},\n): boolean {\n  const secretEnv = options.secretEnv || DEFAULT_FARM_CRON_SECRET_ENV;\n  const secret = options.secret || readEnvironmentValue(secretEnv);\n  if (!secret) {\n    return (\n      options.allowUnsecured === true ||\n      (!getFarmRuntimeBindings() && readEnvironmentValue(\"NODE_ENV\") !== \"production\")\n    );\n  }\n\n  const authorization = request.headers.get(\"authorization\") || \"\";\n  const bearer = /^Bearer (.*)$/i.exec(authorization)?.[1] || \"\";\n  return bearer === secret || request.headers.get(\"x-farm-cron-secret\") === secret;\n}\n\nexport function cronRoute<TArgs extends unknown[], TResult>(\n  handler: (request: Request, ...args: TArgs) => TResult,\n  options: FarmCronRouteOptions = {},\n): (request: Request, ...args: TArgs) => TResult | Promise<Response> {\n  return (request, ...args) => {\n    if (!isCronRequestAuthorized(request, options)) {\n      return Promise.resolve(\n        Response.json({ error: \"Unauthorized cron request.\" }, { status: 401 }),\n      );\n    }\n    return handler(request, ...args);\n  };\n}\n\nfunction normalizeCronJob(name: string, job: FarmCronJobConfig): FarmCronJob {\n  if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)) {\n    throw new TypeError(\n      `Farm cron name ${JSON.stringify(name)} must start with a letter or number and contain only letters, numbers, dots, underscores, or hyphens.`,\n    );\n  }\n  if (!job || typeof job !== \"object\" || Array.isArray(job)) {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} must be a configuration object.`);\n  }\n\n  const path = normalizeCronPath(name, job.path);\n  const rawSchedule = Array.isArray(job.schedule) ? job.schedule : [job.schedule];\n  const schedule = [...new Set(rawSchedule.map((value) => normalizeCronExpression(name, value)))];\n  if (schedule.length === 0) {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} must define at least one schedule.`);\n  }\n\n  return {\n    name,\n    schedule,\n    path,\n    description: job.description?.trim() || undefined,\n  };\n}\n\nfunction normalizeCronPath(name: string, value: unknown): string {\n  if (typeof value !== \"string\" || !value.trim().startsWith(\"/\")) {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} path must start with \"/\".`);\n  }\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n  if (hasUnstableCharacters(value)) {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} path cannot contain backslashes or control characters.`,\n    );\n  }\n\n  const path = value.trim();\n  if (path.startsWith(\"//\") || path.includes(\"?\") || path.includes(\"#\")) {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} path must be an application pathname without a host, query, or hash.`,\n    );\n  }\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal and cannot conceal a separator or dot segment.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new TypeError(\n        `Farm cron ${JSON.stringify(name)} path cannot contain backslashes or control characters.`,\n      );\n    }\n    if (decoded.includes(\"/\")) {\n      throw new TypeError(\n        `Farm cron ${JSON.stringify(name)} path cannot contain percent-encoded path separators.`,\n      );\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new TypeError(\n        `Farm cron ${JSON.stringify(name)} path cannot contain \".\" or \"..\" path segments.`,\n      );\n    }\n  }\n  return path.length > 1 ? path.replace(/\\/+$/, \"\") : path;\n}\n\nfunction normalizeCronExpression(name: string, value: unknown): string {\n  if (typeof value !== \"string\") {\n    throw new TypeError(`Farm cron ${JSON.stringify(name)} schedule must be a string.`);\n  }\n\n  const expression = value.trim().replace(/\\s+/g, \" \");\n  const fields = expression.split(\" \");\n  if (fields.length !== CRON_FIELD_RANGES.length) {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} must use five fields: minute hour day-of-month month day-of-week.`,\n    );\n  }\n\n  fields.forEach((field, index) => {\n    const [minimum, maximum, label] = CRON_FIELD_RANGES[index];\n    validateCronField(name, expression, field, minimum, maximum, label);\n  });\n  if (fields[2] !== \"*\" && fields[4] !== \"*\") {\n    throw new TypeError(\n      `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} cannot constrain both day-of-month and day-of-week.`,\n    );\n  }\n  return expression;\n}\n\nfunction validateCronField(\n  name: string,\n  expression: string,\n  field: string,\n  minimum: number,\n  maximum: number,\n  label: string,\n): void {\n  for (const segment of field.split(\",\")) {\n    const [range, stepText, ...extra] = segment.split(\"/\");\n    if (!range || extra.length > 0 || (stepText !== undefined && !isIntegerInRange(stepText, 1))) {\n      throwInvalidCronField(name, expression, label);\n    }\n\n    if (range === \"*\") continue;\n    const bounds = range.split(\"-\");\n    if (bounds.length > 2 || !bounds.every((value) => isIntegerInRange(value, minimum, maximum))) {\n      throwInvalidCronField(name, expression, label);\n    }\n    if (bounds.length === 2 && Number(bounds[0]) > Number(bounds[1])) {\n      throwInvalidCronField(name, expression, label);\n    }\n  }\n}\n\nfunction isIntegerInRange(value: string, minimum: number, maximum = Number.MAX_SAFE_INTEGER) {\n  if (!/^\\d+$/.test(value)) return false;\n  const parsed = Number(value);\n  return parsed >= minimum && parsed <= maximum;\n}\n\nfunction throwInvalidCronField(name: string, expression: string, label: string): never {\n  throw new TypeError(\n    `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} has an invalid ${label} field.`,\n  );\n}\n\nfunction isResolvedCronConfig(value: unknown): value is FarmCronResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    typeof (value as FarmCronResolvedConfig).enabled === \"boolean\" &&\n    \"jobs\" in value &&\n    Array.isArray((value as FarmCronResolvedConfig).jobs) &&\n    \"secretEnv\" in value\n  );\n}\n\nfunction createCronScheduledTasks(jobs: FarmCronJob[]): Record<string, string | string[]> {\n  const scheduledTasks: Record<string, string | string[]> = {};\n  for (const job of jobs) {\n    const taskName = getFarmCronTaskName(job.name);\n    for (const schedule of job.schedule) {\n      scheduledTasks[schedule] = mergeTaskNames(scheduledTasks[schedule], taskName);\n    }\n  }\n  return scheduledTasks;\n}\n\nfunction mergeTaskNames(\n  current: string | string[] | undefined,\n  taskName: string,\n): string | string[] {\n  if (!current) return taskName;\n  const names = Array.isArray(current) ? current : [current];\n  return names.includes(taskName) ? names : [...names, taskName];\n}\n\nfunction getFarmCronTaskName(name: string): string {\n  return `farm:cron:${name}`;\n}\n\nfunction createNitroCronTaskWrapper(job: FarmCronJob, secretEnv: string): string {\n  return `\nimport { defineTask, useNitroApp } from \"nitro/runtime\";\n\nconst name = ${JSON.stringify(job.name)};\nconst path = ${JSON.stringify(job.path)};\nconst secretEnv = ${JSON.stringify(secretEnv)};\n\nfunction readSecret(event) {\n  const runtimeEnv = event?.context?.cloudflare?.env || event?.context?.env || {};\n  return runtimeEnv[secretEnv] || (typeof process !== \"undefined\" ? process.env?.[secretEnv] : \"\") || \"\";\n}\n\nexport default defineTask({\n  meta: {\n    name: ${JSON.stringify(getFarmCronTaskName(job.name))},\n    description: ${JSON.stringify(job.description || `Farm cron ${job.name}`)}\n  },\n  async run(event) {\n    const headers = new Headers({\n      \"x-farm-cron-name\": name,\n      \"x-farm-cron-scheduled-at\": String(event?.payload?.scheduledTime || Date.now())\n    });\n    const secret = readSecret(event);\n    if (secret) headers.set(\"authorization\", \"Bearer \" + secret);\n\n    const response = await useNitroApp().fetch(path, { method: \"GET\", headers });\n    const contentType = response.headers.get(\"content-type\") || \"\";\n    const body = response.status === 204\n      ? null\n      : contentType.includes(\"application/json\")\n        ? await response.json().catch(() => null)\n        : await response.text();\n\n    if (!response.ok) {\n      const detail = typeof body === \"string\" ? body : JSON.stringify(body);\n      throw new Error(\n        \"Farm cron \" + JSON.stringify(name) + \" received \" + response.status +\n        \" from \" + path + (detail ? \": \" + detail : \"\")\n      );\n    }\n\n    return { result: body };\n  }\n});\n`.trim();\n}\n\n/**\n * Wrapper file names for a set of cron job names.\n *\n * Cron names are case-sensitive and `Daily` and `daily` are both valid, distinct\n * jobs — but macOS and Windows use case-insensitive filesystems by default, so\n * their wrappers would overwrite one another and both jobs would run whichever\n * file was written last. Names are only disambiguated when they actually\n * collide case-insensitively, so ordinary names such as `dailyCleanup` keep a\n * readable wrapper; every name in a colliding group gets a digest of the exact\n * job name appended, which keeps the result independent of configuration order.\n */\nfunction resolveCronWrapperFileNames(names: readonly string[]): Map<string, string> {\n  const groups = new Map<string, number>();\n  for (const name of names) {\n    const key = safeFileName(name).toLowerCase();\n    groups.set(key, (groups.get(key) ?? 0) + 1);\n  }\n\n  const resolved = new Map<string, string>();\n  const claimed = new Map<string, string>();\n  for (const name of names) {\n    const base = safeFileName(name);\n    const key = base.toLowerCase();\n    const fileName = (groups.get(key) ?? 0) > 1 ? `${key}-${cronNameFingerprint(name)}` : base;\n    const claimedBy = claimed.get(fileName.toLowerCase());\n    if (claimedBy !== undefined) {\n      throw new Error(\n        `Farm cron jobs ${JSON.stringify(claimedBy)} and ${JSON.stringify(name)} generate the same wrapper file ${JSON.stringify(`${fileName}.mjs`)}. Rename one of them.`,\n      );\n    }\n    claimed.set(fileName.toLowerCase(), name);\n    resolved.set(name, fileName);\n  }\n  return resolved;\n}\n\n/**\n * FNV-1a. This module is bundled into server runtimes without node:crypto, and\n * the digest only needs to separate file names.\n */\nfunction cronNameFingerprint(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index += 1) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction safeFileName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"cron\";\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 FarmRedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nexport interface FarmRedirectSignal {\n  url: string;\n  status: FarmRedirectStatus;\n}\n\nconst REDIRECT_ERROR_CODE = \"FARM_REDIRECT\";\nconst NOT_FOUND_ERROR_CODE = \"FARM_NOT_FOUND\";\nconst REDIRECT_ERROR_SYMBOL = Symbol.for(\"farm.navigation.redirect\");\nconst NOT_FOUND_ERROR_SYMBOL = Symbol.for(\"farm.navigation.notFound\");\n\ntype FarmNavigationError = Error & {\n  digest: string;\n  [REDIRECT_ERROR_SYMBOL]?: FarmRedirectSignal;\n  [NOT_FOUND_ERROR_SYMBOL]?: true;\n};\n\nexport function redirect(url: string, status: FarmRedirectStatus = 307): never {\n  throw createRedirectError(url, status);\n}\n\nexport function permanentRedirect(url: string): never {\n  redirect(url, 308);\n}\n\nexport function notFound(): never {\n  const error = new Error(NOT_FOUND_ERROR_CODE) as FarmNavigationError;\n  error.digest = NOT_FOUND_ERROR_CODE;\n  error[NOT_FOUND_ERROR_SYMBOL] = true;\n  throw error;\n}\n\nexport function isFarmRedirectError(error: unknown): boolean {\n  return Boolean(getFarmRedirectError(error));\n}\n\nexport function getFarmRedirectError(error: unknown): FarmRedirectSignal | null {\n  if (!error || typeof error !== \"object\") return null;\n  const candidate = error as Partial<FarmNavigationError>;\n  if (candidate[REDIRECT_ERROR_SYMBOL]) {\n    return candidate[REDIRECT_ERROR_SYMBOL] as FarmRedirectSignal;\n  }\n\n  if (\n    typeof candidate.digest === \"string\" &&\n    candidate.digest.startsWith(`${REDIRECT_ERROR_CODE};`)\n  ) {\n    const [, status, ...urlParts] = candidate.digest.split(\";\");\n    const parsedStatus = Number(status);\n    if (isFarmRedirectStatus(parsedStatus)) {\n      return {\n        status: parsedStatus,\n        url: urlParts.join(\";\"),\n      };\n    }\n  }\n\n  return null;\n}\n\nexport function isFarmNotFoundError(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n  const candidate = error as Partial<FarmNavigationError>;\n  return Boolean(candidate[NOT_FOUND_ERROR_SYMBOL] || candidate.digest === NOT_FOUND_ERROR_CODE);\n}\n\nfunction createRedirectError(url: string, status: FarmRedirectStatus): FarmNavigationError {\n  const error = new Error(`${REDIRECT_ERROR_CODE};${status};${url}`) as FarmNavigationError;\n  error.digest = `${REDIRECT_ERROR_CODE};${status};${url}`;\n  error[REDIRECT_ERROR_SYMBOL] = { url, status };\n  return error;\n}\n\nexport function isFarmRedirectStatus(status: unknown): status is FarmRedirectStatus {\n  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n","export type FarmRouteRuntime = \"auto\" | \"node\" | \"edge\";\nexport type FarmRouteRegions = \"auto\" | readonly string[];\nexport type FarmRouteMaxDuration = \"auto\" | number;\n\n/** Portable execution controls shared by file, programmatic, and config routes. */\nexport interface FarmRouteRuntimeConfig {\n  runtime?: FarmRouteRuntime;\n  regions?: FarmRouteRegions;\n  maxDuration?: FarmRouteMaxDuration;\n}\n\nexport interface ResolvedFarmRouteRuntimeConfig {\n  runtime: FarmRouteRuntime;\n  regions?: string[];\n  maxDuration?: number;\n}\n\nexport type FarmRouteRuntimeEntryKind = \"page\" | \"api\" | \"metadata\" | \"rule\";\nexport type FarmRouteRenderingMode = \"static\" | \"dynamic\";\n\nexport interface FarmRouteRuntimeManifestEntry extends ResolvedFarmRouteRuntimeConfig {\n  kind: FarmRouteRuntimeEntryKind;\n  pattern: string;\n  rendering: FarmRouteRenderingMode;\n  source?: string;\n}\n\nexport interface FarmRouteRuntimeManifest {\n  version: 1;\n  routes: FarmRouteRuntimeManifestEntry[];\n}\n\nexport function normalizeFarmRouteRuntimeConfig(\n  value: FarmRouteRuntimeConfig | null | undefined,\n  source = \"Route configuration\",\n): FarmRouteRuntimeConfig {\n  if (!value) return {};\n\n  const normalized: FarmRouteRuntimeConfig = {};\n\n  if (value.runtime !== undefined) {\n    if (value.runtime !== \"auto\" && value.runtime !== \"node\" && value.runtime !== \"edge\") {\n      throw new TypeError(`${source} runtime must be \"auto\", \"node\", or \"edge\"`);\n    }\n    normalized.runtime = value.runtime;\n  }\n\n  if (value.regions !== undefined) {\n    if (value.regions === \"auto\") {\n      normalized.regions = \"auto\";\n    } else {\n      if (!Array.isArray(value.regions) || value.regions.length === 0) {\n        throw new TypeError(`${source} regions must be \"auto\" or a non-empty string array`);\n      }\n\n      const regions = Array.from(\n        new Set(\n          value.regions.map((region) => {\n            if (\n              typeof region !== \"string\" ||\n              !region.trim() ||\n              /[\\u0000-\\u001f\\u007f]/.test(region)\n            ) {\n              throw new TypeError(`${source} regions must contain non-empty region identifiers`);\n            }\n            return region.trim();\n          }),\n        ),\n      );\n\n      normalized.regions = regions;\n    }\n  }\n\n  if (value.maxDuration !== undefined) {\n    if (value.maxDuration === \"auto\") {\n      normalized.maxDuration = \"auto\";\n    } else if (\n      typeof value.maxDuration !== \"number\" ||\n      !Number.isInteger(value.maxDuration) ||\n      value.maxDuration <= 0\n    ) {\n      throw new TypeError(`${source} maxDuration must be \"auto\" or a positive integer in seconds`);\n    } else {\n      normalized.maxDuration = value.maxDuration;\n    }\n  }\n\n  return normalized;\n}\n\n/** Merge from lowest to highest precedence. Explicit \"auto\" values reset inherited hints. */\nexport function mergeFarmRouteRuntimeConfigs(\n  ...configs: Array<FarmRouteRuntimeConfig | null | undefined>\n): FarmRouteRuntimeConfig {\n  const merged: FarmRouteRuntimeConfig = {};\n\n  for (const config of configs) {\n    if (!config) continue;\n    if (config.runtime !== undefined) merged.runtime = config.runtime;\n    if (config.regions !== undefined) merged.regions = config.regions;\n    if (config.maxDuration !== undefined) merged.maxDuration = config.maxDuration;\n  }\n\n  return merged;\n}\n\nexport function resolveFarmRouteRuntimeConfig(\n  config: FarmRouteRuntimeConfig | null | undefined,\n  source?: string,\n): ResolvedFarmRouteRuntimeConfig {\n  const normalized = normalizeFarmRouteRuntimeConfig(config, source);\n\n  return {\n    runtime: normalized.runtime ?? \"auto\",\n    ...(normalized.regions && normalized.regions !== \"auto\"\n      ? { regions: [...normalized.regions] }\n      : {}),\n    ...(typeof normalized.maxDuration === \"number\" ? { maxDuration: normalized.maxDuration } : {}),\n  };\n}\n\nexport function hasFarmRouteRuntimeControls(\n  config: FarmRouteRuntimeConfig | null | undefined,\n): boolean {\n  return Boolean(\n    config &&\n    (config.runtime !== undefined ||\n      config.regions !== undefined ||\n      config.maxDuration !== undefined),\n  );\n}\n\nexport function getFarmRouteRuntimeConfig(value: unknown): FarmRouteRuntimeConfig {\n  if (!value || typeof value !== \"object\") return {};\n  const route = value as FarmRouteRuntimeConfig;\n  return {\n    ...(route.runtime !== undefined ? { runtime: route.runtime } : {}),\n    ...(route.regions !== undefined ? { regions: route.regions } : {}),\n    ...(route.maxDuration !== undefined ? { maxDuration: route.maxDuration } : {}),\n  };\n}\n\nexport function createFarmRouteRuntimeKey(config: ResolvedFarmRouteRuntimeConfig): string {\n  return JSON.stringify({\n    runtime: config.runtime,\n    regions: config.regions || null,\n    maxDuration: config.maxDuration || null,\n  });\n}\n\n/** Resolve matching route rules from broadest to most specific. */\nexport function resolveFarmRouteRuleRuntimeConfig(\n  pathname: string,\n  routeRules: Record<string, FarmRouteRuntimeConfig> | null | undefined,\n): FarmRouteRuntimeConfig {\n  if (!routeRules) return {};\n\n  const matches = Object.entries(routeRules)\n    .filter(\n      ([pattern, rule]) =>\n        hasFarmRouteRuntimeControls(rule) && farmRouteRuleMatches(pattern, pathname),\n    )\n    .sort(([left], [right]) => compareFarmRouteRuleSpecificity(left, right));\n\n  return mergeFarmRouteRuntimeConfigs(...matches.map(([, rule]) => rule));\n}\n\nexport function farmRouteRuleMatches(pattern: string, pathname: string): boolean {\n  const normalizedPattern = normalizeRoutePattern(pattern);\n  const normalizedPathname = normalizeRoutePattern(pathname);\n  if (normalizedPattern === normalizedPathname) return true;\n\n  const expression = normalizedPattern\n    .split(\"/\")\n    .filter(Boolean)\n    .map((segment) => {\n      if (segment === \"**\") return \".*\";\n      if (segment === \"*\") return \"[^/]+\";\n      if (/^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)) return \".*\";\n      if (/^\\[\\.\\.\\..+\\]$/.test(segment)) return \".+\";\n      if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return \"[^/]+\";\n      return escapeRegExp(segment);\n    })\n    .join(\"/\");\n\n  return new RegExp(`^/${expression}/?$`).test(normalizedPathname);\n}\n\nfunction compareFarmRouteRuleSpecificity(left: string, right: string): number {\n  const leftScore = getFarmRouteRuleSpecificity(left);\n  const rightScore = getFarmRouteRuleSpecificity(right);\n  return leftScore - rightScore || left.localeCompare(right);\n}\n\nfunction getFarmRouteRuleSpecificity(pattern: string): number {\n  return normalizeRoutePattern(pattern)\n    .split(\"/\")\n    .filter(Boolean)\n    .reduce((score, segment) => {\n      if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n      if (segment === \"*\" || segment.startsWith(\"[...\")) return score + 10;\n      if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return score + 50;\n      return score + 100;\n    }, 0);\n}\n\nfunction normalizeRoutePattern(value: string): string {\n  const withSlash = value.trim().startsWith(\"/\") ? value.trim() : `/${value.trim()}`;\n  return withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import type { HeaderConfig, RedirectConfig } from \"./config\";\nimport { isFarmRedirectStatus, type FarmRedirectStatus } from \"./navigation-errors\";\nimport type { FarmRouteRuntimeConfig } from \"./route-runtime\";\nimport { normalizeFarmRouteRuntimeConfig } from \"./route-runtime\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\n\nexport type FarmRouteRuleRenderMode = \"static\" | \"dynamic\";\n\nexport type FarmRouteRuleRedirect =\n  | string\n  | {\n      to: string;\n      statusCode?: FarmRedirectStatus;\n      permanent?: boolean;\n    };\n\nexport type FarmRouteRuleCors =\n  | boolean\n  | {\n      origin?: string;\n      methods?: string | readonly string[];\n      headers?: string | readonly string[];\n    };\n\nexport interface FarmRouteRule extends FarmRouteRuntimeConfig {\n  prerender?: boolean;\n  render?: FarmRouteRuleRenderMode;\n  ssr?: boolean;\n  swr?: boolean | number;\n  isr?: boolean | number;\n  cors?: FarmRouteRuleCors;\n  headers?: Record<string, string>;\n  redirect?: FarmRouteRuleRedirect;\n}\n\nexport type FarmRouteRules = Record<string, FarmRouteRule>;\n\nexport function normalizeRouteRules(routeRules: FarmRouteRules | undefined): FarmRouteRules {\n  if (!routeRules) return {};\n\n  const normalized: FarmRouteRules = {};\n  const normalizedSources = new Map<string, string>();\n  for (const [source, rule] of Object.entries(routeRules)) {\n    if (!rule) continue;\n    const normalizedSource = normalizeRuleSource(source);\n    validateConfigRouteSource(normalizedSource, `Route rule \"${source}\" source`);\n    const existingSource = normalizedSources.get(normalizedSource);\n    if (existingSource !== undefined) {\n      throw new Error(\n        `Route rules \"${existingSource}\" and \"${source}\" both normalize to \"${normalizedSource}\".`,\n      );\n    }\n    normalizedSources.set(normalizedSource, source);\n    if (\n      typeof rule.redirect === \"object\" &&\n      rule.redirect.statusCode !== undefined &&\n      !isFarmRedirectStatus(rule.redirect.statusCode)\n    ) {\n      throw new RangeError(\n        `Route rule \"${normalizedSource}\" redirect.statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n    normalized[normalizedSource] = {\n      ...rule,\n      ...normalizeFarmRouteRuntimeConfig(rule, `Route rule \"${normalizedSource}\"`),\n    };\n  }\n  return normalized;\n}\n\nexport function routeRulesToRedirects(routeRules: FarmRouteRules): RedirectConfig[] {\n  return Object.entries(routeRules)\n    .filter((entry): entry is [string, FarmRouteRule & { redirect: FarmRouteRuleRedirect }] =>\n      Boolean(entry[1].redirect),\n    )\n    .map(([source, rule]) => {\n      const redirect = typeof rule.redirect === \"string\" ? { to: rule.redirect } : rule.redirect;\n      return {\n        source,\n        destination: redirect.to,\n        permanent: redirect.permanent,\n        statusCode: redirect.statusCode ?? (redirect.permanent === true ? 308 : undefined),\n      };\n    });\n}\n\nexport function routeRulesToHeaders(routeRules: FarmRouteRules): HeaderConfig[] {\n  const configs: HeaderConfig[] = [];\n\n  for (const [source, rule] of Object.entries(routeRules)) {\n    const headers = {\n      ...normalizeCorsHeaders(rule.cors),\n      ...rule.headers,\n    };\n\n    const entries = Object.entries(headers);\n    if (entries.length === 0) continue;\n\n    configs.push({\n      source,\n      headers: entries.map(([key, value]) => ({ key, value })),\n    });\n  }\n\n  return configs;\n}\n\nexport function routeRulesToNitroRouteRules(routeRules: FarmRouteRules): Record<string, any> {\n  const nitroRules: Record<string, any> = {};\n\n  for (const [source, rule] of Object.entries(routeRules)) {\n    const nitroRule: Record<string, any> = { ...rule };\n\n    if (rule.render === \"static\") {\n      nitroRule.prerender = true;\n    } else if (rule.render === \"dynamic\") {\n      nitroRule.prerender = false;\n    }\n\n    if (rule.redirect) {\n      const redirect = typeof rule.redirect === \"string\" ? { to: rule.redirect } : rule.redirect;\n      if (hasExplicitQuery(redirect.to)) {\n        // Nitro merges the incoming query into redirect targets, including when\n        // the target already declares one. Farm's redirect contract replaces\n        // the incoming query in that case, so let the bundled Farm handler own\n        // these redirects instead of changing their meaning in production.\n        delete nitroRule.redirect;\n      } else {\n        nitroRule.redirect = {\n          to: redirect.to,\n          status: redirect.statusCode ?? (redirect.permanent === true ? 308 : 307),\n        };\n      }\n    }\n\n    if (rule.cors) {\n      nitroRule.cors = true;\n      nitroRule.headers = {\n        ...normalizeCorsHeaders(rule.cors),\n        ...rule.headers,\n      };\n    }\n\n    delete nitroRule.render;\n    delete nitroRule.runtime;\n    delete nitroRule.regions;\n    delete nitroRule.maxDuration;\n    nitroRules[source] = nitroRule;\n  }\n\n  return nitroRules;\n}\n\nfunction normalizeCorsHeaders(cors: FarmRouteRuleCors | undefined): Record<string, string> {\n  if (!cors) return {};\n\n  if (cors === true) {\n    return {\n      \"Access-Control-Allow-Origin\": \"*\",\n      \"Access-Control-Allow-Methods\": \"*\",\n      \"Access-Control-Allow-Headers\": \"*\",\n    };\n  }\n\n  return {\n    \"Access-Control-Allow-Origin\": cors.origin ?? \"*\",\n    \"Access-Control-Allow-Methods\": normalizeList(cors.methods) ?? \"*\",\n    \"Access-Control-Allow-Headers\": normalizeList(cors.headers) ?? \"*\",\n  };\n}\n\nfunction normalizeList(value: string | readonly string[] | undefined): string | undefined {\n  if (!value || typeof value === \"string\") return value;\n  return value.join(\", \");\n}\n\nfunction normalizeRuleSource(source: string): string {\n  const trimmed = source.trim();\n  if (!trimmed) {\n    throw new TypeError(\"Route rule source must be a non-empty pathname pattern.\");\n  }\n  return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\nfunction hasExplicitQuery(destination: string): boolean {\n  const queryIndex = destination.indexOf(\"?\");\n  if (queryIndex === -1) return false;\n  const hashIndex = destination.indexOf(\"#\");\n  return hashIndex === -1 || queryIndex < hashIndex;\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","export const FARM_SERVER_FN_FAILURE_SYMBOL = Symbol.for(\"farm.server-fn.failure\");\n\nexport type SerializedServerFnFailure = {\n  name: \"ServerFnFailure\";\n  message: string;\n  code: string;\n  status: number;\n  data: unknown;\n};\n\nexport class ServerFnFailure<\n  TCode extends string = string,\n  TData = unknown,\n  TStatus extends number = number,\n> extends Error {\n  readonly name = \"ServerFnFailure\" as const;\n  readonly code: TCode;\n  readonly data: TData;\n  readonly status: TStatus;\n\n  constructor(\n    code: TCode,\n    data: TData,\n    options: {\n      status: TStatus;\n      message: string;\n    },\n  ) {\n    super(options.message);\n    this.code = code;\n    this.data = data;\n    this.status = options.status;\n\n    Object.defineProperty(this, FARM_SERVER_FN_FAILURE_SYMBOL, {\n      value: true,\n      enumerable: false,\n    });\n  }\n}\n\nexport class ServerActionError extends Error {\n  readonly name = \"ServerActionError\" as const;\n\n  constructor(message = \"Server function failed\") {\n    super(message);\n  }\n}\n\nexport function isServerFnFailure(value: unknown): value is ServerFnFailure {\n  if (!value || typeof value !== \"object\") return false;\n\n  const candidate = value as Partial<ServerFnFailure> & {\n    [FARM_SERVER_FN_FAILURE_SYMBOL]?: unknown;\n  };\n  return (\n    candidate[FARM_SERVER_FN_FAILURE_SYMBOL] === true &&\n    candidate.name === \"ServerFnFailure\" &&\n    typeof candidate.code === \"string\" &&\n    Number.isInteger(candidate.status) &&\n    (candidate.status ?? 0) >= 400 &&\n    (candidate.status ?? 0) <= 599\n  );\n}\n\nexport function serializeServerFnFailure(value: unknown): SerializedServerFnFailure | null {\n  if (!isServerFnFailure(value)) return null;\n\n  return {\n    name: \"ServerFnFailure\",\n    message: value.message,\n    code: value.code,\n    status: value.status,\n    data: value.data,\n  };\n}\n\nexport function createServerFnTransportError(value: unknown): ServerFnFailure | ServerActionError {\n  if (isSerializedServerFnFailure(value)) {\n    return new ServerFnFailure(value.code, value.data, {\n      status: value.status,\n      message: value.message,\n    });\n  }\n\n  const message =\n    value && typeof value === \"object\" && \"message\" in value && typeof value.message === \"string\"\n      ? value.message\n      : \"Server function failed\";\n  return new ServerActionError(message);\n}\n\nfunction isSerializedServerFnFailure(value: unknown): value is SerializedServerFnFailure {\n  if (!value || typeof value !== \"object\") return false;\n\n  const candidate = value as Partial<SerializedServerFnFailure>;\n  return (\n    candidate.name === \"ServerFnFailure\" &&\n    typeof candidate.message === \"string\" &&\n    typeof candidate.code === \"string\" &&\n    Number.isInteger(candidate.status) &&\n    (candidate.status ?? 0) >= 400 &&\n    (candidate.status ?? 0) <= 599 &&\n    \"data\" in candidate\n  );\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { subscribeFarmCacheInvalidation, subscribeFarmCacheTask } from \"./cache-invalidation\";\nimport {\n  getRequestSourceOrigin,\n  matchesAllowedOrigin,\n  matchesHostHeader,\n  normalizeAllowedOriginPattern,\n} from \"./request-origin\";\nimport { serializeServerFnFailure, type SerializedServerFnFailure } from \"./server-fn-error\";\nimport { parseBodySizeLimit } from \"./server-http\";\n\nconst SERVER_ACTION_ALLOWED_ORIGINS_LABEL = \"serverActions.allowedOrigins\";\n\nexport const DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT = 1_000_000;\n\nexport interface FarmServerActionsConfig {\n  /** Additional trusted origins or host patterns, such as https://app.example.com. */\n  allowedOrigins?: readonly string[];\n  /** Maximum encoded request body size in bytes or as a size string such as \"1mb\". */\n  bodySizeLimit?: number | string;\n}\n\nexport interface ResolvedFarmServerActionsConfig {\n  allowedOrigins: readonly string[];\n  bodySizeLimit: number;\n}\n\nexport type ServerActionRequestKind = \"javascript\" | \"form\";\n\nexport interface PreparedServerActionRequest {\n  body: string | FormData;\n  contentType: string;\n}\n\nexport type SanitizedServerActionError =\n  | {\n      name: \"ServerActionError\";\n      message: \"Server function failed\";\n    }\n  | SerializedServerFnFailure;\n\ntype ServerActionRequestErrorCode =\n  | \"BODY_TOO_LARGE\"\n  | \"INVALID_ACTION_ID\"\n  | \"INVALID_BODY\"\n  | \"INVALID_CONTENT_LENGTH\"\n  | \"INVALID_METHOD\"\n  | \"INVALID_ORIGIN\"\n  | \"MISSING_ORIGIN\"\n  | \"UNSUPPORTED_CONTENT_TYPE\";\n\nexport class ServerActionRequestError extends Error {\n  readonly code: ServerActionRequestErrorCode;\n  readonly status: number;\n\n  constructor(code: ServerActionRequestErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"ServerActionRequestError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\ntype ServerActionExecutionContext = {\n  request: Request;\n  signal: AbortSignal;\n  invalidations: Set<string>;\n  cacheTasks: Set<Promise<void>>;\n};\n\nconst SERVER_ACTION_STORAGE_KEY = Symbol.for(\"farm.serverActionStorage\");\nconst FALLBACK_ABORT_CONTROLLER_KEY = Symbol.for(\"farm.serverActionFallbackAbortController\");\nconst FORM_ACTION_CONTENT_TYPES = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n]);\nconst JAVASCRIPT_ACTION_CONTENT_TYPES = new Set([\n  \"application/octet-stream\",\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\ntype GlobalWithServerActionStorage = typeof globalThis & {\n  [SERVER_ACTION_STORAGE_KEY]?: AsyncLocalStorage<ServerActionExecutionContext>;\n  [FALLBACK_ABORT_CONTROLLER_KEY]?: AbortController;\n};\n\nexport function resolveServerActionsConfig(\n  config: FarmServerActionsConfig | undefined,\n): ResolvedFarmServerActionsConfig {\n  const allowedOrigins = (config?.allowedOrigins ?? []).map((value) =>\n    normalizeAllowedOriginPattern(value, SERVER_ACTION_ALLOWED_ORIGINS_LABEL),\n  );\n  const bodySizeLimit = parseBodySizeLimit(\n    config?.bodySizeLimit ?? DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT,\n    \"serverActions.bodySizeLimit\",\n  );\n\n  return Object.freeze({\n    allowedOrigins: Object.freeze(allowedOrigins),\n    bodySizeLimit,\n  });\n}\n\nexport function validateServerActionRequest(\n  request: Request,\n  config: ResolvedFarmServerActionsConfig,\n): void {\n  if (request.method.toUpperCase() !== \"POST\") {\n    throw new ServerActionRequestError(\n      \"INVALID_METHOD\",\n      405,\n      \"Server actions only accept POST requests\",\n    );\n  }\n\n  const requestUrl = new URL(request.url);\n  const sourceOrigin = resolveSourceOrigin(request);\n  const fetchSite = request.headers.get(\"sec-fetch-site\")?.trim().toLowerCase();\n\n  if (!sourceOrigin) {\n    if (fetchSite !== \"same-origin\") {\n      throw new ServerActionRequestError(\n        \"MISSING_ORIGIN\",\n        403,\n        \"Server action request is missing same-origin metadata\",\n      );\n    }\n    return;\n  }\n\n  const matchesRequest =\n    sourceOrigin === requestUrl.origin || matchesHostHeader(sourceOrigin, request);\n  const matchesConfiguredOrigin = config.allowedOrigins.some((pattern) =>\n    matchesAllowedOrigin(sourceOrigin, pattern),\n  );\n\n  if (!matchesRequest && !matchesConfiguredOrigin) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      \"Server action origin does not match the request origin\",\n    );\n  }\n\n  if (fetchSite === \"cross-site\" && !matchesConfiguredOrigin) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      \"Cross-site server action request was rejected\",\n    );\n  }\n}\n\nexport async function prepareServerActionRequest(\n  request: Request,\n  config: ResolvedFarmServerActionsConfig,\n  kind: ServerActionRequestKind,\n  actionId?: string | null,\n): Promise<PreparedServerActionRequest> {\n  validateServerActionRequest(request, config);\n\n  if (kind === \"javascript\") {\n    validateActionId(actionId);\n  }\n\n  const contentType = getSupportedContentType(request, kind);\n  const bytes = await readBodyWithLimit(request, config.bodySizeLimit);\n\n  if (kind === \"form\" || contentType === \"multipart/form-data\") {\n    return {\n      body: await parseFormData(request, bytes),\n      contentType,\n    };\n  }\n\n  return {\n    body: new TextDecoder().decode(bytes),\n    contentType,\n  };\n}\n\nexport function createServerActionRequestErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof ServerActionRequestError)) {\n    return null;\n  }\n\n  const headers = new Headers({\n    \"cache-control\": \"no-store\",\n    \"content-type\": \"text/plain; charset=utf-8\",\n    \"x-content-type-options\": \"nosniff\",\n  });\n  if (error.status === 405) {\n    headers.set(\"allow\", \"POST\");\n  }\n\n  return new Response(getPublicErrorMessage(error.status), {\n    status: error.status,\n    headers,\n  });\n}\n\nexport function sanitizeServerActionError(error: unknown): SanitizedServerActionError {\n  const declaredFailure = serializeServerFnFailure(error);\n  if (declaredFailure) return declaredFailure;\n\n  return {\n    name: \"ServerActionError\",\n    message: \"Server function failed\",\n  };\n}\n\nexport async function runWithServerActionRequest<T>(\n  request: Request,\n  callback: () => T | Promise<T>,\n): Promise<T> {\n  throwIfAborted(request.signal);\n  const context: ServerActionExecutionContext = {\n    request,\n    signal: request.signal,\n    invalidations: new Set(),\n    cacheTasks: new Set(),\n  };\n\n  return getServerActionStorage().run(context, async () => {\n    try {\n      const result = await callback();\n      await Promise.all(context.cacheTasks);\n      return result;\n    } catch (error) {\n      await Promise.allSettled(context.cacheTasks);\n      throw error;\n    }\n  });\n}\n\nexport function getServerActionExecutionContext(): ServerActionExecutionContext | undefined {\n  return getServerActionStorage().getStore();\n}\n\nexport function getServerActionSignal(): AbortSignal {\n  return getServerActionExecutionContext()?.signal ?? getFallbackAbortController().signal;\n}\n\nexport function getServerActionInvalidations(): readonly string[] {\n  return Array.from(getServerActionExecutionContext()?.invalidations ?? []);\n}\n\nsubscribeFarmCacheInvalidation((key) => {\n  getServerActionExecutionContext()?.invalidations.add(key);\n});\n\nsubscribeFarmCacheTask((task) => {\n  getServerActionExecutionContext()?.cacheTasks.add(task);\n});\n\nfunction getServerActionStorage(): AsyncLocalStorage<ServerActionExecutionContext> {\n  const globalState = globalThis as GlobalWithServerActionStorage;\n  if (!globalState[SERVER_ACTION_STORAGE_KEY]) {\n    globalState[SERVER_ACTION_STORAGE_KEY] = new AsyncLocalStorage<ServerActionExecutionContext>();\n  }\n  return globalState[SERVER_ACTION_STORAGE_KEY]!;\n}\n\nfunction getFallbackAbortController(): AbortController {\n  const globalState = globalThis as GlobalWithServerActionStorage;\n  if (!globalState[FALLBACK_ABORT_CONTROLLER_KEY]) {\n    globalState[FALLBACK_ABORT_CONTROLLER_KEY] = new AbortController();\n  }\n  return globalState[FALLBACK_ABORT_CONTROLLER_KEY]!;\n}\n\n/**\n * Adapt the shared origin resolution onto the server-action error contract:\n * an unusable Origin/Referer is a 403 here, while a request that simply\n * carried neither header returns null for the caller to judge.\n */\nfunction resolveSourceOrigin(request: Request): string | null {\n  const result = getRequestSourceOrigin(request);\n\n  if (!result.ok) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      result.reason === \"opaque-origin\"\n        ? \"Opaque origins are not allowed\"\n        : \"Invalid request origin\",\n    );\n  }\n\n  return result.origin;\n}\n\nfunction validateActionId(actionId?: string | null): asserts actionId is string {\n  if (!actionId || actionId.length > 4096 || hasControlCharacters(actionId)) {\n    throw new ServerActionRequestError(\"INVALID_ACTION_ID\", 400, \"Invalid server action id\");\n  }\n}\n\nfunction hasControlCharacters(value: string): boolean {\n  for (let index = 0; index < value.length; index++) {\n    const code = value.charCodeAt(index);\n    if (code <= 31 || code === 127) return true;\n  }\n  return false;\n}\n\nfunction getSupportedContentType(request: Request, kind: ServerActionRequestKind): string {\n  const header = request.headers.get(\"content-type\")?.trim().toLowerCase();\n  const contentType = header?.split(\";\", 1)[0]?.trim() ?? \"\";\n  const supported = kind === \"form\" ? FORM_ACTION_CONTENT_TYPES : JAVASCRIPT_ACTION_CONTENT_TYPES;\n\n  if (!supported.has(contentType)) {\n    throw new ServerActionRequestError(\n      \"UNSUPPORTED_CONTENT_TYPE\",\n      415,\n      \"Unsupported server action content type\",\n    );\n  }\n\n  return contentType;\n}\n\nasync function readBodyWithLimit(request: Request, limit: number): Promise<Uint8Array> {\n  const contentLength = request.headers.get(\"content-length\")?.trim();\n  if (contentLength) {\n    if (!/^\\d+$/.test(contentLength)) {\n      throw new ServerActionRequestError(\n        \"INVALID_CONTENT_LENGTH\",\n        400,\n        \"Invalid content-length header\",\n      );\n    }\n    if (Number(contentLength) > limit) {\n      throw new ServerActionRequestError(\"BODY_TOO_LARGE\", 413, \"Server action body is too large\");\n    }\n  }\n\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new ServerActionRequestError(\n          \"BODY_TOO_LARGE\",\n          413,\n          \"Server action body is too large\",\n        );\n        // As with API bodies, a cloned stream may wait for its untouched tee\n        // branch. Cleanup must neither delay rejection nor replace its error.\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  throwIfAborted(request.signal);\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nasync function parseFormData(request: Request, bytes: Uint8Array): Promise<FormData> {\n  const body = new ArrayBuffer(bytes.byteLength);\n  new Uint8Array(body).set(bytes);\n  const copy = new Request(request.url, {\n    method: \"POST\",\n    headers: request.headers,\n    body,\n  });\n\n  try {\n    return await copy.formData();\n  } catch {\n    throw new ServerActionRequestError(\"INVALID_BODY\", 400, \"Invalid server action form body\");\n  }\n}\n\nfunction getPublicErrorMessage(status: number): string {\n  switch (status) {\n    case 400:\n      return \"Bad Request\";\n    case 403:\n      return \"Forbidden\";\n    case 405:\n      return \"Method Not Allowed\";\n    case 413:\n      return \"Payload Too Large\";\n    case 415:\n      return \"Unsupported Media Type\";\n    default:\n      return \"Server Action Request Failed\";\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","export const DEFAULT_FARM_IMAGE_PATH = \"/_farm/image\";\nexport const DEFAULT_FARM_IMAGE_DEVICE_SIZES = [\n  640, 750, 828, 1080, 1200, 1920, 2048, 3840,\n] as const;\nexport const DEFAULT_FARM_IMAGE_SIZES = [16, 32, 48, 64, 96, 128, 256, 384] as const;\nexport const DEFAULT_FARM_IMAGE_QUALITIES = [75] as const;\nexport const DEFAULT_FARM_IMAGE_FORMATS = [\"image/webp\"] as const;\n\nexport type FarmImageFormat = \"image/avif\" | \"image/webp\";\nexport type FarmImageProvider = \"auto\" | \"node\" | \"cloudflare\" | \"none\";\n\nexport interface FarmImageRemotePattern {\n  protocol?: \"http\" | \"https\";\n  hostname: string;\n  port?: string;\n  pathname?: string;\n  search?: string;\n}\n\nexport interface FarmImageLocalPattern {\n  pathname: string;\n  search?: string;\n}\n\nexport interface FarmImageConfig {\n  /** Runtime optimizer. Auto selects Cloudflare Images on Cloudflare and Sharp elsewhere. */\n  provider?: FarmImageProvider;\n  /** Public optimizer endpoint. */\n  path?: string;\n  /** @deprecated Prefer remotePatterns, which also restricts protocol, path, port, and query. */\n  domains?: readonly string[];\n  remotePatterns?: readonly FarmImageRemotePattern[];\n  localPatterns?: readonly FarmImageLocalPattern[];\n  deviceSizes?: readonly number[];\n  imageSizes?: readonly number[];\n  qualities?: readonly number[];\n  formats?: readonly FarmImageFormat[];\n  minimumCacheTTL?: number;\n  maximumResponseBody?: number | string;\n  maximumRedirects?: number;\n  dangerouslyAllowSVG?: boolean;\n  dangerouslyAllowLocalIP?: boolean;\n}\n\nexport interface ResolvedFarmImageConfig {\n  provider: FarmImageProvider;\n  path: string;\n  domains: readonly string[];\n  remotePatterns: readonly FarmImageRemotePattern[];\n  localPatterns: readonly FarmImageLocalPattern[];\n  deviceSizes: readonly number[];\n  imageSizes: readonly number[];\n  qualities: readonly number[];\n  formats: readonly FarmImageFormat[];\n  minimumCacheTTL: number;\n  maximumResponseBody: number;\n  maximumRedirects: number;\n  dangerouslyAllowSVG: boolean;\n  dangerouslyAllowLocalIP: boolean;\n}\n\nexport type PublicFarmImageConfig = Pick<\n  ResolvedFarmImageConfig,\n  \"provider\" | \"path\" | \"deviceSizes\" | \"imageSizes\" | \"qualities\" | \"formats\"\n>;\n\nconst SIZE_UNITS: Record<string, number> = {\n  b: 1,\n  kb: 1_000,\n  mb: 1_000_000,\n  gb: 1_000_000_000,\n  kib: 1_024,\n  mib: 1_048_576,\n  gib: 1_073_741_824,\n};\n\nexport function resolveFarmImageConfig(\n  config: FarmImageConfig | undefined,\n): ResolvedFarmImageConfig {\n  const path = normalizeImagePath(config?.path ?? DEFAULT_FARM_IMAGE_PATH);\n  const deviceSizes = normalizeIntegerList(\n    config?.deviceSizes ?? DEFAULT_FARM_IMAGE_DEVICE_SIZES,\n    \"images.deviceSizes\",\n  );\n  const imageSizes = normalizeIntegerList(\n    config?.imageSizes ?? DEFAULT_FARM_IMAGE_SIZES,\n    \"images.imageSizes\",\n  );\n  const qualities = normalizeIntegerList(\n    config?.qualities ?? DEFAULT_FARM_IMAGE_QUALITIES,\n    \"images.qualities\",\n    100,\n  );\n  const formats = [...new Set(config?.formats ?? DEFAULT_FARM_IMAGE_FORMATS)];\n\n  if (formats.some((format) => format !== \"image/avif\" && format !== \"image/webp\")) {\n    throw new TypeError('images.formats only supports \"image/avif\" and \"image/webp\"');\n  }\n\n  const minimumCacheTTL = normalizeNonNegativeInteger(\n    config?.minimumCacheTTL ?? 60,\n    \"images.minimumCacheTTL\",\n  );\n  const maximumRedirects = normalizeNonNegativeInteger(\n    config?.maximumRedirects ?? 3,\n    \"images.maximumRedirects\",\n  );\n\n  return Object.freeze({\n    provider: config?.provider ?? \"auto\",\n    path,\n    domains: Object.freeze([\n      ...new Set(\n        (config?.domains ?? []).map((domain) => domain.trim().toLowerCase()).filter(Boolean),\n      ),\n    ]),\n    remotePatterns: Object.freeze(\n      (config?.remotePatterns ?? []).map((pattern) => normalizeRemotePattern(pattern)),\n    ),\n    localPatterns: Object.freeze(\n      (config?.localPatterns ?? [{ pathname: \"/**\" }]).map((pattern) =>\n        normalizeLocalPattern(pattern),\n      ),\n    ),\n    deviceSizes: Object.freeze(deviceSizes),\n    imageSizes: Object.freeze(imageSizes),\n    qualities: Object.freeze(qualities),\n    formats: Object.freeze(formats),\n    minimumCacheTTL,\n    maximumResponseBody: parseSize(\n      config?.maximumResponseBody ?? \"10mb\",\n      \"images.maximumResponseBody\",\n    ),\n    maximumRedirects,\n    dangerouslyAllowSVG: config?.dangerouslyAllowSVG ?? false,\n    dangerouslyAllowLocalIP: config?.dangerouslyAllowLocalIP ?? false,\n  });\n}\n\nexport function getPublicFarmImageConfig(\n  config: Pick<ResolvedFarmImageConfig, keyof PublicFarmImageConfig>,\n): PublicFarmImageConfig {\n  return {\n    provider: config.provider,\n    path: config.path,\n    deviceSizes: config.deviceSizes,\n    imageSizes: config.imageSizes,\n    qualities: config.qualities,\n    formats: config.formats,\n  };\n}\n\nfunction normalizeImagePath(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 TypeError(\"images.path cannot contain backslashes or control characters\");\n  }\n\n  const path = value.trim().replace(/\\/+$/, \"\") || \"/\";\n  if (!path.startsWith(\"/\") || path.startsWith(\"//\") || path.includes(\"?\") || path.includes(\"#\")) {\n    throw new TypeError(\"images.path must be an absolute pathname without a query or hash\");\n  }\n\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal and cannot conceal a path separator\n      // or dot segment.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new TypeError(\"images.path cannot contain backslashes or control characters\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new TypeError(\"images.path cannot contain percent-encoded path separators\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new TypeError('images.path cannot contain \".\" or \"..\" path segments');\n    }\n  }\n\n  return path;\n}\n\nfunction normalizeIntegerList(values: readonly number[], name: string, max?: number): number[] {\n  if (values.length === 0) {\n    throw new TypeError(`${name} must contain at least one value`);\n  }\n\n  const normalized = [...new Set(values)].sort((left, right) => left - right);\n  for (const value of normalized) {\n    if (!Number.isSafeInteger(value) || value <= 0 || (max !== undefined && value > max)) {\n      throw new TypeError(\n        `${name} must contain positive integers${max ? ` no greater than ${max}` : \"\"}`,\n      );\n    }\n  }\n  return normalized;\n}\n\nfunction normalizeNonNegativeInteger(value: number, name: string): number {\n  if (!Number.isSafeInteger(value) || value < 0) {\n    throw new TypeError(`${name} must be a non-negative safe integer`);\n  }\n  return value;\n}\n\nfunction parseSize(value: number | string, name: string): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${name} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)$/);\n  if (!match) {\n    throw new TypeError(`${name} must be bytes or a size string such as \"5mb\"`);\n  }\n\n  const bytes = Number(match[1]) * SIZE_UNITS[match[2]];\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${name} must resolve to a positive safe integer`);\n  }\n  return bytes;\n}\n\nfunction normalizeRemotePattern(pattern: FarmImageRemotePattern): FarmImageRemotePattern {\n  const hostname = pattern.hostname.trim().toLowerCase();\n  if (!hostname || hostname.includes(\"/\") || hostname.includes(\":\")) {\n    throw new TypeError(\"images.remotePatterns[].hostname must be a hostname or wildcard hostname\");\n  }\n  if (pattern.pathname && !pattern.pathname.startsWith(\"/\")) {\n    throw new TypeError(\"images.remotePatterns[].pathname must start with /\");\n  }\n  if (pattern.search && !pattern.search.startsWith(\"?\")) {\n    throw new TypeError(\"images.remotePatterns[].search must start with ?\");\n  }\n  return Object.freeze({ ...pattern, hostname });\n}\n\nfunction normalizeLocalPattern(pattern: FarmImageLocalPattern): FarmImageLocalPattern {\n  if (!pattern.pathname.startsWith(\"/\")) {\n    throw new TypeError(\"images.localPatterns[].pathname must start with /\");\n  }\n  if (pattern.search && !pattern.search.startsWith(\"?\")) {\n    throw new TypeError(\"images.localPatterns[].search must start with ?\");\n  }\n  return Object.freeze({ ...pattern });\n}\n","import { existsSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { mkdir, unlink } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\ntype EsbuildTransform = (typeof import(\"esbuild\"))[\"transform\"];\n\nexport type FarmLayerEntry = string;\n\nexport interface ResolvedFarmLayer {\n  /** The value used in `extends`. */\n  source: string;\n  /** Stable name used by the `#layers/<name>` alias. */\n  name: string;\n  /** Absolute layer package or directory root. */\n  root: string;\n  /** Source directory relative to the layer root. */\n  srcDir: string;\n  /** Resolved layer config file when one exists. */\n  configFile?: string;\n}\n\nexport interface FarmSourceRoot {\n  name: string;\n  root: string;\n  srcDir: string;\n  layer: boolean;\n}\n\nexport interface ResolveFarmLayersOptions {\n  root: string;\n  mode: \"development\" | \"production\";\n}\n\nexport interface FarmLayerResolution<TConfig extends Record<string, any>> {\n  config: TConfig & {\n    extends?: readonly FarmLayerEntry[];\n    layers: ResolvedFarmLayer[];\n  };\n  layers: ResolvedFarmLayer[];\n}\n\nconst FARM_CORE_PACKAGE = \"@farm.js/core\";\nconst FARM_CONFIG_ENTRY = \"@farm.js/core/config\";\nconst FARM_CORE_REFERENCE_RE = /([\"'])@farm.js\\/core\\1/g;\nconst FARM_CONFIG_HELPER_IMPORT_RE =\n  /(?:^|\\n)[\\t ]*import[\\t ]*\\{([^{}]*)\\}[\\t ]*from[\\t ]*([\"'])@farm.js\\/core\\2[\\t ]*;?[\\t ]*(?:\\n|$)/g;\nconst FARM_CONFIG_HELPER_SPECIFIER_RE =\n  /^(?:defineConfig|defineFarmConfig)(?:\\s+as\\s+[$A-Z_a-z][$\\w]*)?$/;\n\nconst CONFIG_FILENAMES = [\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n];\n\nconst LAYER_LOCAL_CONFIG_KEYS = new Set([\n  \"root\",\n  \"srcDir\",\n  \"outDir\",\n  \"distDir\",\n  \"deploy\",\n  \"output\",\n  \"preset\",\n  \"publicDir\",\n  \"generateBuildId\",\n]);\n\ntype LoadedLayer = ResolvedFarmLayer & {\n  config: Record<string, any>;\n};\n\nexport async function resolveFarmLayers<TConfig extends Record<string, any>>(\n  projectConfig: TConfig,\n  options: ResolveFarmLayersOptions,\n): Promise<FarmLayerResolution<TConfig>> {\n  const projectRoot = path.resolve(options.root);\n  const entries = normalizeLayerEntries(projectConfig.extends, \"project config\");\n\n  if (entries.length === 0) {\n    return {\n      config: {\n        ...projectConfig,\n        layers: [],\n      },\n      layers: [],\n    };\n  }\n\n  const loadedLayers: LoadedLayer[] = [];\n  const visited = new Set<string>();\n  const aliases = new Map<string, string>();\n\n  const visit = async (\n    source: string,\n    ownerRoot: string,\n    stack: Array<{ root: string; source: string }>,\n  ): Promise<void> => {\n    const resolvedSource = resolveLayerSource(source, ownerRoot);\n    const cycleIndex = stack.findIndex((entry) => entry.root === resolvedSource.root);\n    if (cycleIndex !== -1) {\n      const cycle = [...stack.slice(cycleIndex).map((entry) => entry.source), source];\n      throw new Error(`Farm layer cycle detected: ${cycle.join(\" -> \")}`);\n    }\n    if (visited.has(resolvedSource.root)) return;\n\n    const configFile = findFarmConfigFile(resolvedSource.root, resolvedSource.configFile);\n    const config = configFile\n      ? await loadFarmConfigFile(configFile, {\n          cacheRoot: projectRoot,\n          root: resolvedSource.root,\n        })\n      : {};\n    const nestedEntries = normalizeLayerEntries(config.extends, `layer ${JSON.stringify(source)}`);\n    const nextStack = [...stack, { root: resolvedSource.root, source }];\n\n    for (const nestedSource of nestedEntries) {\n      await visit(nestedSource, resolvedSource.root, nextStack);\n    }\n\n    if (visited.has(resolvedSource.root)) return;\n\n    const name = getLayerName(source, resolvedSource.root);\n    const conflictingRoot = aliases.get(name);\n    if (conflictingRoot && conflictingRoot !== resolvedSource.root) {\n      throw new Error(\n        `Farm layer alias \"#layers/${name}\" is ambiguous between ${conflictingRoot} and ${resolvedSource.root}`,\n      );\n    }\n    aliases.set(name, resolvedSource.root);\n\n    visited.add(resolvedSource.root);\n    loadedLayers.push({\n      source,\n      name,\n      root: resolvedSource.root,\n      srcDir: normalizeLayerSrcDir(config.srcDir),\n      configFile,\n      config,\n    });\n  };\n\n  for (const source of entries) {\n    await visit(source, projectRoot, []);\n  }\n\n  let mergedConfig: Record<string, any> = {};\n  for (const layer of loadedLayers) {\n    mergedConfig = mergeFarmLayerConfig(mergedConfig, getLayerDefaults(layer.config));\n  }\n  mergedConfig = mergeFarmLayerConfig(mergedConfig, projectConfig);\n\n  const layers = loadedLayers.map(({ config: _config, ...layer }) => layer);\n  return {\n    config: {\n      ...mergedConfig,\n      root: projectConfig.root,\n      srcDir: projectConfig.srcDir,\n      extends: projectConfig.extends,\n      layers,\n    } as unknown as FarmLayerResolution<TConfig>[\"config\"],\n    layers,\n  };\n}\n\nexport function getFarmSourceRoots(config: {\n  root?: string;\n  srcDir?: string;\n  layers?: readonly ResolvedFarmLayer[];\n}): FarmSourceRoot[] {\n  const roots: FarmSourceRoot[] = (config.layers ?? []).map((layer) => ({\n    name: layer.name,\n    root: layer.root,\n    srcDir: layer.srcDir,\n    layer: true,\n  }));\n\n  roots.push({\n    name: \"project\",\n    root: path.resolve(config.root || process.cwd()),\n    srcDir: config.srcDir || \"src\",\n    layer: false,\n  });\n\n  return roots;\n}\n\nexport function getFarmAppDirectories(config: {\n  root?: string;\n  srcDir?: string;\n  layers?: readonly ResolvedFarmLayer[];\n}): string[] {\n  return getFarmSourceRoots(config).map((source) => path.join(source.root, source.srcDir, \"app\"));\n}\n\nexport function getFarmLayerAliases(\n  layers: readonly ResolvedFarmLayer[] | undefined,\n): Record<string, string> {\n  return Object.fromEntries(\n    (layers ?? []).map((layer) => [`#layers/${layer.name}`, path.join(layer.root, layer.srcDir)]),\n  );\n}\n\n// Matches Windows drive-letter (`E:\\`, `E:/`) and UNC (`\\\\server\\share`) paths,\n// which would otherwise pass the \"bare specifier\" filter below. `path.isAbsolute`\n// only recognizes these on Windows, but esbuild can hand us such paths on any\n// platform (e.g. in cross-platform tests), and no valid package name contains\n// `:` or starts with `\\`.\nconst WINDOWS_ABSOLUTE_PATH_RE = /^(?:[A-Za-z]:[\\\\/]|\\\\\\\\)/;\n\n// External paths are written verbatim into the bundled config's import\n// statements. Node's ESM loader accepts `/abs/path` specifiers on POSIX, but a\n// raw Windows path like `E:\\...` is parsed as a URL with protocol `e:` and\n// rejected, so absolute paths must be emitted as file:// URLs.\nfunction toExternalSpecifier(resolvedPath: string): string {\n  return path.isAbsolute(resolvedPath) ? pathToFileURL(resolvedPath).href : resolvedPath;\n}\n\nexport function createFarmConfigResolutionPlugin(options: {\n  transform: EsbuildTransform;\n}): import(\"esbuild\").Plugin {\n  const configEntryChecks = new Map<string, Promise<boolean>>();\n\n  return {\n    name: \"farm-config-package-resolution\",\n    setup(pluginBuild) {\n      pluginBuild.onResolve({ filter: /^@farm\\.js\\/core$/ }, async (args) => {\n        if (\n          args.pluginData?.farmConfigExternal ||\n          args.kind !== \"import-statement\" ||\n          !args.importer\n        ) {\n          return;\n        }\n\n        let configEntryCheck = configEntryChecks.get(args.importer);\n        if (!configEntryCheck) {\n          configEntryCheck = onlyImportsFarmConfigHelpers(args.importer, options.transform);\n          configEntryChecks.set(args.importer, configEntryCheck);\n        }\n        if (!(await configEntryCheck)) return;\n\n        const resolved = await pluginBuild.resolve(FARM_CONFIG_ENTRY, {\n          importer: args.importer,\n          kind: args.kind,\n          namespace: args.namespace,\n          resolveDir: args.resolveDir,\n          pluginData: { farmConfigExternal: true },\n        });\n        if (resolved.errors.length > 0 || !resolved.path) return;\n\n        return {\n          path: toExternalSpecifier(resolved.path),\n          external: true,\n          warnings: resolved.warnings,\n        };\n      });\n\n      pluginBuild.onResolve({ filter: /^[^./]/ }, async (args) => {\n        // The filter is meant to catch bare package specifiers, but Windows\n        // absolute paths (`E:\\...`) match it too — including the entry point\n        // itself, which esbuild rejects when marked external.\n        if (\n          args.kind === \"entry-point\" ||\n          path.isAbsolute(args.path) ||\n          WINDOWS_ABSOLUTE_PATH_RE.test(args.path)\n        ) {\n          return;\n        }\n        if (args.pluginData?.farmConfigExternal) return;\n\n        const resolved = await pluginBuild.resolve(args.path, {\n          importer: args.importer,\n          kind: args.kind,\n          namespace: args.namespace,\n          resolveDir: args.resolveDir,\n          pluginData: { farmConfigExternal: true },\n        });\n\n        if (resolved.errors.length > 0 || !resolved.path) {\n          return { path: args.path, external: true };\n        }\n\n        return {\n          path: toExternalSpecifier(resolved.path),\n          external: true,\n          warnings: resolved.warnings,\n        };\n      });\n    },\n  };\n}\n\nexport async function loadFarmConfigFile<TConfig = Record<string, any>>(\n  configPath: string,\n  options: { root: string; cacheRoot?: string },\n): Promise<TConfig> {\n  const { build, transform } = await import(\"esbuild\");\n  const cacheRoot = path.resolve(options.cacheRoot || options.root);\n  const configCacheDir = path.join(cacheRoot, \".farm\", \".config-loader\");\n  await mkdir(configCacheDir, { recursive: true });\n\n  const modulePath = path.join(\n    configCacheDir,\n    `farm-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n  );\n\n  await build({\n    absWorkingDir: path.resolve(options.root),\n    entryPoints: [path.resolve(configPath)],\n    outfile: modulePath,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: `node${process.versions.node.split(\".\")[0]}`,\n    plugins: [createFarmConfigResolutionPlugin({ transform })],\n    jsx: \"automatic\",\n    logLevel: \"silent\",\n    sourcemap: \"inline\",\n  });\n\n  const moduleUrl = `${pathToFileURL(modulePath).href}?t=${Date.now()}`;\n  try {\n    const loaded = await import(/* @vite-ignore */ moduleUrl);\n    const config = loaded.default || loaded;\n    if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n      throw new TypeError(`Farm config ${configPath} must export an object`);\n    }\n    return config as TConfig;\n  } finally {\n    await unlink(modulePath).catch(() => undefined);\n  }\n}\n\nasync function onlyImportsFarmConfigHelpers(\n  importer: string,\n  transform: EsbuildTransform,\n): Promise<boolean> {\n  try {\n    const source = readFileSync(importer, \"utf8\");\n    if (!source.includes(FARM_CORE_PACKAGE)) return false;\n\n    const transformed = await transform(source, {\n      format: \"esm\",\n      jsx: \"automatic\",\n      loader: getEsbuildLoader(importer),\n      sourcefile: importer,\n    });\n    const references = [...transformed.code.matchAll(FARM_CORE_REFERENCE_RE)];\n    if (references.length === 0) return false;\n\n    const safeImportRanges: Array<{ start: number; end: number }> = [];\n    for (const match of transformed.code.matchAll(FARM_CONFIG_HELPER_IMPORT_RE)) {\n      const specifiers = match[1]\n        .split(\",\")\n        .map((specifier) => specifier.trim())\n        .filter(Boolean);\n      if (\n        specifiers.length === 0 ||\n        !specifiers.every((specifier) => FARM_CONFIG_HELPER_SPECIFIER_RE.test(specifier))\n      ) {\n        continue;\n      }\n\n      const start = match.index ?? 0;\n      safeImportRanges.push({ start, end: start + match[0].length });\n    }\n\n    return references.every((reference) => {\n      const index = reference.index ?? -1;\n      return safeImportRanges.some((range) => index >= range.start && index < range.end);\n    });\n  } catch {\n    // Unsupported syntax or non-file importers retain the existing package resolution path.\n    return false;\n  }\n}\n\nfunction getEsbuildLoader(file: string): \"js\" | \"jsx\" | \"ts\" | \"tsx\" {\n  switch (path.extname(file)) {\n    case \".ts\":\n    case \".mts\":\n    case \".cts\":\n      return \"ts\";\n    case \".tsx\":\n      return \"tsx\";\n    case \".jsx\":\n      return \"jsx\";\n    default:\n      return \"js\";\n  }\n}\n\nfunction normalizeLayerEntries(value: unknown, owner: string): string[] {\n  if (value === undefined) return [];\n  if (!Array.isArray(value)) {\n    throw new TypeError(`${owner} \"extends\" must be an array of layer paths or package names`);\n  }\n\n  return value.map((entry, index) => {\n    if (typeof entry !== \"string\" || entry.trim() === \"\") {\n      throw new TypeError(`${owner} \"extends\" entry ${index} must be a non-empty string`);\n    }\n    return entry.trim();\n  });\n}\n\nfunction resolveLayerSource(\n  source: string,\n  ownerRoot: string,\n): { root: string; configFile?: string } {\n  if (isPathLayerSource(source)) {\n    const target = source.startsWith(\"file:\")\n      ? path.resolve(ownerRoot, source.slice(\"file:\".length))\n      : path.resolve(ownerRoot, source);\n    if (!existsSync(target)) {\n      throw new Error(`Cannot resolve Farm layer ${JSON.stringify(source)} from ${ownerRoot}`);\n    }\n\n    const stats = statSync(target);\n    const root = stats.isDirectory() ? target : path.dirname(target);\n    return {\n      root: normalizeRealPath(root),\n      configFile: stats.isFile() ? normalizeRealPath(target) : undefined,\n    };\n  }\n\n  const requireFromOwner = createRequire(path.join(ownerRoot, \"package.json\"));\n  let packageJsonPath: string | undefined;\n  try {\n    packageJsonPath = requireFromOwner.resolve(`${source}/package.json`);\n  } catch {\n    // Packages with an exports map often hide package.json. Resolve their entry and walk upward.\n  }\n\n  if (packageJsonPath) {\n    return { root: normalizeRealPath(path.dirname(packageJsonPath)) };\n  }\n\n  try {\n    const entryPath = requireFromOwner.resolve(source);\n    const packageRoot = findNearestPackageRoot(entryPath);\n    if (packageRoot) return { root: normalizeRealPath(packageRoot) };\n  } catch {\n    // Use the common error below so local and package failures have the same shape.\n  }\n\n  throw new Error(`Cannot resolve Farm layer package ${JSON.stringify(source)} from ${ownerRoot}`);\n}\n\nfunction findNearestPackageRoot(entryPath: string): string | null {\n  let current = statSync(entryPath).isDirectory() ? entryPath : path.dirname(entryPath);\n  while (true) {\n    if (existsSync(path.join(current, \"package.json\"))) return current;\n    const parent = path.dirname(current);\n    if (parent === current) return null;\n    current = parent;\n  }\n}\n\nfunction findFarmConfigFile(root: string, explicitPath?: string): string | undefined {\n  if (explicitPath) return explicitPath;\n  for (const fileName of CONFIG_FILENAMES) {\n    const candidate = path.join(root, fileName);\n    if (existsSync(candidate)) return candidate;\n  }\n  return undefined;\n}\n\nfunction getLayerName(source: string, root: string): string {\n  if (!isPathLayerSource(source)) {\n    const packageName = source.split(\"/\").filter(Boolean).pop();\n    if (packageName) return sanitizeLayerName(packageName);\n  }\n\n  try {\n    const packageJson = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\"));\n    if (typeof packageJson.name === \"string\") {\n      return sanitizeLayerName(packageJson.name.split(\"/\").pop() || packageJson.name);\n    }\n  } catch {\n    // A local layer does not need package metadata.\n  }\n\n  return sanitizeLayerName(path.basename(root));\n}\n\nfunction sanitizeLayerName(value: string): string {\n  const name = value\n    .trim()\n    .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n  if (!name) throw new Error(`Cannot derive a name for Farm layer ${JSON.stringify(value)}`);\n  return name;\n}\n\nfunction normalizeLayerSrcDir(value: unknown): string {\n  if (value === undefined) return \"src\";\n  if (typeof value !== \"string\" || value.trim() === \"\" || path.isAbsolute(value)) {\n    throw new TypeError(\"A Farm layer srcDir must be a non-empty relative path\");\n  }\n  const normalized = path.normalize(value.trim());\n  if (normalized === \"..\" || normalized.startsWith(`..${path.sep}`)) {\n    throw new TypeError(\"A Farm layer srcDir cannot leave the layer root\");\n  }\n  return normalized;\n}\n\nfunction getLayerDefaults(config: Record<string, any>): Record<string, any> {\n  return Object.fromEntries(\n    Object.entries(config).filter(\n      ([key, value]) =>\n        key !== \"extends\" && value !== undefined && !LAYER_LOCAL_CONFIG_KEYS.has(key),\n    ),\n  );\n}\n\nfunction mergeFarmLayerConfig(\n  base: Record<string, any>,\n  override: Record<string, any>,\n): Record<string, any> {\n  const output: Record<string, any> = { ...base };\n\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined || key === \"layers\") continue;\n\n    if (key === \"plugins\") {\n      output[key] = [...toArray(output[key]), ...toArray(value)];\n      continue;\n    }\n\n    if (key === \"middleware\" && output[key] !== undefined) {\n      output[key] = [...toArray(output[key]), ...toArray(value)];\n      continue;\n    }\n\n    if ((key === \"redirects\" || key === \"rewrites\" || key === \"headers\") && output[key]) {\n      output[key] = mergeConfigListResolvers(output[key], value);\n      continue;\n    }\n\n    if (isPlainObject(output[key]) && isPlainObject(value)) {\n      output[key] = mergePlainObjects(output[key], value);\n      continue;\n    }\n\n    output[key] = value;\n  }\n\n  return output;\n}\n\nfunction mergePlainObjects(base: Record<string, any>, override: Record<string, any>) {\n  const output: Record<string, any> = { ...base };\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined) continue;\n    output[key] =\n      isPlainObject(output[key]) && isPlainObject(value)\n        ? mergePlainObjects(output[key], value)\n        : value;\n  }\n  return output;\n}\n\nfunction mergeConfigListResolvers(base: unknown, override: unknown) {\n  return async () => [...(await resolveConfigList(base)), ...(await resolveConfigList(override))];\n}\n\nasync function resolveConfigList(value: unknown): Promise<any[]> {\n  const resolved = typeof value === \"function\" ? await value() : value;\n  return toArray(resolved);\n}\n\nfunction toArray(value: unknown): any[] {\n  if (value === undefined || value === null) return [];\n  return Array.isArray(value) ? value : [value];\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, any> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPathLayerSource(source: string): boolean {\n  return (\n    source.startsWith(\".\") ||\n    source.startsWith(\"/\") ||\n    source.startsWith(\"file:\") ||\n    /^[a-zA-Z]:[\\\\/]/.test(source)\n  );\n}\n\nfunction normalizeRealPath(value: string): string {\n  return path.resolve(realpathSync(value));\n}\n","/**\n * Farm.js SSG (Static Site Generation) Module\n *\n * Handles collection and pre-rendering of SSG pages at build time.\n *\n * SSR is the default - pages render on each request\n * SSG is opt-in via `export const ssg = true`, Next-compatible route\n * config exports, or a top-of-file rendering directive.\n *\n * @example\n * ```tsx\n * // SSG Page\n * export const ssg = true;\n * export default function AboutPage() {\n *   return <h1>About</h1>;\n * }\n *\n * // SSG with ISR\n * export const ssg = true;\n * export const revalidate = 60;\n * export default async function ProductsPage() {\n *   const products = await fetchProducts();\n *   return <ProductList products={products} />;\n * }\n *\n * // Dynamic SSG\n * export const ssg = true;\n * export async function getStaticPaths() {\n *   const posts = await fetchPosts();\n *   return posts.map(post => ({ slug: post.slug }));\n * }\n * export default async function BlogPost({ params }) {\n *   return <article>{params.slug}</article>;\n * }\n *\n * // Next-compatible route config\n * export const dynamic = \"force-static\";\n * export const revalidate = 60;\n *\n * // PPR/static-shell route\n * export const experimental_ppr = true;\n * export const revalidate = 60;\n *\n * // Directive config\n * \"use ssg; 60\";\n * export default function DocsPage() {\n *   return <h1>Docs</h1>;\n * }\n * ```\n */\n\nimport { readFile } from \"fs/promises\";\nimport type {\n  RouteModule,\n  SSGPage,\n  SSGCollectionResult,\n  StaticPathParams,\n  StaticPathPrimitive,\n} from \"./types\";\n\ninterface RouteEntry {\n  path: string;\n  filePath: string;\n  isDynamic: boolean;\n  pattern: string;\n}\n\nexport type RouteRenderingDynamic = NonNullable<RouteModule[\"dynamic\"]>;\n\nexport interface RouteRenderingConfig {\n  ssg: boolean;\n  ppr: boolean;\n  revalidate?: number;\n  dynamic?: RouteRenderingDynamic;\n  directive?: string;\n}\n\nexport interface RouteRenderingOptions {\n  /**\n   * Whether `experimental.ppr` is enabled in the app config. Route-level PPR\n   * opt-ins (`ppr`, `experimental_ppr`, `\"use ppr\"`) are inert without it.\n   */\n  experimentalPPR?: boolean;\n}\n\nexport interface StaticRouteCandidateAnalysis {\n  candidate: boolean;\n  blockers: string[];\n}\n\ninterface DirectiveRenderingConfig {\n  ssg: boolean;\n  ppr: boolean;\n  revalidate?: number;\n  dynamic?: RouteRenderingDynamic;\n  directive: string;\n}\n\nconst OPTIONAL_CATCH_ALL_SEGMENT = /^\\[\\[\\.\\.\\.([^\\]]+)\\]\\]$/;\nconst REQUIRED_CATCH_ALL_SEGMENT = /^\\[\\.\\.\\.([^\\]]+)\\]$/;\nconst REQUIRED_DYNAMIC_SEGMENT = /^\\[([^\\]]+)\\]$/;\n\nconst REQUEST_API_LABELS = new Map<string, string>([\n  [\"cookies\", \"request cookies\"],\n  [\"headers\", \"request headers\"],\n  [\"getCurrentRequest\", \"the current Request\"],\n  [\"useSearchParams\", \"URL search parameters\"],\n  [\"auth\", \"request authentication\"],\n  [\"getServerSession\", \"request authentication\"],\n  [\"getSession\", \"request authentication\"],\n  [\"currentUser\", \"request authentication\"],\n]);\n\nconst ROUTE_PROP_LABELS = new Map<string, string>([\n  [\"searchParams\", \"URL search parameters\"],\n  [\"middleware\", \"middleware request data\"],\n  [\"middlewareData\", \"middleware request data\"],\n  [\"context\", \"request context\"],\n]);\n\n/**\n * Resolve route rendering from Farm exports, Next-compatible exports, and\n * top-of-file directives such as `\"use ssg\";` or `\"use ssg; 60\";`.\n */\nfunction resolveConfiguredRouteRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source?: string,\n  options?: RouteRenderingOptions,\n): RouteRenderingConfig {\n  const pprEnabled = options?.experimentalPPR === true;\n  const directiveConfig = parseRouteRenderingDirective(source);\n  let ssg = directiveConfig?.ssg ?? false;\n  let requestedPPR = directiveConfig?.ppr ?? false;\n  let revalidate = directiveConfig?.revalidate;\n  const moduleDynamic = normalizeDynamicMode(mod?.dynamic);\n  const dynamic = moduleDynamic ?? directiveConfig?.dynamic;\n  const hasExplicitSsg = typeof mod?.ssg === \"boolean\";\n  const hasExplicitPPR =\n    typeof mod?.ppr === \"boolean\" || typeof mod?.experimental_ppr === \"boolean\";\n\n  if (hasExplicitSsg) {\n    ssg = mod!.ssg === true;\n  }\n\n  if (hasExplicitPPR) {\n    requestedPPR = mod?.ppr === true || mod?.experimental_ppr === true;\n  }\n\n  if (typeof mod?.revalidate === \"number\") {\n    if (mod.revalidate > 0) {\n      revalidate = mod.revalidate;\n      // A PPR opt-in keeps the route dynamic even while experimental.ppr is\n      // off: the page expects Suspense holes, so falling back to ISR would\n      // bake request-time content into a shared static artifact.\n      if (!hasExplicitSsg && !requestedPPR) {\n        ssg = true;\n      }\n    } else {\n      revalidate = undefined;\n      if (!hasExplicitSsg) {\n        ssg = false;\n      }\n    }\n  } else if (mod?.revalidate === false) {\n    revalidate = undefined;\n  }\n\n  if (moduleDynamic === \"force-static\" || moduleDynamic === \"error\") {\n    ssg = true;\n    requestedPPR = false;\n  } else if (moduleDynamic === \"force-dynamic\") {\n    ssg = false;\n    requestedPPR = false;\n    revalidate = undefined;\n  }\n\n  const ppr = pprEnabled && !ssg && requestedPPR;\n\n  return {\n    ssg,\n    ppr,\n    revalidate: ssg || ppr ? revalidate : undefined,\n    dynamic,\n    directive: directiveConfig?.directive,\n  };\n}\n\n/**\n * Resolve the effective rendering mode. Direct request reads make an explicitly\n * static route dynamic so request-specific HTML cannot enter a shared artifact.\n */\nexport function resolveRouteRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source?: string,\n  options?: RouteRenderingOptions,\n): RouteRenderingConfig {\n  const rendering = resolveConfiguredRouteRenderingConfig(mod, source, options);\n  if (!rendering.ssg || !source) {\n    return rendering;\n  }\n\n  const requestBlockers = findRequestBoundSourceBlockers(source);\n  if (requestBlockers.length === 0) {\n    return rendering;\n  }\n\n  return {\n    ...rendering,\n    ssg: false,\n    revalidate: undefined,\n  };\n}\n\nexport async function resolveRouteRenderingConfigFromFile(\n  mod: RouteModule | null | undefined,\n  filePath: string,\n  options?: RouteRenderingOptions,\n): Promise<RouteRenderingConfig> {\n  const source = await readFile(filePath, \"utf8\").catch(() => undefined);\n  return resolveRouteRenderingConfig(mod, source, options);\n}\n\n/**\n * Conservatively identify a route that may be safe to pre-render.\n *\n * This intentionally produces a suggestion rather than changing rendering:\n * request-bound work can live in a transitive import, which source inspection\n * of the route module cannot prove safe. Explicit route config always wins.\n */\nexport function analyzeStaticRouteCandidate(\n  mod: RouteModule | null | undefined,\n  source: string | undefined,\n  options: { isDynamic?: boolean } = {},\n): StaticRouteCandidateAnalysis {\n  const blockers: string[] = [];\n\n  if (!source) {\n    blockers.push(\"route source is unavailable\");\n  }\n\n  if (options.isDynamic) {\n    blockers.push(\"the route has dynamic path segments\");\n  }\n\n  if (hasExplicitRenderingConfig(mod, source)) {\n    blockers.push(\"the route already has explicit rendering config\");\n  }\n\n  if (source) {\n    blockers.push(...findRequestBoundSourceBlockers(source));\n  }\n\n  return {\n    candidate: blockers.length === 0,\n    blockers,\n  };\n}\n\nfunction findRequestBoundSourceBlockers(source: string): string[] {\n  const blockers = new Set<string>();\n  const code = stripCommentsAndLiteralContents(source);\n\n  const sourceWithoutComments = stripComments(source);\n  for (const binding of readRequestApiImportBindings(sourceWithoutComments)) {\n    if (new RegExp(`\\\\b${escapeRegExp(binding.local)}\\\\s*(?:\\\\?\\\\.\\\\s*)?\\\\(`).test(code)) {\n      blockers.add(`the route reads ${binding.label}`);\n    }\n  }\n\n  for (const namespace of readNamespaceImportBindings(sourceWithoutComments)) {\n    for (const [name, label] of REQUEST_API_LABELS) {\n      if (\n        new RegExp(\n          `\\\\b${escapeRegExp(namespace)}\\\\s*(?:\\\\?\\\\.\\\\s*|\\\\.\\\\s*)${name}\\\\s*(?:\\\\?\\\\.\\\\s*)?\\\\(`,\n        ).test(code)\n      ) {\n        blockers.add(`the route reads ${label}`);\n      }\n    }\n  }\n\n  const params = readDefaultRouteParameters(code);\n  if (params) {\n    for (const [name, label] of ROUTE_PROP_LABELS) {\n      if (new RegExp(`\\\\b${name}\\\\b`).test(params)) {\n        blockers.add(`the route reads ${label}`);\n      }\n    }\n\n    const propsName = params.match(/^\\s*([A-Za-z_$][\\w$]*)\\s*(?::|,|$)/)?.[1];\n    if (propsName) {\n      for (const [name, label] of ROUTE_PROP_LABELS) {\n        if (new RegExp(`\\\\b${escapeRegExp(propsName)}\\\\s*\\\\.\\\\s*${name}\\\\b`).test(code)) {\n          blockers.add(`the route reads ${label}`);\n        }\n        if (\n          new RegExp(`\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}\\\\s*=\\\\s*${escapeRegExp(propsName)}\\\\b`).test(\n            code,\n          )\n        ) {\n          blockers.add(`the route reads ${label}`);\n        }\n      }\n    }\n  }\n\n  return [...blockers];\n}\n\nfunction readRequestApiImportBindings(source: string): Array<{ local: string; label: string }> {\n  const bindings: Array<{ local: string; label: string }> = [];\n  for (const clause of readStaticImportClauses(source)) {\n    const namedGroup = clause.match(/\\{([\\s\\S]*?)\\}/)?.[1];\n    for (const rawSpecifier of (namedGroup ?? \"\").split(\",\")) {\n      const specifier = rawSpecifier.trim().replace(/^type\\s+/, \"\");\n      const imported = specifier.match(/^([A-Za-z_$][\\w$]*)(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?$/);\n      if (!imported?.[1]) continue;\n      const label = REQUEST_API_LABELS.get(imported[1]);\n      if (label) bindings.push({ local: imported[2] ?? imported[1], label });\n    }\n\n    const local = clause.match(/^\\s*([A-Za-z_$][\\w$]*)\\s*(?:,|$)/)?.[1];\n    if (local) {\n      const label = REQUEST_API_LABELS.get(local);\n      if (label) bindings.push({ local, label });\n    }\n  }\n\n  return bindings;\n}\n\nfunction readNamespaceImportBindings(source: string): string[] {\n  return readStaticImportClauses(source)\n    .map((clause) => clause.match(/\\*\\s*as\\s*([A-Za-z_$][\\w$]*)/)?.[1])\n    .filter((binding): binding is string => Boolean(binding));\n}\n\nfunction readStaticImportClauses(source: string): string[] {\n  return [...source.matchAll(/\\bimport\\s+(?!\\()([\\s\\S]*?)\\s+from\\s*[\"'][^\"']+[\"']/g)]\n    .map((match) => match[1])\n    .filter((clause): clause is string => Boolean(clause));\n}\n\nfunction readDefaultRouteParameters(code: string): string | undefined {\n  const inlineParams =\n    code.match(/\\bexport\\s+default\\s+(?:async\\s+)?function\\b[^(]*\\(([^)]*)\\)/)?.[1] ??\n    code.match(/\\bexport\\s+default\\s+(?:async\\s+)?\\(([^)]*)\\)\\s*=>/)?.[1];\n  if (inlineParams !== undefined) return inlineParams;\n\n  const binding =\n    code.match(/\\bexport\\s+default\\s+([A-Za-z_$][\\w$]*)\\s*;?/)?.[1] ??\n    code.match(/\\bexport\\s*\\{\\s*([A-Za-z_$][\\w$]*)\\s+as\\s+default\\s*\\}/)?.[1];\n  if (!binding) return undefined;\n  const escapedBinding = escapeRegExp(binding);\n\n  return (\n    code.match(new RegExp(`\\\\bfunction\\\\s+${escapedBinding}\\\\s*\\\\(([^)]*)\\\\)`))?.[1] ??\n    code.match(\n      new RegExp(\n        `\\\\b(?:const|let|var)\\\\s+${escapedBinding}\\\\s*=\\\\s*(?:async\\\\s+)?\\\\(([^)]*)\\\\)\\\\s*=>`,\n      ),\n    )?.[1] ??\n    code.match(\n      new RegExp(`\\\\b(?:const|let|var)\\\\s+${escapedBinding}\\\\s*=\\\\s*function\\\\s*\\\\(([^)]*)\\\\)`),\n    )?.[1]\n  );\n}\n\nfunction stripCommentsAndLiteralContents(source: string): string {\n  return sanitizeSource(source, true);\n}\n\nfunction stripComments(source: string): string {\n  return sanitizeSource(source, false);\n}\n\nfunction sanitizeSource(source: string, maskLiterals: boolean): string {\n  const output = [...source];\n  const mask = (index: number) => {\n    if (output[index] !== \"\\n\" && output[index] !== \"\\r\") output[index] = \" \";\n  };\n\n  const scanQuoted = (start: number, quote: \"'\" | '\"'): number => {\n    let index = start;\n    if (maskLiterals) mask(index);\n    index += 1;\n    while (index < source.length) {\n      if (source[index] === \"\\\\\") {\n        if (maskLiterals) mask(index);\n        if (index + 1 < source.length && maskLiterals) mask(index + 1);\n        index += 2;\n        continue;\n      }\n      const character = source[index];\n      if (maskLiterals) mask(index);\n      index += 1;\n      if (character === quote) break;\n    }\n    return index;\n  };\n\n  const scanCode = (start: number, stopAtTemplateBrace: boolean): number => {\n    let index = start;\n    let braceDepth = 0;\n    while (index < source.length) {\n      const character = source[index];\n      const next = source[index + 1];\n      if (character === \"/\" && next === \"/\") {\n        while (index < source.length && source[index] !== \"\\n\" && source[index] !== \"\\r\") {\n          mask(index++);\n        }\n        continue;\n      }\n      if (character === \"/\" && next === \"*\") {\n        mask(index++);\n        mask(index++);\n        while (index < source.length) {\n          const closesComment = source[index] === \"*\" && source[index + 1] === \"/\";\n          mask(index++);\n          if (closesComment) {\n            mask(index++);\n            break;\n          }\n        }\n        continue;\n      }\n      if (character === \"'\" || character === '\"') {\n        index = scanQuoted(index, character);\n        continue;\n      }\n      if (character === \"`\") {\n        if (maskLiterals) mask(index);\n        index += 1;\n        while (index < source.length) {\n          if (source[index] === \"\\\\\") {\n            if (maskLiterals) mask(index);\n            if (index + 1 < source.length && maskLiterals) mask(index + 1);\n            index += 2;\n          } else if (source[index] === \"`\") {\n            if (maskLiterals) mask(index);\n            index += 1;\n            break;\n          } else if (source[index] === \"$\" && source[index + 1] === \"{\") {\n            if (maskLiterals) {\n              mask(index);\n              mask(index + 1);\n            }\n            index = scanCode(index + 2, true);\n          } else {\n            if (maskLiterals) mask(index);\n            index += 1;\n          }\n        }\n        continue;\n      }\n      if (character === \"{\") {\n        braceDepth += 1;\n      } else if (character === \"}\") {\n        if (stopAtTemplateBrace && braceDepth === 0) {\n          if (maskLiterals) mask(index);\n          return index + 1;\n        }\n        braceDepth = Math.max(0, braceDepth - 1);\n      }\n      index += 1;\n    }\n    return index;\n  };\n\n  scanCode(0, false);\n  return output.join(\"\");\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction hasExplicitRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source: string | undefined,\n): boolean {\n  return (\n    typeof mod?.ssg === \"boolean\" ||\n    typeof mod?.ppr === \"boolean\" ||\n    typeof mod?.experimental_ppr === \"boolean\" ||\n    typeof mod?.revalidate !== \"undefined\" ||\n    typeof mod?.dynamic !== \"undefined\" ||\n    typeof parseRouteRenderingDirective(source) !== \"undefined\"\n  );\n}\n\nexport function parseRouteRenderingDirective(\n  source: string | undefined,\n): DirectiveRenderingConfig | undefined {\n  if (!source) {\n    return undefined;\n  }\n\n  for (const directive of readDirectivePrologue(source)) {\n    const config = parseKnownRenderingDirective(directive);\n    if (config) {\n      return config;\n    }\n  }\n\n  return undefined;\n}\n\nfunction parseKnownRenderingDirective(directive: string): DirectiveRenderingConfig | undefined {\n  const normalized = directive.trim().toLowerCase();\n  const match = normalized.match(\n    /^use\\s+(ssg|static|isr|ssr|dynamic|ppr)(?:\\s*[;:]\\s*(\\d+))?\\s*;?$/,\n  );\n\n  if (!match?.[1]) {\n    return undefined;\n  }\n\n  const mode = match[1];\n  const revalidate = match[2] ? Number(match[2]) : undefined;\n\n  if (mode === \"ssr\" || mode === \"dynamic\") {\n    return {\n      ssg: false,\n      ppr: false,\n      dynamic: \"force-dynamic\",\n      directive,\n    };\n  }\n\n  if (mode === \"ppr\") {\n    return {\n      ssg: false,\n      ppr: true,\n      revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n      directive,\n    };\n  }\n\n  return {\n    ssg: true,\n    ppr: false,\n    dynamic: \"force-static\",\n    revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n    directive,\n  };\n}\n\nfunction normalizeDynamicMode(value: unknown): RouteRenderingDynamic | undefined {\n  switch (value) {\n    case \"auto\":\n    case \"force-static\":\n    case \"force-dynamic\":\n    case \"error\":\n      return value;\n    default:\n      return undefined;\n  }\n}\n\nfunction readDirectivePrologue(source: string): string[] {\n  const directives: string[] = [];\n  let index = skipTrivia(source, 0);\n\n  while (index < source.length) {\n    const parsed = readStringStatement(source, index);\n    if (!parsed) {\n      break;\n    }\n\n    directives.push(parsed.value);\n    index = skipTrivia(source, parsed.end);\n  }\n\n  return directives;\n}\n\nfunction skipTrivia(source: string, start: number): number {\n  let index = start;\n\n  while (index < source.length) {\n    const char = source[index];\n\n    if (char && /\\s/.test(char)) {\n      index += 1;\n      continue;\n    }\n\n    if (source.startsWith(\"//\", index)) {\n      const nextLine = source.indexOf(\"\\n\", index + 2);\n      index = nextLine === -1 ? source.length : nextLine + 1;\n      continue;\n    }\n\n    if (source.startsWith(\"/*\", index)) {\n      const end = source.indexOf(\"*/\", index + 2);\n      index = end === -1 ? source.length : end + 2;\n      continue;\n    }\n\n    break;\n  }\n\n  return index;\n}\n\nfunction readStringStatement(\n  source: string,\n  start: number,\n): { value: string; end: number } | undefined {\n  const quote = source[start];\n  if (quote !== '\"' && quote !== \"'\") {\n    return undefined;\n  }\n\n  let value = \"\";\n  let index = start + 1;\n\n  while (index < source.length) {\n    const char = source[index];\n    if (char === \"\\\\\") {\n      value += source.slice(index, index + 2);\n      index += 2;\n      continue;\n    }\n\n    if (char === quote) {\n      index += 1;\n      const semicolonIndex = skipHorizontalWhitespace(source, index);\n      const end = source[semicolonIndex] === \";\" ? semicolonIndex + 1 : index;\n      return { value, end };\n    }\n\n    value += char ?? \"\";\n    index += 1;\n  }\n\n  return undefined;\n}\n\nfunction skipHorizontalWhitespace(source: string, start: number): number {\n  let index = start;\n  while (source[index] === \" \" || source[index] === \"\\t\" || source[index] === \"\\r\") {\n    index += 1;\n  }\n  return index;\n}\n\n/**\n * Collect SSG pages from route modules\n *\n * Scans all routes and categorizes them into:\n * - SSG pages: Pre-rendered at build time\n * - SSR routes: Rendered on each request\n *\n * @param routes - Array of route entries\n * @param loadModule - Function to load a route module\n * @returns SSG pages and SSR routes\n */\nexport async function collectSSGPages(\n  routes: RouteEntry[],\n  loadModule: (filePath: string) => Promise<RouteModule>,\n  options: { suggestStaticRendering?: boolean } = {},\n): Promise<SSGCollectionResult> {\n  const ssgPages: SSGPage[] = [];\n  const ssrRoutes: string[] = [];\n  const staticCandidateRoutes: string[] = [];\n\n  for (const route of routes) {\n    try {\n      const mod = await loadModule(route.filePath);\n\n      if (!mod) {\n        ssrRoutes.push(route.path);\n        continue;\n      }\n\n      const source = await readFile(route.filePath, \"utf8\").catch(() => undefined);\n      const configuredRendering = resolveConfiguredRouteRenderingConfig(mod, source);\n      const rendering = resolveRouteRenderingConfig(mod, source);\n\n      if (configuredRendering.ssg && !rendering.ssg && source) {\n        const blockers = findRequestBoundSourceBlockers(source);\n        console.warn(\n          `[Farm.js] Static rendering disabled for \"${route.path}\" because ${blockers.join(\n            \" and \",\n          )}. Farm will render this route on each request instead.`,\n        );\n      }\n\n      // Check if page is marked for SSG\n      if (rendering.ssg) {\n        if (route.isDynamic) {\n          // Dynamic SSG route requires getStaticPaths\n          const getStaticPaths = mod.getStaticPaths || mod.generateStaticParams;\n\n          if (!getStaticPaths) {\n            throw new Error(\n              `Dynamic SSG route \"${route.path}\" requires getStaticPaths export. ` +\n                `Add: export function getStaticPaths() { return [{ paramName: 'value' }]; }`,\n            );\n          }\n\n          // Get all paths to pre-render\n          const paths = await getStaticPaths();\n\n          // Materialize every path before adding any of them. If one entry is\n          // invalid, the outer error handler can safely fall the whole route\n          // back to SSR without leaving a partial SSG manifest behind.\n          const materializedPages = paths.map((params) => ({\n            urlPath: materializeSSGRoutePath(route.path, params),\n            filePath: route.filePath,\n            params: normalizeStaticPathParams(params),\n            revalidate: rendering.revalidate,\n          }));\n\n          ssgPages.push(...materializedPages);\n        } else {\n          // Static SSG page\n          ssgPages.push({\n            urlPath: route.path,\n            filePath: route.filePath,\n            params: {},\n            revalidate: rendering.revalidate,\n          });\n        }\n      } else {\n        // SSR route (default)\n        ssrRoutes.push(route.path);\n\n        if (\n          options.suggestStaticRendering !== false &&\n          analyzeStaticRouteCandidate(mod, source, { isDynamic: route.isDynamic }).candidate\n        ) {\n          staticCandidateRoutes.push(route.path);\n        }\n      }\n    } catch (error) {\n      console.error(`Error processing route ${route.path}:`, error);\n      // Fall back to SSR for problematic routes\n      ssrRoutes.push(route.path);\n    }\n  }\n\n  if (staticCandidateRoutes.length > 0) {\n    const visibleRoutes = staticCandidateRoutes.slice(0, 10);\n    const remainingCount = staticCandidateRoutes.length - visibleRoutes.length;\n    const remainingSuffix = remainingCount > 0 ? `\\n  …and ${remainingCount} more` : \"\";\n\n    console.warn(\n      `[Farm.js] ${staticCandidateRoutes.length} route${\n        staticCandidateRoutes.length === 1 ? \" appears\" : \"s appear\"\n      } eligible for static rendering:\\n  ${visibleRoutes.join(\"\\n  \")}${remainingSuffix}\\n` +\n        `Add \\`export const dynamic = \"force-static\";\\` after verifying that imported code ` +\n        `does not read cookies, headers, authentication, or other request data.`,\n    );\n  }\n\n  return { ssg: ssgPages, ssr: ssrRoutes };\n}\n\nfunction materializeSSGRoutePath(routePattern: string, params: StaticPathParams): string {\n  const outputSegments: string[] = [];\n\n  for (const segment of routePattern.split(\"/\")) {\n    if (!segment) {\n      continue;\n    }\n\n    const optionalCatchAll = segment.match(OPTIONAL_CATCH_ALL_SEGMENT);\n    if (optionalCatchAll) {\n      const parameterName = optionalCatchAll[1]!;\n      const value = params[parameterName];\n      const values = readCatchAllSegments(value, {\n        optional: true,\n        parameterName,\n        routePattern,\n      });\n      outputSegments.push(...values.map(encodePathSegment));\n      continue;\n    }\n\n    const requiredCatchAll = segment.match(REQUIRED_CATCH_ALL_SEGMENT);\n    if (requiredCatchAll) {\n      const parameterName = requiredCatchAll[1]!;\n      const value = params[parameterName];\n      const values = readCatchAllSegments(value, {\n        optional: false,\n        parameterName,\n        routePattern,\n      });\n      outputSegments.push(...values.map(encodePathSegment));\n      continue;\n    }\n\n    const requiredDynamic = segment.match(REQUIRED_DYNAMIC_SEGMENT);\n    if (requiredDynamic) {\n      const parameterName = requiredDynamic[1]!;\n      const value = params[parameterName];\n      if (isStaticPathArray(value)) {\n        throw new Error(\n          `Cannot materialize SSG route \"${routePattern}\": parameter \"${parameterName}\" ` +\n            \"must be a scalar value; arrays are only supported for catch-all segments.\",\n        );\n      }\n      if (isMissingPathValue(value)) {\n        throw missingRequiredParameterError(routePattern, parameterName);\n      }\n      outputSegments.push(encodePathSegment(value));\n      continue;\n    }\n\n    outputSegments.push(segment);\n  }\n\n  return outputSegments.length > 0 ? `/${outputSegments.join(\"/\")}` : \"/\";\n}\n\nfunction readCatchAllSegments(\n  value: StaticPathParams[string] | undefined,\n  options: {\n    optional: boolean;\n    parameterName: string;\n    routePattern: string;\n  },\n): StaticPathPrimitive[] {\n  if (isMissingPathValue(value) || (isStaticPathArray(value) && value.length === 0)) {\n    if (options.optional) {\n      return [];\n    }\n    throw missingRequiredParameterError(options.routePattern, options.parameterName);\n  }\n\n  const segments = isStaticPathArray(value) ? [...value] : [value as StaticPathPrimitive];\n  if (segments.some(isMissingPathValue)) {\n    throw new Error(\n      `Cannot materialize SSG route \"${options.routePattern}\": catch-all parameter ` +\n        `\"${options.parameterName}\" contains an empty path segment.`,\n    );\n  }\n\n  return segments;\n}\n\nfunction normalizeStaticPathParams(params: StaticPathParams): Record<string, string> {\n  return Object.fromEntries(\n    Object.entries(params).map(([key, value]) => [\n      key,\n      isStaticPathArray(value) ? value.map(String).join(\"/\") : String(value),\n    ]),\n  );\n}\n\nfunction isMissingPathValue(value: unknown): value is \"\" | null | undefined {\n  return value === \"\" || value === null || typeof value === \"undefined\";\n}\n\nfunction isStaticPathArray(\n  value: StaticPathParams[string] | undefined,\n): value is readonly StaticPathPrimitive[] {\n  return Array.isArray(value);\n}\n\nfunction missingRequiredParameterError(routePattern: string, parameterName: string): Error {\n  return new Error(\n    `Cannot materialize SSG route \"${routePattern}\": required parameter ` +\n      `\"${parameterName}\" is missing or empty.`,\n  );\n}\n\nfunction encodePathSegment(value: StaticPathPrimitive): string {\n  const encoded = encodeURIComponent(String(value)).replace(\n    /[!'()*]/g,\n    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n\n  // Dot-only URL segments are normalized as navigation by URL parsers and\n  // filesystem joins. Pre-rendering them could therefore escape the intended\n  // route directory or overwrite a parent artifact. They cannot faithfully be\n  // represented as a static URL segment, so keep the route server-rendered.\n  if (encoded === \".\" || encoded === \"..\") {\n    throw new Error(\n      `Cannot materialize SSG path segment \"${encoded}\": dot-only segments are unsafe to prerender.`,\n    );\n  }\n\n  return encoded;\n}\n\n/**\n * Check if a route module is SSG\n */\nexport function isSSGModule(mod: RouteModule | null | undefined): boolean {\n  return resolveRouteRenderingConfig(mod).ssg;\n}\n\n/**\n * Check if a route module has ISR (Incremental Static Regeneration)\n */\nexport function hasISR(mod: RouteModule | null | undefined): boolean {\n  const rendering = resolveRouteRenderingConfig(mod);\n  return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n}\n\n/**\n * Get revalidation interval for a module\n */\nexport function getRevalidateInterval(mod: RouteModule | null | undefined): number | undefined {\n  return resolveRouteRenderingConfig(mod).revalidate;\n}\n\n/**\n * Check if a route module has PPR/static-shell caching enabled.\n */\nexport function hasPPR(\n  mod: RouteModule | null | undefined,\n  options?: RouteRenderingOptions,\n): boolean {\n  return resolveRouteRenderingConfig(mod, undefined, options).ppr;\n}\n\n/**\n * Generate SSG manifest for production builds\n */\nexport function generateSSGManifest(pages: SSGPage[]): string {\n  return JSON.stringify(\n    pages.map((page) => ({\n      urlPath: page.urlPath,\n      params: page.params,\n      revalidate: page.revalidate,\n    })),\n    null,\n    2,\n  );\n}\n\n/**\n * Check if a URL path matches an SSG page\n */\nexport function matchSSGPage(urlPath: string, ssgPages: SSGPage[]): SSGPage | undefined {\n  const normalizedPath = urlPath === \"/\" ? \"/\" : urlPath.replace(/\\/$/, \"\");\n  return ssgPages.find((page) => page.urlPath === normalizedPath);\n}\n","import type { ParsedRoute } from \"./types\";\nimport {\n  assertBrowserStableRoutePath,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n} from \"./routing/specificity\";\n\nexport const PROGRAMMATIC_ROUTE_FILE_NAMES = [\n  \"farm.route.ts\",\n  \"farm.route.tsx\",\n  \"farm.route.js\",\n  \"farm.route.jsx\",\n  \"farm.routes.ts\",\n  \"farm.routes.tsx\",\n  \"farm.routes.js\",\n  \"farm.routes.jsx\",\n  \"routes.ts\",\n  \"routes.tsx\",\n  \"routes.js\",\n  \"routes.jsx\",\n] as const;\n\nexport interface ProgrammaticRouteSearchClientOptions {\n  stripDefaults?: boolean | readonly string[];\n  preserve?: readonly string[];\n  temporary?: readonly string[];\n}\n\ntype ProgrammaticRouteSearchLike =\n  | { parse(value: unknown): unknown }\n  | ({\n      schema?: { parse(value: unknown): unknown };\n    } & ProgrammaticRouteSearchClientOptions);\n\nexport function getProgrammaticRouteSearchClientOptions(\n  search: ProgrammaticRouteSearchLike | undefined,\n): ProgrammaticRouteSearchClientOptions | undefined {\n  if (!search || \"parse\" in search) return undefined;\n\n  const options: ProgrammaticRouteSearchClientOptions = {};\n  if (typeof search.stripDefaults !== \"undefined\") options.stripDefaults = search.stripDefaults;\n  if (search.preserve?.length) options.preserve = [...search.preserve];\n  if (search.temporary?.length) options.temporary = [...search.temporary];\n\n  return Object.keys(options).length > 0 ? options : undefined;\n}\n\nexport function isProgrammaticRoutesFileName(fileName: string): boolean {\n  const normalized = fileName.replace(/\\\\/g, \"/\");\n  const baseName = normalized.split(\"/\").pop() || normalized;\n  return PROGRAMMATIC_ROUTE_FILE_NAMES.includes(\n    baseName as (typeof PROGRAMMATIC_ROUTE_FILE_NAMES)[number],\n  );\n}\n\nexport function createProgrammaticRouteModuleId(\n  filePath: string,\n  kind: \"page\" | \"layout\" | \"api\",\n  routePath: string,\n): string {\n  return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeProgrammaticRoutePath(routePath))}`;\n}\n\nexport function parseProgrammaticRouteModuleId(moduleId: string): {\n  filePath: string;\n  kind: \"page\" | \"layout\" | \"api\";\n  routePath: string;\n} | null {\n  const queryIndex = moduleId.indexOf(\"?\");\n  if (queryIndex === -1) return null;\n\n  const filePath = moduleId.slice(0, queryIndex);\n  const params = new URLSearchParams(moduleId.slice(queryIndex + 1));\n  const value = params.get(\"farm-route\");\n  if (!value) return null;\n\n  const separator = value.indexOf(\":\");\n  if (separator === -1) return null;\n\n  const kind = value.slice(0, separator);\n  if (kind !== \"page\" && kind !== \"layout\" && kind !== \"api\") return null;\n\n  return {\n    filePath,\n    kind,\n    routePath: normalizeProgrammaticRoutePath(value.slice(separator + 1)),\n  };\n}\n\nexport function parseProgrammaticRoutePath(\n  routePath: string,\n  type: ParsedRoute[\"type\"] = \"page\",\n): ParsedRoute {\n  const fileName = type === \"layout\" ? \"layout.tsx\" : \"page.tsx\";\n  const normalized = normalizeProgrammaticRoutePath(routePath);\n  assertTerminalCatchAll(normalized);\n  assertUniqueRouteParameters(normalized);\n  const filePath =\n    normalized === \"/\" ? fileName : `${normalized.slice(1).replace(/\\/+$/, \"\")}/${fileName}`;\n\n  return {\n    filePath,\n    segments: normalized\n      .split(\"/\")\n      .filter(Boolean)\n      .filter((segment) => !(segment.startsWith(\"(\") && segment.endsWith(\")\")))\n      .map(parseRouteSegment),\n    type,\n  };\n}\n\nexport function scanProgrammaticPagePaths(source: string): string[] {\n  const paths = new Set<string>();\n  const callRe = /\\b(?:page|createRoute)\\s*\\(\\s*([\"'`])([^\"'`]+)\\1/g;\n\n  for (const match of source.matchAll(callRe)) {\n    if (match[2]) paths.add(normalizeProgrammaticRoutePath(match[2]));\n  }\n\n  return Array.from(paths);\n}\n\nexport function normalizeProgrammaticRoutePath(routePath: string): string {\n  if (routePath.includes(\"?\") || routePath.includes(\"#\")) {\n    throw new TypeError(\n      `Programmatic route path \"${routePath}\" must be a pathname without a query string or hash.`,\n    );\n  }\n  const withSlash = routePath.startsWith(\"/\") ? routePath : `/${routePath}`;\n  const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n  assertBrowserStableRoutePath(withoutTrailing);\n  return withoutTrailing || \"/\";\n}\n\nfunction parseRouteSegment(segment: string): ParsedRoute[\"segments\"][number] {\n  if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n    let name = segment.slice(1, -1);\n    let isOptional = false;\n    let isCatchAll = false;\n\n    if (name.startsWith(\"[\") && name.endsWith(\"]\")) {\n      isOptional = true;\n      name = name.slice(1, -1);\n    }\n\n    if (name.startsWith(\"...\")) {\n      isCatchAll = true;\n      name = name.slice(3);\n    }\n\n    return { segment: name, isDynamic: true, isOptional, isCatchAll };\n  }\n\n  return { segment, isDynamic: false, isOptional: false, isCatchAll: false };\n}\n","import type { FarmI18nClientSnapshot } from \"./types\";\n\ntype SnapshotResolver = () => FarmI18nClientSnapshot | undefined;\n\nconst FARM_I18N_SNAPSHOT_RESOLVER = Symbol.for(\"farm.i18n.snapshotResolver\");\ntype GlobalWithI18nResolver = typeof globalThis & {\n  [FARM_I18N_SNAPSHOT_RESOLVER]?: SnapshotResolver;\n};\n\nexport function _setFarmI18nSnapshotResolver(resolver: SnapshotResolver | undefined): void {\n  (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER] = resolver;\n}\n\nexport function getActiveFarmI18nSnapshot(): FarmI18nClientSnapshot | undefined {\n  if (typeof window !== \"undefined\" && window.__FARM_I18N__) {\n    return window.__FARM_I18N__;\n  }\n  return (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER]?.();\n}\n","import { emitFarmEvent } from \"./observability\";\nimport { notifyFarmCacheInvalidation, notifyFarmCacheTask } from \"./cache-invalidation\";\nimport { getActiveFarmI18nSnapshot } from \"./i18n/bridge\";\n\nexport { applyFarmCacheInvalidations } from \"./cache-invalidation\";\n\nexport type RevalidateTagProfile =\n  | \"max\"\n  | \"default\"\n  | \"seconds\"\n  | \"minutes\"\n  | \"hours\"\n  | \"days\"\n  | \"weeks\"\n  | \"months\"\n  | { expire?: number };\n\nexport interface FarmCacheOptions {\n  /**\n   * Tag cached data so it can be invalidated with revalidateTag/updateTag.\n   */\n  tags?: readonly string[];\n  /**\n   * Path tags let revalidatePath invalidate data tied to a route.\n   */\n  paths?: readonly string[];\n  /**\n   * Time in seconds before the entry becomes stale. False means no TTL.\n   */\n  revalidate?: number | false;\n}\n\nexport interface FarmCacheSetOptions extends FarmCacheOptions {\n  createdAt?: number;\n}\n\nexport type RouteDataCacheKey = string | readonly unknown[];\n\nexport type FarmCacheInvalidationTarget =\n  | { key: RouteDataCacheKey }\n  | { path: string }\n  | { tag: string };\n\ndeclare const FARM_DEFINED_CACHE_KEY_DATA: unique symbol;\n\n/**\n * A regular Farm cache key carrying the data shape stored under that key.\n *\n * The brand exists only in TypeScript. At runtime the value remains the\n * original string or structured array, so all existing cache APIs continue to\n * accept untyped keys.\n */\nexport type DefinedCacheKey<TData, TKey extends RouteDataCacheKey = RouteDataCacheKey> = TKey & {\n  readonly [FARM_DEFINED_CACHE_KEY_DATA]: TData;\n};\n\nexport type CacheKeyFactory<\n  TData,\n  TArguments extends readonly unknown[],\n  TKey extends RouteDataCacheKey = RouteDataCacheKey,\n> = (...args: TArguments) => DefinedCacheKey<TData, TKey>;\n\nexport type InferCacheKeyData<TKey> =\n  TKey extends DefinedCacheKey<infer TData, RouteDataCacheKey> ? TData : unknown;\n\n/**\n * Optionally add a data type to an existing string/array cache-key factory.\n *\n * This helper does not introduce a new runtime key representation. Calling the\n * returned factory produces the exact key returned by `factory`.\n */\nexport function defineCacheKey<TData>() {\n  return <const TArguments extends readonly unknown[], const TKey extends RouteDataCacheKey>(\n    factory: (...args: TArguments) => TKey,\n  ): CacheKeyFactory<TData, TArguments, TKey> => {\n    if (typeof factory !== \"function\") {\n      throw new TypeError(\"defineCacheKey expects a key factory function.\");\n    }\n\n    return ((...args: TArguments) => {\n      const key = factory(...args);\n      if (typeof key !== \"string\" && !Array.isArray(key)) {\n        throw new TypeError(\n          \"A defined cache key factory must return a string or structured array.\",\n        );\n      }\n      return key as DefinedCacheKey<TData, TKey>;\n    }) as CacheKeyFactory<TData, TArguments, TKey>;\n  };\n}\n\nexport interface FarmCacheEntry<T = unknown> {\n  key: string;\n  value: T;\n  tags: readonly string[];\n  /**\n   * Adapter tag versions captured before the cached value was produced.\n   * A later version makes the entry stale across every server instance.\n   */\n  tagVersions?: Readonly<Record<string, number>>;\n  createdAt: number;\n  createdVersion?: number;\n  revalidate?: number | false;\n}\n\ninterface InternalFarmCacheEntry<T = unknown> {\n  key: string;\n  value: T;\n  tags: Set<string>;\n  tagVersions?: Readonly<Record<string, number>>;\n  createdAt: number;\n  createdVersion: number;\n  revalidate?: number | false;\n}\n\n/**\n * Asynchronous persistence contract used by distributed Farm caches.\n *\n * Implementations are responsible for serializing cache entries and making\n * tag version updates atomic when the backing service supports it.\n */\nexport interface FarmCacheAdapter {\n  readonly name?: string;\n  get<T = unknown>(key: string): Promise<FarmCacheEntry<T> | null | undefined>;\n  set<T = unknown>(key: string, entry: FarmCacheEntry<T>): Promise<void>;\n  delete(key: string): Promise<void>;\n  clear?(): Promise<void>;\n  getTagVersions?(tags: readonly string[]): Promise<Readonly<Record<string, number>>>;\n  invalidateTags?(tags: readonly string[]): Promise<void>;\n  /** Atomically acquire a short-lived regeneration lease. */\n  acquireLease?(key: string, ttlMs: number): Promise<string | null | undefined>;\n  /** Release the lease only when the supplied ownership token still matches. */\n  releaseLease?(key: string, token: string): Promise<void>;\n}\n\nexport interface FarmClientCacheUserConfig {\n  /**\n   * Module path, relative to the project root, whose default export is a\n   * client cache adapter (`defineClientCacheAdapter`). The module is bundled\n   * into the browser entry; the server never imports it.\n   */\n  adapter?: string;\n  /** Extra version salt, typically a build or deploy id; entries persisted under another salt are dropped. */\n  version?: string;\n  /** Debounce for persisted write-behind flushes, in milliseconds. */\n  flushDelayMs?: number;\n}\n\nexport interface FarmCacheUserConfig {\n  /** Shared cache implementation, for example a Redis-backed adapter. */\n  adapter?: FarmCacheAdapter;\n  /** Prefix isolating applications and deployments sharing one adapter. */\n  namespace?: string;\n  /** Browser cache persistence; see the client cache adapter documentation. */\n  client?: FarmClientCacheUserConfig;\n  /**\n   * Coordinate cache fills across processes when the adapter implements\n   * acquireLease/releaseLease. Set false to disable.\n   */\n  lease?:\n    | false\n    | {\n        ttlMs?: number;\n        waitTimeoutMs?: number;\n        pollIntervalMs?: number;\n      };\n}\n\nexport interface FarmCacheStorage {\n  getItem<T = unknown>(key: string): Promise<T | null>;\n  setItem<T = unknown>(key: string, value: T): Promise<unknown>;\n  removeItem(key: string): Promise<unknown>;\n  clear?(base?: string): Promise<unknown>;\n}\n\nexport interface StorageFarmCacheAdapterOptions {\n  /** Prefix used inside the supplied storage client. */\n  base?: string;\n}\n\n/**\n * Adapt a Farm/unstorage-compatible key-value client to the cache contract.\n *\n * This is a portable baseline adapter. Provider-specific adapters should use\n * their atomic increment/transaction primitives for tag invalidation.\n */\nexport function storageCacheAdapter(\n  storage: FarmCacheStorage,\n  options: StorageFarmCacheAdapterOptions = {},\n): FarmCacheAdapter {\n  if (!storage || typeof storage.getItem !== \"function\" || typeof storage.setItem !== \"function\") {\n    throw new TypeError(\"storageCacheAdapter expects a compatible storage client.\");\n  }\n\n  const base = normalizeCacheNamespace(options.base || \"farm-cache\");\n  const entryKey = (key: string) => `${base}:entry:${key}`;\n  const tagKey = (tag: string) => `${base}:tag:${tag}`;\n\n  return {\n    name: \"storage\",\n    get: <T>(key: string) => storage.getItem<FarmCacheEntry<T>>(entryKey(key)),\n    set: async <T>(key: string, entry: FarmCacheEntry<T>) => {\n      await storage.setItem(entryKey(key), entry);\n    },\n    delete: async (key: string) => {\n      await storage.removeItem(entryKey(key));\n    },\n    clear: storage.clear\n      ? async () => {\n          await storage.clear!(base);\n        }\n      : undefined,\n    getTagVersions: async (tags) => {\n      const versions = await Promise.all(\n        tags.map(async (tag) => {\n          const value = await storage.getItem<number>(tagKey(tag));\n          return [tag, normalizeAdapterVersion(value)] as const;\n        }),\n      );\n      return Object.fromEntries(versions);\n    },\n    invalidateTags: async (tags) => {\n      await Promise.all(\n        tags.map(async (tag) => {\n          const key = tagKey(tag);\n          const current = normalizeAdapterVersion(await storage.getItem<number>(key));\n          await storage.setItem(key, Math.max(Date.now(), current + 1));\n        }),\n      );\n    },\n  };\n}\n\nexport interface GetFarmCacheEntryOptions {\n  allowStale?: boolean;\n  now?: number;\n}\n\ninterface FarmCacheStaleEntry {\n  tags: Iterable<string>;\n  createdAt: number;\n  createdVersion?: number;\n  revalidate?: number | false;\n}\n\nexport class FarmDataCache {\n  private entries = new Map<string, InternalFarmCacheEntry>();\n  private inflight = new Map<string, Promise<unknown>>();\n  private invalidatedTagVersions = new Map<string, number>();\n  private version = 0;\n  private generation = 0;\n  private adapter?: FarmCacheAdapter;\n  private namespace = \"farm\";\n  private local = true;\n  private lease = {\n    enabled: true,\n    ttlMs: 10_000,\n    waitTimeoutMs: 10_000,\n    pollIntervalMs: 25,\n  };\n\n  constructor(config: FarmCacheUserConfig = {}) {\n    this.configure(config);\n  }\n\n  configure(config: FarmCacheUserConfig = {}): void {\n    this.generation++;\n    this.entries.clear();\n    this.inflight.clear();\n    this.invalidatedTagVersions.clear();\n    this.version = 0;\n    this.adapter = config.adapter;\n    this.namespace = normalizeCacheNamespace(config.namespace || \"farm\");\n    this.local = !config.adapter;\n    this.lease =\n      config.lease === false\n        ? { ...this.lease, enabled: false }\n        : {\n            enabled: true,\n            ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 10_000, \"cache.lease.ttlMs\"),\n            waitTimeoutMs: normalizePositiveDuration(\n              config.lease?.waitTimeoutMs,\n              10_000,\n              \"cache.lease.waitTimeoutMs\",\n            ),\n            pollIntervalMs: normalizePositiveDuration(\n              config.lease?.pollIntervalMs,\n              25,\n              \"cache.lease.pollIntervalMs\",\n            ),\n          };\n  }\n\n  get adapterName(): string {\n    return this.adapter?.name || (this.adapter ? \"custom\" : \"memory\");\n  }\n\n  get hasAdapter(): boolean {\n    return this.adapter !== undefined;\n  }\n\n  get size(): number {\n    return this.entries.size;\n  }\n\n  get<T>(key: string, options: GetFarmCacheEntryOptions = {}): T | undefined {\n    return this.getEntry<T>(key, options)?.value;\n  }\n\n  getEntry<T = unknown>(\n    key: string,\n    options: GetFarmCacheEntryOptions = {},\n  ): FarmCacheEntry<T> | undefined {\n    const entry = this.entries.get(key) as InternalFarmCacheEntry<T> | undefined;\n    if (!entry) {\n      emitFarmEvent({ type: \"cache.miss\", key });\n      return undefined;\n    }\n\n    const stale = this.isStale(entry, options.now);\n    if (stale) {\n      emitFarmEvent({\n        type: \"cache.stale\",\n        key,\n        tags: Array.from(entry.tags),\n        revalidate: entry.revalidate,\n      });\n    }\n\n    if (!options.allowStale && stale) {\n      emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n      return undefined;\n    }\n\n    emitFarmEvent({\n      type: \"cache.hit\",\n      key,\n      tags: Array.from(entry.tags),\n      revalidate: entry.revalidate,\n      stale,\n    });\n\n    return this.toPublicEntry(entry);\n  }\n\n  async getEntryAsync<T = unknown>(\n    key: string,\n    options: GetFarmCacheEntryOptions = {},\n  ): Promise<FarmCacheEntry<T> | undefined> {\n    if (this.local) {\n      const localEntry = this.getEntry<T>(key, options);\n      if (localEntry) return localEntry;\n    }\n\n    if (!this.adapter) {\n      return this.local ? undefined : this.getEntry<T>(key, options);\n    }\n\n    const generation = this.generation;\n    const adapter = this.adapter;\n    const namespace = this.namespace;\n    const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n    if (generation !== this.generation) return undefined;\n    if (!entry) {\n      emitFarmEvent({ type: \"cache.miss\", key });\n      return undefined;\n    }\n\n    assertFarmCacheEntry(entry, key);\n    const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);\n    if (generation !== this.generation) return undefined;\n    if (stale) {\n      emitFarmEvent({\n        type: \"cache.stale\",\n        key,\n        tags: [...entry.tags],\n        revalidate: entry.revalidate,\n      });\n      if (!options.allowStale) {\n        emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n        return undefined;\n      }\n    }\n\n    emitFarmEvent({\n      type: \"cache.hit\",\n      key,\n      tags: [...entry.tags],\n      revalidate: entry.revalidate,\n      stale,\n    });\n\n    if (this.local && !stale) {\n      this.hydrateLocalEntry(entry);\n    }\n    return { ...entry, key };\n  }\n\n  set<T>(key: string, value: T, options: FarmCacheSetOptions = {}): FarmCacheEntry<T> {\n    const tags = new Set<string>();\n    for (const tag of options.tags ?? []) {\n      tags.add(normalizeCacheTag(tag));\n    }\n    for (const routePath of options.paths ?? []) {\n      tags.add(createPathCacheTag(routePath));\n    }\n\n    const entry: InternalFarmCacheEntry<T> = {\n      key,\n      value,\n      tags,\n      tagVersions: undefined,\n      createdAt: options.createdAt ?? Date.now(),\n      createdVersion: ++this.version,\n      revalidate: normalizeRevalidate(options.revalidate),\n    };\n\n    this.entries.set(key, entry);\n    emitFarmEvent({\n      type: \"cache.set\",\n      key,\n      tags: Array.from(tags),\n      revalidate: entry.revalidate,\n    });\n    return this.toPublicEntry(entry);\n  }\n\n  async setAsync<T>(\n    key: string,\n    value: T,\n    options: FarmCacheSetOptions = {},\n    tagVersions?: Readonly<Record<string, number>>,\n  ): Promise<FarmCacheEntry<T>> {\n    return this.writeAsync(key, value, options, tagVersions);\n  }\n\n  private async writeAsync<T>(\n    key: string,\n    value: T,\n    options: FarmCacheSetOptions,\n    tagVersions?: Readonly<Record<string, number>>,\n    createdVersion?: number,\n  ): Promise<FarmCacheEntry<T>> {\n    const tags = normalizeCacheOptionsTags(options);\n    const capturedVersions =\n      tagVersions ?? (await this.getAdapterTagVersions(Array.from(tags.values())));\n    const entry: FarmCacheEntry<T> = {\n      key,\n      value,\n      tags: Array.from(tags),\n      tagVersions: capturedVersions,\n      createdAt: options.createdAt ?? Date.now(),\n      createdVersion: createdVersion ?? ++this.version,\n      revalidate: normalizeRevalidate(options.revalidate),\n    };\n\n    if (this.local) {\n      this.hydrateLocalEntry(entry);\n    }\n    if (this.adapter) {\n      await this.adapter.set(this.createAdapterKey(key), entry);\n    }\n\n    emitFarmEvent({\n      type: \"cache.set\",\n      key,\n      tags: [...entry.tags],\n      revalidate: entry.revalidate,\n    });\n    return entry;\n  }\n\n  delete(key: string): boolean {\n    const deleted = this.entries.delete(key);\n    emitFarmEvent({ type: \"cache.delete\", key, deleted });\n    return deleted;\n  }\n\n  async deleteAsync(key: string): Promise<boolean> {\n    const deleted = this.entries.delete(key);\n    if (this.adapter) {\n      await this.adapter.delete(this.createAdapterKey(key));\n    }\n    emitFarmEvent({ type: \"cache.delete\", key, deleted: this.adapter ? true : deleted });\n    return this.adapter ? true : deleted;\n  }\n\n  clear(): void {\n    const count = this.entries.size;\n    this.generation++;\n    this.entries.clear();\n    this.inflight.clear();\n    this.invalidatedTagVersions.clear();\n    this.version = 0;\n    emitFarmEvent({ type: \"cache.clear\", count });\n  }\n\n  async clearAsync(): Promise<void> {\n    this.clear();\n    await this.adapter?.clear?.();\n  }\n\n  isStale(entry: FarmCacheStaleEntry, now = Date.now()): boolean {\n    if (\n      typeof entry.revalidate === \"number\" &&\n      entry.revalidate >= 0 &&\n      now - entry.createdAt >= entry.revalidate * 1000\n    ) {\n      return true;\n    }\n\n    for (const tag of entry.tags) {\n      const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));\n      if (\n        typeof invalidatedVersion === \"number\" &&\n        typeof entry.createdVersion === \"number\" &&\n        invalidatedVersion > entry.createdVersion\n      ) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  async isStaleAsync(entry: FarmCacheEntry, now = Date.now()): Promise<boolean> {\n    if (this.adapter) {\n      return this.isAdapterEntryStale(entry, now);\n    }\n    return this.isStale(entry, now);\n  }\n\n  revalidateTag(\n    tag: string,\n    options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n  ): number {\n    const normalized = normalizeCacheTag(tag);\n    const count = this.invalidateTag(normalized);\n    emitFarmEvent(\n      options.source === \"updateTag\"\n        ? { type: \"cache.updateTag\", tag: normalized, count }\n        : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n    );\n    return count;\n  }\n\n  async revalidateTagAsync(\n    tag: string,\n    options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n  ): Promise<number> {\n    const normalized = normalizeCacheTag(tag);\n    const count = this.invalidateTag(normalized);\n    await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);\n    emitFarmEvent(\n      options.source === \"updateTag\"\n        ? { type: \"cache.updateTag\", tag: normalized, count }\n        : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n    );\n    return count;\n  }\n\n  revalidatePath(routePath: string): number {\n    const normalizedPath = normalizeRevalidatePath(routePath);\n    const pathTag = createPathCacheTag(normalizedPath);\n    const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n    const count = this.invalidateTag(pathTag);\n    emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n    if (pprCount > 0) {\n      emitFarmEvent({\n        type: \"ppr.shell.invalidated\",\n        route: normalizedPath,\n        reason: \"revalidatePath\",\n        count: pprCount,\n      });\n    }\n\n    return count;\n  }\n\n  async revalidatePathAsync(routePath: string): Promise<number> {\n    const normalizedPath = normalizeRevalidatePath(routePath);\n    const pathTag = createPathCacheTag(normalizedPath);\n    const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n    const count = this.invalidateTag(pathTag);\n    await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);\n    emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n    if (pprCount > 0) {\n      emitFarmEvent({\n        type: \"ppr.shell.invalidated\",\n        route: normalizedPath,\n        reason: \"revalidatePath\",\n        count: pprCount,\n      });\n    }\n\n    return count;\n  }\n\n  async getOrSet<T>(\n    key: string,\n    producer: () => Promise<T> | T,\n    options: FarmCacheOptions = {},\n  ): Promise<T> {\n    const cached = await this.getEntryAsync<T>(key);\n    if (cached) {\n      return cached.value;\n    }\n\n    const inflight = this.inflight.get(key) as Promise<T> | undefined;\n    if (inflight) {\n      emitFarmEvent({ type: \"cache.dedupe\", key });\n      return inflight;\n    }\n\n    const tags = Array.from(normalizeCacheOptionsTags(options));\n    const generation = this.generation;\n    const promise = this.fillCacheEntry(key, producer, options, tags, generation)\n      .catch((error) => {\n        emitFarmEvent({ type: \"cache.error\", key, operation: \"set\", error });\n        throw error;\n      })\n      .finally(() => {\n        if (this.inflight.get(key) === promise) {\n          this.inflight.delete(key);\n        }\n      });\n\n    this.inflight.set(key, promise);\n    return promise;\n  }\n\n  private async fillCacheEntry<T>(\n    key: string,\n    producer: () => Promise<T> | T,\n    options: FarmCacheOptions,\n    tags: readonly string[],\n    generation: number,\n  ): Promise<T> {\n    const adapter = this.adapter;\n    const namespace = this.namespace;\n    const lease = { ...this.lease };\n    const leaseKey = `${namespace}:lease:${key}`;\n    let leaseToken: string | null | undefined;\n\n    if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {\n      leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n      if (!leaseToken) {\n        const shared = await this.waitForAdapterEntry<T>(\n          key,\n          adapter,\n          namespace,\n          lease,\n          generation,\n        );\n        if (shared) {\n          emitFarmEvent({ type: \"cache.dedupe\", key });\n          return shared.value;\n        }\n        if (generation === this.generation) {\n          leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n        }\n      }\n    }\n\n    try {\n      const initialCreatedVersion = this.version;\n      const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);\n      const value = await producer();\n      if (generation === this.generation) {\n        await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);\n      }\n      return value;\n    } finally {\n      if (leaseToken && adapter?.releaseLease) {\n        await adapter.releaseLease(leaseKey, leaseToken);\n      }\n    }\n  }\n\n  private async waitForAdapterEntry<T>(\n    key: string,\n    adapter: FarmCacheAdapter,\n    namespace: string,\n    lease: typeof this.lease,\n    generation: number,\n  ): Promise<FarmCacheEntry<T> | undefined> {\n    const deadline = Date.now() + lease.waitTimeoutMs;\n    while (Date.now() < deadline) {\n      await delay(lease.pollIntervalMs);\n      if (generation !== this.generation) return undefined;\n      const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n      if (generation !== this.generation) return undefined;\n      if (!entry) {\n        emitFarmEvent({ type: \"cache.miss\", key });\n        continue;\n      }\n      assertFarmCacheEntry(entry, key);\n      const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);\n      if (generation !== this.generation) return undefined;\n      if (stale) {\n        emitFarmEvent({\n          type: \"cache.stale\",\n          key,\n          tags: [...entry.tags],\n          revalidate: entry.revalidate,\n        });\n        emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n      } else {\n        emitFarmEvent({\n          type: \"cache.hit\",\n          key,\n          tags: [...entry.tags],\n          revalidate: entry.revalidate,\n          stale: false,\n        });\n        return { ...entry, key };\n      }\n    }\n    return undefined;\n  }\n\n  private countEntriesForTag(tag: string): number {\n    let count = 0;\n    for (const entry of this.entries.values()) {\n      if (entry.tags.has(tag)) {\n        count++;\n      }\n    }\n    return count;\n  }\n\n  private countEntriesForTags(tags: readonly string[]): number {\n    let count = 0;\n    for (const entry of this.entries.values()) {\n      if (tags.every((tag) => entry.tags.has(tag))) {\n        count++;\n      }\n    }\n    return count;\n  }\n\n  private invalidateTag(normalizedTag: string): number {\n    this.invalidatedTagVersions.set(normalizedTag, ++this.version);\n    return this.countEntriesForTag(normalizedTag);\n  }\n\n  private toPublicEntry<T>(entry: InternalFarmCacheEntry<T>): FarmCacheEntry<T> {\n    return {\n      key: entry.key,\n      value: entry.value,\n      tags: Array.from(entry.tags),\n      tagVersions: entry.tagVersions,\n      createdAt: entry.createdAt,\n      createdVersion: entry.createdVersion,\n      revalidate: entry.revalidate,\n    };\n  }\n\n  private hydrateLocalEntry<T>(entry: FarmCacheEntry<T>): void {\n    this.entries.set(entry.key, {\n      key: entry.key,\n      value: entry.value,\n      tags: new Set(entry.tags.map(normalizeCacheTag)),\n      tagVersions: entry.tagVersions,\n      createdAt: entry.createdAt,\n      createdVersion: entry.createdVersion ?? ++this.version,\n      revalidate: normalizeRevalidate(entry.revalidate),\n    });\n  }\n\n  private createAdapterKey(key: string): string {\n    return `${this.namespace}:entry:${key}`;\n  }\n\n  private createAdapterTag(tag: string): string {\n    return `${this.namespace}:tag:${tag}`;\n  }\n\n  private async getAdapterTagVersions(\n    tags: readonly string[],\n    adapter = this.adapter,\n    namespace = this.namespace,\n  ): Promise<Readonly<Record<string, number>>> {\n    if (!adapter?.getTagVersions || tags.length === 0) return {};\n\n    const normalized = tags.map(normalizeCacheTag);\n    const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);\n    const versions = await adapter.getTagVersions(physicalTags);\n    return Object.fromEntries(\n      normalized.map((tag, index) => [\n        tag,\n        normalizeAdapterVersion(versions[physicalTags[index]!]),\n      ]),\n    );\n  }\n\n  private async isAdapterEntryStale(\n    entry: FarmCacheEntry,\n    now = Date.now(),\n    adapter = this.adapter,\n    namespace = this.namespace,\n  ): Promise<boolean> {\n    if (\n      typeof entry.revalidate === \"number\" &&\n      entry.revalidate >= 0 &&\n      now - entry.createdAt >= entry.revalidate * 1000\n    ) {\n      return true;\n    }\n\n    const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);\n    for (const tag of entry.tags) {\n      if (\n        normalizeAdapterVersion(currentVersions[tag]) >\n        normalizeAdapterVersion(entry.tagVersions?.[tag])\n      ) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n\nconst FARM_DATA_CACHE_SYMBOL = Symbol.for(\"farm.dataCache\");\nconst farmDataCacheGlobal = globalThis as typeof globalThis & {\n  [FARM_DATA_CACHE_SYMBOL]?: FarmDataCache;\n};\nconst sharedFarmDataCache = (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ??= new FarmDataCache());\n\nexport function getFarmDataCache(): FarmDataCache {\n  return sharedFarmDataCache;\n}\n\nexport function configureFarmCache(config: FarmCacheUserConfig | undefined): void {\n  sharedFarmDataCache.configure(config);\n}\n\n/**\n * Wrap an async function so its results are cached and shared across requests,\n * processes, and restarts.\n *\n * The cache key is built from the wrapped function's identity (its name and a\n * hash of its source), the active locale, `keyParts`, and the call arguments.\n * Deriving identity from the source — rather than the closure instance — is\n * deliberate: it keeps the key stable across processes and restarts so a\n * distributed cache adapter can share entries between server instances.\n *\n * The consequence is that two closures with **identical source text but\n * different captured variables** produce the same identity. Pass those captured\n * values in `keyParts` so they take part in the key; otherwise the closures\n * share a cache entry and return each other's data:\n *\n * ```ts\n * // Collides: both closures have identical source, and `table` is captured,\n * // not an argument, so it never reaches the key.\n * const makeLoader = (table: string) =>\n *   unstable_cache(async (id: number) => db.get(table, id));\n *\n * // Correct: the captured value disambiguates the two closures.\n * const makeLoader = (table: string) =>\n *   unstable_cache(async (id: number) => db.get(table, id), [table]);\n * ```\n *\n * Values passed as call arguments already participate in the key and do not\n * need to be repeated in `keyParts`.\n *\n * @param fn The async function to memoize.\n * @param keyParts Extra values that identify this call site. Include every\n *   variable the function closes over that is not one of its arguments.\n * @param options Tags, paths, and revalidation settings for the cached entry.\n */\nexport function unstable_cache<Args extends unknown[], Result>(\n  fn: (...args: Args) => Result | Promise<Result>,\n  keyParts: readonly unknown[] = [],\n  options: FarmCacheOptions = {},\n): (...args: Args) => Promise<Result> {\n  return async (...args: Args): Promise<Result> => {\n    const locale = getActiveFarmI18nSnapshot()?.locale;\n    const key = createFarmCacheKey([\n      \"unstable_cache\",\n      getFunctionCacheIdentity(fn),\n      locale ? [\"locale\", locale] : null,\n      keyParts,\n      args,\n    ]);\n    return getFarmDataCache().getOrSet<Result>(key, () => fn(...args), options);\n  };\n}\n\n/**\n * Invalidate every cache entry carrying `tag`.\n *\n * Observability note: the `count` on the emitted `cache.revalidateTag` event is\n * derived from Farm's process-local entry tracking. With a shared `cache.adapter`\n * configured, entries live in the adapter rather than in local memory, so the\n * count can read as `0` even though the invalidation is still propagated to the\n * adapter and applied. Treat it as a best-effort signal, not a distributed count.\n */\nexport function revalidateTag(_tag: string, _profile?: RevalidateTagProfile): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache\n      .revalidateTagAsync(_tag, {\n        source: \"revalidateTag\",\n        profile: _profile,\n      })\n      .then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidateTag(_tag, {\n    source: \"revalidateTag\",\n    profile: _profile,\n  });\n}\n\nexport function updateTag(tag: string): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache.revalidateTagAsync(tag, { source: \"updateTag\" }).then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidateTag(tag, { source: \"updateTag\" });\n}\n\n/**\n * Invalidate cached data for a route path (and its PPR shell, if any).\n *\n * Observability note: the `count` on the emitted `cache.revalidatePath` event and\n * the `ppr.shell.invalidated` event are derived from process-local entry tracking.\n * With a shared `cache.adapter`, PPR shells live in the adapter rather than in\n * local memory, so the count can read as `0` and `ppr.shell.invalidated` may not\n * be emitted even though the invalidation is still propagated to the adapter and\n * applied.\n */\nexport function revalidatePath(routePath: string): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache.revalidatePathAsync(routePath).then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidatePath(routePath);\n}\n\nexport function invalidate(key: RouteDataCacheKey): void | Promise<void> {\n  const clientKey = createRouteDataCacheKey(key);\n  const task = updateTag(createRouteDataCacheTag(key));\n  notifyFarmCacheInvalidation(clientKey);\n  return task;\n}\n\nexport function invalidateRouteData(key: RouteDataCacheKey): void | Promise<void> {\n  return invalidate(key);\n}\n\n/**\n * Apply a normalized set of invalidation targets and return browser cache keys\n * that should be carried with an action/endpoint response.\n */\nexport async function applyFarmCacheInvalidationTargets(\n  targets: readonly FarmCacheInvalidationTarget[],\n): Promise<readonly string[]> {\n  if (!Array.isArray(targets)) {\n    throw new TypeError(\"Cache invalidations must resolve to an array of targets.\");\n  }\n\n  const clientKeys: string[] = [];\n  for (const target of targets) {\n    assertFarmCacheInvalidationTarget(target);\n    if (\"key\" in target) {\n      await invalidate(target.key);\n      clientKeys.push(createRouteDataCacheKey(target.key));\n    } else if (\"path\" in target) {\n      await revalidatePath(target.path);\n    } else {\n      await updateTag(target.tag);\n    }\n  }\n  return Array.from(new Set(clientKeys));\n}\n\nexport function createPathCacheTag(routePath: string): string {\n  return `path:${normalizeRevalidatePath(routePath)}`;\n}\n\nexport function createRouteDataCacheTag(key: RouteDataCacheKey): string {\n  return `route-data:${createRouteDataCacheKey(key)}`;\n}\n\nexport function createRouteDataCacheKey(key: RouteDataCacheKey): string {\n  return createFarmCacheKey(Array.isArray(key) ? key : [key]);\n}\n\nexport function normalizeRevalidatePath(routePath: string): string {\n  if (typeof routePath !== \"string\") {\n    throw new TypeError(\"revalidatePath expects a path string.\");\n  }\n\n  let normalized = routePath.trim();\n  if (!normalized) {\n    throw new Error(\"revalidatePath expects a non-empty path.\");\n  }\n\n  try {\n    if (/^https?:\\/\\//i.test(normalized)) {\n      normalized = new URL(normalized).pathname;\n    }\n  } catch {\n    // Keep the original path if URL parsing fails.\n  }\n\n  normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;\n  normalized = normalized.startsWith(\"/\") ? normalized : `/${normalized}`;\n  normalized = normalized.replace(/\\/{2,}/g, \"/\");\n  if (normalized.length > 1) {\n    normalized = normalized.replace(/\\/+$/, \"\");\n  }\n  return normalized || \"/\";\n}\n\nexport function createFarmCacheKey(parts: readonly unknown[]): string {\n  return stableSerialize(parts);\n}\n\nfunction normalizeRevalidate(revalidate: number | false | undefined): number | false | undefined {\n  if (revalidate === false || revalidate === undefined) {\n    return revalidate;\n  }\n  if (!Number.isFinite(revalidate) || revalidate < 0) {\n    return undefined;\n  }\n  // 0 is meaningful: the entry is stale immediately, i.e. always re-produced.\n  return revalidate;\n}\n\nfunction normalizeCacheTag(tag: string): string {\n  if (typeof tag !== \"string\") {\n    throw new TypeError(\"Cache tags must be strings.\");\n  }\n  const normalized = tag.trim();\n  if (!normalized) {\n    throw new Error(\"Cache tags cannot be empty.\");\n  }\n  return normalized;\n}\n\nfunction normalizeCacheNamespace(namespace: string): string {\n  if (typeof namespace !== \"string\") {\n    throw new TypeError(\"Cache namespace must be a string.\");\n  }\n  const normalized = namespace.trim().replace(/:+$/g, \"\");\n  if (!normalized) {\n    throw new Error(\"Cache namespace cannot be empty.\");\n  }\n  return normalized;\n}\n\nfunction normalizeAdapterVersion(value: unknown): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\n}\n\nfunction normalizePositiveDuration(\n  value: number | undefined,\n  fallback: number,\n  name: string,\n): number {\n  if (value === undefined) return fallback;\n  if (!Number.isFinite(value) || value <= 0) {\n    throw new TypeError(`${name} must be a positive number of milliseconds.`);\n  }\n  return Math.floor(value);\n}\n\nfunction delay(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction normalizeCacheOptionsTags(options: FarmCacheOptions): Set<string> {\n  const tags = new Set<string>();\n  for (const tag of options.tags ?? []) {\n    tags.add(normalizeCacheTag(tag));\n  }\n  for (const routePath of options.paths ?? []) {\n    tags.add(createPathCacheTag(routePath));\n  }\n  return tags;\n}\n\nfunction assertFarmCacheEntry(\n  entry: FarmCacheEntry,\n  expectedKey: string,\n): asserts entry is FarmCacheEntry {\n  if (\n    !entry ||\n    typeof entry !== \"object\" ||\n    entry.key !== expectedKey ||\n    !Array.isArray(entry.tags) ||\n    typeof entry.createdAt !== \"number\"\n  ) {\n    throw new TypeError(\n      `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`,\n    );\n  }\n}\n\nfunction assertFarmCacheInvalidationTarget(\n  target: unknown,\n): asserts target is FarmCacheInvalidationTarget {\n  if (!target || typeof target !== \"object\") {\n    throw new TypeError(\"Cache invalidation targets must be { key }, { path }, or { tag }.\");\n  }\n\n  if (\"key\" in target) {\n    const key = (target as { key?: unknown }).key;\n    if (typeof key === \"string\" || Array.isArray(key)) return;\n  } else if (\"path\" in target && typeof (target as { path?: unknown }).path === \"string\") {\n    return;\n  } else if (\"tag\" in target && typeof (target as { tag?: unknown }).tag === \"string\") {\n    return;\n  }\n\n  throw new TypeError(\"Cache invalidation targets must contain a string/array key, path, or tag.\");\n}\n\nfunction getFunctionCacheIdentity(fn: Function): string {\n  // The name alone collides across modules — two different functions both\n  // named getUser would share cache entries. Include a hash of the source so\n  // only genuinely identical functions share, and the identity stays stable\n  // across processes and restarts.\n  const name = fn.name || \"anonymous\";\n  return `${name}:${hashFunctionSource(String(fn))}`;\n}\n\nfunction hashFunctionSource(source: string): string {\n  // FNV-1a, 32-bit.\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < source.length; index++) {\n    hash ^= source.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(36);\n}\n\nfunction compareCodepoint(a: string, b: string): number {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction serializeBinaryBytes(bytes: Uint8Array): string {\n  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction stableSerialize(value: unknown, seen = new WeakSet<object>()): string {\n  if (value === null) return \"null\";\n  if (value === undefined) return \"undefined\";\n\n  const valueType = typeof value;\n  if (valueType === \"string\") return JSON.stringify(value);\n  if (valueType === \"number\" || valueType === \"boolean\" || valueType === \"bigint\") {\n    return `${valueType}:${String(value)}`;\n  }\n  if (valueType === \"symbol\") {\n    return `symbol:${String(value)}`;\n  }\n  if (valueType === \"function\") {\n    return `function:${getFunctionCacheIdentity(value as Function)}`;\n  }\n\n  if (value instanceof Date) {\n    // toISOString throws on an Invalid Date. Key building must not throw on a\n    // supported type, so all invalid dates share one stable marker and the\n    // caller's own validation decides what to do with the input.\n    return Number.isNaN(value.getTime()) ? \"date:invalid\" : `date:${value.toISOString()}`;\n  }\n  if (value instanceof URL) {\n    return `url:${value.toString()}`;\n  }\n  if (value instanceof RegExp) {\n    return `regexp:${value.toString()}`;\n  }\n  if (value instanceof ArrayBuffer) {\n    return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n  }\n  if (typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer) {\n    return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n  }\n  if (ArrayBuffer.isView(value)) {\n    const viewType = Object.prototype.toString.call(value).slice(8, -1);\n    const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n    return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;\n  }\n\n  if (value && typeof value === \"object\") {\n    if (seen.has(value)) {\n      return \"[Circular]\";\n    }\n    seen.add(value);\n\n    if (Array.isArray(value)) {\n      const items: string[] = [];\n      for (let index = 0; index < value.length; index++) {\n        items.push(\n          Object.prototype.hasOwnProperty.call(value, index)\n            ? stableSerialize(value[index], seen)\n            : \"[Hole]\",\n        );\n      }\n      seen.delete(value);\n      return `[${items.join(\",\")}]`;\n    }\n\n    // Set and Map keep their contents internally, so Object.entries is empty\n    // for both. Serialize the contents and sort them by codepoint so equal\n    // contents give the same key regardless of insertion order.\n    if (value instanceof Set) {\n      const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);\n      seen.delete(value);\n      return `set:[${items.join(\",\")}]`;\n    }\n    if (value instanceof Map) {\n      const items = Array.from(\n        value,\n        ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`,\n      ).sort(compareCodepoint);\n      seen.delete(value);\n      return `map:[${items.join(\",\")}]`;\n    }\n\n    // Codepoint comparison, not localeCompare: the host locale must not\n    // change how a \"stable\" key serializes, or invalidations computed on one\n    // server can miss entries written by another.\n    const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>\n      compareCodepoint(a, b),\n    );\n    const serialized = entries\n      .map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`)\n      .join(\",\");\n\n    seen.delete(value);\n    return `{${serialized}}`;\n  }\n\n  return String(value);\n}\n","import type { FarmConfig, FarmContextFactoryInput } from \"./types\";\n\nexport const FARM_ROUTE_CONTEXT_SYMBOL = Symbol.for(\"farm.routeContext\");\n\nexport type FarmRouteContextCarrier<TContext = unknown> = {\n  [FARM_ROUTE_CONTEXT_SYMBOL]?: TContext;\n};\n\nexport async function resolveFarmRouteContext(\n  config: Pick<FarmConfig, \"context\">,\n  input: FarmContextFactoryInput,\n): Promise<unknown> {\n  if (typeof config.context !== \"function\") {\n    return undefined;\n  }\n\n  return config.context(input);\n}\n\nexport function withFarmRouteContext<TProps extends object, TContext>(\n  props: TProps,\n  context: TContext | undefined,\n): TProps & FarmRouteContextCarrier<TContext> {\n  if (context === undefined) {\n    return props as TProps & FarmRouteContextCarrier<TContext>;\n  }\n\n  Object.defineProperty(props, FARM_ROUTE_CONTEXT_SYMBOL, {\n    value: context,\n    enumerable: false,\n    configurable: true,\n  });\n\n  return props as TProps & FarmRouteContextCarrier<TContext>;\n}\n\nexport function getFarmRouteContext<TContext = unknown>(props: unknown): TContext | undefined {\n  if (!props || typeof props !== \"object\") {\n    return undefined;\n  }\n\n  return (props as FarmRouteContextCarrier<TContext>)[FARM_ROUTE_CONTEXT_SYMBOL];\n}\n","import type { ComponentType } from \"react\";\nimport {\n  createFarmCacheKey,\n  createRouteDataCacheTag,\n  getFarmDataCache,\n  type FarmCacheOptions,\n  type RouteDataCacheKey,\n} from \"./cache\";\nimport { getFarmRouteContext } from \"./route-context\";\nimport { normalizeFarmRouteRuntimeConfig, type FarmRouteRuntimeConfig } from \"./route-runtime\";\nimport type { ServerFn } from \"./server-fn\";\nimport type { FarmServerRendererRuntime } from \"./renderer\";\nimport { parseProgrammaticRoutePath as parseSharedProgrammaticRoutePath } from \"./routes-shared\";\nimport type {\n  FarmAppContext,\n  LayoutProps,\n  Metadata,\n  PageProps,\n  ParsedRoute,\n  PluginContextProps,\n  RouteModule,\n} from \"./types\";\n\nexport type ProgrammaticRouteRenderMode = \"static\" | \"dynamic\";\nexport type ProgrammaticRouteMethod =\n  | \"GET\"\n  | \"HEAD\"\n  | \"QUERY\"\n  | \"POST\"\n  | \"PUT\"\n  | \"DELETE\"\n  | \"PATCH\"\n  | \"OPTIONS\";\n\nexport type ProgrammaticRoutePrimitive = string | number | boolean;\nexport type ProgrammaticStaticPathParams = Record<\n  string,\n  ProgrammaticRoutePrimitive | readonly ProgrammaticRoutePrimitive[]\n>;\nexport type ProgrammaticStaticPath =\n  | string\n  | readonly ProgrammaticRoutePrimitive[]\n  | ProgrammaticStaticPathParams;\nexport type ProgrammaticStaticPaths = () =>\n  | readonly ProgrammaticStaticPath[]\n  | Promise<readonly ProgrammaticStaticPath[]>;\n\nexport interface ProgrammaticRouteSchema<TOutput = unknown> {\n  parse(value: unknown): TOutput;\n}\n\nexport interface ProgrammaticRouteSearchOptions<TOutput = ProgrammaticRouteSearchFallback> {\n  schema?: ProgrammaticRouteSchema<TOutput>;\n  stripDefaults?: boolean | readonly string[];\n  preserve?: readonly string[];\n  temporary?: readonly string[];\n}\n\nexport type ProgrammaticRouteSearchConfig<TOutput = ProgrammaticRouteSearchFallback> =\n  | ProgrammaticRouteSchema<TOutput>\n  | ProgrammaticRouteSearchOptions<TOutput>;\n\nexport type InferProgrammaticRouteSchema<TSchema, TFallback> =\n  TSchema extends ProgrammaticRouteSchema<infer TOutput> ? TOutput : TFallback;\n\nexport type InferProgrammaticRouteSearch<TSearch, TFallback> =\n  TSearch extends ProgrammaticRouteSearchOptions<infer TOutput>\n    ? TOutput\n    : TSearch extends ProgrammaticRouteSchema<infer TOutput>\n      ? TOutput\n      : TFallback;\n\nexport type ProgrammaticRouteParamsFallback = Record<string, string>;\nexport type ProgrammaticRouteSearchFallback = Record<string, string | string[] | undefined>;\nexport type ProgrammaticRouteMaybePromise<T> = T | Promise<T>;\nexport type ProgrammaticRouteAction = ServerFn<any, any, any>;\nexport type ProgrammaticRouteActions = Readonly<Record<string, ProgrammaticRouteAction>>;\nexport type ProgrammaticRouteDefaultAction<\n  TActions extends ProgrammaticRouteActions,\n  TDefaultAction extends keyof TActions | undefined,\n> = [TDefaultAction] extends [undefined]\n  ? TActions[keyof TActions]\n  : TActions[Extract<TDefaultAction, keyof TActions>];\nexport type ProgrammaticRouteActionContract<\n  TActions extends ProgrammaticRouteActions,\n  TDefaultAction extends keyof TActions | undefined,\n> = keyof TActions extends never\n  ? {\n      actions?: undefined;\n      defaultAction?: undefined;\n      action?: undefined;\n    }\n  : {\n      actions: Readonly<TActions>;\n      defaultAction: [TDefaultAction] extends [undefined]\n        ? keyof TActions\n        : Extract<TDefaultAction, keyof TActions>;\n      action: ProgrammaticRouteDefaultAction<TActions, TDefaultAction>;\n    };\nexport type ProgrammaticRouteWithActions<\n  TRoute extends ProgrammaticPageRoute<any, any, any, any>,\n  TActions extends ProgrammaticRouteActions,\n  TDefaultAction extends keyof TActions | undefined,\n> = Omit<TRoute, \"actions\" | \"defaultAction\" | \"action\"> &\n  ProgrammaticRouteActionContract<TActions, TDefaultAction>;\nexport type ProgrammaticRouteDataStaleTime =\n  | number\n  | false\n  | `${number}ms`\n  | `${number}s`\n  | `${number}m`\n  | `${number}h`;\nexport type ProgrammaticRouteContext = keyof FarmAppContext extends never\n  ? unknown\n  : FarmAppContext;\n\nexport type ProgrammaticRouteComponentProps<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TData = undefined,\n> = Omit<PageProps, \"params\" | \"searchParams\"> & {\n  params: TParams;\n  search: TSearch;\n  searchParams: Promise<TSearch>;\n} & ([TData] extends [undefined] ? { data?: undefined } : { data: TData });\n\nexport type ProgrammaticRouteDataContext<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TContext = ProgrammaticRouteContext,\n> = Omit<ProgrammaticRouteComponentProps<TParams, TSearch>, \"context\" | \"data\"> & {\n  context: TContext;\n  pluginContext?: PluginContextProps;\n};\n\nexport type ProgrammaticRouteDataCacheContext<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TBefore = unknown,\n  TContext = ProgrammaticRouteContext,\n> = ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n  before: TBefore;\n};\n\nexport type ProgrammaticRouteGuardContext<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TContext = ProgrammaticRouteContext,\n> = ProgrammaticRouteDataContext<TParams, TSearch, TContext>;\n\nexport type ProgrammaticRouteGuard<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TContext = ProgrammaticRouteContext,\n> = (\n  context: ProgrammaticRouteGuardContext<TParams, TSearch, TContext>,\n) => ProgrammaticRouteMaybePromise<void>;\n\nexport type ProgrammaticRouteErrorComponentProps<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n> = Partial<ProgrammaticRouteComponentProps<TParams, TSearch>> & {\n  error: unknown;\n};\n\nexport type ProgrammaticRoutePendingComponentProps<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n> = Partial<ProgrammaticRouteComponentProps<TParams, TSearch>>;\n\nexport type ProgrammaticRouteDataCacheKeys<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TBefore = unknown,\n  TContext = ProgrammaticRouteContext,\n> =\n  | readonly string[]\n  | ((\n      context: ProgrammaticRouteDataCacheContext<TParams, TSearch, TBefore, TContext>,\n    ) => ProgrammaticRouteMaybePromise<readonly string[]>);\n\nexport interface ProgrammaticRouteDataHooks<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TBefore = unknown,\n  TData = unknown,\n  TContext = ProgrammaticRouteContext,\n> {\n  key?: (\n    context: ProgrammaticRouteDataCacheContext<TParams, TSearch, NoInfer<TBefore>, TContext>,\n  ) => ProgrammaticRouteMaybePromise<RouteDataCacheKey | null | undefined>;\n  staleTime?: ProgrammaticRouteDataStaleTime;\n  tags?: ProgrammaticRouteDataCacheKeys<TParams, TSearch, NoInfer<TBefore>, TContext>;\n  paths?: ProgrammaticRouteDataCacheKeys<TParams, TSearch, NoInfer<TBefore>, TContext>;\n  before?: (\n    context: ProgrammaticRouteDataContext<TParams, TSearch, TContext>,\n  ) => ProgrammaticRouteMaybePromise<TBefore>;\n  main: (\n    context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n      before: NoInfer<TBefore>;\n    },\n  ) => ProgrammaticRouteMaybePromise<TData>;\n  after?: (\n    context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n      before: NoInfer<TBefore>;\n      data: NoInfer<TData>;\n    },\n  ) => ProgrammaticRouteMaybePromise<void>;\n}\n\nexport type InferProgrammaticRouteData<TDataHooks> = TDataHooks extends {\n  main: (...args: any[]) => infer TResult;\n}\n  ? Awaited<TResult>\n  : undefined;\n\nexport interface ProgrammaticPageRoute<\n  TParams = ProgrammaticRouteParamsFallback,\n  TSearch = ProgrammaticRouteSearchFallback,\n  TDataHooks extends ProgrammaticRouteDataHooks<TParams, TSearch, any, any, any> | undefined =\n    | ProgrammaticRouteDataHooks<TParams, TSearch, any, any, any>\n    | undefined,\n  TContext = ProgrammaticRouteContext,\n> extends FarmRouteRuntimeConfig {\n  kind: \"page\";\n  path: string;\n  component: ComponentType<any>;\n  params?: ProgrammaticRouteSchema<TParams>;\n  search?: ProgrammaticRouteSearchConfig<TSearch>;\n  guard?: ProgrammaticRouteGuard<TParams, TSearch, TContext>;\n  data?: TDataHooks;\n  /** Named server functions owned by this route. */\n  actions?: ProgrammaticRouteActions;\n  /** Named action selected by `useAction(route)`. The first action is used when omitted. */\n  defaultAction?: string;\n  /** Resolved default server function for client and server calls. */\n  action?: ProgrammaticRouteAction;\n  pending?: ComponentType<ProgrammaticRoutePendingComponentProps<TParams, TSearch>>;\n  error?: ComponentType<ProgrammaticRouteErrorComponentProps<TParams, TSearch>>;\n  notFound?: ComponentType<ProgrammaticRouteErrorComponentProps<TParams, TSearch>>;\n  render?: ProgrammaticRouteRenderMode;\n  staticPaths?: ProgrammaticStaticPaths;\n  revalidate?: number | false;\n  ppr?: boolean;\n  metadata?: Metadata & Record<string, any>;\n  generateMetadata?: RouteModule[\"generateMetadata\"];\n}\n\nexport interface ProgrammaticLayoutRoute extends FarmRouteRuntimeConfig {\n  kind: \"layout\";\n  path: string;\n  component: ComponentType<LayoutProps>;\n  metadata?: Metadata & Record<string, any>;\n  generateMetadata?: (props: { params: Record<string, string> }) => Promise<Metadata> | Metadata;\n}\n\nexport type ProgrammaticApiRouteOptions = Partial<Record<ProgrammaticRouteMethod, any>> & {\n  render?: ProgrammaticRouteRenderMode;\n} & FarmRouteRuntimeConfig;\n\nexport interface ProgrammaticApiRoute extends FarmRouteRuntimeConfig {\n  kind: \"api\";\n  path: string;\n  methods: Partial<Record<ProgrammaticRouteMethod, any>>;\n  render?: ProgrammaticRouteRenderMode;\n}\n\nexport interface ProgrammaticRedirectRoute {\n  kind: \"redirect\";\n  source: string;\n  destination: string;\n  permanent?: boolean;\n  statusCode?: number;\n}\n\nexport type ProgrammaticRouteDefinition =\n  | ProgrammaticPageRoute<any, any>\n  | ProgrammaticLayoutRoute\n  | ProgrammaticApiRoute\n  | ProgrammaticRedirectRoute;\n\nexport interface ProgrammaticRouteManifest {\n  readonly __farmRoutes: true;\n  routes: ProgrammaticRouteDefinition[];\n}\n\nexport interface ProgrammaticRouteBuilder {\n  page(\n    path: string,\n    options: Omit<ProgrammaticPageRoute<any, any>, \"kind\" | \"path\">,\n  ): ProgrammaticPageRoute;\n  layout(\n    path: string,\n    options: Omit<ProgrammaticLayoutRoute, \"kind\" | \"path\">,\n  ): ProgrammaticLayoutRoute;\n  api(path: string, options: ProgrammaticApiRouteOptions): ProgrammaticApiRoute;\n  redirect(\n    source: string,\n    destination: string,\n    options?: Omit<ProgrammaticRedirectRoute, \"kind\" | \"source\" | \"destination\">,\n  ): ProgrammaticRedirectRoute;\n}\n\nexport type ProgrammaticRouteFactory = (\n  builder: ProgrammaticRouteBuilder,\n) => readonly ProgrammaticRouteDefinition[];\n\ntype CreateRouteParams<TParamsSchema> = InferProgrammaticRouteSchema<\n  TParamsSchema,\n  ProgrammaticRouteParamsFallback\n>;\n\ntype CreateRouteSearch<TSearchConfig> = InferProgrammaticRouteSearch<\n  TSearchConfig,\n  ProgrammaticRouteSearchFallback\n>;\n\ntype CreateRouteSharedOptions<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n> = Omit<\n  ProgrammaticPageRoute<CreateRouteParams<TParamsSchema>, CreateRouteSearch<TSearchConfig>>,\n  \"kind\" | \"path\" | \"component\" | \"params\" | \"search\" | \"data\" | \"guard\" | \"action\"\n> & {\n  params?: TParamsSchema;\n  search?: TSearchConfig;\n  guard?: ProgrammaticRouteGuard<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>\n  >;\n};\n\ntype CreateRouteDataHooksWithBefore<\n  TParams,\n  TSearch,\n  TBeforeResult,\n  TMainResult,\n  TContext = ProgrammaticRouteContext,\n> = Omit<\n  ProgrammaticRouteDataHooks<\n    TParams,\n    TSearch,\n    NoInfer<Awaited<TBeforeResult>>,\n    NoInfer<Awaited<TMainResult>>,\n    TContext\n  >,\n  \"before\" | \"main\"\n> & {\n  before: (context: ProgrammaticRouteDataContext<TParams, TSearch, TContext>) => TBeforeResult;\n  main: (\n    context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n      before: NoInfer<Awaited<TBeforeResult>>;\n    },\n  ) => TMainResult;\n};\n\ntype CreateRouteDataHooksWithoutBefore<\n  TParams,\n  TSearch,\n  TMainResult,\n  TContext = ProgrammaticRouteContext,\n> = Omit<\n  ProgrammaticRouteDataHooks<TParams, TSearch, undefined, NoInfer<Awaited<TMainResult>>, TContext>,\n  \"before\" | \"main\"\n> & {\n  before?: undefined;\n  main: (\n    context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n      before: undefined;\n    },\n  ) => TMainResult;\n};\n\ntype CreateRouteOptionsWithBefore<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n  TBefore,\n  TData,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n  data: CreateRouteDataHooksWithBefore<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    TBefore,\n    TData\n  >;\n  component: ComponentType<\n    ProgrammaticRouteComponentProps<\n      CreateRouteParams<TParamsSchema>,\n      CreateRouteSearch<TSearchConfig>,\n      NoInfer<Awaited<TData>>\n    >\n  >;\n};\n\ntype CreateRouteOptionsWithoutBefore<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n  TData,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n  data: CreateRouteDataHooksWithoutBefore<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    TData\n  >;\n  component: ComponentType<\n    ProgrammaticRouteComponentProps<\n      CreateRouteParams<TParamsSchema>,\n      CreateRouteSearch<TSearchConfig>,\n      NoInfer<Awaited<TData>>\n    >\n  >;\n};\n\ntype CreateRouteOptionsWithoutData<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n  data?: undefined;\n  component: ComponentType<\n    ProgrammaticRouteComponentProps<\n      CreateRouteParams<TParamsSchema>,\n      CreateRouteSearch<TSearchConfig>,\n      undefined\n    >\n  >;\n};\n\ntype CreateRouteComponentOption<TComponent extends ComponentType<any>, TProps> = {\n  component: TComponent;\n} & (TComponent extends ComponentType<TProps> ? unknown : { component: ComponentType<TProps> });\n\nexport type CreateRouteOptions<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n  TBefore = unknown,\n  TData = unknown,\n> =\n  | CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBefore, TData>\n  | CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TData>\n  | CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>;\n\ntype CreateRouteActionOptions<\n  TActions extends ProgrammaticRouteActions,\n  TDefaultAction extends keyof TActions | undefined,\n> = keyof TActions extends never\n  ? { actions?: undefined; defaultAction?: undefined }\n  : { actions: TActions; defaultAction?: TDefaultAction };\n\nconst FARM_ROUTES_BRAND = Symbol.for(\"farm.routes\");\nexport const PROGRAMMATIC_ROUTE_FILE_NAMES = [\n  \"farm.route.ts\",\n  \"farm.route.tsx\",\n  \"farm.route.js\",\n  \"farm.route.jsx\",\n  \"farm.routes.ts\",\n  \"farm.routes.tsx\",\n  \"farm.routes.js\",\n  \"farm.routes.jsx\",\n  \"routes.ts\",\n  \"routes.tsx\",\n  \"routes.js\",\n  \"routes.jsx\",\n];\n\nexport function defineRoutes(\n  input: readonly ProgrammaticRouteDefinition[] | ProgrammaticRouteFactory,\n): ProgrammaticRouteManifest {\n  const routes = typeof input === \"function\" ? input(routesBuilder) : input;\n  const manifest = {\n    __farmRoutes: true as const,\n    routes: routes.map(normalizeProgrammaticRoute),\n  };\n\n  Object.defineProperty(manifest, FARM_ROUTES_BRAND, {\n    value: true,\n    enumerable: false,\n  });\n\n  return manifest;\n}\n\nexport const routesBuilder: ProgrammaticRouteBuilder = {\n  page(path, options) {\n    return normalizeProgrammaticRoute({\n      kind: \"page\",\n      path,\n      ...options,\n    }) as ProgrammaticPageRoute;\n  },\n  layout(path, options) {\n    return normalizeProgrammaticRoute({\n      kind: \"layout\",\n      path,\n      ...options,\n    }) as ProgrammaticLayoutRoute;\n  },\n  api(path, options) {\n    const { render, runtime, regions, maxDuration, ...methods } = options;\n    return normalizeProgrammaticRoute({\n      kind: \"api\",\n      path,\n      render,\n      runtime,\n      regions,\n      maxDuration,\n      methods: normalizeApiMethods(methods),\n    }) as ProgrammaticApiRoute;\n  },\n  redirect(source, destination, options = {}) {\n    return normalizeProgrammaticRoute({\n      kind: \"redirect\",\n      source,\n      destination,\n      ...options,\n    }) as ProgrammaticRedirectRoute;\n  },\n};\n\nexport const page = routesBuilder.page;\nexport const layout = routesBuilder.layout;\nexport const api = routesBuilder.api;\nexport const redirect = routesBuilder.redirect;\n\nexport interface ProgrammaticRouteSearchClientOptions {\n  stripDefaults?: boolean | readonly string[];\n  preserve?: readonly string[];\n  temporary?: readonly string[];\n}\n\nexport interface ProgrammaticRouteSearchResolution<TSearch = unknown> {\n  search: TSearch;\n  canonicalPath?: string;\n}\n\nexport function getProgrammaticRouteSearchSchema<TSearch = unknown>(\n  search: ProgrammaticRouteSearchConfig<TSearch> | undefined,\n): ProgrammaticRouteSchema<TSearch> | undefined {\n  if (!search) return undefined;\n  if (isProgrammaticRouteSchema(search)) return search;\n  return search.schema;\n}\n\nexport function getProgrammaticRouteSearchClientOptions(\n  search: ProgrammaticRouteSearchConfig<any> | undefined,\n): ProgrammaticRouteSearchClientOptions | undefined {\n  if (!search || isProgrammaticRouteSchema(search)) return undefined;\n\n  const options: ProgrammaticRouteSearchClientOptions = {};\n  if (typeof search.stripDefaults !== \"undefined\") options.stripDefaults = search.stripDefaults;\n  if (search.preserve?.length) options.preserve = [...search.preserve];\n  if (search.temporary?.length) options.temporary = [...search.temporary];\n\n  return Object.keys(options).length > 0 ? options : undefined;\n}\n\nfunction resolveProgrammaticRouteSearch<TSearch>(\n  searchConfig: ProgrammaticRouteSearchConfig<TSearch> | undefined,\n  rawSearch: ProgrammaticRouteSearchFallback,\n  path: string,\n  routePath: string,\n): ProgrammaticRouteSearchResolution<TSearch | ProgrammaticRouteSearchFallback> {\n  const schema = getProgrammaticRouteSearchSchema(searchConfig);\n  const search = parseProgrammaticSchema(schema, rawSearch, \"search\", routePath) as\n    | TSearch\n    | ProgrammaticRouteSearchFallback;\n  const options = getProgrammaticRouteSearchOptions(searchConfig);\n  const canonicalPath = resolveProgrammaticRouteCanonicalPath({\n    options,\n    schema,\n    rawSearch,\n    parsedSearch: search,\n    path,\n  });\n\n  return { search, canonicalPath };\n}\n\nfunction getProgrammaticRouteSearchOptions(\n  search: ProgrammaticRouteSearchConfig<any> | undefined,\n): ProgrammaticRouteSearchOptions<any> | undefined {\n  if (!search || isProgrammaticRouteSchema(search)) return undefined;\n  return search;\n}\n\nfunction isProgrammaticRouteSchema(value: unknown): value is ProgrammaticRouteSchema<any> {\n  return !!value && typeof value === \"object\" && typeof (value as any).parse === \"function\";\n}\n\nfunction resolveProgrammaticRouteCanonicalPath(input: {\n  options: ProgrammaticRouteSearchOptions<any> | undefined;\n  schema: ProgrammaticRouteSchema<any> | undefined;\n  rawSearch: ProgrammaticRouteSearchFallback;\n  parsedSearch: unknown;\n  path: string;\n}): string | undefined {\n  const options = input.options;\n  if (!options?.temporary?.length && !options?.stripDefaults) {\n    return undefined;\n  }\n\n  const params = createSearchParams(input.rawSearch);\n  const original = params.toString();\n\n  for (const key of options.temporary || []) {\n    params.delete(key);\n  }\n\n  if (options.stripDefaults) {\n    const defaultSearch = parseDefaultSearch(input.schema);\n    if (defaultSearch !== undefined) {\n      const keys =\n        options.stripDefaults === true\n          ? Array.from(new Set(Array.from(params.keys())))\n          : [...options.stripDefaults];\n\n      for (const key of keys) {\n        if (\n          params.has(key) &&\n          searchValuesEqual(\n            readSearchValue(input.parsedSearch, key),\n            readSearchValue(defaultSearch, key),\n          )\n        ) {\n          params.delete(key);\n        }\n      }\n    }\n  }\n\n  const next = params.toString();\n  if (next === original) {\n    return undefined;\n  }\n\n  return next ? `${input.path}?${next}` : input.path;\n}\n\nfunction createSearchParams(value: ProgrammaticRouteSearchFallback): URLSearchParams {\n  const params = new URLSearchParams();\n\n  for (const [key, item] of Object.entries(value)) {\n    if (item == null) continue;\n    const values = Array.isArray(item) ? item : [item];\n    for (const entry of values) {\n      if (entry != null) params.append(key, String(entry));\n    }\n  }\n\n  return params;\n}\n\nfunction parseDefaultSearch(\n  schema: ProgrammaticRouteSchema<any> | undefined,\n): Record<string, unknown> | undefined {\n  if (!schema) return undefined;\n\n  try {\n    const value = schema.parse({});\n    return value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction readSearchValue(value: unknown, key: string): unknown {\n  return value && typeof value === \"object\" ? (value as Record<string, unknown>)[key] : undefined;\n}\n\nfunction searchValuesEqual(left: unknown, right: unknown): boolean {\n  return (\n    JSON.stringify(normalizeComparableValue(left)) ===\n    JSON.stringify(normalizeComparableValue(right))\n  );\n}\n\nfunction normalizeComparableValue(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map(normalizeComparableValue);\n  }\n  if (value && typeof value === \"object\") {\n    return Object.keys(value as Record<string, unknown>)\n      .sort()\n      .reduce<Record<string, unknown>>((output, key) => {\n        output[key] = normalizeComparableValue((value as Record<string, unknown>)[key]);\n        return output;\n      }, {});\n  }\n  return value;\n}\n\nexport function createRoute<\n  const TActions extends ProgrammaticRouteActions,\n  TDefaultAction extends keyof TActions | undefined = undefined,\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n  TBeforeResult = unknown,\n  TMainResult = unknown,\n  TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n  path: string,\n  options: Omit<\n    CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBeforeResult, TMainResult>,\n    \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n  > &\n    CreateRouteActionOptions<TActions, TDefaultAction> &\n    CreateRouteComponentOption<\n      TComponent,\n      ProgrammaticRouteComponentProps<\n        CreateRouteParams<TParamsSchema>,\n        CreateRouteSearch<TSearchConfig>,\n        Awaited<TMainResult>\n      >\n    >,\n): ProgrammaticRouteWithActions<\n  ProgrammaticPageRoute<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    CreateRouteDataHooksWithBefore<\n      CreateRouteParams<TParamsSchema>,\n      CreateRouteSearch<TSearchConfig>,\n      TBeforeResult,\n      TMainResult\n    >\n  >,\n  TActions,\n  TDefaultAction\n>;\nexport function createRoute<\n  const TActions extends ProgrammaticRouteActions,\n  TDefaultAction extends keyof TActions | undefined = undefined,\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n  TMainResult = unknown,\n  TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n  path: string,\n  options: Omit<\n    CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TMainResult>,\n    \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n  > &\n    CreateRouteActionOptions<TActions, TDefaultAction> &\n    CreateRouteComponentOption<\n      TComponent,\n      ProgrammaticRouteComponentProps<\n        CreateRouteParams<TParamsSchema>,\n        CreateRouteSearch<TSearchConfig>,\n        Awaited<TMainResult>\n      >\n    >,\n): ProgrammaticRouteWithActions<\n  ProgrammaticPageRoute<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    CreateRouteDataHooksWithoutBefore<\n      CreateRouteParams<TParamsSchema>,\n      CreateRouteSearch<TSearchConfig>,\n      TMainResult\n    >\n  >,\n  TActions,\n  TDefaultAction\n>;\nexport function createRoute<\n  const TActions extends ProgrammaticRouteActions,\n  TDefaultAction extends keyof TActions | undefined = undefined,\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n>(\n  path: string,\n  options: Omit<\n    CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>,\n    \"actions\" | \"defaultAction\" | \"action\"\n  > &\n    CreateRouteActionOptions<TActions, TDefaultAction>,\n): ProgrammaticRouteWithActions<\n  ProgrammaticPageRoute<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    undefined\n  >,\n  TActions,\n  TDefaultAction\n>;\nexport function createRoute<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n  TBeforeResult = unknown,\n  TMainResult = unknown,\n  TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n  path: string,\n  options: Omit<\n    CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBeforeResult, TMainResult>,\n    \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n  > & { actions?: undefined; defaultAction?: undefined } & CreateRouteComponentOption<\n      TComponent,\n      ProgrammaticRouteComponentProps<\n        CreateRouteParams<TParamsSchema>,\n        CreateRouteSearch<TSearchConfig>,\n        Awaited<TMainResult>\n      >\n    >,\n): ProgrammaticRouteWithActions<\n  ProgrammaticPageRoute<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    CreateRouteDataHooksWithBefore<\n      CreateRouteParams<TParamsSchema>,\n      CreateRouteSearch<TSearchConfig>,\n      TBeforeResult,\n      TMainResult\n    >\n  >,\n  {},\n  undefined\n>;\nexport function createRoute<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n  TMainResult = unknown,\n  TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n  path: string,\n  options: Omit<\n    CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TMainResult>,\n    \"component\" | \"actions\" | \"defaultAction\" | \"action\"\n  > & { actions?: undefined; defaultAction?: undefined } & CreateRouteComponentOption<\n      TComponent,\n      ProgrammaticRouteComponentProps<\n        CreateRouteParams<TParamsSchema>,\n        CreateRouteSearch<TSearchConfig>,\n        Awaited<TMainResult>\n      >\n    >,\n): ProgrammaticRouteWithActions<\n  ProgrammaticPageRoute<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    CreateRouteDataHooksWithoutBefore<\n      CreateRouteParams<TParamsSchema>,\n      CreateRouteSearch<TSearchConfig>,\n      TMainResult\n    >\n  >,\n  {},\n  undefined\n>;\nexport function createRoute<\n  TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n  TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n>(\n  path: string,\n  options: Omit<\n    CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>,\n    \"actions\" | \"defaultAction\" | \"action\"\n  > & { actions?: undefined; defaultAction?: undefined },\n): ProgrammaticRouteWithActions<\n  ProgrammaticPageRoute<\n    CreateRouteParams<TParamsSchema>,\n    CreateRouteSearch<TSearchConfig>,\n    undefined\n  >,\n  {},\n  undefined\n>;\nexport function createRoute(path: string, options: any): any {\n  return routesBuilder.page(path, options);\n}\n\nexport function isProgrammaticRoutesFileName(fileName: string): boolean {\n  const normalized = fileName.replace(/\\\\/g, \"/\");\n  const baseName = normalized.split(\"/\").pop() || normalized;\n  return PROGRAMMATIC_ROUTE_FILE_NAMES.includes(baseName);\n}\n\nexport function getProgrammaticRouteManifest(\n  mod: Record<string, any> | null | undefined,\n): ProgrammaticRouteManifest | null {\n  if (!mod) return null;\n\n  const candidates = [mod.default, mod.routes, mod.Route];\n  for (const candidate of candidates) {\n    if (isProgrammaticRouteManifest(candidate)) {\n      return candidate;\n    }\n    if (isProgrammaticRouteDefinition(candidate)) {\n      return defineRoutes([candidate]);\n    }\n    if (Array.isArray(candidate)) {\n      return defineRoutes(candidate as ProgrammaticRouteDefinition[]);\n    }\n  }\n\n  const routeDefinitions = Object.values(mod).filter(isProgrammaticRouteDefinition);\n  if (routeDefinitions.length > 0) {\n    return defineRoutes(routeDefinitions);\n  }\n\n  return null;\n}\n\nexport function isProgrammaticRouteManifest(value: unknown): value is ProgrammaticRouteManifest {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (value as ProgrammaticRouteManifest).__farmRoutes === true &&\n    Array.isArray((value as ProgrammaticRouteManifest).routes)\n  );\n}\n\nexport function isProgrammaticRouteDefinition(\n  value: unknown,\n): value is ProgrammaticRouteDefinition {\n  if (!value || typeof value !== \"object\") {\n    return false;\n  }\n\n  const kind = (value as { kind?: unknown }).kind;\n  return kind === \"page\" || kind === \"layout\" || kind === \"api\" || kind === \"redirect\";\n}\n\nexport function createProgrammaticRouteModuleId(\n  filePath: string,\n  kind: \"page\" | \"layout\" | \"api\",\n  routePath: string,\n): string {\n  return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeRoutePath(routePath))}`;\n}\n\nexport function parseProgrammaticRouteModuleId(moduleId: string): {\n  filePath: string;\n  kind: \"page\" | \"layout\" | \"api\";\n  routePath: string;\n} | null {\n  const queryIndex = moduleId.indexOf(\"?\");\n  if (queryIndex === -1) {\n    return null;\n  }\n\n  const filePath = moduleId.slice(0, queryIndex);\n  const params = new URLSearchParams(moduleId.slice(queryIndex + 1));\n  const value = params.get(\"farm-route\");\n  if (!value) {\n    return null;\n  }\n\n  const separator = value.indexOf(\":\");\n  if (separator === -1) {\n    return null;\n  }\n\n  const kind = value.slice(0, separator);\n  if (kind !== \"page\" && kind !== \"layout\" && kind !== \"api\") {\n    return null;\n  }\n\n  return {\n    filePath,\n    kind,\n    routePath: normalizeRoutePath(value.slice(separator + 1)),\n  };\n}\n\nexport function parseProgrammaticRoutePath(\n  routePath: string,\n  type: ParsedRoute[\"type\"] = \"page\",\n): ParsedRoute {\n  return parseSharedProgrammaticRoutePath(routePath, type);\n}\n\nexport function createRouteModuleFromProgrammaticPage(\n  route: ProgrammaticPageRoute,\n  rendererRuntime?: Pick<FarmServerRendererRuntime, \"createElement\" | \"Suspense\">,\n): RouteModule {\n  const mod: RouteModule = {\n    default: createProgrammaticPageComponent(route, rendererRuntime),\n    ...normalizeFarmRouteRuntimeConfig(route, `Route \"${route.path}\"`),\n  };\n\n  if (route.params || route.search || route.guard || route.data) {\n    (mod as any).__farmRouteSchemas = {\n      params: route.params,\n      search: getProgrammaticRouteSearchSchema(route.search),\n    };\n    (mod as any).__farmRouteSearch = getProgrammaticRouteSearchClientOptions(route.search);\n    (mod as any).__farmRouteGuard = route.guard;\n    (mod as any).__farmRouteData = route.data;\n    (mod as any).__farmRouteParsesProps = true;\n    (mod as any).__farmResolveRouteProps = (props: PageProps) =>\n      resolveProgrammaticRouteProps(route, props);\n    (mod as any).__farmResolveRouteCanonicalPath = (\n      rawSearch: ProgrammaticRouteSearchFallback,\n      path: string,\n    ) => resolveProgrammaticRouteSearch(route.search, rawSearch, path, route.path).canonicalPath;\n  }\n\n  if (route.pending || route.error || route.notFound) {\n    (mod as any).__farmRouteComponents = {\n      pending: route.pending,\n      error: route.error,\n      notFound: route.notFound,\n    };\n  }\n\n  if (route.render === \"static\" || route.staticPaths) {\n    mod.ssg = true;\n    mod.dynamic = \"force-static\";\n  } else if (route.render === \"dynamic\") {\n    mod.ssg = false;\n    mod.dynamic = \"force-dynamic\";\n  }\n\n  if (typeof route.revalidate !== \"undefined\") {\n    mod.revalidate = route.revalidate;\n  }\n\n  if (route.ppr) {\n    mod.ppr = true;\n  }\n\n  if (route.metadata) {\n    mod.metadata = route.metadata;\n  }\n\n  if (route.generateMetadata) {\n    mod.generateMetadata = route.generateMetadata;\n  }\n\n  if (route.staticPaths) {\n    mod.getStaticPaths = async () => normalizeStaticPaths(route.path, await route.staticPaths!());\n  }\n\n  return mod;\n}\n\nexport function createLayoutModuleFromProgrammaticLayout(route: ProgrammaticLayoutRoute) {\n  return {\n    default: route.component,\n    ...normalizeFarmRouteRuntimeConfig(route, `Layout \"${route.path}\"`),\n    metadata: route.metadata,\n    generateMetadata: route.generateMetadata,\n  };\n}\n\nexport function scanProgrammaticPagePaths(source: string): string[] {\n  const paths = new Set<string>();\n  const callRe = /\\b(?:page|createRoute)\\s*\\(\\s*([\"'`])([^\"'`]+)\\1/g;\n\n  for (const match of source.matchAll(callRe)) {\n    if (match[2]) {\n      paths.add(normalizeRoutePath(match[2]));\n    }\n  }\n\n  return Array.from(paths);\n}\n\nfunction createProgrammaticPageComponent(\n  route: ProgrammaticPageRoute,\n  rendererRuntime?: Pick<FarmServerRendererRuntime, \"createElement\" | \"Suspense\">,\n): ComponentType<PageProps> {\n  if (\n    !route.params &&\n    !route.search &&\n    !route.guard &&\n    !route.data &&\n    !route.pending &&\n    !route.error &&\n    !route.notFound\n  ) {\n    return route.component as ComponentType<PageProps>;\n  }\n\n  const createElement: FarmServerRendererRuntime[\"createElement\"] = (...args) => {\n    if (!rendererRuntime) {\n      throw new Error(\n        `Programmatic route \"${route.path}\" requires a FARMJS renderer runtime before it can render.`,\n      );\n    }\n    return rendererRuntime.createElement(...args);\n  };\n  const Component = route.component;\n\n  if (route.pending) {\n    const PendingComponent = route.pending;\n    const routePropsResources = new WeakMap<object, ProgrammaticRoutePropsResource>();\n    const FarmProgrammaticPageContent = function FarmProgrammaticPageContent(props: PageProps) {\n      try {\n        const resolvedProps = readProgrammaticRouteProps(route, props, routePropsResources);\n        return createElement(Component, stripProgrammaticRoutePropsMarker(resolvedProps));\n      } catch (error) {\n        if (isPromiseLike(error) || isProgrammaticRedirectSignal(error)) {\n          throw error;\n        }\n\n        if (isProgrammaticNotFoundSignal(error) && route.notFound) {\n          return createElement(route.notFound, createProgrammaticRouteErrorProps(error, props));\n        }\n\n        if (route.error) {\n          return createElement(route.error, createProgrammaticRouteErrorProps(error, props));\n        }\n\n        throw error;\n      }\n    };\n    const PageContent = FarmProgrammaticPageContent as unknown as ComponentType<PageProps>;\n    const FarmProgrammaticPage = function FarmProgrammaticPage(props: PageProps) {\n      return createElement(\n        rendererRuntime!.Suspense,\n        {\n          fallback: createElement(PendingComponent, createProgrammaticRoutePendingProps(props)),\n        },\n        createElement(PageContent, props),\n      );\n    };\n\n    return FarmProgrammaticPage as unknown as ComponentType<PageProps>;\n  }\n\n  const FarmProgrammaticPageContent = async function FarmProgrammaticPageContent(props: PageProps) {\n    try {\n      const resolvedProps = isProgrammaticRoutePropsResolved(props)\n        ? props\n        : await resolveProgrammaticRouteProps(route, props);\n\n      return createElement(Component, stripProgrammaticRoutePropsMarker(resolvedProps));\n    } catch (error) {\n      if (isProgrammaticRedirectSignal(error)) {\n        throw error;\n      }\n\n      if (isProgrammaticNotFoundSignal(error) && route.notFound) {\n        return createElement(route.notFound, createProgrammaticRouteErrorProps(error, props));\n      }\n\n      if (route.error) {\n        return createElement(route.error, createProgrammaticRouteErrorProps(error, props));\n      }\n\n      throw error;\n    }\n  };\n\n  return FarmProgrammaticPageContent as unknown as ComponentType<PageProps>;\n}\n\ntype ProgrammaticRoutePropsResource =\n  | { status: \"pending\"; promise: Promise<Record<string, any>> }\n  | { status: \"resolved\"; value: Record<string, any> }\n  | { status: \"rejected\"; error: unknown };\n\nfunction readProgrammaticRouteProps(\n  route: ProgrammaticPageRoute,\n  props: PageProps,\n  resources: WeakMap<object, ProgrammaticRoutePropsResource>,\n): Record<string, any> {\n  if (isProgrammaticRoutePropsResolved(props)) {\n    return props;\n  }\n\n  let resource = resources.get(props as object);\n  if (!resource) {\n    const deferredRouteProps = (props as any).__farmRoutePropsPromise;\n    const promise = Promise.resolve<Record<string, any>>(\n      isPromiseLike(deferredRouteProps)\n        ? (deferredRouteProps as PromiseLike<Record<string, any>>)\n        : resolveProgrammaticRouteProps(route, props),\n    );\n    resource = { status: \"pending\", promise };\n    resources.set(props as object, resource);\n    promise.then(\n      (value) => resources.set(props as object, { status: \"resolved\", value }),\n      (error) => resources.set(props as object, { status: \"rejected\", error }),\n    );\n  }\n\n  if (resource.status === \"pending\") throw resource.promise;\n  if (resource.status === \"rejected\") throw resource.error;\n  return resource.value;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n  return Boolean(\n    value &&\n    (typeof value === \"object\" || typeof value === \"function\") &&\n    typeof (value as PromiseLike<unknown>).then === \"function\",\n  );\n}\n\nfunction createProgrammaticRoutePendingProps(\n  props: PageProps,\n): ProgrammaticRoutePendingComponentProps {\n  return {\n    params: props.params,\n    searchParams: props.searchParams,\n    path: props.path,\n  };\n}\n\nfunction createProgrammaticRouteErrorProps(\n  error: unknown,\n  props: PageProps,\n): ProgrammaticRouteErrorComponentProps {\n  return {\n    error,\n    params: props.params,\n    searchParams: props.searchParams,\n    path: props.path,\n  };\n}\n\nfunction isProgrammaticRedirectSignal(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n  const digest = (error as { digest?: unknown }).digest;\n  return typeof digest === \"string\" && digest.startsWith(\"FARM_REDIRECT;\");\n}\n\nfunction isProgrammaticNotFoundSignal(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n  const digest = (error as { digest?: unknown }).digest;\n  return digest === \"FARM_NOT_FOUND\";\n}\n\nasync function resolveProgrammaticRouteProps(\n  route: ProgrammaticPageRoute,\n  props: PageProps,\n): Promise<Record<string, any> & { __farmRoutePropsResolved: true }> {\n  const rawSearch = await props.searchParams;\n  const params = parseProgrammaticSchema(route.params, props.params, \"params\", route.path);\n  const { search, canonicalPath } = resolveProgrammaticRouteSearch(\n    route.search,\n    rawSearch,\n    props.path,\n    route.path,\n  );\n  const routeContextValue = getFarmRouteContext(props);\n  const pluginContext = props.context;\n  const baseProps = {\n    ...props,\n    params,\n    search,\n    searchParams: Promise.resolve(search),\n  };\n  const routeContextProps = {\n    ...baseProps,\n    context: routeContextValue,\n    pluginContext,\n  };\n\n  if (route.guard) {\n    await route.guard(routeContextProps as any);\n  }\n\n  if (!route.data) {\n    return markProgrammaticRoutePropsResolved(addCanonicalPath(baseProps, canonicalPath));\n  }\n\n  const before = route.data.before ? await route.data.before(routeContextProps as any) : undefined;\n  const dataContext = {\n    ...(routeContextProps as any),\n    before,\n  };\n  const data = await resolveProgrammaticRouteData(route, route.data, dataContext);\n\n  if (route.data.after) {\n    await route.data.after({\n      ...(routeContextProps as any),\n      before,\n      data,\n    });\n  }\n\n  return markProgrammaticRoutePropsResolved({\n    ...baseProps,\n    data,\n    ...(canonicalPath ? { __farmCanonicalPath: canonicalPath } : {}),\n  });\n}\n\nasync function resolveProgrammaticRouteData(\n  route: ProgrammaticPageRoute,\n  dataHooks: ProgrammaticRouteDataHooks<any, any, any, any>,\n  context: ProgrammaticRouteDataCacheContext<any, any, any>,\n): Promise<unknown> {\n  if (!dataHooks?.key) {\n    return dataHooks.main(context);\n  }\n\n  const routeDataKey = await dataHooks.key(context);\n  if (routeDataKey == null) {\n    return dataHooks.main(context);\n  }\n\n  const cacheKey = createFarmCacheKey([\"route-data\", routeDataKey]);\n  const cacheOptions: FarmCacheOptions = {\n    tags: [\n      createRouteDataCacheTag(routeDataKey),\n      ...(await resolveProgrammaticRouteDataKeys(dataHooks.tags, context)),\n    ],\n    paths: [\n      ...(typeof context.path === \"string\" ? [context.path] : []),\n      ...(await resolveProgrammaticRouteDataKeys(dataHooks.paths, context)),\n    ],\n    revalidate: normalizeProgrammaticRouteStaleTime(dataHooks.staleTime),\n  };\n\n  return getFarmDataCache().getOrSet(cacheKey, () => dataHooks.main(context), cacheOptions);\n}\n\nasync function resolveProgrammaticRouteDataKeys(\n  input: ProgrammaticRouteDataCacheKeys<any, any, any> | undefined,\n  context: ProgrammaticRouteDataCacheContext<any, any, any>,\n): Promise<readonly string[]> {\n  if (!input) return [];\n  const value = typeof input === \"function\" ? await input(context) : input;\n  return value.filter((item) => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction normalizeProgrammaticRouteStaleTime(\n  staleTime: ProgrammaticRouteDataStaleTime | undefined,\n): number | false | undefined {\n  if (staleTime === undefined) return undefined;\n  if (staleTime === false) return false;\n\n  if (typeof staleTime === \"number\") {\n    if (!Number.isFinite(staleTime) || staleTime <= 0) return undefined;\n    return Math.max(1, Math.ceil(staleTime / 1000));\n  }\n\n  const match = staleTime.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)$/);\n  if (!match) return undefined;\n\n  const value = Number(match[1]);\n  if (!Number.isFinite(value) || value <= 0) return undefined;\n\n  const unit = match[2];\n  const milliseconds =\n    unit === \"ms\"\n      ? value\n      : unit === \"s\"\n        ? value * 1000\n        : unit === \"m\"\n          ? value * 60000\n          : value * 3600000;\n\n  return Math.max(1, Math.ceil(milliseconds / 1000));\n}\n\nfunction isProgrammaticRoutePropsResolved(value: unknown): boolean {\n  return !!value && typeof value === \"object\" && (value as any).__farmRoutePropsResolved === true;\n}\n\nfunction markProgrammaticRoutePropsResolved<T extends Record<string, any>>(\n  props: T,\n): T & { __farmRoutePropsResolved: true } {\n  return {\n    ...props,\n    __farmRoutePropsResolved: true,\n  };\n}\n\nfunction addCanonicalPath<T extends Record<string, any>>(\n  props: T,\n  canonicalPath: string | undefined,\n): T {\n  return canonicalPath ? ({ ...props, __farmCanonicalPath: canonicalPath } as T) : props;\n}\n\nfunction stripProgrammaticRoutePropsMarker<TProps>(props: TProps): TProps {\n  if (!isProgrammaticRoutePropsResolved(props)) {\n    return props;\n  }\n\n  const {\n    __farmRoutePropsResolved,\n    __farmCanonicalPath,\n    __farmRoutePropsPromise,\n    ...componentProps\n  } = props as any;\n  return componentProps;\n}\n\nfunction parseProgrammaticSchema<TFallback>(\n  schema: ProgrammaticRouteSchema<any> | undefined,\n  value: TFallback,\n  label: string,\n  routePath: string,\n): unknown {\n  if (!schema) {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n  }\n}\n\nfunction normalizeProgrammaticRoute(\n  route: ProgrammaticRouteDefinition,\n): ProgrammaticRouteDefinition {\n  if (route.kind === \"redirect\") {\n    return {\n      ...route,\n      source: normalizeRoutePath(route.source),\n    };\n  }\n\n  if (route.kind === \"api\") {\n    return {\n      ...route,\n      ...normalizeFarmRouteRuntimeConfig(route, `API route \"${route.path}\"`),\n      path: normalizeRoutePath(route.path),\n      methods: normalizeApiMethods(route.methods),\n    };\n  }\n\n  const routeActions = route.kind === \"page\" ? normalizeProgrammaticRouteActions(route) : undefined;\n\n  return {\n    ...route,\n    ...routeActions,\n    ...normalizeFarmRouteRuntimeConfig(\n      route,\n      `${route.kind === \"layout\" ? \"Layout\" : \"Route\"} \"${route.path}\"`,\n    ),\n    path: normalizeRoutePath(route.path),\n  };\n}\n\nfunction normalizeProgrammaticRouteActions(route: ProgrammaticPageRoute): {\n  actions?: ProgrammaticRouteActions;\n  defaultAction?: string;\n  action?: ProgrammaticRouteAction;\n} {\n  const entries = Object.entries(route.actions ?? {});\n\n  if (entries.length === 0) {\n    if (route.defaultAction !== undefined) {\n      throw new TypeError(\n        `Route \"${route.path}\" declares defaultAction without declaring any actions.`,\n      );\n    }\n    return {};\n  }\n\n  for (const [name, action] of entries) {\n    if (typeof action !== \"function\") {\n      throw new TypeError(`Route \"${route.path}\" action \"${name}\" must be a server function.`);\n    }\n  }\n\n  const defaultAction = route.defaultAction ?? entries[0]![0];\n  const actions = Object.freeze({ ...route.actions });\n  const action = actions[defaultAction];\n\n  if (!action) {\n    throw new TypeError(\n      `Route \"${route.path}\" defaultAction \"${defaultAction}\" does not match a declared action.`,\n    );\n  }\n\n  return {\n    actions,\n    defaultAction,\n    action,\n  };\n}\n\nfunction normalizeRoutePath(routePath: string): string {\n  const withSlash = routePath.startsWith(\"/\") ? routePath : `/${routePath}`;\n  const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n  return withoutTrailing || \"/\";\n}\n\nfunction normalizeApiMethods(\n  methods: Record<string, any>,\n): Partial<Record<ProgrammaticRouteMethod, any>> {\n  const normalized: Partial<Record<ProgrammaticRouteMethod, any>> = {};\n\n  for (const [method, handler] of Object.entries(methods)) {\n    const normalizedMethod = method.toUpperCase() as ProgrammaticRouteMethod;\n    if (handler && isProgrammaticRouteMethod(normalizedMethod)) {\n      normalized[normalizedMethod] = handler;\n    }\n  }\n\n  return normalized;\n}\n\nfunction isProgrammaticRouteMethod(method: string): method is ProgrammaticRouteMethod {\n  return (\n    method === \"GET\" ||\n    method === \"HEAD\" ||\n    method === \"QUERY\" ||\n    method === \"POST\" ||\n    method === \"PUT\" ||\n    method === \"DELETE\" ||\n    method === \"PATCH\" ||\n    method === \"OPTIONS\"\n  );\n}\n\nfunction normalizeStaticPaths(\n  routePath: string,\n  paths: readonly ProgrammaticStaticPath[],\n): Record<string, string>[] {\n  const dynamicSegments = parseProgrammaticRoutePath(routePath).segments.filter(\n    (segment) => segment.isDynamic,\n  );\n\n  return paths.map((entry) => {\n    if (typeof entry === \"string\" || Array.isArray(entry)) {\n      if (dynamicSegments.length !== 1) {\n        throw new Error(\n          `staticPaths for \"${routePath}\" must return objects when the route has ${dynamicSegments.length} dynamic params.`,\n        );\n      }\n\n      const value = Array.isArray(entry) ? entry.join(\"/\") : entry;\n      return { [dynamicSegments[0].segment]: String(value) };\n    }\n\n    return Object.fromEntries(\n      Object.entries(entry).map(([key, value]) => [\n        key,\n        Array.isArray(value) ? value.map(String).join(\"/\") : String(value),\n      ]),\n    );\n  });\n}\n","import { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { PROGRAMMATIC_ROUTE_FILE_NAMES, scanProgrammaticPagePaths } from \"./routes-shared\";\nimport type { ProgrammaticRouteManifest } from \"./routes\";\n\nexport interface LoadedProgrammaticRouteManifest {\n  filePath: string;\n  manifest: ProgrammaticRouteManifest;\n}\n\nexport async function loadProgrammaticRouteManifests(options: {\n  root: string;\n  srcDir?: string;\n  loadModule: (filePath: string) => Promise<Record<string, any>>;\n}): Promise<LoadedProgrammaticRouteManifest[]> {\n  const manifests: LoadedProgrammaticRouteManifest[] = [];\n  const routeFiles = findProgrammaticRouteFiles(options.root, options.srcDir);\n  if (routeFiles.length === 0) return manifests;\n\n  const { getProgrammaticRouteManifest } = await import(\"./routes\");\n\n  for (const filePath of routeFiles) {\n    const mod = await options.loadModule(filePath);\n    const manifest = getProgrammaticRouteManifest(mod);\n    if (manifest) {\n      manifests.push({ filePath, manifest });\n    }\n  }\n\n  return manifests;\n}\n\nexport function findProgrammaticRouteFiles(root: string, srcDir = \"src\"): string[] {\n  return findProgrammaticRouteFilesInDir(join(root, srcDir));\n}\n\nexport function findProgrammaticRouteFilesInDir(srcRoot: string): string[] {\n  const files: string[] = [];\n\n  for (const fileName of PROGRAMMATIC_ROUTE_FILE_NAMES) {\n    const filePath = join(srcRoot, fileName);\n    if (existsSync(filePath)) {\n      files.push(filePath);\n    }\n  }\n\n  return files;\n}\n\nexport async function discoverProgrammaticRoutePaths(\n  root: string,\n  srcDir = \"src\",\n): Promise<string[]> {\n  const paths = new Set<string>();\n  const files = new Set([\n    ...findProgrammaticRouteFiles(root, srcDir),\n    ...(await findProgrammaticRouteSourceFiles(join(root, srcDir))),\n  ]);\n\n  for (const filePath of files) {\n    const source = readFileSync(filePath, \"utf8\");\n    for (const routePath of scanProgrammaticPagePaths(source)) {\n      paths.add(routePath);\n    }\n  }\n\n  return Array.from(paths).sort();\n}\n\nasync function findProgrammaticRouteSourceFiles(srcRoot: string): Promise<string[]> {\n  if (!existsSync(srcRoot)) {\n    return [];\n  }\n\n  try {\n    const glob = await import(\"fast-glob\");\n    return await glob.default(\"**/*.{ts,tsx,js,jsx}\", {\n      cwd: srcRoot,\n      absolute: true,\n      ignore: [\n        \"**/*.d.ts\",\n        \"**/node_modules/**\",\n        \"**/.*/**\",\n        \"farm-routes.d.ts\",\n        \"farm-env.d.ts\",\n        \"lib/api.generated.ts\",\n      ],\n    });\n  } catch {\n    return [];\n  }\n}\n","import { readFile } from \"fs/promises\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport type { Metadata, RouteModule } from \"./types\";\nimport type { ComponentType } from \"react\";\nimport { requestAcceptsMarkdown } from \"./markdown\";\nimport {\n  resolveMdxConfig,\n  type FarmMdxComponents,\n  type FarmMdxResolvedConfig,\n} from \"./app-markdown-config\";\nexport {\n  resolveMdxConfig,\n  type FarmMdxComponent,\n  type FarmMdxComponents,\n  type FarmMdxResolvedConfig,\n  type FarmMdxUserConfig,\n} from \"./app-markdown-config\";\n\nexport interface FarmMarkdownPageSource {\n  source: string;\n  filePath: string;\n}\n\nexport interface FarmMarkdownPageModuleInput extends FarmMarkdownPageSource {\n  components?: FarmMdxComponents;\n  config?: FarmMdxResolvedConfig;\n}\n\nexport function isFarmMarkdownPageFile(filePath: string): boolean {\n  return /(^|[/\\\\])page\\.mdx?$/i.test(filePath);\n}\n\n/** Content type for Markdown responses, including agent-facing error bodies. */\nexport const FARM_MARKDOWN_CONTENT_TYPE = \"text/markdown; charset=utf-8\";\n\n/**\n * True when the client asked for Markdown — either via a `.md` path or an\n * `Accept: text/markdown` header. Used to serve a Markdown error body to agents\n * that navigate in Markdown, instead of the HTML error shell.\n */\nexport function farmRequestWantsMarkdown(\n  pathname: string,\n  accept: string | null | undefined,\n): boolean {\n  return pathname.toLowerCase().endsWith(\".md\") || requestAcceptsMarkdown(accept);\n}\n\n/**\n * A Markdown error document for agents that requested Markdown but hit an error\n * (typically a 404). Includes a short explanation and a link back to the site so\n * an agent can recover, satisfying the \"Markdown error body\" agent-readiness\n * expectation.\n */\nexport function createFarmMarkdownErrorBody(\n  status: number,\n  pathname: string,\n  homeHref = \"/\",\n): string {\n  const heading = status === 404 ? \"Page not found\" : `Request failed (${status})`;\n  return (\n    `# ${heading}\\n\\n` +\n    `No page is available at \\`${pathname}\\`. The URL may be incorrect, ` +\n    `or the page has not been published.\\n\\n` +\n    `Browse [the site homepage](${homeHref}) to find available pages.\\n`\n  );\n}\n\nexport function normalizeFarmMarkdownRoutePath(pathname: string): string {\n  const withoutExtension = pathname.replace(/\\.md$/i, \"\");\n  const normalized = withoutExtension.startsWith(\"/\") ? withoutExtension : `/${withoutExtension}`;\n  return normalized === \"/index\" ? \"/\" : normalized.replace(/\\/+$/g, \"\") || \"/\";\n}\n\nexport function parseMarkdownFrontmatter(source: string): {\n  frontmatter: Record<string, string>;\n  body: string;\n} {\n  if (!source.startsWith(\"---\")) {\n    return { frontmatter: {}, body: source };\n  }\n\n  const endIndex = source.indexOf(\"\\n---\", 3);\n  if (endIndex === -1) {\n    return { frontmatter: {}, body: source };\n  }\n\n  const frontmatterSource = source.slice(3, endIndex).trim();\n  const closingFenceEnd = endIndex + \"\\n---\".length;\n  const bodyStart =\n    source.slice(closingFenceEnd, closingFenceEnd + 2) === \"\\r\\n\"\n      ? closingFenceEnd + 2\n      : source[closingFenceEnd] === \"\\n\"\n        ? closingFenceEnd + 1\n        : closingFenceEnd;\n  const body = source.slice(bodyStart);\n  const frontmatter: Record<string, string> = {};\n\n  for (const line of frontmatterSource.split(/\\r?\\n/)) {\n    const separator = line.indexOf(\":\");\n    if (separator === -1) continue;\n    const key = line.slice(0, separator).trim();\n    const value = line\n      .slice(separator + 1)\n      .trim()\n      .replace(/^[\"']|[\"']$/g, \"\");\n    if (key && value) frontmatter[key] = value;\n  }\n\n  return { frontmatter, body };\n}\n\nexport function titleFromMarkdown(body: string, fallback?: string): string | undefined {\n  return body.match(/^#\\s+(.+)$/m)?.[1]?.trim() || fallback;\n}\n\nexport function createMarkdownMetadata(\n  source: string,\n  filePath: string,\n): (Metadata & Record<string, any>) | undefined {\n  const { frontmatter, body } = parseMarkdownFrontmatter(source);\n  const routeTitle = titleFromMarkdown(body);\n  const title = frontmatter.title || routeTitle;\n  const description = frontmatter.description;\n\n  if (!title && !description) {\n    return undefined;\n  }\n\n  return {\n    ...(title ? { title } : {}),\n    ...(description ? { description } : {}),\n    source: filePath,\n  };\n}\n\nasync function evaluateMdxSource(source: string, filePath: string) {\n  const [{ evaluate }, runtime, remarkGfmModule] = await Promise.all([\n    import(\"@mdx-js/mdx\"),\n    import(\"react/jsx-runtime\"),\n    import(\"remark-gfm\"),\n  ]);\n  const remarkGfm = remarkGfmModule.default;\n\n  return evaluate(source, {\n    ...runtime,\n    baseUrl: pathToFileURL(filePath),\n    remarkPlugins: [remarkGfm],\n  });\n}\n\nexport function createFarmMarkdownRouteModule(\n  input: FarmMarkdownPageModuleInput,\n): RouteModule & { source: string } {\n  const { body } = parseMarkdownFrontmatter(input.source);\n  const components = input.components || {};\n  const className = input.config?.className || \"farm-markdown\";\n  let evaluatedPromise: Promise<{ default: ComponentType<any> }> | undefined;\n\n  const loadContent = async () => {\n    evaluatedPromise ??= evaluateMdxSource(body, input.filePath) as Promise<{\n      default: ComponentType<any>;\n    }>;\n    return evaluatedPromise;\n  };\n\n  async function FarmMarkdownPage(props: any) {\n    const { createElement } = await import(\"react\");\n    const evaluated = await loadContent();\n    const MDXContent = evaluated.default;\n    return createElement(\n      \"article\",\n      { className, \"data-farm-markdown-page\": \"\" },\n      createElement(MDXContent, {\n        ...props,\n        components: {\n          ...components,\n          ...props?.components,\n        },\n      }),\n    );\n  }\n\n  return {\n    default: FarmMarkdownPage as unknown as RouteModule[\"default\"],\n    metadata: createMarkdownMetadata(input.source, input.filePath),\n    source: input.source,\n  };\n}\n\nexport async function createFarmMarkdownRouteModuleFromFile(\n  filePath: string,\n  options: {\n    components?: FarmMdxComponents;\n    config?: FarmMdxResolvedConfig;\n  } = {},\n) {\n  const source = await readFile(filePath, \"utf8\");\n  return createFarmMarkdownRouteModule({\n    source,\n    filePath,\n    components: options.components,\n    config: options.config,\n  });\n}\n\nexport async function loadFarmMdxComponents(\n  config: FarmMdxResolvedConfig | undefined,\n  options: {\n    root: string;\n    loadModule?: (modulePath: string) => Promise<unknown>;\n  },\n): Promise<FarmMdxComponents> {\n  const configured = config?.components;\n  if (!configured) {\n    return {};\n  }\n\n  if (typeof configured !== \"string\") {\n    return configured;\n  }\n\n  const modulePath = path.isAbsolute(configured) ? configured : path.join(options.root, configured);\n  const mod = options.loadModule\n    ? await options.loadModule(modulePath)\n    : await import(pathToFileURL(modulePath).href);\n  const maybeModule = mod as {\n    components?: FarmMdxComponents;\n    default?: FarmMdxComponents;\n  };\n\n  return maybeModule.components || maybeModule.default || {};\n}\n\nexport async function createFarmMarkdownSourceResponse(options: {\n  request: Request;\n  config?: FarmMdxResolvedConfig;\n  resolveSource: (\n    pathname: string,\n  ) => Promise<FarmMarkdownPageSource | null> | FarmMarkdownPageSource | null;\n}): Promise<Response | null> {\n  if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n    return null;\n  }\n  if (options.config?.markdownRoutes === false) {\n    return null;\n  }\n\n  const url = new URL(options.request.url);\n  const hasMarkdownExtension = url.pathname.toLowerCase().endsWith(\".md\");\n  if (!hasMarkdownExtension && !requestAcceptsMarkdown(options.request.headers.get(\"accept\"))) {\n    return null;\n  }\n\n  const targetPathname = normalizeFarmMarkdownRoutePath(url.pathname);\n  const source = await options.resolveSource(targetPathname);\n  if (!source) {\n    return null;\n  }\n\n  const headers = new Headers({\n    \"Content-Type\": \"text/markdown; charset=utf-8\",\n    \"Content-Location\": targetPathname === \"/\" ? \"/index.md\" : `${targetPathname}.md`,\n    \"Cache-Control\": \"public, s-maxage=60, stale-while-revalidate=300\",\n    \"X-Farm-Markdown-Route\": targetPathname,\n    \"X-Farm-Markdown-Source\": source.filePath,\n  });\n  if (!hasMarkdownExtension) {\n    headers.set(\"Vary\", \"Accept\");\n  }\n\n  return new Response(options.request.method === \"HEAD\" ? null : source.source, {\n    status: 200,\n    headers,\n  });\n}\n","/**\n * Controls when Farm loads and hydrates a server-rendered client boundary.\n *\n * `load` is the compatibility-first default. The deferred strategies keep the\n * server-rendered HTML visible while postponing the boundary's JavaScript.\n */\nexport type FarmIslandStrategy = \"load\" | \"interaction\" | \"visible\" | \"idle\";\n\nexport const FARM_ISLAND_STRATEGIES = [\"load\", \"interaction\", \"visible\", \"idle\"] as const;\n\nexport function isFarmIslandStrategy(value: unknown): value is FarmIslandStrategy {\n  return FARM_ISLAND_STRATEGIES.includes(value as FarmIslandStrategy);\n}\n","import fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { isFarmIslandStrategy, type FarmIslandStrategy } from \"../island\";\nimport type { FarmIsolatedClientHydrationMode } from \"../types\";\n\nfunction readIfExists(filePath: string): string | null {\n  try {\n    if (!filePath || !fs.existsSync(filePath)) {\n      return null;\n    }\n    return fs.readFileSync(filePath, \"utf-8\");\n  } catch {\n    return null;\n  }\n}\n\nexport function resolveModuleSourcePath(modulePath: string, root?: string): string | null {\n  const candidates = new Set<string>();\n  const withoutQuery = modulePath.split(\"?\")[0];\n\n  if (modulePath) {\n    candidates.add(modulePath);\n    candidates.add(withoutQuery);\n\n    if (modulePath.startsWith(\"file://\")) {\n      try {\n        candidates.add(fileURLToPath(modulePath));\n      } catch {\n        // ignore invalid file urls\n      }\n    }\n\n    if (modulePath.startsWith(\"/@fs/\")) {\n      // Vite emits /@fs/C:/... on Windows, where the leading slash is not part of the path.\n      const fsPath = withoutQuery.slice(\"/@fs/\".length);\n      candidates.add(path.normalize(/^[A-Za-z]:/.test(fsPath) ? fsPath : `/${fsPath}`));\n    }\n  }\n\n  if (root && modulePath) {\n    const normalized = withoutQuery.replace(/^\\/+/, \"\");\n    candidates.add(path.join(root, normalized));\n    candidates.add(path.resolve(root, normalized));\n  }\n\n  if (withoutQuery?.startsWith(\"/src/\")) {\n    const normalized = withoutQuery.replace(/^\\/+/, \"\");\n    candidates.add(path.join(process.cwd(), normalized));\n    candidates.add(path.resolve(process.cwd(), normalized));\n  }\n\n  for (const candidate of candidates) {\n    if (fs.existsSync(candidate)) {\n      return candidate;\n    }\n  }\n\n  return null;\n}\n\nexport interface ClientModuleMetadata {\n  isClientComponent: boolean;\n  shouldHydrate: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n  /**\n   * Set when the module would hydrate (client imports or an explicit hydrate\n   * export) but its default export is an async server component, which React\n   * cannot run in a client root. Hydration is suppressed so the\n   * server-rendered HTML stays intact instead of crashing to a blank page.\n   */\n  suppressedAsyncHydration?: true;\n}\n\nexport interface IsolatedClientBoundaryReference {\n  /** Absolute source path. Converted to a Vite URL only at the manifest edge. */\n  modulePath: string;\n  islandStrategy: FarmIslandStrategy;\n}\n\nexport interface ClientModuleHydrationPlan extends ClientModuleMetadata {\n  mode: FarmIsolatedClientHydrationMode;\n  legacyShouldHydrate: boolean;\n  legacyIslandStrategy: FarmIslandStrategy | null;\n  estimatedIsolatedRootCount: number;\n  isolatedHydrationEligible: boolean;\n  hasIsolatedClientBoundaries: boolean;\n  isolatedBoundaries: IsolatedClientBoundaryReference[];\n  costGuardExceeded?: true;\n  fallbackReason?: string;\n}\n\n/** @internal Largest measured statically bounded independent-root plan. */\nexport const FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES = 4;\n\nfunction isolatedHydrationBoundaryLimit(): number {\n  const benchmarkRoot = process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_ROOT;\n  const benchmarkLimit = Number(process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_LIMIT);\n  const resolvedBenchmarkRoot = benchmarkRoot ? path.resolve(benchmarkRoot) : null;\n  const isBenchmarkFixture =\n    process.env.FARM_INTERNAL_BENCHMARK === \"isolated-hydration\" &&\n    resolvedBenchmarkRoot !== null &&\n    (process.cwd() === resolvedBenchmarkRoot ||\n      process.cwd().startsWith(`${resolvedBenchmarkRoot}${path.sep}`));\n  return isBenchmarkFixture &&\n    Number.isSafeInteger(benchmarkLimit) &&\n    benchmarkLimit > FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES\n    ? benchmarkLimit\n    : FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES;\n}\n\ninterface ParsedClientModuleMetadata {\n  isClientComponent: boolean;\n  hasHydrateExport: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n}\n\nconst RESOLVABLE_SOURCE_EXTENSIONS = [\n  \".svelte\",\n  \".vue\",\n  \".tsx\",\n  \".ts\",\n  \".jsx\",\n  \".js\",\n  \".mts\",\n  \".mjs\",\n  \".cts\",\n  \".cjs\",\n] as const;\n\nexport function resolveFarmIsolatedClientHydrationMode(\n  mode: FarmIsolatedClientHydrationMode | undefined,\n  options: {\n    serverComponents?: boolean;\n    hasUnsupportedIntegrationProvider?: boolean;\n  } = {},\n): FarmIsolatedClientHydrationMode {\n  if (options.serverComponents) return \"off\";\n  if (mode === \"enabled\" && options.hasUnsupportedIntegrationProvider) return \"off\";\n  return mode ?? \"off\";\n}\n\nexport function hasUseClientDirective(content: string | null): boolean {\n  if (!content) {\n    return false;\n  }\n\n  // Fast path: directive at the very start of the file.\n  const normalized = content.trimStart();\n  if (normalized.startsWith(\"'use client'\") || normalized.startsWith('\"use client\"')) {\n    return true;\n  }\n  if (!normalized.includes(\"use client\")) {\n    return false;\n  }\n\n  // Directive-prologue semantics allow comments and other directives (e.g.\n  // \"use strict\") before \"use client\". Scan the leading string-literal\n  // statements with the comment-aware tokenizer.\n  for (const token of tokenizeModuleSource(content)) {\n    if (token.kind === \"string\") {\n      if (token.value === \"use client\") {\n        return true;\n      }\n      continue;\n    }\n    if (token.kind === \"punctuation\" && token.value === \";\") {\n      continue;\n    }\n    return false;\n  }\n  return false;\n}\n\nexport function hasHydrateExport(content: string | null): boolean {\n  if (!content) {\n    return false;\n  }\n  if (/\\bexport\\s+const\\s+hydrate\\s*=\\s*true\\b/.test(content)) {\n    return true;\n  }\n  // Export lists may carry several specifiers and as-renames; the module\n  // opts in when any specifier's *exported* name is hydrate.\n  for (const match of content.matchAll(/\\bexport\\s*\\{([^}]*)\\}/g)) {\n    for (const specifier of match[1].split(\",\")) {\n      const parts = specifier.trim().split(/\\s+as\\s+/);\n      const exportedName = (parts[1] ?? parts[0])?.trim();\n      if (exportedName === \"hydrate\") {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\ninterface ModuleSourceToken {\n  kind: \"identifier\" | \"string\" | \"punctuation\";\n  value: string;\n  line: number;\n}\n\nconst REGEXP_PREFIX_PUNCTUATION = new Set([\n  \"(\",\n  \"[\",\n  \"{\",\n  \",\",\n  \";\",\n  \":\",\n  \"=\",\n  \"!\",\n  \"?\",\n  \"&\",\n  \"|\",\n  \"+\",\n  \"-\",\n  \"*\",\n  \"%\",\n  \"^\",\n  \"~\",\n  \">\",\n]);\nconst REGEXP_PREFIX_KEYWORDS = new Set([\n  \"await\",\n  \"case\",\n  \"delete\",\n  \"do\",\n  \"else\",\n  \"in\",\n  \"instanceof\",\n  \"new\",\n  \"of\",\n  \"return\",\n  \"throw\",\n  \"typeof\",\n  \"void\",\n  \"yield\",\n]);\n\nfunction canStartRegularExpression(previous: ModuleSourceToken | undefined): boolean {\n  if (!previous) return true;\n  return previous.kind === \"identifier\"\n    ? REGEXP_PREFIX_KEYWORDS.has(previous.value)\n    : REGEXP_PREFIX_PUNCTUATION.has(previous.value);\n}\n\nfunction skipRegularExpression(content: string, startIndex: number): number | null {\n  let index = startIndex + 1;\n  let inCharacterClass = false;\n\n  while (index < content.length) {\n    const character = content[index];\n    if (character === \"\\n\" || character === \"\\r\") return null;\n    if (character === \"\\\\\") {\n      index += 2;\n      continue;\n    }\n    if (character === \"[\") {\n      inCharacterClass = true;\n      index++;\n      continue;\n    }\n    if (character === \"]\" && inCharacterClass) {\n      inCharacterClass = false;\n      index++;\n      continue;\n    }\n    if (character === \"/\" && !inCharacterClass) {\n      index++;\n      while (index < content.length && /[A-Za-z]/.test(content[index])) index++;\n      return index;\n    }\n    index++;\n  }\n\n  return null;\n}\n\nfunction tokenizeModuleSource(content: string): ModuleSourceToken[] {\n  const tokens: ModuleSourceToken[] = [];\n  let index = 0;\n  let line = 1;\n\n  while (index < content.length) {\n    const character = content[index];\n    if (/\\s/.test(character)) {\n      if (character === \"\\n\") line++;\n      index++;\n      continue;\n    }\n\n    if (character === \"/\" && content[index + 1] === \"/\") {\n      index += 2;\n      while (index < content.length && content[index] !== \"\\n\") index++;\n      continue;\n    }\n    if (character === \"/\" && content[index + 1] === \"*\") {\n      index += 2;\n      while (index < content.length) {\n        if (content[index] === \"\\n\") line++;\n        if (content[index] === \"*\" && content[index + 1] === \"/\") {\n          index += 2;\n          break;\n        }\n        index++;\n      }\n      continue;\n    }\n\n    if (character === \"/\" && canStartRegularExpression(tokens[tokens.length - 1])) {\n      const endIndex = skipRegularExpression(content, index);\n      if (endIndex !== null) {\n        index = endIndex;\n        continue;\n      }\n    }\n\n    if (character === '\"' || character === \"'\") {\n      const quote = character;\n      const tokenLine = line;\n      let value = \"\";\n      index++;\n      while (index < content.length) {\n        const next = content[index];\n        if (next === \"\\\\\") {\n          value += next;\n          if (index + 1 < content.length) value += content[index + 1];\n          index += 2;\n          continue;\n        }\n        if (next === quote) {\n          index++;\n          break;\n        }\n        if (next === \"\\n\") line++;\n        value += next;\n        index++;\n      }\n      tokens.push({ kind: \"string\", value, line: tokenLine });\n      continue;\n    }\n\n    if (character === \"`\") {\n      index++;\n      while (index < content.length) {\n        const next = content[index];\n        if (next === \"\\\\\") {\n          index += 2;\n          continue;\n        }\n        if (next === \"`\") {\n          index++;\n          break;\n        }\n        if (next === \"\\n\") line++;\n        index++;\n      }\n      continue;\n    }\n\n    if (/[A-Za-z_$]/.test(character)) {\n      const start = index++;\n      while (index < content.length && /[\\w$]/.test(content[index])) index++;\n      tokens.push({ kind: \"identifier\", value: content.slice(start, index), line });\n      continue;\n    }\n\n    tokens.push({ kind: \"punctuation\", value: character, line });\n    index++;\n  }\n\n  return tokens;\n}\n\nfunction isIslandExportStart(tokens: ModuleSourceToken[], index: number): boolean {\n  const token = tokens[index];\n  const previous = tokens[index - 1];\n  const startsStatement =\n    !previous ||\n    previous.value === \";\" ||\n    previous.value === \"{\" ||\n    previous.value === \"}\" ||\n    token.line > previous.line;\n  return (\n    startsStatement &&\n    token.value === \"export\" &&\n    tokens[index + 1]?.value === \"const\" &&\n    tokens[index + 2]?.value === \"island\"\n  );\n}\n\nexport function getIslandStrategyExport(content: string | null): FarmIslandStrategy | null {\n  if (!content) return null;\n\n  const tokens = tokenizeModuleSource(content);\n  for (let index = 0; index < tokens.length - 2; index++) {\n    if (!isIslandExportStart(tokens, index)) continue;\n\n    let valueIndex = index + 3;\n    if (tokens[valueIndex]?.value === \":\") {\n      while (valueIndex < tokens.length && tokens[valueIndex].value !== \"=\") valueIndex++;\n    }\n    if (tokens[valueIndex]?.value !== \"=\") break;\n    valueIndex++;\n\n    const literal = tokens[valueIndex];\n    if (!literal || literal.kind !== \"string\" || !isFarmIslandStrategy(literal.value)) break;\n\n    let trailingIndex = valueIndex + 1;\n    if (tokens[trailingIndex]?.value === \"as\" && tokens[trailingIndex + 1]?.value === \"const\") {\n      trailingIndex += 2;\n    }\n    const trailing = tokens[trailingIndex];\n    if (trailing && trailing.value !== \";\" && trailing.line === literal.line) break;\n    return literal.value;\n  }\n\n  if (tokens.some((_token, index) => isIslandExportStart(tokens, index))) {\n    throw new Error(\n      'Farm island configuration must be a static \"load\", \"interaction\", \"visible\", or \"idle\" string literal.',\n    );\n  }\n\n  return null;\n}\n\nexport function stripUseClientDirective(content: string): string {\n  // Comments (and other directives) may precede \"use client\"; keep them and\n  // remove only the directive itself.\n  return content.replace(\n    /^((?:\\s|\\/\\/[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/|(?:\"[^\"\\n]*\"|'[^'\\n]*')\\s*;?)*)([\"'])use client\\2\\s*;?\\s*/,\n    \"$1\",\n  );\n}\n\n/**\n * Best-effort static detection of an async default export, e.g.\n * `export default async function Page() {}`. Covers direct async\n * function/arrow default exports and `export default X` where `X` is a local\n * `async function X` or `X = async ...` declaration. Wrapped exports such as\n * `export default withAuth(Page)` cannot be resolved statically; the client\n * runtime guards against those at hydration time.\n */\nexport function hasAsyncDefaultExport(content: string | null): boolean {\n  if (!content) return false;\n\n  const tokens = tokenizeModuleSource(content);\n  for (let index = 0; index < tokens.length - 2; index++) {\n    const token = tokens[index];\n    if (token.kind !== \"identifier\" || token.value !== \"export\") continue;\n    if (tokens[index - 1]?.value === \".\") continue;\n    if (tokens[index + 1]?.value !== \"default\") continue;\n\n    const exported = tokens[index + 2];\n    if (exported.kind === \"identifier\" && exported.value === \"async\") {\n      return true;\n    }\n    if (\n      exported.kind === \"identifier\" &&\n      ![\"function\", \"class\"].includes(exported.value) &&\n      tokens[index + 3]?.value !== \"(\" &&\n      isAsyncLocalDeclaration(tokens, exported.value)\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction isAsyncLocalDeclaration(tokens: ModuleSourceToken[], name: string): boolean {\n  for (let index = 0; index < tokens.length - 2; index++) {\n    if (\n      tokens[index].value === \"async\" &&\n      tokens[index + 1]?.value === \"function\" &&\n      tokens[index + 2]?.value === name\n    ) {\n      return true;\n    }\n    if (\n      tokens[index].value === name &&\n      tokens[index + 1]?.value === \"=\" &&\n      tokens[index + 2]?.value === \"async\"\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction parseClientModuleMetadata(\n  content: string | null,\n  inspectIslandExport: boolean,\n): ParsedClientModuleMetadata {\n  if (!content) {\n    return {\n      isClientComponent: false,\n      hasHydrateExport: false,\n      islandStrategy: null,\n    };\n  }\n\n  const isClientComponent = hasUseClientDirective(content);\n  const hasHydrate = hasHydrateExport(content);\n  return {\n    isClientComponent,\n    hasHydrateExport: hasHydrate,\n    islandStrategy:\n      inspectIslandExport || isClientComponent || hasHydrate\n        ? getIslandStrategyExport(content)\n        : null,\n  };\n}\n\nexport function getClientModuleMetadata(modulePath: string, root?: string): ClientModuleMetadata {\n  const resolvedPath = resolveModuleSourcePath(modulePath, root);\n  return inspectClientModuleMetadata(resolvedPath, root, new Set(), true);\n}\n\n/**\n * Resolve hydration ownership without changing the legacy metadata contract.\n * The old metadata remains the conservative fallback; only an enabled and\n * completely supported graph moves ownership to leaf client modules.\n */\nexport function getClientModuleHydrationPlan(\n  modulePath: string,\n  root: string | undefined,\n  mode: FarmIsolatedClientHydrationMode = \"off\",\n): ClientModuleHydrationPlan {\n  const metadata = getClientModuleMetadata(modulePath, root);\n  const resolvedPath = resolveModuleSourcePath(modulePath, root);\n  const content = readIfExists(resolvedPath ?? \"\");\n  const parsed = parseClientModuleMetadata(content, true);\n  const emptyPlan = (\n    fallbackReason?: string,\n    costGuardExceeded = false,\n    estimatedIsolatedRootCount = 0,\n  ): ClientModuleHydrationPlan => ({\n    ...metadata,\n    mode,\n    legacyShouldHydrate: metadata.shouldHydrate,\n    legacyIslandStrategy: metadata.islandStrategy,\n    estimatedIsolatedRootCount,\n    isolatedHydrationEligible: false,\n    hasIsolatedClientBoundaries: false,\n    isolatedBoundaries: [],\n    ...(costGuardExceeded ? { costGuardExceeded: true as const } : {}),\n    ...(fallbackReason ? { fallbackReason } : {}),\n  });\n\n  if (mode === \"off\") return emptyPlan();\n  if (!resolvedPath) return emptyPlan(\"the owner source could not be resolved\");\n  if (parsed.isClientComponent) {\n    return emptyPlan(\"the owner is already a client component\");\n  }\n  if (parsed.hasHydrateExport) {\n    return emptyPlan(\"the owner explicitly exports `hydrate = true`\");\n  }\n\n  const inspection = collectIsolatedClientBoundaries(resolvedPath, root);\n  if (inspection.boundaries.length === 0) {\n    return emptyPlan(inspection.fallbackReason);\n  }\n  if (inspection.fallbackReason) {\n    return emptyPlan(\n      inspection.fallbackReason,\n      inspection.costGuardExceeded,\n      inspection.estimatedBoundaryCount,\n    );\n  }\n  const boundaryLimit = isolatedHydrationBoundaryLimit();\n  if (inspection.estimatedBoundaryCount > boundaryLimit) {\n    return emptyPlan(\n      `the client graph can create ${inspection.estimatedBoundaryCount} isolated roots, above the measured limit of ${boundaryLimit}`,\n      true,\n      inspection.estimatedBoundaryCount,\n    );\n  }\n\n  const enabled = mode === \"enabled\";\n  return {\n    ...metadata,\n    shouldHydrate: enabled ? false : metadata.shouldHydrate,\n    islandStrategy: enabled ? null : metadata.islandStrategy,\n    mode,\n    legacyShouldHydrate: metadata.shouldHydrate,\n    legacyIslandStrategy: metadata.islandStrategy,\n    estimatedIsolatedRootCount: inspection.estimatedBoundaryCount,\n    isolatedHydrationEligible: true,\n    hasIsolatedClientBoundaries: enabled,\n    isolatedBoundaries: inspection.boundaries,\n  };\n}\n\ninterface FarmIsolatedHydrationRoutePlan {\n  mode: FarmIsolatedClientHydrationMode;\n  shouldHydrate: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n  legacyShouldHydrate: boolean;\n  legacyIslandStrategy: FarmIslandStrategy | null;\n  estimatedIsolatedRootCount: number;\n  hasIsolatedClientBoundaries: boolean;\n  isolatedBoundaries: IsolatedClientBoundaryReference[];\n  costGuardExceeded?: true;\n  fallbackReason?: string;\n}\n\ninterface FarmIsolatedHydrationRouteOwner {\n  pattern: string;\n  depth: number;\n  metadata: FarmIsolatedHydrationRoutePlan;\n}\n\nfunction restoreRouteWideHydration(\n  metadata: FarmIsolatedHydrationRoutePlan,\n  fallbackReason?: string,\n): void {\n  metadata.shouldHydrate = metadata.legacyShouldHydrate;\n  metadata.islandStrategy = metadata.legacyIslandStrategy;\n  metadata.hasIsolatedClientBoundaries = false;\n  metadata.isolatedBoundaries = [];\n  if (fallbackReason) {\n    metadata.costGuardExceeded = true;\n    metadata.fallbackReason = fallbackReason;\n  }\n}\n\n/** @internal Applies the measured root budget to each complete layout and page chain. */\nexport function enforceFarmIsolatedHydrationRouteBudget(\n  layouts: FarmIsolatedHydrationRouteOwner[],\n  routes: FarmIsolatedHydrationRouteOwner[],\n  layoutAppliesToRoute: (layoutPattern: string, routePattern: string) => boolean,\n): void {\n  const boundaryLimit = isolatedHydrationBoundaryLimit();\n  const sortedLayouts = [...layouts].sort((left, right) => left.depth - right.depth);\n\n  for (const route of routes) {\n    if (route.metadata.mode !== \"enabled\") continue;\n    const applicableLayouts = sortedLayouts.filter((layout) =>\n      layoutAppliesToRoute(layout.pattern, route.pattern),\n    );\n    if (applicableLayouts.some((layout) => layout.metadata.shouldHydrate)) continue;\n\n    const layoutRootCount = applicableLayouts.reduce(\n      (count, layout) =>\n        count +\n        (layout.metadata.hasIsolatedClientBoundaries\n          ? layout.metadata.estimatedIsolatedRootCount\n          : 0),\n      0,\n    );\n    const routeRootCount = route.metadata.hasIsolatedClientBoundaries\n      ? route.metadata.estimatedIsolatedRootCount\n      : 0;\n    const totalRootCount = layoutRootCount + routeRootCount;\n    if (totalRootCount <= boundaryLimit) continue;\n\n    let accumulatedLayoutRoots = 0;\n    const overflowingLayout = applicableLayouts.find((layout) => {\n      if (layout.metadata.hasIsolatedClientBoundaries) {\n        accumulatedLayoutRoots += layout.metadata.estimatedIsolatedRootCount;\n      }\n      return accumulatedLayoutRoots > boundaryLimit;\n    });\n    const fallbackReason = `the matched route ${route.pattern} can create ${totalRootCount} isolated roots, above the measured limit of ${boundaryLimit}`;\n\n    if (overflowingLayout) {\n      restoreRouteWideHydration(overflowingLayout.metadata, fallbackReason);\n    } else if (route.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(route.metadata, fallbackReason);\n    }\n  }\n\n  for (const layout of sortedLayouts) {\n    const hasRouteWideAncestor = sortedLayouts.some(\n      (ancestor) =>\n        ancestor !== layout &&\n        ancestor.depth < layout.depth &&\n        ancestor.metadata.shouldHydrate &&\n        layoutAppliesToRoute(ancestor.pattern, layout.pattern),\n    );\n    if (hasRouteWideAncestor && layout.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(layout.metadata);\n    }\n  }\n\n  for (const route of routes) {\n    const hasRouteWideLayout = sortedLayouts.some(\n      (layout) =>\n        layout.metadata.shouldHydrate && layoutAppliesToRoute(layout.pattern, route.pattern),\n    );\n    if (hasRouteWideLayout && route.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(route.metadata);\n    }\n  }\n}\n\n/**\n * The first compiler pass intentionally accepts only statically named React\n * component exports. A rejected module retains route-wide hydration.\n */\nexport function isIsolatableClientBoundarySource(content: string | null): boolean {\n  if (!content || !hasUseClientDirective(content)) return false;\n  if (/\\bexport\\s*\\{/.test(content) || /\\bexport\\s*\\*/.test(content)) return false;\n  return (\n    /\\bexport\\s+default\\s+(?!(?:type|interface)\\b)/.test(content) ||\n    /\\bexport\\s+(?:async\\s+)?function\\s+[A-Z][$\\w]*/.test(content) ||\n    /\\bexport\\s+(?:const|let|var|class)\\s+[A-Z][$\\w]*/.test(content)\n  );\n}\n\nfunction getStaticImportBindings(content: string | null): Map<string, string[]> {\n  const bindings = new Map<string, string[]>();\n  if (!content) return bindings;\n  const tokens = tokenizeModuleSource(content);\n\n  for (let index = 0; index < tokens.length; index++) {\n    if (tokens[index].value !== \"import\" || tokens[index - 1]?.value === \".\") continue;\n    const first = tokens[index + 1];\n    if (!first || first.value === \"type\" || first.value === \"(\" || first.kind === \"string\") {\n      continue;\n    }\n\n    let fromIndex = -1;\n    for (let cursor = index + 1; cursor < tokens.length; cursor++) {\n      if (tokens[cursor].value === \";\") break;\n      if (tokens[cursor].value === \"from\" && tokens[cursor + 1]?.kind === \"string\") {\n        fromIndex = cursor;\n        break;\n      }\n    }\n    if (fromIndex === -1) continue;\n    const specifier = tokens[fromIndex + 1].value;\n    const clause = tokens.slice(index + 1, fromIndex);\n    const localNames: string[] = [];\n\n    if (clause[0]?.kind === \"identifier\" && clause[0].value !== \"type\") {\n      localNames.push(clause[0].value);\n    }\n    const namespaceAs = clause.findIndex(\n      (token, clauseIndex) => token.value === \"*\" && clause[clauseIndex + 1]?.value === \"as\",\n    );\n    if (namespaceAs !== -1 && clause[namespaceAs + 2]?.kind === \"identifier\") {\n      localNames.push(clause[namespaceAs + 2].value);\n    }\n\n    const openingBrace = clause.findIndex((token) => token.value === \"{\");\n    const closingBrace = clause.findIndex(\n      (token, clauseIndex) => clauseIndex > openingBrace && token.value === \"}\",\n    );\n    if (openingBrace !== -1 && closingBrace !== -1) {\n      let entryStart = openingBrace + 1;\n      for (let cursor = entryStart; cursor <= closingBrace; cursor++) {\n        if (cursor !== closingBrace && clause[cursor]?.value !== \",\") continue;\n        const entry = clause.slice(entryStart, cursor).filter((token) => token.value !== \"type\");\n        const asIndex = entry.findIndex((token) => token.value === \"as\");\n        const local = asIndex === -1 ? entry[0] : entry[asIndex + 1];\n        if (local?.kind === \"identifier\") localNames.push(local.value);\n        entryStart = cursor + 1;\n      }\n    }\n\n    bindings.set(\n      specifier,\n      Array.from(new Set([...(bindings.get(specifier) ?? []), ...localNames])),\n    );\n  }\n\n  return bindings;\n}\n\n/**\n * Elements whose content model the HTML parser enforces. A boundary marker\n * emitted inside one of these is relocated or ignored before any script runs:\n * in a table the marker and its row are foster-parented out of the table, in a\n * select the options stop being direct children and the control renders empty,\n * and inside svg the marker is created in the SVG namespace as an unknown\n * element whose children never render. RFC 0001 requires these to take the\n * route-wide fallback.\n */\nconst PARSER_SENSITIVE_JSX_CONTAINERS = new Set([\n  \"table\",\n  \"thead\",\n  \"tbody\",\n  \"tfoot\",\n  \"tr\",\n  \"select\",\n  \"optgroup\",\n  \"svg\",\n]);\n\n/**\n * Names a parser-sensitive element that encloses a use of one of the bindings,\n * or undefined when every use is in ordinary flow content.\n *\n * Ambiguity resolves toward reporting a container: the caller turns a hit into\n * the complete route-wide fallback, which is always correct, while a miss would\n * leave the silent DOM corruption in place.\n */\nfunction findParserSensitiveJsxContainer(\n  content: string | null,\n  localBindings: string[],\n): string | undefined {\n  if (!content || localBindings.length === 0) return undefined;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  const openDepth = new Map<string, number>();\n\n  const isSelfClosing = (openingIndex: number): boolean => {\n    for (let index = openingIndex; index < tokens.length; index++) {\n      if (tokens[index].value === \">\") return tokens[index - 1]?.value === \"/\";\n    }\n    return false;\n  };\n\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value !== \"<\") continue;\n\n    if (tokens[index + 1].value === \"/\") {\n      const closing = tokens[index + 2]?.value;\n      if (closing && openDepth.has(closing)) {\n        openDepth.set(closing, Math.max(0, (openDepth.get(closing) ?? 0) - 1));\n      }\n      continue;\n    }\n\n    const tag = tokens[index + 1].value;\n    if (names.has(tag)) {\n      for (const [container, depth] of openDepth) {\n        if (depth > 0) return container;\n      }\n      continue;\n    }\n    if (PARSER_SENSITIVE_JSX_CONTAINERS.has(tag) && !isSelfClosing(index)) {\n      openDepth.set(tag, (openDepth.get(tag) ?? 0) + 1);\n    }\n  }\n\n  return undefined;\n}\n\nfunction countStaticJsxUses(content: string | null, localBindings: string[]): number {\n  if (!content || localBindings.length === 0) return 0;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  let count = 0;\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value === \"<\" && names.has(tokens[index + 1].value)) count++;\n  }\n  return count;\n}\n\nfunction findMatchingToken(\n  tokens: ModuleSourceToken[],\n  openingIndex: number,\n  opening: string,\n  closing: string,\n): number {\n  let depth = 0;\n  for (let index = openingIndex; index < tokens.length; index++) {\n    if (tokens[index].value === opening) depth++;\n    if (tokens[index].value !== closing) continue;\n    depth--;\n    if (depth === 0) return index;\n  }\n  return tokens.length - 1;\n}\n\nfunction containsClientJsx(\n  tokens: ModuleSourceToken[],\n  start: number,\n  end: number,\n  clientBindings: Set<string>,\n): boolean {\n  for (let index = start; index < end; index++) {\n    if (tokens[index].value === \"<\" && clientBindings.has(tokens[index + 1]?.value)) return true;\n  }\n  return false;\n}\n\nfunction findStatementEnd(tokens: ModuleSourceToken[], start: number): number {\n  let parentheses = 0;\n  let brackets = 0;\n  let braces = 0;\n  const statementStarters = new Set([\n    \"class\",\n    \"const\",\n    \"export\",\n    \"function\",\n    \"import\",\n    \"let\",\n    \"var\",\n  ]);\n  for (let index = start; index < tokens.length; index++) {\n    const value = tokens[index].value;\n    if (\n      index > start &&\n      parentheses === 0 &&\n      brackets === 0 &&\n      braces === 0 &&\n      tokens[index].line > tokens[index - 1].line &&\n      statementStarters.has(value)\n    ) {\n      return index;\n    }\n    if (value === \";\" && parentheses === 0 && brackets === 0 && braces === 0) return index;\n    if (value === \"(\") parentheses++;\n    if (value === \")\") parentheses--;\n    if (value === \"[\") brackets++;\n    if (value === \"]\") brackets--;\n    if (value === \"{\") braces++;\n    if (value === \"}\") braces--;\n  }\n  return tokens.length;\n}\n\nfunction getClientRenderingHelpers(\n  tokens: ModuleSourceToken[],\n  clientBindings: Set<string>,\n): Set<string> {\n  const helperBodies = new Map<string, [start: number, end: number]>();\n  for (let index = 0; index < tokens.length; index++) {\n    let helperName: string | undefined;\n    let bodyStart = -1;\n    let bodyEnd = -1;\n\n    if (tokens[index].value === \"function\" && tokens[index + 1]?.kind === \"identifier\") {\n      helperName = tokens[index + 1].value;\n      const parametersStart = tokens.findIndex(\n        (token, tokenIndex) => tokenIndex > index + 1 && token.value === \"(\",\n      );\n      const parametersEnd =\n        parametersStart === -1 ? index + 1 : findMatchingToken(tokens, parametersStart, \"(\", \")\");\n      bodyStart = tokens.findIndex(\n        (token, tokenIndex) => tokenIndex > parametersEnd && token.value === \"{\",\n      );\n      if (bodyStart !== -1) bodyEnd = findMatchingToken(tokens, bodyStart, \"{\", \"}\");\n    } else if (\n      (tokens[index].value === \"const\" ||\n        tokens[index].value === \"let\" ||\n        tokens[index].value === \"var\") &&\n      tokens[index + 1]?.kind === \"identifier\"\n    ) {\n      helperName = tokens[index + 1].value;\n      let assignmentIndex = -1;\n      let arrowIndex = -1;\n      for (let cursor = index + 2; cursor < tokens.length; cursor++) {\n        if (tokens[cursor].value === \";\") break;\n        if (assignmentIndex === -1 && tokens[cursor].value === \"=\") assignmentIndex = cursor;\n        if (tokens[cursor].value === \"=\" && tokens[cursor + 1]?.value === \">\") {\n          arrowIndex = cursor;\n          break;\n        }\n      }\n      if (arrowIndex !== -1) {\n        bodyStart = arrowIndex + 2;\n        bodyEnd =\n          tokens[bodyStart]?.value === \"{\"\n            ? findMatchingToken(tokens, bodyStart, \"{\", \"}\")\n            : findStatementEnd(tokens, bodyStart);\n      } else if (assignmentIndex !== -1) {\n        bodyStart = assignmentIndex + 1;\n        bodyEnd = findStatementEnd(tokens, bodyStart);\n      }\n    }\n\n    if (helperName && bodyStart !== -1 && bodyEnd !== -1) {\n      helperBodies.set(helperName, [bodyStart, bodyEnd]);\n    }\n  }\n\n  const helpers = new Set<string>();\n  let addedHelper = true;\n  while (addedHelper) {\n    addedHelper = false;\n    for (const [helperName, [bodyStart, bodyEnd]] of helperBodies) {\n      if (helpers.has(helperName)) continue;\n      const rendersClientBoundary =\n        containsClientJsx(tokens, bodyStart, bodyEnd, clientBindings) ||\n        tokens.slice(bodyStart, bodyEnd).some((token) => helpers.has(token.value));\n      if (!rendersClientBoundary) continue;\n      helpers.add(helperName);\n      addedHelper = true;\n    }\n  }\n  return helpers;\n}\n\n/**\n * True when a boundary is handed a React element, as JSX children or as an\n * element-valued prop.\n *\n * Boundary props cross to the browser as JSON, and an element cannot be\n * serialized. Without this check the SSR wrapper drops the marker for that\n * boundary and the component renders as ordinary server markup that nothing\n * ever hydrates, leaving an interactive-looking widget permanently dead with\n * no browser-visible diagnostic. String and number children serialize fine and\n * are deliberately not flagged.\n */\nfunction passesElementValuedProps(content: string | null, localBindings: string[]): boolean {\n  if (!content || localBindings.length === 0) return false;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value !== \"<\" || !names.has(tokens[index + 1].value)) continue;\n    const name = tokens[index + 1].value;\n\n    // Walk the opening tag, watching for an element inside an attribute\n    // expression such as icon={<Icon />}.\n    let cursor = index + 2;\n    let braceDepth = 0;\n    let selfClosing = false;\n    for (; cursor < tokens.length; cursor++) {\n      const value = tokens[cursor].value;\n      if (value === \"{\") braceDepth++;\n      else if (value === \"}\") braceDepth--;\n      else if (value === \"<\" && braceDepth > 0) return true;\n      else if (value === \">\" && braceDepth === 0) {\n        selfClosing = tokens[cursor - 1]?.value === \"/\";\n        break;\n      }\n    }\n    if (selfClosing || cursor >= tokens.length) continue;\n\n    // The first tag after the opening one decides it: the boundary's own\n    // closing tag means no element children, anything else is an element child.\n    for (let child = cursor + 1; child < tokens.length; child++) {\n      if (tokens[child].value !== \"<\") continue;\n      const closesBoundary = tokens[child + 1]?.value === \"/\" && tokens[child + 2]?.value === name;\n      if (!closesBoundary) return true;\n      break;\n    }\n  }\n\n  return false;\n}\n\nfunction hasDynamicJsxCardinality(content: string | null, localBindings: string[]): boolean {\n  if (!content || localBindings.length === 0) return false;\n  const clientBindings = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  const renderingHelpers = getClientRenderingHelpers(tokens, clientBindings);\n  const containsDynamicRenderer = (start: number, end: number) =>\n    containsClientJsx(tokens, start, end, clientBindings) ||\n    tokens.slice(start, end).some((token) => renderingHelpers.has(token.value));\n\n  for (let index = 0; index < tokens.length; index++) {\n    let callStart = -1;\n    if (\n      tokens[index].value === \".\" &&\n      (tokens[index + 1]?.value === \"map\" || tokens[index + 1]?.value === \"flatMap\") &&\n      tokens[index + 2]?.value === \"(\"\n    ) {\n      callStart = index + 2;\n    } else if (\n      tokens[index].value === \"Array\" &&\n      tokens[index + 1]?.value === \".\" &&\n      tokens[index + 2]?.value === \"from\" &&\n      tokens[index + 3]?.value === \"(\"\n    ) {\n      callStart = index + 3;\n    }\n    if (callStart !== -1) {\n      const callEnd = findMatchingToken(tokens, callStart, \"(\", \")\");\n      if (containsDynamicRenderer(callStart + 1, callEnd)) return true;\n      index = callEnd;\n      continue;\n    }\n\n    if (\n      (tokens[index].value === \"for\" || tokens[index].value === \"while\") &&\n      tokens[index + 1]?.value === \"(\"\n    ) {\n      const conditionEnd = findMatchingToken(tokens, index + 1, \"(\", \")\");\n      const bodyStart = conditionEnd + 1;\n      const bodyEnd =\n        tokens[bodyStart]?.value === \"{\"\n          ? findMatchingToken(tokens, bodyStart, \"{\", \"}\")\n          : tokens.findIndex((token, tokenIndex) => tokenIndex > bodyStart && token.value === \";\");\n      if (containsDynamicRenderer(bodyStart, bodyEnd === -1 ? tokens.length : bodyEnd)) return true;\n    }\n  }\n\n  return false;\n}\n\nfunction collectIsolatedClientBoundaries(\n  ownerPath: string,\n  root: string | undefined,\n): {\n  boundaries: IsolatedClientBoundaryReference[];\n  estimatedBoundaryCount: number;\n  costGuardExceeded?: boolean;\n  fallbackReason?: string;\n} {\n  const boundaries = new Map<string, IsolatedClientBoundaryReference>();\n  const estimates = new Map<string, number>();\n  const visiting = new Set<string>();\n  let fallbackReason: string | undefined;\n  let costGuardExceeded = false;\n  const projectRoot = root ? path.resolve(root) : undefined;\n\n  const visit = (moduleSourcePath: string): number => {\n    if (fallbackReason) return 0;\n    const cached = estimates.get(moduleSourcePath);\n    if (cached !== undefined) return cached;\n    if (visiting.has(moduleSourcePath)) return 0;\n    visiting.add(moduleSourcePath);\n    const content = readIfExists(moduleSourcePath);\n    const parsed = parseClientModuleMetadata(content, false);\n\n    if (parsed.isClientComponent) {\n      if (projectRoot && !path.resolve(moduleSourcePath).startsWith(`${projectRoot}${path.sep}`)) {\n        fallbackReason = `client boundary ${moduleSourcePath} is outside the application root`;\n        return 0;\n      }\n      if (!isIsolatableClientBoundarySource(content)) {\n        fallbackReason = `client boundary ${moduleSourcePath} uses an unsupported export shape`;\n        return 0;\n      }\n      boundaries.set(moduleSourcePath, {\n        modulePath: moduleSourcePath,\n        islandStrategy: parsed.islandStrategy ?? \"load\",\n      });\n      estimates.set(moduleSourcePath, 1);\n      visiting.delete(moduleSourcePath);\n      return 1;\n    }\n\n    if (parsed.hasHydrateExport) {\n      fallbackReason = `imported module ${moduleSourcePath} explicitly exports hydrate = true`;\n      return 0;\n    }\n\n    const importedBindings = getStaticImportBindings(content);\n    let estimatedBoundaryCount = 0;\n    for (const specifier of new Set(getImportSpecifiers(content))) {\n      const importedPath = resolveImportedModuleSourcePath(moduleSourcePath, specifier, root);\n      if (!importedPath) continue;\n      if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n        const packageMetadata = inspectPackageClientBoundary(importedPath, root, new Set());\n        if (packageMetadata.shouldHydrate) {\n          fallbackReason = `package client boundary ${specifier} cannot yet be isolated`;\n          return 0;\n        }\n        continue;\n      }\n      const importedBoundaryCount = visit(importedPath);\n      if (fallbackReason || importedBoundaryCount === 0) continue;\n      const localBindings = importedBindings.get(specifier) ?? [];\n      const staticUses = countStaticJsxUses(content, localBindings);\n      if (staticUses > 0) {\n        const container = findParserSensitiveJsxContainer(content, localBindings);\n        if (container) {\n          fallbackReason = `the client boundary imported from ${specifier} renders inside <${container}>, where the HTML parser relocates its hydration marker`;\n          return 0;\n        }\n        if (passesElementValuedProps(content, localBindings)) {\n          fallbackReason = `the client boundary imported from ${specifier} receives React elements, which cannot cross the boundary as serialized props`;\n          return 0;\n        }\n      }\n      if (staticUses > 0 && hasDynamicJsxCardinality(content, localBindings)) {\n        fallbackReason = `the client boundary count imported from ${specifier} is data-dependent`;\n        costGuardExceeded = true;\n        return 0;\n      }\n      estimatedBoundaryCount += importedBoundaryCount * Math.max(1, staticUses);\n    }\n\n    estimates.set(moduleSourcePath, estimatedBoundaryCount);\n    visiting.delete(moduleSourcePath);\n    return estimatedBoundaryCount;\n  };\n\n  const estimatedBoundaryCount = visit(ownerPath);\n  return {\n    boundaries: Array.from(boundaries.values()),\n    estimatedBoundaryCount,\n    costGuardExceeded,\n    fallbackReason,\n  };\n}\n\nexport function isClientComponentModule(modulePath: string, root?: string): boolean {\n  return getClientModuleMetadata(modulePath, root).isClientComponent;\n}\n\nexport function shouldHydrateModule(modulePath: string, root?: string): boolean {\n  return getClientModuleMetadata(modulePath, root).shouldHydrate;\n}\n\nfunction inspectClientModuleMetadata(\n  resolvedPath: string | null,\n  root: string | undefined,\n  visited: Set<string>,\n  inspectIslandExport: boolean,\n): ClientModuleMetadata {\n  if (!resolvedPath || visited.has(resolvedPath)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n    };\n  }\n\n  visited.add(resolvedPath);\n\n  const content = readIfExists(resolvedPath);\n  const parsed = parseClientModuleMetadata(content, inspectIslandExport);\n  if (parsed.isClientComponent) {\n    return {\n      isClientComponent: true,\n      shouldHydrate: true,\n      islandStrategy: parsed.islandStrategy ?? \"load\",\n    };\n  }\n\n  let importsClientBoundary = false;\n  let importedIslandStrategy: FarmIslandStrategy | null = null;\n  for (const specifier of getImportSpecifiers(content)) {\n    const importedPath = resolveImportedModuleSourcePath(resolvedPath, specifier, root);\n    const importedMetadata =\n      !specifier.startsWith(\".\") && !specifier.startsWith(\"/\")\n        ? inspectPackageClientBoundary(importedPath, root, visited)\n        : inspectClientModuleMetadata(importedPath, root, visited, false);\n    if (importedMetadata.isClientComponent || importedMetadata.shouldHydrate) {\n      importsClientBoundary = true;\n      if (importedIslandStrategy === null) {\n        importedIslandStrategy = importedMetadata.islandStrategy;\n      } else if (importedIslandStrategy !== importedMetadata.islandStrategy) {\n        // One route-level React root cannot honor multiple schedules safely.\n        // Fall back to eager hydration when its imported boundaries disagree.\n        importedIslandStrategy = \"load\";\n      }\n    }\n  }\n\n  const shouldHydrate = parsed.hasHydrateExport || importsClientBoundary;\n\n  // React cannot run an async component in a client root: hydrating the route\n  // module would throw, blank the server-rendered HTML, and re-run the page's\n  // data fetching in a loop. Keep async server pages server-only even when\n  // they import client components.\n  if (shouldHydrate && hasAsyncDefaultExport(content)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n      suppressedAsyncHydration: true,\n    };\n  }\n\n  return {\n    isClientComponent: false,\n    shouldHydrate,\n    islandStrategy: shouldHydrate\n      ? (parsed.islandStrategy ?? importedIslandStrategy ?? \"load\")\n      : null,\n  };\n}\n\nfunction inspectPackageClientBoundary(\n  resolvedPath: string | null,\n  root: string | undefined,\n  visited: Set<string>,\n): ClientModuleMetadata {\n  if (!resolvedPath || visited.has(resolvedPath)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n    };\n  }\n\n  visited.add(resolvedPath);\n  const content = readIfExists(resolvedPath);\n  const parsed = parseClientModuleMetadata(content, false);\n  let importsClientBoundary = false;\n  let importedIslandStrategy: FarmIslandStrategy | null = null;\n\n  // Package entry points commonly re-export their React implementation from a\n  // relative file. Follow only files inside that package entry graph: scanning\n  // bare dependencies here would incorrectly turn server package APIs into\n  // client boundaries because of unrelated transitive imports.\n  for (const specifier of getImportSpecifiers(content)) {\n    if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) continue;\n    const importedPath = resolveImportedModuleSourcePath(resolvedPath, specifier, root);\n    const importedMetadata = inspectPackageClientBoundary(importedPath, root, visited);\n    if (!importedMetadata.shouldHydrate) continue;\n    importsClientBoundary = true;\n    if (importedIslandStrategy === null) {\n      importedIslandStrategy = importedMetadata.islandStrategy;\n    } else if (importedIslandStrategy !== importedMetadata.islandStrategy) {\n      importedIslandStrategy = \"load\";\n    }\n  }\n\n  const shouldHydrate =\n    parsed.isClientComponent || parsed.hasHydrateExport || importsClientBoundary;\n  return {\n    isClientComponent: parsed.isClientComponent,\n    shouldHydrate,\n    islandStrategy: shouldHydrate\n      ? (parsed.islandStrategy ?? importedIslandStrategy ?? \"load\")\n      : null,\n  };\n}\n\nfunction getImportSpecifiers(content: string | null): string[] {\n  if (!content) return [];\n\n  const tokens = tokenizeModuleSource(content);\n  const matches = new Set<string>();\n  let braceDepth = 0;\n\n  for (let index = 0; index < tokens.length; index++) {\n    const keyword = tokens[index];\n    if (keyword.value === \"{\") {\n      braceDepth++;\n      continue;\n    }\n    if (keyword.value === \"}\") {\n      braceDepth = Math.max(0, braceDepth - 1);\n      continue;\n    }\n    if (braceDepth !== 0) continue;\n    if (keyword.kind !== \"identifier\" || ![\"import\", \"export\"].includes(keyword.value)) {\n      continue;\n    }\n\n    const previous = tokens[index - 1];\n    if (previous?.value === \".\") continue;\n\n    const first = tokens[index + 1];\n    if (!first || first.value === \"type\" || first.value === \"(\" || first.value === \".\") {\n      continue;\n    }\n\n    let specifier: string | undefined;\n    if (keyword.value === \"import\" && first.kind === \"string\") {\n      specifier = first.value;\n    } else {\n      if (keyword.value === \"export\" && first.value !== \"{\" && first.value !== \"*\") {\n        continue;\n      }\n\n      let fromIndex = -1;\n      for (let cursor = index + 1; cursor < tokens.length; cursor++) {\n        const token = tokens[cursor];\n        if (token.value === \";\") break;\n        if (token.value === \"from\" && tokens[cursor + 1]?.kind === \"string\") {\n          fromIndex = cursor;\n          break;\n        }\n      }\n      if (fromIndex === -1 || isTypeOnlyNamedClause(tokens, index + 1, fromIndex)) {\n        continue;\n      }\n      specifier = tokens[fromIndex + 1].value;\n    }\n\n    if (!specifier || specifier.startsWith(\"node:\") || specifier.includes(\"?\")) {\n      continue;\n    }\n    matches.add(specifier);\n  }\n\n  return Array.from(matches);\n}\n\nfunction isTypeOnlyNamedClause(\n  tokens: ModuleSourceToken[],\n  startIndex: number,\n  endIndex: number,\n): boolean {\n  if (tokens[startIndex]?.value !== \"{\") return false;\n\n  const closingBraceIndex = tokens.findIndex(\n    (token, index) => index > startIndex && index < endIndex && token.value === \"}\",\n  );\n  if (closingBraceIndex === -1) return false;\n\n  let entryStartsAt = startIndex + 1;\n  for (let index = entryStartsAt; index <= closingBraceIndex; index++) {\n    if (index !== closingBraceIndex && tokens[index]?.value !== \",\") continue;\n    const entry = tokens.slice(entryStartsAt, index);\n    if (entry.length > 0 && entry[0].value !== \"type\") return false;\n    entryStartsAt = index + 1;\n  }\n  return true;\n}\n\nfunction resolveImportedModuleSourcePath(\n  importerPath: string,\n  specifier: string,\n  root?: string,\n): string | null {\n  if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n    return resolvePackageModuleSourcePath(importerPath, specifier, root);\n  }\n\n  const candidates = new Set<string>();\n  const basePath = specifier.startsWith(\".\")\n    ? path.resolve(path.dirname(importerPath), specifier)\n    : root\n      ? path.resolve(root, specifier.replace(/^\\/+/, \"\"))\n      : path.resolve(specifier);\n\n  candidates.add(basePath);\n  return resolveSourceCandidate(candidates);\n}\n\nfunction resolvePackageModuleSourcePath(\n  importerPath: string,\n  specifier: string,\n  root?: string,\n): string | null {\n  const packageParts = specifier.split(\"/\");\n  const packageName = specifier.startsWith(\"@\")\n    ? packageParts.slice(0, 2).join(\"/\")\n    : packageParts[0];\n  const packageSubpath = packageParts.slice(packageName.startsWith(\"@\") ? 2 : 1).join(\"/\");\n  const packageDirectory = findPackageDirectory(importerPath, packageName, root);\n  if (!packageDirectory) return null;\n\n  const packageJsonPath = path.join(packageDirectory, \"package.json\");\n  const packageJson = readPackageJson(packageJsonPath);\n  const exportKey = packageSubpath ? `./${packageSubpath}` : \".\";\n  const exportTarget = resolvePackageExport(packageJson?.exports, exportKey);\n  const candidates = new Set<string>();\n\n  if (exportTarget?.startsWith(\"./\")) {\n    candidates.add(path.resolve(packageDirectory, exportTarget));\n  }\n  if (packageSubpath) {\n    candidates.add(path.join(packageDirectory, packageSubpath));\n  } else {\n    for (const entry of [packageJson?.browser, packageJson?.module, packageJson?.main]) {\n      if (typeof entry === \"string\") candidates.add(path.resolve(packageDirectory, entry));\n    }\n    candidates.add(path.join(packageDirectory, \"index\"));\n  }\n\n  return resolveSourceCandidate(candidates);\n}\n\nfunction findPackageDirectory(\n  importerPath: string,\n  packageName: string,\n  root?: string,\n): string | null {\n  const searchRoots = new Set<string>();\n  let current = path.dirname(importerPath);\n  while (true) {\n    searchRoots.add(current);\n    const parent = path.dirname(current);\n    if (parent === current) break;\n    current = parent;\n  }\n  if (root) {\n    current = path.resolve(root);\n    while (true) {\n      searchRoots.add(current);\n      const parent = path.dirname(current);\n      if (parent === current) break;\n      current = parent;\n    }\n  }\n\n  for (const searchRoot of searchRoots) {\n    const packageDirectory = path.join(searchRoot, \"node_modules\", packageName);\n    if (fs.existsSync(path.join(packageDirectory, \"package.json\"))) {\n      return packageDirectory;\n    }\n  }\n  return null;\n}\n\nfunction readPackageJson(packageJsonPath: string): Record<string, any> | null {\n  try {\n    return JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n  } catch {\n    return null;\n  }\n}\n\nfunction resolvePackageExport(exportsField: unknown, exportKey: string): string | null {\n  if (typeof exportsField === \"string\") {\n    return exportKey === \".\" ? exportsField : null;\n  }\n  if (Array.isArray(exportsField)) {\n    for (const candidate of exportsField) {\n      const resolved = resolvePackageExport(candidate, exportKey);\n      if (resolved) return resolved;\n    }\n    return null;\n  }\n  if (!exportsField || typeof exportsField !== \"object\") return null;\n\n  const entries = Object.entries(exportsField as Record<string, unknown>);\n  const subpathExports = entries.some(([key]) => key.startsWith(\".\"));\n  if (subpathExports) {\n    const exact = (exportsField as Record<string, unknown>)[exportKey];\n    if (exact !== undefined) return resolveConditionalExportTarget(exact);\n\n    for (const [key, value] of entries) {\n      const wildcardIndex = key.indexOf(\"*\");\n      if (wildcardIndex === -1) continue;\n      const prefix = key.slice(0, wildcardIndex);\n      const suffix = key.slice(wildcardIndex + 1);\n      if (!exportKey.startsWith(prefix) || !exportKey.endsWith(suffix)) continue;\n      const wildcard = exportKey.slice(prefix.length, exportKey.length - suffix.length);\n      const target = resolveConditionalExportTarget(value);\n      return target?.replace(\"*\", wildcard) ?? null;\n    }\n    return null;\n  }\n\n  return exportKey === \".\" ? resolveConditionalExportTarget(exportsField) : null;\n}\n\nfunction resolveConditionalExportTarget(value: unknown): string | null {\n  if (typeof value === \"string\") return value;\n  if (Array.isArray(value)) {\n    for (const candidate of value) {\n      const resolved = resolveConditionalExportTarget(candidate);\n      if (resolved) return resolved;\n    }\n    return null;\n  }\n  if (!value || typeof value !== \"object\") return null;\n\n  const conditions = value as Record<string, unknown>;\n  // This metadata controls browser hydration, so prefer client-facing exports\n  // regardless of declaration order while retaining Node-only package support.\n  for (const condition of [\"browser\", \"import\", \"module\", \"node\", \"default\", \"require\"]) {\n    if (conditions[condition] === undefined) continue;\n    const resolved = resolveConditionalExportTarget(conditions[condition]);\n    if (resolved) return resolved;\n  }\n  return null;\n}\n\nfunction resolveSourceCandidate(candidates: Iterable<string>): string | null {\n  for (const candidate of candidates) {\n    const paths = [candidate];\n    for (const extension of RESOLVABLE_SOURCE_EXTENSIONS) {\n      paths.push(`${candidate}${extension}`, path.join(candidate, `index${extension}`));\n    }\n    for (const sourcePath of paths) {\n      try {\n        if (fs.statSync(sourcePath).isFile()) return sourcePath;\n      } catch {\n        // Continue to the next candidate.\n      }\n    }\n  }\n  return null;\n}\n","import type { FarmIslandStrategy } from \"../island\";\nimport type { RouteRenderingConfig } from \"../ssg\";\n\n/**\n * A build-time rendering decision consumed by the browser router.\n *\n * The browser never inspects module source to choose a rendering path. It\n * executes this compact plan and only evaluates request-specific cache keys at\n * runtime.\n */\nexport interface FarmRouteRenderPlan {\n  version: 1;\n  output: \"html\";\n  navigation: \"html-fragment\";\n  hydration: \"none\" | \"route-island\" | \"layout-island\" | \"route-and-layout-islands\";\n  islandStrategy: FarmIslandStrategy | null;\n  cache: {\n    mode: \"static\" | \"revalidate\" | \"dynamic\";\n    revalidate?: number;\n  };\n}\n\nexport interface FarmRouteRenderPlanInput {\n  pageShouldHydrate?: boolean;\n  layoutShouldHydrate?: boolean;\n  islandStrategy?: FarmIslandStrategy | null;\n  rendering?: Pick<RouteRenderingConfig, \"ssg\" | \"ppr\" | \"revalidate\">;\n}\n\n/** Create a deterministic route plan during manifest generation. */\nexport function createFarmRouteRenderPlan(\n  input: FarmRouteRenderPlanInput = {},\n): FarmRouteRenderPlan {\n  const pageShouldHydrate = input.pageShouldHydrate === true;\n  const layoutShouldHydrate = input.layoutShouldHydrate === true;\n  const hydration = pageShouldHydrate\n    ? layoutShouldHydrate\n      ? \"route-and-layout-islands\"\n      : \"route-island\"\n    : layoutShouldHydrate\n      ? \"layout-island\"\n      : \"none\";\n\n  const rendering = input.rendering;\n  const cache = rendering?.ssg\n    ? typeof rendering.revalidate === \"number\" && rendering.revalidate > 0\n      ? { mode: \"revalidate\" as const, revalidate: rendering.revalidate }\n      : { mode: \"static\" as const }\n    : { mode: \"dynamic\" as const };\n\n  return {\n    version: 1,\n    output: \"html\",\n    navigation: \"html-fragment\",\n    hydration,\n    islandStrategy: hydration === \"none\" ? null : (input.islandStrategy ?? \"load\"),\n    cache,\n  };\n}\n\n/**\n * Cache policy for a fragment response. Explicit static rendering is safe to\n * share; dynamic output remains private even when the browser caches it.\n */\nexport function getFarmFragmentCacheControl(plan: FarmRouteRenderPlan): string {\n  if (plan.cache.mode === \"static\") {\n    return \"public, max-age=0, s-maxage=31536000, immutable\";\n  }\n  if (plan.cache.mode === \"revalidate\") {\n    const seconds = Math.max(1, plan.cache.revalidate ?? 1);\n    return `public, max-age=0, s-maxage=${seconds}, stale-while-revalidate=${seconds}`;\n  }\n  return \"private, max-age=0\";\n}\n\nexport function parseFarmLayoutChainHeader(value: string | null): string[] {\n  if (!value || value.length > 8_192) return [];\n  try {\n    const parsed = JSON.parse(value);\n    if (!Array.isArray(parsed) || parsed.length > 64) return [];\n    return parsed.filter(\n      (pattern): pattern is string =>\n        typeof pattern === \"string\" && pattern.startsWith(\"/\") && pattern.length <= 512,\n    );\n  } catch {\n    return [];\n  }\n}\n\nexport function getSharedLayoutPrefixLength(current: string[], next: string[]): number {\n  let index = 0;\n  while (index < current.length && index < next.length && current[index] === next[index]) {\n    index++;\n  }\n  return index;\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { imageSize } from \"image-size\";\n\nexport const STATIC_METADATA_IMAGE_EXTENSIONS = [\"png\", \"jpg\", \"jpeg\", \"gif\", \"webp\"] as const;\n\nexport type StaticMetadataImageExtension = (typeof STATIC_METADATA_IMAGE_EXTENSIONS)[number];\n\nexport interface StaticMetadataImageInfo {\n  extension: StaticMetadataImageExtension;\n  contentType: string;\n  width: number;\n  height: number;\n  alt?: string;\n  hash: string;\n  byteLength: number;\n}\n\nconst CONTENT_TYPES: Record<StaticMetadataImageExtension, string> = {\n  png: \"image/png\",\n  jpg: \"image/jpeg\",\n  jpeg: \"image/jpeg\",\n  gif: \"image/gif\",\n  webp: \"image/webp\",\n};\n\nexport function isStaticMetadataImageFile(filePath: string): boolean {\n  return getStaticMetadataImageExtension(filePath) !== null;\n}\n\nexport async function inspectStaticMetadataImage(\n  filePath: string,\n): Promise<StaticMetadataImageInfo> {\n  const extension = getStaticMetadataImageExtension(filePath);\n  if (!extension) {\n    throw new Error(`Unsupported static metadata image: ${filePath}`);\n  }\n\n  const bytes = await readFile(filePath);\n  let dimensions: ReturnType<typeof imageSize>;\n\n  try {\n    dimensions = imageSize(bytes);\n  } catch (error) {\n    const reason = error instanceof Error ? error.message : String(error);\n    throw new Error(`Could not read metadata image ${filePath}: ${reason}`);\n  }\n\n  if (!dimensions.width || !dimensions.height) {\n    throw new Error(`Could not determine metadata image dimensions for ${filePath}`);\n  }\n\n  const alt = await readAltText(filePath);\n\n  return {\n    extension,\n    contentType: CONTENT_TYPES[extension],\n    width: dimensions.width,\n    height: dimensions.height,\n    alt,\n    hash: createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 16),\n    byteLength: bytes.byteLength,\n  };\n}\n\nexport function getStaticMetadataImageAltPath(filePath: string): string {\n  return path.join(\n    path.dirname(filePath),\n    `${path.basename(filePath, path.extname(filePath))}.alt.txt`,\n  );\n}\n\nfunction getStaticMetadataImageExtension(filePath: string): StaticMetadataImageExtension | null {\n  const extension = path.extname(filePath).slice(1).toLowerCase();\n  return STATIC_METADATA_IMAGE_EXTENSIONS.includes(extension as StaticMetadataImageExtension)\n    ? (extension as StaticMetadataImageExtension)\n    : null;\n}\n\nasync function readAltText(filePath: string): Promise<string | undefined> {\n  try {\n    const value = (await readFile(getStaticMetadataImageAltPath(filePath), \"utf8\")).trim();\n    return value || undefined;\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return undefined;\n    }\n    throw error;\n  }\n}\n","/** Preserve an incoming query when a redirect destination does not declare one. */\nexport function appendFarmRedirectQuery(destination: string, search: string): string {\n  if (!search || search === \"?\") return destination;\n\n  const hashIndex = destination.indexOf(\"#\");\n  const pathAndQuery = hashIndex === -1 ? destination : destination.slice(0, hashIndex);\n  if (pathAndQuery.includes(\"?\")) return destination;\n\n  if (hashIndex === -1) return `${destination}${search}`;\n  return `${pathAndQuery}${search}${destination.slice(hashIndex)}`;\n}\n","import type { ParsedRoute } from \"../types\";\nimport { parseRoutePath } from \"../utils\";\n\nexport type RouteSlotConvention = {\n  name: string;\n  ownerRoute: ParsedRoute;\n  route: ParsedRoute;\n  interception: boolean;\n  fallback: boolean;\n};\n\nconst SLOT_SEGMENT = /^@([A-Za-z][A-Za-z0-9_-]*)$/;\n\n/**\n * Parse a page nested below an `@slot` directory without adding the slot name\n * or interception marker to its public URL.\n */\nexport function parseRouteSlotFile(filePath: string): RouteSlotConvention | null {\n  const normalized = filePath.replace(/\\\\/g, \"/\");\n  const parts = normalized.split(\"/\").filter(Boolean);\n  const fileName = parts.at(-1) ?? \"\";\n  const baseName = fileName.replace(/\\.(tsx?|jsx?|vue|svelte)$/, \"\");\n  if (baseName !== \"page\" && baseName !== \"default\") return null;\n\n  const slotIndex = parts.findIndex((part) => SLOT_SEGMENT.test(part));\n  if (slotIndex < 0) return null;\n  if (parts.slice(slotIndex + 1, -1).some((part) => SLOT_SEGMENT.test(part))) {\n    throw new Error(`Nested route slots are not supported in \"${filePath}\"`);\n  }\n\n  const slotMatch = parts[slotIndex]!.match(SLOT_SEGMENT);\n  const name = slotMatch?.[1];\n  if (!name) return null;\n\n  const ownerParts = parts.slice(0, slotIndex);\n  const contentParts = parts.slice(slotIndex + 1, -1);\n  const marker = parseInterceptionMarker(contentParts[0]);\n  let targetBase = ownerParts;\n  let targetParts = contentParts;\n\n  if (marker) {\n    targetBase =\n      marker.root === true ? [] : ownerParts.slice(0, Math.max(0, ownerParts.length - marker.up));\n    targetParts = [...(marker.remainder ? [marker.remainder] : []), ...contentParts.slice(1)];\n  }\n\n  const ownerFile = [...ownerParts, \"layout.tsx\"].join(\"/\");\n  const routeFile = [\n    ...(baseName === \"default\" ? ownerParts : targetBase),\n    ...(baseName === \"default\" ? [] : targetParts),\n    \"page.tsx\",\n  ].join(\"/\");\n\n  return {\n    name,\n    ownerRoute: parseRoutePath(ownerFile || \"layout.tsx\"),\n    route: parseRoutePath(routeFile || \"page.tsx\"),\n    interception: marker !== null,\n    fallback: baseName === \"default\",\n  };\n}\n\nexport function createRouteSlotContainerId(name: string, ownerPattern: string): string {\n  const owner =\n    ownerPattern === \"/\"\n      ? \"root\"\n      : ownerPattern\n          .replace(/^\\//, \"\")\n          .replace(/[^A-Za-z0-9_-]+/g, \"-\")\n          .replace(/^-+|-+$/g, \"\");\n  return `__farm_slot_${name}_${owner || \"root\"}__`;\n}\n\nfunction parseInterceptionMarker(\n  segment: string | undefined,\n): { up: number; root?: boolean; remainder: string } | null {\n  if (!segment) return null;\n  if (segment.startsWith(\"(...)\")) {\n    return {\n      up: 0,\n      root: true,\n      remainder: segment.slice(5),\n    };\n  }\n  if (segment.startsWith(\"(.)\")) {\n    return {\n      up: 0,\n      remainder: segment.slice(3),\n    };\n  }\n\n  let remainder = segment;\n  let up = 0;\n  while (remainder.startsWith(\"(..)\")) {\n    up += 1;\n    remainder = remainder.slice(4);\n  }\n  return up > 0 ? { up, remainder } : null;\n}\n","import type {\n  FarmConfig,\n  ParsedRoute,\n  RouteModule,\n  LayoutModule,\n  SSGCollectionResult,\n} from \"../types\";\nimport {\n  parseRoutePath,\n  matchRoute,\n  matchRoutePrefix,\n  resolveAppPath,\n  globFiles,\n  logger,\n  toRootRelativeUrlPath,\n  toViteModuleId,\n} from \"../utils\";\nimport { collectSSGPages, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport type {\n  ProgrammaticPageRoute,\n  ProgrammaticLayoutRoute,\n  ProgrammaticRedirectRoute,\n  ProgrammaticRouteSearchClientOptions,\n} from \"../routes\";\nimport {\n  createProgrammaticRouteModuleId,\n  getProgrammaticRouteSearchClientOptions,\n  parseProgrammaticRoutePath,\n} from \"../routes-shared\";\nimport { loadProgrammaticRouteManifests } from \"../routes.server\";\nimport {\n  createFarmMarkdownRouteModuleFromFile,\n  isFarmMarkdownPageFile,\n  loadFarmMdxComponents,\n  resolveMdxConfig,\n} from \"../app-markdown\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport {\n  enforceFarmIsolatedHydrationRouteBudget,\n  getClientModuleHydrationPlan,\n  getClientModuleMetadata,\n  resolveFarmIsolatedClientHydrationMode,\n  type IsolatedClientBoundaryReference,\n} from \"../utils/client-component\";\nimport { getIntegrationProviders } from \"../integrations\";\nimport type { MetadataImageKind } from \"../metadata\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport type { FarmServerRendererRuntime } from \"../renderer\";\nimport { createFarmRouteRenderPlan, type FarmRouteRenderPlan } from \"../navigation/render-plan\";\nimport { getFarmSourceRoots, type FarmSourceRoot } from \"../layers\";\nimport {\n  inspectStaticMetadataImage,\n  isStaticMetadataImageFile,\n  type StaticMetadataImageInfo,\n} from \"../static-metadata-image\";\nimport {\n  getFarmRouteRuntimeConfig,\n  mergeFarmRouteRuntimeConfigs,\n  normalizeFarmRouteRuntimeConfig,\n  resolveFarmRouteRuleRuntimeConfig,\n  resolveFarmRouteRuntimeConfig,\n  type ResolvedFarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport {\n  localizeFarmHref,\n  localizeFarmPathname,\n  resolveFarmLocalePath,\n  stripFarmLocaleFromPathname,\n} from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { appendFarmRedirectQuery } from \"../redirect-query\";\nimport { createRouteSlotContainerId, parseRouteSlotFile } from \"./route-slots\";\nimport { getFarmRendererComponentExtensions } from \"../renderer\";\nimport type { ApplicationMetadataRouteKind } from \"../metadata-route\";\nimport {\n  AmbiguousRouteError,\n  assertUniqueRouteParameters,\n  compareRouteSpecificity,\n  getRoutePatternShape,\n  type RouteSegmentSpecificity,\n} from \"./specificity\";\n\ninterface RouteEntry {\n  route: ParsedRoute;\n  modulePath: string;\n  markdownSourcePath?: string;\n  pattern: string;\n  source?: \"file\" | \"programmatic\";\n  sourceRoot: string;\n}\n\nexport interface RouteSlotEntry extends RouteEntry {\n  name: string;\n  ownerPattern: string;\n  interception: boolean;\n  fallback: boolean;\n  containerId: string;\n}\n\nexport interface MatchedRouteSlot {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  interception: boolean;\n  fallback: boolean;\n  route: RouteSlotEntry;\n  params: Record<string, string>;\n}\n\nexport interface FarmClientRouteManifest {\n  routes: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries?: true;\n    isolatedBoundaries?: IsolatedClientBoundaryReference[];\n    renderPlan: FarmRouteRenderPlan;\n    suppressedAsyncHydration?: true;\n    search?: ProgrammaticRouteSearchClientOptions;\n    segments: Array<{\n      segment: string;\n      isDynamic: boolean;\n      isCatchAll?: boolean;\n      isOptional?: boolean;\n    }>;\n  }>;\n  layouts: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries?: true;\n    isolatedBoundaries?: IsolatedClientBoundaryReference[];\n  }>;\n  slots: Array<{\n    name: string;\n    ownerPattern: string;\n    pattern: string;\n    modulePath: string;\n    containerId: string;\n    interception: boolean;\n    fallback: boolean;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    segments: RouteEntry[\"route\"][\"segments\"];\n  }>;\n}\n\nexport function shouldSuggestStaticRenderingForI18n(\n  i18n: Pick<ResolvedFarmI18nConfig, \"routing\" | \"detection\"> | undefined,\n): boolean {\n  return (\n    !i18n ||\n    i18n.routing === \"prefix-always\" ||\n    (i18n.routing === \"prefix-except-default\" && i18n.detection.every((signal) => signal === \"url\"))\n  );\n}\n\ninterface MetadataImageEntry extends RouteEntry {\n  kind: MetadataImageKind;\n  fileName: \"opengraph-image\" | \"twitter-image\";\n  sourceType: \"module\" | \"static\";\n  staticInfo?: StaticMetadataImageInfo;\n}\n\nexport interface ApplicationMetadataRouteEntry extends RouteEntry {\n  kind: ApplicationMetadataRouteKind;\n  fileName: \"sitemap\" | \"robots\" | \"manifest\";\n  outputName: \"sitemap.xml\" | \"robots.txt\" | \"manifest.webmanifest\";\n}\n\ninterface RedirectEntry {\n  route: ParsedRoute;\n  pattern: string;\n  definition: ProgrammaticRedirectRoute;\n}\n\nfunction getRouteSpecificity(entry: RouteEntry): RouteSegmentSpecificity[] {\n  return entry.route.segments.map((segment) => {\n    if (!segment.isDynamic) return \"static\";\n    if (!segment.isCatchAll) return \"dynamic\";\n    return segment.isOptional ? \"optional-catch-all\" : \"catch-all\";\n  });\n}\n\nfunction compareRouteEntries(left: RouteEntry, right: RouteEntry): number {\n  return compareRouteSpecificity(getRouteSpecificity(left), getRouteSpecificity(right));\n}\n\n/**\n * Manages route discovery and matching for the Farm.js application\n */\nexport class RouteManager {\n  private config: Required<FarmConfig>;\n  private routes: Map<string, RouteEntry> = new Map();\n  private pageRouteShapes: Map<string, RouteEntry> = new Map();\n  private layouts: Map<string, RouteEntry> = new Map();\n  private routeSlots: Map<string, RouteSlotEntry> = new Map();\n  private loadings: Map<string, RouteEntry> = new Map();\n  private errors: Map<string, RouteEntry> = new Map();\n  private metadataImages: Map<string, MetadataImageEntry> = new Map();\n  private metadataRoutes: Map<string, ApplicationMetadataRouteEntry> = new Map();\n  private redirects: Map<string, RedirectEntry> = new Map();\n  private programmaticPages: Map<string, ProgrammaticPageRoute> = new Map();\n  private programmaticLayouts: Map<string, ProgrammaticLayoutRoute> = new Map();\n  private rendererRuntime?: FarmServerRendererRuntime;\n  private viteServer?: ViteDevServer;\n  private clientManifestCache?: {\n    projectRoot: string;\n    manifest: FarmClientRouteManifest;\n    isolatedClientBoundaryModules: ReadonlySet<string>;\n  };\n\n  constructor(config: Required<FarmConfig>, viteServer?: ViteDevServer) {\n    this.config = config;\n    this.viteServer = viteServer;\n  }\n\n  setRendererRuntime(rendererRuntime: FarmServerRendererRuntime): void {\n    this.rendererRuntime = rendererRuntime;\n  }\n\n  /**\n   * Discover all routes in the app directory\n   */\n  async discoverRoutes(): Promise<void> {\n    this.invalidateClientManifest();\n    this.routes.clear();\n    this.pageRouteShapes.clear();\n    this.layouts.clear();\n    this.routeSlots.clear();\n    this.loadings.clear();\n    this.errors.clear();\n    this.metadataImages.clear();\n    this.metadataRoutes.clear();\n    this.redirects.clear();\n    this.programmaticPages.clear();\n    this.programmaticLayouts.clear();\n\n    for (const source of getFarmSourceRoots(this.config)) {\n      await this.discoverFileRoutes(source);\n      await this.discoverProgrammaticRoutes(source);\n    }\n\n    for (const slot of this.routeSlots.values()) {\n      if (slot.interception && !this.pageRouteShapes.has(getRoutePatternShape(slot.pattern))) {\n        throw new AmbiguousRouteError(\n          `Intercepting route slot \"${slot.name}\" targets \"${slot.pattern}\", but no canonical page exists for that URL`,\n        );\n      }\n    }\n\n    this.routes = new Map(\n      Array.from(this.routes.entries()).sort(([, left], [, right]) =>\n        compareRouteEntries(left, right),\n      ),\n    );\n    this.metadataRoutes = new Map(\n      Array.from(this.metadataRoutes.entries()).sort(([, left], [, right]) =>\n        compareRouteEntries(left, right),\n      ),\n    );\n\n    // Silent discovery - only log if verbose mode enabled\n    if (process.env.FARM_VERBOSE) {\n      logger.info(\n        `Discovered ${this.routes.size} pages, ${this.layouts.size} layouts, and ${this.metadataRoutes.size} metadata routes`,\n      );\n    }\n\n    if (process.env.FARM_VERBOSE) {\n      this.logRoutes();\n    }\n  }\n\n  /**\n   * Find matching route for a given URL path\n   */\n  matchRoute(\n    pathname: string,\n    options: {\n      interceptFrom?: string;\n    } = {},\n  ): {\n    route: RouteEntry | null;\n    params: Record<string, string>;\n    layouts: RouteEntry[];\n    slots: MatchedRouteSlot[];\n  } {\n    // Remove trailing slash except for root\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    // Find matching page route\n    let matchedRoute: RouteEntry | null = null;\n    let params: Record<string, string> = {};\n\n    for (const routeEntry of this.routes.values()) {\n      const match = matchRoute(normalizedPath, routeEntry.route.segments);\n      if (match.matches) {\n        matchedRoute = routeEntry;\n        params = match.params;\n        break;\n      }\n    }\n\n    // Find all matching layouts (from root to specific)\n    const layouts = this.findMatchingLayouts(normalizedPath);\n    const slots = this.findMatchingRouteSlots(normalizedPath, options.interceptFrom);\n\n    return {\n      route: matchedRoute,\n      params,\n      layouts,\n      slots,\n    };\n  }\n\n  /**\n   * Get all registered routes\n   */\n  getRoutes(): Map<string, RouteEntry> {\n    return new Map(this.routes);\n  }\n\n  /**\n   * Get all registered layouts\n   */\n  getLayouts(): Map<string, RouteEntry> {\n    return new Map(this.layouts);\n  }\n\n  getRouteSlots(): Map<string, RouteSlotEntry> {\n    return new Map(this.routeSlots);\n  }\n\n  /** Resolve route rules, inherited layouts, and the page export in precedence order. */\n  async resolveRouteRuntimeConfig(pattern: string): Promise<ResolvedFarmRouteRuntimeConfig> {\n    const routeEntry = this.routes.get(pattern);\n    if (!routeEntry) {\n      throw new Error(`Cannot resolve runtime configuration for unknown route \"${pattern}\"`);\n    }\n\n    const inherited = resolveFarmRouteRuleRuntimeConfig(pattern, this.config.routeRules);\n    const layouts = this.findMatchingLayouts(pattern);\n    const layoutConfigs = [];\n\n    for (const layout of layouts) {\n      const layoutModule = await this.loadLayoutModule(layout.modulePath);\n      layoutConfigs.push(\n        normalizeFarmRouteRuntimeConfig(\n          getFarmRouteRuntimeConfig(layoutModule),\n          `Layout \"${layout.pattern}\"`,\n        ),\n      );\n    }\n\n    const routeModule = await this.loadRouteModule(routeEntry.modulePath);\n    const routeConfig = normalizeFarmRouteRuntimeConfig(\n      getFarmRouteRuntimeConfig(routeModule),\n      `Route \"${pattern}\"`,\n    );\n\n    return resolveFarmRouteRuntimeConfig(\n      mergeFarmRouteRuntimeConfigs(inherited, ...layoutConfigs, routeConfig),\n      `Route \"${pattern}\"`,\n    );\n  }\n\n  /**\n   * Get all route-level loading boundaries.\n   */\n  getLoadings(): Map<string, RouteEntry> {\n    return new Map(this.loadings);\n  }\n\n  /**\n   * Get all route-level error boundaries.\n   */\n  getErrors(): Map<string, RouteEntry> {\n    return new Map(this.errors);\n  }\n\n  getMetadataImages(): Map<string, MetadataImageEntry> {\n    return new Map(this.metadataImages);\n  }\n\n  getMetadataRoutes(): Map<string, ApplicationMetadataRouteEntry> {\n    return new Map(this.metadataRoutes);\n  }\n\n  getRedirects(): ProgrammaticRedirectRoute[] {\n    return Array.from(this.redirects.values()).map((entry) => entry.definition);\n  }\n\n  matchRedirect(\n    pathname: string,\n    search = \"\",\n  ): {\n    redirect: ProgrammaticRedirectRoute;\n    destination: string;\n    statusCode: number;\n    params: Record<string, string>;\n  } | null {\n    const i18n = this.getI18nConfig();\n    const localeMatch = i18n ? resolveFarmLocalePath(pathname, i18n) : undefined;\n    const routePathname = localeMatch?.pathname || pathname;\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n\n    for (const redirectEntry of this.redirects.values()) {\n      const match = matchRoute(normalizedPath, redirectEntry.route.segments);\n      if (!match.matches) continue;\n\n      const statusCode =\n        redirectEntry.definition.statusCode || (redirectEntry.definition.permanent ? 308 : 307);\n\n      return {\n        redirect: redirectEntry.definition,\n        destination: appendFarmRedirectQuery(\n          this.localizeRedirectDestination(\n            interpolateRedirectDestination(redirectEntry.definition.destination, match.params),\n            localeMatch?.locale,\n          ),\n          search,\n        ),\n        statusCode,\n        params: match.params,\n      };\n    }\n\n    return null;\n  }\n\n  /**\n   * Return the nearest matching loading boundary for a pathname.\n   */\n  getMatchingLoading(pathname: string): RouteEntry | null {\n    return this.findNearestBoundary(this.toRoutePathname(pathname), this.loadings);\n  }\n\n  /**\n   * Return the nearest matching error boundary for a pathname.\n   */\n  getMatchingError(pathname: string): RouteEntry | null {\n    return this.findNearestBoundary(this.toRoutePathname(pathname), this.errors);\n  }\n\n  matchMetadataImage(pathname: string): {\n    image: MetadataImageEntry;\n    params: Record<string, string>;\n    pagePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const suffix = getMetadataImageSuffix(normalizedPath);\n    if (!suffix) return null;\n\n    const pagePath = normalizedPath.slice(0, -suffix.fileName.length - 1) || \"/\";\n\n    for (const imageEntry of this.metadataImages.values()) {\n      if (imageEntry.kind !== suffix.kind) continue;\n\n      const match = matchRoute(pagePath, imageEntry.route.segments);\n      if (!match.matches) continue;\n\n      return {\n        image: imageEntry,\n        params: match.params,\n        pagePath,\n      };\n    }\n\n    return null;\n  }\n\n  matchMetadataRoute(pathname: string): {\n    metadata: ApplicationMetadataRouteEntry;\n    params: Record<string, string>;\n    routePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const suffix = getApplicationMetadataRouteSuffix(normalizedPath);\n    if (!suffix) return null;\n\n    const routePath = normalizedPath.slice(0, -suffix.outputName.length - 1) || \"/\";\n    for (const metadata of this.metadataRoutes.values()) {\n      if (metadata.kind !== suffix.kind) continue;\n      const match = matchRoute(routePath, metadata.route.segments);\n      if (!match.matches) continue;\n      return { metadata, params: match.params, routePath };\n    }\n\n    return null;\n  }\n\n  getMatchingMetadataRoute(\n    pathname: string,\n    kind: ApplicationMetadataRouteKind,\n  ): {\n    metadata: ApplicationMetadataRouteEntry;\n    params: Record<string, string>;\n    routePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n    let bestMatch: {\n      metadata: ApplicationMetadataRouteEntry;\n      params: Record<string, string>;\n      routePath: string;\n    } | null = null;\n\n    for (const metadata of this.metadataRoutes.values()) {\n      if (metadata.kind !== kind || metadata.route.segments.length > pathSegments.length) continue;\n      const routePath =\n        metadata.route.segments.length === 0\n          ? \"/\"\n          : `/${pathSegments.slice(0, metadata.route.segments.length).join(\"/\")}`;\n      const match = matchRoute(routePath, metadata.route.segments);\n      if (!match.matches) continue;\n      if (!bestMatch || metadata.route.segments.length > bestMatch.metadata.route.segments.length) {\n        bestMatch = { metadata, params: match.params, routePath };\n      }\n    }\n\n    return bestMatch;\n  }\n\n  resolveMetadataRoutePath(\n    metadata: ApplicationMetadataRouteEntry,\n    params: Record<string, string> = {},\n  ): string {\n    const routePath = routeSegmentsToPath(metadata.route.segments, params);\n    return routePath === \"/\" ? `/${metadata.outputName}` : `${routePath}/${metadata.outputName}`;\n  }\n\n  getMatchingMetadataImage(\n    pathname: string,\n    kind: MetadataImageKind,\n  ): {\n    image: MetadataImageEntry;\n    params: Record<string, string>;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n    let bestMatch: {\n      image: MetadataImageEntry;\n      params: Record<string, string>;\n    } | null = null;\n\n    for (const imageEntry of this.metadataImages.values()) {\n      if (imageEntry.kind !== kind) continue;\n      if (imageEntry.route.segments.length > pathSegments.length) continue;\n\n      const candidatePath =\n        imageEntry.route.segments.length === 0\n          ? \"/\"\n          : `/${pathSegments.slice(0, imageEntry.route.segments.length).join(\"/\")}`;\n      const match = matchRoute(candidatePath, imageEntry.route.segments);\n      if (!match.matches) continue;\n\n      if (!bestMatch || imageEntry.route.segments.length > bestMatch.image.route.segments.length) {\n        bestMatch = {\n          image: imageEntry,\n          params: match.params,\n        };\n      }\n    }\n\n    return bestMatch;\n  }\n\n  resolveMetadataImagePath(image: MetadataImageEntry, params: Record<string, string> = {}): string {\n    const pagePath = routeSegmentsToPath(image.route.segments, params);\n    const imagePath = pagePath === \"/\" ? `/${image.fileName}` : `${pagePath}/${image.fileName}`;\n    return image.staticInfo ? `${imagePath}?v=${image.staticInfo.hash}` : imagePath;\n  }\n\n  /**\n   * Generate the compiled route decisions consumed by SPA navigation.\n   * Requests still fetch route data, but never inspect component source.\n   */\n  generateClientManifest(projectRoot: string = this.config.root): FarmClientRouteManifest {\n    const normalizedProjectRoot = path.resolve(projectRoot);\n    if (this.clientManifestCache?.projectRoot === normalizedProjectRoot) {\n      return this.clientManifestCache.manifest;\n    }\n\n    const toUrlPath = (absolutePath: string) => {\n      const rootRelative = toRootRelativeUrlPath(absolutePath, normalizedProjectRoot);\n      if (rootRelative !== undefined) return rootRelative;\n      if (path.isAbsolute(absolutePath)) {\n        const normalized = absolutePath.replace(/\\\\/g, \"/\");\n        return normalized.startsWith(\"/\") ? `/@fs${normalized}` : `/@fs/${normalized}`;\n      }\n      return absolutePath;\n    };\n\n    const integrationProviders = getIntegrationProviders(this.config.integrations).filter(\n      (provider) => provider.component || provider.type === \"clerk\",\n    );\n    const unsupportedIntegrationProvider = integrationProviders.find(\n      (provider) => provider.supportsIsolatedHydration !== true,\n    );\n    if (\n      this.config.experimental?.isolatedClientHydration === \"enabled\" &&\n      this.config.experimental?.serverComponents !== true &&\n      unsupportedIntegrationProvider\n    ) {\n      logger.warn(\n        `[Farm.js] isolated hydration kept route-wide because integration provider \"${unsupportedIntegrationProvider.name}\" does not declare supportsIsolatedHydration: true.`,\n      );\n    }\n    const isolatedMode = resolveFarmIsolatedClientHydrationMode(\n      this.config.experimental?.isolatedClientHydration,\n      {\n        serverComponents: this.config.experimental?.serverComponents === true,\n        hasUnsupportedIntegrationProvider: Boolean(unsupportedIntegrationProvider),\n      },\n    );\n    const layoutEntries = Array.from(this.layouts.values()).map((entry) => ({\n      entry,\n      metadata: getClientModuleHydrationPlan(entry.modulePath, normalizedProjectRoot, isolatedMode),\n    }));\n\n    const routeEntries = Array.from(this.routes.values()).map((entry) => ({\n      entry,\n      metadata: getClientModuleHydrationPlan(entry.modulePath, normalizedProjectRoot, isolatedMode),\n    }));\n\n    enforceFarmIsolatedHydrationRouteBudget(\n      layoutEntries.map(({ entry, metadata }) => ({\n        pattern: entry.pattern,\n        depth: entry.route.segments.length,\n        metadata,\n      })),\n      routeEntries.map(({ entry, metadata }) => ({\n        pattern: entry.pattern,\n        depth: entry.route.segments.length,\n        metadata,\n      })),\n      (layoutPattern, routePattern) =>\n        layoutPattern === \"/\" ||\n        routePattern === layoutPattern ||\n        routePattern.startsWith(`${layoutPattern.replace(/\\/$/, \"\")}/`),\n    );\n\n    for (const { entry, metadata } of [...layoutEntries, ...routeEntries]) {\n      if (!metadata.costGuardExceeded) continue;\n      logger.warn(\n        `[Farm.js] isolated hydration kept route-wide for ${entry.modulePath}: ${metadata.fallbackReason}.`,\n      );\n    }\n    if (isolatedMode === \"analyze\") {\n      for (const { entry, metadata } of [...layoutEntries, ...routeEntries]) {\n        if (!metadata.isolatedHydrationEligible) continue;\n        logger.info(\n          `[Farm.js] isolated hydration analysis: ${entry.modulePath} can keep ${metadata.isolatedBoundaries.length} client ${metadata.isolatedBoundaries.length === 1 ? \"boundary\" : \"boundaries\"} while excluding its server owner from the browser graph.`,\n        );\n      }\n    }\n\n    const routes = routeEntries.map(({ entry, metadata }) => {\n      const programmaticPage = this.programmaticPages.get(entry.modulePath);\n      const layoutShouldHydrate = layoutEntries.some(\n        ({ entry: layout, metadata: layoutMetadata }) =>\n          layoutMetadata.shouldHydrate &&\n          (layout.pattern === \"/\" ||\n            entry.pattern === layout.pattern ||\n            entry.pattern.startsWith(`${layout.pattern.replace(/\\/$/, \"\")}/`)),\n      );\n      return {\n        pattern: entry.pattern,\n        modulePath: toUrlPath(entry.modulePath),\n        shouldHydrate: metadata.shouldHydrate,\n        isClientComponent: metadata.isClientComponent,\n        islandStrategy: metadata.islandStrategy,\n        ...(metadata.hasIsolatedClientBoundaries\n          ? {\n              hasIsolatedClientBoundaries: true as const,\n              isolatedBoundaries: metadata.isolatedBoundaries.map((boundary) => ({\n                ...boundary,\n                modulePath: toUrlPath(boundary.modulePath),\n              })),\n            }\n          : {}),\n        renderPlan: createFarmRouteRenderPlan({\n          pageShouldHydrate: metadata.shouldHydrate,\n          layoutShouldHydrate,\n          islandStrategy: metadata.islandStrategy,\n        }),\n        suppressedAsyncHydration: metadata.suppressedAsyncHydration,\n        search: getProgrammaticRouteSearchClientOptions(programmaticPage?.search),\n        segments: entry.route.segments.map((seg) => ({\n          segment: seg.segment,\n          isDynamic: seg.isDynamic,\n          isCatchAll: seg.isCatchAll,\n          isOptional: seg.isOptional,\n        })),\n      };\n    });\n\n    const layouts = layoutEntries.map(({ entry, metadata }) => ({\n      pattern: entry.pattern,\n      modulePath: toUrlPath(entry.modulePath),\n      shouldHydrate: metadata.shouldHydrate,\n      isClientComponent: metadata.isClientComponent,\n      islandStrategy: metadata.islandStrategy,\n      ...(metadata.hasIsolatedClientBoundaries\n        ? {\n            hasIsolatedClientBoundaries: true as const,\n            isolatedBoundaries: metadata.isolatedBoundaries.map((boundary) => ({\n              ...boundary,\n              modulePath: toUrlPath(boundary.modulePath),\n            })),\n          }\n        : {}),\n    }));\n\n    const slots = Array.from(this.routeSlots.values()).map((entry) => {\n      const metadata = getClientModuleMetadata(entry.modulePath, normalizedProjectRoot);\n      return {\n        name: entry.name,\n        ownerPattern: entry.ownerPattern,\n        pattern: entry.pattern,\n        modulePath: toUrlPath(entry.modulePath),\n        containerId: entry.containerId,\n        interception: entry.interception,\n        fallback: entry.fallback,\n        shouldHydrate: metadata.shouldHydrate,\n        isClientComponent: metadata.isClientComponent,\n        segments: entry.route.segments,\n      };\n    });\n\n    const isolatedClientBoundaryModules = new Set<string>();\n    for (const { metadata } of [...layoutEntries, ...routeEntries]) {\n      if (!metadata.hasIsolatedClientBoundaries) continue;\n      for (const boundary of metadata.isolatedBoundaries) {\n        isolatedClientBoundaryModules.add(path.resolve(boundary.modulePath));\n      }\n    }\n\n    const manifest = { routes, layouts, slots };\n    this.clientManifestCache = {\n      projectRoot: normalizedProjectRoot,\n      manifest,\n      isolatedClientBoundaryModules,\n    };\n    return manifest;\n  }\n\n  /** @internal Client modules selected by the compiled hydration ownership plan. */\n  getIsolatedClientBoundaryModules(projectRoot: string = this.config.root): ReadonlySet<string> {\n    const normalizedProjectRoot = path.resolve(projectRoot);\n    this.generateClientManifest(normalizedProjectRoot);\n    return this.clientManifestCache?.isolatedClientBoundaryModules ?? new Set();\n  }\n\n  /**\n   * Invalidate build-time route metadata after a page or layout changes in dev.\n   * Navigation requests reuse the cached manifest and never inspect source files.\n   */\n  invalidateClientManifest(): void {\n    this.clientManifestCache = undefined;\n  }\n\n  /**\n   * Load a route module dynamically\n   */\n  async loadRouteModule(modulePath: string): Promise<RouteModule> {\n    try {\n      const programmaticPage = this.programmaticPages.get(modulePath);\n      if (programmaticPage) {\n        const { createRouteModuleFromProgrammaticPage } = await import(\"../routes\");\n        return createRouteModuleFromProgrammaticPage(programmaticPage, this.rendererRuntime);\n      }\n\n      if (isFarmMarkdownPageFile(modulePath)) {\n        const mdxConfig = resolveMdxConfig(this.config.mdx);\n        const components = await loadFarmMdxComponents(mdxConfig, {\n          root: this.config.root,\n          loadModule: this.viteServer\n            ? (componentModulePath) => this.viteServer!.ssrLoadModule(componentModulePath)\n            : undefined,\n        });\n        return await createFarmMarkdownRouteModuleFromFile(modulePath, {\n          components,\n          config: mdxConfig,\n        });\n      }\n\n      if (this.viteServer) {\n        const module = await this.viteServer.ssrLoadModule(modulePath);\n        return module as RouteModule;\n      } else {\n        const module = await import(/* @vite-ignore */ modulePath);\n        return module as RouteModule;\n      }\n    } catch (error) {\n      logger.error(`Failed to load route module: ${modulePath}`);\n      throw error;\n    }\n  }\n\n  /**\n   * Load a layout module dynamically\n   */\n  async loadLayoutModule(modulePath: string): Promise<LayoutModule> {\n    try {\n      const programmaticLayout = this.programmaticLayouts.get(modulePath);\n      if (programmaticLayout) {\n        const { createLayoutModuleFromProgrammaticLayout } = await import(\"../routes\");\n        return createLayoutModuleFromProgrammaticLayout(programmaticLayout) as LayoutModule;\n      }\n\n      if (this.viteServer) {\n        const module = await this.viteServer.ssrLoadModule(modulePath);\n        return module as LayoutModule;\n      } else {\n        const module = await import(/* @vite-ignore */ modulePath);\n        return module as LayoutModule;\n      }\n    } catch (error) {\n      logger.error(`Failed to load layout module: ${modulePath}`);\n      throw error;\n    }\n  }\n\n  /**\n   * Create a route pattern from parsed route\n   */\n  private createRoutePattern(route: ParsedRoute): string {\n    if (route.segments.length === 0) return \"/\";\n\n    return (\n      \"/\" +\n      route.segments\n        .map((segment) => {\n          if (!segment.isDynamic) return segment.segment;\n\n          if (segment.isCatchAll) {\n            return segment.isOptional ? `[[...${segment.segment}]]` : `[...${segment.segment}]`;\n          }\n\n          return `[${segment.segment}]`;\n        })\n        .join(\"/\")\n    );\n  }\n\n  private registerPageRoute(entry: RouteEntry): void {\n    assertUniqueRouteParameters(entry.pattern);\n    const shape = getRoutePatternShape(entry.pattern);\n    const existing = this.pageRouteShapes.get(shape);\n\n    if (existing && existing.pattern !== entry.pattern) {\n      if (existing.sourceRoot === entry.sourceRoot) {\n        throw new Error(\n          `Ambiguous page routes \"${existing.pattern}\" and \"${entry.pattern}\" match the same URLs. Found ${existing.modulePath} and ${entry.modulePath}. Keep only one route for this URL shape.`,\n        );\n      }\n      this.routes.delete(existing.pattern);\n    }\n\n    this.routes.set(entry.pattern, entry);\n    this.pageRouteShapes.set(shape, entry);\n  }\n\n  private async discoverFileRoutes(source: FarmSourceRoot): Promise<void> {\n    const appDir = resolveAppPath(source.root, source.srcDir, \"app\");\n    const componentExtensions = getFarmRendererComponentExtensions(this.config.renderer).map(\n      (extension) => extension.slice(1),\n    );\n    const componentGlob = componentExtensions.join(\",\");\n    const pageFiles = await safeGlobFiles(`**/page.{${componentGlob},md,mdx}`, appDir);\n    const slotDefaultFiles = await safeGlobFiles(`**/@*/**/default.{${componentGlob}}`, appDir);\n    const layoutFiles = await safeGlobFiles(`**/layout.{${componentGlob}}`, appDir);\n    const loadingFiles = await safeGlobFiles(`**/loading.{${componentGlob}}`, appDir);\n    const errorFiles = await safeGlobFiles(`**/error.{${componentGlob}}`, appDir);\n    const metadataImageFiles = await safeGlobFiles(\n      `**/{opengraph-image,twitter-image}.{${componentGlob},png,jpg,jpeg,gif,webp}`,\n      appDir,\n    );\n    const metadataRouteFiles = await safeGlobFiles(\"**/{sitemap,robots,manifest}.{ts,js}\", appDir);\n\n    const canonicalPageGroups = new Map<\n      string,\n      {\n        route: ParsedRoute;\n        files: string[];\n      }\n    >();\n    for (const file of pageFiles.filter((candidate) => parseRouteSlotFile(candidate) === null)) {\n      const route = parseRoutePath(file);\n      const pattern = this.createRoutePattern(route);\n      const group = canonicalPageGroups.get(pattern);\n      if (group) {\n        group.files.push(file);\n      } else {\n        canonicalPageGroups.set(pattern, {\n          route,\n          files: [file],\n        });\n      }\n    }\n\n    for (const [pattern, group] of canonicalPageGroups) {\n      const componentFiles = group.files.filter((file) => !isFarmMarkdownPageFile(file));\n      const markdownFiles = group.files.filter(isFarmMarkdownPageFile);\n      if (componentFiles.length > 1) {\n        throw new Error(\n          `Duplicate page route \"${pattern}\". Found ${componentFiles\n            .map((file) => path.join(appDir, file))\n            .join(\" and \")}.`,\n        );\n      }\n      if (markdownFiles.length > 1) {\n        throw new Error(\n          `Duplicate markdown representation for page route \"${pattern}\". Found ${markdownFiles\n            .map((file) => path.join(appDir, file))\n            .join(\" and \")}.`,\n        );\n      }\n\n      const componentFile = componentFiles[0];\n      const markdownFile = markdownFiles[0];\n      const primaryFile = componentFile || markdownFile;\n      if (!primaryFile) continue;\n\n      const modulePath = path.join(appDir, primaryFile);\n      const existing = this.routes.get(pattern);\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate page route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n        );\n      }\n      this.registerPageRoute({\n        route: group.route,\n        modulePath,\n        ...(markdownFile\n          ? {\n              markdownSourcePath: path.join(appDir, markdownFile),\n            }\n          : {}),\n        pattern,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n\n    for (const [kind, files, target] of [\n      [\"layout\", layoutFiles, this.layouts],\n      [\"loading\", loadingFiles, this.loadings],\n      [\"error\", errorFiles, this.errors],\n    ] as const) {\n      for (const file of files) {\n        const route = parseRoutePath(file);\n        const modulePath = path.join(appDir, file);\n        const pattern = this.createRoutePattern(route);\n        const existing = target.get(pattern);\n        if (existing?.sourceRoot === source.root) {\n          throw new Error(\n            `Duplicate ${kind} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n          );\n        }\n        target.set(pattern, {\n          route,\n          modulePath,\n          pattern,\n          source: \"file\",\n          sourceRoot: source.root,\n        });\n      }\n    }\n\n    for (const file of [...pageFiles, ...slotDefaultFiles]) {\n      const slot = parseRouteSlotFile(file);\n      if (!slot) continue;\n\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(slot.route);\n      const ownerPattern = this.createRoutePattern(slot.ownerRoute);\n      const key = `${ownerPattern}:${slot.name}:${slot.interception ? \"intercept\" : \"slot\"}:${\n        slot.fallback ? \"default\" : pattern\n      }`;\n      const existing = this.routeSlots.get(key);\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate route slot \"${slot.name}\" for \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n        );\n      }\n\n      this.routeSlots.set(key, {\n        route: slot.route,\n        modulePath,\n        pattern,\n        source: \"file\",\n        sourceRoot: source.root,\n        name: slot.name,\n        ownerPattern,\n        interception: slot.interception,\n        fallback: slot.fallback,\n        containerId: createRouteSlotContainerId(slot.name, ownerPattern),\n      });\n    }\n\n    for (const file of metadataImageFiles) {\n      const fileBase = path.basename(file, path.extname(file));\n      const kind: MetadataImageKind = fileBase === \"twitter-image\" ? \"twitter\" : \"opengraph\";\n      const fileName = kind === \"twitter\" ? \"twitter-image\" : \"opengraph-image\";\n      const route = parseRoutePath(file);\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(route);\n      const key = `${kind}:${pattern}`;\n      const existing = this.metadataImages.get(key);\n      const sourceType = isStaticMetadataImageFile(file) ? \"static\" : \"module\";\n\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate ${fileName} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}. Keep only one static image or module per route segment.`,\n        );\n      }\n\n      const staticInfo =\n        sourceType === \"static\" ? await inspectStaticMetadataImage(modulePath) : undefined;\n\n      this.metadataImages.set(key, {\n        route,\n        modulePath,\n        pattern,\n        kind,\n        fileName,\n        sourceType,\n        staticInfo,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n\n    for (const file of metadataRouteFiles) {\n      const descriptor = getApplicationMetadataRouteDescriptor(\n        path.basename(file, path.extname(file)),\n      );\n      if (!descriptor) continue;\n      const route = parseRoutePath(file);\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(route);\n      const key = `${descriptor.kind}:${pattern}`;\n      const existing = this.metadataRoutes.get(key);\n\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate ${descriptor.fileName} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}. Keep only one .ts or .js metadata route per segment.`,\n        );\n      }\n\n      this.metadataRoutes.set(key, {\n        route,\n        modulePath,\n        pattern,\n        ...descriptor,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n  }\n\n  private async discoverProgrammaticRoutes(source: FarmSourceRoot): Promise<void> {\n    const manifests = await loadProgrammaticRouteManifests({\n      root: source.root,\n      srcDir: source.srcDir,\n      loadModule: (filePath) => this.loadProgrammaticRoutesModule(filePath),\n    });\n\n    for (const { filePath, manifest } of manifests) {\n      for (const definition of manifest.routes) {\n        if (definition.kind === \"page\") {\n          const route = parseProgrammaticRoutePath(definition.path, \"page\");\n          const pattern = this.createRoutePattern(route);\n          const existing = this.routes.get(pattern);\n\n          if (existing?.sourceRoot === source.root) {\n            throw new Error(\n              `Duplicate page route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n            );\n          }\n\n          const modulePath = createProgrammaticRouteModuleId(filePath, \"page\", definition.path);\n          this.programmaticPages.set(modulePath, definition);\n          this.registerPageRoute({\n            route,\n            modulePath,\n            pattern,\n            source: \"programmatic\",\n            sourceRoot: source.root,\n          });\n        }\n\n        if (definition.kind === \"layout\") {\n          const route = parseProgrammaticRoutePath(definition.path, \"layout\");\n          const pattern = this.createRoutePattern(route);\n          const existing = this.layouts.get(pattern);\n          if (existing?.sourceRoot === source.root) {\n            throw new Error(\n              `Duplicate layout route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n            );\n          }\n          const modulePath = createProgrammaticRouteModuleId(filePath, \"layout\", definition.path);\n          this.programmaticLayouts.set(modulePath, definition);\n          this.layouts.set(pattern, {\n            route,\n            modulePath,\n            pattern,\n            source: \"programmatic\",\n            sourceRoot: source.root,\n          });\n        }\n\n        if (definition.kind === \"redirect\") {\n          const route = parseProgrammaticRoutePath(definition.source, \"page\");\n          const pattern = this.createRoutePattern(route);\n          this.redirects.set(pattern, {\n            route,\n            pattern,\n            definition,\n          });\n        }\n      }\n    }\n  }\n\n  private async loadProgrammaticRoutesModule(filePath: string): Promise<Record<string, any>> {\n    if (this.viteServer) {\n      const viteRoot = this.viteServer.config?.root || this.config.root || process.cwd();\n      return await this.viteServer.ssrLoadModule(toViteModuleId(filePath, viteRoot));\n    }\n\n    const fileUrl = `file://${filePath}`;\n    return await import(/* @vite-ignore */ fileUrl);\n  }\n\n  /**\n   * Find all layouts that should wrap a given path\n   */\n  private findMatchingLayouts(pathname: string): RouteEntry[] {\n    const matchingLayouts: RouteEntry[] = [];\n\n    const sortedLayouts = Array.from(this.layouts.values()).sort((a, b) => {\n      return a.route.segments.length - b.route.segments.length;\n    });\n\n    for (const layoutEntry of sortedLayouts) {\n      if (matchRoutePrefix(pathname, layoutEntry.route.segments)) {\n        matchingLayouts.push(layoutEntry);\n      }\n    }\n\n    return matchingLayouts;\n  }\n\n  private findMatchingRouteSlots(pathname: string, interceptFrom?: string): MatchedRouteSlot[] {\n    const groups = new Map<string, RouteSlotEntry[]>();\n    for (const entry of this.routeSlots.values()) {\n      if (!this.matchesRoutePrefix(pathname, entry.ownerPattern)) continue;\n      const key = `${entry.ownerPattern}:${entry.name}`;\n      const entries = groups.get(key) ?? [];\n      entries.push(entry);\n      groups.set(key, entries);\n    }\n\n    const normalizedFrom = interceptFrom\n      ? this.toRoutePathname(new URL(interceptFrom, \"http://farm.local\").pathname)\n      : undefined;\n    const matches: MatchedRouteSlot[] = [];\n\n    for (const entries of groups.values()) {\n      const candidates = entries\n        .filter((entry) => !entry.fallback)\n        .filter(\n          (entry) =>\n            !entry.interception ||\n            (normalizedFrom !== undefined &&\n              this.matchesRoutePrefix(normalizedFrom, entry.ownerPattern)),\n        )\n        .map((entry) => ({\n          entry,\n          match: matchRoute(pathname, entry.route.segments),\n        }))\n        .filter((candidate) => candidate.match.matches)\n        .sort((left, right) => {\n          if (left.entry.interception !== right.entry.interception) {\n            return left.entry.interception ? -1 : 1;\n          }\n          return compareRouteEntries(left.entry, right.entry);\n        });\n\n      const selected = candidates[0];\n      if (selected) {\n        matches.push({\n          name: selected.entry.name,\n          ownerPattern: selected.entry.ownerPattern,\n          containerId: selected.entry.containerId,\n          interception: selected.entry.interception,\n          fallback: false,\n          route: selected.entry,\n          params: selected.match.params,\n        });\n        continue;\n      }\n\n      const fallback = entries.find((entry) => entry.fallback);\n      if (fallback) {\n        matches.push({\n          name: fallback.name,\n          ownerPattern: fallback.ownerPattern,\n          containerId: fallback.containerId,\n          interception: false,\n          fallback: true,\n          route: fallback,\n          params: {},\n        });\n      }\n    }\n\n    return matches.sort((left, right) => {\n      const ownerDifference = left.route.route.segments.length - right.route.route.segments.length;\n      return ownerDifference || left.name.localeCompare(right.name);\n    });\n  }\n\n  private matchesRoutePrefix(pathname: string, pattern: string): boolean {\n    if (pattern === \"/\") return true;\n    const patternSegments = parseRoutePath(`${pattern}/page.tsx`).segments;\n    return matchRoutePrefix(pathname, patternSegments);\n  }\n\n  private findNearestBoundary(\n    pathname: string,\n    boundaries: Map<string, RouteEntry>,\n  ): RouteEntry | null {\n    const normalizedPath = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n    let bestMatch: RouteEntry | null = null;\n\n    for (const boundaryEntry of boundaries.values()) {\n      if (!matchRoutePrefix(normalizedPath, boundaryEntry.route.segments)) continue;\n\n      if (!bestMatch || boundaryEntry.route.segments.length > bestMatch.route.segments.length) {\n        bestMatch = boundaryEntry;\n      }\n    }\n\n    return bestMatch;\n  }\n\n  /**\n   * Log discovered routes for debugging\n   */\n  private logRoutes(): void {\n    if (this.routes.size > 0) {\n      logger.info(\"Registered routes:\");\n      for (const [pattern, entry] of this.routes) {\n        console.log(`  ${pattern} -> ${entry.modulePath}`);\n      }\n    }\n\n    if (this.layouts.size > 0) {\n      logger.info(\"Registered layouts:\");\n      for (const [pattern, entry] of this.layouts) {\n        console.log(`  ${pattern} -> ${entry.modulePath}`);\n      }\n    }\n  }\n\n  /**\n   * Collect SSG pages for static generation\n   *\n   * Returns all pages marked with `export const ssg = true` along with\n   * their pre-computed paths (for dynamic routes using getStaticPaths)\n   */\n  async collectSSGPages(): Promise<SSGCollectionResult> {\n    const routes = Array.from(this.routes.values()).map((entry) => ({\n      path: entry.pattern,\n      filePath: entry.modulePath,\n      isDynamic: entry.route.segments.some((seg) => seg.isDynamic),\n      pattern: entry.pattern,\n    }));\n\n    const i18n = this.getI18nConfig();\n    const result = await collectSSGPages(routes, (filePath) => this.loadRouteModule(filePath), {\n      suggestStaticRendering: shouldSuggestStaticRenderingForI18n(i18n),\n    });\n    if (!i18n) {\n      return result;\n    }\n\n    // A single static URL cannot safely vary by cookie or Accept-Language.\n    // Keep locale-without-prefix pages dynamic so caches never pin one language.\n    if (i18n.routing === \"none\") {\n      return {\n        ssg: [],\n        ssr: Array.from(new Set([...result.ssr, ...result.ssg.map((page) => page.urlPath)])),\n      };\n    }\n\n    return {\n      ssg: result.ssg.flatMap((page) =>\n        i18n.locales.map((locale) => ({\n          ...page,\n          urlPath: localizeFarmPathname(page.urlPath, locale, i18n),\n        })),\n      ),\n      ssr: result.ssr.flatMap((routePath) =>\n        i18n.locales.map((locale) => localizeFarmPathname(routePath, locale, i18n)),\n      ),\n    };\n  }\n\n  private toRoutePathname(pathname: string): string {\n    const i18n = this.getI18nConfig();\n    return i18n ? stripFarmLocaleFromPathname(pathname, i18n) : pathname;\n  }\n\n  private localizeRedirectDestination(destination: string, locale?: string): string {\n    if (!locale || !destination.startsWith(\"/\") || destination.startsWith(\"//\")) {\n      return destination;\n    }\n    const i18n = this.getI18nConfig();\n    return i18n ? localizeFarmHref(destination, locale, i18n) : destination;\n  }\n\n  private getI18nConfig(): ResolvedFarmI18nConfig | undefined {\n    const i18n = this.config.i18n;\n    return i18n && typeof i18n === \"object\" && \"enabled\" in i18n && i18n.enabled ? i18n : undefined;\n  }\n\n  /**\n   * Check if a route is SSG\n   */\n  async isRouteSSG(modulePath: string): Promise<boolean> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.ssg;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Check if a route has ISR (Incremental Static Regeneration)\n   */\n  async hasRouteISR(modulePath: string): Promise<boolean> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Get revalidation interval for a route\n   */\n  async getRouteRevalidateInterval(modulePath: string): Promise<number | undefined> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.revalidate;\n    } catch {\n      return undefined;\n    }\n  }\n}\n\nexport function interpolateRedirectDestination(\n  destination: string,\n  params: Record<string, string>,\n): string {\n  let result = destination;\n\n  for (const [key, value] of Object.entries(params)) {\n    // Longest token first: [[...key]] contains [...key], which contains [key].\n    result = replaceAll(result, `[[...${key}]]`, value);\n    result = replaceAll(result, `[...${key}]`, value);\n    result = replaceAll(result, `[${key}]`, value);\n    result = replaceAll(result, `:${key}*`, value);\n    result = replaceAll(result, `:${key}`, value);\n  }\n\n  return result;\n}\n\nfunction getMetadataImageSuffix(pathname: string): {\n  kind: MetadataImageKind;\n  fileName: MetadataImageEntry[\"fileName\"];\n} | null {\n  if (pathname === \"/opengraph-image\" || pathname.endsWith(\"/opengraph-image\")) {\n    return { kind: \"opengraph\", fileName: \"opengraph-image\" };\n  }\n\n  if (pathname === \"/twitter-image\" || pathname.endsWith(\"/twitter-image\")) {\n    return { kind: \"twitter\", fileName: \"twitter-image\" };\n  }\n\n  return null;\n}\n\nfunction getApplicationMetadataRouteDescriptor(fileName: string): {\n  kind: ApplicationMetadataRouteKind;\n  fileName: ApplicationMetadataRouteEntry[\"fileName\"];\n  outputName: ApplicationMetadataRouteEntry[\"outputName\"];\n} | null {\n  if (fileName === \"sitemap\") {\n    return { kind: \"sitemap\", fileName: \"sitemap\", outputName: \"sitemap.xml\" };\n  }\n  if (fileName === \"robots\") {\n    return { kind: \"robots\", fileName: \"robots\", outputName: \"robots.txt\" };\n  }\n  if (fileName === \"manifest\") {\n    return { kind: \"manifest\", fileName: \"manifest\", outputName: \"manifest.webmanifest\" };\n  }\n  return null;\n}\n\nfunction getApplicationMetadataRouteSuffix(pathname: string): {\n  kind: ApplicationMetadataRouteKind;\n  outputName: ApplicationMetadataRouteEntry[\"outputName\"];\n} | null {\n  for (const fileName of [\"sitemap\", \"robots\", \"manifest\"] as const) {\n    const descriptor = getApplicationMetadataRouteDescriptor(fileName)!;\n    if (\n      pathname === `/${descriptor.outputName}` ||\n      pathname.endsWith(`/${descriptor.outputName}`)\n    ) {\n      return { kind: descriptor.kind, outputName: descriptor.outputName };\n    }\n  }\n  return null;\n}\n\nfunction routeSegmentsToPath(\n  segments: ParsedRoute[\"segments\"],\n  params: Record<string, string>,\n): string {\n  if (segments.length === 0) return \"/\";\n\n  const parts: string[] = [];\n  for (const segment of segments) {\n    if (!segment.isDynamic) {\n      parts.push(segment.segment);\n      continue;\n    }\n\n    const value = params[segment.segment];\n    if (!value && segment.isOptional) continue;\n    if (!value) {\n      parts.push(`[${segment.segment}]`);\n      continue;\n    }\n\n    parts.push(...value.split(\"/\").map((part) => encodeURIComponent(part)));\n  }\n\n  return `/${parts.join(\"/\")}`;\n}\n\nfunction replaceAll(input: string, search: string, replacement: string): string {\n  return input.split(search).join(replacement);\n}\n\nasync function safeGlobFiles(pattern: string, cwd: string): Promise<string[]> {\n  try {\n    return await globFiles(pattern, cwd);\n  } catch {\n    return [];\n  }\n}\n","// Stylesheets the dev document must link beyond globals.css.\n//\n// The dev shell links `/src/app/globals.css` and nothing else, so CSS that\n// enters through a JS import — `import \"@fontsource-variable/geist\"` in a\n// layout, a component stylesheet, vendor CSS — never reaches the page: no\n// error, just silently missing rules (farming-labs/farm.js#658). Vite's module\n// graph knows every stylesheet the app touched; collecting it closes the gap.\n\n/** The slice of Vite's ModuleNode this module reads, kept minimal for tests. */\nexport interface DevStyleModule {\n  url?: string | null;\n  id?: string | null;\n  file?: string | null;\n}\n\nconst STYLE_EXTENSIONS = /\\.(css|scss|sass|less|styl|stylus)(?:$|\\?)/;\n\n/** The stylesheet link the shell already emits; its own `@import`s resolve\n * inside that response, so neither it nor its query variants repeat here. */\nconst ALREADY_LINKED = \"/src/app/globals.css\";\n\n/**\n * Stylesheet URLs from the module graph that the document should link,\n * deduped and sorted for a deterministic head. CSS modules (`.module.css`)\n * are excluded: their classes are hashed through the JS pipeline and a plain\n * link would apply nothing useful.\n */\nexport function collectDevStylesheetUrls(modules: Iterable<DevStyleModule>): string[] {\n  const seen = new Set<string>();\n  for (const mod of modules) {\n    const id = mod.id ?? mod.file ?? \"\";\n    if (!STYLE_EXTENSIONS.test(id)) continue;\n    if (id.includes(\".module.\")) continue;\n    const url = mod.url;\n    if (!url || !url.startsWith(\"/\")) continue;\n    const bare = url.split(\"?\")[0]!;\n    if (bare === ALREADY_LINKED) continue;\n    seen.add(bare);\n  }\n  return [...seen].sort();\n}\n","// Handling for a root layout that returns a full `<html>…</html>` document.\n//\n// Farm owns the document shell — a layout is expected to return a fragment (its\n// children), like the docs example does. When a layout instead returns a whole\n// document, the dev renderer must compose that document as the response rather\n// than nesting it inside the generated shell, which would emit invalid nested\n// `<html>`/`<head>`/`<body>`. This mirrors the production (Nitro) build's\n// `hasFullDocument` path so dev and prod agree.\n\n/** Peel Farm's leading `display:contents` wrapper divs (the stream root and any\n * layout-boundary divs) so the layout's own markup is exposed for inspection. */\nfunction stripContentsWrappers(markup: string): string {\n  let out = markup.replace(/^\\s+/, \"\");\n  const opener = /^<div\\b[^>]*style=\"display\\s*:\\s*contents\"[^>]*>/i;\n  let match: RegExpExecArray | null;\n  while ((match = opener.exec(out))) {\n    out = out.slice(match[0].length).replace(/^\\s+/, \"\");\n  }\n  return out;\n}\n\n/**\n * When `markup` (a rendered layout tree, possibly wrapped in Farm's\n * `display:contents` boundary divs) is a full HTML document, return just that\n * `<html>…</html>` document (leading `<!DOCTYPE>` preserved when present);\n * otherwise return `null`.\n */\nexport function extractFarmFullDocument(markup: string): string | null {\n  const inner = stripContentsWrappers(markup);\n  if (!/^<!doctype/i.test(inner) && !/^<html[\\s>]/i.test(inner)) return null;\n  const start = markup.search(/<!doctype|<html[\\s>]/i);\n  const closeIndex = markup.toLowerCase().lastIndexOf(\"</html>\");\n  if (start < 0 || closeIndex < 0) return null;\n  return markup.slice(start, closeIndex + \"</html>\".length);\n}\n\n/** True when a rendered layout tree is (or wraps) a full HTML document. */\nexport function isFarmFullDocument(markup: string): boolean {\n  return extractFarmFullDocument(markup) !== null;\n}\n\n/**\n * True when `markup` *begins* a full HTML document once Farm's wrappers are\n * peeled — usable on a streamed prefix, before the closing `</html>` has been\n * flushed.\n */\nexport function opensFarmFullDocument(markup: string): boolean {\n  const inner = stripContentsWrappers(markup);\n  return /^<!doctype/i.test(inner) || /^<html[\\s>]/i.test(inner);\n}\n\nexport interface FarmFullDocumentAssets {\n  /** Farm-managed `<head>` markup (styles, client/runtime scripts, metadata). */\n  headAssets: string;\n  /** Markup injected just before `</body>` (client bootstrap / entry scripts). */\n  bodyFooter: string;\n  /** Extra `<html>` attributes to merge (theme, direction). */\n  htmlAttributes?: string;\n}\n\n/**\n * Compose a layout's own full document with Farm's managed head + body assets,\n * instead of nesting it inside the shell. String replacements use function\n * replacers so any `$`-sequences (`$&`, `$'`, `$$`) in the injected markup or\n * the document are inserted literally rather than expanded.\n */\nexport function composeFarmFullDocument(\n  documentHtml: string,\n  assets: FarmFullDocumentAssets,\n): string {\n  let html = documentHtml;\n\n  if (assets.htmlAttributes) {\n    html = html.replace(\n      /<html\\b([^>]*)>/i,\n      (_match, attrs: string) => `<html${attrs}${assets.htmlAttributes}>`,\n    );\n  }\n\n  // Ensure a hydration root exists so the client can mount, matching the shell.\n  if (!/\\sid=[\"']root[\"']/i.test(html)) {\n    html = html\n      .replace(/<body\\b([^>]*)>/i, '<body$1><div id=\"root\">')\n      .replace(/<\\/body>/i, \"</div></body>\");\n  }\n\n  if (assets.headAssets) {\n    html = html.replace(/<\\/head>/i, () => `  ${assets.headAssets}\\n</head>`);\n  }\n  if (assets.bodyFooter) {\n    html = html.replace(/<\\/body>/i, () => `  ${assets.bodyFooter}\\n</body>`);\n  }\n\n  return /^\\s*<!doctype/i.test(html) ? html : `<!DOCTYPE html>\\n${html}`;\n}\n","/**\n * Server-side middleware utilities for accessing middleware data in pages\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport type { ReadonlyMiddlewareStore } from \"./types\";\n\ntype MiddlewareStoreInput = Record<string, any> | Map<string, any>;\nconst MIDDLEWARE_DATA_STORE_KEY = Symbol.for(\"farm.middlewareDataStore\");\nconst MIDDLEWARE_CONTEXT_STORE_KEY = Symbol.for(\"farm.middlewareContextStore\");\n\nfunction getGlobalMiddlewareStore(key: symbol): AsyncLocalStorage<Map<string, any>> {\n  const state = globalThis as typeof globalThis & Record<symbol, unknown>;\n  const existing = state[key];\n  if (existing instanceof AsyncLocalStorage) {\n    return existing as AsyncLocalStorage<Map<string, any>>;\n  }\n\n  const store = new AsyncLocalStorage<Map<string, any>>();\n  state[key] = store;\n  return store;\n}\n\nconst middlewareStore = getGlobalMiddlewareStore(MIDDLEWARE_DATA_STORE_KEY);\nconst middlewareContextStore = getGlobalMiddlewareStore(MIDDLEWARE_CONTEXT_STORE_KEY);\n\nfunction toMiddlewareMap(data: MiddlewareStoreInput): Map<string, any> {\n  if (data instanceof Map) {\n    return new Map(data);\n  }\n  return new Map(Object.entries(data));\n}\n\n/**\n * Internal: Set middleware data for the current request\n * This is called by the server renderer before rendering starts.\n * Prefer _runWithMiddlewareData for request-scoped async flows.\n */\nexport function _setCurrentMiddlewareData(data: MiddlewareStoreInput): void {\n  middlewareStore.enterWith(toMiddlewareMap(data));\n}\n\n/**\n * Internal: Clear middleware data after request completes\n */\nexport function _clearCurrentMiddlewareData(): void {\n  middlewareStore.enterWith(new Map());\n}\n\n/** Internal: Clear server-only middleware context after rendering. */\nexport function _clearCurrentMiddlewareContext(): void {\n  middlewareContextStore.enterWith(new Map());\n}\n\n/**\n * Internal: Run code with middleware data available\n * This is called by the server renderer\n */\nexport async function _runWithMiddlewareData<T>(\n  data: MiddlewareStoreInput,\n  fn: () => T | Promise<T>,\n): Promise<T> {\n  return middlewareStore.run(toMiddlewareMap(data), fn);\n}\n\n/** Internal: Run code with server-only middleware context available. */\nexport async function _runWithMiddlewareContext<T>(\n  context: MiddlewareStoreInput,\n  fn: () => T | Promise<T>,\n): Promise<T> {\n  return middlewareContextStore.run(toMiddlewareMap(context), fn);\n}\n\n/**\n * Get middleware data in a server component\n * No props needed - uses global storage!\n *\n * @example\n * ```tsx\n * import { getMiddlewareData } from 'farm/middleware';\n *\n * export default function Page() {\n *   const data = getMiddlewareData();  // ← No props needed!\n *   const user = data.get('user');\n *   const demoInfo = data.get('demoInfo');\n *\n *   return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function getMiddlewareData<T extends Record<string, any> = Record<string, any>>(): Map<\n  keyof T,\n  T[keyof T]\n> {\n  return (middlewareStore.getStore() || new Map()) as Map<keyof T, T[keyof T]>;\n}\n\n/**\n * Get a specific value from middleware data (synchronous)\n * Uses AsyncLocalStorage for request scoping - no props needed.\n *\n * @example\n * ```tsx\n * import { getMiddlewareValue } from 'farm/middleware';\n *\n * export default function Page() {\n *   const user = getMiddlewareValue<User>('user');  // ← No props needed!\n *   const stats = getMiddlewareValue('dashboardStats');\n *\n *   return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function getMiddlewareValue<T = any>(key: string): T | undefined {\n  const data = getMiddlewareData();\n  return data.get(key);\n}\n\n/**\n * Read server-only values set by route middleware for the current request.\n * The returned store is available to the matched page, layouts, and nested\n * Server Components, but is never added to hydration props.\n */\nexport function getMiddlewareContext<\n  T extends Record<string, any> = Record<string, any>,\n>(): ReadonlyMiddlewareStore<T> {\n  return (middlewareContextStore.getStore() || new Map()) as unknown as ReadonlyMiddlewareStore<T>;\n}\n\n/**\n * Type-safe middleware data accessor with type parameter\n *\n * @example\n * ```tsx\n * import { createMiddlewareAccessor } from 'farm/middleware/server';\n *\n * interface MiddlewareData {\n *   user: { id: number; name: string };\n *   dashboardStats: { views: number; clicks: number };\n * }\n *\n * const getData = createMiddlewareAccessor<MiddlewareData>();\n *\n * export default function Page() {\n *   const data = getData();\n *   const user = data.user;  // Fully typed!\n *   const stats = data.dashboardStats;  // Fully typed!\n *\n *   return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function createMiddlewareAccessor<T extends Record<string, any>>() {\n  return (): Partial<T> => {\n    const data = getMiddlewareData();\n    const result: any = {};\n\n    for (const [key, value] of data) {\n      result[key] = value;\n    }\n\n    return result as Partial<T>;\n  };\n}\n","type CurrentRequestResolver = () => Request | undefined;\n\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\n\ntype GlobalWithCurrentRequestResolver = typeof globalThis & {\n  [CURRENT_REQUEST_RESOLVER_KEY]?: CurrentRequestResolver;\n};\n\nfunction getGlobalState(): GlobalWithCurrentRequestResolver {\n  return globalThis as GlobalWithCurrentRequestResolver;\n}\n\nexport function _setCurrentRequestResolver(resolver: CurrentRequestResolver | undefined): void {\n  getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;\n}\n\nexport function _resolveCurrentRequest(): Request | undefined {\n  return getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { Readable } from \"node:stream\";\nimport type { FarmRequest } from \"../types\";\nimport { _setCurrentRequestResolver } from \"./request-bridge\";\n\nconst REQUEST_STORAGE_KEY = Symbol.for(\"@farm.js/core/request-storage\");\n\nfunction getRequestStore(): AsyncLocalStorage<Request> {\n  const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n  const existing = runtime[REQUEST_STORAGE_KEY];\n  if (existing instanceof AsyncLocalStorage) {\n    return existing as AsyncLocalStorage<Request>;\n  }\n\n  const storage = new AsyncLocalStorage<Request>();\n  runtime[REQUEST_STORAGE_KEY] = storage;\n  return storage;\n}\n\nconst requestStore = getRequestStore();\n\n_setCurrentRequestResolver(() => requestStore.getStore());\n\nexport interface FarmRequestURLOptions {\n  origin?: string | URL;\n  trustProxy?: boolean;\n}\n\nexport function resolveFarmRequestURL(req: FarmRequest, options: FarmRequestURLOptions = {}): URL {\n  if (options.origin) {\n    return new URL(req.url || \"/\", options.origin);\n  }\n\n  const forwardedHost = options.trustProxy\n    ? firstForwardedHeaderValue(req.headers[\"x-forwarded-host\"])\n    : undefined;\n  const fallbackHost = firstForwardedHeaderValue(req.headers.host) || \"localhost\";\n  const forwardedProto = options.trustProxy\n    ? firstForwardedHeaderValue(req.headers[\"x-forwarded-proto\"])\n    : undefined;\n  const normalizedProto = forwardedProto?.toLowerCase();\n  const proto =\n    normalizedProto === \"https\" || normalizedProto === \"http\"\n      ? normalizedProto\n      : isEncryptedFarmRequest(req)\n        ? \"https\"\n        : \"http\";\n  return new URL(req.url || \"/\", resolveRequestOrigin(proto, forwardedHost, fallbackHost));\n}\n\nexport function createWebRequestFromFarmRequest(\n  req: FarmRequest,\n  options: FarmRequestURLOptions = {},\n): Request {\n  const fullUrl = resolveFarmRequestURL(req, options).toString();\n\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        headers.append(key, item);\n      }\n      continue;\n    }\n\n    headers.set(key, value);\n  }\n\n  const method = (req.method || \"GET\").toUpperCase();\n  const init: RequestInit & { duplex?: \"half\" } = {\n    method: req.method,\n    headers,\n  };\n\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    init.body = Readable.toWeb(req) as ReadableStream<Uint8Array>;\n    init.duplex = \"half\";\n  }\n\n  return new Request(fullUrl, init);\n}\n\nfunction isEncryptedFarmRequest(req: FarmRequest): boolean {\n  return Boolean((req.socket as { encrypted?: boolean } | undefined)?.encrypted);\n}\n\nfunction firstForwardedHeaderValue(value: string | string[] | undefined): string | undefined {\n  const first = Array.isArray(value) ? value[0] : value;\n  const token = first?.split(\",\", 1)[0]?.trim();\n  return token || undefined;\n}\n\nfunction resolveRequestOrigin(proto: \"http\" | \"https\", host: string | undefined, fallback: string) {\n  for (const candidate of [host, fallback, \"localhost\"]) {\n    if (!candidate) continue;\n    if (/[\\s/?#@\\\\]/u.test(candidate)) continue;\n    try {\n      const url = new URL(`${proto}://${candidate}`);\n      if (url.username || url.password || url.pathname !== \"/\" || url.search || url.hash) continue;\n      return url.origin;\n    } catch {\n      // Try the next host instead of turning an untrusted proxy header into a 500.\n    }\n  }\n  return `${proto}://localhost`;\n}\n\nexport async function _runWithCurrentRequest<T>(\n  request: Request,\n  fn: () => Promise<T> | T,\n): Promise<T> {\n  return requestStore.run(request, fn);\n}\n\nexport function getCurrentRequest(): Request {\n  const request = requestStore.getStore();\n  if (!request) {\n    throw new Error(\n      \"No current request is available. getCurrentRequest() can only be used during server rendering.\",\n    );\n  }\n\n  return request;\n}\n\n// Some runtimes (StackBlitz WebContainers among them) lose AsyncLocalStorage\n// context across async boundaries mid-render. Callers whose feature can\n// degrade gracefully should use this instead of getCurrentRequest() so a\n// missing store never turns into a 500.\nexport function getCurrentRequestOrNull(): Request | null {\n  return requestStore.getStore() ?? null;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { getFarmRendererComponentExtensions, type FarmRenderer } from \"./renderer\";\n\ninterface FarmNotFoundPathConfig {\n  root: string;\n  renderer: FarmRenderer;\n  notFound?: {\n    component?: string;\n  };\n}\n\nexport function resolveFarmNotFoundComponentPath(\n  config: FarmNotFoundPathConfig,\n  appDirs: readonly string[],\n): string | null {\n  const extensions = getFarmRendererComponentExtensions(config.renderer);\n  const configuredPath = config.notFound?.component?.trim();\n\n  if (configuredPath) {\n    const componentPath = path.isAbsolute(configuredPath)\n      ? path.normalize(configuredPath)\n      : path.resolve(config.root, configuredPath);\n    if (!extensions.some((extension) => componentPath.endsWith(extension))) {\n      throw new Error(\n        `notFound.component must use one of the configured renderer extensions: ${extensions.join(\", \")}`,\n      );\n    }\n    if (!fs.existsSync(componentPath) || !fs.statSync(componentPath).isFile()) {\n      throw new Error(`notFound.component was not found: ${componentPath}`);\n    }\n    return componentPath;\n  }\n\n  let discoveredPath: string | null = null;\n  for (const appDir of appDirs) {\n    for (const extension of extensions) {\n      const candidate = path.join(appDir, `not-found${extension}`);\n      if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\n        discoveredPath = candidate;\n        break;\n      }\n    }\n  }\n  return discoveredPath;\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(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\nfunction 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\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","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    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    output[key] = reviveDeferredValue(item, controllers, settlements, applyingSettlements);\n  }\n  return output;\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","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","import path from \"node:path\";\nimport type {\n  FarmI18nDetectionSignal,\n  FarmI18nDirection,\n  FarmI18nUserConfig,\n  ResolvedFarmI18nConfig,\n} from \"./types\";\n\nexport const DEFAULT_FARM_I18N_COOKIE = \"farm_locale\";\nexport const DEFAULT_FARM_I18N_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\nconst DEFAULT_DETECTION: readonly FarmI18nDetectionSignal[] = [\"url\", \"cookie\", \"accept-language\"];\n\nexport function resolveFarmI18nConfig(\n  input: FarmI18nUserConfig | false | undefined,\n  options: { root?: string; mode?: \"development\" | \"production\"; basePath?: string } = {},\n): ResolvedFarmI18nConfig {\n  const root = options.root || process.cwd();\n  const basePath = options.basePath || \"/\";\n  const strictByDefault = options.mode === \"production\";\n\n  if (!input) {\n    return {\n      enabled: false,\n      basePath,\n      locales: [\"en\"],\n      defaultLocale: \"en\",\n      messages: path.join(root, \"src/messages\"),\n      routing: \"none\",\n      detection: [],\n      fallbackLocale: \"en\",\n      strict: strictByDefault,\n      cookie: {\n        name: DEFAULT_FARM_I18N_COOKIE,\n        maxAge: DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n        path: \"/\",\n        sameSite: \"lax\",\n        secure: options.mode === \"production\",\n      },\n      direction: {},\n    };\n  }\n\n  if (!Array.isArray(input.locales) || input.locales.length === 0) {\n    throw new Error(\"i18n.locales must contain at least one locale.\");\n  }\n\n  const locales = input.locales.map(canonicalizeLocale);\n  if (new Set(locales).size !== locales.length) {\n    throw new Error(\"i18n.locales must not contain duplicate locales.\");\n  }\n\n  const defaultLocale = canonicalizeLocale(input.defaultLocale);\n  if (!locales.includes(defaultLocale)) {\n    throw new Error(`i18n.defaultLocale \"${defaultLocale}\" must be included in i18n.locales.`);\n  }\n\n  const fallbackLocale = canonicalizeLocale(input.fallbackLocale || defaultLocale);\n  if (!locales.includes(fallbackLocale)) {\n    throw new Error(`i18n.fallbackLocale \"${fallbackLocale}\" must be included in i18n.locales.`);\n  }\n\n  const detection = resolveDetection(input);\n  const sameSite = input.cookie?.sameSite ?? \"lax\";\n  if (sameSite !== \"lax\" && sameSite !== \"strict\" && sameSite !== \"none\") {\n    throw new Error('i18n.cookie.sameSite must be \"lax\", \"strict\", or \"none\".');\n  }\n  const direction: Record<string, FarmI18nDirection> = {};\n  for (const [rawLocale, value] of Object.entries(input.direction || {})) {\n    const locale = canonicalizeLocale(rawLocale);\n    if (!locales.includes(locale)) {\n      throw new Error(`i18n.direction contains unknown locale \"${rawLocale}\".`);\n    }\n    if (value !== \"ltr\" && value !== \"rtl\") {\n      throw new Error(`i18n.direction.${rawLocale} must be \"ltr\" or \"rtl\".`);\n    }\n    direction[locale] = value;\n  }\n\n  return {\n    enabled: true,\n    basePath,\n    locales,\n    defaultLocale,\n    messages: path.resolve(root, input.messages || \"src/messages\"),\n    routing: input.routing || \"prefix-except-default\",\n    detection,\n    fallbackLocale,\n    strict: input.strict ?? strictByDefault,\n    cookie: {\n      name: input.cookie?.name?.trim() || DEFAULT_FARM_I18N_COOKIE,\n      maxAge: normalizePositiveInteger(\n        input.cookie?.maxAge,\n        DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n        \"i18n.cookie.maxAge\",\n      ),\n      path: normalizeCookiePath(input.cookie?.path),\n      sameSite,\n      secure: input.cookie?.secure ?? options.mode === \"production\",\n    },\n    direction,\n  };\n}\n\nexport function resolveFarmI18nMessagePath(\n  config: Pick<ResolvedFarmI18nConfig, \"messages\">,\n  locale: string,\n): string {\n  return config.messages.includes(\"{locale}\")\n    ? config.messages.split(\"{locale}\").join(locale)\n    : path.join(config.messages, `${locale}.json`);\n}\n\nexport function canonicalizeLocale(locale: string): string {\n  if (!locale || typeof locale !== \"string\") {\n    throw new Error(\"Farm i18n locales must be non-empty strings.\");\n  }\n\n  try {\n    return Intl.getCanonicalLocales(locale)[0]!;\n  } catch {\n    throw new Error(`Invalid i18n locale \"${locale}\".`);\n  }\n}\n\nfunction resolveDetection(input: FarmI18nUserConfig): readonly FarmI18nDetectionSignal[] {\n  if (input.detection === false || input.localeDetection === false) {\n    return [\"url\"];\n  }\n\n  const detection = input.detection || DEFAULT_DETECTION;\n  const allowed = new Set<FarmI18nDetectionSignal>([\"url\", \"cookie\", \"accept-language\"]);\n  const unique: FarmI18nDetectionSignal[] = [];\n\n  for (const signal of detection) {\n    if (!allowed.has(signal)) {\n      throw new Error(`Unsupported i18n detection signal \"${signal}\".`);\n    }\n    if (!unique.includes(signal)) unique.push(signal);\n  }\n\n  return unique;\n}\n\nfunction normalizePositiveInteger(\n  value: number | undefined,\n  fallback: number,\n  name: string,\n): number {\n  if (value === undefined) return fallback;\n  if (!Number.isInteger(value) || value < 0) {\n    throw new Error(`${name} must be a positive integer.`);\n  }\n  return value;\n}\n\nfunction normalizeCookiePath(value: string | undefined): string {\n  if (value === undefined) return \"/\";\n  if (typeof value !== \"string\") {\n    throw new Error(\"i18n.cookie.path must be a root-relative pathname.\");\n  }\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(value)) {\n    throw new Error(\"i18n.cookie.path cannot contain backslashes or control characters.\");\n  }\n\n  const pathname = value.trim();\n  if (\n    !pathname ||\n    !pathname.startsWith(\"/\") ||\n    pathname.startsWith(\"//\") ||\n    pathname.includes(\";\") ||\n    pathname.includes(\"?\") ||\n    pathname.includes(\"#\")\n  ) {\n    throw new Error(\n      \"i18n.cookie.path must be a root-relative pathname without attributes, a query, or a hash.\",\n    );\n  }\n\n  for (const segment of pathname.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal and cannot conceal a separator or dot segment.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"i18n.cookie.path cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"i18n.cookie.path cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('i18n.cookie.path cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  return pathname;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { TYPE, parse, type MessageFormatElement } from \"@formatjs/icu-messageformat-parser\";\nimport { resolveFarmI18nMessagePath } from \"./config\";\nimport type { FarmI18nCatalog, FarmI18nCatalogs, ResolvedFarmI18nConfig } from \"./types\";\n\nexport type FarmI18nArgumentKind = \"string\" | \"number\" | \"date\" | \"select\" | \"rich\";\nexport type FarmI18nMessageSignature = Record<string, FarmI18nArgumentKind>;\n\nexport interface FarmI18nCatalogBundle {\n  catalogs: FarmI18nCatalogs;\n  signatures: Record<string, FarmI18nMessageSignature>;\n}\n\nexport async function readFarmI18nCatalogs(\n  config: ResolvedFarmI18nConfig,\n): Promise<FarmI18nCatalogBundle> {\n  if (!config.enabled) {\n    return { catalogs: {}, signatures: {} };\n  }\n\n  const catalogs: FarmI18nCatalogs = {};\n  for (const locale of config.locales) {\n    const filePath = resolveFarmI18nMessagePath(config, locale);\n    let source: string;\n    try {\n      source = await readFile(filePath, \"utf8\");\n    } catch (error) {\n      throw new Error(\n        `Unable to read Farm i18n catalog for \"${locale}\" at ${filePath}: ${messageOf(error)}`,\n      );\n    }\n\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(source);\n    } catch (error) {\n      throw new Error(`Invalid JSON in Farm i18n catalog ${filePath}: ${messageOf(error)}`);\n    }\n    catalogs[locale] = flattenFarmI18nCatalog(parsed, filePath);\n  }\n\n  const reference = catalogs[config.defaultLocale] || {};\n  const signatures: Record<string, FarmI18nMessageSignature> = {};\n  for (const [key, message] of Object.entries(reference)) {\n    signatures[key] = analyzeFarmI18nMessage(message, `${config.defaultLocale}:${key}`);\n  }\n\n  validateFarmI18nCatalogs(config, catalogs, signatures);\n  return { catalogs, signatures };\n}\n\nexport function flattenFarmI18nCatalog(input: unknown, source = \"i18n catalog\"): FarmI18nCatalog {\n  if (!isPlainObject(input)) {\n    throw new Error(`${source} must contain a JSON object at its root.`);\n  }\n\n  const output: FarmI18nCatalog = {};\n  const visit = (value: unknown, segments: string[]) => {\n    if (typeof value === \"string\") {\n      const key = segments.join(\".\");\n      if (!key) throw new Error(`${source} contains an empty message key.`);\n      // Own-property check: `in` would see Object.prototype members, falsely\n      // rejecting legitimate keys like \"toString\" as duplicates.\n      if (Object.prototype.hasOwnProperty.call(output, key)) {\n        throw new Error(`${source} contains duplicate message key \"${key}\".`);\n      }\n      output[key] = value;\n      return;\n    }\n\n    if (!isPlainObject(value)) {\n      const key = segments.join(\".\") || \"<root>\";\n      throw new Error(`${source} message \"${key}\" must be a string or nested object.`);\n    }\n\n    for (const [key, nested] of Object.entries(value)) {\n      if (!key.trim()) throw new Error(`${source} contains an empty message key.`);\n      visit(nested, [...segments, key]);\n    }\n  };\n\n  visit(input, []);\n  return output;\n}\n\nexport function analyzeFarmI18nMessage(\n  message: string,\n  label = \"message\",\n): FarmI18nMessageSignature {\n  let ast: MessageFormatElement[];\n  try {\n    ast = parse(message, { captureLocation: false });\n  } catch (error) {\n    throw new Error(`Invalid ICU syntax in ${label}: ${messageOf(error)}`);\n  }\n\n  const signature: FarmI18nMessageSignature = {};\n  collectArguments(ast, signature, label);\n  return signature;\n}\n\nfunction validateFarmI18nCatalogs(\n  config: ResolvedFarmI18nConfig,\n  catalogs: FarmI18nCatalogs,\n  signatures: Record<string, FarmI18nMessageSignature>,\n): void {\n  const referenceKeys = Object.keys(catalogs[config.defaultLocale] || {}).sort();\n\n  for (const locale of config.locales) {\n    const catalog = catalogs[locale] || {};\n    const localeKeys = Object.keys(catalog).sort();\n    const missing = referenceKeys.filter(\n      (key) => !Object.prototype.hasOwnProperty.call(catalog, key),\n    );\n    const extra = localeKeys.filter(\n      (key) => !Object.prototype.hasOwnProperty.call(signatures, key),\n    );\n\n    if (config.strict && (missing.length > 0 || extra.length > 0)) {\n      const details = [\n        missing.length ? `missing: ${missing.join(\", \")}` : \"\",\n        extra.length ? `extra: ${extra.join(\", \")}` : \"\",\n      ]\n        .filter(Boolean)\n        .join(\"; \");\n      throw new Error(\n        `Farm i18n catalog \"${locale}\" does not match the default catalog (${details}).`,\n      );\n    }\n\n    for (const [key, message] of Object.entries(catalog)) {\n      const actual = analyzeFarmI18nMessage(message, `${locale}:${key}`);\n      const expected = signatures[key];\n      if (!expected || sameSignature(expected, actual)) continue;\n      throw new Error(\n        `Farm i18n message \"${key}\" in \"${locale}\" uses different variables than \"${config.defaultLocale}\".`,\n      );\n    }\n  }\n}\n\nfunction collectArguments(\n  elements: MessageFormatElement[],\n  signature: FarmI18nMessageSignature,\n  label: string,\n): void {\n  for (const element of elements) {\n    switch (element.type) {\n      case TYPE.argument:\n        addArgument(signature, element.value, \"string\", label);\n        break;\n      case TYPE.number:\n      case TYPE.plural:\n        addArgument(signature, element.value, \"number\", label);\n        break;\n      case TYPE.date:\n      case TYPE.time:\n        addArgument(signature, element.value, \"date\", label);\n        break;\n      case TYPE.select:\n        addArgument(signature, element.value, \"select\", label);\n        break;\n      case TYPE.tag:\n        addArgument(signature, element.value, \"rich\", label);\n        collectArguments(element.children, signature, label);\n        break;\n    }\n\n    if (element.type === TYPE.plural || element.type === TYPE.select) {\n      for (const option of Object.values(element.options)) {\n        collectArguments(option.value, signature, label);\n      }\n    }\n  }\n}\n\nfunction addArgument(\n  signature: FarmI18nMessageSignature,\n  name: string,\n  kind: FarmI18nArgumentKind,\n  label: string,\n): void {\n  const existing = signature[name];\n  if (existing && existing !== kind) {\n    throw new Error(`Farm i18n ${label} uses variable \"${name}\" as both ${existing} and ${kind}.`);\n  }\n  signature[name] = kind;\n}\n\nfunction sameSignature(\n  expected: FarmI18nMessageSignature,\n  actual: FarmI18nMessageSignature,\n): boolean {\n  const expectedEntries = Object.entries(expected).sort(([a], [b]) => a.localeCompare(b));\n  const actualEntries = Object.entries(actual).sort(([a], [b]) => a.localeCompare(b));\n  return JSON.stringify(expectedEntries) === JSON.stringify(actualEntries);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction messageOf(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n","import { localizeFarmPathname, resolveFarmLocalePath } from \"./routing\";\nimport { stripFarmBasePath } from \"../base-path\";\nimport type { FarmI18nLocaleSource, ResolvedFarmI18nConfig } from \"./types\";\n\nexport interface FarmLocaleResolution {\n  locale: string;\n  source: FarmI18nLocaleSource;\n  pathname: string;\n  redirect?: string;\n  persist: boolean;\n}\n\nexport function getFarmLocaleVaryHeaders(\n  config: ResolvedFarmI18nConfig,\n  resolution: FarmLocaleResolution,\n): string[] {\n  if (!config.enabled || resolution.source === \"url\") return [];\n\n  const headers: string[] = [];\n  if (config.detection.includes(\"cookie\")) headers.push(\"Cookie\");\n  if (config.detection.includes(\"accept-language\")) headers.push(\"Accept-Language\");\n  return headers;\n}\n\nexport function resolveFarmLocaleRequest(\n  request: Request,\n  config: ResolvedFarmI18nConfig,\n  options: { redirect?: boolean } = {},\n): FarmLocaleResolution {\n  const url = new URL(request.url);\n  if (!config.enabled) {\n    return {\n      locale: config.defaultLocale,\n      source: \"default\",\n      pathname: url.pathname,\n      persist: false,\n    };\n  }\n\n  const pathMatch = resolveFarmLocalePath(url.pathname, config);\n  if (pathMatch.explicit && pathMatch.locale) {\n    const canonicalPath = localizeFarmPathname(pathMatch.pathname, pathMatch.locale, config);\n    const redirect =\n      options.redirect !== false && canonicalPath !== url.pathname\n        ? `${canonicalPath}${url.search}${url.hash}`\n        : undefined;\n    return {\n      locale: pathMatch.locale,\n      source: \"url\",\n      pathname: pathMatch.pathname,\n      redirect,\n      // Locale-prefixed pages are canonical and can be cached publicly. Locale\n      // switchers persist the same choice before navigating in the browser.\n      persist: false,\n    };\n  }\n\n  const detected = detectLocale(request, config);\n  const shouldRedirect =\n    options.redirect !== false &&\n    !isInternalOrApiPath(stripFarmBasePath(url.pathname, config.basePath)) &&\n    config.routing !== \"none\" &&\n    (config.routing === \"prefix-always\" || detected.locale !== config.defaultLocale);\n\n  return {\n    locale: detected.locale,\n    source: detected.source,\n    pathname: pathMatch.pathname,\n    redirect: shouldRedirect\n      ? `${localizeFarmPathname(pathMatch.pathname, detected.locale, config)}${url.search}${url.hash}`\n      : undefined,\n    persist: detected.source !== \"default\",\n  };\n}\n\nexport function createFarmLocaleCookie(\n  locale: string,\n  config: Pick<ResolvedFarmI18nConfig, \"cookie\">,\n): string {\n  const cookie = config.cookie;\n  let value = `${encodeURIComponent(cookie.name)}=${encodeURIComponent(locale)}`;\n  value += `; Max-Age=${cookie.maxAge}`;\n  value += `; Path=${cookie.path}`;\n  value += `; SameSite=${capitalize(cookie.sameSite)}`;\n  if (cookie.secure) value += \"; Secure\";\n  return value;\n}\n\nexport function matchFarmLocale(\n  requested: string | null | undefined,\n  locales: readonly string[],\n): string | undefined {\n  if (!requested) return undefined;\n  let canonical: string;\n  try {\n    canonical = Intl.getCanonicalLocales(requested)[0]!;\n  } catch {\n    return undefined;\n  }\n\n  const exact = locales.find((locale) => locale.toLowerCase() === canonical.toLowerCase());\n  if (exact) return exact;\n\n  const language = canonical.split(\"-\")[0]?.toLowerCase();\n  return locales.find((locale) => locale.split(\"-\")[0]?.toLowerCase() === language);\n}\n\nfunction detectLocale(\n  request: Request,\n  config: ResolvedFarmI18nConfig,\n): { locale: string; source: FarmI18nLocaleSource } {\n  for (const signal of config.detection) {\n    if (signal === \"url\") continue;\n\n    if (signal === \"cookie\") {\n      const locale = matchFarmLocale(\n        readCookie(request.headers.get(\"cookie\"), config.cookie.name),\n        config.locales,\n      );\n      if (locale) return { locale, source: \"cookie\" };\n    }\n\n    if (signal === \"accept-language\") {\n      const locale = resolveAcceptLanguage(request.headers.get(\"accept-language\"), config.locales);\n      if (locale) return { locale, source: \"accept-language\" };\n    }\n  }\n\n  return { locale: config.defaultLocale, source: \"default\" };\n}\n\nfunction resolveAcceptLanguage(\n  header: string | null,\n  locales: readonly string[],\n): string | undefined {\n  if (!header) return undefined;\n\n  const byRange = new Map<string, { locale: string; quality: number; index: number }>();\n  for (const [index, entry] of header.split(\",\").entries()) {\n    const [rawLocale = \"\", ...parameters] = entry.trim().split(\";\");\n    const locale = rawLocale.trim();\n    if (!locale) continue;\n\n    let quality = 1;\n    for (const parameter of parameters) {\n      const [rawName, rawValue] = parameter.trim().split(\"=\", 2);\n      if (rawName?.trim().toLowerCase() !== \"q\") continue;\n      const value = rawValue?.trim() ?? \"\";\n      quality = /^(?:0(?:\\.\\d{0,3})?|1(?:\\.0{0,3})?)$/.test(value) ? Number(value) : 0;\n    }\n\n    const key = locale.toLowerCase();\n    const previous = byRange.get(key);\n    if (!previous || quality > previous.quality) {\n      byRange.set(key, { locale, quality, index: previous?.index ?? index });\n    }\n  }\n\n  const candidates = [...byRange.values()]\n    .filter((candidate) => candidate.quality > 0)\n    .sort((a, b) => b.quality - a.quality || a.index - b.index);\n  const explicitRanges = [...byRange.values()].filter(({ locale }) => locale !== \"*\");\n\n  for (const candidate of candidates) {\n    if (candidate.locale === \"*\") {\n      const wildcardMatch = locales.find(\n        (locale) =>\n          !explicitRanges.some((range) => matchFarmLocale(range.locale, [locale]) !== undefined),\n      );\n      if (wildcardMatch) return wildcardMatch;\n      continue;\n    }\n\n    const locale = matchFarmLocale(candidate.locale, locales);\n    if (locale) return locale;\n  }\n  return undefined;\n}\n\nfunction readCookie(header: string | null, name: string): string | undefined {\n  if (!header) return undefined;\n  for (const part of header.split(\";\")) {\n    const separator = part.indexOf(\"=\");\n    if (separator < 0) continue;\n    let key: string;\n    try {\n      key = decodeURIComponent(part.slice(0, separator).trim());\n    } catch {\n      continue;\n    }\n    if (key !== name) continue;\n    try {\n      return decodeURIComponent(part.slice(separator + 1).trim());\n    } catch {\n      return part.slice(separator + 1).trim();\n    }\n  }\n  return undefined;\n}\n\nfunction isInternalOrApiPath(pathname: string): boolean {\n  return (\n    pathname === \"/api\" ||\n    pathname.startsWith(\"/api/\") ||\n    pathname.startsWith(\"/__farm/\") ||\n    pathname.startsWith(\"/_farm/\")\n  );\n}\n\nfunction capitalize(value: string): string {\n  return value.charAt(0).toUpperCase() + value.slice(1);\n}\n","import IntlMessageFormat from \"intl-messageformat\";\nimport { readFarmI18nCatalogs } from \"./catalog\";\nimport { getFarmLocaleDirection } from \"./routing\";\nimport { resolveFarmLocaleRequest, type FarmLocaleResolution } from \"./resolver\";\nimport type { FarmI18nCatalogs, FarmI18nClientSnapshot, ResolvedFarmI18nConfig } from \"./types\";\n\nexport class FarmI18nRuntime {\n  readonly config: ResolvedFarmI18nConfig;\n  private catalogs: FarmI18nCatalogs;\n  private compiled = new Map<string, IntlMessageFormat>();\n  private warnedMissing = new Set<string>();\n\n  constructor(config: ResolvedFarmI18nConfig, catalogs: FarmI18nCatalogs = {}) {\n    this.config = config;\n    this.catalogs = catalogs;\n  }\n\n  async initialize(): Promise<void> {\n    if (!this.config.enabled) return;\n    const bundle = await readFarmI18nCatalogs(this.config);\n    this.replaceCatalogs(bundle.catalogs);\n  }\n\n  async reload(): Promise<void> {\n    await this.initialize();\n  }\n\n  replaceCatalogs(catalogs: FarmI18nCatalogs): void {\n    this.catalogs = catalogs;\n    this.compiled.clear();\n    this.warnedMissing.clear();\n  }\n\n  getCatalogs(): FarmI18nCatalogs {\n    return Object.fromEntries(\n      Object.entries(this.catalogs).map(([locale, catalog]) => [locale, { ...catalog }]),\n    );\n  }\n\n  resolveRequest(request: Request, options: { redirect?: boolean } = {}): FarmLocaleResolution {\n    return resolveFarmLocaleRequest(request, this.config, options);\n  }\n\n  translate(locale: string, key: string, values?: Record<string, unknown>): string {\n    const result = this.formatMessage(locale, key, values);\n    if (Array.isArray(result) && result.some((part) => typeof part !== \"string\")) {\n      throw new Error(`Farm i18n message \"${key}\" contains rich content. Render it with t.rich().`);\n    }\n    return Array.isArray(result) ? result.join(\"\") : String(result);\n  }\n\n  translateRich(locale: string, key: string, values?: Record<string, unknown>): unknown {\n    const result = this.formatMessage(locale, key, values);\n    return Array.isArray(result) && result.length === 1 ? result[0] : result;\n  }\n\n  getRawMessage(locale: string, key: string): string {\n    return this.resolveMessage(locale, key);\n  }\n\n  hasMessage(locale: string, key: string): boolean {\n    return this.readOwnMessage(locale, key) !== undefined;\n  }\n\n  getClientSnapshot(resolution: FarmLocaleResolution): FarmI18nClientSnapshot {\n    return {\n      locale: resolution.locale,\n      source: resolution.source,\n      locales: this.config.locales,\n      defaultLocale: this.config.defaultLocale,\n      routing: this.config.routing,\n      basePath: this.config.basePath,\n      cookie: this.config.cookie,\n      direction: getFarmLocaleDirection(resolution.locale, this.config.direction),\n      messages: {\n        ...this.catalogs[this.config.fallbackLocale],\n        ...this.catalogs[resolution.locale],\n      },\n    };\n  }\n\n  private formatMessage(locale: string, key: string, values?: Record<string, unknown>): unknown {\n    const message = this.resolveMessage(locale, key);\n    const cacheKey = `${locale}\\u0000${key}\\u0000${message}`;\n    let formatter = this.compiled.get(cacheKey);\n    if (!formatter) {\n      formatter = new IntlMessageFormat(message, locale);\n      this.compiled.set(cacheKey, formatter);\n    }\n    return formatter.format(values as any);\n  }\n\n  // Look up a message by own-property only. A key named after an\n  // Object.prototype member (toString, valueOf, constructor, ...) must resolve\n  // to a real catalog entry or undefined, never the inherited prototype value\n  // (mirrors the own-property handling added to catalog.ts in #454).\n  private readOwnMessage(locale: string, key: string): string | undefined {\n    const direct = this.catalogs[locale];\n    if (direct && Object.prototype.hasOwnProperty.call(direct, key)) return direct[key];\n    const fallback = this.catalogs[this.config.fallbackLocale];\n    if (fallback && Object.prototype.hasOwnProperty.call(fallback, key)) return fallback[key];\n    return undefined;\n  }\n\n  private resolveMessage(locale: string, key: string): string {\n    const message = this.readOwnMessage(locale, key);\n    if (message !== undefined) return message;\n    if (this.config.strict) {\n      throw new Error(`Missing Farm i18n message \"${key}\" for locale \"${locale}\".`);\n    }\n    const warningKey = `${locale}:${key}`;\n    if (!this.warnedMissing.has(warningKey)) {\n      this.warnedMissing.add(warningKey);\n      console.warn(`[Farm.js] Missing i18n message \"${key}\" for locale \"${locale}\".`);\n    }\n    return key;\n  }\n}\n\nexport function createFarmI18nRuntime(\n  config: ResolvedFarmI18nConfig,\n  catalogs?: FarmI18nCatalogs,\n): FarmI18nRuntime {\n  return new FarmI18nRuntime(config, catalogs);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { FarmLocaleResolution } from \"./resolver\";\nimport { _setFarmI18nSnapshotResolver } from \"./bridge\";\nimport { FarmI18nRuntime, createFarmI18nRuntime } from \"./runtime\";\nimport type {\n  FarmI18nClientSnapshot,\n  FarmI18nLocale,\n  FarmI18nLocaleSource,\n  FarmI18nMessageArgs,\n  FarmI18nMessageKey,\n  FarmTranslator,\n} from \"./types\";\n\ninterface FarmI18nRequestState {\n  runtime: FarmI18nRuntime;\n  resolution: FarmLocaleResolution;\n  snapshot: FarmI18nClientSnapshot;\n}\n\ninterface FarmListFormatOptions {\n  localeMatcher?: \"lookup\" | \"best fit\";\n  type?: \"conjunction\" | \"disjunction\" | \"unit\";\n  style?: \"long\" | \"short\" | \"narrow\";\n}\n\nconst FARM_I18N_REQUEST_STORE = Symbol.for(\"farm.i18n.requestStore\");\nconst FARM_I18N_DEFAULT_RUNTIME = Symbol.for(\"farm.i18n.defaultRuntime\");\n\ntype GlobalFarmI18nState = typeof globalThis & {\n  [FARM_I18N_REQUEST_STORE]?: AsyncLocalStorage<FarmI18nRequestState>;\n  [FARM_I18N_DEFAULT_RUNTIME]?: FarmI18nRuntime;\n};\n\nfunction getRequestStore(): AsyncLocalStorage<FarmI18nRequestState> {\n  const state = globalThis as GlobalFarmI18nState;\n  return (state[FARM_I18N_REQUEST_STORE] ??= new AsyncLocalStorage<FarmI18nRequestState>());\n}\n\nfunction getState(): FarmI18nRequestState {\n  const state = getRequestStore().getStore();\n  if (!state) {\n    throw new Error(\n      \"No Farm i18n request context is active. Use this API while rendering, inside an API route, or use createTranslator(locale).\",\n    );\n  }\n  return state;\n}\n\nexport function _setDefaultFarmI18nRuntime(runtime: FarmI18nRuntime | undefined): void {\n  (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME] = runtime;\n}\n\nexport async function _runWithFarmI18nRequest<T>(\n  runtime: FarmI18nRuntime,\n  request: Request,\n  fn: (resolution: FarmLocaleResolution) => T | Promise<T>,\n  options: { redirect?: boolean } = {},\n): Promise<T> {\n  const resolution = runtime.resolveRequest(request, options);\n  const state: FarmI18nRequestState = {\n    runtime,\n    resolution,\n    snapshot: runtime.getClientSnapshot(resolution),\n  };\n  return getRequestStore().run(state, () => fn(resolution));\n}\n\nexport async function runWithLocale<T>(\n  locale: FarmI18nLocale,\n  fn: () => T | Promise<T>,\n): Promise<T> {\n  const runtime = getDefaultRuntime();\n  assertLocale(runtime, locale);\n  const resolution: FarmLocaleResolution = {\n    locale,\n    source: \"explicit\",\n    pathname: \"/\",\n    persist: false,\n  };\n  const state: FarmI18nRequestState = {\n    runtime,\n    resolution,\n    snapshot: runtime.getClientSnapshot(resolution),\n  };\n  return getRequestStore().run(state, fn);\n}\n\nexport function getLocale(): FarmI18nLocale {\n  return getState().resolution.locale as FarmI18nLocale;\n}\n\nexport function getLocaleSource(): FarmI18nLocaleSource {\n  return getState().resolution.source;\n}\n\nexport const t = createTranslatorFromState(() => getState());\n\nexport function createTranslator(locale: FarmI18nLocale): FarmTranslator {\n  const runtime = getDefaultRuntime();\n  assertLocale(runtime, locale);\n  return createTranslatorFromState(() => ({\n    runtime,\n    resolution: {\n      locale,\n      source: \"explicit\",\n      pathname: \"/\",\n      persist: false,\n    },\n    snapshot: runtime.getClientSnapshot({\n      locale,\n      source: \"explicit\",\n      pathname: \"/\",\n      persist: false,\n    }),\n  }));\n}\n\nexport function getFarmI18nClientSnapshot(): FarmI18nClientSnapshot | undefined {\n  return getRequestStore().getStore()?.snapshot;\n}\n\nexport const format = {\n  number(value: number, options?: Intl.NumberFormatOptions): string {\n    return new Intl.NumberFormat(getLocale(), options).format(value);\n  },\n  currency(\n    value: number,\n    currency: string,\n    options: Omit<Intl.NumberFormatOptions, \"style\" | \"currency\"> = {},\n  ): string {\n    return new Intl.NumberFormat(getLocale(), {\n      ...options,\n      style: \"currency\",\n      currency,\n    }).format(value);\n  },\n  date(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n    return new Intl.DateTimeFormat(getLocale(), options).format(value);\n  },\n  relativeTime(\n    value: number,\n    unit: Intl.RelativeTimeFormatUnit,\n    options?: Intl.RelativeTimeFormatOptions,\n  ): string {\n    return new Intl.RelativeTimeFormat(getLocale(), options).format(value, unit);\n  },\n  list(values: Iterable<string>, options?: FarmListFormatOptions): string {\n    const ListFormat = (Intl as any).ListFormat;\n    return new ListFormat(getLocale(), options).format(Array.from(values));\n  },\n};\n\nfunction getDefaultRuntime(): FarmI18nRuntime {\n  const runtime = (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME];\n  if (!runtime?.config.enabled) {\n    throw new Error(\"Farm i18n is not configured for this application.\");\n  }\n  return runtime;\n}\n\nfunction assertLocale(runtime: FarmI18nRuntime, locale: string): void {\n  if (!runtime.config.locales.includes(locale)) {\n    throw new Error(`Unsupported Farm i18n locale \"${locale}\".`);\n  }\n}\n\nfunction createTranslatorFromState(resolveState: () => FarmI18nRequestState): FarmTranslator {\n  const translator = ((key: string, values?: Record<string, unknown>) => {\n    const state = resolveState();\n    return state.runtime.translate(state.resolution.locale, key, values);\n  }) as FarmTranslator;\n  translator.rich = (key: string, values?: Record<string, unknown>) => {\n    const state = resolveState();\n    return state.runtime.translateRich(state.resolution.locale, key, values);\n  };\n  translator.raw = (key: string) => {\n    const state = resolveState();\n    return state.runtime.getRawMessage(state.resolution.locale, key);\n  };\n  translator.has = (key: string) => {\n    const state = resolveState();\n    return state.runtime.hasMessage(state.resolution.locale, key);\n  };\n  return translator;\n}\n\n_setFarmI18nSnapshotResolver(() => getFarmI18nClientSnapshot());\n\nexport { FarmI18nRuntime, createFarmI18nRuntime };\nexport type { FarmI18nClientSnapshot, FarmI18nLocale, FarmI18nMessageArgs, FarmI18nMessageKey };\n","import { createHash, timingSafeEqual } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { pathToFileURL } from \"node:url\";\nimport type { Plugin, ResolvedConfig, Rollup, ViteDevServer } from \"vite\";\nimport type { FarmFontDisplay, FarmFontSource, RemoteFontSource } from \"./font\";\n\nconst FONT_IMPORTS = new Set([\"@farm.js/core\", \"@farm.js/core/font\"]);\nconst FONT_FUNCTIONS = new Set<FontLoaderKind>([\"localFont\", \"remoteFont\"]);\nconst FONT_CSS_PREFIX = \"\\0farm:font-css:\";\nconst FONT_RUNTIME_ID = \"\\0farm:font-runtime\";\nconst PUBLIC_FONT_RUNTIME_ID = \"virtual:farm-font-runtime\";\nconst PRELOAD_HEADER_MARKER = \"__FARM_FONT_PRELOAD_HEADER__\";\nconst FONT_SECTION_START = \"/* farm-fonts:start */\";\nconst FONT_SECTION_END = \"/* farm-fonts:end */\";\nconst MODULE_EXTENSION_RE = /\\.[cm]?[jt]sx?$/;\nconst FONT_EXTENSION_RE = /\\.(woff2?|ttf|otf)$/i;\nconst MAX_REMOTE_FONT_BYTES = 20 * 1024 * 1024;\nconst FONT_REGISTRIES_KEY = Symbol.for(\"farm.fontRegistries\");\nconst FONT_REMOTE_BYTES_KEY = Symbol.for(\"farm.fontRemoteBytes\");\n\ntype FontLoaderKind = \"localFont\" | \"remoteFont\";\ntype OutputAsset = Rollup.OutputAsset;\ntype OutputBundle = Rollup.OutputBundle;\n\ninterface AstNode {\n  type: string;\n  start: number;\n  end: number;\n  [key: string]: unknown;\n}\n\ninterface FontResource {\n  bytes?: Buffer;\n  extension: string;\n  format: string;\n  hash: string;\n  outputFileName?: string;\n  publicPath?: string;\n  publicUrl: string;\n}\n\ninterface NormalizedFontSource {\n  source: string;\n  weight: string;\n  style: string;\n  unicodeRange?: string;\n  resource: FontResource;\n}\n\ninterface FontDefinition {\n  id: string;\n  family: string;\n  className: string;\n  variableClassName: string;\n  variable?: string;\n  fallback: string[];\n  display: FarmFontDisplay;\n  preload: boolean;\n  preloadResources: Array<{ href: string; type: string }>;\n  weight?: number | string;\n  style?: string;\n  sources: NormalizedFontSource[];\n}\n\ninterface FontCall {\n  kind: FontLoaderKind;\n  binding?: string;\n  node: AstNode;\n  ancestors: readonly AstNode[];\n}\n\ninterface Replacement {\n  start: number;\n  end: number;\n  code: string;\n}\n\nexport interface TransformFarmFontCallsOptions {\n  code: string;\n  id: string;\n  root: string;\n  production: boolean;\n  parse: (code: string) => AstNode;\n  register: (\n    moduleId: string,\n    calls: Array<{ kind: FontLoaderKind; options: Record<string, unknown> }>,\n  ) => Promise<FontDefinition[]>;\n}\n\nexport interface TransformFarmFontCallsResult {\n  code: string;\n  fonts: FontDefinition[];\n}\n\nconst registries = getGlobalMap<string, FarmFontRegistry>(FONT_REGISTRIES_KEY);\nconst remoteBytes = getGlobalMap<string, Promise<Buffer>>(FONT_REMOTE_BYTES_KEY);\n\nexport function farmFontImportsPlugin(\n  options: { root?: string; basePath?: string; publicDir?: string | false } = {},\n): Plugin {\n  let root = normalizeRoot(options.root || process.cwd());\n  let production = process.env.NODE_ENV === \"production\";\n  let registry = getOrCreateRegistry(root, options.basePath, options.publicDir);\n\n  const updateRoot = (nextRoot: string, basePath?: string, publicDir?: string | false) => {\n    const normalized = normalizeRoot(nextRoot);\n    root = normalized;\n    registry = getOrCreateRegistry(root, basePath, publicDir);\n  };\n\n  return {\n    name: \"farm:font-imports\",\n    enforce: \"post\",\n\n    configResolved(config: ResolvedConfig) {\n      production = config.command === \"build\";\n      updateRoot(\n        config.root,\n        options.basePath || config.base,\n        options.publicDir === undefined ? config.publicDir : options.publicDir,\n      );\n      registry.production = production;\n    },\n\n    configureServer(server: ViteDevServer) {\n      updateRoot(\n        server.config.root,\n        options.basePath || server.config.base,\n        options.publicDir === undefined ? server.config.publicDir : options.publicDir,\n      );\n      registry.production = false;\n      server.middlewares.use(async (req, res, next) => {\n        const pathname = new URL(req.url || \"/\", \"http://farm.local\").pathname;\n\n        if (pathname === \"/@farm/fonts.css\") {\n          res.statusCode = 200;\n          res.setHeader(\"Content-Type\", \"text/css; charset=utf-8\");\n          res.setHeader(\"Cache-Control\", \"no-store\");\n          res.end(registry.renderCss(false));\n          return;\n        }\n\n        const resource = registry.getDevResource(pathname);\n        if (!resource?.bytes) {\n          next();\n          return;\n        }\n\n        res.statusCode = 200;\n        res.setHeader(\"Content-Type\", fontContentType(resource.extension));\n        res.setHeader(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n        res.end(resource.bytes);\n      });\n    },\n\n    resolveId(id) {\n      if (id === PUBLIC_FONT_RUNTIME_ID || id === FONT_RUNTIME_ID) return FONT_RUNTIME_ID;\n      if (id.startsWith(\"virtual:farm-font-css/\")) {\n        return `${FONT_CSS_PREFIX}${id.slice(\"virtual:farm-font-css/\".length)}`;\n      }\n      if (id.startsWith(FONT_CSS_PREFIX)) return id;\n      return null;\n    },\n\n    load(id) {\n      if (id === FONT_RUNTIME_ID) {\n        return `export const farmFontPreloadHeader = decodeURIComponent(${JSON.stringify(PRELOAD_HEADER_MARKER)});`;\n      }\n      if (!id.startsWith(FONT_CSS_PREFIX)) return null;\n      return registry.renderFontCss(\n        id.slice(FONT_CSS_PREFIX.length).replace(/\\.css$/, \"\"),\n        production,\n      );\n    },\n\n    async transform(code, id) {\n      const result = await transformFarmFontCalls({\n        code,\n        id,\n        root,\n        production,\n        parse: (source) => this.parse(source) as unknown as AstNode,\n        register: (moduleId, calls) => registry.register(moduleId, calls, production),\n      });\n\n      if (!result) registry.clearModule(id.split(\"?\", 1)[0]);\n\n      return result ? { code: result.code, map: null } : null;\n    },\n\n    async generateBundle(_options, bundle) {\n      registry.emitAssets(this, bundle);\n    },\n  };\n}\n\nexport async function transformFarmFontCalls(\n  options: TransformFarmFontCallsOptions,\n): Promise<TransformFarmFontCallsResult | null> {\n  const cleanId = options.id.split(\"?\", 1)[0];\n  if (\n    !MODULE_EXTENSION_RE.test(cleanId) ||\n    /\\.d\\.[cm]?ts$/.test(cleanId) ||\n    !containsFontFunction(options.code)\n  ) {\n    return null;\n  }\n\n  const ast = options.parse(options.code);\n  const bindings = findFontBindings(ast);\n  if (bindings.named.size === 0 && bindings.namespaces.size === 0) return null;\n\n  const calls = findFontCalls(ast, bindings);\n  if (calls.length === 0) return null;\n  validateFontBindingReferences(ast, calls, cleanId);\n\n  const registeredCalls = calls.map((call) => ({\n    kind: call.kind,\n    options: readFontOptions(options.code, cleanId, call),\n  }));\n  const fonts = await options.register(cleanId, registeredCalls);\n  const replacements: Replacement[] = calls.map((call, index) => ({\n    start: call.node.start,\n    end: call.node.end,\n    code: serializeFontResult(fonts[index]),\n  }));\n  replacements.push(\n    ...createFontImportReplacements(\n      options.code,\n      ast,\n      new Set(calls.map((call) => call.binding).filter((value): value is string => Boolean(value))),\n    ),\n  );\n  const imports = options.production\n    ? \"\"\n    : Array.from(new Set(fonts.map((font) => font.id)))\n        .map((id) => `import ${JSON.stringify(`virtual:farm-font-css/${id}.css`)};`)\n        .join(\"\\n\");\n\n  return {\n    code: `${applyReplacements(options.code, replacements)}\\n${imports}\\n`,\n    fonts,\n  };\n}\n\nexport function renderFarmFontDevHead(root: string): string {\n  const registry = registries.get(normalizeRoot(root));\n  if (!registry || registry.production || registry.size === 0) return \"\";\n  return `${registry.renderPreloadTags(false)}\\n  <link rel=\"stylesheet\" href=\"/@farm/fonts.css\">`;\n}\n\nclass FarmFontRegistry {\n  root: string;\n  basePath: string;\n  publicDir: string | false;\n  production = false;\n  private modules = new Map<string, FontDefinition[]>();\n  private definitions = new Map<string, FontDefinition>();\n  private resources = new Map<string, FontResource>();\n\n  constructor(root: string, basePath = \"/\", publicDir?: string | false) {\n    this.root = root;\n    this.basePath = normalizeBasePath(basePath);\n    this.publicDir = normalizePublicDir(root, publicDir);\n  }\n\n  get size(): number {\n    return this.getDefinitions().length;\n  }\n\n  async register(\n    moduleId: string,\n    calls: Array<{ kind: FontLoaderKind; options: Record<string, unknown> }>,\n    production: boolean,\n  ): Promise<FontDefinition[]> {\n    const definitions: FontDefinition[] = [];\n    for (const call of calls) {\n      definitions.push(await this.createDefinition(moduleId, call.kind, call.options, production));\n    }\n    this.modules.set(moduleId, definitions);\n    for (const definition of definitions) this.definitions.set(definition.id, definition);\n    return definitions;\n  }\n\n  clearModule(moduleId: string): void {\n    this.modules.delete(moduleId);\n  }\n\n  renderFontCss(id: string, production: boolean): string {\n    const definition = this.definitions.get(id);\n    return definition ? renderFontDefinitionCss(definition, production, this.basePath) : \"\";\n  }\n\n  renderCss(production: boolean): string {\n    const css = this.getDefinitions()\n      .map((definition) => renderFontDefinitionCss(definition, production, this.basePath))\n      .join(\"\\n\\n\");\n    return css ? `${FONT_SECTION_START}\\n${css}\\n${FONT_SECTION_END}\\n` : \"\";\n  }\n\n  renderPreloadHeader(production: boolean): string {\n    return this.getPreloadResources(production)\n      .map(\n        ({ url, resource }) =>\n          `<${url}>; rel=preload; as=font; type=${fontContentType(resource.extension)}; crossorigin`,\n      )\n      .join(\", \");\n  }\n\n  renderPreloadTags(production: boolean): string {\n    return this.getPreloadResources(production)\n      .map(\n        ({ url, resource }) =>\n          `<link rel=\"preload\" href=\"${escapeHtmlAttribute(url)}\" as=\"font\" type=\"${fontContentType(resource.extension)}\" crossorigin>`,\n      )\n      .join(\"\\n  \");\n  }\n\n  getDevResource(pathname: string): FontResource | undefined {\n    for (const resource of this.getActiveResources()) {\n      if (resource.bytes && resourceUrl(resource, false, this.basePath) === pathname) {\n        return resource;\n      }\n    }\n    return undefined;\n  }\n\n  emitAssets(context: { emitFile: (file: any) => string }, bundle: OutputBundle): void {\n    for (const resource of this.getActiveResources()) {\n      if (!resource.bytes || !resource.outputFileName) continue;\n      if (bundle[resource.outputFileName]) continue;\n      context.emitFile({\n        type: \"asset\",\n        fileName: resource.outputFileName,\n        source: resource.bytes,\n      });\n    }\n\n    const css = this.renderCss(true);\n    if (css) {\n      const cssAssets = Object.values(bundle).filter(\n        (entry): entry is OutputAsset => entry.type === \"asset\" && entry.fileName.endsWith(\".css\"),\n      );\n      const clientCss =\n        cssAssets.find(\n          (entry): entry is OutputAsset =>\n            entry.type === \"asset\" && entry.fileName === \"farm-client.css\",\n        ) ?? (cssAssets.length === 1 ? cssAssets[0] : undefined);\n      if (clientCss) {\n        clientCss.source = replaceFontSection(assetSourceToString(clientCss.source), css);\n      } else if (!bundle[\"farm-fonts.css\"]) {\n        context.emitFile({\n          type: \"asset\",\n          fileName: \"farm-fonts.css\",\n          source: css,\n        });\n      }\n    }\n\n    const preloadHeader = encodeURIComponent(this.renderPreloadHeader(true));\n    for (const entry of Object.values(bundle)) {\n      if (entry.type === \"chunk\" && entry.code.includes(PRELOAD_HEADER_MARKER)) {\n        entry.code = entry.code.split(PRELOAD_HEADER_MARKER).join(preloadHeader);\n      }\n    }\n  }\n\n  private getDefinitions(): FontDefinition[] {\n    const active = new Map<string, FontDefinition>();\n    for (const definitions of this.modules.values()) {\n      for (const definition of definitions) active.set(definition.id, definition);\n    }\n    return Array.from(active.values()).sort((left, right) => left.id.localeCompare(right.id));\n  }\n\n  private getActiveResources(): FontResource[] {\n    const active = new Set<FontResource>();\n    for (const definition of this.getDefinitions()) {\n      for (const source of definition.sources) active.add(source.resource);\n    }\n    return Array.from(active);\n  }\n\n  private getPreloadResources(production: boolean) {\n    const seen = new Set<string>();\n    const resources: Array<{ url: string; resource: FontResource }> = [];\n    for (const definition of this.getDefinitions()) {\n      if (!definition.preload) continue;\n      for (const source of definition.sources) {\n        const url = resourceUrl(source.resource, production, this.basePath);\n        if (seen.has(url)) continue;\n        seen.add(url);\n        resources.push({ url, resource: source.resource });\n      }\n    }\n    return resources;\n  }\n\n  private async createDefinition(\n    moduleId: string,\n    kind: FontLoaderKind,\n    raw: Record<string, unknown>,\n    production: boolean,\n  ): Promise<FontDefinition> {\n    validateOptionKeys(moduleId, kind, raw);\n    const family = requireString(raw.family, moduleId, `${kind}() family`);\n    const display = (raw.display ?? \"swap\") as FarmFontDisplay;\n    if (![\"auto\", \"block\", \"swap\", \"fallback\", \"optional\"].includes(display)) {\n      throw fontError(moduleId, `invalid font-display value ${JSON.stringify(display)}`);\n    }\n    const variable = optionalString(raw.variable, moduleId, `${kind}() variable`);\n    if (variable && !/^--[A-Za-z_][\\w-]*$/.test(variable)) {\n      throw fontError(moduleId, `font variable must be a CSS custom property such as --font-sans`);\n    }\n    const fallback = readStringArray(raw.fallback, moduleId, `${kind}() fallback`);\n    const defaultWeight = optionalWeight(raw.weight, moduleId);\n    const defaultStyle = optionalCssDescriptor(raw.style, moduleId, \"style\") || \"normal\";\n    const sources = readSources(raw.src, moduleId, kind, defaultWeight, defaultStyle);\n    const strategy = kind === \"remoteFont\" ? (raw.strategy ?? \"self-host\") : \"self-host\";\n    if (strategy !== \"self-host\" && strategy !== \"external\") {\n      throw fontError(moduleId, `remoteFont() strategy must be \"self-host\" or \"external\"`);\n    }\n    const integrity = optionalString(raw.integrity, moduleId, `${kind}() integrity`);\n\n    const normalizedSources: NormalizedFontSource[] = [];\n    for (const source of sources) {\n      const resource = await this.resolveResource({\n        kind,\n        moduleId,\n        source: source.path,\n        strategy,\n        integrity: source.integrity ?? integrity,\n        production,\n      });\n      normalizedSources.push({\n        source: source.path,\n        weight: String(source.weight ?? defaultWeight ?? \"400\"),\n        style: source.style || defaultStyle,\n        unicodeRange: source.unicodeRange,\n        resource,\n      });\n    }\n\n    const identity = JSON.stringify({\n      family,\n      display,\n      variable,\n      fallback,\n      preload: raw.preload !== false,\n      sources: normalizedSources.map((source) => ({\n        hash: source.resource.hash,\n        url: source.resource.publicUrl,\n        weight: source.weight,\n        style: source.style,\n        unicodeRange: source.unicodeRange,\n      })),\n    });\n    const id = createHash(\"sha256\").update(identity).digest(\"hex\").slice(0, 10);\n\n    return {\n      id,\n      family,\n      className: `farm-font-${id}`,\n      variableClassName: variable ? `farm-font-variable-${id}` : \"\",\n      variable,\n      fallback,\n      display,\n      preload: raw.preload !== false,\n      preloadResources:\n        raw.preload === false\n          ? []\n          : normalizedSources.map(({ resource }) => ({\n              href: resourceUrl(resource, production, this.basePath),\n              type: fontContentType(resource.extension),\n            })),\n      weight: defaultWeight,\n      style: raw.style === undefined ? undefined : defaultStyle,\n      sources: normalizedSources,\n    };\n  }\n\n  private async resolveResource(input: {\n    kind: FontLoaderKind;\n    moduleId: string;\n    source: string;\n    strategy: unknown;\n    integrity?: string;\n    production: boolean;\n  }): Promise<FontResource> {\n    if (input.kind === \"remoteFont\") {\n      let url: URL;\n      try {\n        url = new URL(input.source);\n      } catch {\n        throw fontError(input.moduleId, `remoteFont() source must be an absolute HTTPS URL`);\n      }\n      if (url.protocol !== \"https:\") {\n        throw fontError(input.moduleId, `remoteFont() only accepts HTTPS URLs`);\n      }\n      const extension = extensionFromPath(url.pathname);\n      if (input.strategy === \"external\") {\n        const hash = createHash(\"sha256\").update(url.href).digest(\"hex\").slice(0, 12);\n        const resource = {\n          extension,\n          format: fontFormat(extension),\n          hash,\n          publicUrl: url.href,\n        };\n        this.resources.set(`external:${url.href}`, resource);\n        return resource;\n      }\n\n      const bytes = await fetchRemoteFont(url, input.integrity);\n      return this.createSelfHostedResource(bytes, extension, path.basename(url.pathname));\n    }\n\n    if (input.source.startsWith(\"/\")) {\n      return this.createPublicResource(input.moduleId, input.source);\n    }\n\n    const resolvedPath = resolveLocalFontPath(input.source, input.moduleId, this.root);\n    if (!FONT_EXTENSION_RE.test(resolvedPath)) {\n      throw fontError(\n        input.moduleId,\n        `unsupported local font file ${JSON.stringify(input.source)}`,\n      );\n    }\n    let bytes: Buffer;\n    try {\n      bytes = await readFile(resolvedPath);\n    } catch (error) {\n      throw fontError(\n        input.moduleId,\n        `could not read ${JSON.stringify(input.source)}: ${(error as Error).message}`,\n      );\n    }\n    return this.createSelfHostedResource(\n      bytes,\n      path.extname(resolvedPath),\n      path.basename(resolvedPath),\n    );\n  }\n\n  private async createPublicResource(moduleId: string, source: string): Promise<FontResource> {\n    if (!this.publicDir) {\n      throw fontError(\n        moduleId,\n        `cannot resolve ${JSON.stringify(source)} because publicDir is disabled`,\n      );\n    }\n    const publicPath = normalizePublicFontPath(source, moduleId);\n    const resolvedPath = path.resolve(this.publicDir, `.${publicPath}`);\n    if (!isPathInside(this.publicDir, resolvedPath)) {\n      throw fontError(moduleId, `public font path must stay inside publicDir`);\n    }\n    if (!FONT_EXTENSION_RE.test(resolvedPath)) {\n      throw fontError(moduleId, `unsupported public font file ${JSON.stringify(source)}`);\n    }\n\n    let bytes: Buffer;\n    try {\n      bytes = await readFile(resolvedPath);\n    } catch (error) {\n      throw fontError(\n        moduleId,\n        `could not read ${JSON.stringify(source)} from publicDir: ${(error as Error).message}`,\n      );\n    }\n\n    const extension = path.extname(resolvedPath).toLowerCase();\n    const hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 12);\n    const resource: FontResource = {\n      extension,\n      format: fontFormat(extension),\n      hash,\n      publicPath,\n      publicUrl: \"\",\n    };\n    this.resources.set(`public:${publicPath}`, resource);\n    return resource;\n  }\n\n  private createSelfHostedResource(\n    bytes: Buffer,\n    extension: string,\n    fileName: string,\n  ): FontResource {\n    const normalizedExtension = extension.toLowerCase();\n    const hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 12);\n    const baseName = sanitizeFileName(path.basename(fileName, extension)) || \"font\";\n    const outputFileName = `assets/fonts/${baseName}-h${hash}${normalizedExtension}`;\n    const key = `${hash}${normalizedExtension}`;\n    const existing = this.resources.get(key);\n    if (existing) return existing;\n\n    const resource: FontResource = {\n      bytes,\n      extension: normalizedExtension,\n      format: fontFormat(normalizedExtension),\n      hash,\n      outputFileName,\n      publicUrl: \"\",\n    };\n    this.resources.set(key, resource);\n    return resource;\n  }\n}\n\nfunction findFontBindings(ast: AstNode) {\n  const named = new Map<string, FontLoaderKind>();\n  const namespaces = new Set<string>();\n  const body = Array.isArray(ast.body) ? ast.body : [];\n\n  for (const statement of body) {\n    if (!isAstNode(statement) || statement.type !== \"ImportDeclaration\") continue;\n    const source = isAstNode(statement.source) ? statement.source.value : undefined;\n    if (typeof source !== \"string\" || !FONT_IMPORTS.has(source)) continue;\n\n    const specifiers = Array.isArray(statement.specifiers) ? statement.specifiers : [];\n    for (const specifier of specifiers) {\n      if (!isAstNode(specifier) || !isAstNode(specifier.local)) continue;\n      const localName = specifier.local.name;\n      if (typeof localName !== \"string\") continue;\n      if (specifier.type === \"ImportNamespaceSpecifier\") {\n        namespaces.add(localName);\n        continue;\n      }\n      if (specifier.type !== \"ImportSpecifier\" || !isAstNode(specifier.imported)) continue;\n      const importedName = specifier.imported.name ?? specifier.imported.value;\n      if (isFontLoaderKind(importedName)) named.set(localName, importedName);\n    }\n  }\n  return { named, namespaces };\n}\n\nfunction findFontCalls(ast: AstNode, bindings: ReturnType<typeof findFontBindings>): FontCall[] {\n  const calls: FontCall[] = [];\n  walkAst(ast, (node, ancestors) => {\n    if (node.type !== \"CallExpression\" || !isAstNode(node.callee)) return;\n    let kind: FontLoaderKind | undefined;\n    if (node.callee.type === \"Identifier\" && typeof node.callee.name === \"string\") {\n      kind = bindings.named.get(node.callee.name);\n      if (kind) calls.push({ kind, binding: node.callee.name, node, ancestors });\n    } else if (\n      node.callee.type === \"MemberExpression\" &&\n      node.callee.computed !== true &&\n      isAstNode(node.callee.object) &&\n      isAstNode(node.callee.property) &&\n      node.callee.object.type === \"Identifier\" &&\n      node.callee.property.type === \"Identifier\" &&\n      typeof node.callee.object.name === \"string\" &&\n      typeof node.callee.property.name === \"string\" &&\n      bindings.namespaces.has(node.callee.object.name) &&\n      isFontLoaderKind(node.callee.property.name)\n    ) {\n      kind = node.callee.property.name;\n    }\n    if (kind && node.callee.type !== \"Identifier\") calls.push({ kind, node, ancestors });\n  });\n  return calls;\n}\n\nfunction validateFontBindingReferences(ast: AstNode, calls: FontCall[], id: string): void {\n  const calledBindings = new Set(\n    calls.map((call) => call.binding).filter((binding): binding is string => Boolean(binding)),\n  );\n  const transformedCallees = new Set(\n    calls.flatMap((call) => {\n      const callee = call.node.callee;\n      return call.binding && isAstNode(callee) ? [`${callee.start}:${callee.end}`] : [];\n    }),\n  );\n\n  walkAst(ast, (node, ancestors) => {\n    if (\n      node.type !== \"Identifier\" ||\n      typeof node.name !== \"string\" ||\n      !calledBindings.has(node.name)\n    ) {\n      return;\n    }\n    const parent = ancestors.at(-1);\n    if (!parent || isNonReferenceIdentifier(node, parent)) return;\n    if (transformedCallees.has(`${node.start}:${node.end}`)) return;\n    throw fontError(\n      id,\n      `${node.name} can only be referenced by statically compiled font declarations`,\n    );\n  });\n}\n\nfunction isNonReferenceIdentifier(node: AstNode, parent: AstNode): boolean {\n  if (parent.type === \"ImportSpecifier\") return true;\n  if (\n    (parent.type === \"MemberExpression\" || parent.type === \"OptionalMemberExpression\") &&\n    parent.property === node &&\n    parent.computed !== true\n  ) {\n    return true;\n  }\n  if (\n    (parent.type === \"Property\" || parent.type === \"PropertyDefinition\") &&\n    parent.key === node &&\n    parent.computed !== true &&\n    parent.shorthand !== true\n  ) {\n    return true;\n  }\n  return false;\n}\n\nfunction createFontImportReplacements(\n  code: string,\n  ast: AstNode,\n  calledBindings: ReadonlySet<string>,\n): Replacement[] {\n  if (calledBindings.size === 0) return [];\n  const replacements: Replacement[] = [];\n  const body = Array.isArray(ast.body) ? ast.body : [];\n\n  for (const statement of body) {\n    if (!isAstNode(statement) || statement.type !== \"ImportDeclaration\") continue;\n    const source = isAstNode(statement.source) ? statement.source.value : undefined;\n    if (typeof source !== \"string\" || !FONT_IMPORTS.has(source)) continue;\n    const specifiers = (Array.isArray(statement.specifiers) ? statement.specifiers : []).filter(\n      isAstNode,\n    );\n    const retained = specifiers.filter((specifier) => {\n      if (specifier.type !== \"ImportSpecifier\" || !isAstNode(specifier.local)) return true;\n      return typeof specifier.local.name !== \"string\" || !calledBindings.has(specifier.local.name);\n    });\n    if (retained.length === specifiers.length) continue;\n\n    replacements.push({\n      start: statement.start,\n      end: statement.end,\n      code: renderImportDeclaration(code, source, retained),\n    });\n  }\n\n  return replacements;\n}\n\nfunction renderImportDeclaration(code: string, source: string, specifiers: AstNode[]): string {\n  if (specifiers.length === 0) return \"\";\n  const defaultSpecifier = specifiers.find(\n    (specifier) => specifier.type === \"ImportDefaultSpecifier\",\n  );\n  const namespaceSpecifier = specifiers.find(\n    (specifier) => specifier.type === \"ImportNamespaceSpecifier\",\n  );\n  const namedSpecifiers = specifiers.filter((specifier) => specifier.type === \"ImportSpecifier\");\n  const parts: string[] = [];\n\n  if (defaultSpecifier && isAstNode(defaultSpecifier.local)) {\n    parts.push(code.slice(defaultSpecifier.local.start, defaultSpecifier.local.end));\n  }\n  if (namespaceSpecifier && isAstNode(namespaceSpecifier.local)) {\n    parts.push(`* as ${code.slice(namespaceSpecifier.local.start, namespaceSpecifier.local.end)}`);\n  }\n  if (namedSpecifiers.length > 0) {\n    parts.push(\n      `{ ${namedSpecifiers.map((specifier) => code.slice(specifier.start, specifier.end)).join(\", \")} }`,\n    );\n  }\n\n  return parts.length > 0 ? `import ${parts.join(\", \")} from ${JSON.stringify(source)};` : \"\";\n}\n\nfunction readFontOptions(code: string, id: string, call: FontCall): Record<string, unknown> {\n  if (!call.binding) {\n    throw fontError(id, `${call.kind}() must use a named import from @farm.js/core/font`);\n  }\n  const args = Array.isArray(call.node.arguments) ? call.node.arguments : [];\n  if (args.length !== 1 || !isAstNode(args[0]) || args[0].type !== \"ObjectExpression\") {\n    throw fontError(id, `${call.kind}() requires one inline options object`);\n  }\n  const parent = call.ancestors.at(-1);\n  if (!parent || parent.type !== \"VariableDeclarator\" || parent.init !== call.node) {\n    throw fontError(id, `${call.kind}() must initialize a module-scope variable`);\n  }\n  const declaration = call.ancestors.at(-2);\n  const statement = call.ancestors.at(-3);\n  const statementParent = call.ancestors.at(-4);\n  const isModuleScope =\n    declaration?.type === \"VariableDeclaration\" &&\n    (statement?.type === \"Program\" ||\n      (statement?.type === \"ExportNamedDeclaration\" && statementParent?.type === \"Program\"));\n  if (!isModuleScope || call.ancestors.some((ancestor) => isFunctionNode(ancestor))) {\n    throw fontError(id, `${call.kind}() must be declared directly at module scope`);\n  }\n  return evaluateStaticObject(code, id, args[0]);\n}\n\nfunction evaluateStaticObject(code: string, id: string, node: AstNode): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  const properties = Array.isArray(node.properties) ? node.properties : [];\n  for (const property of properties) {\n    if (!isAstNode(property) || property.type !== \"Property\" || property.computed === true) {\n      throw fontError(id, \"font options do not support spreads or computed properties\");\n    }\n    const key = readPropertyName(property.key);\n    if (!key || !isAstNode(property.value)) {\n      throw fontError(id, \"font options must use static property names and values\");\n    }\n    result[key] = evaluateStaticValue(code, id, property.value);\n  }\n  return result;\n}\n\nfunction evaluateStaticValue(code: string, id: string, node: AstNode): unknown {\n  if (node.type === \"Literal\") return node.value;\n  if (node.type === \"TemplateLiteral\") {\n    const expressions = Array.isArray(node.expressions) ? node.expressions : [];\n    const quasis = Array.isArray(node.quasis) ? node.quasis : [];\n    if (expressions.length === 0 && quasis.length === 1 && isAstNode(quasis[0])) {\n      const templateValue = quasis[0].value;\n      const value =\n        templateValue && typeof templateValue === \"object\"\n          ? (templateValue as { cooked?: unknown }).cooked\n          : undefined;\n      if (typeof value === \"string\") return value;\n    }\n  }\n  if (node.type === \"ArrayExpression\") {\n    const elements = Array.isArray(node.elements) ? node.elements : [];\n    return elements.map((element) => {\n      if (!isAstNode(element) || element.type === \"SpreadElement\") {\n        throw fontError(id, \"font option arrays must contain static values\");\n      }\n      return evaluateStaticValue(code, id, element);\n    });\n  }\n  if (node.type === \"ObjectExpression\") return evaluateStaticObject(code, id, node);\n  if (\n    node.type === \"UnaryExpression\" &&\n    (node.operator === \"+\" || node.operator === \"-\") &&\n    isAstNode(node.argument)\n  ) {\n    const value = evaluateStaticValue(code, id, node.argument);\n    if (typeof value === \"number\") return node.operator === \"-\" ? -value : value;\n  }\n  throw fontError(\n    id,\n    `font options must be statically analyzable near ${code.slice(node.start, node.end)}`,\n  );\n}\n\nfunction readSources(\n  value: unknown,\n  id: string,\n  kind: FontLoaderKind,\n  weight: number | string | undefined,\n  style: string,\n): Array<FarmFontSource & Pick<RemoteFontSource, \"integrity\">> {\n  if (typeof value === \"string\") return [{ path: value, weight, style }];\n  if (!Array.isArray(value) || value.length === 0) {\n    throw fontError(id, `${kind}() src must be a string or a non-empty source array`);\n  }\n  return value.map((entry, index) => {\n    if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n      throw fontError(id, `${kind}() src[${index}] must be an object`);\n    }\n    const source = entry as Record<string, unknown>;\n    const unknown = Object.keys(source).filter(\n      (key) =>\n        ![\n          \"path\",\n          \"weight\",\n          \"style\",\n          \"unicodeRange\",\n          ...(kind === \"remoteFont\" ? [\"integrity\"] : []),\n        ].includes(key),\n    );\n    if (unknown.length) throw fontError(id, `unknown src[${index}] option ${unknown[0]}`);\n    return {\n      path: requireString(source.path, id, `${kind}() src[${index}].path`),\n      weight: optionalWeight(source.weight, id) ?? weight,\n      style: optionalCssDescriptor(source.style, id, \"style\") || style,\n      unicodeRange: optionalUnicodeRange(source.unicodeRange, id),\n      integrity: optionalString(source.integrity, id, `${kind}() src[${index}].integrity`),\n    };\n  });\n}\n\nfunction validateOptionKeys(id: string, kind: FontLoaderKind, raw: Record<string, unknown>) {\n  const allowed = new Set([\n    \"src\",\n    \"family\",\n    \"weight\",\n    \"style\",\n    \"display\",\n    \"variable\",\n    \"fallback\",\n    \"preload\",\n    ...(kind === \"remoteFont\" ? [\"strategy\", \"integrity\"] : []),\n  ]);\n  const unknown = Object.keys(raw).find((key) => !allowed.has(key));\n  if (unknown) throw fontError(id, `unknown ${kind}() option ${JSON.stringify(unknown)}`);\n  if (typeof raw.preload !== \"undefined\" && typeof raw.preload !== \"boolean\") {\n    throw fontError(id, `${kind}() preload must be a boolean`);\n  }\n}\n\nfunction serializeFontResult(font: FontDefinition): string {\n  const stack = renderFamilyStack(font.family, font.fallback);\n  return JSON.stringify({\n    className: font.className,\n    variable: font.variableClassName,\n    style: {\n      fontFamily: stack,\n      ...(font.style ? { fontStyle: font.style } : {}),\n      ...(font.weight !== undefined && !String(font.weight).includes(\" \")\n        ? { fontWeight: font.weight }\n        : {}),\n    },\n    preloads: font.preloadResources,\n  });\n}\n\nfunction renderFontDefinitionCss(\n  font: FontDefinition,\n  production: boolean,\n  basePath: string,\n): string {\n  const faces = font.sources.map((source) => {\n    const descriptors = [\n      `  font-family: ${quoteCssString(font.family)};`,\n      `  src: url(${quoteCssString(resourceUrl(source.resource, production, basePath))}) format(${quoteCssString(source.resource.format)});`,\n      `  font-display: ${font.display};`,\n      `  font-weight: ${source.weight};`,\n      `  font-style: ${source.style};`,\n      ...(source.unicodeRange ? [`  unicode-range: ${source.unicodeRange};`] : []),\n    ];\n    return `@font-face {\\n${descriptors.join(\"\\n\")}\\n}`;\n  });\n  const stack = renderFamilyStack(font.family, font.fallback);\n  faces.push(`.${font.className} {\\n  font-family: ${stack};\\n}`);\n  if (font.variable && font.variableClassName) {\n    faces.push(`.${font.variableClassName} {\\n  ${font.variable}: ${stack};\\n}`);\n  }\n  return faces.join(\"\\n\\n\");\n}\n\nfunction resourceUrl(resource: FontResource, production: boolean, basePath: string): string {\n  // Production font URLs are root-relative: emitted assets land in the client\n  // output, which the server publishes at \"/\" regardless of basePath — the\n  // same convention as the hashed client JS/CSS hrefs. Only the dev server\n  // mounts under basePath (the Vite base), so only dev URLs carry the prefix.\n  if (resource.publicPath) {\n    return resource.publicPath;\n  }\n  if (!resource.bytes) return resource.publicUrl;\n  if (!production) {\n    return joinBasePath(basePath, `/@farm/font/${resource.hash}${resource.extension}`);\n  }\n  return `/${resource.outputFileName}`;\n}\n\nasync function fetchRemoteFont(url: URL, integrity?: string): Promise<Buffer> {\n  const key = `${url.href}\\0${integrity || \"\"}`;\n  let pending = remoteBytes.get(key);\n  if (!pending) {\n    pending = (async () => {\n      const response = await fetch(url, {\n        headers: { \"User-Agent\": \"Farm.js font compiler\" },\n        redirect: \"follow\",\n      });\n      if (!response.ok)\n        throw new Error(`request returned ${response.status} ${response.statusText}`);\n      const length = Number(response.headers.get(\"content-length\") || 0);\n      if (length > MAX_REMOTE_FONT_BYTES) throw new Error(\"font exceeds the 20 MB limit\");\n      const bytes = await readResponseBodyWithLimit(response, MAX_REMOTE_FONT_BYTES);\n      if (integrity) verifyIntegrity(bytes, integrity);\n      return bytes;\n    })().catch((error) => {\n      throw new Error(`[Farm fonts] Failed to download ${url.href}: ${(error as Error).message}`);\n    });\n    remoteBytes.set(key, pending);\n    const clearPending = () => {\n      if (remoteBytes.get(key) === pending) remoteBytes.delete(key);\n    };\n    void pending.then(clearPending, clearPending);\n  }\n  return pending;\n}\n\nasync function readResponseBodyWithLimit(response: Response, limit: number): Promise<Buffer> {\n  if (!response.body) return Buffer.alloc(0);\n  const reader = response.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n\n  while (true) {\n    const chunk = await reader.read();\n    if (chunk.done) break;\n    total += chunk.value.byteLength;\n    if (total > limit) {\n      await reader.cancel(\"font exceeds the configured byte limit\");\n      throw new Error(\"font exceeds the 20 MB limit\");\n    }\n    chunks.push(chunk.value);\n  }\n\n  return Buffer.concat(chunks, total);\n}\n\nfunction verifyIntegrity(bytes: Buffer, integrity: string): void {\n  const entries = integrity.trim().split(/\\s+/);\n  const supported = entries\n    .map((entry) => entry.match(/^(sha(?:256|384|512))-(.+)$/))\n    .filter((entry): entry is RegExpMatchArray => Boolean(entry));\n  if (supported.length === 0) throw new Error(\"integrity must use sha256, sha384, or sha512\");\n  const matches = supported.some((entry) => {\n    const actual = createHash(entry[1]).update(bytes).digest();\n    const expected = Buffer.from(entry[2], \"base64\");\n    return actual.length === expected.length && timingSafeEqual(actual, expected);\n  });\n  if (!matches) throw new Error(\"downloaded font did not match its integrity value\");\n}\n\nfunction resolveLocalFontPath(source: string, importer: string, root: string): string {\n  if (source.startsWith(\".\")) return path.resolve(path.dirname(importer), source);\n  if (path.isAbsolute(source)) {\n    return source;\n  }\n  try {\n    return createRequire(pathToFileURL(importer)).resolve(source);\n  } catch {\n    const segments = source.replace(/\\\\/g, \"/\").split(\"/\");\n    if (segments.includes(\"..\")) return path.resolve(root, source);\n\n    let current = path.dirname(importer);\n    const filesystemRoot = path.parse(current).root;\n    while (true) {\n      const candidate = path.join(current, \"node_modules\", ...segments);\n      if (existsSync(candidate)) return candidate;\n      if (current === filesystemRoot) break;\n      current = path.dirname(current);\n    }\n    return path.resolve(root, \"node_modules\", ...segments);\n  }\n}\n\nfunction replaceFontSection(css: string, section: string): string {\n  const start = css.indexOf(FONT_SECTION_START);\n  const end = css.indexOf(FONT_SECTION_END);\n  const withoutExisting =\n    start >= 0 && end >= start\n      ? `${css.slice(0, start)}${css.slice(end + FONT_SECTION_END.length)}`.trimEnd()\n      : css.trimEnd();\n  return `${withoutExisting}${withoutExisting ? \"\\n\\n\" : \"\"}${section}`;\n}\n\nexport function mergeFarmFontCss(clientCss: string, fontCss: string): string {\n  return replaceFontSection(clientCss, fontCss);\n}\n\nfunction getOrCreateRegistry(\n  root: string,\n  basePath = \"/\",\n  publicDir?: string | false,\n): FarmFontRegistry {\n  const normalized = normalizeRoot(root);\n  const existing = registries.get(normalized);\n  if (existing) {\n    existing.basePath = normalizeBasePath(basePath);\n    existing.publicDir = normalizePublicDir(normalized, publicDir);\n    return existing;\n  }\n  const registry = new FarmFontRegistry(normalized, basePath, publicDir);\n  registries.set(normalized, registry);\n  return registry;\n}\n\nfunction getGlobalMap<TKey, TValue>(key: symbol): Map<TKey, TValue> {\n  const runtime = globalThis as typeof globalThis & Record<symbol, unknown>;\n  const existing = runtime[key];\n  if (existing instanceof Map) return existing as Map<TKey, TValue>;\n  const created = new Map<TKey, TValue>();\n  runtime[key] = created;\n  return created;\n}\n\nfunction normalizeRoot(root: string): string {\n  return path.resolve(root).replace(/\\\\/g, \"/\");\n}\n\nfunction normalizePublicDir(root: string, publicDir?: string | false): string | false {\n  if (publicDir === false || publicDir === \"\") return false;\n  return path.resolve(root, publicDir || \"public\");\n}\n\nfunction normalizePublicFontPath(source: string, moduleId: string): string {\n  if (source.includes(\"?\") || source.includes(\"#\")) {\n    throw fontError(moduleId, `public font paths cannot contain a query string or fragment`);\n  }\n  return `/${source.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\")}`;\n}\n\nfunction isPathInside(parent: string, child: string): boolean {\n  const relative = path.relative(parent, child);\n  return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction normalizeBasePath(value: string): string {\n  if (!value || value === \"/\") return \"/\";\n  return `/${value.replace(/^\\/+|\\/+$/g, \"\")}/`;\n}\n\nfunction joinBasePath(basePath: string, value: string): string {\n  return basePath === \"/\" ? value : `${basePath.replace(/\\/$/, \"\")}${value}`;\n}\n\nfunction extensionFromPath(pathname: string): string {\n  const extension = path.extname(pathname).toLowerCase();\n  if (!FONT_EXTENSION_RE.test(extension)) {\n    throw new Error(`[Farm fonts] Remote font URL must end in .woff2, .woff, .ttf, or .otf`);\n  }\n  return extension;\n}\n\nfunction fontFormat(extension: string): string {\n  switch (extension.toLowerCase()) {\n    case \".woff2\":\n      return \"woff2\";\n    case \".woff\":\n      return \"woff\";\n    case \".ttf\":\n      return \"truetype\";\n    case \".otf\":\n      return \"opentype\";\n    default:\n      throw new Error(`[Farm fonts] Unsupported font extension ${extension}`);\n  }\n}\n\nfunction fontContentType(extension: string): string {\n  switch (extension.toLowerCase()) {\n    case \".woff2\":\n      return \"font/woff2\";\n    case \".woff\":\n      return \"font/woff\";\n    case \".ttf\":\n      return \"font/ttf\";\n    case \".otf\":\n      return \"font/otf\";\n    default:\n      return \"application/octet-stream\";\n  }\n}\n\nfunction renderFamilyStack(family: string, fallback: string[]): string {\n  return [quoteCssString(family), ...fallback.map(formatFallbackFamily)].join(\", \");\n}\n\nfunction formatFallbackFamily(value: string): string {\n  return /^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-serif|ui-sans-serif|ui-monospace|emoji|math|fangsong)$/.test(\n    value,\n  )\n    ? value\n    : quoteCssString(value);\n}\n\nfunction quoteCssString(value: string): string {\n  return JSON.stringify(value.replace(/[\\n\\r\\f]/g, \" \"));\n}\n\nfunction sanitizeFileName(value: string): string {\n  return value\n    .replace(/[^A-Za-z0-9_-]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\")\n    .slice(0, 80);\n}\n\nfunction assetSourceToString(source: string | Uint8Array): string {\n  return typeof source === \"string\" ? source : Buffer.from(source).toString(\"utf8\");\n}\n\nfunction applyReplacements(code: string, replacements: Replacement[]): string {\n  let output = code;\n  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n    output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n  }\n  return output;\n}\n\nfunction walkAst(\n  node: AstNode,\n  visit: (node: AstNode, ancestors: readonly AstNode[]) => void,\n  ancestors: readonly AstNode[] = [],\n): void {\n  visit(node, ancestors);\n  const childAncestors = [...ancestors, node];\n  for (const [key, value] of Object.entries(node)) {\n    if ([\"start\", \"end\", \"loc\", \"range\"].includes(key)) continue;\n    if (isAstNode(value)) walkAst(value, visit, childAncestors);\n    else if (Array.isArray(value)) {\n      for (const item of value) if (isAstNode(item)) walkAst(item, visit, childAncestors);\n    }\n  }\n}\n\nfunction readPropertyName(value: unknown): string | undefined {\n  if (!isAstNode(value)) return undefined;\n  if (value.type === \"Identifier\" && typeof value.name === \"string\") return value.name;\n  if (value.type === \"Literal\" && typeof value.value === \"string\") return value.value;\n  return undefined;\n}\n\nfunction isAstNode(value: unknown): value is AstNode {\n  return (\n    Boolean(value) &&\n    typeof value === \"object\" &&\n    typeof (value as AstNode).type === \"string\" &&\n    typeof (value as AstNode).start === \"number\" &&\n    typeof (value as AstNode).end === \"number\"\n  );\n}\n\nfunction isFunctionNode(node: AstNode): boolean {\n  return (\n    node.type === \"FunctionDeclaration\" ||\n    node.type === \"FunctionExpression\" ||\n    node.type === \"ArrowFunctionExpression\"\n  );\n}\n\nfunction isFontLoaderKind(value: unknown): value is FontLoaderKind {\n  return typeof value === \"string\" && FONT_FUNCTIONS.has(value as FontLoaderKind);\n}\n\nfunction containsFontFunction(code: string): boolean {\n  return Array.from(FONT_FUNCTIONS).some((name) => code.includes(name));\n}\n\nfunction requireString(value: unknown, id: string, label: string): string {\n  if (typeof value !== \"string\" || value.trim() === \"\") {\n    throw fontError(id, `${label} must be a non-empty string`);\n  }\n  return value;\n}\n\nfunction optionalString(value: unknown, id: string, label: string): string | undefined {\n  if (value === undefined) return undefined;\n  return requireString(value, id, label);\n}\n\nfunction readStringArray(value: unknown, id: string, label: string): string[] {\n  if (value === undefined) return [];\n  if (!Array.isArray(value) || value.some((entry) => typeof entry !== \"string\")) {\n    throw fontError(id, `${label} must be an array of family names`);\n  }\n  return value as string[];\n}\n\nfunction optionalWeight(value: unknown, id: string): number | string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value === \"number\" && Number.isInteger(value) && value >= 1 && value <= 1000) {\n    return value;\n  }\n  if (\n    typeof value === \"string\" &&\n    /^(?:[1-9]\\d{0,2}|1000)(?:\\s+(?:[1-9]\\d{0,2}|1000))?$/.test(value)\n  ) {\n    const bounds = value.split(/\\s+/).map(Number);\n    if (bounds.length === 2 && bounds[0] > bounds[1]) {\n      throw fontError(id, `font weight range must be ordered from lowest to highest`);\n    }\n    return value;\n  }\n  throw fontError(id, `font weight must be a number or range such as \"100 900\"`);\n}\n\nfunction optionalCssDescriptor(value: unknown, id: string, label: string): string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value !== \"string\" || !/^[A-Za-z0-9 .-]+$/.test(value)) {\n    throw fontError(id, `font ${label} contains unsupported characters`);\n  }\n  return value;\n}\n\nfunction optionalUnicodeRange(value: unknown, id: string): string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value !== \"string\" || !/^[Uu+0-9A-Fa-f?*, -]+$/.test(value)) {\n    throw fontError(id, `font unicodeRange contains unsupported characters`);\n  }\n  return value;\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n  return value.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\");\n}\n\nfunction fontError(id: string, message: string): Error {\n  return new Error(`[Farm fonts] ${message} in ${id.split(\"?\", 1)[0]}`);\n}\n","/** @internal */\nexport function omitFarmResponseBody(response: Response): Response {\n  if (response.body) {\n    void response.body.cancel().catch(() => undefined);\n  }\n\n  return new Response(null, {\n    status: response.status,\n    statusText: response.statusText,\n    headers: response.headers,\n  });\n}\n","import type { ImageResponseOptions } from \"@vercel/og\";\nimport type { ReactElement } from \"react\";\nimport { omitFarmResponseBody } from \"./response-body\";\nimport { matchesFarmIfNoneMatch } from \"./server-http\";\n\nconst REACT_ELEMENT_TYPE = Symbol.for(\"react.element\");\nconst REACT_TRANSITIONAL_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\");\nconst REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\");\nconst REACT_MEMO_TYPE = Symbol.for(\"react.memo\");\nconst REACT_LAZY_TYPE = Symbol.for(\"react.lazy\");\n\ntype MetadataImageSize = {\n  width?: number;\n  height?: number;\n};\n\ntype MetadataImageFont = Omit<NonNullable<ImageResponseOptions[\"fonts\"]>[number], \"data\"> & {\n  data: ArrayBuffer | ArrayBufferView | Promise<ArrayBuffer | ArrayBufferView>;\n};\n\nexport type FarmMetadataImageModule = {\n  size?: MetadataImageSize;\n  contentType?: string;\n  revalidate?: number | false;\n  fonts?: MetadataImageFont[];\n  emoji?: ImageResponseOptions[\"emoji\"];\n  debug?: boolean;\n};\n\nexport type FarmMetadataImageResponseOptions = {\n  method?: string;\n  ifNoneMatch?: string | null;\n};\n\nfunction isResponse(value: unknown): value is Response {\n  return (\n    typeof Response !== \"undefined\" &&\n    (value instanceof Response ||\n      Boolean(\n        value &&\n        typeof value === \"object\" &&\n        typeof (value as Response).arrayBuffer === \"function\" &&\n        (value as Response).headers,\n      ))\n  );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n  return Boolean(\n    value &&\n    (typeof value === \"object\" || typeof value === \"function\") &&\n    typeof (value as PromiseLike<unknown>).then === \"function\",\n  );\n}\n\nfunction isReactElement(value: unknown): value is ReactElement<Record<string, unknown>> {\n  if (!value || typeof value !== \"object\") return false;\n  const marker = (value as { $$typeof?: symbol }).$$typeof;\n  return marker === REACT_ELEMENT_TYPE || marker === REACT_TRANSITIONAL_ELEMENT_TYPE;\n}\n\nasync function prepareMetadataImageNode(node: unknown): Promise<unknown> {\n  if (isThenable(node)) {\n    return prepareMetadataImageNode(await node);\n  }\n\n  if (Array.isArray(node)) {\n    return Promise.all(node.map((child) => prepareMetadataImageNode(child)));\n  }\n\n  if (!isReactElement(node)) {\n    return node;\n  }\n\n  const element = node;\n  const type = element.type as any;\n  const props = element.props || {};\n\n  if (typeof type === \"function\") {\n    if (type.prototype?.isReactComponent) {\n      throw new Error(\n        \"Metadata image components must be stateless function components; React class components are not supported.\",\n      );\n    }\n    return prepareMetadataImageNode(await type(props));\n  }\n\n  if (type && typeof type === \"object\") {\n    if (type.$$typeof === REACT_MEMO_TYPE) {\n      const { createElement } = await import(\"react\");\n      return prepareMetadataImageNode(createElement(type.type, props));\n    }\n    if (type.$$typeof === REACT_FORWARD_REF_TYPE) {\n      return prepareMetadataImageNode(await type.render(props, null));\n    }\n    if (type.$$typeof === REACT_LAZY_TYPE) {\n      const { createElement } = await import(\"react\");\n      return prepareMetadataImageNode(createElement(type._init(type._payload), props));\n    }\n  }\n\n  const preparedChildren = await prepareMetadataImageNode(props.children);\n  const preparedProps: Record<string, unknown> = { ...props };\n\n  if (typeof preparedProps.className === \"string\") {\n    preparedProps.tw = [preparedProps.tw, preparedProps.className].filter(Boolean).join(\" \");\n    delete preparedProps.className;\n  }\n  delete preparedProps.children;\n\n  const { createElement } = await import(\"react\");\n  return createElement(type, {\n    ...preparedProps,\n    key: element.key,\n    children: preparedChildren,\n  });\n}\n\nasync function normalizeFonts(\n  fonts: MetadataImageFont[] | undefined,\n): Promise<ImageResponseOptions[\"fonts\"] | undefined> {\n  if (!fonts?.length) return undefined;\n\n  return Promise.all(\n    fonts.map(async (font) => {\n      const data = await font.data;\n      const arrayBuffer = ArrayBuffer.isView(data) ? toArrayBuffer(data) : data;\n      return { ...font, data: arrayBuffer } as NonNullable<ImageResponseOptions[\"fonts\"]>[number];\n    }),\n  );\n}\n\nfunction resolveCacheControl(revalidate: number | false | undefined): string {\n  if (revalidate === false) {\n    return \"public, max-age=31536000, immutable\";\n  }\n  if (typeof revalidate === \"number\" && Number.isFinite(revalidate) && revalidate > 0) {\n    return `public, s-maxage=${Math.floor(revalidate)}, stale-while-revalidate=300`;\n  }\n  return \"public, max-age=0, must-revalidate\";\n}\n\nfunction toArrayBuffer(value: ArrayBuffer | ArrayBufferView): ArrayBuffer {\n  if (value instanceof ArrayBuffer) return value;\n  const bytes = new Uint8Array(value.byteLength);\n  bytes.set(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));\n  return bytes.buffer;\n}\n\nasync function createEntityTag(body: ArrayBuffer): Promise<string> {\n  const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", body);\n  const hash = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\"))\n    .join(\"\")\n    .slice(0, 32);\n  return `\"${hash}\"`;\n}\n\nasync function finalizeMetadataImageResponse(\n  body: ArrayBuffer,\n  headers: HeadersInit,\n  options: FarmMetadataImageResponseOptions,\n): Promise<Response> {\n  const responseHeaders = new Headers(headers);\n  const etag = await createEntityTag(body);\n  responseHeaders.set(\"ETag\", etag);\n  responseHeaders.set(\"Content-Length\", String(body.byteLength));\n  responseHeaders.set(\"X-Content-Type-Options\", \"nosniff\");\n\n  if (matchesFarmIfNoneMatch(options.ifNoneMatch, etag)) {\n    return new Response(null, { status: 304, headers: responseHeaders });\n  }\n\n  return new Response(options.method?.toUpperCase() === \"HEAD\" ? null : body, {\n    status: 200,\n    headers: responseHeaders,\n  });\n}\n\n/** @internal */\nexport async function createFarmMetadataImageResponse(\n  value: unknown,\n  imageModule: FarmMetadataImageModule,\n  options: FarmMetadataImageResponseOptions = {},\n): Promise<Response> {\n  const method = (options.method || \"GET\").toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    return new Response(null, { status: 405, headers: { Allow: \"GET, HEAD\" } });\n  }\n\n  if (isResponse(value)) {\n    return method === \"HEAD\" ? omitFarmResponseBody(value) : value;\n  }\n\n  const cacheControl = resolveCacheControl(imageModule.revalidate);\n  const explicitContentType = imageModule.contentType?.split(\";\", 1)[0]?.trim().toLowerCase();\n\n  if (isReactElement(value) && explicitContentType !== \"image/svg+xml\") {\n    const { ImageResponse } = await import(\"@vercel/og\");\n    const element = (await prepareMetadataImageNode(value)) as ReactElement;\n    const response = new ImageResponse(element, {\n      width: imageModule.size?.width || 1200,\n      height: imageModule.size?.height || 630,\n      fonts: await normalizeFonts(imageModule.fonts),\n      emoji: imageModule.emoji,\n      debug: imageModule.debug,\n      headers: { \"cache-control\": cacheControl },\n    });\n    const headers = new Headers(response.headers);\n    headers.set(\"Cache-Control\", cacheControl);\n    return finalizeMetadataImageResponse(await response.arrayBuffer(), headers, options);\n  }\n\n  let body: ArrayBuffer;\n  if (typeof value === \"string\") {\n    body = toArrayBuffer(new TextEncoder().encode(value));\n  } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n    body = toArrayBuffer(value);\n  } else if (isReactElement(value)) {\n    const { renderToStaticMarkup } = await import(\"react-dom/server\");\n    body = toArrayBuffer(new TextEncoder().encode(renderToStaticMarkup(value)));\n  } else {\n    throw new Error(\"Metadata image must return a Response, string, bytes, or React element\");\n  }\n\n  return finalizeMetadataImageResponse(\n    body,\n    {\n      \"Content-Type\": imageModule.contentType || \"image/svg+xml; charset=utf-8\",\n      \"Cache-Control\": cacheControl,\n    },\n    options,\n  );\n}\n","import { omitFarmResponseBody } from \"./response-body\";\n\nexport type ApplicationMetadataRouteKind = \"sitemap\" | \"robots\" | \"manifest\";\n\nexport namespace MetadataRoute {\n  export type SitemapChangeFrequency =\n    | \"always\"\n    | \"hourly\"\n    | \"daily\"\n    | \"weekly\"\n    | \"monthly\"\n    | \"yearly\"\n    | \"never\";\n\n  export interface SitemapEntry {\n    url: string;\n    lastModified?: string | Date;\n    changeFrequency?: SitemapChangeFrequency;\n    priority?: number;\n    alternates?: {\n      languages?: Record<string, string>;\n    };\n  }\n\n  export type Sitemap = SitemapEntry[];\n\n  export interface RobotsRule {\n    userAgent: string | string[];\n    allow?: string | string[];\n    disallow?: string | string[];\n    crawlDelay?: number;\n  }\n\n  export interface Robots {\n    rules: RobotsRule | RobotsRule[];\n    sitemap?: string | string[];\n    host?: string;\n  }\n\n  export interface ManifestIcon {\n    src: string;\n    sizes?: string;\n    type?: string;\n    purpose?: string;\n  }\n\n  export interface Manifest {\n    name?: string;\n    short_name?: string;\n    description?: string;\n    id?: string;\n    start_url?: string;\n    scope?: string;\n    display?: \"fullscreen\" | \"standalone\" | \"minimal-ui\" | \"browser\" | string;\n    orientation?: string;\n    background_color?: string;\n    theme_color?: string;\n    lang?: string;\n    dir?: \"ltr\" | \"rtl\" | \"auto\";\n    categories?: string[];\n    icons?: ManifestIcon[];\n    [key: string]: unknown;\n  }\n}\n\nexport interface MetadataRouteContext {\n  request: Request;\n  params: Record<string, string>;\n  searchParams: URLSearchParams;\n  /** The concrete route-segment path that owns the metadata file. */\n  path: string;\n}\n\nexport interface FarmMetadataRouteModule {\n  revalidate?: number | false;\n}\n\nexport interface FarmMetadataRouteResponseOptions {\n  method?: string;\n}\n\nfunction isResponse(value: unknown): value is Response {\n  return (\n    typeof Response !== \"undefined\" &&\n    (value instanceof Response ||\n      Boolean(\n        value &&\n        typeof value === \"object\" &&\n        typeof (value as Response).arrayBuffer === \"function\" &&\n        (value as Response).headers,\n      ))\n  );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction resolveCacheControl(revalidate: number | false | undefined): string {\n  if (revalidate === false) {\n    return \"public, max-age=31536000, immutable\";\n  }\n  if (typeof revalidate === \"number\" && Number.isFinite(revalidate) && revalidate > 0) {\n    return `public, s-maxage=${Math.floor(revalidate)}, stale-while-revalidate=300`;\n  }\n  return \"public, max-age=0, must-revalidate\";\n}\n\nfunction escapeXml(value: unknown): string {\n  return String(value)\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&apos;\");\n}\n\nfunction serializeSitemap(value: unknown): string {\n  if (!Array.isArray(value)) {\n    throw new TypeError(\"sitemap.ts must return an array or a Response\");\n  }\n\n  const entries = value.map((candidate, index) => {\n    if (!isRecord(candidate) || typeof candidate.url !== \"string\" || !candidate.url) {\n      throw new TypeError(`sitemap.ts entry ${index} must include a non-empty url`);\n    }\n    return candidate as unknown as MetadataRoute.SitemapEntry;\n  });\n  const hasLanguageAlternates = entries.some(\n    (entry) => entry.alternates?.languages && Object.keys(entry.alternates.languages).length > 0,\n  );\n  const namespace = hasLanguageAlternates ? ' xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"' : \"\";\n  const lines = [\n    '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n    `<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"${namespace}>`,\n  ];\n\n  for (const entry of entries) {\n    lines.push(\"  <url>\", `    <loc>${escapeXml(entry.url)}</loc>`);\n    if (entry.lastModified !== undefined) {\n      const lastModified =\n        entry.lastModified instanceof Date ? entry.lastModified.toISOString() : entry.lastModified;\n      lines.push(`    <lastmod>${escapeXml(lastModified)}</lastmod>`);\n    }\n    if (entry.changeFrequency) {\n      lines.push(`    <changefreq>${escapeXml(entry.changeFrequency)}</changefreq>`);\n    }\n    if (entry.priority !== undefined) {\n      lines.push(`    <priority>${escapeXml(entry.priority)}</priority>`);\n    }\n    for (const [language, href] of Object.entries(entry.alternates?.languages || {})) {\n      lines.push(\n        `    <xhtml:link rel=\"alternate\" hreflang=\"${escapeXml(language)}\" href=\"${escapeXml(href)}\" />`,\n      );\n    }\n    lines.push(\"  </url>\");\n  }\n\n  lines.push(\"</urlset>\");\n  return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction toArray<T>(value: T | T[] | undefined): T[] {\n  return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n\nfunction serializeRobots(value: unknown): string {\n  if (!isRecord(value)) {\n    throw new TypeError(\"robots.ts must return a robots object or a Response\");\n  }\n\n  const robots = value as unknown as MetadataRoute.Robots;\n  const rules = toArray(robots.rules);\n  if (rules.length === 0) {\n    throw new TypeError(\"robots.ts must return at least one rule\");\n  }\n\n  const sections = rules.map((rule, index) => {\n    if (!isRecord(rule)) {\n      throw new TypeError(`robots.ts rule ${index} must be an object`);\n    }\n    const userAgents = toArray(rule.userAgent).filter(\n      (userAgent): userAgent is string => typeof userAgent === \"string\" && Boolean(userAgent),\n    );\n    if (userAgents.length === 0) {\n      throw new TypeError(`robots.ts rule ${index} must include a userAgent`);\n    }\n\n    const lines = userAgents.map((userAgent) => `User-agent: ${userAgent}`);\n    for (const allow of toArray(rule.allow)) lines.push(`Allow: ${allow}`);\n    for (const disallow of toArray(rule.disallow)) lines.push(`Disallow: ${disallow}`);\n    if (rule.crawlDelay !== undefined) lines.push(`Crawl-delay: ${rule.crawlDelay}`);\n    return lines.join(\"\\n\");\n  });\n\n  const globalLines = [\n    ...toArray(robots.sitemap).map((sitemap) => `Sitemap: ${sitemap}`),\n    ...(robots.host ? [`Host: ${robots.host}`] : []),\n  ];\n  return `${[...sections, ...(globalLines.length ? [globalLines.join(\"\\n\")] : [])].join(\"\\n\\n\")}\\n`;\n}\n\nfunction serializeManifest(value: unknown): string {\n  if (!isRecord(value)) {\n    throw new TypeError(\"manifest.ts must return a manifest object or a Response\");\n  }\n  return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\n/** @internal */\nexport function createFarmMetadataRouteResponse(\n  kind: ApplicationMetadataRouteKind,\n  value: unknown,\n  routeModule: FarmMetadataRouteModule = {},\n  options: FarmMetadataRouteResponseOptions = {},\n): Response {\n  const method = (options.method || \"GET\").toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    return new Response(null, { status: 405, headers: { Allow: \"GET, HEAD\" } });\n  }\n\n  if (isResponse(value)) {\n    return method === \"HEAD\" ? omitFarmResponseBody(value) : value;\n  }\n\n  const body =\n    kind === \"sitemap\"\n      ? serializeSitemap(value)\n      : kind === \"robots\"\n        ? serializeRobots(value)\n        : serializeManifest(value);\n  const contentType =\n    kind === \"sitemap\"\n      ? \"application/xml; charset=utf-8\"\n      : kind === \"robots\"\n        ? \"text/plain; charset=utf-8\"\n        : \"application/manifest+json; charset=utf-8\";\n\n  return new Response(method === \"HEAD\" ? null : body, {\n    headers: {\n      \"Content-Type\": contentType,\n      \"Cache-Control\": resolveCacheControl(routeModule.revalidate),\n      \"X-Content-Type-Options\": \"nosniff\",\n    },\n  });\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","export const DEFAULT_NOT_FOUND_STYLES = `\nbody {\n  margin: 0;\n}\n\n.farm-default-not-found {\n  --farm-not-found-bg: #fafafa;\n  --farm-not-found-fg: #171717;\n  --farm-not-found-muted: #737373;\n  --farm-not-found-line: rgba(0, 0, 0, 0.16);\n  --farm-not-found-button-fg: #ffffff;\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  place-items: center;\n  padding: 24px;\n  color: var(--farm-not-found-fg);\n  background: var(--farm-not-found-bg);\n  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  color-scheme: light;\n}\n\n.farm-default-not-found,\n.farm-default-not-found * {\n  box-sizing: border-box;\n}\n\n.farm-default-not-found__content {\n  width: min(100%, 280px);\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n}\n\n.farm-default-not-found__code {\n  margin: 0;\n  color: var(--farm-not-found-fg);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: clamp(88px, 20vw, 140px);\n  font-weight: 800;\n  line-height: 0.75;\n  letter-spacing: -0.1em;\n  transform: translateX(-3px);\n}\n\n@supports (-webkit-text-stroke: 1px currentColor) {\n  .farm-default-not-found__code {\n    color: var(--farm-not-found-bg);\n    -webkit-text-stroke: 2px var(--farm-not-found-fg);\n    text-shadow: 5px 5px 0 var(--farm-not-found-fg);\n  }\n}\n\n.farm-default-not-found__description {\n  width: 100%;\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  margin: 34px 0 30px;\n  color: var(--farm-not-found-muted);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: 10px;\n  line-height: 1;\n  letter-spacing: 0.14em;\n  text-transform: uppercase;\n  white-space: nowrap;\n}\n\n.farm-default-not-found__description::before,\n.farm-default-not-found__description::after {\n  content: \"\";\n  height: 1px;\n  flex: 1 1 auto;\n  background: var(--farm-not-found-line);\n}\n\n.farm-default-not-found__home {\n  min-width: 132px;\n  min-height: 44px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 20px;\n  border: 1px solid var(--farm-not-found-fg);\n  border-radius: 0;\n  color: var(--farm-not-found-button-fg);\n  background: var(--farm-not-found-fg);\n  font-size: 14px;\n  font-weight: 500;\n  line-height: 1;\n  text-decoration: none;\n  transition: opacity 150ms ease-out, transform 100ms ease-out;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  .farm-default-not-found__home:hover {\n    opacity: 0.78;\n  }\n}\n\n.farm-default-not-found__home:active {\n  transform: translateY(1px);\n}\n\n.farm-default-not-found__home:focus-visible {\n  outline: 2px solid var(--farm-not-found-fg);\n  outline-offset: 3px;\n}\n\n@media (prefers-color-scheme: dark) {\n  .farm-default-not-found {\n    --farm-not-found-bg: #0a0a0a;\n    --farm-not-found-fg: #ededed;\n    --farm-not-found-muted: #a1a1a1;\n    --farm-not-found-line: rgba(255, 255, 255, 0.2);\n    --farm-not-found-button-fg: #0a0a0a;\n    color-scheme: dark;\n  }\n}\n\n.dark .farm-default-not-found,\n[data-theme=\"dark\"] .farm-default-not-found,\n[data-color-scheme=\"dark\"] .farm-default-not-found {\n  --farm-not-found-bg: #0a0a0a;\n  --farm-not-found-fg: #ededed;\n  --farm-not-found-muted: #a1a1a1;\n  --farm-not-found-line: rgba(255, 255, 255, 0.2);\n  --farm-not-found-button-fg: #0a0a0a;\n  color-scheme: dark;\n}\n\n.light .farm-default-not-found,\n[data-theme=\"light\"] .farm-default-not-found,\n[data-color-scheme=\"light\"] .farm-default-not-found {\n  --farm-not-found-bg: #fafafa;\n  --farm-not-found-fg: #171717;\n  --farm-not-found-muted: #737373;\n  --farm-not-found-line: rgba(0, 0, 0, 0.16);\n  --farm-not-found-button-fg: #ffffff;\n  color-scheme: light;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .farm-default-not-found__home {\n    transition: none;\n  }\n\n  .farm-default-not-found__home:active {\n    transform: none;\n  }\n}\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}\n\n.farm-default-error {\n  --farm-error-bg: #fafafa;\n  --farm-error-fg: #171717;\n  --farm-error-muted: #737373;\n  --farm-error-line: rgba(0, 0, 0, 0.1);\n  --farm-error-line-strong: rgba(0, 0, 0, 0.22);\n  --farm-error-panel: rgba(0, 0, 0, 0.018);\n  --farm-error-button-fg: #ffffff;\n  --farm-error-source-line: rgba(185, 28, 28, 0.08);\n  --farm-error-source-marker: #b91c1c;\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  place-items: center;\n  padding: clamp(28px, 6vw, 72px) 24px;\n  color: var(--farm-error-fg);\n  background: var(--farm-error-bg);\n  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  color-scheme: light;\n}\n\n.farm-default-error,\n.farm-default-error * {\n  box-sizing: border-box;\n}\n\n.farm-default-error__content {\n  width: min(100%, 840px);\n  display: flex;\n  flex-direction: column;\n  align-items: stretch;\n}\n\n.farm-default-error__code {\n  margin: 0;\n  color: var(--farm-error-fg);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: clamp(76px, 13vw, 112px);\n  font-weight: 800;\n  line-height: 0.78;\n  letter-spacing: -0.08em;\n  text-align: center;\n  transform: translateX(-3px);\n}\n\n@supports (-webkit-text-stroke: 1px currentColor) {\n  .farm-default-error__code {\n    color: var(--farm-error-bg);\n    -webkit-text-stroke: 1.5px var(--farm-error-fg);\n    text-shadow: 2px 2px 0 var(--farm-error-fg);\n  }\n}\n\n.farm-default-error__eyebrow {\n  width: min(100%, 590px);\n  display: flex;\n  align-items: center;\n  align-self: center;\n  gap: 16px;\n  margin: 34px 0 28px;\n  color: var(--farm-error-fg);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: 11px;\n  font-weight: 600;\n  line-height: 1;\n  letter-spacing: 0.16em;\n  text-transform: uppercase;\n  white-space: nowrap;\n}\n\n.farm-default-error__eyebrow::before,\n.farm-default-error__eyebrow::after {\n  content: \"\";\n  height: 1px;\n  flex: 1 1 auto;\n  background: var(--farm-error-line-strong);\n}\n\n.farm-default-error__summary {\n  margin-bottom: 28px;\n  text-align: center;\n}\n\n.farm-default-error__title {\n  margin: 0;\n  font-size: clamp(20px, 3vw, 26px);\n  font-weight: 540;\n  line-height: 1.25;\n  letter-spacing: -0.02em;\n}\n\n.farm-default-error__message {\n  max-width: 680px;\n  margin: 8px auto 0;\n  color: var(--farm-error-muted);\n  font-size: 15px;\n  line-height: 1.55;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__panel {\n  border: 1px solid var(--farm-error-line-strong);\n  background: var(--farm-error-panel);\n}\n\n.farm-default-error__row {\n  min-height: 58px;\n  display: grid;\n  grid-template-columns: minmax(124px, 180px) minmax(0, 1fr);\n  align-items: center;\n  border-bottom: 1px solid var(--farm-error-line);\n}\n\n.farm-default-error__row:last-child {\n  border-bottom: 0;\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  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n}\n\n.farm-default-error__label {\n  padding: 0 22px;\n  color: var(--farm-error-muted);\n  font-size: 11px;\n  font-weight: 600;\n  letter-spacing: 0.12em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__value {\n  min-width: 0;\n  padding: 15px 22px;\n  color: var(--farm-error-fg);\n  font-size: 14px;\n  line-height: 1.45;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__details {\n  padding: 20px 22px 18px;\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: 10px;\n}\n\n.farm-default-error__details-title {\n  margin: 0;\n  font-size: 11px;\n  font-weight: 600;\n  letter-spacing: 0.12em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__copy {\n  min-height: 34px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 12px;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 0;\n  color: var(--farm-error-fg);\n  background: transparent;\n  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  font-size: 12px;\n  font-weight: 600;\n  line-height: 1;\n  letter-spacing: 0.01em;\n  cursor: pointer;\n  transition: border-color 150ms ease-out, background 150ms ease-out;\n}\n\n.farm-default-error__source {\n  border: 1px solid var(--farm-error-line);\n  background: var(--farm-error-bg);\n  overflow: hidden;\n}\n\n.farm-default-error__source-path {\n  margin: 0;\n  padding: 11px 14px;\n  border-bottom: 1px solid var(--farm-error-line);\n  color: var(--farm-error-fg);\n  font-size: 12px;\n  line-height: 1.4;\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: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\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-muted);\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: 15px;\n  border: 1px solid var(--farm-error-line);\n  color: var(--farm-error-muted);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: 12px;\n  line-height: 1.5;\n}\n\n.farm-default-error__meta {\n  margin: 14px 0 0;\n  color: var(--farm-error-muted);\n  font-size: 10px;\n  line-height: 1.5;\n  letter-spacing: 0.04em;\n  text-align: center;\n}\n\n.farm-default-error__actions {\n  display: flex;\n  justify-content: center;\n  gap: 12px;\n  margin-top: 28px;\n}\n\n.farm-default-error__action {\n  min-width: 152px;\n  min-height: 44px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 20px;\n  border: 1px solid var(--farm-error-line-strong);\n  border-radius: 0;\n  color: var(--farm-error-fg);\n  background: transparent;\n  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  font-size: 13px;\n  font-weight: 600;\n  line-height: 1;\n  letter-spacing: 0.01em;\n  text-decoration: none;\n  cursor: pointer;\n  transition: opacity 150ms ease-out, transform 100ms ease-out;\n}\n\n.farm-default-error__action--primary {\n  border-color: var(--farm-error-fg);\n  color: var(--farm-error-button-fg);\n  background: var(--farm-error-fg);\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__copy:hover {\n    border-color: var(--farm-error-line-strong);\n    background: var(--farm-error-panel);\n  }\n\n  .farm-default-error__action:hover {\n    opacity: 0.76;\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  outline: 1px solid var(--farm-error-fg);\n  outline-offset: 2px;\n}\n\n@media (max-width: 620px) {\n  .farm-default-error {\n    place-items: start center;\n    padding: 48px 16px 32px;\n  }\n\n  .farm-default-error__eyebrow {\n    margin-top: 28px;\n  }\n\n  .farm-default-error__row {\n    grid-template-columns: 1fr;\n    gap: 5px;\n    padding: 14px 16px;\n  }\n\n  .farm-default-error__label,\n  .farm-default-error__value {\n    padding: 0;\n  }\n\n  .farm-default-error__details {\n    padding: 16px;\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: 56px minmax(0, 1fr);\n  }\n\n  .farm-default-error__actions {\n    flex-direction: column;\n  }\n\n  .farm-default-error__action {\n    width: 100%;\n  }\n}\n\n@media (prefers-color-scheme: dark) {\n  .farm-default-error {\n    --farm-error-bg: #0a0a0a;\n    --farm-error-fg: #ededed;\n    --farm-error-muted: #a1a1a1;\n    --farm-error-line: rgba(255, 255, 255, 0.1);\n    --farm-error-line-strong: rgba(255, 255, 255, 0.22);\n    --farm-error-panel: rgba(255, 255, 255, 0.018);\n    --farm-error-button-fg: #0a0a0a;\n    --farm-error-source-line: rgba(248, 113, 113, 0.12);\n    --farm-error-source-marker: #f87171;\n    color-scheme: dark;\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: #0a0a0a;\n  --farm-error-fg: #ededed;\n  --farm-error-muted: #a1a1a1;\n  --farm-error-line: rgba(255, 255, 255, 0.1);\n  --farm-error-line-strong: rgba(255, 255, 255, 0.22);\n  --farm-error-panel: rgba(255, 255, 255, 0.018);\n  --farm-error-button-fg: #0a0a0a;\n  --farm-error-source-line: rgba(248, 113, 113, 0.12);\n  --farm-error-source-marker: #f87171;\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: #fafafa;\n  --farm-error-fg: #171717;\n  --farm-error-muted: #737373;\n  --farm-error-line: rgba(0, 0, 0, 0.1);\n  --farm-error-line-strong: rgba(0, 0, 0, 0.22);\n  --farm-error-panel: rgba(0, 0, 0, 0.018);\n  --farm-error-button-fg: #ffffff;\n  --farm-error-source-line: rgba(185, 28, 28, 0.08);\n  --farm-error-source-marker: #b91c1c;\n  color-scheme: light;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .farm-default-error__copy,\n  .farm-default-error__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","import { DEFAULT_ERROR_STYLES } from \"./error-styles\";\n\nexport { DEFAULT_ERROR_STYLES } from \"./error-styles\";\n\nconst ERROR_STATUS_TEXT: Record<number, string> = {\n  400: \"Bad Request\",\n  401: \"Unauthorized\",\n  402: \"Payment Required\",\n  403: \"Forbidden\",\n  404: \"Not Found\",\n  405: \"Method Not Allowed\",\n  406: \"Not Acceptable\",\n  408: \"Request Timeout\",\n  409: \"Conflict\",\n  410: \"Gone\",\n  411: \"Length Required\",\n  412: \"Precondition Failed\",\n  413: \"Content Too Large\",\n  414: \"URI Too Long\",\n  415: \"Unsupported Media Type\",\n  416: \"Range Not Satisfiable\",\n  418: \"I'm a Teapot\",\n  422: \"Unprocessable Content\",\n  423: \"Locked\",\n  424: \"Failed Dependency\",\n  425: \"Too Early\",\n  426: \"Upgrade Required\",\n  428: \"Precondition Required\",\n  429: \"Too Many Requests\",\n  431: \"Request Header Fields Too Large\",\n  451: \"Unavailable For Legal Reasons\",\n  500: \"Internal Server Error\",\n  501: \"Not Implemented\",\n  502: \"Bad Gateway\",\n  503: \"Service Unavailable\",\n  504: \"Gateway Timeout\",\n  505: \"HTTP Version Not Supported\",\n  506: \"Variant Also Negotiates\",\n  507: \"Insufficient Storage\",\n  508: \"Loop Detected\",\n  510: \"Not Extended\",\n  511: \"Network Authentication Required\",\n};\n\nconst ERROR_TITLES: Record<number, string> = {\n  400: \"The request could not be understood\",\n  401: \"Authentication is required\",\n  403: \"You do not have access to this page\",\n  404: \"The requested page could not be found\",\n  405: \"This request method is not supported\",\n  408: \"The request took too long\",\n  409: \"The request conflicts with the current state\",\n  410: \"This resource is no longer available\",\n  413: \"The request is too large\",\n  422: \"The request could not be processed\",\n  429: \"Too many requests were sent\",\n  500: \"Application failed during server rendering\",\n  501: \"This operation is not implemented\",\n  502: \"An upstream service returned an invalid response\",\n  503: \"The service is temporarily unavailable\",\n  504: \"An upstream service took too long to respond\",\n};\n\nconst ERROR_PUBLIC_MESSAGES: Record<number, string> = {\n  400: \"Check the request and try again.\",\n  401: \"Sign in and try this request again.\",\n  403: \"Use an account with the required permissions or return home.\",\n  404: \"Check the address or return to the home page.\",\n  405: \"Use a supported request method and try again.\",\n  408: \"Try the request again in a moment.\",\n  409: \"Refresh the page, review the latest state, and try again.\",\n  410: \"Return home to continue browsing.\",\n  413: \"Reduce the request size and try again.\",\n  422: \"Review the request data and try again.\",\n  429: \"Wait a moment before trying again.\",\n  500: \"An unexpected error prevented this page from rendering.\",\n  501: \"This operation is not available yet.\",\n  502: \"Try again after the upstream service recovers.\",\n  503: \"Try again in a moment.\",\n  504: \"Try again after the upstream service recovers.\",\n};\n\nexport interface DefaultErrorSourceLine {\n  number: number;\n  content: string;\n  highlight?: boolean;\n}\n\nexport interface DefaultErrorSourceFrame {\n  file: string;\n  line: number;\n  column: number;\n  lines: DefaultErrorSourceLine[];\n}\n\nexport interface DefaultErrorPageOptions {\n  statusCode?: number;\n  statusText?: string;\n  requestPath?: string;\n  method?: string;\n  message?: string;\n  errorName?: string;\n  stack?: string;\n  sourceFrame?: DefaultErrorSourceFrame;\n  development?: boolean;\n  farmVersion?: string;\n  nodeVersion?: string;\n  mode?: string;\n}\n\nfunction escapeHtml(value: unknown): string {\n  return String(value ?? \"\")\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&#39;\");\n}\n\nfunction serializeJsonForHtml(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction normalizeErrorStatus(status: unknown): number | undefined {\n  const value = typeof status === \"string\" && status.trim() ? Number(status) : status;\n  return typeof value === \"number\" && Number.isInteger(value) && value >= 400 && value <= 599\n    ? value\n    : undefined;\n}\n\nexport function resolveDefaultErrorStatus(error: unknown): number {\n  if (error && typeof error === \"object\") {\n    const candidate = error as { status?: unknown; statusCode?: unknown };\n    return (\n      normalizeErrorStatus(candidate.status) ?? normalizeErrorStatus(candidate.statusCode) ?? 500\n    );\n  }\n  return 500;\n}\n\nexport function getDefaultErrorStatusText(statusCode: number): string {\n  return ERROR_STATUS_TEXT[statusCode] || (statusCode >= 500 ? \"Server Error\" : \"Request Error\");\n}\n\nexport function getDefaultErrorTitle(statusCode: number): string {\n  return (\n    ERROR_TITLES[statusCode] ||\n    (statusCode >= 500\n      ? \"The server could not complete the request\"\n      : \"The request could not be completed\")\n  );\n}\n\nfunction getDefaultErrorPublicMessage(statusCode: number): string {\n  return ERROR_PUBLIC_MESSAGES[statusCode] || \"Try again or return to the home page.\";\n}\n\nfunction createSourceFrameMarkup(sourceFrame?: DefaultErrorSourceFrame): string {\n  if (!sourceFrame) {\n    return `<p class=\"farm-default-error__details-empty\">Source location is unavailable. Copy the debug report to inspect the filtered stack trace.</p>`;\n  }\n\n  const lines = sourceFrame.lines\n    .map(\n      (line) =>\n        `<span class=\"farm-default-error__source-line${line.highlight ? \" farm-default-error__source-line--active\" : \"\"}\"><span class=\"farm-default-error__source-gutter\">${line.highlight ? \"&gt;\" : \"&nbsp;\"} ${line.number}</span><span class=\"farm-default-error__source-text\">${escapeHtml(line.content || \" \")}</span></span>`,\n    )\n    .join(\"\\n\");\n\n  return `<div class=\"farm-default-error__source\"><p class=\"farm-default-error__source-path\">${escapeHtml(sourceFrame.file)}:${sourceFrame.line}:${sourceFrame.column}</p><pre class=\"farm-default-error__source-code\" tabindex=\"0\"><code>${lines}</code></pre></div>`;\n}\n\nfunction createDebugReport(\n  options: Required<Pick<DefaultErrorPageOptions, \"statusCode\">> & DefaultErrorPageOptions,\n): string {\n  const statusText = options.statusText || getDefaultErrorStatusText(options.statusCode);\n  const sourceFrame = options.sourceFrame;\n  const source = sourceFrame\n    ? [\n        `\\`${sourceFrame.file}:${sourceFrame.line}:${sourceFrame.column}\\``,\n        \"\",\n        \"```text\",\n        ...sourceFrame.lines.map(\n          (line) =>\n            `${line.highlight ? \">\" : \" \"} ${String(line.number).padStart(4, \" \")} | ${line.content}`,\n        ),\n        \"```\",\n      ].join(\"\\n\")\n    : \"Source frame unavailable.\";\n\n  return [\n    \"# Farm.js debug report\",\n    \"\",\n    \"## Error\",\n    `- Status: ${options.statusCode} ${statusText}`,\n    `- Name: ${options.errorName || \"Error\"}`,\n    `- Message: ${options.message || getDefaultErrorPublicMessage(options.statusCode)}`,\n    `- Request: ${(options.method || \"GET\").toUpperCase()} ${options.requestPath || \"/\"}`,\n    \"\",\n    \"## Runtime\",\n    `- Farm.js: ${options.farmVersion || \"unknown\"}`,\n    `- Node.js: ${options.nodeVersion || \"unknown\"}`,\n    `- Mode: ${options.mode || \"development\"}`,\n    \"\",\n    \"## Source\",\n    source,\n    \"\",\n    \"## Filtered stack\",\n    \"```text\",\n    options.stack || \"Stack trace unavailable.\",\n    \"```\",\n  ].join(\"\\n\");\n}\n\nconst ERROR_PAGE_SCRIPT = `<script>(function(){var root=document.querySelector(\"[data-farm-default-error]\");if(!root)return;var retry=root.querySelector(\"[data-farm-error-retry]\");if(retry)retry.addEventListener(\"click\",function(){window.location.reload()})})();</script>`;\nconst ERROR_COPY_SCRIPT = `<script>(function(){var root=document.querySelector(\"[data-farm-default-error]\");var copy=root&&root.querySelector(\"[data-farm-error-copy]\");var report=document.getElementById(\"farm-default-error-report\");if(!copy||!report)return;copy.addEventListener(\"click\",async function(){var value=\"\";try{value=JSON.parse(report.textContent||'\"\"')}catch(_error){value=report.textContent||\"\"}try{if(navigator.clipboard&&window.isSecureContext){await navigator.clipboard.writeText(value)}else{var area=document.createElement(\"textarea\");area.value=value;area.setAttribute(\"readonly\",\"\");area.style.position=\"fixed\";area.style.opacity=\"0\";document.body.appendChild(area);area.select();document.execCommand(\"copy\");area.remove()}var label=copy.querySelector(\"[data-farm-error-copy-label]\");var status=copy.querySelector(\"[data-farm-error-copy-status]\");if(label)label.textContent=\"COPIED\";if(status)status.textContent=\"Debug report copied\";window.setTimeout(function(){if(label)label.textContent=\"COPY DEBUG REPORT\";if(status)status.textContent=\"\"},1800)}catch(_error){var status=copy.querySelector(\"[data-farm-error-copy-status]\");if(status)status.textContent=\"Unable to copy the debug report\"}})})();</script>`;\n\nexport function createDefaultErrorMarkup(options: DefaultErrorPageOptions = {}): string {\n  const statusCode = normalizeErrorStatus(options.statusCode) ?? 500;\n  const statusText = options.statusText || getDefaultErrorStatusText(statusCode);\n  const development = options.development === true;\n  const title = getDefaultErrorTitle(statusCode);\n  const message =\n    development && options.message ? options.message : getDefaultErrorPublicMessage(statusCode);\n  const requestPath = options.requestPath || \"/\";\n  const method = (options.method || \"GET\").toUpperCase();\n  const eyebrow = statusCode >= 500 ? \"Runtime error\" : \"Request error\";\n  const details = development\n    ? `<section class=\"farm-default-error__details\" aria-labelledby=\"farm-default-error-details-title\"><div class=\"farm-default-error__details-header\"><h2 id=\"farm-default-error-details-title\" class=\"farm-default-error__details-title\">Details</h2><button class=\"farm-default-error__copy\" type=\"button\" data-farm-error-copy><span data-farm-error-copy-label>COPY DEBUG REPORT</span><span class=\"farm-default-error__sr-only\" aria-live=\"polite\" data-farm-error-copy-status></span></button></div>${createSourceFrameMarkup(options.sourceFrame)}<p class=\"farm-default-error__meta\">Farm.js v${escapeHtml(options.farmVersion || \"unknown\")} · ${escapeHtml(options.mode || \"development\")} · Node.js ${escapeHtml(options.nodeVersion || \"unknown\")}</p></section>`\n    : \"\";\n  const report = development\n    ? `<script id=\"farm-default-error-report\" type=\"application/json\">${serializeJsonForHtml(createDebugReport({ ...options, statusCode, statusText, requestPath, method }))}</script>${ERROR_COPY_SCRIPT}`\n    : \"\";\n\n  return `<style>${DEFAULT_ERROR_STYLES}</style><main class=\"farm-default-error\" data-farm-default-error role=\"alert\" aria-labelledby=\"farm-default-error-title\" aria-describedby=\"farm-default-error-description\"><div class=\"farm-default-error__content\"><p class=\"farm-default-error__code\" aria-hidden=\"true\">${statusCode}</p><p class=\"farm-default-error__eyebrow\">${escapeHtml(eyebrow)}</p><header class=\"farm-default-error__summary\"><h1 id=\"farm-default-error-title\" class=\"farm-default-error__title\">${escapeHtml(title)}</h1><p id=\"farm-default-error-description\" class=\"farm-default-error__message\">${escapeHtml(message)}</p></header><section class=\"farm-default-error__panel\" aria-label=\"Error information\"><div class=\"farm-default-error__row\"><span class=\"farm-default-error__label\">Request</span><span class=\"farm-default-error__value\">${escapeHtml(method)} ${escapeHtml(requestPath)}</span></div><div class=\"farm-default-error__row\"><span class=\"farm-default-error__label\">Status</span><span class=\"farm-default-error__value\">${statusCode} ${escapeHtml(statusText)}</span></div>${details}</section><div class=\"farm-default-error__actions\"><button class=\"farm-default-error__action farm-default-error__action--primary\" type=\"button\" data-farm-error-retry>TRY AGAIN</button><a class=\"farm-default-error__action\" href=\"/\">RETURN HOME</a></div></div>${report}${ERROR_PAGE_SCRIPT}</main>`;\n}\n","import type { FarmThemeConfig, ResolvedFarmThemeConfig } from \"./types\";\n\nexport const DEFAULT_FARM_THEME_STORAGE_KEY = \"farm-theme\";\n\nconst STORAGE_KEY_PATTERN = /^[A-Za-z0-9._-]+$/;\n\nexport function resolveFarmThemeConfig(\n  config: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n): ResolvedFarmThemeConfig {\n  if (config && \"enabled\" in config) {\n    return config;\n  }\n\n  if (!config) {\n    return {\n      enabled: false,\n      default: \"system\",\n      storageKey: DEFAULT_FARM_THEME_STORAGE_KEY,\n      cookiePath: normalizeCookiePath(basePath),\n    };\n  }\n\n  const storageKey = config.storageKey?.trim() || DEFAULT_FARM_THEME_STORAGE_KEY;\n  if (!STORAGE_KEY_PATTERN.test(storageKey)) {\n    throw new Error(\n      \"theme.storageKey may only contain letters, numbers, dots, underscores, and hyphens.\",\n    );\n  }\n\n  const defaultTheme = config.default ?? \"system\";\n  if (defaultTheme !== \"light\" && defaultTheme !== \"dark\" && defaultTheme !== \"system\") {\n    throw new Error('theme.default must be \"light\", \"dark\", or \"system\".');\n  }\n\n  return {\n    enabled: true,\n    default: defaultTheme,\n    storageKey,\n    cookiePath: normalizeCookiePath(basePath),\n  };\n}\n\nfunction normalizeCookiePath(basePath: string): string {\n  const normalized = `/${basePath}`.replace(/\\/{2,}/g, \"/\");\n  if (normalized === \"/\") return normalized;\n  return normalized.replace(/\\/$/, \"\");\n}\n","import { resolveFarmThemeConfig } from \"./config\";\nimport type {\n  FarmThemeConfig,\n  FarmThemePreference,\n  FarmThemeRuntime,\n  ResolvedFarmThemeConfig,\n} from \"./types\";\n\nconst THEME_SCRIPT_ID = \"farm-theme-script\";\nconst THEME_STYLE_ID = \"farm-theme-style\";\n\ndeclare global {\n  interface Window {\n    __FARM_THEME__?: FarmThemeRuntime;\n  }\n}\n\nexport interface FarmThemeDocumentParts {\n  attributes: string;\n  head: string;\n}\n\nexport function createFarmThemeDocumentParts(\n  input: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n  serverTheme?: FarmThemePreference,\n): FarmThemeDocumentParts {\n  const config = resolveFarmThemeConfig(input, basePath);\n  if (!config.enabled) return { attributes: \"\", head: \"\" };\n\n  const hydrationTheme = serverTheme ?? config.default;\n  const initialTheme = hydrationTheme === \"system\" ? \"light\" : hydrationTheme;\n  const script = createFarmThemeBootstrapScript(config, hydrationTheme);\n\n  return {\n    attributes: ` data-theme=\"${initialTheme}\"`,\n    head: `<style id=\"${THEME_STYLE_ID}\">:root[data-theme=\"light\"]{color-scheme:light}:root[data-theme=\"dark\"]{color-scheme:dark}</style><script id=\"${THEME_SCRIPT_ID}\">${script}</script>`,\n  };\n}\n\nexport function createFarmThemeBootstrapScript(\n  config: ResolvedFarmThemeConfig,\n  serverTheme: FarmThemePreference = config.default,\n): string {\n  return `(function(config,serverTheme){\nvar isTheme=function(value){return value===\"light\"||value===\"dark\"||value===\"system\";};\nvar decode=function(value){try{return decodeURIComponent(value);}catch(_error){return value;}};\nvar readCookie=function(){var entries=document.cookie.split(\";\");for(var index=0;index<entries.length;index++){var entry=entries[index];var separator=entry.indexOf(\"=\");if(separator<0)continue;if(decode(entry.slice(0,separator).trim())===config.storageKey)return decode(entry.slice(separator+1).trim());}};\nvar media=window.matchMedia(\"(prefers-color-scheme: dark)\");\nvar resolveTheme=function(theme){return theme===\"system\"?(media.matches?\"dark\":\"light\"):theme;};\nvar storedTheme=readCookie();\nvar preference=isTheme(storedTheme)?storedTheme:config.default;\nvar serverSnapshot={theme:serverTheme,resolvedTheme:serverTheme===\"system\"?undefined:serverTheme,mounted:false};\nvar apply=function(){var resolvedTheme=resolveTheme(preference);document.documentElement.dataset.theme=resolvedTheme;var snapshot={theme:preference,resolvedTheme:resolvedTheme,mounted:true};if(window.__FARM_THEME__)window.__FARM_THEME__.snapshot=snapshot;return snapshot;};\nvar emit=function(){var snapshot=apply();window.dispatchEvent(new CustomEvent(\"farm:themechange\",{detail:snapshot}));};\nvar persist=function(theme){var secure=window.location.protocol===\"https:\"?\"; Secure\":\"\";document.cookie=encodeURIComponent(config.storageKey)+\"=\"+encodeURIComponent(theme)+\"; Path=\"+config.cookiePath+\"; Max-Age=31536000; SameSite=Lax\"+secure;try{localStorage.setItem(config.storageKey,theme);}catch(_error){}};\nvar setTheme=function(theme){if(!isTheme(theme))throw new TypeError(\"Unknown FARMJS theme: \"+String(theme));preference=theme;persist(theme);emit();};\nvar initialSnapshot={theme:preference,resolvedTheme:resolveTheme(preference),mounted:true};\nwindow.__FARM_THEME__={config:config,serverSnapshot:serverSnapshot,snapshot:initialSnapshot,setTheme:setTheme};\ndocument.documentElement.dataset.theme=initialSnapshot.resolvedTheme;\nvar handleSystemChange=function(){if(preference===\"system\")emit();};\nif(typeof media.addEventListener===\"function\")media.addEventListener(\"change\",handleSystemChange);else if(typeof media.addListener===\"function\")media.addListener(handleSystemChange);\nwindow.addEventListener(\"storage\",function(event){if(event.key!==config.storageKey||!isTheme(event.newValue))return;preference=event.newValue;persist(preference);emit();});\n})(${serializeInlineValue(config)},${serializeInlineValue(serverTheme)});`;\n}\n\nexport function applyFarmThemeDocument(\n  html: string,\n  input: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n  serverTheme?: FarmThemePreference,\n): string {\n  const parts = createFarmThemeDocumentParts(input, basePath, serverTheme);\n  if (!parts.head) return html;\n\n  let output = html.replace(/<html([^>]*)>/i, (_match, attributes: string) => {\n    const nextAttributes = attributes.replace(/\\sdata-theme=(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/i, \"\");\n    return `<html${nextAttributes}${parts.attributes}>`;\n  });\n\n  if (!output.includes(`id=\"${THEME_SCRIPT_ID}\"`)) {\n    output = output.replace(/<head([^>]*)>/i, `<head$1>${parts.head}`);\n  }\n\n  return output;\n}\n\nfunction serializeInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\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","import { getCurrentRequestOrNull } from \"../server/request\";\nimport { _setFarmThemeServerSnapshotResolver } from \"./bridge\";\nimport { resolveFarmThemeConfig } from \"./config\";\nimport type {\n  FarmThemeConfig,\n  FarmThemePreference,\n  FarmThemeSnapshot,\n  ResolvedFarmThemeConfig,\n} from \"./types\";\n\nlet defaultThemeConfig = resolveFarmThemeConfig(undefined);\n\nexport function _setDefaultFarmThemeConfig(\n  config: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n): void {\n  defaultThemeConfig = resolveFarmThemeConfig(config, basePath);\n}\n\n// The theme preference is cosmetic, so a missing request context must never\n// crash a render: without a request to read the cookie from, the configured\n// default applies. Runtimes with partial AsyncLocalStorage support (for\n// example StackBlitz WebContainers) can lose the store mid-render, and a\n// thrown error here would also take down the error page itself.\nexport function getTheme(request: Request | null = getCurrentRequestOrNull()): FarmThemePreference {\n  if (!request) return defaultThemeConfig.default;\n  return readFarmThemePreference(request, defaultThemeConfig);\n}\n\nexport function getThemeSnapshot(\n  request: Request | null = getCurrentRequestOrNull(),\n): FarmThemeSnapshot {\n  const theme = request\n    ? readFarmThemePreference(request, defaultThemeConfig)\n    : defaultThemeConfig.default;\n  return {\n    theme,\n    resolvedTheme: theme === \"system\" ? undefined : theme,\n    mounted: false,\n  };\n}\n\nexport function readFarmThemePreference(\n  request: Request,\n  config: ResolvedFarmThemeConfig,\n): FarmThemePreference {\n  if (!config.enabled) return config.default;\n  const stored = readCookie(request.headers.get(\"cookie\"), config.storageKey);\n  return isFarmThemePreference(stored) ? stored : config.default;\n}\n\nfunction readCookie(cookieHeader: string | null, name: string): string | undefined {\n  if (!cookieHeader) return undefined;\n  for (const entry of cookieHeader.split(\";\")) {\n    const separator = entry.indexOf(\"=\");\n    if (separator < 0) continue;\n    const key = decodeCookieValue(entry.slice(0, separator).trim());\n    if (key !== name) continue;\n    return decodeCookieValue(entry.slice(separator + 1).trim());\n  }\n  return undefined;\n}\n\nfunction decodeCookieValue(value: string): string {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return value;\n  }\n}\n\nfunction isFarmThemePreference(value: unknown): value is FarmThemePreference {\n  return value === \"light\" || value === \"dark\" || value === \"system\";\n}\n\n_setFarmThemeServerSnapshotResolver(() => {\n  try {\n    return getThemeSnapshot();\n  } catch {\n    const theme = defaultThemeConfig.default;\n    return {\n      theme,\n      resolvedTheme: theme === \"system\" ? undefined : theme,\n      mounted: false,\n    };\n  }\n});\n","{\n  \"name\": \"@farm.js/core\",\n  \"version\": \"0.1.0-beta.99\",\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      \"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/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    \"./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/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","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DefaultErrorSourceFrame } from \"../components/error-page\";\n\nexport interface DefaultErrorDiagnostics {\n  name: string;\n  message: string;\n  stack?: string;\n  sourceFrame?: DefaultErrorSourceFrame;\n}\n\ninterface StackLocation {\n  absolutePath: string;\n  displayPath: string;\n  line: number;\n  column: number;\n}\n\nconst SECRET_VALUE_PATTERN =\n  /\\b(api[_-]?key|access[_-]?token|auth[_-]?token|token|password|secret)\\s*[:=]\\s*([^\\s,;]+)/gi;\nconst BEARER_PATTERN = /\\b(Bearer\\s+)[A-Za-z0-9._~+/=-]+/gi;\n\nfunction redactErrorText(value: string): string {\n  return value\n    .replace(BEARER_PATTERN, \"$1[REDACTED]\")\n    .replace(SECRET_VALUE_PATTERN, \"$1=[REDACTED]\");\n}\n\nfunction isPathInsideRoot(root: string, filePath: string): boolean {\n  const relative = path.relative(root, filePath);\n  return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction normalizeStackPath(value: string): string | undefined {\n  const withoutQuery = value.replace(/[?#].*$/, \"\");\n  try {\n    return withoutQuery.startsWith(\"file://\") ? fileURLToPath(withoutQuery) : withoutQuery;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction findStackLocation(stack: string, root: string): StackLocation | undefined {\n  for (const stackLine of stack.split(\"\\n\")) {\n    const match = stackLine.match(\n      /(?:\\()?((?:file:\\/\\/\\/|\\/|[A-Za-z]:[\\\\/])[^\\n()]+):(\\d+):(\\d+)\\)?$/,\n    );\n    if (!match) continue;\n\n    const candidate = normalizeStackPath(match[1]);\n    if (!candidate || candidate.includes(`${path.sep}node_modules${path.sep}`)) continue;\n\n    const absolutePath = path.resolve(candidate);\n    if (!isPathInsideRoot(root, absolutePath) || !fs.existsSync(absolutePath)) continue;\n\n    const relativePath = path.relative(root, absolutePath).split(path.sep).join(\"/\");\n    return {\n      absolutePath,\n      displayPath: relativePath || path.basename(absolutePath),\n      line: Number(match[2]),\n      column: Number(match[3]),\n    };\n  }\n  return undefined;\n}\n\nfunction createSourceFrame(location: StackLocation): DefaultErrorSourceFrame | undefined {\n  try {\n    const sourceLines = fs.readFileSync(location.absolutePath, \"utf8\").split(/\\r?\\n/);\n    if (location.line < 1 || location.line > sourceLines.length) return undefined;\n\n    const start = Math.max(1, location.line - 2);\n    const end = Math.min(sourceLines.length, location.line + 2);\n    const lines = [];\n    for (let line = start; line <= end; line++) {\n      lines.push({\n        number: line,\n        content: sourceLines[line - 1],\n        highlight: line === location.line,\n      });\n    }\n\n    return {\n      file: location.displayPath,\n      line: location.line,\n      column: location.column,\n      lines,\n    };\n  } catch {\n    return undefined;\n  }\n}\n\nfunction sanitizeStack(stack: string, root: string): string {\n  const normalizedRoot = path.resolve(root);\n  return (\n    redactErrorText(stack)\n      .split(normalizedRoot)\n      .join(\"<project>\")\n      // Match displayPath, which reports project-relative paths with POSIX separators.\n      .replace(/<project>[^\\s)]*/g, (segment) => segment.split(\"\\\\\").join(\"/\"))\n      .split(\"\\n\")\n      .filter((line, index) => index === 0 || !line.includes(\"node:internal\"))\n      .slice(0, 14)\n      .join(\"\\n\")\n  );\n}\n\nexport function createDefaultErrorDiagnostics(\n  error: unknown,\n  root: string,\n): DefaultErrorDiagnostics {\n  const normalizedError =\n    error instanceof Error\n      ? error\n      : new Error(typeof error === \"string\" ? error : \"Unknown server rendering error\");\n  const rawStack = normalizedError.stack || `${normalizedError.name}: ${normalizedError.message}`;\n  const location = findStackLocation(rawStack, path.resolve(root));\n\n  return {\n    name: redactErrorText(normalizedError.name || \"Error\"),\n    message: redactErrorText(normalizedError.message || \"Unknown server rendering error\"),\n    stack: sanitizeStack(rawStack, root),\n    sourceFrame: location ? createSourceFrame(location) : undefined,\n  };\n}\n","import type React from \"react\";\nimport type { FarmIslandStrategy } from \"../island\";\n\nconst REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\");\nconst LEGACY_REACT_ELEMENT_TYPE = Symbol.for(\"react.element\");\nconst BOUNDARY_GRAPH_CONTEXT = Symbol.for(\"farm.isolated-hydration.client-graph-context\");\n\nfunction getBoundaryGraphContext(ReactRuntime: typeof React): React.Context<boolean> {\n  const shared = globalThis as typeof globalThis &\n    Record<symbol, WeakMap<object, React.Context<boolean>> | undefined>;\n  const contexts = shared[BOUNDARY_GRAPH_CONTEXT] ?? new WeakMap();\n  shared[BOUNDARY_GRAPH_CONTEXT] = contexts;\n  const runtimeIdentity = ReactRuntime.createElement;\n  const existing = contexts.get(runtimeIdentity);\n  if (existing) return existing;\n\n  const context = ReactRuntime.createContext(false);\n  contexts.set(runtimeIdentity, context);\n  return context;\n}\n\nfunction serializeBoundaryProps(value: unknown, seen = new Set<object>()): unknown {\n  if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n  if (typeof value === \"number\") {\n    if (!Number.isFinite(value)) throw new TypeError(\"non-finite numbers are not serializable\");\n    return value;\n  }\n  if (typeof value === \"undefined\") {\n    throw new TypeError(\"undefined values are not serializable\");\n  }\n  if (typeof value !== \"object\") {\n    throw new TypeError(`${typeof value} values are not serializable`);\n  }\n  if (\n    (value as { $$typeof?: symbol }).$$typeof === REACT_ELEMENT_TYPE ||\n    (value as { $$typeof?: symbol }).$$typeof === LEGACY_REACT_ELEMENT_TYPE\n  ) {\n    throw new TypeError(\"React elements cannot cross an isolated hydration boundary\");\n  }\n  if (seen.has(value)) throw new TypeError(\"circular props are not serializable\");\n  seen.add(value);\n  try {\n    if (Array.isArray(value)) return value.map((entry) => serializeBoundaryProps(entry, seen));\n    const prototype = Object.getPrototypeOf(value);\n    if (prototype !== Object.prototype && prototype !== null) {\n      throw new TypeError(\"class instances are not serializable\");\n    }\n    return Object.fromEntries(\n      Object.entries(value).map(([key, entry]) => [key, serializeBoundaryProps(entry, seen)]),\n    );\n  } finally {\n    seen.delete(value);\n  }\n}\n\nfunction serializeBoundaryPayload(value: unknown): string {\n  return JSON.stringify(serializeBoundaryProps(value))\n    .replace(/&/g, \"\\\\u0026\")\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/>/g, \"\\\\u003e\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\n/** @internal Keeps client-to-client imports inside one isolated React root. */\nexport function wrapFarmIsolatedClientGraph(\n  ReactRuntime: typeof React,\n  element: React.ReactNode,\n): React.ReactElement {\n  const Context = getBoundaryGraphContext(ReactRuntime);\n  return ReactRuntime.createElement(Context.Provider, { value: true }, element);\n}\n\n/** @internal Generated by Farm's experimental isolated-hydration transform. */\nexport function createFarmIsolatedClientBoundary(\n  ReactRuntime: typeof React,\n  Component: React.ComponentType<any>,\n  moduleReference: string,\n  exportName: string,\n  islandStrategy: FarmIslandStrategy,\n): React.ComponentType<any> {\n  function FarmIsolatedClientBoundary(props: Record<string, unknown>) {\n    const Context = getBoundaryGraphContext(ReactRuntime);\n    const belongsToParentClientGraph = ReactRuntime.useContext(Context);\n    const boundaryId = ReactRuntime.useId();\n\n    if (belongsToParentClientGraph) {\n      return ReactRuntime.createElement(Component, props);\n    }\n\n    let serializedProps: string;\n    try {\n      serializedProps = serializeBoundaryPayload(props);\n    } catch (error) {\n      if (typeof window === \"undefined\") {\n        console.warn(\n          `[Farm.js] Could not isolate ${moduleReference}#${exportName}: ${\n            error instanceof Error ? error.message : String(error)\n          }. The server-rendered component was preserved without client hydration.`,\n        );\n      }\n      return ReactRuntime.createElement(Component, props);\n    }\n\n    return ReactRuntime.createElement(\n      ReactRuntime.Fragment,\n      null,\n      ReactRuntime.createElement(\n        \"farm-client-boundary\",\n        {\n          \"data-farm-client-boundary\": moduleReference,\n          \"data-farm-client-id\": boundaryId,\n          \"data-farm-client-export\": exportName,\n          \"data-farm-island-strategy\": islandStrategy,\n          style: { display: \"contents\" },\n        },\n        ReactRuntime.createElement(\n          Context.Provider,\n          { value: true },\n          ReactRuntime.createElement(Component, props),\n        ),\n      ),\n      ReactRuntime.createElement(\"script\", {\n        type: \"application/json\",\n        \"data-farm-client-props\": boundaryId,\n        dangerouslySetInnerHTML: { __html: serializedProps },\n      }),\n    );\n  }\n\n  FarmIsolatedClientBoundary.displayName = `FarmIsolated(${\n    Component.displayName || Component.name || exportName\n  })`;\n  return FarmIsolatedClientBoundary;\n}\n\ntype FarmIsolatedRoot = {\n  render(element: React.ReactNode): void;\n  unmount(): void;\n};\n\ninterface FarmIsolatedRootRecord {\n  root: FarmIsolatedRoot;\n  reference: string;\n  exportName: string;\n  props: Record<string, unknown>;\n  serverHTML: string;\n  restore(error: unknown): void;\n}\n\ninterface FarmIsolatedHydrationRootOptions {\n  onUncaughtError?: (error: unknown) => void;\n}\n\nexport interface FarmIsolatedHydrationRuntimeOptions {\n  ReactRuntime: typeof React;\n  hydrateRoot(\n    container: Element,\n    element: React.ReactNode,\n    options?: FarmIsolatedHydrationRootOptions,\n  ): FarmIsolatedRoot;\n  load(reference: string): Promise<Record<string, unknown>>;\n  schedule(options: {\n    container: Element;\n    strategy: FarmIslandStrategy;\n    signal?: AbortSignal;\n    hydrate(): Promise<void>;\n  }): Promise<unknown>;\n  wrap?(element: React.ReactElement): React.ReactNode;\n  report?(message: string, error?: unknown): void;\n}\n\nfunction findBoundaryPayload(container: Element, boundaryId: string): HTMLScriptElement | null {\n  const sibling = container.nextElementSibling;\n  if (\n    sibling instanceof HTMLScriptElement &&\n    sibling.type === \"application/json\" &&\n    sibling.getAttribute(\"data-farm-client-props\") === boundaryId\n  ) {\n    return sibling;\n  }\n\n  for (const candidate of container.ownerDocument.querySelectorAll<HTMLScriptElement>(\n    'script[type=\"application/json\"][data-farm-client-props]',\n  )) {\n    if (candidate.getAttribute(\"data-farm-client-props\") === boundaryId) return candidate;\n  }\n  return null;\n}\n\n/** @internal Shared development and production runtime for isolated React roots. */\nexport function createFarmIsolatedHydrationRuntime(options: FarmIsolatedHydrationRuntimeOptions) {\n  const roots = new Map<Element, FarmIsolatedRootRecord>();\n  const pending = new Map<Element, AbortController>();\n  const report =\n    options.report ??\n    ((message: string, error?: unknown) => console.warn(`[Farm.js] ${message}`, error));\n\n  const failRoot = (\n    container: Element,\n    reference: string,\n    exportName: string,\n    serverHTML: string,\n    error: unknown,\n  ) => {\n    report(\n      `Could not hydrate isolated client boundary ${reference}#${exportName}. ` +\n        \"The server-rendered HTML was restored.\",\n      error,\n    );\n    queueMicrotask(() => {\n      try {\n        roots.get(container)?.root.unmount();\n      } catch {\n        // React may already have detached a root that failed during hydration.\n      }\n      roots.delete(container);\n      container.removeAttribute(\"data-farm-hydrated\");\n      container.removeAttribute(\"data-farm-island-hydrated\");\n      container.innerHTML = serverHTML;\n    });\n  };\n\n  class FarmIsolatedRootErrorBoundary extends options.ReactRuntime.Component<\n    { children?: React.ReactNode; onError(error: unknown): void },\n    { failed: boolean }\n  > {\n    state = { failed: false };\n\n    static getDerivedStateFromError() {\n      return { failed: true };\n    }\n\n    componentDidCatch(error: unknown) {\n      this.props.onError(error);\n    }\n\n    render() {\n      return this.state.failed ? null : this.props.children;\n    }\n  }\n\n  const createBoundaryGraph = (\n    Component: React.ComponentType<any>,\n    props: Record<string, unknown>,\n    restore: (error: unknown) => void,\n  ) => {\n    const componentElement = options.ReactRuntime.createElement(Component, props);\n    const wrappedElement = options.wrap ? options.wrap(componentElement) : componentElement;\n    return wrapFarmIsolatedClientGraph(\n      options.ReactRuntime,\n      options.ReactRuntime.createElement(\n        FarmIsolatedRootErrorBoundary,\n        { onError: restore },\n        wrappedElement,\n      ),\n    );\n  };\n\n  async function hydrate(scope: ParentNode = document, signal?: AbortSignal): Promise<void> {\n    const candidates = Array.from(\n      scope.querySelectorAll<Element>(\"farm-client-boundary[data-farm-client-boundary]\"),\n    );\n    if (\n      scope instanceof Element &&\n      scope.matches(\"farm-client-boundary[data-farm-client-boundary]\")\n    ) {\n      candidates.unshift(scope);\n    }\n    const boundaries = candidates.filter((container) => {\n      if (roots.has(container) || pending.has(container)) return false;\n      return !container.parentElement?.closest(\"farm-client-boundary[data-farm-client-boundary]\");\n    });\n\n    await Promise.all(\n      boundaries.map(async (container) => {\n        const reference = container.getAttribute(\"data-farm-client-boundary\");\n        const boundaryId = container.getAttribute(\"data-farm-client-id\");\n        const exportName = container.getAttribute(\"data-farm-client-export\") || \"default\";\n        const strategy =\n          (container.getAttribute(\"data-farm-island-strategy\") as FarmIslandStrategy | null) ??\n          \"load\";\n        if (!reference || !boundaryId) {\n          report(\"An isolated client boundary is missing its module reference or payload ID.\");\n          return;\n        }\n\n        const controller = new AbortController();\n        pending.set(container, controller);\n        const abort = () => controller.abort();\n        if (signal?.aborted) abort();\n        else signal?.addEventListener(\"abort\", abort, { once: true });\n        const cleanup = () => {\n          signal?.removeEventListener(\"abort\", abort);\n          if (pending.get(container) === controller) pending.delete(container);\n        };\n\n        let scheduled: Promise<unknown>;\n        try {\n          scheduled = options.schedule({\n            container,\n            strategy,\n            signal: controller.signal,\n            hydrate: async () => {\n              if (controller.signal.aborted || !container.isConnected) return;\n              const serverHTML = container.innerHTML;\n              try {\n                const module = await options.load(reference);\n                if (controller.signal.aborted || !container.isConnected) return;\n                const originals = module.__farm_client_boundary_originals__ as\n                  | Record<string, unknown>\n                  | undefined;\n                const Component = originals?.[exportName];\n                if (typeof Component !== \"function\" && typeof Component !== \"object\") {\n                  throw new Error(\"compiled original export was not found\");\n                }\n                const payload = findBoundaryPayload(container, boundaryId);\n                if (!payload) throw new Error(`serialized props ${boundaryId} were not found`);\n                const props = JSON.parse(payload.textContent || \"{}\");\n                if (!props || typeof props !== \"object\" || Array.isArray(props)) {\n                  throw new Error(\"serialized props must be an object\");\n                }\n\n                let rootFailure: unknown;\n                const restore = (error: unknown) => {\n                  if (rootFailure !== undefined) return;\n                  rootFailure = error;\n                  failRoot(container, reference, exportName, serverHTML, error);\n                  controller.abort();\n                };\n                const graphElement = createBoundaryGraph(\n                  Component as React.ComponentType<any>,\n                  props as Record<string, unknown>,\n                  restore,\n                );\n                const root = options.hydrateRoot(container, graphElement, {\n                  onUncaughtError: restore,\n                });\n                roots.set(container, {\n                  root,\n                  reference,\n                  exportName,\n                  props: props as Record<string, unknown>,\n                  serverHTML,\n                  restore,\n                });\n                container.setAttribute(\"data-farm-hydrated\", \"true\");\n              } catch (error) {\n                failRoot(container, reference, exportName, serverHTML, error);\n                controller.abort();\n              }\n            },\n          });\n        } catch (error) {\n          failRoot(container, reference, exportName, container.innerHTML, error);\n          controller.abort();\n          cleanup();\n          return;\n        }\n\n        const tracked = Promise.resolve(scheduled)\n          .catch((error) => {\n            if (!controller.signal.aborted) {\n              failRoot(container, reference, exportName, container.innerHTML, error);\n              controller.abort();\n            }\n          })\n          .finally(cleanup);\n        if (strategy === \"load\") await tracked;\n        else void tracked;\n      }),\n    );\n  }\n\n  function updateModule(reference: string, module: Record<string, unknown>): number {\n    const originals = module.__farm_client_boundary_originals__ as\n      | Record<string, unknown>\n      | undefined;\n    let updated = 0;\n\n    for (const [container, record] of roots) {\n      if (record.reference !== reference) continue;\n      const Component = originals?.[record.exportName];\n      if (typeof Component !== \"function\" && typeof Component !== \"object\") {\n        failRoot(\n          container,\n          record.reference,\n          record.exportName,\n          record.serverHTML,\n          new Error(\"updated compiled original export was not found\"),\n        );\n        continue;\n      }\n\n      try {\n        record.root.render(\n          createBoundaryGraph(Component as React.ComponentType<any>, record.props, record.restore),\n        );\n        updated++;\n      } catch (error) {\n        failRoot(container, record.reference, record.exportName, record.serverHTML, error);\n      }\n    }\n\n    return updated;\n  }\n\n  function dispose(scope: Node): void {\n    for (const [container, controller] of pending) {\n      if (container === scope || scope.contains(container)) {\n        controller.abort();\n        pending.delete(container);\n      }\n    }\n    for (const [container, record] of roots) {\n      if (container === scope || scope.contains(container)) {\n        try {\n          record.root.unmount();\n        } catch {\n          // The DOM owner may already have removed a failed root.\n        }\n        roots.delete(container);\n        container.removeAttribute(\"data-farm-hydrated\");\n        container.removeAttribute(\"data-farm-island-hydrated\");\n      }\n    }\n  }\n\n  return {\n    hydrate,\n    updateModule,\n    dispose,\n    rootCount: () => roots.size,\n  };\n}\n","import React from \"react\";\nimport {\n  renderToPipeableStream as reactRenderToPipeableStream,\n  renderToString as reactRenderToString,\n} from \"react-dom/server\";\nimport { wrapFarmIsolatedClientGraph } from \"../../client/isolated-boundary\";\n\nexport class ErrorBoundary extends React.Component<\n  {\n    Fallback: React.ComponentType<any>;\n    fallbackProps: Record<string, any>;\n    children: React.ReactNode;\n  },\n  { hasError: boolean; error: unknown }\n> {\n  constructor(props: any) {\n    super(props);\n    this.state = { hasError: false, error: null };\n  }\n\n  static getDerivedStateFromError(error: unknown) {\n    return { hasError: true, error };\n  }\n\n  render() {\n    if (this.state.hasError) {\n      const Fallback = this.props.Fallback;\n      return React.createElement(Fallback, {\n        ...this.props.fallbackProps,\n        error: this.state.error,\n        reset: () => this.setState({ hasError: false, error: null }),\n      });\n    }\n    return this.props.children as React.ReactElement;\n  }\n}\n\nexport const name = \"react\";\nexport const capabilities = {\n  streaming: { node: true, web: false },\n} as const;\nexport const Fragment = React.Fragment;\nexport const Suspense = React.Suspense;\nexport const createElement = React.createElement;\nexport const isValidElement = React.isValidElement;\nexport const wrapClientGraph = (element: React.ReactNode) =>\n  wrapFarmIsolatedClientGraph(React, element);\nexport const renderToString = reactRenderToString;\nexport const renderToPipeableStream = reactRenderToPipeableStream;\n\nexport default React;\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport type {\n  FarmConfig,\n  FarmRequest,\n  FarmResponse,\n  LoadingProps,\n  PageProps,\n  RouteModule,\n  SSGPage,\n} from \"../types\";\nimport type { MatchedRouteSlot, RouteManager } from \"../routing/route-manager\";\nimport { logger, toViteModuleId } from \"../utils\";\nimport { collectDevStylesheetUrls } from \"./dev-styles\";\nimport {\n  composeFarmFullDocument,\n  extractFarmFullDocument,\n  opensFarmFullDocument,\n} from \"./full-document\";\nimport { getClientModuleMetadata } from \"../utils/client-component\";\nimport { Writable } from \"stream\";\nimport {\n  _clearCurrentMiddlewareContext,\n  _clearCurrentMiddlewareData,\n  _runWithMiddlewareContext,\n  _runWithMiddlewareData,\n} from \"../middleware/server\";\nimport { getRequestContextSnapshot } from \"../request-context\";\nimport { matchSSGPage, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport {\n  FARM_MARKDOWN_CONTENT_TYPE,\n  createFarmMarkdownErrorBody,\n  farmRequestWantsMarkdown,\n} from \"../app-markdown\";\nimport {\n  getIntegrationProviders,\n  getRegisteredIntegrationAPIManifest,\n  isFarmIntegrationProviderComponentReference,\n} from \"../integrations\";\nimport {\n  _runWithCurrentRequest,\n  createWebRequestFromFarmRequest,\n  resolveFarmRequestURL,\n} from \"./request\";\nimport { createFarmCacheKey, getFarmDataCache, normalizeRevalidatePath } from \"../cache\";\nimport { resolveFarmNotFoundComponentPath } from \"../not-found\";\nimport { getFarmAppDirectories } from \"../layers\";\nimport { emitFarmEvent } from \"../observability\";\nimport {\n  getFarmRedirectError,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n} from \"../navigation-errors\";\nimport {\n  addMetadataImageReference,\n  mergeMetadata,\n  renderMetadataHead,\n  type FarmMetadataImageReference,\n  type MetadataImageKind,\n} from \"../metadata\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"../route-context\";\nimport { searchParamsToObject } from \"../search-params\";\nimport { prepareDeferredData, snapshotDeferredData, type DeferredRecord } from \"../deferred\";\nimport { createFarmDeploymentCookie, FARM_DEPLOYMENT_ID_HEADER } from \"../deployment\";\nimport type { StaticMetadataImageInfo } from \"../static-metadata-image\";\nimport {\n  _runWithFarmI18nRequest,\n  getFarmI18nClientSnapshot,\n  type FarmI18nClientSnapshot,\n  type FarmI18nRuntime,\n} from \"../i18n/server\";\nimport { createFarmLocaleCookie, getFarmLocaleVaryHeaders } from \"../i18n/resolver\";\nimport { localizeFarmHref, localizeFarmPathname } from \"../i18n/routing\";\nimport { sendWebResponse } from \"./response\";\nimport { matchesFarmIfNoneMatch } from \"../server-http\";\nimport { renderFarmFontDevHead } from \"../font-vite\";\nimport { createFarmMetadataImageResponse } from \"../metadata-image\";\nimport { createFarmMetadataRouteResponse } from \"../metadata-route\";\nimport {\n  resolveFarmTrailingSlashRedirect,\n  setFarmTrailingSlashPreference,\n} from \"../trailing-slash\";\nimport { applyFarmBasePath, setFarmBasePath } from \"../base-path\";\nimport { DEFAULT_NOT_FOUND_STYLES } from \"../components/not-found-styles\";\nimport {\n  createDefaultErrorMarkup,\n  getDefaultErrorStatusText,\n  resolveDefaultErrorStatus,\n} from \"../components/error-page\";\nimport { createFarmThemeDocumentParts } from \"../theme/server-runtime\";\nimport { getTheme as getFarmTheme } from \"../theme/server\";\nimport { FARM_VERSION } from \"../version\";\nimport type { ViteDevServer } from \"vite\";\nimport {\n  getFarmRendererCapabilities,\n  getFarmRendererComponentExtensions,\n  isReactRenderer,\n  readFarmRendererWebStream,\n  resolveFarmRendererModule,\n  type FarmServerRendererRuntime,\n} from \"../renderer\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport { createDefaultErrorDiagnostics } from \"./error-diagnostics\";\n\nlet cachedClerkProvider: { ClerkProvider: any } | null = null;\n\nconst importRuntimeModule = new Function(\"specifier\", \"return import(specifier);\") as (\n  specifier: string,\n) => Promise<any>;\n\ninterface CachedSSGPage {\n  html: string;\n  document: boolean;\n}\n\ninterface CachedPPRShell {\n  html: string;\n}\n\nexport function shouldServePrerenderedPage(\n  nodeEnv: string | undefined,\n  method: string | undefined,\n): boolean {\n  if (nodeEnv !== \"production\") return false;\n  const normalizedMethod = (method || \"GET\").toUpperCase();\n  return normalizedMethod === \"GET\" || normalizedMethod === \"HEAD\";\n}\n\nfunction formatSSGManifestError(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\nfunction parseSSGManifest(content: string, manifestPath: string): SSGPage[] {\n  let manifest: unknown;\n\n  try {\n    manifest = JSON.parse(content);\n  } catch (error) {\n    throw new Error(\n      `Failed to parse SSG manifest at ${manifestPath}: ${formatSSGManifestError(error)}`,\n    );\n  }\n\n  if (!Array.isArray(manifest)) {\n    throw new Error(`Invalid SSG manifest at ${manifestPath}: expected an array of pages.`);\n  }\n\n  for (const [index, page] of manifest.entries()) {\n    if (!page || typeof page !== \"object\" || Array.isArray(page)) {\n      throw new Error(`Invalid SSG manifest at ${manifestPath}: page ${index} must be an object.`);\n    }\n\n    const entry = page as Record<string, unknown>;\n    if (typeof entry.urlPath !== \"string\") {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} must have a string urlPath.`,\n      );\n    }\n    if (\n      !entry.params ||\n      typeof entry.params !== \"object\" ||\n      Array.isArray(entry.params) ||\n      Object.values(entry.params).some((value) => typeof value !== \"string\")\n    ) {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} must have string params.`,\n      );\n    }\n    if (\n      entry.revalidate !== undefined &&\n      (typeof entry.revalidate !== \"number\" ||\n        !Number.isFinite(entry.revalidate) ||\n        entry.revalidate <= 0)\n    ) {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} revalidate must be a positive number.`,\n      );\n    }\n  }\n\n  return manifest as SSGPage[];\n}\n\ninterface PPRShellCacheOptions {\n  pathname: string;\n  search: string;\n  /**\n   * Locale the shell was rendered in, resolved once when these options are built.\n   * The shell carries `lang`, `dir`, the message catalog and the alternate links, so\n   * it cannot be shared across locales. It is captured rather than read at write\n   * time because the shell is stored from a streaming `onComplete` callback, which\n   * can run outside the request context that resolved the locale.\n   */\n  locale: string;\n  revalidate?: number;\n}\n\nexport interface FarmNavigationFragmentLayout {\n  pattern: string;\n  module: { default?: any };\n}\n\nexport interface FarmNavigationFragmentSlot {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  module: { default?: any };\n  props: Record<string, unknown>;\n}\n\nexport interface FarmNavigationFragmentInput {\n  PageComponent: any;\n  LoadingComponent?: any;\n  pageProps: Record<string, unknown>;\n  params: Record<string, string>;\n  layouts: FarmNavigationFragmentLayout[];\n  /** First destination layout that changed compared with the active shell. */\n  layoutStartIndex?: number;\n  slots?: FarmNavigationFragmentSlot[];\n  pageShouldHydrate: boolean;\n  layoutShouldHydrate: boolean;\n  islandStrategy?: FarmIslandStrategy | null;\n}\n\nconst warnedSuppressedAsyncHydrationModules = new Set<string>();\n\nfunction warnSuppressedAsyncHydrationOnce(modulePath: string): void {\n  if (warnedSuppressedAsyncHydrationModules.has(modulePath)) return;\n  warnedSuppressedAsyncHydrationModules.add(modulePath);\n  logger.warn(\n    `${modulePath} is an async server component that imports client components. ` +\n      `React cannot hydrate async components in the browser, so this route stays ` +\n      `server-rendered and its client imports are not interactive. Move the ` +\n      `interactive UI into a \"use client\" child rendered by a synchronous page, ` +\n      `or enable experimental server components support.`,\n  );\n}\n\n// Routes whose layout was observed to render a full `<html>` document. The\n// streaming path can't rewrite a document after its shell is flushed, so once a\n// route is seen to be full-document it is served through the buffered path\n// (which composes the document correctly) on every subsequent request.\nconst fullDocumentRoutes = new Set<string>();\n\nlet warnedFullDocumentLayout = false;\n\nfunction warnFarmFullDocumentLayout(): void {\n  if (warnedFullDocumentLayout) return;\n  warnedFullDocumentLayout = true;\n  logger.warn(\n    `A root layout returned a full <html> document. Farm.js owns the document ` +\n      `shell, so a layout should return a fragment (its children) — like the docs ` +\n      `example — and let the framework provide <html>/<head>/<body>. The document ` +\n      `has been composed into the response, but returning a fragment avoids the ` +\n      `ambiguity and keeps dev and production identical.`,\n  );\n}\n\nfunction hasRequestHeader(req: FarmRequest, name: string): boolean {\n  const value = req.headers[name.toLowerCase()];\n  return Array.isArray(value) ? value.length > 0 : Boolean(value);\n}\n\n/**\n * The request pathname (without query/hash) used as the default canonical URL.\n * Prefers the resolved route path recorded on the request, falling back to the\n * raw request URL.\n */\nfunction getFarmMetadataPathname(req: FarmRequest): string | undefined {\n  const raw = (req as any).__FARM_ROUTE__ || req.url;\n  if (typeof raw !== \"string\" || raw.length === 0) return undefined;\n  const boundary = raw.search(/[?#]/);\n  return boundary === -1 ? raw : raw.slice(0, boundary);\n}\n\nfunction serializeInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nfunction appendResponseHeader(res: FarmResponse, name: string, value: string): void {\n  const current = res.getHeader(name);\n  if (current === undefined) {\n    res.setHeader(name, value);\n  } else if (Array.isArray(current)) {\n    res.setHeader(name, [...current.map(String), value]);\n  } else {\n    res.setHeader(name, [String(current), value]);\n  }\n}\n\nfunction appendResponseVary(res: FarmResponse, value: string): void {\n  const current = res.getHeader(\"Vary\");\n  const values = new Set(\n    (Array.isArray(current) ? current.join(\",\") : String(current || \"\"))\n      .split(\",\")\n      .map((entry) => entry.trim())\n      .filter(Boolean),\n  );\n  values.add(value);\n  res.setHeader(\"Vary\", Array.from(values).join(\", \"));\n}\n\nfunction renderI18nAlternateLinks(requestPath: string, snapshot: FarmI18nClientSnapshot): string {\n  if (snapshot.routing === \"none\") return \"\";\n  const url = new URL(requestPath, \"http://farm.local\");\n  const links = snapshot.locales.map((locale) => {\n    const href = localizeFarmPathname(url.pathname, locale, snapshot);\n    return `<link rel=\"alternate\" hreflang=\"${escapeHtmlAttribute(locale)}\" href=\"${escapeHtmlAttribute(href)}\">`;\n  });\n  links.push(\n    `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeHtmlAttribute(\n      localizeFarmPathname(url.pathname, snapshot.defaultLocale, snapshot),\n    )}\">`,\n  );\n  return links.join(\"\");\n}\n\nfunction findPPRDynamicChunkIndex(chunk: string): number {\n  const markerIndexes = [\n    chunk.indexOf('id=\"S:'),\n    chunk.indexOf(\"id='S:\"),\n    chunk.indexOf(\"$RC(\"),\n    chunk.indexOf(\"$RS(\"),\n    chunk.indexOf(\"$RV(\"),\n    chunk.indexOf(\"$RX(\"),\n  ].filter((index) => index >= 0);\n\n  if (markerIndexes.length === 0) {\n    return -1;\n  }\n\n  const markerIndex = Math.min(...markerIndexes);\n  const tagStart = chunk.lastIndexOf(\"<\", markerIndex);\n  return tagStart >= 0 ? tagStart : markerIndex;\n}\n\nfunction createPPRRefreshScript(): string {\n  return `<script>(function(){if(window.__FARM_PPR_REFRESHING__)return;window.__FARM_PPR_REFRESHING__=true;function replaceRoot(html){var doc=new DOMParser().parseFromString(html,\"text/html\");var next=doc.getElementById(\"root\");var current=document.getElementById(\"root\");if(!next||!current)return;current.innerHTML=next.innerHTML;}fetch(window.location.href,{credentials:\"same-origin\",headers:{\"x-farm-ppr-refresh\":\"1\"}}).then(function(response){return response.ok?response.text():null;}).then(function(html){if(html)replaceRoot(html);}).catch(function(){});})();</script>`;\n}\n\nfunction createPreHydrationClickQueueScript(): string {\n  return `<script>(function(){if(window.__FARM_PREHYDRATION_CLICK_QUEUE__)return;var queue=[];window.__FARM_PREHYDRATION_CLICK_QUEUE__=queue;window.__FARM_HYDRATED__=false;document.documentElement.dataset.farmHydrated=\"false\";function isModified(event){return !!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}function closestQueuedTarget(target){while(target&&target!==document.documentElement){if(target.matches&&target.matches('button,[role=\"button\"],input[type=\"button\"],input[type=\"submit\"],input[type=\"reset\"]'))return target;target=target.parentElement}return null}document.addEventListener(\"click\",function(event){if(window.__FARM_HYDRATED__)return;if(event.defaultPrevented||event.button!==0||isModified(event))return;var target=closestQueuedTarget(event.target);if(!target||target.closest&&target.closest(\"a[href]\")||target.closest&&target.closest('[data-farm-island-hydrated=\"true\"]'))return;if(queue.some(function(item){return item.target===target}))return;queue.push({target:target,createdAt:Date.now()});document.dispatchEvent(new CustomEvent(\"farm:island-interaction\",{detail:{target:target}}));event.preventDefault();event.stopImmediatePropagation()},true);})();</script>`;\n}\n\nfunction createDocumentFooter(options: {\n  suspenseRevealFallback: string;\n  refreshPPR?: boolean;\n  deferredHydrationScript?: string;\n}): string {\n  return `</div>\n  ${options.suspenseRevealFallback}\n  ${options.refreshPPR ? createPPRRefreshScript() : \"\"}\n  ${options.deferredHydrationScript || \"\"}\n  <script type=\"module\" src=\"/@farm/client.js\"></script>\n</body>\n</html>`;\n}\n\nfunction createDeferredHydrationScript(records: readonly DeferredRecord[]): string {\n  if (records.length === 0) return \"\";\n  return `<script>window.__FARM_DEFERRED_DATA__=${serializeInlineValue(\n    snapshotDeferredData(records),\n  )};</script>`;\n}\n\nfunction toMiddlewareMap(input: unknown): Map<string, any> {\n  if (input instanceof Map) {\n    return new Map(input as Map<string, any>);\n  }\n  if (input && typeof input === \"object\") {\n    return new Map(Object.entries(input as Record<string, any>));\n  }\n  return new Map<string, any>();\n}\n\nfunction isWebResponse(value: unknown): value is Response {\n  return (\n    typeof Response !== \"undefined\" &&\n    value instanceof Response &&\n    typeof value.arrayBuffer === \"function\"\n  );\n}\n\nasync function parseRouteModuleProps(\n  routeModule: RouteModule,\n  input: {\n    props: PageProps;\n    search: Record<string, string | string[] | undefined>;\n    routePath: string;\n  },\n): Promise<\n  PageProps & {\n    search: unknown;\n    data?: unknown;\n    __farmCanonicalPath?: string;\n    __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n    __farmRoutePropsResolved?: true;\n  }\n> {\n  const resolveRouteProps = (routeModule as any).__farmResolveRouteProps;\n  if (typeof resolveRouteProps === \"function\") {\n    // Resolve the top-level route state before starting the HTTP stream. It can\n    // still return explicit defer() values for nested Suspense boundaries, but\n    // redirects, notFound(), and failures must retain their real HTTP status.\n    return await resolveRouteProps(input.props);\n  }\n\n  if ((routeModule as any).__farmRouteParsesProps) {\n    return {\n      ...input.props,\n      search: input.search,\n    };\n  }\n\n  const schemas = (routeModule as any).__farmRouteSchemas;\n  const params = parseRouteModuleSchema(\n    schemas?.params,\n    input.props.params,\n    \"params\",\n    input.routePath,\n  );\n  const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n  return {\n    ...input.props,\n    params: params as Record<string, string>,\n    search,\n    searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n  };\n}\n\nfunction parseRouteModuleSchema(\n  schema: { parse?: (value: unknown) => unknown } | undefined,\n  value: unknown,\n  label: string,\n  routePath: string,\n): unknown {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n  }\n}\n\nfunction createRouteStateProps(input: {\n  params: Record<string, string>;\n  searchParamsObject: Record<string, string | string[] | undefined>;\n  path: string;\n  middlewareMap: Map<string, any>;\n  pluginExposedContext: Map<string, any>;\n}): LoadingProps {\n  return {\n    params: input.params,\n    search: input.searchParamsObject,\n    searchParams: Promise.resolve(input.searchParamsObject),\n    path: input.path,\n    middleware: input.middlewareMap.size > 0 ? { data: input.middlewareMap } : undefined,\n    context: input.pluginExposedContext.size > 0 ? { data: input.pluginExposedContext } : undefined,\n  };\n}\n\nexport class ServerRenderer {\n  private config: Required<FarmConfig>;\n  private routeManager: RouteManager;\n  private ssgManifest: SSGPage[] = [];\n  private dataCache = getFarmDataCache();\n  private i18nRuntime?: FarmI18nRuntime;\n  private viteServer?: ViteDevServer;\n  private rendererRuntime!: FarmServerRendererRuntime;\n\n  constructor(\n    config: Required<FarmConfig>,\n    routeManager: RouteManager,\n    i18nRuntime?: FarmI18nRuntime,\n    viteServer?: ViteDevServer,\n  ) {\n    this.config = config;\n    this.routeManager = routeManager;\n    this.i18nRuntime = i18nRuntime;\n    this.viteServer = viteServer;\n    this.loadSSGManifest();\n  }\n\n  async initialize(): Promise<void> {\n    if (this.rendererRuntime) return;\n\n    if (this.config.notFound?.component?.trim()) {\n      resolveFarmNotFoundComponentPath(this.config, getFarmAppDirectories(this.config));\n    }\n\n    const loaded = isReactRenderer(this.config.renderer)\n      ? await import(\"../renderer/react/server\")\n      : this.viteServer\n        ? await this.viteServer.ssrLoadModule(this.config.renderer.server)\n        : await import(\n            pathToFileURL(\n              resolveFarmRendererModule(\n                this.config.root || process.cwd(),\n                this.config.renderer.server,\n              ),\n            ).href\n          );\n    const runtime = loaded as Partial<FarmServerRendererRuntime>;\n    const required = [\"createElement\", \"isValidElement\", \"renderToString\"] as const;\n    for (const key of required) {\n      if (typeof runtime[key] !== \"function\") {\n        throw new Error(\n          `Renderer \\`${this.config.renderer.name}\\` server module must export ${key}().`,\n        );\n      }\n    }\n\n    const capabilities = getFarmRendererCapabilities(this.config.renderer);\n    if (capabilities.streaming.node && typeof runtime.renderToPipeableStream !== \"function\") {\n      throw new Error(\n        `Renderer \\`${this.config.renderer.name}\\` advertises Node streaming but its server module does not export renderToPipeableStream().`,\n      );\n    }\n    if (capabilities.streaming.web && typeof runtime.renderToReadableStream !== \"function\") {\n      throw new Error(\n        `Renderer \\`${this.config.renderer.name}\\` advertises Web streaming but its server module does not export renderToReadableStream().`,\n      );\n    }\n\n    this.rendererRuntime = runtime as FarmServerRendererRuntime;\n    this.routeManager.setRendererRuntime?.(this.rendererRuntime);\n  }\n\n  private createPageBoundary(\n    pageElement: unknown,\n    options: {\n      pageShouldHydrate: boolean;\n      layoutShouldHydrate: boolean;\n      islandStrategy?: FarmIslandStrategy | null;\n    },\n  ): unknown {\n    return this.rendererRuntime.createElement(\n      \"div\",\n      {\n        id: \"__farm_page__\",\n        \"data-farm-segment\": \"page\",\n        \"data-farm-client\": options.pageShouldHydrate ? \"true\" : \"false\",\n        ...(options.layoutShouldHydrate ? { \"data-farm-layout-client\": \"true\" } : {}),\n        \"data-farm-island\": \"page\",\n        \"data-farm-island-strategy\": options.islandStrategy || \"load\",\n      },\n      pageElement,\n    );\n  }\n\n  /// Stylesheets the app imported through JS (fontsource packages, component\n  /// CSS) that the document must link alongside globals.css — see #658.\n  private collectDevStyleHrefs(): string[] {\n    const graph = this.viteServer?.moduleGraph;\n    if (!graph) return [];\n    return collectDevStylesheetUrls(graph.idToModuleMap.values());\n  }\n\n  private collectDevStyleLinks(): string[] {\n    return this.collectDevStyleHrefs().map(\n      (href) => `<link rel=\"stylesheet\" href=\"${escapeHtmlAttribute(href)}\">`,\n    );\n  }\n\n  private createLayoutBoundary(pattern: string, layoutElement: unknown): unknown {\n    return this.rendererRuntime.createElement(\n      \"div\",\n      {\n        \"data-farm-layout-boundary\": \"true\",\n        \"data-farm-layout-pattern\": pattern,\n        style: { display: \"contents\" },\n      },\n      layoutElement,\n    );\n  }\n\n  private wrapClientGraph(element: unknown): unknown {\n    const getIsolatedClientBoundaryModules = this.routeManager.getIsolatedClientBoundaryModules;\n    if (\n      !this.rendererRuntime.wrapClientGraph ||\n      typeof getIsolatedClientBoundaryModules !== \"function\" ||\n      getIsolatedClientBoundaryModules.call(this.routeManager, this.config.root).size === 0\n    ) {\n      return element;\n    }\n    return this.rendererRuntime.wrapClientGraph(element);\n  }\n\n  private async renderElementToCompleteHTML(element: unknown): Promise<string> {\n    const capabilities = getFarmRendererCapabilities(this.config.renderer);\n    const renderToPipeableStream = capabilities.streaming.node\n      ? this.rendererRuntime.renderToPipeableStream\n      : undefined;\n\n    if (renderToPipeableStream) {\n      return await new Promise<string>((resolve, reject) => {\n        const chunks: Buffer[] = [];\n        let started = false;\n        const writable = new Writable({\n          write(chunk, _encoding, callback) {\n            chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n            callback();\n          },\n        });\n        writable.once(\"finish\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n        writable.once(\"error\", reject);\n\n        const stream = renderToPipeableStream(element, {\n          onShellReady() {\n            started = true;\n            stream.pipe(writable);\n          },\n          onShellError(error) {\n            reject(error);\n          },\n          onError(error) {\n            if (!started) reject(error);\n          },\n        });\n      });\n    }\n\n    if (capabilities.streaming.web && this.rendererRuntime.renderToReadableStream) {\n      const stream = await this.rendererRuntime.renderToReadableStream(element);\n      return await readFarmRendererWebStream(stream);\n    }\n\n    return await this.rendererRuntime.renderToString(element);\n  }\n\n  /**\n   * Buffered render carrying document-head markup for renderers that emit it\n   * during render (e.g. <svelte:head>). Other renderers return an empty head.\n   */\n  private async renderElementToDocumentParts(\n    element: unknown,\n  ): Promise<{ html: string; head: string }> {\n    if (this.rendererRuntime.renderToStringWithHead) {\n      const rendered = await this.rendererRuntime.renderToStringWithHead(element);\n      return { html: rendered.html, head: rendered.head || \"\" };\n    }\n    return { html: await this.rendererRuntime.renderToString(element), head: \"\" };\n  }\n\n  /**\n   * Render the route tree used by client navigation without producing a second\n   * document response. Layout markers let the browser preserve the longest\n   * common shell and replace only the first changed boundary.\n   */\n  async renderNavigationFragment(input: FarmNavigationFragmentInput): Promise<string> {\n    await this.initialize();\n    setFarmBasePath(this.config.basePath);\n    setFarmTrailingSlashPreference(this.config.trailingSlash);\n    let element = this.rendererRuntime.createElement(input.PageComponent, input.pageProps);\n    if (input.LoadingComponent) {\n      element = this.rendererRuntime.createElement(\n        this.rendererRuntime.Suspense,\n        {\n          fallback: this.rendererRuntime.createElement(input.LoadingComponent, {\n            params: input.params,\n            path: (input.pageProps as any).path,\n          }),\n        },\n        element,\n      );\n    }\n    if (input.pageShouldHydrate && !input.layoutShouldHydrate) {\n      element = this.wrapClientGraph(element);\n    }\n    element = this.createPageBoundary(element, {\n      pageShouldHydrate: input.pageShouldHydrate,\n      layoutShouldHydrate: input.layoutShouldHydrate,\n      islandStrategy: input.islandStrategy,\n    });\n\n    const layoutStartIndex = Math.max(\n      0,\n      Math.min(input.layoutStartIndex ?? 0, input.layouts.length),\n    );\n    for (let index = input.layouts.length - 1; index >= layoutStartIndex; index--) {\n      const layout = input.layouts[index]!;\n      const LayoutComponent = layout.module.default;\n      if (!LayoutComponent) continue;\n      const slotProps: Record<string, unknown> = {};\n      for (const slot of input.slots || []) {\n        if (slot.ownerPattern !== layout.pattern || !slot.module.default) continue;\n        let slotElement = this.rendererRuntime.createElement(slot.module.default, slot.props);\n        slotElement = this.wrapClientGraph(slotElement);\n        slotProps[slot.name] = this.rendererRuntime.createElement(\n          \"div\",\n          {\n            id: slot.containerId,\n            \"data-farm-route-slot\": slot.name,\n            \"data-farm-slot-owner\": slot.ownerPattern,\n          },\n          slotElement,\n        );\n      }\n      element = this.rendererRuntime.createElement(LayoutComponent, {\n        children: element,\n        params: input.params,\n        ...slotProps,\n      });\n      element = this.createLayoutBoundary(layout.pattern, element);\n    }\n\n    if (input.layoutShouldHydrate) {\n      element = this.wrapClientGraph(element);\n    }\n\n    return this.renderElementToCompleteHTML(await this.wrapWithIntegrationProviders(element));\n  }\n\n  async runWithRequestContext<T>(request: Request, fn: () => T | Promise<T>): Promise<T> {\n    return _runWithCurrentRequest(request, () =>\n      this.i18nRuntime?.config.enabled\n        ? _runWithFarmI18nRequest(this.i18nRuntime, request, fn, {\n            redirect: false,\n          })\n        : fn(),\n    );\n  }\n\n  async resolveRouteContext(input: {\n    request: Request;\n    rawRequest?: FarmRequest;\n    params: Record<string, string>;\n    search: Record<string, string | string[] | undefined>;\n    path: string;\n  }): Promise<unknown> {\n    return resolveFarmRouteContext(this.config, input);\n  }\n\n  /**\n   * Load SSG manifest from build output\n   */\n  private loadSSGManifest(): void {\n    const manifestPath = path.join(this.config.root, this.config.outDir, \"__ssg_manifest.json\");\n    let content: string;\n\n    try {\n      content = fs.readFileSync(manifestPath, \"utf-8\");\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n        return;\n      }\n\n      throw new Error(\n        `Failed to read SSG manifest at ${manifestPath}: ${formatSSGManifestError(error)}`,\n      );\n    }\n\n    this.ssgManifest = parseSSGManifest(content, manifestPath);\n    logger.info(`Loaded SSG manifest: ${this.ssgManifest.length} pages`);\n  }\n\n  /**\n   * Check if a path should be served from SSG cache\n   */\n  private async shouldServeSSG(pathname: string): Promise<SSGPage | null> {\n    const ssgPage = matchSSGPage(pathname, this.ssgManifest);\n    if (!ssgPage) return null;\n\n    const cached = await this.getCachedSSGPage(pathname);\n    if (cached && (await this.dataCache.isStaleAsync(cached))) {\n      // Stale - needs revalidation (serve stale, regenerate in background)\n      this.regenerateSSGPage(ssgPage);\n    }\n\n    return ssgPage;\n  }\n\n  private getSSGCacheKey(urlPath: string): string {\n    return createFarmCacheKey([\"ssg\", normalizeRevalidatePath(urlPath)]);\n  }\n\n  private getPPRCacheKey(pathname: string, search = \"\", locale = \"\"): string {\n    return createFarmCacheKey([\"ppr\", locale, normalizeRevalidatePath(pathname), search]);\n  }\n\n  private getCachedSSGPage(urlPath: string) {\n    return this.dataCache.getEntryAsync<CachedSSGPage>(this.getSSGCacheKey(urlPath), {\n      allowStale: true,\n    });\n  }\n\n  private async cacheSSGPage(\n    page: SSGPage,\n    html: string,\n    options: { document: boolean; createdAt?: number },\n  ): Promise<void> {\n    await this.dataCache.setAsync(\n      this.getSSGCacheKey(page.urlPath),\n      { html, document: options.document },\n      {\n        createdAt: options.createdAt,\n        paths: [page.urlPath],\n        tags: [\"ssg\"],\n        revalidate: page.revalidate ?? false,\n      },\n    );\n  }\n\n  private getCachedPPRShell(pathname: string, search: string, locale = \"\") {\n    return this.dataCache.getEntryAsync<CachedPPRShell>(\n      this.getPPRCacheKey(pathname, search, locale),\n    );\n  }\n\n  private async cachePPRShell(options: PPRShellCacheOptions, html: string): Promise<void> {\n    const key = this.getPPRCacheKey(options.pathname, options.search, options.locale);\n    await this.dataCache.setAsync(\n      key,\n      { html },\n      {\n        paths: [options.pathname],\n        tags: [\"ppr\"],\n        revalidate: options.revalidate ?? false,\n      },\n    );\n    emitFarmEvent({\n      type: \"ppr.shell.cached\",\n      route: options.pathname,\n      key,\n      revalidate: options.revalidate,\n    });\n  }\n\n  private getPPRShellBypassReason(\n    req: FarmRequest,\n    middlewareMap: Map<string, any>,\n    middlewareContext: Map<string, any>,\n    pluginExposedContext: Map<string, any>,\n  ): string | undefined {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      return \"method\";\n    }\n\n    if (req.headers.cookie) {\n      return \"cookie\";\n    }\n\n    if (req.headers.authorization) {\n      return \"authorization\";\n    }\n\n    if (hasRequestHeader(req, \"x-farm-ppr-refresh\")) {\n      return \"refresh\";\n    }\n\n    if (middlewareMap.size > 0) {\n      return \"middleware-data\";\n    }\n\n    if (middlewareContext.size > 0) {\n      return \"middleware-context\";\n    }\n\n    if (pluginExposedContext.size > 0) {\n      return \"plugin-context\";\n    }\n\n    return undefined;\n  }\n\n  private getPPRHeaders(status: \"hit\" | \"miss\" | \"bypass\", revalidate?: number) {\n    const headers: Record<string, string> = {\n      \"X-Farm-PPR\": status,\n    };\n\n    if (status === \"bypass\") {\n      headers[\"Cache-Control\"] = \"private, no-store\";\n      return headers;\n    }\n\n    if (typeof revalidate === \"number\" && revalidate > 0) {\n      headers[\"Cache-Control\"] = `s-maxage=${revalidate}, stale-while-revalidate`;\n    }\n\n    return headers;\n  }\n\n  private serveCachedPPRShell(res: FarmResponse, shell: CachedPPRShell, revalidate?: number): void {\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    for (const [key, value] of Object.entries(this.getPPRHeaders(\"hit\", revalidate))) {\n      res.setHeader(key, value);\n    }\n    res.write(shell.html);\n    res.end();\n  }\n\n  /**\n   * Regenerate an SSG page in the background (ISR)\n   */\n  private async regenerateSSGPage(page: SSGPage): Promise<void> {\n    try {\n      // This runs in the background - don't await\n      setImmediate(async () => {\n        try {\n          const mod = await this.routeManager.loadRouteModule(page.filePath);\n          if (!mod?.default) return;\n\n          const { route, layouts } = this.routeManager.matchRoute(page.urlPath);\n          const layoutModules = await Promise.all(\n            layouts.map((l) => this.routeManager.loadLayoutModule(l.modulePath)),\n          );\n          const routeManifest = this.routeManager.generateClientManifest(this.config.root);\n\n          const PageComponent = mod.default;\n          const pageProps = {\n            params: page.params,\n            searchParams: Promise.resolve({}),\n            path: page.urlPath,\n          };\n\n          let pageElement: any = this.rendererRuntime.createElement(PageComponent, pageProps);\n          const pageMetadata = routeManifest.routes.find(\n            (entry) => entry.pattern === route?.pattern,\n          ) ?? {\n            shouldHydrate: false,\n            islandStrategy: null,\n          };\n          const layoutMetadata = layouts.map(\n            (layout) =>\n              routeManifest.layouts.find((entry) => entry.pattern === layout.pattern) ?? {\n                shouldHydrate: false,\n                islandStrategy: null,\n              },\n          );\n          const layoutShouldHydrate = layoutMetadata.some((metadata) => metadata.shouldHydrate);\n          pageElement = this.createPageBoundary(pageElement, {\n            pageShouldHydrate: pageMetadata.shouldHydrate,\n            layoutShouldHydrate,\n            islandStrategy: pageMetadata.islandStrategy,\n          });\n\n          for (let i = layoutModules.length - 1; i >= 0; i--) {\n            const layoutModule = layoutModules[i];\n            const LayoutComponent = layoutModule.default;\n            pageElement = this.rendererRuntime.createElement(LayoutComponent, {\n              children: pageElement,\n              params: page.params,\n            });\n            pageElement = this.createLayoutBoundary(layouts[i]!.pattern, pageElement);\n          }\n\n          const html = await this.rendererRuntime.renderToString(\n            await this.wrapWithIntegrationProviders(pageElement),\n          );\n\n          // Resolve metadata so the regenerated document keeps its title and\n          // meta/OG tags instead of falling back to the framework default\n          // (\"Farm.js App\"). Without this, a static route served from the ISR\n          // cache loses its metadata after the first revalidation (issue #1018).\n          const mergedMetadata = await this.resolveRouteMetadata({\n            layoutModules,\n            routeModule: mod,\n            pageProps: pageProps as unknown as PageProps,\n            pathname: page.urlPath,\n          });\n          const { title, tags, hasFavicon } = renderMetadataHead(mergedMetadata);\n          const metadataHead = `${\n            hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">\\n  '\n          }<title>${title}</title>${tags}`;\n          const fullDocument = this.createFullHTML(\n            html,\n            pageMetadata.shouldHydrate === true,\n            page.urlPath,\n            metadataHead,\n          );\n\n          await this.cacheSSGPage(page, fullDocument, { document: true });\n\n          logger.info(`ISR: Regenerated ${page.urlPath}`);\n        } catch (error) {\n          logger.error(`ISR regeneration failed for ${page.urlPath}: ${error}`);\n        }\n      });\n    } catch (error) {\n      logger.error(`ISR trigger failed: ${error}`);\n    }\n  }\n\n  /**\n   * Serve a pre-rendered SSG page\n   */\n  private async serveSSGPage(req: FarmRequest, res: FarmResponse, page: SSGPage): Promise<boolean> {\n    // Check cache first (for ISR)\n    const cached = await this.getCachedSSGPage(page.urlPath);\n    if (cached) {\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      res.setHeader(\"X-Farm-SSG\", \"cached\");\n      if (page.revalidate) {\n        res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n      }\n      res.write(\n        cached.value.document\n          ? cached.value.html\n          : this.createFullHTML(cached.value.html, false, page.urlPath),\n      );\n      res.end();\n      return true;\n    }\n\n    // Try to read from file system (production)\n    try {\n      const htmlPath =\n        page.urlPath === \"/\"\n          ? path.join(this.config.root, this.config.outDir, \"client\", \"index.html\")\n          : path.join(this.config.root, this.config.outDir, \"client\", page.urlPath + \".html\");\n\n      if (fs.existsSync(htmlPath)) {\n        const stat = fs.statSync(htmlPath);\n        const html = fs.readFileSync(htmlPath, \"utf-8\");\n        await this.cacheSSGPage(page, html, {\n          document: true,\n          createdAt: stat.mtimeMs,\n        });\n        const fileCacheEntry = await this.getCachedSSGPage(page.urlPath);\n        if (fileCacheEntry && (await this.dataCache.isStaleAsync(fileCacheEntry))) {\n          this.regenerateSSGPage(page);\n        }\n\n        res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n        res.setHeader(\"X-Farm-SSG\", \"file\");\n        if (page.revalidate) {\n          res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n        }\n        res.write(html);\n        res.end();\n        return true;\n      }\n    } catch (error) {\n      logger.error(`Failed to serve SSG page ${page.urlPath}: ${error}`);\n    }\n\n    return false;\n  }\n\n  async renderPage(req: FarmRequest, res: FarmResponse): Promise<void> {\n    await this.initialize();\n    setFarmBasePath(this.config.basePath);\n    setFarmTrailingSlashPreference(this.config.trailingSlash);\n    const request = createWebRequestFromFarmRequest(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const runtime = this.i18nRuntime;\n\n    if (runtime?.config.enabled) {\n      const resolution = runtime.resolveRequest(request);\n      const varyHeaders = getFarmLocaleVaryHeaders(runtime.config, resolution);\n      for (const header of varyHeaders) appendResponseVary(res, header);\n      if (resolution.persist) {\n        appendResponseHeader(\n          res,\n          \"Set-Cookie\",\n          createFarmLocaleCookie(resolution.locale, runtime.config),\n        );\n      }\n      if (resolution.redirect && (request.method === \"GET\" || request.method === \"HEAD\")) {\n        res.statusCode = 307;\n        res.setHeader(\"Location\", resolution.redirect);\n        if (varyHeaders.length > 0) res.setHeader(\"Cache-Control\", \"private, no-store\");\n        res.end();\n        return;\n      }\n    }\n\n    return this.runWithRequestContext(request, () => this.renderPageInContext(req, res));\n  }\n\n  private async renderPageInContext(req: FarmRequest, res: FarmResponse): Promise<void> {\n    const renderStartTime = Date.now();\n    let pathname = \"/\";\n    let params: Record<string, string> = {};\n    let layouts: Array<{ modulePath: string; pattern: string }> = [];\n    let routeSlots: MatchedRouteSlot[] = [];\n    let searchParamsObject: Record<string, string | string[] | undefined> = {};\n    let middlewareMap = new Map<string, any>();\n    let middlewareContext = new Map<string, any>();\n    let pluginExposedContext = new Map<string, any>();\n    let errorBoundaryEntry: { modulePath: string } | null = null;\n    let pprRefreshRoute: string | null = null;\n\n    const completeRender = (status = res.statusCode || 200, route = pathname) => {\n      emitFarmEvent({\n        type: \"render.complete\",\n        route,\n        pathname,\n        status,\n        durationMs: Date.now() - renderStartTime,\n      });\n    };\n\n    try {\n      const url = resolveFarmRequestURL(req, { trustProxy: this.config.server?.trustProxy });\n      pathname = url.pathname;\n      emitFarmEvent({ type: \"render.start\", route: pathname, pathname });\n      searchParamsObject = searchParamsToObject(url.searchParams);\n\n      const metadataRouteMatch = this.routeManager.matchMetadataRoute(pathname);\n      if (metadataRouteMatch) {\n        await this.renderMetadataRoute(req, res, metadataRouteMatch);\n        completeRender(res.statusCode || 200, pathname);\n        return;\n      }\n\n      const metadataImageMatch = this.routeManager.matchMetadataImage(pathname);\n      if (metadataImageMatch) {\n        await this.renderMetadataImage(req, res, {\n          pathname,\n          searchParamsObject,\n          ...metadataImageMatch,\n        });\n        completeRender(res.statusCode || 200, pathname);\n        return;\n      }\n\n      this.applyDeploymentHeaders(req, res);\n\n      const match = this.routeManager.matchRoute(pathname);\n      if (match.route) {\n        const redirectLocation = resolveFarmTrailingSlashRedirect(url, this.config.trailingSlash);\n        if (redirectLocation) {\n          res.statusCode = 308;\n          res.setHeader(\"Location\", redirectLocation);\n          res.end();\n          completeRender(308, match.route.pattern);\n          return;\n        }\n      }\n\n      // Pre-rendered HTML only represents retrieval requests. Other methods must\n      // continue through the live route so their request semantics are preserved.\n      if (shouldServePrerenderedPage(process.env.NODE_ENV, req.method)) {\n        const ssgPage = await this.shouldServeSSG(pathname);\n        if (ssgPage) {\n          const served = await this.serveSSGPage(req, res, ssgPage);\n          if (served) {\n            completeRender(res.statusCode || 200, ssgPage.urlPath);\n            return;\n          }\n        }\n      }\n\n      // Match route\n      const route = match.route;\n      params = match.params;\n      layouts = match.layouts;\n      routeSlots = match.slots ?? [];\n\n      if (!route) {\n        emitFarmEvent({ type: \"route.notFound\", pathname });\n        await this.render404(req, res);\n        completeRender(404);\n        return;\n      }\n\n      emitFarmEvent({\n        type: \"route.matched\",\n        pathname,\n        route: route.pattern,\n        params,\n      });\n\n      const loadingBoundaryEntry = this.routeManager.getMatchingLoading(pathname);\n      errorBoundaryEntry = this.routeManager.getMatchingError(pathname);\n\n      middlewareMap = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_DATA__);\n      middlewareContext = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_CONTEXT__);\n      pluginExposedContext = getRequestContextSnapshot(req as object, {\n        exposedOnly: true,\n      });\n      const currentRequest = createWebRequestFromFarmRequest(req, {\n        trustProxy: this.config.server?.trustProxy,\n      });\n      const routeContext = await this.resolveRouteContext({\n        request: currentRequest,\n        rawRequest: req,\n        params,\n        search: searchParamsObject,\n        path: pathname,\n      });\n\n      // Load route module\n      const routeModule = await this.routeManager.loadRouteModule(route.modulePath);\n\n      if (!routeModule.default) {\n        throw new Error(`Route module ${route.modulePath} does not export a default component`);\n      }\n\n      // Create page props with searchParams as plain object and middleware data\n      const rawPageProps: PageProps = withFarmRouteContext(\n        {\n          params,\n          searchParams: Promise.resolve(searchParamsObject),\n          path: pathname,\n          middleware: middlewareMap.size > 0 ? { data: middlewareMap } : undefined,\n          context: pluginExposedContext.size > 0 ? { data: pluginExposedContext } : undefined,\n        } as PageProps & { search: unknown },\n        routeContext,\n      );\n      const programmaticRouteComponents = (routeModule as any).__farmRouteComponents as\n        | {\n            error?: any;\n            notFound?: any;\n          }\n        | undefined;\n      let PageComponent = routeModule.default;\n      let pageProps: PageProps & {\n        search: unknown;\n        data?: unknown;\n        error?: unknown;\n        __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n        __farmRoutePropsResolved?: true;\n      };\n\n      try {\n        pageProps = await parseRouteModuleProps(routeModule, {\n          props: rawPageProps,\n          search: searchParamsObject,\n          routePath: route.pattern,\n        });\n      } catch (error) {\n        if (isFarmRedirectError(error)) throw error;\n\n        const routeStateProps = {\n          ...rawPageProps,\n          search: searchParamsObject,\n          searchParams: Promise.resolve(searchParamsObject),\n          error,\n        };\n\n        if (isFarmNotFoundError(error) && programmaticRouteComponents?.notFound) {\n          res.statusCode = 404;\n          PageComponent = programmaticRouteComponents.notFound;\n          pageProps = routeStateProps;\n        } else if (programmaticRouteComponents?.error) {\n          res.statusCode = 500;\n          PageComponent = programmaticRouteComponents.error;\n          pageProps = routeStateProps;\n        } else {\n          throw error;\n        }\n      }\n\n      const renderingConfig = await resolveRouteRenderingConfigFromFile(\n        routeModule,\n        route.modulePath,\n        { experimentalPPR: this.config.experimental?.ppr === true },\n      );\n      const pprBypassReason = renderingConfig.ppr\n        ? this.getPPRShellBypassReason(req, middlewareMap, middlewareContext, pluginExposedContext)\n        : undefined;\n      const canCachePPRShell = renderingConfig.ppr && !pprBypassReason;\n      const pprShellOptions: PPRShellCacheOptions | undefined = canCachePPRShell\n        ? {\n            pathname,\n            search: url.search,\n            locale: getFarmI18nClientSnapshot()?.locale ?? \"\",\n            revalidate: renderingConfig.revalidate,\n          }\n        : undefined;\n\n      if (renderingConfig.ppr && pprBypassReason) {\n        emitFarmEvent({\n          type: \"ppr.shell.bypass\",\n          route: pathname,\n          reason: pprBypassReason,\n        });\n        emitFarmEvent({\n          type: \"cache.bypass\",\n          route: pathname,\n          reason: pprBypassReason,\n        });\n\n        if (pprBypassReason === \"refresh\") {\n          pprRefreshRoute = pathname;\n          emitFarmEvent({ type: \"ppr.refresh.start\", route: pathname });\n        }\n      }\n\n      if (pprShellOptions) {\n        // Same locale for the lookup and the later store, so the two cannot diverge.\n        const pprCacheKey = this.getPPRCacheKey(pathname, url.search, pprShellOptions.locale);\n        const cachedPPRShell = await this.getCachedPPRShell(\n          pathname,\n          url.search,\n          pprShellOptions.locale,\n        );\n        if (cachedPPRShell) {\n          emitFarmEvent({\n            type: \"ppr.shell.hit\",\n            route: pathname,\n            key: pprCacheKey,\n          });\n          this.serveCachedPPRShell(res, cachedPPRShell.value, renderingConfig.revalidate);\n          completeRender(res.statusCode || 200, pathname);\n          return;\n        }\n        emitFarmEvent({\n          type: \"ppr.shell.miss\",\n          route: pathname,\n          key: pprCacheKey,\n        });\n      }\n\n      let LoadingFallbackComponent: any = null;\n      if (loadingBoundaryEntry) {\n        const loadingModule = await this.routeManager.loadRouteModule(\n          loadingBoundaryEntry.modulePath,\n        );\n        if (loadingModule.default) {\n          LoadingFallbackComponent = loadingModule.default;\n        }\n      }\n\n      let ErrorFallbackComponent: any = null;\n      if (errorBoundaryEntry) {\n        const errorModule = await this.routeManager.loadRouteModule(errorBoundaryEntry.modulePath);\n        if (errorModule.default) {\n          ErrorFallbackComponent = errorModule.default;\n        }\n      }\n\n      // Hydration decisions are compiled into a manifest and reused on requests.\n      // Development HMR invalidates this cache when a route module changes.\n      const routeManifest = this.routeManager.generateClientManifest(this.config.root);\n      const routeManifestEntry = routeManifest.routes.find(\n        (entry) => entry.pattern === route.pattern,\n      );\n      const moduleMetadata =\n        routeManifestEntry || getClientModuleMetadata(route.modulePath, this.config.root);\n      const isClientComponent = moduleMetadata.isClientComponent;\n      const renderedRouteSlots = await Promise.all(\n        routeSlots.map(async (slot) => {\n          const slotModule = await this.routeManager.loadRouteModule(slot.route.modulePath);\n          if (!slotModule.default) {\n            throw new Error(\n              `Route slot \"${slot.name}\" module ${slot.route.modulePath} does not export a default component`,\n            );\n          }\n\n          const slotContext = await this.resolveRouteContext({\n            request: currentRequest,\n            rawRequest: req,\n            params: slot.params,\n            search: searchParamsObject,\n            path: pathname,\n          });\n          const rawSlotProps = withFarmRouteContext(\n            {\n              params: slot.params,\n              searchParams: Promise.resolve(searchParamsObject),\n              path: pathname,\n              middleware: middlewareMap.size > 0 ? { data: middlewareMap } : undefined,\n              context: pluginExposedContext.size > 0 ? { data: pluginExposedContext } : undefined,\n            } as PageProps & { search: unknown },\n            slotContext,\n          );\n          const slotProps = await parseRouteModuleProps(slotModule, {\n            props: rawSlotProps,\n            search: searchParamsObject,\n            routePath: slot.route.pattern,\n          });\n          const metadata = routeManifest.slots.find(\n            (entry) =>\n              entry.name === slot.name &&\n              entry.ownerPattern === slot.ownerPattern &&\n              entry.pattern === slot.route.pattern,\n          ) ?? {\n            isClientComponent: false,\n            shouldHydrate: false,\n          };\n\n          return {\n            ...slot,\n            module: slotModule,\n            props: slotProps,\n            isClientComponent: metadata.isClientComponent,\n            shouldHydrate: metadata.shouldHydrate,\n          };\n        }),\n      );\n      const shouldHydrate = moduleMetadata.shouldHydrate;\n      if (moduleMetadata.suppressedAsyncHydration) {\n        warnSuppressedAsyncHydrationOnce(route.modulePath);\n      }\n      const layoutHydrationMetadata = layouts.map((layout) => {\n        const manifestEntry = routeManifest.layouts.find(\n          (entry) => entry.pattern === layout.pattern,\n        ) as\n          | {\n              isClientComponent?: boolean;\n              shouldHydrate?: boolean;\n              islandStrategy?: \"load\" | \"interaction\" | \"visible\" | \"idle\" | null;\n              hasIsolatedClientBoundaries?: boolean;\n            }\n          | undefined;\n        if (typeof manifestEntry?.shouldHydrate === \"boolean\") {\n          return {\n            isClientComponent: manifestEntry.isClientComponent === true,\n            shouldHydrate: manifestEntry.shouldHydrate,\n            islandStrategy: manifestEntry.islandStrategy ?? null,\n            ...(manifestEntry.hasIsolatedClientBoundaries === true\n              ? { hasIsolatedClientBoundaries: true }\n              : {}),\n          };\n        }\n        return {\n          isClientComponent: false,\n          shouldHydrate: false,\n          islandStrategy: null,\n        };\n      });\n      const shouldHydrateLayout = layoutHydrationMetadata.some(\n        (metadata) => metadata.shouldHydrate,\n      );\n      const clientLayouts = layouts.map((layout, index) => ({\n        pattern: layout.pattern,\n        modulePath: toViteModuleId(layout.modulePath, this.config.root),\n        shouldHydrate: layoutHydrationMetadata[index]?.shouldHydrate === true,\n        islandStrategy: layoutHydrationMetadata[index]?.islandStrategy ?? null,\n        ...(layoutHydrationMetadata[index]?.hasIsolatedClientBoundaries === true\n          ? { hasIsolatedClientBoundaries: true }\n          : {}),\n      }));\n      const hydrationStrategies = [\n        ...(shouldHydrate && moduleMetadata.islandStrategy ? [moduleMetadata.islandStrategy] : []),\n        ...layoutHydrationMetadata.flatMap((metadata) =>\n          metadata.shouldHydrate && metadata.islandStrategy ? [metadata.islandStrategy] : [],\n        ),\n      ];\n      const hydrationIslandStrategy = hydrationStrategies.every(\n        (strategy) => strategy === hydrationStrategies[0],\n      )\n        ? (hydrationStrategies[0] ?? \"load\")\n        : \"load\";\n      const hasHydratableRouteSlots = renderedRouteSlots.some(\n        (slot) => slot.isClientComponent || slot.shouldHydrate,\n      );\n      const hasIsolatedClientBoundaries =\n        routeManifestEntry?.hasIsolatedClientBoundaries === true ||\n        layoutHydrationMetadata.some((metadata) => metadata.hasIsolatedClientBoundaries === true);\n\n      (req as any).__FARM_PAGE_PATH__ = route.modulePath;\n      (req as any).__FARM_ROUTE__ = pathname;\n      (req as any).__FARM_IS_CLIENT_COMPONENT__ = isClientComponent;\n      (req as any).__FARM_PAGE_SHOULD_HYDRATE__ = shouldHydrate;\n      (req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ = shouldHydrateLayout;\n      (req as any).__FARM_LAYOUTS__ = clientLayouts;\n      if (hasIsolatedClientBoundaries) {\n        (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\n      }\n      (req as any).__FARM_SHOULD_HYDRATE__ =\n        shouldHydrate || shouldHydrateLayout || hasIsolatedClientBoundaries;\n      (req as any).__FARM_ISLAND_STRATEGY__ = hydrationIslandStrategy;\n      (req as any).__FARM_HAS_HYDRATABLE_ROUTE_SLOTS__ = hasHydratableRouteSlots;\n      (req as any).__FARM_LOADING_MODULE_PATH__ = loadingBoundaryEntry?.modulePath\n        ? toViteModuleId(loadingBoundaryEntry.modulePath, this.config.root)\n        : null;\n      (req as any).__FARM_ROUTE_SLOTS__ = renderedRouteSlots.map((slot) => ({\n        name: slot.name,\n        ownerPattern: slot.ownerPattern,\n        containerId: slot.containerId,\n        interception: slot.interception,\n        fallback: slot.fallback,\n        modulePath: slot.route.modulePath,\n        isClientComponent: slot.isClientComponent,\n        shouldHydrate: slot.shouldHydrate,\n        props: {\n          params: slot.props.params,\n          search: (slot.props as any).search,\n          searchParams: (slot.props as any).search,\n          ...(\"data\" in slot.props ? { data: (slot.props as any).data } : {}),\n          ...((slot.props as any).__farmCanonicalPath\n            ? { __farmCanonicalPath: (slot.props as any).__farmCanonicalPath }\n            : {}),\n          ...((slot.props as any).__farmRoutePropsResolved\n            ? { __farmRoutePropsResolved: true }\n            : {}),\n          path: pathname,\n        },\n      }));\n      // Store pageProps for client-side hydration (serializable version - no Promises)\n      (req as any).__FARM_PROPS__ = {\n        params: pageProps.params,\n        search: (pageProps as any).search,\n        searchParams: (pageProps as any).search,\n        ...(\"data\" in pageProps ? { data: (pageProps as any).data } : {}),\n        ...((pageProps as any).__farmCanonicalPath\n          ? { __farmCanonicalPath: (pageProps as any).__farmCanonicalPath }\n          : {}),\n        ...((pageProps as any).__farmRoutePropsResolved ? { __farmRoutePropsResolved: true } : {}),\n        path: pathname,\n        middleware:\n          middlewareMap.size > 0\n            ? {\n                data: Object.fromEntries(middlewareMap),\n              }\n            : undefined,\n        context:\n          pluginExposedContext.size > 0\n            ? {\n                data: Object.fromEntries(pluginExposedContext),\n              }\n            : undefined,\n      };\n\n      // Load layout modules\n      const layoutModules = await Promise.all(\n        layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n      );\n\n      const mergedMetadata = await this.resolveRouteMetadata({\n        layoutModules,\n        routeModule,\n        pageProps,\n        pathname,\n      });\n\n      // Store metadata on request for renderWithSSR\n      (req as any).__FARM_METADATA__ = mergedMetadata;\n\n      // Get middleware data for AsyncLocalStorage\n      const middlewareDataForContext = middlewareMap;\n\n      await _runWithMiddlewareData(middlewareDataForContext, async () => {\n        await _runWithMiddlewareContext(middlewareContext, async () => {\n          await _runWithCurrentRequest(currentRequest, async () => {\n            let pageElement: any = this.rendererRuntime.createElement(PageComponent, pageProps);\n\n            if (LoadingFallbackComponent) {\n              const loadingFallback = this.rendererRuntime.createElement(LoadingFallbackComponent, {\n                ...createRouteStateProps({\n                  params,\n                  searchParamsObject,\n                  path: pathname,\n                  middlewareMap,\n                  pluginExposedContext,\n                }),\n              });\n\n              pageElement = this.rendererRuntime.createElement(\n                this.rendererRuntime.Suspense,\n                { fallback: loadingFallback },\n                pageElement,\n              );\n            }\n\n            // A route-wide page owns every compiled client component beneath\n            // its React root. Keep shared leaf modules as ordinary components\n            // here even when an isolated layout also imports the same module.\n            if ((isClientComponent || shouldHydrate) && !shouldHydrateLayout) {\n              pageElement = this.wrapClientGraph(pageElement);\n            }\n\n            // Every route gets a stable HTML boundary. Server-only pages keep\n            // native markup with no React root; interactive pages hydrate this\n            // exact boundary.\n            pageElement = this.createPageBoundary(pageElement, {\n              pageShouldHydrate: isClientComponent || shouldHydrate,\n              layoutShouldHydrate: shouldHydrateLayout,\n              islandStrategy: hydrationIslandStrategy,\n            });\n\n            let wrappedElement: any = pageElement;\n            for (let i = layoutModules.length - 1; i >= 0; i--) {\n              const layoutModule = layoutModules[i];\n              const layoutEntry = layouts[i];\n              const LayoutComponent = layoutModule.default;\n              const slotProps: Record<string, any> = {};\n              for (const slot of renderedRouteSlots) {\n                if (slot.ownerPattern !== layoutEntry.pattern) continue;\n\n                let slotElement = this.rendererRuntime.createElement(\n                  slot.module.default,\n                  slot.props,\n                );\n                slotElement = this.wrapClientGraph(slotElement);\n                slotElement = this.rendererRuntime.createElement(\n                  \"div\",\n                  {\n                    id: slot.containerId,\n                    \"data-farm-route-slot\": slot.name,\n                    \"data-farm-slot-owner\": slot.ownerPattern,\n                  },\n                  slotElement,\n                );\n                slotProps[slot.name] = slotElement;\n              }\n              wrappedElement = this.rendererRuntime.createElement(LayoutComponent, {\n                children: wrappedElement,\n                params,\n                ...slotProps,\n              });\n              wrappedElement = this.createLayoutBoundary(layoutEntry.pattern, wrappedElement);\n            }\n\n            if (shouldHydrateLayout) {\n              wrappedElement = this.wrapClientGraph(wrappedElement);\n            }\n\n            if (ErrorFallbackComponent && this.rendererRuntime.ErrorBoundary) {\n              wrappedElement = this.rendererRuntime.createElement(\n                this.rendererRuntime.ErrorBoundary,\n                {\n                  Fallback: ErrorFallbackComponent,\n                  fallbackProps: {\n                    ...createRouteStateProps({\n                      params,\n                      searchParamsObject,\n                      path: pathname,\n                      middlewareMap,\n                      pluginExposedContext,\n                    }),\n                  },\n                },\n                wrappedElement,\n              );\n            }\n\n            const integratedElement = await this.wrapWithIntegrationProviders(wrappedElement);\n            const pprHeaders = renderingConfig.ppr\n              ? this.getPPRHeaders(pprShellOptions ? \"miss\" : \"bypass\", renderingConfig.revalidate)\n              : undefined;\n\n            // Render with middleware data available\n            await this.renderWithSSR(\n              integratedElement,\n              req,\n              res,\n              () => {\n                _clearCurrentMiddlewareData();\n                _clearCurrentMiddlewareContext();\n              },\n              {\n                responseHeaders: pprHeaders,\n                routeManifest,\n                captureStaticShell: Boolean(pprShellOptions),\n                observabilityRoute: pathname,\n                onSuspenseHoleDetected: pprShellOptions\n                  ? () =>\n                      emitFarmEvent({\n                        type: \"ppr.suspense.holeDetected\",\n                        route: pathname,\n                      })\n                  : undefined,\n                onComplete:\n                  pprShellOptions && req.method !== \"HEAD\"\n                    ? (html) => this.cachePPRShell(pprShellOptions, html)\n                    : undefined,\n              },\n            );\n            if (pprRefreshRoute) {\n              emitFarmEvent({\n                type: \"ppr.refresh.complete\",\n                route: pprRefreshRoute,\n                durationMs: Date.now() - renderStartTime,\n              });\n            }\n            completeRender(res.statusCode || 200, pathname);\n          });\n        });\n      });\n    } catch (caughtError) {\n      let error = caughtError;\n\n      if (isWebResponse(error)) {\n        if (!res.headersSent && !(res as any).writableEnded) {\n          await sendWebResponse(res, error);\n        } else if (!(res as any).writableEnded) {\n          res.end();\n        }\n        completeRender(error.status, pathname);\n        return;\n      }\n\n      if (isFarmRedirectError(error)) {\n        const redirect = getFarmRedirectError(error)!;\n        const snapshot = getFarmI18nClientSnapshot();\n        const redirectUrl =\n          snapshot && redirect.url.startsWith(\"/\") && !redirect.url.startsWith(\"//\")\n            ? localizeFarmHref(redirect.url, snapshot.locale, snapshot)\n            : redirect.url;\n        emitFarmEvent({\n          type: \"route.redirect\",\n          from: pathname,\n          to: redirectUrl,\n          status: redirect.status,\n        });\n        if (!res.headersSent && !(res as any).writableEnded) {\n          res.statusCode = redirect.status;\n          res.setHeader(\"Location\", redirectUrl);\n          res.end();\n        } else if (!(res as any).writableEnded) {\n          res.end();\n        }\n        completeRender(redirect.status, pathname);\n        return;\n      }\n\n      if (isFarmNotFoundError(error)) {\n        emitFarmEvent({ type: \"route.notFound\", pathname });\n        if (!res.headersSent && !(res as any).writableEnded) {\n          try {\n            await this.render404(req, res);\n            completeRender(404, pathname);\n            return;\n          } catch (notFoundRenderError) {\n            error = notFoundRenderError;\n          }\n        } else {\n          if (!(res as any).writableEnded) {\n            res.end();\n          }\n          completeRender(404, pathname);\n          return;\n        }\n      }\n\n      emitFarmEvent({ type: \"render.error\", route: pathname, error });\n      const errorStatus = resolveDefaultErrorStatus(error);\n      if (pprRefreshRoute) {\n        emitFarmEvent({\n          type: \"ppr.refresh.error\",\n          route: pprRefreshRoute,\n          error,\n        });\n      }\n      logger.error(`Error rendering page: ${error}`);\n\n      if (res.headersSent || (res as any).writableEnded) {\n        if (!(res as any).writableEnded) {\n          res.end();\n        }\n        return;\n      }\n\n      if (errorBoundaryEntry) {\n        const rendered = await this.renderRouteErrorBoundary(req, res, {\n          pathname,\n          params,\n          layouts,\n          searchParamsObject,\n          middlewareMap,\n          middlewareContext,\n          pluginExposedContext,\n          error,\n          statusCode: errorStatus,\n          errorModulePath: errorBoundaryEntry.modulePath,\n        });\n\n        if (rendered) {\n          return;\n        }\n      }\n\n      await this.renderError(req, res, error, errorStatus);\n    }\n  }\n\n  private async wrapWithIntegrationProviders(element: any): Promise<any> {\n    const providers = getIntegrationProviders(this.config.integrations);\n    let wrapped = element;\n\n    for (let i = providers.length - 1; i >= 0; i--) {\n      const provider = providers[i];\n      if (provider.component || provider.type === \"clerk\") {\n        if (!isReactRenderer(this.config.renderer)) {\n          throw new Error(\n            `Integration provider \\`${provider.type}\\` currently requires the React renderer.`,\n          );\n        }\n        let ProviderComponent;\n        if (isFarmIntegrationProviderComponentReference(provider.component)) {\n          const providerModuleId = provider.component.module.startsWith(\".\")\n            ? toViteModuleId(\n                path.resolve(this.config.root, provider.component.module),\n                this.config.root,\n              )\n            : provider.component.module;\n          const providerModule = this.viteServer\n            ? await this.viteServer.ssrLoadModule(providerModuleId)\n            : await importRuntimeModule(\n                provider.component.module.startsWith(\".\")\n                  ? pathToFileURL(path.resolve(this.config.root, provider.component.module)).href\n                  : provider.component.module,\n              );\n          ProviderComponent = providerModule[provider.component.export || \"default\"];\n        } else if (typeof provider.component === \"function\") {\n          ProviderComponent = provider.component;\n        } else if (provider.type === \"clerk\") {\n          if (!cachedClerkProvider) {\n            cachedClerkProvider = await importRuntimeModule(\"@clerk/react\");\n          }\n          ProviderComponent = cachedClerkProvider!.ClerkProvider;\n        } else {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` has an invalid component reference.`,\n          );\n        }\n        if (!ProviderComponent) {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` did not export its configured component.`,\n          );\n        }\n\n        wrapped = this.rendererRuntime.createElement(\n          ProviderComponent,\n          provider.props || {},\n          wrapped,\n        );\n      }\n    }\n\n    return wrapped;\n  }\n\n  private async resolveRouteMetadata(options: {\n    layoutModules: Array<Record<string, any>>;\n    routeModule: RouteModule;\n    pageProps: PageProps;\n    pathname: string;\n  }): Promise<Record<string, any>> {\n    let metadata: Record<string, any> = {};\n\n    for (const layoutModule of options.layoutModules) {\n      metadata = mergeMetadata(metadata, layoutModule.metadata);\n      if (typeof layoutModule.generateMetadata === \"function\") {\n        metadata = mergeMetadata(\n          metadata,\n          await layoutModule.generateMetadata({\n            params: options.pageProps.params,\n          }),\n        );\n      }\n    }\n\n    metadata = mergeMetadata(metadata, (options.routeModule as any).metadata);\n    if (typeof (options.routeModule as any).generateMetadata === \"function\") {\n      metadata = mergeMetadata(\n        metadata,\n        await (options.routeModule as any).generateMetadata(options.pageProps),\n      );\n    }\n\n    if (!metadata.manifest) {\n      const manifestMatch = this.routeManager.getMatchingMetadataRoute(\n        options.pathname,\n        \"manifest\",\n      );\n      if (manifestMatch) {\n        const rawHref = this.routeManager.resolveMetadataRoutePath(\n          manifestMatch.metadata,\n          manifestMatch.params,\n        );\n        const snapshot = getFarmI18nClientSnapshot();\n        const localizedHref = snapshot\n          ? localizeFarmHref(rawHref, snapshot.locale, snapshot)\n          : rawHref;\n        metadata.manifest = applyFarmBasePath(localizedHref, this.config.basePath);\n      }\n    }\n\n    for (const kind of [\"opengraph\", \"twitter\"] as const) {\n      const reference = await this.resolveMetadataImageReference(kind, options.pathname);\n      if (reference) {\n        metadata = addMetadataImageReference(metadata, reference);\n      }\n    }\n\n    return metadata;\n  }\n\n  private async resolveMetadataImageReference(\n    kind: MetadataImageKind,\n    pathname: string,\n  ): Promise<FarmMetadataImageReference | null> {\n    const match = this.routeManager.getMatchingMetadataImage(pathname, kind);\n    if (!match) return null;\n\n    const rawHref = this.routeManager.resolveMetadataImagePath(match.image, match.params);\n    const snapshot = getFarmI18nClientSnapshot();\n    const localizedHref = snapshot ? localizeFarmHref(rawHref, snapshot.locale, snapshot) : rawHref;\n    const href = applyFarmBasePath(localizedHref, this.config.basePath);\n    const reference: FarmMetadataImageReference = {\n      kind,\n      href,\n    };\n\n    if (match.image.sourceType === \"static\" && match.image.staticInfo) {\n      return {\n        ...reference,\n        width: match.image.staticInfo.width,\n        height: match.image.staticInfo.height,\n        alt: match.image.staticInfo.alt,\n        contentType: match.image.staticInfo.contentType,\n      };\n    }\n\n    try {\n      const imageModule = await this.routeManager.loadRouteModule(match.image.modulePath);\n      const size = (imageModule as any).size;\n      if (size && typeof size === \"object\") {\n        reference.width = typeof size.width === \"number\" ? size.width : undefined;\n        reference.height = typeof size.height === \"number\" ? size.height : undefined;\n      }\n      if (typeof (imageModule as any).alt === \"string\") {\n        reference.alt = (imageModule as any).alt;\n      }\n      if (typeof (imageModule as any).contentType === \"string\") {\n        reference.contentType = (imageModule as any).contentType;\n      }\n    } catch (error) {\n      logger.warn(`Failed to read ${kind} image metadata for ${pathname}: ${error}`);\n    }\n\n    return reference;\n  }\n\n  private async renderMetadataRoute(\n    req: FarmRequest,\n    res: FarmResponse,\n    match: NonNullable<ReturnType<RouteManager[\"matchMetadataRoute\"]>>,\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    try {\n      const routeModule = await this.routeManager.loadRouteModule(match.metadata.modulePath);\n      if (routeModule.default === undefined) {\n        throw new Error(\n          `Metadata route module ${match.metadata.modulePath} does not export a default value or handler`,\n        );\n      }\n\n      const request = createWebRequestFromFarmRequest(req, {\n        trustProxy: this.config.server?.trustProxy,\n      });\n      const url = new URL(request.url);\n      const value =\n        typeof routeModule.default === \"function\"\n          ? await (routeModule.default as any)({\n              request,\n              params: match.params,\n              searchParams: url.searchParams,\n              path: match.routePath,\n            })\n          : routeModule.default;\n      const response = createFarmMetadataRouteResponse(match.metadata.kind, value, routeModule, {\n        method,\n      });\n      await sendWebResponse(res as any, response);\n    } catch (error) {\n      logger.error(`Metadata route render failed for ${match.metadata.modulePath}: ${error}`);\n      await sendWebResponse(\n        res as any,\n        new Response(\"Internal Server Error\", {\n          status: 500,\n          headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n        }),\n      );\n    }\n  }\n\n  private async renderMetadataImage(\n    req: FarmRequest,\n    res: FarmResponse,\n    options: {\n      pathname: string;\n      pagePath: string;\n      params: Record<string, string>;\n      searchParamsObject: Record<string, string | string[] | undefined>;\n      image: {\n        modulePath: string;\n        kind: MetadataImageKind;\n        sourceType?: \"module\" | \"static\";\n        staticInfo?: StaticMetadataImageInfo;\n      };\n    },\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    if (options.image.sourceType === \"static\") {\n      if (!options.image.staticInfo) {\n        throw new Error(`Static metadata image ${options.image.modulePath} is missing file info`);\n      }\n      await this.writeStaticMetadataImageResponse(req, res, {\n        modulePath: options.image.modulePath,\n        staticInfo: options.image.staticInfo,\n      });\n      return;\n    }\n\n    const imageModule = await this.routeManager.loadRouteModule(options.image.modulePath);\n    if (!imageModule.default) {\n      throw new Error(\n        `Metadata image module ${options.image.modulePath} does not export a default component or handler`,\n      );\n    }\n\n    const imageProps: PageProps = {\n      params: options.params,\n      searchParams: Promise.resolve(options.searchParamsObject),\n      path: options.pagePath,\n    };\n    const handlerResult =\n      typeof imageModule.default === \"function\"\n        ? await (imageModule.default as any)(imageProps)\n        : imageModule.default;\n\n    await this.writeMetadataImageResponse(req, res, handlerResult, imageModule);\n  }\n\n  private async writeMetadataImageResponse(\n    req: FarmRequest,\n    res: FarmResponse,\n    value: unknown,\n    imageModule: RouteModule,\n  ): Promise<void> {\n    const ifNoneMatch = req.headers[\"if-none-match\"];\n    const response = await createFarmMetadataImageResponse(value, imageModule, {\n      method: req.method,\n      ifNoneMatch: Array.isArray(ifNoneMatch) ? ifNoneMatch[0] : ifNoneMatch,\n    });\n    await sendWebResponse(res as any, response);\n  }\n\n  private async writeStaticMetadataImageResponse(\n    req: FarmRequest,\n    res: FarmResponse,\n    image: { modulePath: string; staticInfo: StaticMetadataImageInfo },\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    const etag = `\"${image.staticInfo.hash}\"`;\n    const requestUrl = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const isVersioned = requestUrl.searchParams.get(\"v\") === image.staticInfo.hash;\n\n    res.setHeader(\"Content-Type\", image.staticInfo.contentType);\n    res.setHeader(\"Content-Length\", image.staticInfo.byteLength);\n    res.setHeader(\"ETag\", etag);\n    res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n    res.setHeader(\n      \"Cache-Control\",\n      isVersioned ? \"public, max-age=31536000, immutable\" : \"public, max-age=0, must-revalidate\",\n    );\n\n    if (matchesFarmIfNoneMatch(req.headers[\"if-none-match\"], etag)) {\n      res.statusCode = 304;\n      res.end();\n      return;\n    }\n\n    res.statusCode = res.statusCode || 200;\n    if (method === \"HEAD\") {\n      res.end();\n      return;\n    }\n\n    res.write(await fs.promises.readFile(image.modulePath));\n    res.end();\n  }\n\n  private async renderRouteErrorBoundary(\n    req: FarmRequest,\n    res: FarmResponse,\n    options: {\n      pathname: string;\n      params: Record<string, string>;\n      layouts: Array<{ modulePath: string }>;\n      searchParamsObject: Record<string, string | string[] | undefined>;\n      middlewareMap: Map<string, any>;\n      middlewareContext: Map<string, any>;\n      pluginExposedContext: Map<string, any>;\n      error: unknown;\n      statusCode: number;\n      errorModulePath: string;\n    },\n  ): Promise<boolean> {\n    try {\n      if (res.headersSent || (res as any).writableEnded) {\n        if (!(res as any).writableEnded) {\n          res.end();\n        }\n        return true;\n      }\n\n      const errorModule = await this.routeManager.loadRouteModule(options.errorModulePath);\n      if (!errorModule.default) {\n        return false;\n      }\n\n      const ErrorComponent = errorModule.default;\n      const errorElement = this.rendererRuntime.createElement(ErrorComponent, {\n        ...createRouteStateProps({\n          params: options.params,\n          searchParamsObject: options.searchParamsObject,\n          path: options.pathname,\n          middlewareMap: options.middlewareMap,\n          pluginExposedContext: options.pluginExposedContext,\n        }),\n        error: options.error,\n        reset: () => {},\n      });\n\n      let wrapped: any = errorElement;\n      const layoutModules = await Promise.all(\n        options.layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n      );\n      for (let i = layoutModules.length - 1; i >= 0; i--) {\n        const LayoutComponent = layoutModules[i].default;\n        wrapped = this.rendererRuntime.createElement(LayoutComponent, {\n          children: wrapped,\n          params: options.params,\n        });\n      }\n\n      wrapped = await this.wrapWithIntegrationProviders(wrapped);\n\n      const html = await _runWithMiddlewareData(options.middlewareMap, () =>\n        _runWithMiddlewareContext(options.middlewareContext, () =>\n          this.rendererRuntime.renderToString(wrapped),\n        ),\n      );\n      res.statusCode = options.statusCode;\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      // A PPR shell failure leaves the \"miss\" caching headers (s-maxage,\n      // stale-while-revalidate, X-Farm-PPR) on res. Error responses must not be\n      // cached by shared/CDN caches, so clear them here, matching renderError.\n      res.setHeader(\"Cache-Control\", \"private, no-store\");\n      res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n      if (typeof res.removeHeader === \"function\") {\n        res.removeHeader(\"X-Farm-PPR\");\n      }\n      res.write(this.createFullHTML(html, false, options.pathname));\n      res.end();\n      return true;\n    } catch (renderError) {\n      logger.warn(`Failed to render route-level error boundary: ${renderError}`);\n      return false;\n    }\n  }\n\n  private async renderBufferedSSR(\n    element: unknown,\n    req: FarmRequest,\n    res: FarmResponse,\n    clearMiddlewareData?: () => void,\n    options: {\n      responseHeaders?: Record<string, string> | undefined;\n      routeManifest?: ReturnType<RouteManager[\"generateClientManifest\"]>;\n      onComplete?: (html: string) => void | Promise<void>;\n      captureStaticShell?: boolean;\n      observabilityRoute?: string;\n      onSuspenseHoleDetected?: () => void;\n    } = {},\n  ): Promise<void> {\n    const startedAt = Date.now();\n    const route = options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n    emitFarmEvent({ type: \"render.stream.start\", route });\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    for (const [key, value] of Object.entries(options.responseHeaders || {})) {\n      res.setHeader(key, value);\n    }\n\n    try {\n      const manifest =\n        options.routeManifest ?? this.routeManager.generateClientManifest(this.config.root);\n      const clientManifest = {\n        clientEntry: \"/@farm/client.js\",\n        routes: {} as Record<string, any>,\n        layouts: {} as Record<string, any>,\n        slots: [] as Array<Record<string, any>>,\n        sharedAssets: [\n          {\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n          },\n          ...this.collectDevStyleHrefs().map((href) => ({\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href },\n          })),\n        ],\n      };\n\n      for (const routeEntry of manifest.routes) {\n        clientManifest.routes[routeEntry.pattern] = {\n          modulePath: routeEntry.modulePath,\n          pattern: routeEntry.pattern,\n          segments: routeEntry.segments,\n          search: routeEntry.search,\n          isClientComponent: routeEntry.isClientComponent,\n          shouldHydrate: routeEntry.shouldHydrate,\n          islandStrategy: routeEntry.islandStrategy,\n          renderPlan: routeEntry.renderPlan,\n          preloads: [routeEntry.modulePath],\n          assets: [],\n        };\n      }\n      for (const layoutEntry of manifest.layouts) {\n        clientManifest.layouts[layoutEntry.pattern] = {\n          modulePath: layoutEntry.modulePath,\n          pattern: layoutEntry.pattern,\n          shouldHydrate: layoutEntry.shouldHydrate,\n          islandStrategy: layoutEntry.islandStrategy,\n          preloads: [layoutEntry.modulePath],\n          assets: [],\n        };\n      }\n      for (const slotEntry of manifest.slots ?? []) {\n        clientManifest.slots.push({\n          ...slotEntry,\n          preloads: [slotEntry.modulePath],\n          assets: [],\n        });\n      }\n\n      const routeSlots = ((req as any).__FARM_ROUTE_SLOTS__ || []).map(\n        (slot: Record<string, any>) => ({\n          ...slot,\n          modulePath:\n            typeof slot.modulePath === \"string\"\n              ? toViteModuleId(slot.modulePath, this.config.root)\n              : slot.modulePath,\n        }),\n      );\n      const deferredProps = prepareDeferredData({\n        page: (req as any).__FARM_PROPS__ || {},\n        slots: routeSlots,\n      });\n      const pagePath = (req as any).__FARM_PAGE_PATH__;\n      const relativePath = pagePath\n        ? toViteModuleId(pagePath, this.config.root)\n        : \"/src/app/page.tsx\";\n      const deploymentId = this.getDeploymentId();\n      const bootstrapScript = `<script>\nwindow.__FARM_PROPS__ = ${serializeInlineValue((deferredProps.data as any).page)};\nwindow.__FARM_ROUTE_SLOTS__ = ${serializeInlineValue((deferredProps.data as any).slots)};\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(deploymentId)};\nwindow.__FARM_PATH__ = ${JSON.stringify((req as any).__FARM_ROUTE__ || req.url || \"/\")};\nwindow.__FARM_IS_CLIENT__ = ${JSON.stringify((req as any).__FARM_IS_CLIENT_COMPONENT__ === true)};\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_PAGE_SHOULD_HYDRATE__ === true)};\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ === true)};\nwindow.__FARM_LAYOUTS__ = ${JSON.stringify((req as any).__FARM_LAYOUTS__ || [])};\nwindow.__FARM_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_SHOULD_HYDRATE__ === true)};\n${\n  (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true\n    ? \"window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\"\n    : \"\"\n}\nwindow.__FARM_ISLAND_STRATEGY__ = ${JSON.stringify((req as any).__FARM_ISLAND_STRATEGY__ || \"load\")};\nwindow.__FARM_PAGE_MODULE__ = ${JSON.stringify(relativePath)};\nwindow.__FARM_LOADING_MODULE__ = ${JSON.stringify((req as any).__FARM_LOADING_MODULE_PATH__ || null)};\nwindow.__FARM_MANIFEST__ = ${JSON.stringify(clientManifest)};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${getFarmI18nClientSnapshot() ? `window.__FARM_I18N__ = ${serializeInlineValue(getFarmI18nClientSnapshot())};` : \"\"}\n</script>`;\n      const deferredScript = createDeferredHydrationScript(deferredProps.records);\n      const rendererHydrationScript = this.rendererRuntime.generateHydrationScript?.() || \"\";\n      const { html: content, head: rendererHead } =\n        await this.renderElementToDocumentParts(element);\n      const {\n        title,\n        tags: metaTags,\n        hasFavicon,\n        hasExplicitTitle,\n      } = renderMetadataHead((req as any).__FARM_METADATA__, {\n        pathname: getFarmMetadataPathname(req),\n        jsonLd: this.config.agent?.jsonLd,\n      });\n      // A renderer-emitted <title> (e.g. <svelte:head>) must take effect: the\n      // first <title> in a document wins, so the fallback framework title is\n      // suppressed when the renderer supplies one. Explicit metadata titles\n      // still come first and win.\n      const documentTitleTag =\n        !hasExplicitTitle && /<title[\\s>]/i.test(rendererHead) ? \"\" : `<title>${title}</title>`;\n      const i18nSnapshot = getFarmI18nClientSnapshot();\n      const alternateTags = i18nSnapshot\n        ? renderI18nAlternateLinks((req as any).__FARM_ROUTE__ || req.url || \"/\", i18nSnapshot)\n        : \"\";\n      const themeDocument = createFarmThemeDocumentParts(\n        this.config.theme,\n        this.config.basePath,\n        getFarmTheme(),\n      );\n\n      // A layout that returns its own full `<html>` document is composed as the\n      // document (Farm assets merged in) rather than nested inside the shell,\n      // matching the production build and avoiding invalid nested documents.\n      const fullDocument = extractFarmFullDocument(content);\n      let html: string;\n      if (fullDocument) {\n        warnFarmFullDocumentLayout();\n        html = composeFarmFullDocument(fullDocument, {\n          htmlAttributes: `${i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"}${themeDocument.attributes}`,\n          headAssets: [\n            themeDocument.head,\n            `<meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">`,\n            metaTags,\n            alternateTags,\n            rendererHead,\n            renderFarmFontDevHead(this.config.root || process.cwd()),\n            `<link rel=\"stylesheet\" href=\"/src/app/globals.css\">`,\n            ...this.collectDevStyleLinks(),\n            `<script type=\"module\" src=\"/@vite/client\"></script>`,\n            rendererHydrationScript,\n            bootstrapScript,\n          ]\n            .filter(Boolean)\n            .join(\"\\n  \"),\n          bodyFooter: [deferredScript, `<script type=\"module\" src=\"/@farm/client.js\"></script>`]\n            .filter(Boolean)\n            .join(\"\\n  \"),\n        });\n      } else {\n        html = `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n          i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n        }${themeDocument.attributes}>\n<head>\n  ${themeDocument.head}\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">\n  ${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  ${documentTitleTag}${metaTags}${alternateTags}${rendererHead ? `\\n  ${rendererHead}` : \"\"}\n  ${renderFarmFontDevHead(this.config.root || process.cwd())}\n  <link rel=\"stylesheet\" href=\"/src/app/globals.css\">${this.collectDevStyleLinks()\n    .map((l) => `\\n  ${l}`)\n    .join(\"\")}\n  <script type=\"module\" src=\"/@vite/client\"></script>\n  ${rendererHydrationScript}\n  ${bootstrapScript}\n</head>\n<body class=\"\">\n  <div id=\"root\">${content}</div>\n  ${deferredScript}\n  <script type=\"module\" src=\"/@farm/client.js\"></script>\n</body>\n</html>`;\n      }\n\n      emitFarmEvent({\n        type: \"render.stream.shellReady\",\n        route,\n        durationMs: Date.now() - startedAt,\n      });\n      if ((req.method || \"GET\").toUpperCase() !== \"HEAD\") res.write(html);\n      res.end();\n      await options.onComplete?.(html);\n      emitFarmEvent({\n        type: \"render.stream.complete\",\n        route,\n        durationMs: Date.now() - startedAt,\n      });\n    } catch (error) {\n      emitFarmEvent({ type: \"render.error\", route, error });\n      throw error;\n    } finally {\n      clearMiddlewareData?.();\n    }\n  }\n\n  private async renderWithSSR(\n    element: any,\n    req: FarmRequest,\n    res: FarmResponse,\n    clearMiddlewareData?: () => void,\n    options: {\n      responseHeaders?: Record<string, string> | undefined;\n      routeManifest?: ReturnType<RouteManager[\"generateClientManifest\"]>;\n      onComplete?: (html: string) => void | Promise<void>;\n      captureStaticShell?: boolean;\n      observabilityRoute?: string;\n      onSuspenseHoleDetected?: () => void;\n    } = {},\n  ): Promise<void> {\n    const renderToPipeableStream = this.rendererRuntime.renderToPipeableStream;\n    const fullDocumentRouteKey =\n      options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n    // A full-document layout can't be composed once the stream's shell is\n    // flushed, so a route previously seen to render one is served through the\n    // buffered path, which produces a valid single document.\n    if (!renderToPipeableStream || fullDocumentRoutes.has(fullDocumentRouteKey)) {\n      return this.renderBufferedSSR(element, req, res, clearMiddlewareData, options);\n    }\n\n    return new Promise((resolve, reject) => {\n      const streamStartTime = Date.now();\n      const observabilityRoute =\n        options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n      const deploymentId = this.getDeploymentId();\n      emitFarmEvent({ type: \"render.stream.start\", route: observabilityRoute });\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      for (const [key, value] of Object.entries(options.responseHeaders || {})) {\n        res.setHeader(key, value);\n      }\n      const htmlParts: string[] = [];\n      const staticShellParts: string[] | undefined = options.captureStaticShell ? [] : undefined;\n      let staticShellClosed = false;\n      let suspenseHoleEmitted = false;\n      let didError = false;\n\n      // Get the page path for client-side hydration\n      const pagePath = (req as any).__FARM_PAGE_PATH__;\n      const isClientComponent = (req as any).__FARM_IS_CLIENT_COMPONENT__ === true;\n      const relativePath = pagePath\n        ? toViteModuleId(pagePath, this.config.root)\n        : \"/src/app/page.tsx\";\n\n      // Generate manifest for client-side SPA navigation (TanStack Start pattern)\n      // This manifest is inlined in HTML - no separate file or API endpoint\n      const manifest =\n        options.routeManifest ?? this.routeManager.generateClientManifest(this.config.root);\n\n      // Convert to object format for client\n      const clientManifest = {\n        clientEntry: \"/@farm/client.js\",\n        routes: {} as Record<string, any>,\n        layouts: {} as Record<string, any>,\n        slots: [] as Array<Record<string, any>>,\n        sharedAssets: [\n          {\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n          },\n          ...this.collectDevStyleHrefs().map((href) => ({\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href },\n          })),\n        ],\n      };\n\n      // Convert routes array to object keyed by pattern\n      for (const routeEntry of manifest.routes) {\n        clientManifest.routes[routeEntry.pattern] = {\n          modulePath: routeEntry.modulePath,\n          pattern: routeEntry.pattern,\n          segments: routeEntry.segments,\n          search: routeEntry.search,\n          isClientComponent: routeEntry.isClientComponent,\n          shouldHydrate: routeEntry.shouldHydrate,\n          islandStrategy: routeEntry.islandStrategy,\n          renderPlan: routeEntry.renderPlan,\n          preloads: [routeEntry.modulePath],\n          assets: [],\n        };\n      }\n\n      // Convert layouts array to object\n      for (const layoutEntry of manifest.layouts) {\n        clientManifest.layouts[layoutEntry.pattern] = {\n          modulePath: layoutEntry.modulePath,\n          pattern: layoutEntry.pattern,\n          shouldHydrate: layoutEntry.shouldHydrate,\n          islandStrategy: layoutEntry.islandStrategy,\n          preloads: [layoutEntry.modulePath],\n          assets: [],\n        };\n      }\n\n      for (const slotEntry of manifest.slots ?? []) {\n        clientManifest.slots.push({\n          ...slotEntry,\n          preloads: [slotEntry.modulePath],\n          assets: [],\n        });\n      }\n\n      // Inject page props, component info, and MANIFEST for client-side SPA\n      // __FARM_MANIFEST__ contains the full route manifest (TanStack Start pattern)\n      const routeSlotPayload = ((req as any).__FARM_ROUTE_SLOTS__ || []).map(\n        (slot: Record<string, any>) => ({\n          ...slot,\n          modulePath:\n            typeof slot.modulePath === \"string\"\n              ? toViteModuleId(slot.modulePath, this.config.root)\n              : slot.modulePath,\n        }),\n      );\n      const deferredProps = prepareDeferredData({\n        page: (req as any).__FARM_PROPS__ || {},\n        slots: routeSlotPayload,\n      });\n      const propsScript = `<script>\nwindow.__FARM_PROPS__ = ${serializeInlineValue((deferredProps.data as any).page)};\nwindow.__FARM_ROUTE_SLOTS__ = ${serializeInlineValue((deferredProps.data as any).slots)};\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(deploymentId)};\nwindow.__FARM_PATH__ = ${JSON.stringify((req as any).__FARM_ROUTE__ || req.url || \"/\")};\nwindow.__FARM_IS_CLIENT__ = ${JSON.stringify(isClientComponent)};\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = ${JSON.stringify(\n        (req as any).__FARM_PAGE_SHOULD_HYDRATE__ === true,\n      )};\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = ${JSON.stringify(\n        (req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ === true,\n      )};\nwindow.__FARM_LAYOUTS__ = ${JSON.stringify((req as any).__FARM_LAYOUTS__ || [])};\nwindow.__FARM_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_SHOULD_HYDRATE__ === true)};\n${\n  (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true\n    ? \"window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\"\n    : \"\"\n}\nwindow.__FARM_ISLAND_STRATEGY__ = ${JSON.stringify((req as any).__FARM_ISLAND_STRATEGY__ || \"load\")};\nwindow.__FARM_PAGE_MODULE__ = ${JSON.stringify(relativePath)};\nwindow.__FARM_LOADING_MODULE__ = ${JSON.stringify(\n        (req as any).__FARM_LOADING_MODULE_PATH__ || null,\n      )};\nwindow.__FARM_MANIFEST__ = ${JSON.stringify(clientManifest)};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${getFarmI18nClientSnapshot() ? `window.__FARM_I18N__ = ${serializeInlineValue(getFarmI18nClientSnapshot())};` : \"\"}\n</script>`;\n      const hydrationClickQueueScript =\n        isClientComponent ||\n        (req as any).__FARM_SHOULD_HYDRATE__ === true ||\n        (req as any).__FARM_HAS_HYDRATABLE_ROUTE_SLOTS__ === true\n          ? createPreHydrationClickQueueScript()\n          : \"\";\n\n      const {\n        title,\n        tags: metaTags,\n        hasFavicon,\n      } = renderMetadataHead((req as any).__FARM_METADATA__, {\n        pathname: getFarmMetadataPathname(req),\n        jsonLd: this.config.agent?.jsonLd,\n      });\n      const i18nSnapshot = getFarmI18nClientSnapshot();\n      const i18nAlternateTags = i18nSnapshot\n        ? renderI18nAlternateLinks((req as any).__FARM_ROUTE__ || req.url || \"/\", i18nSnapshot)\n        : \"\";\n      const fontHead = renderFarmFontDevHead(this.config.root || process.cwd());\n      const themeDocument = createFarmThemeDocumentParts(\n        this.config.theme,\n        this.config.basePath,\n        getFarmTheme(),\n      );\n\n      // React 19: ensure root is a single DOM node so streaming starts early (avoids Fragment delay)\n      const streamRoot = this.rendererRuntime.createElement(\n        \"div\",\n        { style: { display: \"contents\" } },\n        element,\n      );\n      const devStyleLinks = this.collectDevStyleLinks();\n      const { pipe } = renderToPipeableStream(streamRoot, {\n        onShellReady() {\n          const shellReadyMs = Date.now() - streamStartTime;\n          emitFarmEvent({\n            type: \"render.stream.shellReady\",\n            route: observabilityRoute,\n            durationMs: shellReadyMs,\n          });\n          if (process.env.FARM_VERBOSE) {\n            console.log(`[FARM STREAM] onShellReady at ${shellReadyMs}ms`);\n          }\n          const shell = `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n            i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n          }${themeDocument.attributes}>\n<head>\n  ${themeDocument.head}\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">\n  ${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  <title>${title}</title>${metaTags}${i18nAlternateTags}\n  ${fontHead}\n  <link rel=\"stylesheet\" href=\"/src/app/globals.css\" />${devStyleLinks\n    .map((l) => `\\n  ${l}`)\n    .join(\"\")}\n  <script type=\"module\" src=\"/@vite/client\"></script>\n  ${propsScript}\n  ${hydrationClickQueueScript}\n</head>\n<body class=\"\">\n  <div id=\"root\">`;\n          htmlParts.push(shell);\n          staticShellParts?.push(shell);\n\n          let firstChunk = true;\n          let checkedFullDocument = false;\n          const writableStream = new Writable({\n            write(chunk, encoding, callback) {\n              if (firstChunk && process.env.FARM_VERBOSE) {\n                console.log(`[FARM STREAM] first pipe chunk at ${Date.now() - streamStartTime}ms`);\n                firstChunk = false;\n              }\n              const chunkText = Buffer.isBuffer(chunk) ? chunk.toString() : String(chunk);\n              // The shell was already flushed, so this response still nests the\n              // document; record the route so later requests take the buffered\n              // path (which composes it correctly) and warn the developer once.\n              if (!checkedFullDocument) {\n                checkedFullDocument = true;\n                if (opensFarmFullDocument(chunkText)) {\n                  fullDocumentRoutes.add(fullDocumentRouteKey);\n                  warnFarmFullDocumentLayout();\n                }\n              }\n              htmlParts.push(chunkText);\n\n              if (staticShellParts && !staticShellClosed) {\n                const dynamicIndex = findPPRDynamicChunkIndex(chunkText);\n                if (dynamicIndex >= 0) {\n                  if (dynamicIndex > 0) {\n                    staticShellParts.push(chunkText.slice(0, dynamicIndex));\n                  }\n                  staticShellClosed = true;\n                  if (!suspenseHoleEmitted) {\n                    suspenseHoleEmitted = true;\n                    options.onSuspenseHoleDetected?.();\n                  }\n                } else {\n                  staticShellParts.push(chunkText);\n                }\n              }\n\n              res.write(chunk, encoding, () => {\n                if (typeof (res as any).flush === \"function\") (res as any).flush();\n                callback();\n              });\n            },\n            final(callback) {\n              const suspenseRevealFallback = `<script>(function(){function moveFragment(srcId,placeholderId){var src=document.getElementById(srcId),ph=document.getElementById(placeholderId);if(!src||!ph||!ph.parentNode)return false;while(src.firstChild)ph.parentNode.insertBefore(src.firstChild,ph);ph.parentNode.removeChild(ph);if(src.parentNode)src.parentNode.removeChild(src);return true}function revealBoundary(boundaryId,sectionId){var boundary=document.getElementById(boundaryId),section=document.getElementById(sectionId);if(!boundary||!section||!boundary.parentNode)return false;var start=boundary.previousSibling;if(!start||start.nodeType!==8)return false;var parent=boundary.parentNode;var node=boundary;var depth=0;while(node){if(node.nodeType===8){var data=node.data;if(data===\"/$\"||data===\"/&\"){if(depth===0)break;depth--;}else if(data===\"$\"||data===\"$?\"||data===\"$~\"||data===\"$!\"||data===\"&\"){depth++;}}var next=node.nextSibling;parent.removeChild(node);node=next;}while(section.firstChild)parent.insertBefore(section.firstChild,node);if(section.parentNode)section.parentNode.removeChild(section);start.data=\"$\";return true}var tries=0;var timer=setInterval(function(){var changed=false;document.querySelectorAll('div[id^=\"S:\"]').forEach(function(section){var suffix=section.id.slice(2);changed=moveFragment('S:'+suffix,'P:'+suffix)||changed;});document.querySelectorAll('template[id^=\"B:\"]').forEach(function(boundary){var suffix=boundary.id.slice(2);changed=revealBoundary('B:'+suffix,'S:'+suffix)||changed;});tries++;if(tries>80||(!document.querySelector('template[id^=\"B:\"]')&&!document.querySelector('template[id^=\"P:\"]'))){clearInterval(timer);}},50);})();</script>`;\n              const footer = createDocumentFooter({\n                suspenseRevealFallback,\n                deferredHydrationScript: createDeferredHydrationScript(deferredProps.records),\n              });\n              htmlParts.push(footer);\n              res.write(footer);\n              res.end();\n              callback();\n              if (clearMiddlewareData) {\n                clearMiddlewareData();\n              }\n              if (!didError && options.onComplete) {\n                if (staticShellParts) {\n                  staticShellParts.push(\n                    createDocumentFooter({\n                      suspenseRevealFallback,\n                      refreshPPR: staticShellClosed,\n                    }),\n                  );\n                }\n\n                const cachedHtml = staticShellParts\n                  ? staticShellParts.join(\"\")\n                  : htmlParts.join(\"\");\n                Promise.resolve(options.onComplete(cachedHtml)).catch((error) => {\n                  logger.warn(`Failed to cache PPR shell: ${error}`);\n                });\n              }\n              emitFarmEvent({\n                type: \"render.stream.complete\",\n                route: observabilityRoute,\n                durationMs: Date.now() - streamStartTime,\n              });\n              resolve();\n            },\n          });\n\n          // Queue the shell immediately, then start piping the Suspense stream.\n          // Waiting for the write callback can delay the fallback until the whole\n          // response is ready under some dev-server wrappers.\n          res.write(shell);\n          if (typeof (res as any).flush === \"function\") {\n            (res as any).flush();\n          }\n          pipe(writableStream);\n        },\n        onShellError(error) {\n          didError = true;\n          if (!isWebResponse(error) && !isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n            logger.error(`SSR shell error: ${error}`);\n            emitFarmEvent({\n              type: \"render.error\",\n              route: observabilityRoute,\n              error,\n            });\n          }\n\n          if (clearMiddlewareData) {\n            clearMiddlewareData();\n          }\n\n          reject(error);\n        },\n        onError(error) {\n          didError = true;\n          if (!isWebResponse(error) && !isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n            logger.error(`SSR streaming error: ${error}`);\n            emitFarmEvent({\n              type: \"render.error\",\n              route: observabilityRoute,\n              error,\n            });\n          }\n        },\n      });\n    });\n  }\n\n  private async render404(req: FarmRequest, res: FarmResponse): Promise<void> {\n    res.statusCode = 404;\n\n    const pathname = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    }).pathname;\n\n    // Agents that navigate in Markdown (a `.md` URL or `Accept: text/markdown`)\n    // get a Markdown error body instead of the HTML not-found shell.\n    const acceptHeader = req.headers.accept;\n    const accept = Array.isArray(acceptHeader) ? acceptHeader.join(\",\") : acceptHeader;\n    if (farmRequestWantsMarkdown(pathname, accept)) {\n      res.setHeader(\"Content-Type\", FARM_MARKDOWN_CONTENT_TYPE);\n      res.setHeader(\"X-Farm-Markdown-Error\", \"404\");\n      res.setHeader(\"Cache-Control\", \"no-store\");\n      res.end(createFarmMarkdownErrorBody(404, pathname, this.config.basePath || \"/\"));\n      return;\n    }\n\n    try {\n      // Look for custom not-found page\n      const appDir = path.join(this.config.root, this.config.srcDir, \"app\");\n      const notFoundExtensions = getFarmRendererComponentExtensions(this.config.renderer);\n      const notFoundPath = resolveFarmNotFoundComponentPath(\n        this.config,\n        getFarmAppDirectories(this.config),\n      );\n\n      if (notFoundPath) {\n        // Use routeManager to load the module (uses Vite's ssrLoadModule in dev)\n        const notFoundModule = await this.routeManager.loadRouteModule(notFoundPath);\n        const NotFoundComponent = notFoundModule.default;\n\n        if (NotFoundComponent) {\n          // Look for root layout\n          let LayoutComponent: any = null;\n          for (const ext of notFoundExtensions) {\n            const layoutPath = path.join(appDir, `layout${ext}`);\n            if (fs.existsSync(layoutPath)) {\n              const layoutModule = await this.routeManager.loadLayoutModule(layoutPath);\n              LayoutComponent = layoutModule.default;\n              break;\n            }\n          }\n\n          // Render the 404 page\n          let element: any = this.rendererRuntime.createElement(NotFoundComponent, { pathname });\n\n          // Wrap with layout if available\n          if (LayoutComponent) {\n            element = this.rendererRuntime.createElement(LayoutComponent, {\n              children: element,\n            });\n          }\n\n          element = await this.wrapWithIntegrationProviders(element);\n\n          // Render to string\n          const content = await this.rendererRuntime.renderToString(element);\n\n          const html = this.createFullHTML(content, false, pathname);\n          res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n          res.write(html);\n          res.end();\n          return;\n        }\n      }\n    } catch (error) {\n      throw new Error(`Failed to render custom 404 page: ${error}`);\n    }\n\n    // Render the shared adaptive fallback when the app does not provide its own page.\n    const homeHref = escapeHtmlAttribute(applyFarmBasePath(\"/\", this.config.basePath));\n    const defaultContent = `<style>${DEFAULT_NOT_FOUND_STYLES}</style><main class=\"farm-default-not-found\" aria-labelledby=\"farm-default-not-found-title\" aria-describedby=\"farm-default-not-found-description\"><div class=\"farm-default-not-found__content\"><h1 id=\"farm-default-not-found-title\" class=\"farm-default-not-found__code\">404</h1><p id=\"farm-default-not-found-description\" class=\"farm-default-not-found__description\">Not found</p><a class=\"farm-default-not-found__home\" href=\"${homeHref}\">GO HOME</a></div></main>`;\n\n    const html = this.createFullHTML(defaultContent, false, pathname);\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    res.write(html);\n    res.end();\n  }\n\n  private async renderError(\n    req: FarmRequest,\n    res: FarmResponse,\n    error: unknown,\n    statusCode = 500,\n  ): Promise<void> {\n    if (res.headersSent || (res as any).writableEnded) {\n      if (!(res as any).writableEnded) {\n        res.end();\n      }\n      return;\n    }\n\n    res.statusCode = statusCode;\n    const isDev = process.env.NODE_ENV === \"development\";\n    const requestUrl = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const diagnostics = isDev\n      ? createDefaultErrorDiagnostics(error, this.config.root || process.cwd())\n      : undefined;\n    const statusText = getDefaultErrorStatusText(statusCode);\n    const content = createDefaultErrorMarkup({\n      statusCode,\n      statusText,\n      requestPath: requestUrl.pathname,\n      method: req.method || \"GET\",\n      message: diagnostics?.message,\n      errorName: diagnostics?.name,\n      stack: diagnostics?.stack,\n      sourceFrame: diagnostics?.sourceFrame,\n      development: isDev,\n      farmVersion: FARM_VERSION,\n      nodeVersion: process.version,\n      mode: isDev ? \"development\" : \"production\",\n    });\n\n    const html = this.createFullHTML(\n      content,\n      false,\n      requestUrl.pathname,\n      `${statusCode} - ${statusText}`,\n    );\n\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    res.setHeader(\"Cache-Control\", \"private, no-store\");\n    res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n    res.write(html);\n    res.end();\n  }\n\n  private createFullHTML(\n    content: string,\n    isClientComponent = false,\n    requestPath = \"/\",\n    metadataHead?: string,\n  ): string {\n    const i18nSnapshot = getFarmI18nClientSnapshot();\n    const clientScript = isClientComponent\n      ? `  <script type=\"module\" src=\"/@farm/client.js\"></script>`\n      : \"\";\n    const integrationManifestScript = `<script>\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(this.getDeploymentId())};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${i18nSnapshot ? `window.__FARM_I18N__ = ${serializeInlineValue(i18nSnapshot)};` : \"\"}\n</script>`;\n    const alternateLinks = i18nSnapshot ? renderI18nAlternateLinks(requestPath, i18nSnapshot) : \"\";\n    const fontHead = renderFarmFontDevHead(this.config.root || process.cwd());\n    const themeDocument = createFarmThemeDocumentParts(\n      this.config.theme,\n      this.config.basePath,\n      getFarmTheme(),\n    );\n    const rendererHydrationScript = this.rendererRuntime.generateHydrationScript?.() || \"\";\n\n    // A layout that returns its own full `<html>` document must not be nested\n    // inside this shell (that yields invalid nested `<html>`/`<head>`/`<body>`).\n    // Compose Farm's managed assets into the layout's document instead, matching\n    // the production build's `hasFullDocument` path.\n    const fullDocument = extractFarmFullDocument(content);\n    if (fullDocument) {\n      warnFarmFullDocumentLayout();\n      return composeFarmFullDocument(fullDocument, {\n        htmlAttributes: `${i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"}${themeDocument.attributes}`,\n        headAssets: [\n          themeDocument.head,\n          `<meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(this.getDeploymentId())}\">`,\n          metadataHead,\n          alternateLinks,\n          fontHead,\n          `<link rel=\"stylesheet\" href=\"/src/app/globals.css\" />`,\n          ...this.collectDevStyleLinks(),\n          `<script type=\"module\" src=\"/@vite/client\"></script>`,\n          rendererHydrationScript,\n          integrationManifestScript,\n        ]\n          .filter(Boolean)\n          .join(\"\\n  \"),\n        bodyFooter: clientScript.trim(),\n      });\n    }\n\n    return `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n      i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n    }${themeDocument.attributes}>\n<head>\n  ${themeDocument.head}\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(this.getDeploymentId())}\">\n  ${metadataHead ?? '<link rel=\"icon\" href=\"data:,\">\\n  <title>Farm.js App</title>'}${alternateLinks}\n  ${fontHead}\n  <link rel=\"stylesheet\" href=\"/src/app/globals.css\" />${this.collectDevStyleLinks()\n    .map((l) => `\\n  ${l}`)\n    .join(\"\")}\n  <script type=\"module\" src=\"/@vite/client\"></script>\n  ${rendererHydrationScript}\n  ${integrationManifestScript}\n</head>\n<body class=\"\">\n  <div id=\"root\">${content}</div>\n${clientScript}\n</body>\n</html>`;\n  }\n\n  private applyDeploymentHeaders(req: FarmRequest, res: FarmResponse): void {\n    const deploymentId = this.getDeploymentId();\n    res.setHeader(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n    if ((req.method || \"GET\").toUpperCase() !== \"GET\") return;\n\n    const forwardedProto = req.headers[\"x-forwarded-proto\"];\n    const isSecure =\n      (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)\n        ?.split(\",\")[0]\n        ?.trim() === \"https\" || Boolean((req.socket as any)?.encrypted);\n    const cookie = createFarmDeploymentCookie(deploymentId, this.config.basePath || \"/\", isSecure);\n    const existing = res.getHeader(\"Set-Cookie\");\n\n    if (Array.isArray(existing)) {\n      res.setHeader(\"Set-Cookie\", [...existing, cookie]);\n    } else if (existing) {\n      res.setHeader(\"Set-Cookie\", [String(existing), cookie]);\n    } else {\n      res.setHeader(\"Set-Cookie\", cookie);\n    }\n  }\n\n  private getDeploymentId(): string {\n    return this.config.deploymentId || \"development\";\n  }\n}\n","export const DEFAULT_FARM_DEVTOOLS_SHORTCUT = \"mod+shift+.\";\nexport const FARM_DEVTOOLS_PATH = \"/__farm/devtools\";\nexport const FARM_DEVTOOLS_LAUNCH_PARAM = \"__farm_devtools\";\n\n/**\n * Configuration for the built-in DevTools dashboard. The dashboard is deprecated in favor\n * of the `@farm.js/devtools` plugin, which reuses this configuration for enablement and\n * the keyboard shortcut. Both options keep working while the built-in UI remains available.\n */\nexport interface FarmDevtoolsConfig {\n  /** Enable the development-only DevTools UI and runtime endpoints. */\n  enabled?: boolean;\n  /** Keyboard shortcut used to toggle DevTools, or false to disable the shortcut. */\n  shortcut?: string | false;\n}\n\nexport type FarmDevtoolsUserConfig = boolean | FarmDevtoolsConfig;\n\nexport interface ResolvedFarmDevtoolsConfig {\n  enabled: boolean;\n  shortcut: string | false;\n}\n\nexport function resolveFarmDevtoolsConfig(\n  config: FarmDevtoolsUserConfig | ResolvedFarmDevtoolsConfig | undefined,\n  mode: \"development\" | \"production\" = \"development\",\n): ResolvedFarmDevtoolsConfig {\n  if (mode !== \"development\" || config === false) {\n    return { enabled: false, shortcut: false };\n  }\n\n  const options = config === true || config === undefined ? {} : config;\n  const enabled = options.enabled ?? true;\n\n  if (!enabled) {\n    return { enabled: false, shortcut: false };\n  }\n\n  const shortcut =\n    typeof options.shortcut === \"string\" && options.shortcut.trim()\n      ? options.shortcut\n          .toLowerCase()\n          .split(\"+\")\n          .map((part) => part.trim())\n          .filter(Boolean)\n          .join(\"+\")\n      : options.shortcut === false\n        ? false\n        : DEFAULT_FARM_DEVTOOLS_SHORTCUT;\n\n  return { enabled: true, shortcut };\n}\n","export type FarmBuildActivityPosition = \"bottom-right\" | \"bottom-left\" | \"top-right\" | \"top-left\";\n\nexport interface FarmDevIndicatorsConfig {\n  /** Show build and HMR activity in the browser during development. */\n  buildActivity?: boolean;\n  /** Corner used by the build activity indicator. */\n  buildActivityPosition?: FarmBuildActivityPosition;\n}\n\nexport interface ResolvedFarmDevIndicatorsConfig {\n  buildActivity: boolean;\n  buildActivityPosition: FarmBuildActivityPosition;\n}\n\nexport function resolveFarmDevIndicatorsConfig(\n  config: FarmDevIndicatorsConfig | undefined,\n  mode: \"development\" | \"production\" = \"development\",\n): ResolvedFarmDevIndicatorsConfig {\n  return {\n    buildActivity: mode === \"development\" && (config?.buildActivity ?? true),\n    buildActivityPosition: config?.buildActivityPosition ?? \"bottom-right\",\n  };\n}\n\nexport function generateFarmDevIndicatorsClientRuntime(\n  config: ResolvedFarmDevIndicatorsConfig,\n): string {\n  if (!config.buildActivity) return \"\";\n\n  const position = {\n    \"bottom-right\": \"right: 16px; bottom: 16px;\",\n    \"bottom-left\": \"left: 16px; bottom: 16px;\",\n    \"top-right\": \"right: 16px; top: 16px;\",\n    \"top-left\": \"left: 16px; top: 16px;\",\n  }[config.buildActivityPosition];\n  const styles = `\n    #__farm_build_activity__ {\n      position: fixed;\n      ${position}\n      z-index: 2147483645;\n      display: inline-flex;\n      align-items: center;\n      gap: 7px;\n      min-height: 30px;\n      padding: 0 10px;\n      border: 1px solid rgb(255 255 255 / 0.16);\n      border-radius: 999px;\n      background: rgb(17 17 17 / 0.9);\n      box-shadow: 0 8px 24px rgb(0 0 0 / 0.2);\n      color: rgb(250 250 250);\n      font: 500 12px/1 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n      letter-spacing: -0.01em;\n      opacity: 0;\n      pointer-events: none;\n      transform: translateY(4px);\n      transition: opacity 120ms ease-out, transform 120ms ease-out;\n    }\n    #__farm_build_activity__[data-visible=\"true\"] {\n      opacity: 1;\n      transform: translateY(0);\n    }\n    #__farm_build_activity__::before {\n      width: 8px;\n      height: 8px;\n      border: 1.5px solid rgb(255 255 255 / 0.32);\n      border-top-color: currentColor;\n      border-radius: 50%;\n      content: \"\";\n      animation: farm-build-activity-spin 650ms linear infinite;\n    }\n    #__farm_build_activity__[data-state=\"ready\"]::before {\n      border-color: currentColor;\n      animation: none;\n    }\n    #__farm_build_activity__[data-state=\"error\"] {\n      border-color: rgb(248 113 113 / 0.55);\n      color: rgb(254 202 202);\n    }\n    #__farm_build_activity__[data-state=\"error\"]::before {\n      border-color: currentColor;\n      animation: none;\n    }\n    @keyframes farm-build-activity-spin { to { transform: rotate(360deg); } }\n    @media (prefers-reduced-motion: reduce) {\n      #__farm_build_activity__ { transition: none; }\n      #__farm_build_activity__::before { animation-duration: 1.4s; }\n    }\n  `;\n\n  return `\nif (import.meta.hot) {\n  (() => {\n    const hot = import.meta.hot;\n    const indicatorId = \"__farm_build_activity__\";\n    const styleId = \"__farm_build_activity_styles__\";\n    const runtimeKey = \"__FARM_BUILD_ACTIVITY_RUNTIME__\";\n    const reloadMarker = \"__FARM_BUILD_ACTIVITY_RELOADING__\";\n    let hideTimer;\n\n    const ensureIndicator = () => {\n      let style = document.getElementById(styleId);\n      if (!style) {\n        style = document.createElement(\"style\");\n        style.id = styleId;\n        style.textContent = ${JSON.stringify(styles)};\n        document.head.appendChild(style);\n      }\n\n      let indicator = document.getElementById(indicatorId);\n      if (!indicator) {\n        indicator = document.createElement(\"div\");\n        indicator.id = indicatorId;\n        indicator.setAttribute(\"role\", \"status\");\n        indicator.setAttribute(\"aria-live\", \"polite\");\n        document.body.appendChild(indicator);\n      }\n      return indicator;\n    };\n\n    const show = (state, label) => {\n      window.clearTimeout(hideTimer);\n      const indicator = ensureIndicator();\n      indicator.dataset.state = state;\n      indicator.dataset.visible = \"true\";\n      indicator.textContent = label;\n    };\n    const hide = () => {\n      const indicator = document.getElementById(indicatorId);\n      if (indicator) indicator.dataset.visible = \"false\";\n    };\n    const onBeforeUpdate = () => show(\"building\", \"Farm updating\");\n    const onAfterUpdate = () => {\n      show(\"ready\", \"Farm ready\");\n      hideTimer = window.setTimeout(hide, 500);\n    };\n    const onError = () => show(\"error\", \"Build failed\");\n    const onBeforeFullReload = () => {\n      try {\n        window.sessionStorage.setItem(reloadMarker, \"1\");\n      } catch {}\n      show(\"building\", \"Farm updating\");\n    };\n\n    window[runtimeKey]?.dispose?.();\n    ensureIndicator();\n    let completedReload = false;\n    try {\n      completedReload = window.sessionStorage.getItem(reloadMarker) === \"1\";\n      window.sessionStorage.removeItem(reloadMarker);\n    } catch {}\n    if (completedReload) onAfterUpdate();\n    else hide();\n    hot.on(\"vite:beforeUpdate\", onBeforeUpdate);\n    hot.on(\"vite:afterUpdate\", onAfterUpdate);\n    hot.on(\"vite:error\", onError);\n    hot.on(\"vite:beforeFullReload\", onBeforeFullReload);\n    window[runtimeKey] = {\n      dispose() {\n        window.clearTimeout(hideTimer);\n        hot.off(\"vite:beforeUpdate\", onBeforeUpdate);\n        hot.off(\"vite:afterUpdate\", onAfterUpdate);\n        hot.off(\"vite:error\", onError);\n        hot.off(\"vite:beforeFullReload\", onBeforeFullReload);\n        document.getElementById(indicatorId)?.remove();\n      },\n    };\n  })();\n}\n`;\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmIntegration } from \"./integrations\";\n\nexport interface FarmAuthEmailAndPasswordConfig {\n  /** Require a verified email before creating a session. @default false */\n  requireEmailVerification?: boolean;\n  /** Smallest accepted password length. @default 8 */\n  minPasswordLength?: number;\n  /** Largest accepted password length. @default 128 */\n  maxPasswordLength?: number;\n}\n\nexport interface FarmAuthSessionConfig {\n  /** Session lifetime in seconds. @default 604800 */\n  expiresIn?: number;\n  /** Session refresh interval in seconds. @default 86400 */\n  updateAge?: number;\n}\n\nexport interface FarmAuthDatabaseConfig {\n  /**\n   * Postgres connection string. Defaults to DATABASE_URL.\n   * Local development falls back to SQLite when no URL is present.\n   */\n  url?: string;\n  /** Local SQLite path. @default \".farm/auth.sqlite\" */\n  path?: string;\n  /** Automatically update the auth schema in development. @default true */\n  migrateInDevelopment?: boolean;\n}\n\nexport interface FarmAuthConfig {\n  /** Set false to disable auth without removing its configuration. @default true */\n  enabled?: boolean;\n  /** Display name used by authentication emails and metadata. */\n  appName?: string;\n  /** Route prefix for the auth endpoints. @default \"/api/auth\" */\n  basePath?: string;\n  /**\n   * Email/password authentication. It is enabled by default; set false to\n   * disable it when adding another sign-in method.\n   */\n  emailAndPassword?: boolean | FarmAuthEmailAndPasswordConfig;\n  session?: FarmAuthSessionConfig;\n  database?: FarmAuthDatabaseConfig;\n}\n\nexport type FarmAuthUserConfig = boolean | FarmAuthConfig;\n\nexport interface ResolvedFarmAuthConfig {\n  enabled: boolean;\n  appName?: string;\n  basePath: string;\n  emailAndPassword: {\n    enabled: boolean;\n    requireEmailVerification: boolean;\n    minPasswordLength: number;\n    maxPasswordLength: number;\n  };\n  session: {\n    expiresIn: number;\n    updateAge: number;\n  };\n  database: {\n    url?: string;\n    path: string;\n    migrateInDevelopment: boolean;\n  };\n}\n\ninterface FarmAuthRuntimeModule {\n  createFarmAuthIntegration(\n    config: ResolvedFarmAuthConfig,\n    options: {\n      root: string;\n      mode: \"development\" | \"production\";\n    },\n  ): FarmIntegration;\n}\n\nexport function resolveFarmAuthConfig(\n  input: FarmAuthUserConfig | undefined,\n): ResolvedFarmAuthConfig {\n  const config = input === true ? {} : input && typeof input === \"object\" ? input : {};\n  const passwordConfig = typeof config.emailAndPassword === \"object\" ? config.emailAndPassword : {};\n\n  const resolved: ResolvedFarmAuthConfig = {\n    enabled: input !== undefined && input !== false && config.enabled !== false,\n    appName: config.appName,\n    basePath: normalizeBasePath(config.basePath),\n    emailAndPassword: {\n      enabled: config.emailAndPassword !== false,\n      requireEmailVerification: passwordConfig.requireEmailVerification ?? false,\n      minPasswordLength: passwordConfig.minPasswordLength ?? 8,\n      maxPasswordLength: passwordConfig.maxPasswordLength ?? 128,\n    },\n    session: {\n      expiresIn: config.session?.expiresIn ?? 60 * 60 * 24 * 7,\n      updateAge: config.session?.updateAge ?? 60 * 60 * 24,\n    },\n    database: {\n      url: config.database?.url,\n      path: config.database?.path || \".farm/auth.sqlite\",\n      migrateInDevelopment: config.database?.migrateInDevelopment ?? true,\n    },\n  };\n\n  validateFarmAuthConfig(resolved);\n  return resolved;\n}\n\nexport async function resolveFarmAuthIntegration(\n  config: ResolvedFarmAuthConfig,\n  options: {\n    root: string;\n    mode: \"development\" | \"production\";\n  },\n): Promise<FarmIntegration | undefined> {\n  if (!config.enabled) return undefined;\n\n  const root = path.resolve(options.root);\n  let modulePath: string;\n  try {\n    const resolveFromApp = createRequire(path.join(root, \"package.json\"));\n    modulePath = resolveFromApp.resolve(\"@farm.js/auth/internal\");\n  } catch {\n    throw new Error(\n      \"The `auth` config requires @farm.js/auth. Install it with `pnpm add @farm.js/auth` and try again.\",\n    );\n  }\n\n  const runtime = (await import(\n    /* @vite-ignore */ pathToFileURL(modulePath).href\n  )) as FarmAuthRuntimeModule;\n  if (typeof runtime.createFarmAuthIntegration !== \"function\") {\n    throw new Error(\n      \"The installed @farm.js/auth package is incompatible with this version of @farm.js/core.\",\n    );\n  }\n\n  return runtime.createFarmAuthIntegration(config, {\n    ...options,\n    root,\n  });\n}\n\nfunction normalizeBasePath(value: string | undefined): string {\n  const route = (value || \"/api/auth\").trim();\n  if (!route) return \"/api/auth\";\n  assertStableBasePath(route);\n  const withLeadingSlash = route.startsWith(\"/\") ? route : `/${route}`;\n  const normalized = withLeadingSlash.replace(/\\/+/g, \"/\").replace(/\\/+$/, \"\");\n  return normalized || \"/api/auth\";\n}\n\nfunction assertStableBasePath(route: string): void {\n  if (route.includes(\"?\") || route.includes(\"#\")) {\n    throw new Error(\"auth.basePath cannot contain a query string or fragment.\");\n  }\n  if (route.startsWith(\"//\") || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(route)) {\n    throw new Error('auth.basePath must be an application pathname such as \"/api/auth\".');\n  }\n  if (hasUnstablePathCharacters(route)) {\n    throw new Error(\"auth.basePath cannot contain backslashes or control characters.\");\n  }\n  for (const segment of route.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal URL pathname segments.\n    }\n    if (hasUnstablePathCharacters(decoded) || decoded.includes(\"/\")) {\n      throw new Error(\"auth.basePath cannot contain encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('auth.basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n}\n\nfunction hasUnstablePathCharacters(value: string): boolean {\n  return (\n    value.includes(\"\\\\\") ||\n    Array.from(value).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  );\n}\n\nfunction validateFarmAuthConfig(config: ResolvedFarmAuthConfig): void {\n  const { minPasswordLength, maxPasswordLength } = config.emailAndPassword;\n  if (!Number.isInteger(minPasswordLength) || minPasswordLength < 1) {\n    throw new Error(\"auth.emailAndPassword.minPasswordLength must be a positive integer.\");\n  }\n  if (!Number.isInteger(maxPasswordLength) || maxPasswordLength < minPasswordLength) {\n    throw new Error(\n      \"auth.emailAndPassword.maxPasswordLength must be an integer greater than or equal to minPasswordLength.\",\n    );\n  }\n  if (!Number.isInteger(config.session.expiresIn) || config.session.expiresIn < 1) {\n    throw new Error(\"auth.session.expiresIn must be a positive integer.\");\n  }\n  if (!Number.isInteger(config.session.updateAge) || config.session.updateAge < 0) {\n    throw new Error(\"auth.session.updateAge must be a non-negative integer.\");\n  }\n}\n","export type FarmPreloadMode = \"warn\" | \"enforce\";\n\nexport interface FarmPreloadUserConfig {\n  /** Report excess hints or remove the lower-priority hints. @default \"enforce\" */\n  mode?: FarmPreloadMode;\n  /** Maximum image preload hints per document. @default 1 */\n  maxImages?: number;\n  /** Maximum font preload hints per document. @default 2 */\n  maxFonts?: number;\n}\n\nexport interface ResolvedFarmPreloadConfig {\n  mode: FarmPreloadMode;\n  maxImages: number;\n  maxFonts: number;\n}\n\nexport interface FarmPerformanceConfig {\n  preload?: FarmPreloadUserConfig;\n}\n\nexport interface ResolvedFarmPerformanceConfig {\n  preload: ResolvedFarmPreloadConfig;\n}\n\nexport type FarmPreloadKind = \"image\" | \"font\";\n\nexport interface FarmPreloadBudgetWarning {\n  kind: FarmPreloadKind;\n  count: number;\n  budget: number;\n  removed: number;\n}\n\nexport interface FarmManagedPreloads {\n  value: string;\n  warnings: FarmPreloadBudgetWarning[];\n}\n\nexport interface FarmManagedDocumentPreloads {\n  html: string;\n  linkHeader: string;\n  warnings: FarmPreloadBudgetWarning[];\n}\n\nconst DEFAULT_PRELOAD_CONFIG: ResolvedFarmPreloadConfig = {\n  mode: \"enforce\",\n  maxImages: 1,\n  maxFonts: 2,\n};\n\nconst reportedWarnings = new Map<string, number>();\nconst PRELOAD_WARNING_TTL_MS = 60_000;\nconst MAX_REPORTED_PRELOAD_WARNINGS = 256;\n\nexport function resolveFarmPerformanceConfig(\n  config: FarmPerformanceConfig | undefined,\n): ResolvedFarmPerformanceConfig {\n  return {\n    preload: {\n      mode: config?.preload?.mode === \"warn\" ? \"warn\" : \"enforce\",\n      maxImages: normalizeBudget(config?.preload?.maxImages, DEFAULT_PRELOAD_CONFIG.maxImages),\n      maxFonts: normalizeBudget(config?.preload?.maxFonts, DEFAULT_PRELOAD_CONFIG.maxFonts),\n    },\n  };\n}\n\n/**\n * Apply image and font budgets to HTML preload elements. High-priority image\n * hints are retained before ordinary hints, making an explicitly preloaded LCP\n * image the winner when a document contains too many React-generated hints.\n */\nexport function manageFarmHtmlPreloads(\n  html: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedPreloads {\n  const elements = findHtmlLinkElements(html);\n  const candidates = elements.flatMap((element, index) => {\n    const kind = getHtmlPreloadKind(element.value);\n    return kind\n      ? [\n          {\n            index,\n            kind,\n            highPriority:\n              readHtmlAttribute(element.value, \"fetchpriority\")?.toLowerCase() === \"high\",\n          },\n        ]\n      : [];\n  });\n\n  const budget = selectPreloadsWithinBudget(candidates, config);\n  if (config.mode === \"warn\" || budget.removed.size === 0) {\n    return { value: html, warnings: budget.warnings };\n  }\n\n  return {\n    value: removeHtmlLinkElements(html, elements, budget.removed),\n    warnings: budget.warnings,\n  };\n}\n\n/** Apply the same budgets to HTTP Link preload hints, including Farm fonts. */\nexport function manageFarmLinkHeaderPreloads(\n  value: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedPreloads {\n  if (!value) return { value, warnings: [] };\n\n  const links = splitLinkHeader(value);\n  const candidates = links.flatMap((link, index) => {\n    const kind = getLinkHeaderPreloadKind(link);\n    return kind\n      ? [\n          {\n            index,\n            kind,\n            highPriority: getLinkHeaderParameter(link, \"fetchpriority\")?.toLowerCase() === \"high\",\n          },\n        ]\n      : [];\n  });\n  const budget = selectPreloadsWithinBudget(candidates, config);\n\n  return {\n    value:\n      config.mode === \"enforce\"\n        ? links.filter((_, index) => !budget.removed.has(index)).join(\", \")\n        : value,\n    warnings: budget.warnings,\n  };\n}\n\n/** Apply a single document budget across HTML and HTTP Link header hints. */\nexport function manageFarmDocumentPreloads(\n  html: string,\n  linkHeader: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedDocumentPreloads {\n  const elements = findHtmlLinkElements(html);\n  const links = linkHeader ? splitLinkHeader(linkHeader) : [];\n  const headerOffset = elements.length;\n  const candidates: PreloadCandidate[] = [];\n\n  for (const [index, element] of elements.entries()) {\n    const kind = getHtmlPreloadKind(element.value);\n    if (!kind) continue;\n    candidates.push({\n      index,\n      kind,\n      highPriority: readHtmlAttribute(element.value, \"fetchpriority\")?.toLowerCase() === \"high\",\n    });\n  }\n  for (const [index, link] of links.entries()) {\n    const kind = getLinkHeaderPreloadKind(link);\n    if (!kind) continue;\n    candidates.push({\n      index: headerOffset + index,\n      kind,\n      highPriority: getLinkHeaderParameter(link, \"fetchpriority\")?.toLowerCase() === \"high\",\n    });\n  }\n\n  const budget = selectPreloadsWithinBudget(candidates, config);\n  if (config.mode === \"warn\" || budget.removed.size === 0) {\n    return { html, linkHeader, warnings: budget.warnings };\n  }\n\n  return {\n    html: removeHtmlLinkElements(html, elements, budget.removed),\n    linkHeader: links.filter((_, index) => !budget.removed.has(headerOffset + index)).join(\", \"),\n    warnings: budget.warnings,\n  };\n}\n\n/** Rate-limit identical route-and-budget warnings within a server process. */\nexport function reportFarmPreloadWarnings(\n  warnings: FarmPreloadBudgetWarning[],\n  context = \"the rendered document\",\n): void {\n  const now = Date.now();\n  for (const [key, reportedAt] of reportedWarnings) {\n    if (now - reportedAt >= PRELOAD_WARNING_TTL_MS) reportedWarnings.delete(key);\n  }\n\n  for (const warning of warnings) {\n    const key = `${context}:${warning.kind}:${warning.count}:${warning.budget}:${warning.removed}`;\n    const reportedAt = reportedWarnings.get(key);\n    if (reportedAt !== undefined && now - reportedAt < PRELOAD_WARNING_TTL_MS) continue;\n    reportedWarnings.set(key, now);\n    while (reportedWarnings.size > MAX_REPORTED_PRELOAD_WARNINGS) {\n      const oldest = reportedWarnings.keys().next().value;\n      if (oldest === undefined) break;\n      reportedWarnings.delete(oldest);\n    }\n\n    const action = warning.removed > 0 ? ` Removed ${warning.removed} lower-priority hint(s).` : \"\";\n    const recommendation =\n      warning.kind === \"image\"\n        ? ' Mark only the LCP image with `preload` or `fetchPriority=\"high\"`.'\n        : \" Set `preload: false` on fonts that are not required above the fold.\";\n    console.warn(\n      `[Farm.js] ${context} emitted ${warning.count} ${warning.kind} preload hints ` +\n        `(budget: ${warning.budget}).${action}${recommendation}`,\n    );\n  }\n}\n\nexport function clearReportedFarmPreloadWarnings(): void {\n  reportedWarnings.clear();\n}\n\ninterface PreloadCandidate {\n  index: number;\n  kind: FarmPreloadKind;\n  highPriority: boolean;\n}\n\nfunction selectPreloadsWithinBudget(\n  candidates: PreloadCandidate[],\n  config: ResolvedFarmPreloadConfig,\n): { removed: Set<number>; warnings: FarmPreloadBudgetWarning[] } {\n  const removed = new Set<number>();\n  const warnings: FarmPreloadBudgetWarning[] = [];\n\n  for (const kind of [\"image\", \"font\"] as const) {\n    const matching = candidates.filter((candidate) => candidate.kind === kind);\n    const limit = kind === \"image\" ? config.maxImages : config.maxFonts;\n    if (matching.length <= limit) continue;\n\n    const retained = new Set(\n      [...matching]\n        .sort(\n          (left, right) =>\n            Number(right.highPriority) - Number(left.highPriority) || left.index - right.index,\n        )\n        .slice(0, limit)\n        .map((candidate) => candidate.index),\n    );\n\n    if (config.mode === \"enforce\") {\n      for (const candidate of matching) {\n        if (!retained.has(candidate.index)) removed.add(candidate.index);\n      }\n    }\n\n    warnings.push({\n      kind,\n      count: matching.length,\n      budget: limit,\n      removed: config.mode === \"enforce\" ? matching.length - retained.size : 0,\n    });\n  }\n\n  return { removed, warnings };\n}\n\nfunction getHtmlPreloadKind(link: string): FarmPreloadKind | undefined {\n  const rel = readHtmlAttribute(link, \"rel\")?.toLowerCase().split(/\\s+/) || [];\n  if (!rel.includes(\"preload\")) return undefined;\n  return normalizePreloadKind(readHtmlAttribute(link, \"as\"));\n}\n\nfunction getLinkHeaderPreloadKind(link: string): FarmPreloadKind | undefined {\n  const relations = getLinkHeaderParameter(link, \"rel\")?.toLowerCase().split(/\\s+/) ?? [];\n  if (!relations.includes(\"preload\")) return undefined;\n  return normalizePreloadKind(getLinkHeaderParameter(link, \"as\"));\n}\n\nfunction getLinkHeaderParameter(link: string, name: string): string | undefined {\n  const uriEnd = link.indexOf(\">\");\n  if (uriEnd === -1) return undefined;\n\n  for (const parameter of splitLinkParameters(link.slice(uriEnd + 1))) {\n    const separator = parameter.indexOf(\"=\");\n    const parameterName = (separator === -1 ? parameter : parameter.slice(0, separator))\n      .trim()\n      .toLowerCase();\n    if (parameterName !== name.toLowerCase() || separator === -1) continue;\n    const rawValue = parameter.slice(separator + 1).trim();\n    if (rawValue.startsWith('\"') && rawValue.endsWith('\"')) {\n      return rawValue.slice(1, -1).replace(/\\\\([\\\\\"])/g, \"$1\");\n    }\n    return rawValue;\n  }\n  return undefined;\n}\n\nfunction splitLinkParameters(value: string): string[] {\n  const parameters: string[] = [];\n  let start = 0;\n  let quoted = false;\n  for (let index = 0; index < value.length; index += 1) {\n    const character = value[index];\n    if (character === '\"' && !isEscaped(value, index)) quoted = !quoted;\n    else if (character === \";\" && !quoted) {\n      const parameter = value.slice(start, index).trim();\n      if (parameter) parameters.push(parameter);\n      start = index + 1;\n    }\n  }\n  const parameter = value.slice(start).trim();\n  if (parameter) parameters.push(parameter);\n  return parameters;\n}\n\nfunction normalizePreloadKind(value: string | undefined): FarmPreloadKind | undefined {\n  const normalized = value?.toLowerCase();\n  return normalized === \"image\" || normalized === \"font\" ? normalized : undefined;\n}\n\nfunction readHtmlAttribute(element: string, name: string): string | undefined {\n  const match = element.match(\n    new RegExp(`\\\\s${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s>]+))`, \"i\"),\n  );\n  return match?.[1] ?? match?.[2] ?? match?.[3];\n}\n\ninterface HtmlLinkElement {\n  start: number;\n  end: number;\n  value: string;\n}\n\nfunction findHtmlLinkElements(html: string): HtmlLinkElement[] {\n  const elements: HtmlLinkElement[] = [];\n  const lowerHtml = html.toLowerCase();\n  let cursor = 0;\n\n  while (cursor < html.length) {\n    const start = html.indexOf(\"<\", cursor);\n    if (start === -1) break;\n\n    if (lowerHtml.startsWith(\"<!--\", start)) {\n      const commentEnd = lowerHtml.indexOf(\"-->\", start + 4);\n      cursor = commentEnd === -1 ? html.length : commentEnd + 3;\n      continue;\n    }\n\n    const rawText = lowerHtml\n      .slice(start)\n      .match(/^<(script|style|template|textarea|title|noscript|svg)(?=[\\s/>])/);\n    if (rawText?.[1]) {\n      const openingEnd = findHtmlTagEnd(html, start);\n      if (openingEnd === -1) break;\n      const closingStart = findHtmlClosingTag(lowerHtml, rawText[1], openingEnd);\n      if (closingStart === -1) {\n        cursor = html.length;\n        continue;\n      }\n      const closingEnd = findHtmlTagEnd(html, closingStart);\n      cursor = closingEnd === -1 ? html.length : closingEnd;\n      continue;\n    }\n\n    if (/^<link(?=[\\s/>])/i.test(html.slice(start))) {\n      const end = findHtmlTagEnd(html, start);\n      if (end === -1) break;\n      elements.push({ start, end, value: html.slice(start, end) });\n      cursor = end;\n      continue;\n    }\n\n    if (/^<\\/?[A-Za-z][\\w:-]*(?=[\\s/>])/.test(html.slice(start))) {\n      const end = findHtmlTagEnd(html, start);\n      cursor = end === -1 ? html.length : end;\n      continue;\n    }\n\n    cursor = start + 1;\n  }\n\n  return elements;\n}\n\nfunction findHtmlClosingTag(html: string, tagName: string, start: number): number {\n  const prefix = `</${tagName}`;\n  let candidate = html.indexOf(prefix, start);\n  while (candidate !== -1) {\n    const boundary = html[candidate + prefix.length];\n    if (boundary === \">\" || boundary === \"/\" || /\\s/.test(boundary ?? \"\")) return candidate;\n    candidate = html.indexOf(prefix, candidate + prefix.length);\n  }\n  return -1;\n}\n\nfunction findHtmlTagEnd(html: string, start: number): number {\n  let quote: '\"' | \"'\" | undefined;\n  for (let index = start + 1; index < html.length; index += 1) {\n    const character = html[index];\n    if (quote) {\n      if (character === quote) quote = undefined;\n    } else if (character === '\"' || character === \"'\") {\n      quote = character;\n    } else if (character === \">\") {\n      return index + 1;\n    }\n  }\n  return -1;\n}\n\nfunction removeHtmlLinkElements(\n  html: string,\n  elements: HtmlLinkElement[],\n  removed: ReadonlySet<number>,\n): string {\n  let cursor = 0;\n  let output = \"\";\n  for (const [index, element] of elements.entries()) {\n    if (!removed.has(index)) continue;\n    output += html.slice(cursor, element.start);\n    cursor = element.end;\n  }\n  return output + html.slice(cursor);\n}\n\nfunction splitLinkHeader(value: string): string[] {\n  const links: string[] = [];\n  let start = 0;\n  let insideAngleBrackets = false;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index += 1) {\n    const character = value[index];\n    if (quoted) {\n      if (character === '\"' && !isEscaped(value, index)) quoted = false;\n      continue;\n    }\n    if (character === '\"') {\n      quoted = true;\n    } else if (character === \"<\") {\n      insideAngleBrackets = true;\n    } else if (character === \">\") {\n      insideAngleBrackets = false;\n    } else if (character === \",\" && !insideAngleBrackets) {\n      links.push(value.slice(start, index).trim());\n      start = index + 1;\n    }\n  }\n\n  links.push(value.slice(start).trim());\n  return links.filter(Boolean);\n}\n\nfunction isEscaped(value: string, index: number): boolean {\n  let backslashes = 0;\n  for (let cursor = index - 1; cursor >= 0 && value[cursor] === \"\\\\\"; cursor -= 1) {\n    backslashes += 1;\n  }\n  return backslashes % 2 === 1;\n}\n\nfunction normalizeBudget(value: number | undefined, fallback: number): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value >= 0\n    ? Math.floor(value)\n    : fallback;\n}\n","export type FarmCspDirectiveValue = string | readonly string[] | boolean | null | undefined;\n\nexport type FarmCspDirectives = Readonly<Record<string, FarmCspDirectiveValue>>;\n\nexport interface FarmCspOptions {\n  /** A pre-serialized CSP value. Cannot be combined with directives. */\n  policy?: string;\n  /** CSP directives using camelCase or kebab-case names. */\n  directives?: FarmCspDirectives;\n  /** Emit Content-Security-Policy-Report-Only instead of enforcing the policy. */\n  reportOnly?: boolean;\n}\n\nexport type FarmCspConfig = string | FarmCspOptions;\n\nexport interface FarmSecurityConfig {\n  /** App-wide Content Security Policy applied to pages, APIs, and static output. */\n  csp?: FarmCspConfig | false;\n  /** @deprecated Use csp. */\n  contentSecurityPolicy?: never;\n}\n\nexport interface ResolvedFarmCspConfig {\n  value: string;\n  reportOnly: boolean;\n}\n\nexport interface ResolvedFarmSecurityConfig {\n  csp: ResolvedFarmCspConfig | false;\n}\n\nexport function resolveFarmSecurityConfig(\n  input: FarmSecurityConfig | ResolvedFarmSecurityConfig | undefined,\n): ResolvedFarmSecurityConfig {\n  if (input === undefined) return { csp: false };\n  if (!isPlainRecord(input)) {\n    throw new TypeError(\"security must be an object containing the csp option.\");\n  }\n  if (Object.prototype.hasOwnProperty.call(input, \"contentSecurityPolicy\")) {\n    throw new TypeError(\n      \"security.contentSecurityPolicy is not supported. Use security.csp instead.\",\n    );\n  }\n\n  const csp = input.csp;\n  if (csp === undefined || csp === false) return { csp: false };\n\n  if (typeof csp === \"string\") {\n    return {\n      csp: {\n        value: validateSerializedCsp(csp),\n        reportOnly: false,\n      },\n    };\n  }\n\n  if (!isPlainRecord(csp)) {\n    throw new TypeError(\"security.csp must be a policy string, false, or an options object.\");\n  }\n\n  const reportOnly = validateReportOnly(csp.reportOnly);\n  if (Object.prototype.hasOwnProperty.call(csp, \"value\")) {\n    if (\n      Object.prototype.hasOwnProperty.call(csp, \"policy\") ||\n      Object.prototype.hasOwnProperty.call(csp, \"directives\")\n    ) {\n      throw new TypeError(\n        \"Resolved security.csp values cannot include policy or directives options.\",\n      );\n    }\n    return {\n      csp: {\n        value: validateSerializedCsp(csp.value),\n        reportOnly,\n      },\n    };\n  }\n\n  const { policy, directives } = csp;\n  if (policy !== undefined && directives !== undefined) {\n    throw new TypeError(\"security.csp accepts either policy or directives, not both.\");\n  }\n  if (policy === undefined && directives === undefined) {\n    throw new TypeError(\"security.csp requires a policy string or directives object.\");\n  }\n\n  return {\n    csp: {\n      value:\n        policy !== undefined\n          ? validateSerializedCsp(policy)\n          : serializeFarmCspDirectives(directives as FarmCspDirectives),\n      reportOnly,\n    },\n  };\n}\n\nexport function serializeFarmCspDirectives(directives: FarmCspDirectives): string {\n  if (!isPlainRecord(directives)) {\n    throw new TypeError(\"security.csp.directives must be an object.\");\n  }\n  const serialized: string[] = [];\n  const normalizedNames = new Set<string>();\n\n  for (const [configuredName, configuredValue] of Object.entries(directives)) {\n    if (configuredValue === false || configuredValue === null || configuredValue === undefined) {\n      continue;\n    }\n\n    const name = normalizeDirectiveName(configuredName);\n    if (normalizedNames.has(name)) {\n      throw new TypeError(`security.csp contains the duplicate directive ${JSON.stringify(name)}.`);\n    }\n    normalizedNames.add(name);\n\n    const values =\n      configuredValue === true\n        ? []\n        : (Array.isArray(configuredValue) ? configuredValue : [configuredValue]).map(\n            validateDirectiveValue,\n          );\n    serialized.push(values.length > 0 ? `${name} ${values.join(\" \")}` : name);\n  }\n\n  if (serialized.length === 0) {\n    throw new TypeError(\"security.csp.directives must contain at least one enabled directive.\");\n  }\n  return serialized.join(\"; \");\n}\n\nexport function getFarmSecurityHeader(\n  security: ResolvedFarmSecurityConfig,\n): { key: string; value: string } | undefined {\n  if (!security.csp) return undefined;\n  return {\n    key: security.csp.reportOnly\n      ? \"Content-Security-Policy-Report-Only\"\n      : \"Content-Security-Policy\",\n    value: security.csp.value,\n  };\n}\n\nfunction normalizeDirectiveName(value: string): string {\n  const name = value\n    .trim()\n    .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n    .toLowerCase();\n  if (!/^[a-z][a-z0-9-]*$/.test(name)) {\n    throw new TypeError(`Invalid security.csp directive name: ${JSON.stringify(value)}.`);\n  }\n  return name;\n}\n\nfunction validateDirectiveValue(value: string): string {\n  if (typeof value !== \"string\") {\n    throw new TypeError(\"security.csp directive values must be strings or booleans.\");\n  }\n  const normalized = value.trim();\n  if (!normalized || /[;\\r\\n]/.test(normalized) || normalized.includes(\"\\0\")) {\n    throw new TypeError(`Invalid security.csp directive value: ${JSON.stringify(value)}.`);\n  }\n  return normalized;\n}\n\nfunction validateSerializedCsp(value: unknown): string {\n  if (typeof value !== \"string\") {\n    throw new TypeError(\"security.csp policy must be a non-empty single-line string.\");\n  }\n  const normalized = value.trim().replace(/;+$/g, \"\").trim();\n  if (!normalized || /[\\r\\n]/.test(normalized) || normalized.includes(\"\\0\")) {\n    throw new TypeError(\"security.csp policy must be a non-empty single-line string.\");\n  }\n  return normalized;\n}\n\nfunction validateReportOnly(value: unknown): boolean {\n  if (value === undefined) return false;\n  if (typeof value !== \"boolean\") {\n    throw new TypeError(\"security.csp.reportOnly must be a boolean.\");\n  }\n  return value;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n","import type { ResolvedFarmEnv } from \"../env\";\n\nexport const DEFAULT_FARM_API_BASE_PATH = \"/api\";\n\nexport interface FarmAPIConfigResolverContext {\n  root: string;\n  mode: \"development\" | \"production\";\n  env: ResolvedFarmEnv;\n}\n\nexport type FarmAPIConfigValue =\n  | string\n  | undefined\n  | ((context: FarmAPIConfigResolverContext) => string | undefined | Promise<string | undefined>);\n\nexport interface FarmAPIConfig {\n  /**\n   * Public API root. An origin-only URL is joined with `basePath`; a URL that\n   * already has a path is used as-is. May be resolved from deployment context.\n   */\n  baseURL?: FarmAPIConfigValue;\n  /** Public API path and same-origin server mount used when `baseURL` has no path. @default \"/api\" */\n  basePath?: FarmAPIConfigValue;\n}\n\nexport interface ResolvedFarmAPIConfig {\n  /** Fully resolved public API root, either absolute or root-relative. */\n  baseURL: string;\n  /** Effective pathname of `baseURL`. */\n  basePath: string;\n}\n\ndeclare const __FARM_API_BASE_URL__: string | undefined;\n\nexport async function resolveFarmAPIConfig(\n  config: FarmAPIConfig | undefined,\n  context: FarmAPIConfigResolverContext,\n): Promise<ResolvedFarmAPIConfig> {\n  const configuredBasePath = await resolveConfigValue(config?.basePath, context, \"api.basePath\");\n  const basePath = normalizeFarmAPIBasePath(configuredBasePath ?? DEFAULT_FARM_API_BASE_PATH);\n  const configuredBaseURL = await resolveConfigValue(config?.baseURL, context, \"api.baseURL\");\n\n  return normalizeFarmAPIConfig({ baseURL: configuredBaseURL, basePath });\n}\n\n/** Normalize already-resolved API strings. */\nexport function normalizeFarmAPIConfig(\n  config: { baseURL?: string; basePath?: string } | undefined,\n): ResolvedFarmAPIConfig {\n  const basePath = normalizeFarmAPIBasePath(config?.basePath ?? DEFAULT_FARM_API_BASE_PATH);\n  const baseURL = config?.baseURL?.trim();\n\n  if (!baseURL) {\n    return { baseURL: basePath, basePath };\n  }\n\n  if (baseURL.startsWith(\"//\")) {\n    throw new Error(\n      'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\", not a network-path reference.',\n    );\n  }\n\n  if (baseURL.startsWith(\"/\")) {\n    const url = parseRootRelativeBaseURL(baseURL);\n    if (url.pathname !== \"/\") {\n      const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n      return { baseURL: effectivePath, basePath: effectivePath };\n    }\n    return { baseURL: basePath, basePath };\n  }\n\n  let url: URL;\n  try {\n    url = new URL(baseURL);\n  } catch {\n    throw new Error(\n      'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\".',\n    );\n  }\n\n  if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n    throw new Error(\"Farm api.baseURL must use http or https.\");\n  }\n  if (url.search || url.hash) {\n    throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n  }\n\n  if (url.pathname !== \"/\") {\n    const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n    return {\n      baseURL: `${url.origin}${effectivePath}`,\n      basePath: effectivePath,\n    };\n  }\n\n  return {\n    baseURL: basePath === \"/\" ? url.origin : `${url.origin}${basePath}`,\n    basePath,\n  };\n}\n\nexport function normalizeFarmAPIBasePath(value: string): string {\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(value)) {\n    throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n  }\n\n  const path = value.trim();\n  if (!path) {\n    throw new Error(\"Farm api.basePath cannot be empty.\");\n  }\n  if (path.includes(\"?\") || path.includes(\"#\")) {\n    throw new Error(\"Farm api.basePath cannot contain a query string or hash.\");\n  }\n  if (path.startsWith(\"//\")) {\n    throw new Error('Farm api.basePath must be a pathname such as \"/api\", not a URL.');\n  }\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // A malformed escape remains literal in a URL pathname. It cannot be a\n      // dot segment, so leave the ordinary URL parser to preserve it.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"Farm api.basePath cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('Farm api.basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  const normalized = `/${path.replace(/^\\/+|\\/+$/g, \"\")}`;\n  return normalized === \"/\" ? \"/\" : normalized;\n}\n\n/** Read the API root embedded by Farm's Vite build. */\nexport function getFarmAPIBaseURL(): string {\n  if (typeof __FARM_API_BASE_URL__ !== \"undefined\" && __FARM_API_BASE_URL__) {\n    return __FARM_API_BASE_URL__;\n  }\n  return DEFAULT_FARM_API_BASE_PATH;\n}\n\n/** Resolve a canonical Farm route such as `/api/users` against an API root. */\nexport function resolveFarmAPIRequestURL(\n  routePath: string,\n  baseURL = getFarmAPIBaseURL(),\n  fallbackOrigin = getDefaultOrigin(),\n): URL {\n  const base = new URL(baseURL, fallbackOrigin);\n  if (base.pathname === \"/\") {\n    return new URL(routePath, base);\n  }\n\n  const route = new URL(routePath, fallbackOrigin);\n  const suffix = stripCanonicalAPIBasePath(route.pathname);\n  const joinedPath = joinURLPath(base.pathname, suffix);\n  base.pathname = joinedPath;\n  base.search = route.search;\n  base.hash = route.hash;\n  return base;\n}\n\nasync function resolveConfigValue(\n  value: FarmAPIConfigValue,\n  context: FarmAPIConfigResolverContext,\n  name: string,\n): Promise<string | undefined> {\n  const resolved = typeof value === \"function\" ? await value(context) : value;\n  if (resolved === undefined) return undefined;\n  if (typeof resolved !== \"string\") {\n    throw new Error(`Farm ${name} must resolve to a string or undefined.`);\n  }\n  if (!resolved.trim()) {\n    throw new Error(`Farm ${name} cannot be empty.`);\n  }\n  return resolved;\n}\n\nfunction parseRootRelativeBaseURL(value: string): URL {\n  const url = new URL(value, \"http://farm.local\");\n  if (url.search || url.hash) {\n    throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n  }\n  return url;\n}\n\nfunction stripCanonicalAPIBasePath(pathname: string): string {\n  if (pathname === DEFAULT_FARM_API_BASE_PATH) return \"\";\n  if (pathname.startsWith(`${DEFAULT_FARM_API_BASE_PATH}/`)) {\n    return pathname.slice(DEFAULT_FARM_API_BASE_PATH.length + 1);\n  }\n  return pathname.replace(/^\\/+/, \"\");\n}\n\nfunction joinURLPath(basePath: string, suffix: string): string {\n  const normalizedBase = basePath === \"/\" ? \"\" : basePath.replace(/\\/+$/, \"\");\n  const normalizedSuffix = suffix.replace(/^\\/+/, \"\");\n  if (!normalizedSuffix) return normalizedBase || \"/\";\n  return `${normalizedBase}/${normalizedSuffix}`;\n}\n\nfunction getDefaultOrigin(): string {\n  return typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\";\n}\n","import type { FarmConfig } from \"./types\";\nimport type { FarmDocsResolvedConfig } from \"./docs/types\";\nimport type { FarmMarkdownResolvedConfig } from \"./markdown\";\nimport { resolveMdxConfig, type FarmMdxResolvedConfig } from \"./app-markdown-config\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig, type FarmWorkflowsResolvedConfig } from \"./workflows\";\nimport { resolveCronConfig, type FarmCronResolvedConfig } from \"./cron\";\nimport { resolveAppPath, fileExists, logger } from \"./utils\";\nimport { initStorage } from \"./storage\";\nimport { configureFarmObservability } from \"./observability\";\nimport { normalizeRouteRules } from \"./route-rules\";\nimport { resolveServerActionsConfig } from \"./server-action-security\";\nimport { resolveFarmServerConfig } from \"./server-http\";\nimport { resolveFarmImageConfig, type ResolvedFarmImageConfig } from \"./image-config\";\nimport { getFarmAppDirectories, getFarmSourceRoots } from \"./layers\";\nimport { RouteManager } from \"./routing/route-manager\";\nimport { ServerRenderer } from \"./server/renderer\";\nimport { findProgrammaticRouteFiles } from \"./routes.server\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n  resolveFarmDevIndicatorsConfig,\n  type ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport {\n  createFarmI18nRuntime,\n  _setDefaultFarmI18nRuntime,\n  type FarmI18nRuntime,\n} from \"./i18n/server\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport { configureFarmCache } from \"./cache\";\nimport { resolveFarmAuthConfig, type ResolvedFarmAuthConfig } from \"./auth-config\";\nimport { resolveFarmPerformanceConfig, type ResolvedFarmPerformanceConfig } from \"./preload\";\nimport { normalizeFarmConfigBasePath } from \"./base-path\";\nimport { resolveFarmSecurityConfig, type ResolvedFarmSecurityConfig } from \"./security\";\nimport { resolveFarmThemeConfig } from \"./theme/config\";\nimport { _setDefaultFarmThemeConfig } from \"./theme/server\";\nimport type { ResolvedFarmThemeConfig } from \"./theme/types\";\nimport { getFarmRendererComponentExtensions, resolveFarmRenderer } from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { normalizeFarmAPIConfig, type ResolvedFarmAPIConfig } from \"./api/config\";\n\ntype NormalizedFarmConfig = Omit<\n  Required<FarmConfig>,\n  \"api\" | \"devtools\" | \"devIndicators\" | \"images\" | \"i18n\" | \"performance\" | \"security\" | \"theme\"\n> & {\n  api: ResolvedFarmAPIConfig;\n  docs: FarmDocsResolvedConfig;\n  md: FarmMarkdownResolvedConfig;\n  mdx: FarmMdxResolvedConfig;\n  cron: FarmCronResolvedConfig;\n  workflows: FarmWorkflowsResolvedConfig;\n  devtools: ResolvedFarmDevtoolsConfig;\n  devIndicators: ResolvedFarmDevIndicatorsConfig;\n  images: ResolvedFarmImageConfig;\n  i18n: ResolvedFarmI18nConfig;\n  auth: ResolvedFarmAuthConfig;\n  performance: ResolvedFarmPerformanceConfig;\n  security: ResolvedFarmSecurityConfig;\n  theme: ResolvedFarmThemeConfig;\n  renderer: FarmRenderer;\n};\n\nconst defaultDocsConfig: FarmDocsResolvedConfig = {\n  enabled: false,\n  entry: \"/docs\",\n  config: { entry: \"docs\", docsPath: \"/docs\" },\n};\n\nfunction isResolvedDocsConfig(value: FarmConfig[\"docs\"]): value is FarmDocsResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    \"entry\" in value &&\n    \"config\" in value\n  );\n}\n\nexport class FarmApp {\n  private config: NormalizedFarmConfig;\n  private routeManager: RouteManager;\n  private serverRenderer: ServerRenderer;\n  private i18nRuntime: FarmI18nRuntime;\n  private viteServer?: ViteDevServer;\n\n  constructor(config: FarmConfig = {}, viteServer?: ViteDevServer) {\n    this.config = this.normalizeConfig(config);\n    configureFarmObservability(this.config.observability);\n    _setDefaultFarmThemeConfig(this.config.theme);\n    this.i18nRuntime = createFarmI18nRuntime(this.config.i18n);\n    _setDefaultFarmI18nRuntime(this.i18nRuntime);\n    this.viteServer = viteServer;\n    this.routeManager = new RouteManager(this.config, viteServer);\n    this.serverRenderer = new ServerRenderer(\n      this.config,\n      this.routeManager,\n      this.i18nRuntime,\n      this.viteServer,\n    );\n  }\n\n  async initialize(): Promise<void> {\n    // Silent initialization unless verbose mode\n    if (process.env.FARM_VERBOSE) {\n      logger.info(\"Initializing Farm.js application...\");\n    }\n\n    await initStorage(this.config.storage);\n    await configureFarmCache(this.config.cache);\n    await this.i18nRuntime.initialize();\n    await this.serverRenderer.initialize();\n\n    // Verify app directory structure\n    await this.verifyAppStructure();\n\n    // Discover and register routes\n    await this.routeManager.discoverRoutes();\n\n    // Compile hydration and island decisions once during startup. Navigation\n    // requests only read this manifest; HMR invalidates it when route code changes.\n    this.routeManager.generateClientManifest(this.config.root);\n\n    if (process.env.FARM_VERBOSE) {\n      logger.success(\"Farm.js application initialized successfully!\");\n    }\n  }\n\n  getRouteManager(): RouteManager {\n    return this.routeManager;\n  }\n\n  getServerRenderer(): ServerRenderer {\n    return this.serverRenderer;\n  }\n\n  getI18nRuntime(): FarmI18nRuntime {\n    return this.i18nRuntime;\n  }\n\n  getConfig(): NormalizedFarmConfig {\n    return this.config;\n  }\n\n  private normalizeConfig(config: FarmConfig): NormalizedFarmConfig {\n    const root = config.root || process.cwd();\n    const basePath = normalizeFarmConfigBasePath(config.basePath);\n\n    return {\n      root,\n      srcDir: config.srcDir || \"src\",\n      extends: config.extends || [],\n      layers: [...(config.layers || [])],\n      outDir: config.outDir || \"dist\",\n      basePath,\n      trailingSlash: config.trailingSlash ?? false,\n      renderer: resolveFarmRenderer(config.renderer),\n      preset: config.preset ?? \"node-server\",\n      deploy: config.deploy || {},\n      storage: config.storage || {},\n      cache: config.cache || {},\n      auth: isResolvedAuthConfig(config.auth) ? config.auth : resolveFarmAuthConfig(config.auth),\n      integrations: config.integrations || {},\n      plugins: config.plugins || [],\n      migrations: config.migrations || { commands: [] },\n      cron: resolveCronConfig(config.cron),\n      workflows: resolveWorkflowsConfig(config.workflows),\n      api: normalizeFarmAppAPIConfig(config.api),\n      middleware: config.middleware || {},\n      routeRules: normalizeRouteRules(config.routeRules),\n      context: config.context || (() => undefined),\n      server: resolveFarmServerConfig(config.server),\n      serverActions: resolveServerActionsConfig(config.serverActions),\n      security: resolveFarmSecurityConfig(config.security),\n      images: resolveFarmImageConfig(config.images),\n      performance: resolveFarmPerformanceConfig(config.performance),\n      theme: resolveFarmThemeConfig(config.theme, basePath),\n      i18n: isResolvedI18nConfig(config.i18n)\n        ? config.i18n\n        : resolveFarmI18nConfig(config.i18n, {\n            root,\n            mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n            basePath,\n          }),\n      deploymentId: config.deploymentId || \"development\",\n      notFound: config.notFound || {},\n      serverRuntimeConfig: config.serverRuntimeConfig || {},\n      publicRuntimeConfig: config.publicRuntimeConfig || {},\n      docs: isResolvedDocsConfig(config.docs) ? config.docs : defaultDocsConfig,\n      md: resolveMarkdownConfig(config.md),\n      mdx: resolveMdxConfig(config.mdx),\n      observability: config.observability ?? false,\n      telemetry: config.telemetry !== false,\n      devtools: resolveFarmDevtoolsConfig(\n        config.devtools,\n        process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      ),\n      devIndicators: resolveFarmDevIndicatorsConfig(\n        config.devIndicators,\n        process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      ),\n      env: config.env || { server: {}, public: {} },\n      suppressLintOnLink: config.suppressLintOnLink ?? false,\n      experimental: {\n        serverComponents: config.experimental?.serverComponents ?? false,\n        serverActions: config.experimental?.serverActions ?? false,\n        isolatedClientHydration: config.experimental?.isolatedClientHydration ?? \"off\",\n        ppr: config.experimental?.ppr ?? false,\n        ...config.experimental,\n      },\n      agent: config.agent ?? {},\n      vite: config.vite || {},\n    };\n  }\n\n  private async verifyAppStructure(): Promise<void> {\n    const appDirs = getFarmAppDirectories(this.config);\n\n    const hasAppDirectory = (await Promise.all(appDirs.map((appDir) => fileExists(appDir)))).some(\n      Boolean,\n    );\n\n    if (!hasAppDirectory) {\n      const routeFiles = getFarmSourceRoots(this.config).flatMap((source) =>\n        findProgrammaticRouteFiles(source.root, source.srcDir),\n      );\n      if (routeFiles.length > 0) {\n        return;\n      }\n\n      const appDir = resolveAppPath(this.config.root, this.config.srcDir, \"app\");\n      throw new Error(\n        `App directory not found at ${appDir}. ` +\n          \"Please create a src/app directory or extend a Farm layer containing routes.\",\n      );\n    }\n\n    const componentExtensions = getFarmRendererComponentExtensions(this.config.renderer);\n    const rootLayoutPaths = appDirs.flatMap((appDir) =>\n      componentExtensions.map((extension) => path.join(appDir, `layout${extension}`)),\n    );\n\n    const hasRootLayout = await Promise.all(rootLayoutPaths.map((p) => fileExists(p))).then(\n      (results) => results.some(Boolean),\n    );\n\n    if (!hasRootLayout) {\n      logger.warn(\n        `No root layout found. Consider creating src/app/layout${componentExtensions[0]} for consistent page structure.`,\n      );\n    }\n  }\n}\n\nfunction isResolvedI18nConfig(value: FarmConfig[\"i18n\"]): value is ResolvedFarmI18nConfig {\n  return Boolean(value && typeof value === \"object\" && \"enabled\" in value);\n}\n\nfunction isResolvedAuthConfig(value: FarmConfig[\"auth\"]): value is ResolvedFarmAuthConfig {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    \"emailAndPassword\" in value &&\n    \"database\" in value,\n  );\n}\n\nfunction normalizeFarmAppAPIConfig(config: FarmConfig[\"api\"]): ResolvedFarmAPIConfig {\n  if (typeof config?.baseURL === \"function\" || typeof config?.basePath === \"function\") {\n    throw new Error(\n      \"Farm API config resolver functions must be processed with resolveConfig() before creating a FarmApp.\",\n    );\n  }\n  return normalizeFarmAPIConfig(config as { baseURL?: string; basePath?: string } | undefined);\n}\n\nexport function createFarmApp(config?: FarmConfig, viteServer?: ViteDevServer): FarmApp {\n  return new FarmApp(config, viteServer);\n}\n","export interface EnvSchema<TOutput = unknown> {\n  parse(value: unknown): TOutput;\n}\n\nexport type EnvParser<TOutput = unknown> =\n  | EnvSchema<TOutput>\n  | ((value: string | undefined, context: { key: string; scope: \"server\" | \"public\" }) => TOutput);\n\nexport type EnvShape = Record<string, EnvParser<any>>;\n\nexport type InferEnvParser<TParser> =\n  TParser extends EnvSchema<infer TOutput>\n    ? TOutput\n    : TParser extends (value: string | undefined, context: any) => infer TOutput\n      ? TOutput\n      : never;\n\nexport type InferEnvShape<TShape> = TShape extends EnvShape\n  ? { [K in keyof TShape]: InferEnvParser<TShape[K]> }\n  : {};\n\nexport interface FarmEnvConfig<\n  TServer extends EnvShape = EnvShape,\n  TPublic extends EnvShape = EnvShape,\n> {\n  server?: TServer;\n  public?: TPublic;\n}\n\nexport interface ResolvedFarmEnv<\n  TServer extends Record<string, any> = Record<string, unknown>,\n  TPublic extends Record<string, any> = Record<string, unknown>,\n> {\n  server: TServer;\n  public: TPublic;\n}\n\nexport type InferEnv<TConfig> =\n  TConfig extends FarmEnvConfig<infer TServer, infer TPublic>\n    ? ResolvedFarmEnv<InferEnvShape<TServer>, InferEnvShape<TPublic>>\n    : ResolvedFarmEnv;\n\n/**\n * Augmented by generated src/farm.d.ts for project-specific autocomplete.\n */\nexport interface FarmEnvTypes {}\n\nexport type FarmServerEnv = FarmEnvTypes extends { server: infer TServer }\n  ? TServer extends Record<string, any>\n    ? TServer\n    : Record<string, unknown>\n  : Record<string, unknown>;\n\nexport type FarmPublicEnv = FarmEnvTypes extends { public: infer TPublic }\n  ? TPublic extends Record<string, any>\n    ? TPublic\n    : Record<string, unknown>\n  : Record<string, unknown>;\n\nexport type FarmTypedEnv = ResolvedFarmEnv<FarmServerEnv, FarmPublicEnv>;\n\ndeclare const __FARM_PUBLIC_ENV__: Record<string, unknown> | undefined;\ndeclare const __FARM_ENV__: ResolvedFarmEnv | undefined;\n\nconst FARM_ENV_SYMBOL = Symbol.for(\"farm.env\");\nconst farmEnvGlobal = globalThis as typeof globalThis & {\n  [FARM_ENV_SYMBOL]?: ResolvedFarmEnv;\n};\nlet currentEnv: ResolvedFarmEnv = getInitialEnv();\n\nexport function resolveEnv<TConfig extends FarmEnvConfig<any, any> | undefined>(\n  config: TConfig,\n  source: Record<string, string | undefined> = getProcessEnv(),\n): InferEnv<NonNullable<TConfig>> {\n  const resolved = {\n    server: resolveEnvScope(config?.server, source, \"server\"),\n    public: resolveEnvScope(config?.public, source, \"public\"),\n  } as InferEnv<NonNullable<TConfig>>;\n\n  return resolved;\n}\n\nexport function setEnv(env: ResolvedFarmEnv): void {\n  currentEnv = normalizeResolvedEnv(env);\n  if (typeof window === \"undefined\") {\n    farmEnvGlobal[FARM_ENV_SYMBOL] = currentEnv;\n  }\n}\n\nexport function getResolvedEnv<TEnv extends ResolvedFarmEnv = FarmTypedEnv>(): TEnv {\n  return getCurrentEnv() as TEnv;\n}\n\nexport function getEnv<TServer extends Record<string, any> = FarmServerEnv>(): TServer;\nexport function getEnv<TKey extends Extract<keyof FarmServerEnv, string>>(\n  key: TKey,\n): FarmServerEnv[TKey];\nexport function getEnv(key?: string): unknown {\n  assertServerEnvAccess();\n  if (key === undefined) {\n    return getCurrentEnv().server;\n  }\n\n  return getCurrentEnv().server[key];\n}\n\nexport function getPublicEnv<TPublic extends Record<string, any> = FarmPublicEnv>(): TPublic;\nexport function getPublicEnv<TKey extends Extract<keyof FarmPublicEnv, string>>(\n  key: TKey,\n): FarmPublicEnv[TKey];\nexport function getPublicEnv(key?: string): unknown {\n  if (key === undefined) {\n    return getCurrentEnv().public;\n  }\n\n  return getCurrentEnv().public[key];\n}\n\nexport const env = createEnvProxy(\"server\") as FarmServerEnv;\nexport const serverEnv = env;\nexport const publicEnv = createEnvProxy(\"public\") as FarmPublicEnv;\n\nfunction resolveEnvScope(\n  shape: EnvShape | undefined,\n  source: Record<string, string | undefined>,\n  scope: \"server\" | \"public\",\n): Record<string, unknown> {\n  if (!shape) {\n    return {};\n  }\n\n  const resolved: Record<string, unknown> = {};\n\n  for (const [key, parser] of Object.entries(shape)) {\n    try {\n      resolved[key] = parseEnvValue(parser, source[key], key, scope);\n    } catch (error) {\n      const message = error instanceof Error ? error.message : String(error);\n      throw new Error(`Invalid ${scope} env \"${key}\": ${message}`);\n    }\n  }\n\n  return resolved;\n}\n\nfunction parseEnvValue(\n  parser: EnvParser<any>,\n  value: string | undefined,\n  key: string,\n  scope: \"server\" | \"public\",\n): unknown {\n  if (typeof parser === \"function\") {\n    return parser(value, { key, scope });\n  }\n\n  if (parser && typeof parser.parse === \"function\") {\n    return parser.parse(value);\n  }\n\n  throw new Error(\"expected a parser function or schema with parse()\");\n}\n\nfunction createEnvProxy(scope: \"server\" | \"public\"): Record<string, unknown> {\n  return new Proxy(\n    {},\n    {\n      get(_target, property) {\n        if (typeof property === \"symbol\") {\n          return undefined;\n        }\n\n        const env = getEnvScope(scope);\n        return env[property];\n      },\n      ownKeys() {\n        return Reflect.ownKeys(getEnvScope(scope));\n      },\n      getOwnPropertyDescriptor(_target, property) {\n        const env = getEnvScope(scope);\n        if (!(property in env)) {\n          return undefined;\n        }\n\n        return {\n          enumerable: true,\n          configurable: true,\n          value: env[property as keyof typeof env],\n        };\n      },\n      has(_target, property) {\n        return property in getEnvScope(scope);\n      },\n    },\n  );\n}\n\nfunction getEnvScope(scope: \"server\" | \"public\"): Record<string, unknown> {\n  if (scope === \"server\") {\n    assertServerEnvAccess();\n  }\n\n  return getCurrentEnv()[scope] || {};\n}\n\nfunction assertServerEnvAccess(): void {\n  if (typeof window !== \"undefined\") {\n    throw new Error(\"Farm server env is not available in the browser. Use publicEnv.\");\n  }\n}\n\nfunction getInitialEnv(): ResolvedFarmEnv {\n  const injectedEnv = getInjectedEnv();\n  if (injectedEnv) {\n    return injectedEnv;\n  }\n\n  if (typeof window === \"undefined\" && farmEnvGlobal[FARM_ENV_SYMBOL]) {\n    return normalizeResolvedEnv(farmEnvGlobal[FARM_ENV_SYMBOL]);\n  }\n\n  return {\n    server: {},\n    public: getInjectedPublicEnv(),\n  };\n}\n\nfunction getCurrentEnv(): ResolvedFarmEnv {\n  if (typeof window === \"undefined\" && farmEnvGlobal[FARM_ENV_SYMBOL]) {\n    return farmEnvGlobal[FARM_ENV_SYMBOL];\n  }\n\n  return currentEnv;\n}\n\nfunction getInjectedEnv(): ResolvedFarmEnv | null {\n  try {\n    if (typeof __FARM_ENV__ !== \"undefined\" && __FARM_ENV__) {\n      return normalizeResolvedEnv(__FARM_ENV__);\n    }\n  } catch {\n    // The compile-time global is only defined in Farm server bundles.\n  }\n\n  return null;\n}\n\nfunction getInjectedPublicEnv(): Record<string, unknown> {\n  try {\n    if (typeof __FARM_PUBLIC_ENV__ !== \"undefined\" && __FARM_PUBLIC_ENV__) {\n      return __FARM_PUBLIC_ENV__;\n    }\n  } catch {\n    // The compile-time global is only defined in Farm browser bundles.\n  }\n\n  return {};\n}\n\nfunction normalizeResolvedEnv(env: ResolvedFarmEnv): ResolvedFarmEnv {\n  return {\n    server: isRecord(env.server) ? env.server : {},\n    public: isRecord(env.public) ? env.public : {},\n  };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction getProcessEnv(): Record<string, string | undefined> {\n  if (typeof process !== \"undefined\" && process.env) {\n    return process.env;\n  }\n\n  return {};\n}\n","// Tailwind v4 syntax (used with @tailwindcss/vite – no PostCSS or tailwind.config)\nexport const defaultGlobalCSS = `@import \"tailwindcss\";\n`;\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { FarmClientPlugin } from \"./client/plugin\";\nimport type { FarmPlugin, FarmPluginClientConfig } from \"./plugin\";\n\nexport interface ResolvedFarmClientPlugin {\n  name: string;\n  version?: string;\n  enforce?: \"pre\" | \"post\";\n  definition: FarmClientPlugin;\n  publicData?: unknown;\n}\n\nexport interface FarmClientPluginEntryCode {\n  imports: string;\n  registrations: string;\n  plugins: ResolvedFarmClientPlugin[];\n}\n\nconst CLIENT_KEYS = [\n  \"public\",\n  \"setup\",\n  \"hydration\",\n  \"navigation\",\n  \"error\",\n  \"performance\",\n  \"close\",\n] as const;\nconst HYDRATION_KEYS = [\"before\", \"after\"] as const;\nconst NAVIGATION_KEYS = [\"before\", \"loaded\", \"resolved\", \"rendered\", \"error\"] as const;\nconst APP_CLIENT_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"mjs\"] as const;\n\n/** Resolve the optional application-owned browser lifecycle entry. */\nexport function resolveFarmAppClientEntry(\n  root = process.cwd(),\n  srcDir = \"src\",\n): string | undefined {\n  const sourceRoot = path.resolve(root, srcDir);\n  for (const extension of APP_CLIENT_EXTENSIONS) {\n    const candidate = path.join(sourceRoot, `client.${extension}`);\n    if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;\n  }\n  return undefined;\n}\n\nexport function resolveFarmClientPlugins(\n  plugins: readonly FarmPlugin[] | undefined,\n  _root?: string,\n): ResolvedFarmClientPlugin[] {\n  if (!plugins?.length) return [];\n\n  return plugins.flatMap((plugin) => {\n    if (!plugin.client) return [];\n    assertClientLifecycle(plugin.client, plugin.name);\n    assertPublicData(plugin.client.public, plugin.name);\n\n    return [\n      {\n        name: plugin.name,\n        version: plugin.version,\n        enforce: plugin.enforce,\n        definition: plugin.client,\n        publicData: plugin.client.public,\n      },\n    ];\n  });\n}\n\nexport function generateFarmClientPluginEntryCode(\n  plugins: readonly FarmPlugin[] | undefined,\n  root?: string,\n  srcDir = \"src\",\n  appPublicData?: unknown,\n): FarmClientPluginEntryCode {\n  const resolved = resolveFarmClientPlugins(plugins, root);\n  const appClientEntry = root ? resolveFarmAppClientEntry(root, srcDir) : undefined;\n  const imports = appClientEntry\n    ? `import farmAppClientDefinition from ${JSON.stringify(appClientEntry.replace(/\\\\/g, \"/\"))};`\n    : \"\";\n  const serializedPlugins = resolved.map(\n    (plugin) => `  {\n    name: ${JSON.stringify(plugin.name)},\n    version: ${serializeOptionalString(plugin.version)},\n    enforce: ${serializeOptionalString(plugin.enforce)},\n    definition: ${serializeClientLifecycle(plugin.definition, plugin.name)},\n    public: ${serializePublicData(plugin.publicData)},\n  }`,\n  );\n  if (appClientEntry) {\n    assertPublicData(appPublicData, \"farm:app-client\");\n    serializedPlugins.push(`  {\n    name: \"farm:app-client\",\n    enforce: \"post\",\n    definition: farmAppClientDefinition,\n    public: ${serializePublicData(appPublicData)},\n  }`);\n  }\n  const registrations = `[\n${serializedPlugins.join(\",\\n\")}\n]`;\n\n  return { imports, registrations, plugins: resolved };\n}\n\nfunction assertClientLifecycle(client: FarmPluginClientConfig, pluginName: string): void {\n  assertLifecycleObject(client, pluginName, \"client\", CLIENT_KEYS);\n  assertHook(client.setup, pluginName, \"client.setup\");\n  assertHook(client.error, pluginName, \"client.error\");\n  assertHook(client.performance, pluginName, \"client.performance\");\n  assertHook(client.close, pluginName, \"client.close\");\n\n  if (client.hydration !== undefined) {\n    assertLifecycleObject(client.hydration, pluginName, \"client.hydration\", HYDRATION_KEYS);\n    assertHook(client.hydration.before, pluginName, \"client.hydration.before\");\n    assertHook(client.hydration.after, pluginName, \"client.hydration.after\");\n  }\n\n  if (client.navigation !== undefined) {\n    assertLifecycleObject(client.navigation, pluginName, \"client.navigation\", NAVIGATION_KEYS);\n    for (const key of NAVIGATION_KEYS) {\n      assertHook(client.navigation[key], pluginName, `client.navigation.${key}`);\n    }\n  }\n}\n\nfunction assertLifecycleObject(\n  value: unknown,\n  pluginName: string,\n  location: string,\n  allowedKeys: readonly string[],\n): asserts value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be an object`);\n  }\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a plain object`);\n  }\n\n  for (const key of Reflect.ownKeys(value)) {\n    if (typeof key === \"symbol\") {\n      throw new TypeError(`Client plugin \"${pluginName}\" ${location} cannot contain symbol keys`);\n    }\n    if (!allowedKeys.includes(key)) {\n      throw new TypeError(`Client plugin \"${pluginName}\" has an unknown ${location}.${key} option`);\n    }\n    const descriptor = Object.getOwnPropertyDescriptor(value, key);\n    if (!descriptor?.enumerable) {\n      throw new TypeError(`Client plugin \"${pluginName}\" ${location}.${key} must be enumerable`);\n    }\n    if (!(\"value\" in descriptor)) {\n      throw new TypeError(`Client plugin \"${pluginName}\" ${location}.${key} cannot be an accessor`);\n    }\n  }\n}\n\nfunction assertHook(value: unknown, pluginName: string, location: string): void {\n  if (value === undefined) return;\n  if (typeof value !== \"function\") {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a function`);\n  }\n  functionSource(value, pluginName, location);\n}\n\nfunction serializeClientLifecycle(definition: FarmClientPlugin, pluginName: string): string {\n  const fields: string[] = [];\n  pushHook(fields, \"setup\", definition.setup, pluginName, \"client.setup\", 2);\n  pushHookGroup(fields, \"hydration\", definition.hydration, HYDRATION_KEYS, pluginName, 2);\n  pushHookGroup(fields, \"navigation\", definition.navigation, NAVIGATION_KEYS, pluginName, 2);\n  pushHook(fields, \"error\", definition.error, pluginName, \"client.error\", 2);\n  pushHook(fields, \"performance\", definition.performance, pluginName, \"client.performance\", 2);\n  pushHook(fields, \"close\", definition.close, pluginName, \"client.close\", 2);\n\n  return fields.length ? `{\\n${fields.join(\",\\n\")}\\n  }` : \"{}\";\n}\n\nfunction pushHookGroup(\n  fields: string[],\n  groupName: \"hydration\" | \"navigation\",\n  group: Record<string, unknown> | undefined,\n  keys: readonly string[],\n  pluginName: string,\n  indent: number,\n): void {\n  if (!group) return;\n  const hooks: string[] = [];\n  for (const key of keys) {\n    pushHook(hooks, key, group[key], pluginName, `client.${groupName}.${key}`, indent + 2);\n  }\n  fields.push(\n    `${\" \".repeat(indent)}${JSON.stringify(groupName)}: {\\n${hooks.join(\",\\n\")}\\n${\" \".repeat(indent)}}`,\n  );\n}\n\nfunction pushHook(\n  fields: string[],\n  key: string,\n  hook: unknown,\n  pluginName: string,\n  location: string,\n  indent: number,\n): void {\n  if (hook === undefined) return;\n  fields.push(\n    `${\" \".repeat(indent)}${JSON.stringify(key)}: ${functionSource(hook, pluginName, location)}`,\n  );\n}\n\nfunction functionSource(value: unknown, pluginName: string, location: string): string {\n  if (typeof value !== \"function\") {\n    throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a function`);\n  }\n\n  const source = Function.prototype.toString.call(value).trim();\n  if (!source || source.includes(\"[native code]\")) {\n    throw new TypeError(\n      `Client plugin \"${pluginName}\" ${location} must be authored inline and cannot be native or bound`,\n    );\n  }\n\n  if (/^(?:async\\s+)?function(?:\\s*\\*)?(?:\\s+|\\()/.test(source)) {\n    return `(${source})`;\n  }\n\n  const method = source.match(/^(async\\s+)?(\\*\\s*)?[$A-Z_a-z][$\\w]*\\s*(\\([\\s\\S]*)$/);\n  if (method) {\n    const asyncPrefix = method[1] ?? \"\";\n    const generator = method[2] ? \"*\" : \"\";\n    return `(${asyncPrefix}function${generator}${method[3]})`;\n  }\n\n  if (source.includes(\"=>\")) return `(${source})`;\n\n  throw new TypeError(\n    `Client plugin \"${pluginName}\" ${location} must use a function, method, or arrow function`,\n  );\n}\n\nfunction assertPublicData(value: unknown, pluginName: string): void {\n  if (value === undefined) return;\n  const seen = new WeakSet<object>();\n\n  const visit = (current: unknown, pathSegments: string[]): void => {\n    if (current === null || typeof current === \"string\" || typeof current === \"boolean\") {\n      return;\n    }\n    if (typeof current === \"number\") {\n      if (Number.isFinite(current)) return;\n      throwPublicDataError(pluginName, pathSegments, \"must be a finite number\");\n    }\n    if (typeof current !== \"object\") {\n      throwPublicDataError(pluginName, pathSegments, `cannot contain ${typeof current} values`);\n    }\n    if (seen.has(current)) {\n      throwPublicDataError(pluginName, pathSegments, \"cannot contain circular references\");\n    }\n    seen.add(current);\n\n    if (Array.isArray(current)) {\n      for (let index = 0; index < current.length; index += 1) {\n        if (!Object.prototype.hasOwnProperty.call(current, index)) {\n          throwPublicDataError(\n            pluginName,\n            [...pathSegments, String(index)],\n            \"cannot contain sparse array slots\",\n          );\n        }\n        visit(current[index], [...pathSegments, String(index)]);\n      }\n      for (const key of Reflect.ownKeys(current)) {\n        if (key === \"length\" || (typeof key === \"string\" && isArrayIndex(key))) continue;\n        throwPublicDataError(\n          pluginName,\n          pathSegments,\n          typeof key === \"symbol\"\n            ? \"cannot contain symbol keys\"\n            : `cannot contain non-index array property ${key}`,\n        );\n      }\n      seen.delete(current);\n      return;\n    }\n\n    const prototype = Object.getPrototypeOf(current);\n    if (prototype !== Object.prototype && prototype !== null) {\n      throwPublicDataError(pluginName, pathSegments, \"must contain only plain objects and arrays\");\n    }\n    for (const key of Reflect.ownKeys(current)) {\n      if (typeof key === \"symbol\") {\n        throwPublicDataError(pluginName, pathSegments, \"cannot contain symbol keys\");\n      }\n      const descriptor = Object.getOwnPropertyDescriptor(current, key);\n      if (!descriptor?.enumerable) {\n        throwPublicDataError(\n          pluginName,\n          [...pathSegments, key],\n          \"cannot contain non-enumerable properties\",\n        );\n      }\n      if (!(\"value\" in descriptor)) {\n        throwPublicDataError(\n          pluginName,\n          [...pathSegments, key],\n          \"cannot contain accessor properties\",\n        );\n      }\n      visit(descriptor.value, [...pathSegments, key]);\n    }\n    seen.delete(current);\n  };\n\n  visit(value, []);\n}\n\nfunction throwPublicDataError(pluginName: string, pathSegments: string[], message: string): never {\n  const location = pathSegments.length ? ` at client.public.${pathSegments.join(\".\")}` : \"\";\n  throw new TypeError(`Client plugin \"${pluginName}\"${location} ${message}`);\n}\n\nfunction serializePublicData(value: unknown): string {\n  if (value === undefined) return \"undefined\";\n  return `JSON.parse(${JSON.stringify(JSON.stringify(value))})`;\n}\n\nfunction serializeOptionalString(value: string | undefined): string {\n  return value === undefined ? \"undefined\" : JSON.stringify(value);\n}\n\nfunction isArrayIndex(key: string): boolean {\n  const value = Number(key);\n  return Number.isInteger(value) && value >= 0 && value < 4_294_967_295 && String(value) === key;\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { FarmCacheUserConfig } from \"./cache\";\n\nconst ADAPTER_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"jsx\", \"mts\", \"mjs\"] as const;\n\nexport interface ResolvedClientCacheAdapterEntry {\n  /** Absolute adapter module path with forward slashes, ready for codegen. */\n  importPath: string;\n  options: { version?: string; flushDelayMs?: number };\n}\n\nexport interface ClientCachePersistenceEntryCode {\n  imports: string;\n  init: string;\n}\n\n/**\n * Resolve `cache.client.adapter` from configuration to an absolute module\n * path for the generated client entries. Fails the build with an actionable\n * error when the option is set but the module cannot be found.\n */\nexport function resolveFarmClientCacheAdapterEntry(\n  root: string,\n  cache: FarmCacheUserConfig | undefined,\n): ResolvedClientCacheAdapterEntry | undefined {\n  const client = cache?.client;\n  const adapter = client?.adapter;\n  if (adapter === undefined) return undefined;\n\n  if (typeof adapter !== \"string\" || adapter.trim().length === 0) {\n    throw new Error(\n      'cache.client.adapter must be a module path string, for example \"./src/cache-adapter\".',\n    );\n  }\n\n  const resolved = path.resolve(root, adapter);\n  const found = resolveAdapterFile(resolved);\n  if (!found) {\n    throw new Error(\n      `cache.client.adapter was not found: ${adapter} (resolved to ${resolved}). ` +\n        \"Point it at a client module whose default export is created with defineClientCacheAdapter().\",\n    );\n  }\n\n  const options: ResolvedClientCacheAdapterEntry[\"options\"] = {};\n  if (client?.version !== undefined) options.version = client.version;\n  if (client?.flushDelayMs !== undefined) options.flushDelayMs = client.flushDelayMs;\n  return { importPath: found.replace(/\\\\/g, \"/\"), options };\n}\n\nfunction resolveAdapterFile(resolved: string): string | undefined {\n  if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) return resolved;\n  for (const extension of ADAPTER_EXTENSIONS) {\n    const candidate = `${resolved}.${extension}`;\n    if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate;\n  }\n  return undefined;\n}\n\n/**\n * Code fragments for the generated client entries: an import of the user's\n * adapter module and an init call that runs before hydration starts. Empty\n * strings when persistence is not configured, so entries stay unchanged.\n */\nexport function generateClientCachePersistenceCode(\n  entry: ResolvedClientCacheAdapterEntry | undefined,\n): ClientCachePersistenceEntryCode {\n  if (!entry) return { imports: \"\", init: \"\" };\n\n  return {\n    imports: [\n      `import * as __farmClientCacheAdapterModule from ${JSON.stringify(entry.importPath)};`,\n      `import { initConfiguredClientCachePersistence as __farmInitClientCachePersistence } from \"@farm.js/core/client\";`,\n    ].join(\"\\n\"),\n    init: `__farmInitClientCachePersistence(__farmClientCacheAdapterModule, ${JSON.stringify(entry.options)});`,\n  };\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 { createEndpoint as betterCallEndpoint } from \"better-call\";\nimport { applyFarmCacheInvalidationTargets, type FarmCacheInvalidationTarget } from \"../cache\";\nimport { isMultipartSchema, type MultipartSchema, type TypedFormData } from \"./transport\";\nimport type { RouteSchema, RouteSchemaInput, RouteSchemaOutput } from \"./route-schema\";\n\n// Share the route factory's Zod and Standard Schema contract.\ntype AnySchema = RouteSchema;\n\ntype MaybePromise<T> = T | Promise<T>;\ntype Simplify<T> = { [TKey in keyof T]: T[TKey] } & {};\ntype UnionToIntersection<T> = (T extends unknown ? (value: T) => void : never) extends (\n  value: infer TIntersection,\n) => void\n  ? TIntersection\n  : never;\n\n// Handlers receive parsed output; callers supply the schema input.\ntype InferOutput<T> = RouteSchemaOutput<T>;\n\ntype InferInput<T> = T extends { _input: infer I }\n  ? I\n  : T extends { \"~standard\": unknown }\n    ? RouteSchemaInput<T>\n    : T extends { parse: (data: infer I) => unknown }\n      ? I\n      : unknown;\n\ntype InferBodyInput<T> =\n  T extends MultipartSchema<AnySchema> ? TypedFormData<InferInput<T>> : InferInput<T>;\n\ntype InferHeadersOutput<T> = [T] extends [never]\n  ? Record<string, string>\n  : T extends AnySchema\n    ? InferOutput<T>\n    : Record<string, string>;\n\nexport type EndpointErrorSchema = AnySchema & { parse: (data: unknown) => unknown };\n\ntype EndpointErrorDefinitionBase<TStatus extends number> = {\n  status: TStatus;\n  /** Public message safe to expose to API callers. */\n  message?: string;\n};\n\nexport type EndpointErrorDefinition<\n  TSchema extends EndpointErrorSchema = EndpointErrorSchema,\n  TStatus extends number = number,\n> = EndpointErrorDefinitionBase<TStatus> &\n  (\n    | {\n        /** Schema for the public error payload exposed to API callers. */\n        data: TSchema;\n        schema?: never;\n      }\n    | {\n        data?: never;\n        /** @deprecated Use `data` for consistency with server functions. */\n        schema: TSchema;\n      }\n  );\n\nexport type EndpointErrorDefinitions = Record<\n  string,\n  EndpointErrorDefinition<EndpointErrorSchema, number>\n>;\n\ntype InferEndpointErrorSchema<TDefinition> = TDefinition extends {\n  data: infer TSchema extends AnySchema;\n}\n  ? TSchema\n  : TDefinition extends { schema: infer TSchema extends AnySchema }\n    ? TSchema\n    : never;\n\nexport type EndpointErrorContracts<TErrors extends EndpointErrorDefinitions> = {\n  [TCode in keyof TErrors]: {\n    data: InferOutput<InferEndpointErrorSchema<TErrors[TCode]>>;\n    status: TErrors[TCode][\"status\"];\n  };\n};\n\nexport type EndpointErrorHandler<TErrors extends EndpointErrorDefinitions> = <\n  TCode extends keyof TErrors & string,\n>(\n  code: TCode,\n  data: InferInput<InferEndpointErrorSchema<TErrors[TCode]>>,\n) => never;\n\n/** @deprecated Use `EndpointErrorHandler`. */\nexport type EndpointFail<TErrors extends EndpointErrorDefinitions> = EndpointErrorHandler<TErrors>;\n\nexport class EndpointFailure<TCode extends string = string, TData = unknown> extends Error {\n  readonly code: TCode;\n  readonly data: TData;\n  readonly status: number;\n\n  constructor(\n    code: TCode,\n    data: TData,\n    options: {\n      status: number;\n      message: string;\n    },\n  ) {\n    super(options.message);\n    this.name = \"EndpointFailure\";\n    this.code = code;\n    this.data = data;\n    this.status = options.status;\n  }\n}\n\nexport function isEndpointFailure(value: unknown): value is EndpointFailure<string, unknown> {\n  return value instanceof EndpointFailure;\n}\n\nexport type EndpointParamValue = string | string[];\nexport type EndpointParams = Record<string, EndpointParamValue>;\n\nexport type EndpointMiddlewareContext<\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> = {\n  body: TBody;\n  query: TQuery;\n  headers: THeaders;\n  request: Request;\n  /** Context accumulated from middleware that ran earlier in the chain. */\n  context: Readonly<TContext>;\n  params: EndpointParams;\n};\n\nexport type EndpointMiddlewareResult<TProvidedContext extends object = object> =\n  | TProvidedContext\n  | true\n  | false\n  | Response;\n\n/** A plain async function. No wrapper or `next()` callback is required. */\nexport type EndpointMiddleware<\n  TProvidedContext extends object = object,\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> = (\n  ctx: EndpointMiddlewareContext<TContext, TBody, TQuery, THeaders>,\n) => MaybePromise<EndpointMiddlewareResult<TProvidedContext>>;\n\nexport type AnyEndpointMiddleware = (ctx: EndpointMiddlewareContext<any, any, any, any>) => unknown;\n\nexport type EndpointInvalidationTarget = FarmCacheInvalidationTarget;\n\nexport type EndpointInvalidationContext<\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> = EndpointMiddlewareContext<TContext, TBody, TQuery, THeaders> & {\n  /** The raw value returned by the endpoint handler. */\n  result: unknown;\n};\n\nexport type EndpointInvalidations<\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> =\n  | readonly EndpointInvalidationTarget[]\n  | ((\n      context: EndpointInvalidationContext<TContext, TBody, TQuery, THeaders>,\n    ) => readonly EndpointInvalidationTarget[] | Promise<readonly EndpointInvalidationTarget[]>);\n\ntype ValidateEndpointMiddlewares<TMiddlewares extends readonly AnyEndpointMiddleware[]> = {\n  readonly [TIndex in keyof TMiddlewares]: TMiddlewares[TIndex] extends AnyEndpointMiddleware\n    ? [Awaited<ReturnType<TMiddlewares[TIndex]>>] extends [EndpointMiddlewareResult<object>]\n      ? TMiddlewares[TIndex]\n      : never\n    : never;\n};\n\ntype ContextFromMiddlewareResult<TResult> =\n  Exclude<TResult, Response | boolean> extends infer TContext\n    ? [TContext] extends [never]\n      ? {}\n      : TContext extends object\n        ? TContext\n        : {}\n    : {};\n\ntype ContextFromMiddleware<TMiddleware> = TMiddleware extends (...args: any[]) => infer TResult\n  ? ContextFromMiddlewareResult<Awaited<TResult>>\n  : {};\n\nexport type InferEndpointMiddlewareContext<\n  TMiddlewares extends readonly ((...args: any[]) => any)[],\n  TContext extends object = {},\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n  ? TMiddleware extends (...args: any[]) => any\n    ? TRest extends readonly ((...args: any[]) => any)[]\n      ? InferEndpointMiddlewareContext<\n          TRest,\n          Simplify<TContext & ContextFromMiddleware<TMiddleware>>\n        >\n      : Simplify<TContext>\n    : Simplify<TContext>\n  : number extends TMiddlewares[\"length\"]\n    ? Simplify<TContext & UnionToIntersection<ContextFromMiddleware<TMiddlewares[number]>>>\n    : Simplify<TContext>;\n\nexport type EndpointOptions<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TMiddlewares extends readonly AnyEndpointMiddleware[] = readonly [],\n  TErrors extends EndpointErrorDefinitions = {},\n> = {\n  method?: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"OPTIONS\";\n  body?: TBody;\n  query?: TQuery;\n  headers?: THeaders;\n  middleware?: TMiddlewares;\n  /**\n   * Cache keys, tags, and route paths made stale after a successful handler result.\n   * The resolver receives validated input and middleware context.\n   */\n  invalidates?: EndpointInvalidations<\n    InferEndpointMiddlewareContext<TMiddlewares>,\n    InferOutput<TBody>,\n    InferOutput<TQuery>,\n    InferHeadersOutput<THeaders>\n  >;\n  errors?: TErrors;\n  /** @deprecated Use plain functions in `middleware` for Farm endpoint middleware. */\n  use?: any[];\n};\n\nexport type EndpointHandler<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n  TContext extends object = {},\n  TErrors extends EndpointErrorDefinitions = {},\n> = (ctx: {\n  body: InferOutput<TBody>;\n  query: InferOutput<TQuery>;\n  headers: InferHeadersOutput<THeaders>;\n  request: Request;\n  context: Readonly<TContext>;\n  params: EndpointParams;\n  error: EndpointErrorHandler<TErrors>;\n  /** @deprecated Use `error`. */\n  fail: EndpointFail<TErrors>;\n}) => Promise<TResponse> | TResponse;\n\n// Type to represent an endpoint with its input/output types\nexport type TypedEndpoint<\n  TBody = never,\n  TQuery = never,\n  TResponse = any,\n  THeaders = Record<string, string>,\n  TErrors = never,\n  TBodyInput = TBody,\n  TQueryInput = TQuery,\n> = {\n  __types: {\n    body: TBody;\n    inputBody: TBodyInput;\n    query: TQuery;\n    inputQuery: TQueryInput;\n    headers: THeaders;\n    response: TResponse;\n    errors: TErrors;\n  };\n  __path?: string;\n  __method?: string;\n} & ((options?: { body?: TBodyInput; query?: TQueryInput }) => Promise<TResponse>);\n\ntype CreatedEndpoint<\n  TBody extends AnySchema,\n  TQuery extends AnySchema,\n  THeaders extends AnySchema,\n  TResponse,\n  TErrors extends EndpointErrorDefinitions = {},\n> = TypedEndpoint<\n  InferOutput<TBody>,\n  InferOutput<TQuery>,\n  Awaited<TResponse>,\n  InferHeadersOutput<THeaders>,\n  EndpointErrorContracts<TErrors>,\n  InferBodyInput<TBody>,\n  InferInput<TQuery>\n>;\n\ntype AnyEndpointOptions = EndpointOptions<\n  AnySchema,\n  AnySchema,\n  AnySchema,\n  readonly AnyEndpointMiddleware[],\n  EndpointErrorDefinitions\n>;\ntype EndpointBodyFromOptions<TOptions> = TOptions extends {\n  body: infer TBody extends AnySchema;\n}\n  ? TBody\n  : never;\ntype EndpointQueryFromOptions<TOptions> = TOptions extends {\n  query: infer TQuery extends AnySchema;\n}\n  ? TQuery\n  : never;\ntype EndpointHeadersFromOptions<TOptions> = TOptions extends {\n  headers: infer THeaders extends AnySchema;\n}\n  ? THeaders\n  : never;\ntype EndpointMiddlewaresFromOptions<TOptions> = TOptions extends {\n  middleware: infer TMiddlewares extends readonly AnyEndpointMiddleware[];\n}\n  ? TMiddlewares\n  : readonly [];\ntype EndpointErrorsFromOptions<TOptions> = TOptions extends {\n  errors: infer TErrors extends EndpointErrorDefinitions;\n}\n  ? TErrors\n  : {};\ntype MethodlessEndpointOptions = Omit<AnyEndpointOptions, \"method\">;\ntype EndpointHandlerFromOptions<TOptions, TResponse> = EndpointHandler<\n  EndpointBodyFromOptions<TOptions>,\n  EndpointQueryFromOptions<TOptions>,\n  EndpointHeadersFromOptions<TOptions>,\n  TResponse,\n  InferEndpointMiddlewareContext<EndpointMiddlewaresFromOptions<TOptions>>,\n  EndpointErrorsFromOptions<TOptions>\n>;\ntype ValidatedEndpointHandlerFromOptions<TOptions, TResponse> = EndpointHandlerFromOptions<\n  TOptions,\n  TResponse\n> &\n  (EndpointMiddlewaresFromOptions<TOptions> extends ValidateEndpointMiddlewares<\n    EndpointMiddlewaresFromOptions<TOptions>\n  >\n    ? unknown\n    : never);\ntype CreatedEndpointFromOptions<TOptions, TResponse> = CreatedEndpoint<\n  EndpointBodyFromOptions<TOptions>,\n  EndpointQueryFromOptions<TOptions>,\n  EndpointHeadersFromOptions<TOptions>,\n  TResponse,\n  EndpointErrorsFromOptions<TOptions>\n>;\n\n/**\n * Create a Farm.js API endpoint\n *\n * Supports two patterns:\n * 1. File-based routing (path auto-inferred from file location):\n *    `export const POST = createEndpoint({ method: 'POST', body: schema }, handler)`\n *    `createEndpoint({ method: 'GET', query: z.object({...}) }, handler)`\n *\n * 2. Explicit path (for routes.ts at project root):\n *    `createEndpoint('/api/hello', { method: 'GET', query: z.object({...}) }, handler)`\n */\nexport function createEndpoint<const TOptions extends AnyEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function createEndpoint<const TOptions extends AnyEndpointOptions, TResponse = any>(\n  path: string,\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function createEndpoint<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: EndpointOptions<TBody, TQuery, THeaders, readonly []>,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function createEndpoint<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  path: string,\n  options: EndpointOptions<TBody, TQuery, THeaders, readonly []>,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function createEndpoint(\n  pathOrOptions:\n    | string\n    | EndpointOptions<any, any, any, readonly AnyEndpointMiddleware[], EndpointErrorDefinitions>,\n  optionsOrHandler:\n    | EndpointOptions<any, any, any, readonly AnyEndpointMiddleware[], EndpointErrorDefinitions>\n    | EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n  maybeHandler?: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n): TypedEndpoint<any, any, any, any> {\n  // Determine if first arg is path or options\n  let path: string;\n  let options: EndpointOptions<\n    any,\n    any,\n    any,\n    readonly AnyEndpointMiddleware[],\n    EndpointErrorDefinitions\n  >;\n  let handler: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>;\n\n  if (typeof pathOrOptions === \"string\") {\n    // createEndpoint('/path', options, handler)\n    path = pathOrOptions;\n    options = optionsOrHandler as typeof options;\n    handler = maybeHandler as typeof handler;\n  } else {\n    // createEndpoint(options, handler) - path will be set by API plugin from file location\n    path = \"\";\n    options = pathOrOptions;\n    handler = optionsOrHandler as typeof handler;\n  }\n\n  if (typeof handler !== \"function\") {\n    throw new TypeError(\"createEndpoint requires a handler function\");\n  }\n\n  const middleware = normalizeEndpointMiddleware(options.middleware);\n  const errors = normalizeEndpointErrors(options.errors);\n  const error = createEndpointErrorHandler(errors);\n  const wrappedHandler = (async (ctx: EndpointMiddlewareContext<any, any, any, any>) => {\n    const execution = await runEndpointMiddleware(\n      middleware,\n      ctx,\n      handler,\n      error,\n      options.invalidates,\n    );\n    return execution.result;\n  }) as typeof handler;\n  const {\n    middleware: _middleware,\n    errors: _errors,\n    invalidates: _invalidates,\n    ...betterCallOptions\n  } = options;\n\n  // Create the endpoint - path will be set later by API plugin if not provided\n  // We use a temporary path that will be replaced when the router is created\n  const endpoint = betterCallEndpoint(\n    path || \"/__farm_auto_path__\",\n    betterCallOptions as any,\n    wrappedHandler as any,\n  ) as any;\n\n  // Store the path and type information on the endpoint for later access\n  // Empty/undefined path means it will be inferred from file location by the API plugin\n  endpoint.__path = path || undefined;\n  endpoint.__method = options.method || \"GET\";\n  endpoint.__autoPath = !path; // Flag to indicate path should be auto-inferred\n  endpoint.__handler = wrappedHandler; // Used by Farm's route runtime.\n  endpoint.__farmInvoke = (ctx: EndpointMiddlewareContext<any, any, any, any>) =>\n    runEndpointMiddleware(middleware, ctx, handler, error, options.invalidates);\n  endpoint.__middleware = middleware;\n  endpoint.__sourceHandler = handler;\n  endpoint.__invalidates = options.invalidates;\n  endpoint.__errors = errors;\n\n  // Store type information for inference\n  endpoint.__types = {\n    body: options.body,\n    inputBody: isMultipartSchema(options.body) ? \"form-data\" : options.body,\n    query: options.query,\n    inputQuery: options.query,\n    headers: options.headers,\n    response: null as any,\n    errors,\n  };\n\n  return endpoint as any;\n}\n\nconst EMPTY_ENDPOINT_MIDDLEWARE = Object.freeze([]) as readonly AnyEndpointMiddleware[];\nconst EMPTY_ENDPOINT_CONTEXT = Object.freeze(Object.create(null)) as Readonly<\n  Record<string | symbol, unknown>\n>;\nconst UNSAFE_ENDPOINT_CONTEXT_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction normalizeEndpointErrors(\n  definitions: EndpointErrorDefinitions | undefined,\n): Readonly<EndpointErrorDefinitions> {\n  if (definitions === undefined) return Object.freeze({});\n  if (!isPlainEndpointContext(definitions)) {\n    throw new TypeError(\"createEndpoint errors must be an object\");\n  }\n\n  const normalized: EndpointErrorDefinitions = Object.create(null);\n  for (const [code, definition] of Object.entries(definitions)) {\n    if (!code.trim()) {\n      throw new TypeError(\"Endpoint error codes cannot be empty\");\n    }\n    if (!definition || typeof definition !== \"object\") {\n      throw new TypeError(`Endpoint error \"${code}\" must be an object`);\n    }\n    if (\n      !Number.isInteger(definition.status) ||\n      definition.status < 400 ||\n      definition.status > 599\n    ) {\n      throw new TypeError(`Endpoint error \"${code}\" status must be an integer between 400 and 599`);\n    }\n    const dataSchema = resolveEndpointErrorSchema(definition);\n    if (!dataSchema || typeof dataSchema.parse !== \"function\") {\n      throw new TypeError(`Endpoint error \"${code}\" requires a data schema with parse()`);\n    }\n    if (definition.message !== undefined && typeof definition.message !== \"string\") {\n      throw new TypeError(`Endpoint error \"${code}\" message must be a string`);\n    }\n\n    normalized[code] = Object.freeze({ ...definition });\n  }\n\n  return Object.freeze(normalized);\n}\n\nfunction resolveEndpointErrorSchema(\n  definition: EndpointErrorDefinition<EndpointErrorSchema, number>,\n): EndpointErrorSchema | undefined {\n  if (definition.data && definition.schema) {\n    throw new TypeError(\"Endpoint errors cannot define both data and schema\");\n  }\n  return definition.data ?? definition.schema;\n}\n\nfunction createEndpointErrorHandler(\n  definitions: Readonly<EndpointErrorDefinitions>,\n): EndpointErrorHandler<EndpointErrorDefinitions> {\n  return ((code: string, data: unknown): never => {\n    const definition = definitions[code];\n    if (!definition) {\n      throw new TypeError(`Endpoint error \"${code}\" is not declared`);\n    }\n\n    const parsed = resolveEndpointErrorSchema(definition)!.parse(data);\n    throw new EndpointFailure(code, parsed, {\n      status: definition.status,\n      message: definition.message ?? \"Request failed\",\n    });\n  }) as EndpointErrorHandler<EndpointErrorDefinitions>;\n}\n\nfunction normalizeEndpointMiddleware(\n  middleware: readonly AnyEndpointMiddleware[] | undefined,\n): readonly AnyEndpointMiddleware[] {\n  if (middleware === undefined) return EMPTY_ENDPOINT_MIDDLEWARE;\n  if (!Array.isArray(middleware)) {\n    throw new TypeError(\"createEndpoint middleware must be an array of functions\");\n  }\n\n  const normalized = [...middleware];\n  for (const entry of normalized) {\n    if (typeof entry !== \"function\") {\n      throw new TypeError(\"createEndpoint middleware entries must be functions\");\n    }\n  }\n\n  return Object.freeze(normalized);\n}\n\nasync function runEndpointMiddleware(\n  middleware: readonly AnyEndpointMiddleware[],\n  handlerContext: EndpointMiddlewareContext<any, any, any, any>,\n  handler: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n  error: EndpointErrorHandler<EndpointErrorDefinitions>,\n  invalidations: EndpointInvalidations<any, any, any, any> | undefined,\n): Promise<{\n  result: unknown;\n  context: Readonly<Record<string | symbol, unknown>>;\n  handlerExecuted: boolean;\n  invalidations: readonly string[];\n}> {\n  let context = createInitialEndpointContext(handlerContext.context);\n\n  for (let index = 0; index < middleware.length; index++) {\n    const result = await middleware[index]({ ...handlerContext, context });\n\n    if (isEndpointResponse(result)) {\n      return {\n        result,\n        context,\n        handlerExecuted: false,\n        invalidations: [],\n      };\n    }\n    if (result === false) {\n      return {\n        result: forbiddenEndpointResponse(),\n        context,\n        handlerExecuted: false,\n        invalidations: [],\n      };\n    }\n    if (result === true) continue;\n\n    if (!isPlainEndpointContext(result)) {\n      throw new TypeError(\n        `Endpoint middleware ${index + 1} must return an object, true, false, or a Response`,\n      );\n    }\n\n    context = mergeEndpointContext(context, result, index);\n  }\n\n  const result = await handler({ ...handlerContext, context, error, fail: error });\n  return {\n    result,\n    context,\n    handlerExecuted: true,\n    invalidations: await applyEndpointInvalidations(\n      invalidations,\n      {\n        ...handlerContext,\n        context,\n        result,\n      },\n      result,\n    ),\n  };\n}\n\nasync function applyEndpointInvalidations(\n  declaration: EndpointInvalidations<any, any, any, any> | undefined,\n  context: EndpointInvalidationContext<any, any, any, any>,\n  result: unknown,\n): Promise<readonly string[]> {\n  if (!declaration || (isEndpointResponse(result) && result.status >= 400)) {\n    return [];\n  }\n\n  const targets = typeof declaration === \"function\" ? await declaration(context) : declaration;\n  if (!Array.isArray(targets)) {\n    throw new TypeError(\n      \"Endpoint invalidates must resolve to an array of { key }, { path }, or { tag } targets\",\n    );\n  }\n\n  return applyFarmCacheInvalidationTargets(targets);\n}\n\nfunction createInitialEndpointContext(value: unknown) {\n  if (value === undefined || value === null) return EMPTY_ENDPOINT_CONTEXT;\n  if (!isPlainEndpointContext(value)) {\n    throw new TypeError(\"Endpoint context must be a plain object\");\n  }\n\n  return mergeEndpointContext(EMPTY_ENDPOINT_CONTEXT, value);\n}\n\nfunction mergeEndpointContext(\n  current: Readonly<Record<string | symbol, unknown>>,\n  added: object,\n  middlewareIndex?: number,\n) {\n  const next = Object.assign(Object.create(null), current) as Record<string | symbol, unknown>;\n\n  for (const key of Reflect.ownKeys(added)) {\n    if (!Object.prototype.propertyIsEnumerable.call(added, key)) continue;\n    if (typeof key === \"string\" && UNSAFE_ENDPOINT_CONTEXT_KEYS.has(key)) {\n      throw new TypeError(`Endpoint middleware cannot provide the unsafe context key \"${key}\"`);\n    }\n    if (Object.prototype.hasOwnProperty.call(current, key)) {\n      const source =\n        middlewareIndex === undefined\n          ? \"Endpoint context\"\n          : `Endpoint middleware ${middlewareIndex + 1}`;\n      throw new TypeError(`${source} cannot replace the existing context key \"${String(key)}\"`);\n    }\n    next[key] = (added as Record<string | symbol, unknown>)[key];\n  }\n\n  return Object.freeze(next);\n}\n\nfunction isPlainEndpointContext(value: unknown): value is object {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction isEndpointResponse(value: unknown): value is Response {\n  return (\n    value instanceof Response ||\n    (typeof value === \"object\" &&\n      value !== null &&\n      \"headers\" in value &&\n      \"status\" in value &&\n      typeof (value as Response).arrayBuffer === \"function\")\n  );\n}\n\nfunction forbiddenEndpointResponse() {\n  return new Response(JSON.stringify({ error: \"Forbidden\" }), {\n    status: 403,\n    headers: { \"Content-Type\": \"application/json\" },\n  });\n}\n\n/**\n * Convenience method for GET requests\n */\nexport function GET<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function GET<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function GET<\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<never, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<never, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<never, TQuery, THeaders, TResponse>;\nexport function GET(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"GET\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"GET\" }, args[1]);\n}\n\n/**\n * Convenience method for HEAD requests\n */\nexport function HEAD<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function HEAD<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function HEAD<\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<never, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<never, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<never, TQuery, THeaders, TResponse>;\nexport function HEAD(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"HEAD\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"HEAD\" }, args[1]);\n}\n\n/**\n * Convenience method for safe, idempotent QUERY requests with a request body\n */\nexport function QUERY<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function QUERY<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function QUERY<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function QUERY(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"QUERY\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"QUERY\" }, args[1]);\n}\n\n/**\n * Convenience method for POST requests\n */\nexport function POST<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function POST<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function POST<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function POST(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"POST\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"POST\" }, args[1]);\n}\n\n/**\n * Convenience method for PUT requests\n */\nexport function PUT<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function PUT<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function PUT<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function PUT(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"PUT\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"PUT\" }, args[1]);\n}\n\n/**\n * Convenience method for DELETE requests\n */\nexport function DELETE<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function DELETE<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function DELETE<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function DELETE(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"DELETE\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"DELETE\" }, args[1]);\n}\n\n/**\n * Convenience method for PATCH requests\n */\nexport function PATCH<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function PATCH<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function PATCH<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function PATCH(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"PATCH\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"PATCH\" }, args[1]);\n}\n\n/**\n * Convenience method for OPTIONS requests\n */\nexport function OPTIONS<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function OPTIONS<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function OPTIONS<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function OPTIONS(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"OPTIONS\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"OPTIONS\" }, args[1]);\n}\n","import {\n  createEndpoint,\n  type TypedEndpoint,\n  type AnyEndpointMiddleware,\n  type EndpointMiddlewareResult,\n  type InferEndpointMiddlewareContext,\n} from \"./endpoint\";\nimport {\n  assertBrowserStableRoutePath,\n  assertUniqueRouteParameters,\n  getRoutePatternShape,\n} from \"../routing/specificity\";\nimport type { RouteSchema, RouteSchemaInput, RouteSchemaOutput } from \"./route-schema\";\n\nexport type RouteMethod =\n  | \"GET\"\n  | \"HEAD\"\n  | \"QUERY\"\n  | \"POST\"\n  | \"PUT\"\n  | \"PATCH\"\n  | \"DELETE\"\n  | \"OPTIONS\";\nexport type RoutePathParams<Path extends string> = Path extends `${infer Head}/${infer Tail}`\n  ? RoutePathParams<Head> & RoutePathParams<Tail>\n  : Path extends `[[...${infer Name}]]`\n    ? { [K in Name]?: string[] }\n    : Path extends `[...${infer Name}]`\n      ? { [K in Name]: string[] }\n      : Path extends `[${infer Name}]`\n        ? { [K in Name]: string }\n        : {};\n\nexport interface RouteInputSchemas {\n  body?: RouteSchema;\n  query?: RouteSchema;\n  params?: RouteSchema;\n  headers?: RouteSchema;\n}\ntype Input<I, K extends PropertyKey> = K extends keyof I ? RouteSchemaInput<I[K]> : never;\ntype Output<I, K extends PropertyKey, Fallback = unknown> = K extends keyof I\n  ? RouteSchemaOutput<I[K]>\n  : Fallback;\n/** JSON responses have wire types, not server-side instances such as Date. */\nexport type RouteJSON<T> = T extends Response\n  ? unknown\n  : T extends { toJSON(): infer J }\n    ? RouteJSON<J>\n    : T extends bigint | symbol | ((...args: any[]) => any)\n      ? never\n      : T extends readonly (infer V)[]\n        ? RouteJSON<V>[]\n        : T extends object\n          ? { [K in keyof T]: RouteJSON<T[K]> }\n          : T;\n\nexport type RouteDefinition<\n  P extends string = string,\n  M extends RouteMethod = RouteMethod,\n  E = any,\n> = {\n  readonly path: P;\n  readonly method: M;\n  readonly endpoint: E;\n};\n\ntype RouteEndpoint<P extends string, I extends RouteInputSchemas, R> = TypedEndpoint<\n  Output<I, \"body\">,\n  Input<I, \"query\">,\n  RouteJSON<R>,\n  Input<I, \"headers\">,\n  never,\n  Input<I, \"body\">\n> & {\n  __types: { params: RoutePathParams<P>; inputHeaders: Input<I, \"headers\"> };\n};\n\ntype TrimStart<P extends string> = P extends `/${infer Rest}` ? TrimStart<Rest> : P;\ntype Join<P extends string, C extends string> = C extends \"\" ? P : `${P}/${TrimStart<C>}`;\ntype ParamsCheck<P extends string, I extends RouteInputSchemas> = I extends { params: infer S }\n  ? Exclude<keyof RoutePathParams<P>, keyof RouteSchemaOutput<S>> extends never\n    ? Exclude<keyof RouteSchemaOutput<S>, keyof RoutePathParams<P>> extends never\n      ? unknown\n      : { __error_unknown_route_params: never }\n    : { __error_missing_route_params: never }\n  : unknown;\n\ntype RouteMiddlewareResults = readonly (\n  | EndpointMiddlewareResult\n  | Promise<EndpointMiddlewareResult>\n)[];\n// Infer callback results directly so inline middleware is contextually typed before\n// its returned context is exposed to the route handler.\ntype RouteMiddlewares<Results extends readonly unknown[]> = {\n  readonly [K in keyof Results]: (context: Parameters<AnyEndpointMiddleware>[0]) => Results[K];\n};\n\nexport type RouteOptions<\n  P extends string,\n  I extends RouteInputSchemas,\n  O extends RouteSchema | undefined,\n  R,\n  MiddlewareResults extends RouteMiddlewareResults = RouteMiddlewareResults,\n> = {\n  input?: I & ParamsCheck<P, I>;\n  /** Validate plain JSON handler results. Raw Response/stream results are never buffered. */\n  output?: O;\n  middleware?: RouteMiddlewares<MiddlewareResults>;\n  handler(\n    request: Request,\n    context: {\n      input: {\n        body: Output<I, \"body\">;\n        query: Output<I, \"query\", Record<string, string | string[]>>;\n        headers: Output<I, \"headers\", Record<string, string>>;\n        params: Output<I, \"params\", RoutePathParams<P>>;\n      };\n      params: Output<I, \"params\", RoutePathParams<P>>;\n      context: Readonly<InferEndpointMiddlewareContext<RouteMiddlewares<MiddlewareResults>>>;\n    },\n  ): R | Promise<R>;\n};\n\ntype RouteBuilder<P extends string, M extends RouteMethod> = <\n  const C extends string,\n  const MiddlewareResults extends RouteMiddlewareResults,\n  const I extends RouteInputSchemas = {},\n  O extends RouteSchema | undefined = undefined,\n  R = unknown,\n>(\n  path: C,\n  options: RouteOptions<Join<P, C>, I, O, R, MiddlewareResults>,\n) => RouteDefinition<\n  Join<P, C>,\n  M,\n  RouteEndpoint<\n    Join<P, C>,\n    I,\n    Extract<Awaited<R>, Response> extends never\n      ? O extends RouteSchema\n        ? RouteSchemaOutput<O>\n        : Awaited<R>\n      : unknown\n  >\n>;\n\nexport type RouteFactory<P extends string = \"\"> = {\n  [M in Lowercase<RouteMethod>]: RouteBuilder<P, Uppercase<M> & RouteMethod>;\n} & {\n  /** Return a new builder; never mutate the parent scope. */\n  scope<const C extends string>(path: C): RouteFactory<Join<P, C>>;\n};\n\nexport type PluginRoutes = readonly RouteDefinition[];\nexport type PluginRoutesFactory<R extends PluginRoutes = PluginRoutes> = (context: {\n  route: RouteFactory;\n}) => R;\n\nexport function createRouteFactory(): RouteFactory {\n  return createRouteFactoryAt(\"\");\n}\n\nfunction createRouteFactoryAt(prefix: string): RouteFactory {\n  const factory: Record<string, unknown> = {\n    scope(child: string) {\n      return createRouteFactoryAt(joinRoutePath(prefix, child));\n    },\n  };\n  for (const method of [\n    \"GET\",\n    \"HEAD\",\n    \"QUERY\",\n    \"POST\",\n    \"PUT\",\n    \"PATCH\",\n    \"DELETE\",\n    \"OPTIONS\",\n  ] as const) {\n    factory[method.toLowerCase()] = (\n      child: string,\n      options: RouteOptions<string, any, any, any>,\n    ) => {\n      const path = joinRoutePath(prefix, child);\n      const input = options.input ?? {};\n      const endpoint = createEndpoint(\n        path,\n        {\n          method,\n          body: input.body,\n          query: input.query,\n          headers: input.headers,\n          middleware: options.middleware,\n        },\n        (ctx) =>\n          options.handler(ctx.request, {\n            input: { body: ctx.body, query: ctx.query, headers: ctx.headers, params: ctx.params },\n            params: ctx.params,\n            context: ctx.context,\n          }),\n      ) as any;\n      endpoint.__types.params = input.params;\n      endpoint.__output = options.output;\n      return Object.freeze({ path, method, endpoint });\n    };\n  }\n  return Object.freeze(factory) as RouteFactory;\n}\n\nfunction joinRoutePath(prefix: string, child: string): string {\n  if (typeof child !== \"string\") throw new TypeError(\"Route paths must be strings.\");\n  const path = child === \"\" ? prefix : `${prefix}/${child.replace(/^\\//, \"\")}`;\n  if (!(path === \"/api\" || path.startsWith(\"/api/\")) || /[?#]|\\/\\/|\\/$/.test(path)) {\n    throw new TypeError(\n      `Plugin route \"${path}\" must be a canonical /api path without a query, hash, or empty segment.`,\n    );\n  }\n  assertBrowserStableRoutePath(path);\n  assertUniqueRouteParameters(path, \"api\");\n  getRoutePatternShape(path, \"api\");\n  for (const segment of path.split(\"/\")) {\n    if ([\"__proto__\", \"constructor\", \"prototype\", \"$params\"].includes(segment)) {\n      throw new TypeError(`Route segment \"${segment}\" is reserved.`);\n    }\n  }\n  return path;\n}\n\ntype UnionToIntersection<U> = (U extends unknown ? (v: U) => void : never) extends (\n  v: infer I,\n) => void\n  ? I\n  : never;\ntype RouteTree<P extends string, M extends string, E> = P extends `${infer Head}/${infer Tail}`\n  ? { [K in Head]: RouteTree<Tail, M, E> }\n  : P extends \"\"\n    ? { [K in Lowercase<M>]: E }\n    : { [K in P]: { [Method in Lowercase<M>]: E } };\ntype HasMethodSegment<P extends string> = P extends `${infer H}/${infer T}`\n  ? H extends Lowercase<RouteMethod>\n    ? true\n    : HasMethodSegment<T>\n  : P extends Lowercase<RouteMethod>\n    ? true\n    : false;\ntype DefinitionTree<D> =\n  D extends RouteDefinition<infer P, infer M, infer E>\n    ? string extends P\n      ? {}\n      : (P extends `/api/integrations${string}` ? true : HasMethodSegment<P>) extends true\n        ? { [K in P extends `/api/${infer C}` ? `/${C}` : \"/\"]: { [Method in Lowercase<M>]: E } }\n        : RouteTree<P extends `/api/${infer C}` ? C : \"\", M, E>\n    : {};\nexport type PluginAPIRouter<C> = C extends { plugins: readonly (infer P)[] }\n  ? UnionToIntersection<\n      P extends { routes?: PluginRoutesFactory<infer R> } ? DefinitionTree<R[number]> : {}\n    >\n  : {};\n\nexport function resolvePluginRoutes(\n  plugins: readonly { name: string; routes?: PluginRoutesFactory }[] = [],\n): PluginRoutes {\n  return plugins.flatMap((plugin) => {\n    if (!plugin.routes) return [];\n    const routes = plugin.routes({ route: createRouteFactory() });\n    if (!Array.isArray(routes))\n      throw new TypeError(`Plugin \"${plugin.name}\" routes must return an array synchronously.`);\n    for (const route of routes) {\n      if (\n        !route ||\n        joinRoutePath(\"\", route.path) !== route.path ||\n        typeof route.endpoint !== \"function\" ||\n        ![\"GET\", \"HEAD\", \"QUERY\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\"].includes(\n          route.method,\n        )\n      ) {\n        throw new TypeError(`Plugin \"${plugin.name}\" returned an invalid API route.`);\n      }\n    }\n    return routes;\n  });\n}\n","import {\n  AmbiguousRouteError,\n  assertUniqueRouteParameters,\n  getRoutePatternShape,\n} from \"../routing/specificity\";\n\nexport interface APIRouteShapeSource<TSource> {\n  routePath: string;\n  source: TSource;\n  filePath: string;\n}\n\n/** Validate API URL shapes and return the lower-priority route replaced by this source. */\nexport function registerAPIRouteShape<TSource>(\n  shapes: Map<string, APIRouteShapeSource<TSource>>,\n  routePath: string,\n  filePath: string,\n  source: TSource,\n): string | undefined {\n  assertUniqueRouteParameters(routePath, \"api\");\n  const shape = getRoutePatternShape(routePath, \"api\");\n  const existing = shapes.get(shape);\n  const replacesPath = existing && existing.routePath !== routePath;\n\n  if (replacesPath && existing.source === source) {\n    throw new AmbiguousRouteError(\n      `Ambiguous API routes \"${existing.routePath}\" and \"${routePath}\" match the same URLs. Found ${existing.filePath} and ${filePath}. Keep only one route for this URL shape.`,\n    );\n  }\n\n  shapes.set(shape, { routePath, source, filePath });\n  return replacesPath ? existing.routePath : undefined;\n}\n","import { resolvePluginRoutes, type PluginRoutesFactory } from \"./route\";\nimport { registerAPIRouteShape } from \"./route-shape\";\n\ninterface MountedRoute {\n  path: string;\n  methods: string[];\n  endpoints: Record<string, any>;\n  filePath?: string;\n  pluginMethods?: string[];\n}\n\n/** The same registration step is used by dev discovery and the production bundle. */\nexport function mergePluginAPIRoutes(\n  existing: readonly MountedRoute[],\n  plugins: readonly { name: string; routes?: PluginRoutesFactory }[],\n  expected?: readonly { path: string; methods: readonly string[] }[],\n): Array<MountedRoute & { filePath: string }> {\n  const routes = new Map<string, MountedRoute & { filePath: string }>();\n  const shapes = new Map();\n  for (const route of existing) {\n    registerAPIRouteShape(shapes, route.path, route.filePath || route.path, \"app\");\n    routes.set(route.path, {\n      ...route,\n      filePath: route.filePath || \"\",\n      methods: [...route.methods],\n      endpoints: { ...route.endpoints },\n    });\n  }\n  for (const definition of resolvePluginRoutes(plugins)) {\n    registerAPIRouteShape(shapes, definition.path, `plugin:${definition.path}`, \"app\");\n    let route = routes.get(definition.path);\n    if (route?.methods.includes(definition.method)) {\n      throw new Error(\n        `Duplicate API route for ${definition.method} ${definition.path}. Plugin routes cannot override app or other plugin endpoints.`,\n      );\n    }\n    if (!route) {\n      route = { path: definition.path, filePath: \"\", methods: [], endpoints: {} };\n      routes.set(definition.path, route);\n    }\n    route.methods.push(definition.method);\n    route.pluginMethods = [...(route.pluginMethods ?? []), definition.method];\n    route.endpoints[definition.method] = definition.endpoint;\n  }\n  const result = [...routes.values()];\n  if (expected) {\n    const signature = (entries: readonly { path: string; methods: readonly string[] }[]) =>\n      entries\n        .map(({ path, methods }) => `${path}:${[...methods].sort().join(\",\")}`)\n        .sort()\n        .join(\"\\n\");\n    if (signature(result) !== signature(expected)) {\n      throw new Error(\n        \"Plugin API routes changed between build and runtime. Route paths and methods must be stable across environments; rebuild the app.\",\n      );\n    }\n  }\n  return result;\n}\n","import {\n  DEFAULT_FARM_API_BASE_PATH,\n  normalizeFarmAPIBasePath,\n  resolveFarmAPIRequestURL,\n  type ResolvedFarmAPIConfig,\n} from \"./config\";\n\n/** Return the same-origin path served by this Farm application. */\nexport function resolveFarmAPIServerBasePath(config: ResolvedFarmAPIConfig): string {\n  // Absolute API URLs belong to another origin and must not move local routes.\n  return config.baseURL.startsWith(\"/\") ? config.basePath : DEFAULT_FARM_API_BASE_PATH;\n}\n\n/** Translate a public local API pathname back to Farm's canonical `/api` route table. */\nexport function resolveFarmAPICanonicalPathname(\n  pathname: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): string {\n  const basePath = normalizeFarmAPIBasePath(serverBasePath);\n  if (basePath === DEFAULT_FARM_API_BASE_PATH) return pathname;\n\n  if (basePath === \"/\") {\n    return pathname === \"/\"\n      ? DEFAULT_FARM_API_BASE_PATH\n      : `${DEFAULT_FARM_API_BASE_PATH}${pathname.startsWith(\"/\") ? pathname : `/${pathname}`}`;\n  }\n\n  if (pathname === basePath) return DEFAULT_FARM_API_BASE_PATH;\n  if (pathname.startsWith(`${basePath}/`)) {\n    return `${DEFAULT_FARM_API_BASE_PATH}${pathname.slice(basePath.length)}`;\n  }\n  return pathname;\n}\n\n/** Resolve a canonical `/api` route to the path served by this application. */\nexport function resolveFarmAPIServerRoutePath(\n  routePath: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): string {\n  return resolveFarmAPIRequestURL(routePath, serverBasePath).pathname;\n}\n","/** Server-only schema contract shared by declarative routes and the API runtime. */\nexport interface RouteSchema {\n  readonly _input?: unknown;\n  readonly _output?: unknown;\n  parse?: (value: unknown) => unknown;\n  parseAsync?: (value: unknown) => Promise<unknown>;\n  readonly \"~standard\"?: {\n    readonly types?: { input: unknown; output: unknown };\n    validate(value: unknown): unknown;\n  };\n}\n\nexport type RouteSchemaInput<T> = T extends { _input: infer I }\n  ? I\n  : T extends { \"~standard\": { types?: { input: infer I } } }\n    ? I\n    : unknown;\n\nexport type RouteSchemaOutput<T> = T extends { _output: infer O }\n  ? O\n  : T extends { \"~standard\": { types?: { output: infer O } } }\n    ? O\n    : T extends { parse: (...args: any[]) => infer O }\n      ? Awaited<O>\n      : unknown;\n\nexport async function parseRouteSchema(schema: RouteSchema, value: unknown): Promise<unknown> {\n  if (schema[\"~standard\"]) {\n    const result = (await schema[\"~standard\"].validate(value)) as {\n      value?: unknown;\n      issues?: readonly unknown[];\n    };\n    if (result.issues)\n      throw Object.assign(new Error(\"Validation failed\"), { issues: result.issues });\n    return result.value;\n  }\n  if (schema.parseAsync) return schema.parseAsync(value);\n  if (schema.parse) return schema.parse(value);\n  throw new TypeError(\"Route validators must implement Standard Schema or parse().\");\n}\n","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 { _runWithCurrentRequest } from \"../server/request\";\nimport {\n  decodeFarmCacheInvalidations,\n  encodeFarmCacheInvalidations,\n  FARM_CACHE_INVALIDATION_HEADER,\n} from \"../cache-invalidation\";\nimport { isEndpointFailure, type EndpointFailure } from \"./endpoint\";\nimport {\n  bufferFarmRequestBody,\n  createFarmRequestBodyErrorResponse,\n  DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n} from \"../server-http\";\nimport { DEFAULT_FARM_API_BASE_PATH, normalizeFarmAPIBasePath } from \"./config\";\nimport { resolveFarmAPICanonicalPathname } from \"./server-path\";\nimport { parseRouteSchema } from \"./route-schema\";\nimport { omitFarmResponseBody } from \"../response-body\";\n\nexport { registerAPIRouteShape, type APIRouteShapeSource } from \"./route-shape\";\nexport { mergePluginAPIRoutes } from \"./plugin-route-runtime\";\n\nexport {\n  matchAPIRoute,\n  type APIRouteParams,\n  type APIRouteParamValue,\n  type APIRouteMatch,\n} from \"./route-pattern\";\nimport { matchAPIRoute, type APIRouteParams, type APIRouteMatch } from \"./route-pattern\";\ninterface APIRouteMethodTable {\n  methods: string[];\n  endpoints: Record<string, any>;\n}\n\nexport function resolveAPIRouteEndpoint(\n  route: APIRouteMethodTable,\n  method: string,\n): any | undefined {\n  const normalizedMethod = method.toUpperCase();\n  return (\n    route.endpoints[normalizedMethod] ??\n    (normalizedMethod === \"HEAD\" ? route.endpoints.GET : undefined)\n  );\n}\n\nexport function getAllowedAPIRouteMethods(route: APIRouteMethodTable): string[] {\n  const methods = [...route.methods];\n  const getIndex = methods.indexOf(\"GET\");\n  if (getIndex >= 0 && !methods.includes(\"HEAD\")) {\n    methods.splice(getIndex + 1, 0, \"HEAD\");\n  }\n  return methods;\n}\n\n/** Match canonical routes through a configurable same-origin public API path. */\nexport function matchAPIRouteAtBasePath<T extends { path: string }>(\n  routes: Map<string, T>,\n  pathname: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): APIRouteMatch<T> | null {\n  const directMatch = matchAPIRoute(routes, pathname);\n  if (directMatch) return directMatch;\n\n  const canonicalPathname = resolveFarmAPICanonicalPathname(pathname, serverBasePath);\n  return canonicalPathname === pathname ? null : matchAPIRoute(routes, canonicalPathname);\n}\n\n/** Test whether a pathname belongs to the configured local API surface. */\nexport function isFarmAPIPathname(\n  pathname: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): boolean {\n  const basePath = normalizeFarmAPIBasePath(serverBasePath);\n  return basePath !== \"/\" && (pathname === basePath || pathname.startsWith(`${basePath}/`));\n}\n\nexport async function invokeAPIRouteEndpoint(\n  endpoint: any,\n  request: Request,\n  params: APIRouteParams = {},\n  bodySizeLimit = DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n): Promise<Response> {\n  try {\n    request = await bufferFarmRequestBody(request, bodySizeLimit);\n  } catch (error) {\n    const response = createFarmRequestBodyErrorResponse(error);\n    if (response) return response;\n    throw error;\n  }\n\n  const response = await _runWithCurrentRequest(request, () =>\n    invokeAPIRouteEndpointInContext(endpoint, request, params),\n  );\n\n  if (request.method.toUpperCase() !== \"HEAD\") {\n    return response;\n  }\n\n  return omitFarmResponseBody(response);\n}\n\nasync function invokeAPIRouteEndpointInContext(\n  endpoint: any,\n  request: Request,\n  params: APIRouteParams,\n): Promise<Response> {\n  const queryContentTypeError = validateQueryContentType(request);\n  if (queryContentTypeError) {\n    return queryContentTypeError;\n  }\n\n  // `createEndpoint` brands its parsed-context handler explicitly. Plain route\n  // exports always receive the Web Request regardless of their parameter name;\n  // inferring a calling convention from `Function#toString()` misclassified\n  // valid handlers named `context`, `ctx`, or using destructuring.\n  const farmHandler = endpoint.__handler || null;\n\n  if (!farmHandler) {\n    const result = await endpoint(request, {\n      params: Promise.resolve(params),\n    });\n    return normalizeRouteResponse(result);\n  }\n\n  const url = new URL(request.url);\n  // Repeated keys collect into arrays, the same representation the rest of the\n  // framework hands to routes, and the same helper this path already uses for\n  // urlencoded and multipart bodies. Spread back onto a normal object so an\n  // endpoint without a query schema still receives the object shape it did\n  // before; `entriesToObject` has already dropped the prototype-poisoning keys.\n  const query: Record<string, string | string[]> = {\n    ...searchParamsToObject(url.searchParams),\n  };\n\n  let body: any = undefined;\n  if (request.method.toUpperCase() !== \"GET\" && request.method.toUpperCase() !== \"HEAD\") {\n    const parsedBody = await readRequestBody(request);\n    if (parsedBody.error) return parsedBody.error;\n    body = parsedBody.body;\n  }\n\n  const headers = Object.fromEntries(request.headers.entries());\n  const types = endpoint.__types || {};\n\n  const queryValidation = await validateInput(types.query, query, \"Invalid query parameters\");\n  if (queryValidation instanceof Response) {\n    return queryValidation;\n  }\n\n  const bodyValidation = await validateInput(types.body, body, \"Invalid request body\");\n  if (bodyValidation instanceof Response) {\n    return bodyValidation;\n  }\n\n  const headersValidation = await validateInput(types.headers, headers, \"Invalid request headers\");\n  if (headersValidation instanceof Response) {\n    return headersValidation;\n  }\n\n  const paramsValidation = await validateInput(types.params, params, \"Invalid route parameters\");\n  if (paramsValidation instanceof Response) return paramsValidation;\n\n  const handlerContext = {\n    query: queryValidation,\n    body: bodyValidation,\n    headers: headersValidation,\n    request,\n    context: {},\n    params: paramsValidation,\n  };\n  let execution: {\n    result: unknown;\n    context: unknown;\n    handlerExecuted: boolean;\n    invalidations: readonly string[];\n  };\n  try {\n    execution =\n      typeof endpoint.__farmInvoke === \"function\"\n        ? await endpoint.__farmInvoke(handlerContext)\n        : {\n            result: await farmHandler(handlerContext),\n            context: handlerContext.context,\n            handlerExecuted: true,\n            invalidations: [],\n          };\n  } catch (error) {\n    if (isEndpointFailure(error)) {\n      return createEndpointFailureResponse(error);\n    }\n    throw error;\n  }\n\n  if (execution.handlerExecuted && endpoint.__output && !isWebResponse(execution.result)) {\n    try {\n      execution.result = await parseRouteSchema(endpoint.__output, execution.result);\n    } catch {\n      throw new Error(\"API route returned a value that does not match its output schema.\");\n    }\n  }\n  const response = normalizeRouteResponse(execution.result);\n  return attachEndpointInvalidations(response, execution.invalidations);\n}\n\nfunction validateQueryContentType(request: Request): Response | null {\n  if (request.method.toUpperCase() !== \"QUERY\" || request.headers.has(\"content-type\")) {\n    return null;\n  }\n\n  return new Response(\n    JSON.stringify({\n      error: \"Invalid QUERY request\",\n      message: \"QUERY requests must include a Content-Type header.\",\n    }),\n    {\n      status: 400,\n      headers: { \"Content-Type\": \"application/json\" },\n    },\n  );\n}\n\nexport function normalizeRouteResponse(result: unknown): Response {\n  if (isWebResponse(result)) {\n    return result;\n  }\n\n  if (result === undefined) {\n    return new Response(null, { status: 204 });\n  }\n\n  return new Response(JSON.stringify(result), {\n    status: 200,\n    headers: { \"Content-Type\": \"application/json\" },\n  });\n}\n\nexport function isWebResponse(value: unknown): value is Response {\n  return (\n    value instanceof Response ||\n    (typeof value === \"object\" &&\n      value !== null &&\n      \"headers\" in value &&\n      \"status\" in value &&\n      typeof (value as Response).arrayBuffer === \"function\")\n  );\n}\n\nfunction attachEndpointInvalidations(response: Response, keys: readonly string[]): Response {\n  const existing = decodeFarmCacheInvalidations(\n    response.headers.get(FARM_CACHE_INVALIDATION_HEADER),\n  );\n  const encoded = encodeFarmCacheInvalidations([...existing, ...keys]);\n  if (!encoded) return response;\n\n  const headers = new Headers(response.headers);\n  headers.set(FARM_CACHE_INVALIDATION_HEADER, encoded);\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function createEndpointFailureResponse(failure: EndpointFailure<string, unknown>): Response {\n  return new Response(\n    JSON.stringify({\n      error: {\n        code: failure.code,\n        message: failure.message,\n        data: failure.data,\n      },\n    }),\n    {\n      status: failure.status,\n      headers: {\n        \"cache-control\": \"no-store\",\n        \"content-type\": \"application/json\",\n      },\n    },\n  );\n}\n\ninterface RequestBodyParseResult {\n  body?: unknown;\n  error?: Response;\n}\n\nasync function readRequestBody(request: Request): Promise<RequestBodyParseResult> {\n  const contentType = request.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n\n  try {\n    if (contentType === \"multipart/form-data\") {\n      return { body: formDataToObject(await request.clone().formData()) };\n    }\n\n    const text = await request.clone().text();\n    if (!text) return { body: undefined };\n    if (contentType === \"application/x-www-form-urlencoded\") {\n      return { body: searchParamsToObject(new URLSearchParams(text)) };\n    }\n    if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n      return { body: JSON.parse(text) };\n    }\n\n    // Preserve the previous permissive behavior for callers that omit the\n    // content type but still send JSON.\n    return { body: JSON.parse(text) };\n  } catch {\n    if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n      return {\n        error: new Response(\n          JSON.stringify({\n            error: \"Invalid request body\",\n            message: \"The request body is not valid JSON.\",\n          }),\n          {\n            status: 400,\n            headers: { \"Content-Type\": \"application/json\" },\n          },\n        ),\n      };\n    }\n    // The body format is unsupported or malformed. Schema validation below\n    // will turn the missing value into a typed 400 response when applicable.\n  }\n\n  return { body: undefined };\n}\n\nfunction formDataToObject(\n  formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n  return entriesToObject(formData.entries());\n}\n\nfunction searchParamsToObject(searchParams: URLSearchParams): Record<string, string | string[]> {\n  return entriesToObject(searchParams.entries());\n}\n\nfunction entriesToObject<TValue>(\n  entries: IterableIterator<[string, TValue]>,\n): Record<string, TValue | TValue[]> {\n  const output: Record<string, TValue | TValue[]> = Object.create(null);\n  for (const [key, value] of entries) {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n    const current = output[key];\n    if (current === undefined) {\n      output[key] = value;\n    } else if (Array.isArray(current)) {\n      current.push(value);\n    } else {\n      output[key] = [current, value];\n    }\n  }\n  return output;\n}\n\nasync function validateInput(\n  schema: any,\n  value: unknown,\n  error: string,\n): Promise<unknown | Response> {\n  if (!schema) return value;\n  try {\n    return await parseRouteSchema(schema, value);\n  } catch (validationError: any) {\n    return Response.json(\n      {\n        error,\n        details: (validationError.issues || validationError.errors || []).map((issue: any) => ({\n          path: issue.path,\n          message: issue.message,\n          code: issue.code,\n        })),\n      },\n      { status: 400 },\n    );\n  }\n}\n","export function isFarmAPIRouteFileName(fileName: string): boolean {\n  return /^route\\.(?:ts|tsx|js|jsx)$/.test(fileName);\n}\n","import { mergePluginAPIRoutes } from \"./plugin-route-runtime\";\nimport type { FarmPlugin } from \"../plugin\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { logger } from \"../utils\";\nimport type { ProgrammaticApiRoute } from \"../routes\";\nimport { createProgrammaticRouteModuleId } from \"../routes-shared\";\nimport { findProgrammaticRouteFilesInDir } from \"../routes.server\";\nimport {\n  getFarmRouteRuntimeConfig,\n  normalizeFarmRouteRuntimeConfig,\n  type FarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport { _runWithFarmI18nRequest, type FarmI18nRuntime } from \"../i18n/server\";\nimport {\n  getAllowedAPIRouteMethods,\n  invokeAPIRouteEndpoint,\n  registerAPIRouteShape,\n  type APIRouteShapeSource,\n  matchAPIRouteAtBasePath,\n  matchAPIRoute,\n  resolveAPIRouteEndpoint,\n  type APIRouteMatch,\n} from \"./runtime\";\nimport { isFarmAPIRouteFileName } from \"./route-files\";\nimport { AmbiguousRouteError, NonTerminalCatchAllRouteError } from \"../routing/specificity\";\n\nexport interface APIRoute extends FarmRouteRuntimeConfig {\n  pluginMethods?: string[];\n  path: string;\n  filePath: string;\n  methods: string[];\n  endpoints: Record<string, any>;\n}\n\nexport interface APIRouteManagerOptions {\n  plugins?: readonly FarmPlugin[];\n  throwOnLoadError?: boolean;\n  i18n?: FarmI18nRuntime;\n  bodySizeLimit?: number;\n  /** Same-origin path where canonical `/api` routes are served. */\n  basePath?: string;\n}\n\nexport interface APIRouteHandlerOptions {\n  /** Let a framework request boundary report the original endpoint error. */\n  throwOnError?: boolean;\n}\n\nexport class APIRouteConflictError extends Error {\n  constructor(routePath: string, method: string, existingFile: string, conflictingFile: string) {\n    super(\n      `Duplicate API route for ${method.toUpperCase()} ${routePath}: ${existingFile} conflicts with ${conflictingFile}`,\n    );\n    this.name = \"APIRouteConflictError\";\n  }\n}\n\nexport const API_ROUTE_METHODS = [\n  \"GET\",\n  \"HEAD\",\n  \"QUERY\",\n  \"POST\",\n  \"PUT\",\n  \"DELETE\",\n  \"PATCH\",\n  \"OPTIONS\",\n] as const;\n\nexport class APIRouteManager {\n  private plugins: readonly FarmPlugin[];\n  private routes: Map<string, APIRoute> = new Map();\n  private endpointSources: Map<string, Map<string, { appDir: string; filePath: string }>> =\n    new Map();\n  private routeShapes = new Map<string, APIRouteShapeSource<string>>();\n  private viteServer?: ViteDevServer;\n  private appDirs: string[];\n  private throwOnLoadError: boolean;\n  private i18n?: FarmI18nRuntime;\n  private bodySizeLimit?: number;\n  private basePath?: string;\n\n  constructor(\n    appDir: string | readonly string[],\n    viteServer?: ViteDevServer,\n    options: APIRouteManagerOptions = {},\n  ) {\n    this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n    this.viteServer = viteServer;\n    this.plugins = options.plugins ?? [];\n    this.throwOnLoadError = options.throwOnLoadError === true;\n    this.i18n = options.i18n;\n    this.bodySizeLimit = options.bodySizeLimit;\n    this.basePath = options.basePath;\n  }\n\n  /**\n   * Discover route.ts files in /app/api and explicit endpoints in root routes.ts\n   */\n  async discoverRoutes(): Promise<void> {\n    const previousRoutes = this.routes;\n    const previousEndpointSources = this.endpointSources;\n    const previousRouteShapes = this.routeShapes;\n    this.routes = new Map();\n    this.endpointSources = new Map();\n    this.routeShapes = new Map();\n\n    try {\n      for (const appDir of this.appDirs) {\n        const apiDir = path.join(appDir, \"api\");\n        let routeFiles: string[] = [];\n\n        if (fs.existsSync(apiDir)) {\n          routeFiles = this.findRouteFiles(apiDir);\n        }\n\n        for (const filePath of routeFiles) {\n          await this.loadRoute(filePath, appDir);\n        }\n\n        await this.loadRootRoutes(appDir);\n        await this.loadProgrammaticApiRoutes(appDir);\n      }\n      this.routes = new Map(\n        mergePluginAPIRoutes([...this.routes.values()], this.plugins).map((route) => [\n          route.path,\n          route,\n        ]),\n      );\n    } catch (error) {\n      this.routes = previousRoutes;\n      this.endpointSources = previousEndpointSources;\n      this.routeShapes = previousRouteShapes;\n      throw error;\n    }\n\n    if (process.env.FARM_VERBOSE) {\n      logger.success(`Discovered ${this.routes.size} API routes`);\n      for (const [routePath, route] of this.routes) {\n        logger.info(`  ${route.methods.join(\", \")} ${routePath}`);\n      }\n    }\n  }\n\n  /**\n   * Recursively find all route.ts files\n   */\n  private findRouteFiles(dir: string): string[] {\n    const files: string[] = [];\n\n    if (!fs.existsSync(dir)) {\n      return files;\n    }\n\n    const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n    for (const entry of entries) {\n      const fullPath = path.join(dir, entry.name);\n\n      if (entry.isDirectory()) {\n        files.push(...this.findRouteFiles(fullPath));\n      } else if (isFarmAPIRouteFileName(entry.name)) {\n        files.push(fullPath);\n      }\n    }\n\n    return files;\n  }\n\n  /**\n   * Load a route.ts file and extract HTTP method exports\n   */\n  private async loadRoute(filePath: string, appDir: string): Promise<void> {\n    try {\n      // Convert file path to API route path\n      // /app/api/auth/login/route.ts -> /api/auth/login\n      const apiDir = path.join(appDir, \"api\");\n      const relativePath = path.relative(apiDir, path.dirname(filePath));\n      const routePath = \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n\n      const routeModule = await this.loadModule(filePath);\n\n      const endpoints: Record<string, any> = {};\n      const availableMethods: string[] = [];\n\n      for (const method of API_ROUTE_METHODS) {\n        if (routeModule[method]) {\n          endpoints[method] = routeModule[method];\n          availableMethods.push(method);\n        }\n      }\n\n      if (availableMethods.length > 0) {\n        const existingSources = this.endpointSources.get(routePath);\n        if (existingSources) {\n          for (const method of availableMethods) {\n            const existingSource = existingSources.get(method);\n            if (existingSource?.appDir === appDir) {\n              throw new APIRouteConflictError(routePath, method, existingSource.filePath, filePath);\n            }\n          }\n        }\n        const runtimeConfig = normalizeFarmRouteRuntimeConfig(\n          getFarmRouteRuntimeConfig(routeModule),\n          `API route \"${routePath}\"`,\n        );\n        this.registerRouteShape(routePath, filePath, appDir);\n        const existingRoute = this.routes.get(routePath);\n        const mergedMethods = existingRoute ? [...existingRoute.methods] : [];\n        for (const method of availableMethods) {\n          if (!mergedMethods.includes(method)) mergedMethods.push(method);\n        }\n        this.routes.set(routePath, {\n          ...existingRoute,\n          path: routePath,\n          filePath,\n          methods: mergedMethods,\n          endpoints: { ...existingRoute?.endpoints, ...endpoints },\n          ...runtimeConfig,\n        });\n        const nextSources = new Map(existingSources);\n        for (const method of availableMethods) {\n          nextSources.set(method, { appDir, filePath });\n        }\n        this.endpointSources.set(routePath, nextSources);\n      }\n    } catch (error) {\n      this.handleLoadError(`Error loading route ${filePath}`, error);\n    }\n  }\n\n  /**\n   * Load explicit-path endpoints from src/routes.ts-style files.\n   */\n  private async loadRootRoutes(appDir: string): Promise<void> {\n    const routesFile = this.findRootRoutesFile(appDir);\n    if (!routesFile) {\n      return;\n    }\n\n    try {\n      const routesModule = await this.loadModule(routesFile);\n\n      for (const exportValue of Object.values(routesModule)) {\n        const endpoint = exportValue as any;\n        if (!endpoint?.__path) {\n          continue;\n        }\n\n        const method = String(endpoint.__method || \"GET\").toUpperCase();\n        this.registerRouteShape(endpoint.__path, routesFile, appDir);\n        this.addEndpoint(endpoint.__path, routesFile, method, endpoint, appDir);\n      }\n    } catch (error) {\n      this.handleLoadError(`Error loading root API routes ${routesFile}`, error);\n    }\n  }\n\n  private async loadProgrammaticApiRoutes(appDir: string): Promise<void> {\n    const candidateRoots = [path.dirname(appDir), appDir];\n    const routeFiles = Array.from(\n      new Set(candidateRoots.flatMap((srcRoot) => findProgrammaticRouteFilesInDir(srcRoot))),\n    );\n    if (routeFiles.length === 0) return;\n\n    const { getProgrammaticRouteManifest } = await import(\"../routes\");\n\n    for (const routeFile of routeFiles) {\n      try {\n        const routesModule = await this.loadModule(routeFile);\n        const manifest = getProgrammaticRouteManifest(routesModule);\n        if (!manifest) continue;\n\n        for (const definition of manifest.routes) {\n          if (definition.kind !== \"api\") continue;\n          if (!Object.values(definition.methods).some(Boolean)) continue;\n          this.addProgrammaticApiRoute(routeFile, definition, appDir);\n        }\n      } catch (error) {\n        this.handleLoadError(`Error loading programmatic API routes ${routeFile}`, error);\n      }\n    }\n  }\n\n  private handleLoadError(message: string, error: unknown): void {\n    logger.error(`${message}: ${error}`);\n    if (\n      this.throwOnLoadError ||\n      error instanceof APIRouteConflictError ||\n      error instanceof AmbiguousRouteError ||\n      error instanceof NonTerminalCatchAllRouteError\n    ) {\n      throw error;\n    }\n  }\n\n  private findRootRoutesFile(appDir: string): string | null {\n    const routeNames = [\"routes.ts\", \"routes.tsx\", \"routes.js\"];\n    const candidateDirs = [path.dirname(appDir), appDir];\n    const seen = new Set<string>();\n\n    for (const dir of candidateDirs) {\n      for (const routeName of routeNames) {\n        const routesFile = path.join(dir, routeName);\n        if (seen.has(routesFile)) {\n          continue;\n        }\n        seen.add(routesFile);\n\n        if (fs.existsSync(routesFile)) {\n          return routesFile;\n        }\n      }\n    }\n\n    return null;\n  }\n\n  private async loadModule(filePath: string): Promise<Record<string, unknown>> {\n    if (this.viteServer) {\n      return await this.viteServer.ssrLoadModule(filePath);\n    }\n\n    const fileUrl = `file://${filePath}`;\n    return await import(/* @vite-ignore */ fileUrl);\n  }\n\n  private addEndpoint(\n    routePath: string,\n    filePath: string,\n    method: string,\n    endpoint: any,\n    appDir: string,\n    runtimeConfig: FarmRouteRuntimeConfig = {},\n  ): void {\n    const normalizedMethod = method.toUpperCase();\n    const existingRoute = this.routes.get(routePath);\n    const existingSource = this.endpointSources.get(routePath)?.get(normalizedMethod);\n\n    if (existingSource?.appDir === appDir) {\n      throw new APIRouteConflictError(\n        routePath,\n        normalizedMethod,\n        existingSource.filePath,\n        filePath,\n      );\n    }\n\n    if (existingRoute) {\n      if (!existingRoute.methods.includes(normalizedMethod)) {\n        existingRoute.methods.push(normalizedMethod);\n      }\n      existingRoute.endpoints[normalizedMethod] = endpoint;\n      Object.assign(existingRoute, runtimeConfig);\n      const sources = this.endpointSources.get(routePath) ?? new Map();\n      sources.set(normalizedMethod, { appDir, filePath });\n      this.endpointSources.set(routePath, sources);\n      return;\n    }\n\n    this.routes.set(routePath, {\n      path: routePath,\n      filePath,\n      methods: [normalizedMethod],\n      endpoints: { [normalizedMethod]: endpoint },\n      ...runtimeConfig,\n    });\n    this.endpointSources.set(routePath, new Map([[normalizedMethod, { appDir, filePath }]]));\n  }\n\n  private addProgrammaticApiRoute(\n    filePath: string,\n    route: ProgrammaticApiRoute,\n    appDir: string,\n  ): void {\n    const modulePath = createProgrammaticRouteModuleId(filePath, \"api\", route.path);\n    const runtimeConfig = normalizeFarmRouteRuntimeConfig(route, `API route \"${route.path}\"`);\n    for (const [method, endpoint] of Object.entries(route.methods)) {\n      if (endpoint) {\n        this.addEndpoint(route.path, modulePath, method, endpoint, appDir, runtimeConfig);\n      }\n    }\n  }\n\n  private registerRouteShape(routePath: string, filePath: string, appDir: string): void {\n    const replacedPath = registerAPIRouteShape(this.routeShapes, routePath, filePath, appDir);\n    if (replacedPath) {\n      this.routes.delete(replacedPath);\n      this.endpointSources.delete(replacedPath);\n    }\n  }\n\n  /**\n   * Get the handler that directly invokes endpoint handlers\n   */\n  getHandler(options: APIRouteHandlerOptions = {}): ((req: Request) => Promise<Response>) | null {\n    if (this.routes.size === 0) {\n      return null;\n    }\n\n    return async (request: Request): Promise<Response> => {\n      const url = new URL(request.url);\n      const pathname = url.pathname;\n      const method = request.method.toUpperCase();\n\n      // Find matching route\n      const match = matchAPIRouteAtBasePath(this.routes, pathname, this.basePath);\n      if (!match) {\n        return new Response(JSON.stringify({ error: \"Not Found\" }), {\n          status: 404,\n          headers: { \"Content-Type\": \"application/json\" },\n        });\n      }\n\n      // Check if method is supported\n      const { route, params } = match;\n      const endpoint = resolveAPIRouteEndpoint(route, method);\n      if (!endpoint) {\n        return new Response(JSON.stringify({ error: \"Method Not Allowed\" }), {\n          status: 405,\n          headers: {\n            Allow: getAllowedAPIRouteMethods(route).join(\", \"),\n            \"Content-Type\": \"application/json\",\n          },\n        });\n      }\n\n      const invoke = async () => {\n        try {\n          return await invokeAPIRouteEndpoint(endpoint, request, params, this.bodySizeLimit);\n        } catch (error: any) {\n          if (options.throwOnError) throw error;\n          console.error(`[API Error] ${pathname}:`, error);\n          return new Response(JSON.stringify({ error: \"Internal Server Error\" }), {\n            status: 500,\n            headers: { \"Content-Type\": \"application/json\" },\n          });\n        }\n      };\n\n      return this.i18n?.config.enabled\n        ? _runWithFarmI18nRequest(this.i18n, request, invoke, {\n            redirect: false,\n          })\n        : invoke();\n    };\n  }\n\n  /**\n   * Check if a path is an API route\n   */\n  isAPIRoute(pathname: string): boolean {\n    return Boolean(this.matchRoute(pathname));\n  }\n\n  matchRoute(pathname: string): APIRouteMatch<APIRoute> | null {\n    return matchAPIRouteAtBasePath(this.routes, pathname, this.basePath);\n  }\n\n  /**\n   * Get all routes for client type generation\n   */\n  getRoutes(): Map<string, APIRoute> {\n    return this.routes;\n  }\n}\n\nexport {\n  getAllowedAPIRouteMethods,\n  invokeAPIRouteEndpoint,\n  isWebResponse,\n  matchAPIRoute,\n  normalizeRouteResponse,\n  resolveAPIRouteEndpoint,\n} from \"./runtime\";\nexport type { APIRouteMatch, APIRouteParams, APIRouteParamValue } from \"./runtime\";\n","function decodeCookieValue(value: string): string {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    // Cookies are not required to be percent-encoded; keep the raw value\n    // instead of failing the whole request on malformed encoding.\n    return value;\n  }\n}\n\nexport function parseMiddlewareCookieHeader(cookieHeader?: string | null): Record<string, string> {\n  const cookies = Object.create(null) as Record<string, string>;\n  if (!cookieHeader) return cookies;\n\n  for (const cookie of cookieHeader.split(\";\")) {\n    const separator = cookie.indexOf(\"=\");\n    if (separator < 0) continue;\n\n    const name = cookie.slice(0, separator).trim();\n    if (!name) continue;\n\n    const value = cookie.slice(separator + 1).trim();\n    cookies[name] = decodeCookieValue(value);\n  }\n\n  return cookies;\n}\n","/**\n * Middleware Context Implementation\n */\n\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type { ViteDevServer } from \"vite\";\nimport type { MiddlewareContext, CookieJar, CookieOptions } from \"./types\";\nimport type { FarmServerConfig, ResolvedFarmServerConfig } from \"../server-http\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport { parseMiddlewareCookieHeader } from \"./cookie-header\";\n\n/**\n * Serialize a cookie\n */\nfunction serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n  let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n  if (options.maxAge != null) {\n    cookie += `; Max-Age=${options.maxAge}`;\n  }\n\n  if (options.expires) {\n    cookie += `; Expires=${options.expires.toUTCString()}`;\n  }\n\n  if (options.path) {\n    cookie += `; Path=${options.path}`;\n  } else {\n    cookie += \"; Path=/\";\n  }\n\n  if (options.domain) {\n    cookie += `; Domain=${options.domain}`;\n  }\n\n  if (options.secure) {\n    cookie += \"; Secure\";\n  }\n\n  if (options.httpOnly) {\n    cookie += \"; HttpOnly\";\n  }\n\n  if (options.sameSite) {\n    cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;\n  }\n\n  return cookie;\n}\n\n/**\n * Cookie Jar implementation\n */\nclass CookieJarImpl implements CookieJar {\n  private cookies: Record<string, string>;\n  private setCookies: string[];\n\n  constructor(\n    private req: IncomingMessage,\n    private res: ServerResponse,\n  ) {\n    this.cookies = parseMiddlewareCookieHeader(req.headers.cookie);\n    const existing = res.getHeader(\"Set-Cookie\");\n    this.setCookies = Array.isArray(existing)\n      ? existing.map(String)\n      : existing === undefined\n        ? []\n        : [String(existing)];\n  }\n\n  get(name: string): string | undefined {\n    return this.cookies[name];\n  }\n\n  set(name: string, value: string, options: CookieOptions = {}): void {\n    this.cookies[name] = value;\n    const cookieString = serializeCookie(name, value, options);\n    this.setCookies.push(cookieString);\n\n    // Update Set-Cookie header\n    this.res.setHeader(\"Set-Cookie\", this.setCookies);\n  }\n\n  delete(name: string): void {\n    delete this.cookies[name];\n    const cookieString = serializeCookie(name, \"\", {\n      maxAge: 0,\n      expires: new Date(0),\n    });\n    this.setCookies.push(cookieString);\n    this.res.setHeader(\"Set-Cookie\", this.setCookies);\n  }\n\n  getAll(): Record<string, string> {\n    return { ...this.cookies };\n  }\n}\n\n/**\n * Create a middleware context from request/response\n */\nexport function createContext(\n  req: IncomingMessage,\n  res: ServerResponse,\n  viteServer?: ViteDevServer,\n  parent?: MiddlewareContext[\"parent\"],\n  server?: FarmServerConfig | ResolvedFarmServerConfig,\n): MiddlewareContext {\n  const url = resolveFarmRequestURL(req, { trustProxy: server?.trustProxy });\n  const headers = new Map<string, string>();\n  const data = parent?.data ? new Map(parent.data) : new Map<string, any>();\n  const locals = parent?.locals ? new Map(parent.locals) : new Map<string, any>();\n  const cookies = new CookieJarImpl(req, res);\n\n  if (parent?.headers) {\n    for (const [key, value] of Object.entries(parent.headers)) {\n      headers.set(key, value);\n    }\n  }\n\n  let handled = false;\n\n  const applyResponseHeaders = () => {\n    for (const [key, value] of headers) {\n      try {\n        res.setHeader(key, value);\n      } catch {\n        // Keep helper behavior aligned with the middleware manager: an invalid\n        // optional header must not prevent the response itself from completing.\n      }\n    }\n  };\n\n  const ctx: MiddlewareContext = {\n    request: req,\n    response: res,\n    url,\n    pathname: url.pathname,\n    searchParams: url.searchParams,\n    method: req.method || \"GET\",\n    params: {},\n    route: url.pathname,\n    parent,\n    vite: {\n      isDev: process.env.NODE_ENV !== \"production\",\n      hmr: !!viteServer?.hot,\n      server: viteServer,\n    },\n    data,\n    locals,\n    headers,\n    cookies,\n    _handled: false,\n\n    redirect(redirectUrl: string, status = 307): void {\n      if (handled) {\n        console.warn(\"Response already sent, cannot redirect\");\n        return;\n      }\n\n      ctx._redirectUrl = redirectUrl;\n      ctx._handled = true;\n      handled = true;\n\n      applyResponseHeaders();\n      res.writeHead(status, {\n        Location: redirectUrl,\n        \"Content-Type\": \"text/plain\",\n      });\n      res.end(`Redirecting to ${redirectUrl}`);\n    },\n\n    rewrite(rewriteUrl: string): void {\n      ctx._rewriteUrl = rewriteUrl;\n      // Update the URL for downstream middleware\n      const newUrl = new URL(rewriteUrl, `http://${req.headers.host || \"localhost\"}`);\n      ctx.url = newUrl;\n      ctx.pathname = newUrl.pathname;\n      ctx.searchParams = newUrl.searchParams;\n      // Update the original request URL\n      req.url = rewriteUrl;\n    },\n\n    json(jsonData: any, status = 200): void {\n      if (handled) {\n        console.warn(\"Response already sent, cannot send JSON\");\n        return;\n      }\n\n      ctx._handled = true;\n      handled = true;\n\n      applyResponseHeaders();\n      res.writeHead(status, {\n        \"Content-Type\": \"application/json\",\n      });\n      res.end(JSON.stringify(jsonData));\n    },\n\n    text(content: string, status = 200): void {\n      if (handled) {\n        console.warn(\"Response already sent, cannot send text\");\n        return;\n      }\n\n      ctx._handled = true;\n      handled = true;\n\n      applyResponseHeaders();\n      res.writeHead(status, {\n        \"Content-Type\": \"text/plain\",\n      });\n      res.end(content);\n    },\n\n    html(content: string, status = 200): void {\n      if (handled) {\n        console.warn(\"Response already sent, cannot send HTML\");\n        return;\n      }\n\n      ctx._handled = true;\n      handled = true;\n\n      applyResponseHeaders();\n      res.writeHead(status, {\n        \"Content-Type\": \"text/html\",\n      });\n      res.end(content);\n    },\n  };\n\n  return ctx;\n}\n","import { createWebRequestFromFarmRequest } from \"../server/request\";\nimport type {\n  MiddlewareConfig,\n  MiddlewareContext,\n  MiddlewareFunction,\n  MiddlewareModule,\n  MiddlewareStore,\n  RequestMiddlewareContext,\n} from \"./types\";\n\nexport interface NormalizedMiddlewareModule {\n  handlers: MiddlewareFunction[];\n  config?: MiddlewareConfig;\n}\n\nfunction isWebRequest(request: unknown): request is Request {\n  return typeof Request !== \"undefined\" && request instanceof Request;\n}\n\nfunction toWebRequest(ctx: MiddlewareContext): Request {\n  if (isWebRequest(ctx.request)) {\n    return ctx.request;\n  }\n  return createWebRequestFromFarmRequest(ctx.request, { origin: ctx.url.origin });\n}\n\nfunction createRequestMiddlewareContext(\n  ctx: MiddlewareContext,\n): RequestMiddlewareContext<Record<string, any>, Record<string, any>> {\n  const context = {\n    get url() {\n      return ctx.url;\n    },\n    get pathname() {\n      return ctx.pathname;\n    },\n    get searchParams() {\n      return ctx.searchParams;\n    },\n    get method() {\n      return ctx.method;\n    },\n    get params() {\n      return ctx.params;\n    },\n    get route() {\n      return ctx.route;\n    },\n    get locals() {\n      return ctx.locals as MiddlewareStore<Record<string, any>>;\n    },\n    get data() {\n      return ctx.data as MiddlewareStore<Record<string, any>>;\n    },\n    get headers() {\n      return ctx.headers;\n    },\n    get cookies() {\n      return ctx.cookies;\n    },\n    get(key: string) {\n      return ctx.locals.get(key);\n    },\n    has(key: string) {\n      return ctx.locals.has(key);\n    },\n    set(key: string, value: any) {\n      ctx.locals.set(key, value);\n    },\n    delete(key: string) {\n      return ctx.locals.delete(key);\n    },\n    redirect(url: string, status?: number) {\n      ctx.redirect(url, status);\n    },\n    rewrite(url: string) {\n      ctx.rewrite(url);\n    },\n    json(data: any, status?: number) {\n      ctx.json(data, status);\n    },\n    text(content: string, status?: number) {\n      ctx.text(content, status);\n    },\n    html(content: string, status?: number) {\n      ctx.html(content, status);\n    },\n  } satisfies RequestMiddlewareContext;\n\n  return context;\n}\n\n/**\n * Normalize the two supported middleware file styles to Farm's internal chain.\n */\nexport function normalizeMiddlewareModule(\n  middlewareModule: MiddlewareModule | Record<string, any>,\n  routePath: string,\n): NormalizedMiddlewareModule | null {\n  const module = middlewareModule as MiddlewareModule;\n  const defaultExport = module.default;\n  const namedExport = module.middleware;\n  const hasNamedExport = typeof namedExport === \"function\";\n\n  if (namedExport !== undefined && !hasNamedExport) {\n    throw new TypeError(\"The named middleware export must be a function\");\n  }\n\n  if (defaultExport && hasNamedExport) {\n    throw new Error(\n      \"A middleware file cannot export both a default handler and a named middleware handler\",\n    );\n  }\n\n  if (hasNamedExport) {\n    return {\n      handlers: [\n        async (ctx) => {\n          return namedExport(toWebRequest(ctx), createRequestMiddlewareContext(ctx));\n        },\n      ],\n      config: module.config,\n    };\n  }\n\n  if (defaultExport && typeof defaultExport === \"object\" && \"build\" in defaultExport) {\n    if (typeof (defaultExport as any).setBasePath === \"function\") {\n      (defaultExport as any).setBasePath(routePath);\n    }\n    const built = (defaultExport as any).build();\n    const handlers = Array.isArray(built?.handlers)\n      ? built.handlers.filter((handler: unknown) => typeof handler === \"function\")\n      : [];\n    return handlers.length > 0\n      ? {\n          handlers,\n          config: module.config || built?.config,\n        }\n      : null;\n  }\n\n  if (typeof defaultExport === \"function\") {\n    return {\n      handlers: [defaultExport as MiddlewareFunction],\n      config: module.config,\n    };\n  }\n\n  return null;\n}\n","import picocolors from \"picocolors\";\n\n/**\n * Create colors for Farm's terminal output.\n *\n * Some interactive terminal hosts advertise a limited TERM value or set\n * NO_COLOR for captured subprocess output even though they render ANSI styles.\n * Prefer the actual stream type so the dev server remains colored in a TTY,\n * while redirected output stays plain.\n */\nexport function createCliColors(interactive = process.stdout.isTTY === true) {\n  return picocolors.createColors(interactive);\n}\n","export function appendMiddlewareRoutePath(routePath: string, directoryName: string): string {\n  if (directoryName.startsWith(\"(\") && directoryName.endsWith(\")\")) {\n    return routePath;\n  }\n\n  return routePath === \"/\" ? `/${directoryName}` : `${routePath}/${directoryName}`;\n}\n","/**\n * Middleware Manager\n *\n * Discovers and executes middleware files in the file system\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { decodeRouteSegment } from \"../utils/decode\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type {\n  FarmMiddlewareConfig,\n  MiddlewareFunction,\n  MiddlewareMatcher,\n  MiddlewareConfig,\n  MiddlewareContext,\n  MiddlewareResult,\n} from \"./types\";\nimport { createContext } from \"./context\";\nimport { normalizeMiddlewareModule } from \"./module\";\nimport { logger } from \"../utils\";\nimport { sendWebResponse } from \"../server/response\";\nimport { emitFarmEvent } from \"../observability\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { createCliColors } from \"../cli-colors\";\nimport { appendMiddlewareRoutePath } from \"./path\";\nimport type { FarmServerConfig, ResolvedFarmServerConfig } from \"../server-http\";\nimport { resolveFarmRequestURL } from \"../server/request\";\n\nexport interface DiscoveredMiddleware {\n  path: string;\n  filePath: string;\n  handlers: MiddlewareFunction[];\n  config?: MiddlewareConfig;\n  source?: \"config\" | \"file\";\n}\n\nfunction isMiddlewareResponse(value: unknown): value is Response {\n  return value instanceof Response;\n}\n\n/**\n * Middleware Manager - discovers and executes middleware\n */\nexport class MiddlewareManager {\n  private middleware: DiscoveredMiddleware[] = [];\n  private configMiddleware: DiscoveredMiddleware[] = [];\n  private globalConfig?: MiddlewareConfig;\n  private viteServer?: ViteDevServer;\n  private appDirs: string[];\n  private i18n?: ResolvedFarmI18nConfig;\n  private server?: FarmServerConfig | ResolvedFarmServerConfig;\n\n  constructor(\n    appDir: string | readonly string[],\n    viteServer?: ViteDevServer,\n    config?: FarmMiddlewareConfig,\n    i18n?: ResolvedFarmI18nConfig,\n    server?: FarmServerConfig | ResolvedFarmServerConfig,\n  ) {\n    this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n    this.viteServer = viteServer;\n    this.i18n = i18n;\n    this.server = server;\n    this.configure(config);\n  }\n\n  configure(config?: FarmMiddlewareConfig): void {\n    this.configMiddleware = [];\n    this.globalConfig = undefined;\n\n    if (!config) return;\n\n    const entries = Array.isArray(config) ? config : [config];\n\n    for (const [index, entry] of entries.entries()) {\n      const handlers = this.getConfigHandlers(entry);\n      const middlewareConfig = this.toMiddlewareConfig(entry);\n\n      if (handlers.length === 0) {\n        this.globalConfig = middlewareConfig;\n        continue;\n      }\n\n      this.configMiddleware.push({\n        path: \"/\",\n        filePath: `farm.config.ts#middleware-${index}`,\n        handlers,\n        config: middlewareConfig,\n        source: \"config\",\n      });\n    }\n  }\n\n  /**\n   * Discover all middleware.ts files\n   */\n  async discover(): Promise<void> {\n    const middlewareByPath = new Map<string, DiscoveredMiddleware>();\n    for (const appDir of this.appDirs) {\n      const discovered: DiscoveredMiddleware[] = [];\n      await this.discoverInDirectory(appDir, \"/\", discovered);\n      for (const middleware of discovered) {\n        middlewareByPath.set(middleware.path, middleware);\n      }\n    }\n    this.middleware = Array.from(middlewareByPath.values());\n\n    // Sort by path depth (root first, then nested)\n    this.middleware.sort((a, b) => {\n      const depthA = a.path.split(\"/\").length;\n      const depthB = b.path.split(\"/\").length;\n      return depthA - depthB;\n    });\n\n    if (process.env.FARM_VERBOSE && this.middleware.length > 0) {\n      logger.success(`Discovered ${this.middleware.length} middleware files`);\n      for (const mw of this.middleware) {\n        logger.info(`  ${mw.path} (${mw.handlers.length} handlers)`);\n      }\n    }\n  }\n\n  /**\n   * Recursively discover middleware files\n   */\n  private async discoverInDirectory(\n    dir: string,\n    routePath: string,\n    discovered: DiscoveredMiddleware[],\n  ): Promise<void> {\n    if (!fs.existsSync(dir)) {\n      return;\n    }\n\n    // Check for middleware.ts in current directory\n    const middlewareFile = this.findMiddlewareFile(dir);\n    if (middlewareFile) {\n      const middleware = await this.loadMiddleware(middlewareFile, routePath);\n      if (middleware) {\n        discovered.push(middleware);\n      }\n    }\n\n    // Recursively check subdirectories\n    const entries = fs.readdirSync(dir, { withFileTypes: true });\n    for (const entry of entries) {\n      if (entry.isDirectory() && !entry.name.startsWith(\".\") && !entry.name.startsWith(\"_\")) {\n        const subPath = path.join(dir, entry.name);\n        const subRoutePath = appendMiddlewareRoutePath(routePath, entry.name);\n        await this.discoverInDirectory(subPath, subRoutePath, discovered);\n      }\n    }\n  }\n\n  /**\n   * Find middleware file in directory\n   */\n  private findMiddlewareFile(dir: string): string | null {\n    const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"];\n    for (const ext of extensions) {\n      const filePath = path.join(dir, `middleware${ext}`);\n      if (fs.existsSync(filePath)) {\n        return filePath;\n      }\n    }\n    return null;\n  }\n\n  /**\n   * Load a middleware file\n   */\n  private async loadMiddleware(filePath: string, routePath: string): Promise<DiscoveredMiddleware> {\n    try {\n      // Load the module\n      let module: any;\n      if (this.viteServer) {\n        module = await this.viteServer.ssrLoadModule(filePath);\n      } else {\n        const fileUrl = `file://${filePath}`;\n        module = await import(/* @vite-ignore */ fileUrl);\n      }\n\n      const normalized = normalizeMiddlewareModule(module, routePath);\n      if (!normalized) {\n        throw new Error(\"must export a default handler or a named middleware handler\");\n      }\n\n      return {\n        path: routePath,\n        filePath,\n        handlers: normalized.handlers,\n        config: normalized.config,\n        source: \"file\",\n      };\n    } catch (error) {\n      throw new Error(`Failed to load middleware ${filePath}: ${error}`);\n    }\n  }\n\n  /**\n   * Execute middleware for a request\n   */\n  async execute(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n    const url = resolveFarmRequestURL(req, { trustProxy: this.server?.trustProxy });\n    const pathname = url.pathname;\n    const routePathname = this.i18n?.enabled\n      ? stripFarmLocaleFromPathname(pathname, this.i18n)\n      : pathname;\n    const method = req.method || \"GET\";\n    const startTime = Date.now();\n\n    let parentData: MiddlewareContext[\"parent\"] | undefined;\n    let ctx = createContext(req, res, this.viteServer, undefined, this.server);\n\n    if (this.globalConfig) {\n      const globalMatch = this.matchesConfig(routePathname, this.globalConfig, ctx);\n      if (!globalMatch.matched) {\n        return false;\n      }\n      if (globalMatch.params) {\n        ctx.params = { ...ctx.params, ...globalMatch.params };\n      }\n    }\n\n    // Find applicable middleware (config entries first, then cascading files)\n    const applicable: Array<{\n      mw: DiscoveredMiddleware;\n      routeMatch: { matched: boolean; params?: Record<string, string> };\n    }> = [\n      ...this.configMiddleware.map((mw) => ({ mw, routeMatch: { matched: true } })),\n      ...this.middleware\n        .map((mw) => ({ mw, routeMatch: this.matchRoutePath(routePathname, mw.path) }))\n        .filter((entry) => entry.routeMatch.matched),\n    ];\n\n    if (applicable.length === 0) {\n      return false; // No middleware to run\n    }\n    const pc = createCliColors();\n    const log = [\n      pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.magenta(\"MIDDLEWARE\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n      pc.gray(\"Executing middleware: \"),\n      pc.gray(pathname),\n      pc.dim(` (${(Date.now() - startTime).toFixed(2)}ms)`),\n    ].join(\" \");\n    console.log(log);\n\n    // Execute middleware in cascade order\n    for (const entry of applicable) {\n      // Check matcher configuration\n      const { mw, routeMatch } = entry;\n      const configMatch = mw.config\n        ? this.matchesConfig(routePathname, mw.config, ctx)\n        : { matched: true };\n      if (!configMatch.matched) {\n        continue;\n      }\n      if (routeMatch.params) {\n        ctx.params = { ...ctx.params, ...routeMatch.params };\n      }\n      if (configMatch.params) {\n        ctx.params = { ...ctx.params, ...configMatch.params };\n      }\n\n      // Create new context with parent data\n      if (parentData) {\n        ctx = createContext(req, res, this.viteServer, parentData, this.server);\n        if (routeMatch.params) {\n          ctx.params = { ...ctx.params, ...routeMatch.params };\n        }\n        if (configMatch.params) {\n          ctx.params = { ...ctx.params, ...configMatch.params };\n        }\n      }\n\n      const middlewareStartTime = Date.now();\n      const middlewareEvent = {\n        route: mw.path,\n        pathname,\n        name: mw.filePath,\n      };\n      emitFarmEvent({ type: \"middleware.start\", ...middlewareEvent });\n\n      try {\n        // Execute all handlers in this middleware\n        let handlerIndex = 0;\n        let returnedResponse: Response | undefined;\n        const executeNext = async (): Promise<MiddlewareResult> => {\n          if (handlerIndex < mw.handlers.length) {\n            const handler = mw.handlers[handlerIndex++];\n            const result = await handler(ctx, executeNext);\n            if (isMiddlewareResponse(result)) {\n              returnedResponse = result;\n              return result;\n            }\n          }\n          return returnedResponse;\n        };\n\n        const result = await executeNext();\n        const response = isMiddlewareResponse(result) ? result : returnedResponse;\n        if (response) {\n          if (!res.headersSent && !res.writableEnded) {\n            for (const [key, value] of ctx.headers) {\n              try {\n                res.setHeader(key, value);\n              } catch (error) {}\n            }\n          }\n          emitFarmEvent({\n            type: \"middleware.shortCircuit\",\n            ...middlewareEvent,\n            status: response.status,\n          });\n          await sendWebResponse(res, response);\n          return true;\n        }\n\n        // Check if response has been sent or handled by middleware helpers.\n        if (ctx._handled || res.headersSent || res.writableEnded) {\n          emitFarmEvent({\n            type: \"middleware.shortCircuit\",\n            ...middlewareEvent,\n            status: res.statusCode,\n          });\n          return true;\n        }\n\n        emitFarmEvent({\n          type: \"middleware.complete\",\n          ...middlewareEvent,\n          durationMs: Date.now() - middlewareStartTime,\n        });\n      } catch (error) {\n        emitFarmEvent({\n          type: \"middleware.error\",\n          ...middlewareEvent,\n          error,\n        });\n        throw error;\n      }\n\n      parentData = {\n        data: new Map(ctx.data),\n        locals: new Map(ctx.locals),\n        headers: Object.fromEntries(ctx.headers),\n      };\n    }\n\n    if (!res.headersSent && !res.writableEnded) {\n      for (const [key, value] of ctx.headers) {\n        try {\n          res.setHeader(key, value);\n        } catch (error) {}\n      }\n    }\n\n    (req as any).__FARM_MIDDLEWARE_DATA__ = new Map(ctx.data);\n    (req as any).__FARM_MIDDLEWARE_CONTEXT__ = new Map(ctx.locals);\n\n    return false; // Continue to page rendering\n  }\n\n  /**\n   * Check if pathname matches middleware config\n   */\n  private matchesConfig(\n    pathname: string,\n    config: MiddlewareConfig,\n    ctx: MiddlewareContext,\n  ): { matched: boolean; params?: Record<string, string> } {\n    // Check exclusions\n    if (config.exclude) {\n      for (const pattern of config.exclude) {\n        if (this.matchPattern(pattern, pathname).matched) {\n          return { matched: false };\n        }\n      }\n    }\n\n    // Check matchers\n    if (config.matcher) {\n      for (const matcher of this.toMatcherList(config.matcher)) {\n        if (typeof matcher === \"string\" || matcher instanceof RegExp) {\n          const result = this.matchPattern(matcher, pathname);\n          if (result.matched) {\n            return result;\n          }\n        } else if (typeof matcher === \"function\" && matcher(ctx)) {\n          return { matched: true };\n        }\n      }\n      return { matched: false };\n    }\n\n    return { matched: true };\n  }\n\n  /**\n   * Match a pattern against pathname\n   */\n  private matchPattern(\n    pattern: string | RegExp,\n    pathname: string,\n  ): { matched: boolean; params?: Record<string, string> } {\n    if (pattern instanceof RegExp) {\n      pattern.lastIndex = 0;\n      const match = pattern.exec(pathname);\n      return {\n        matched: !!match,\n        params: match?.groups ? { ...match.groups } : undefined,\n      };\n    }\n\n    if (pattern === \"*\" || pattern === \"/(.*)\") {\n      return { matched: true };\n    }\n\n    if (pattern.endsWith(\"(.*)\")) {\n      const prefix = pattern.slice(0, -4);\n      return { matched: pathname === prefix || pathname.startsWith(`${prefix}/`) };\n    }\n\n    const { regex, params } = this.compilePathPattern(pattern);\n    const match = regex.exec(pathname);\n    if (!match) {\n      return { matched: false };\n    }\n\n    const values: Record<string, string> = {};\n    params.forEach((param, index) => {\n      values[param] = decodeRouteSegment(match[index + 1] || \"\");\n    });\n\n    return {\n      matched: true,\n      params: Object.keys(values).length > 0 ? values : undefined,\n    };\n  }\n\n  /**\n   * Reload middleware (for HMR)\n   */\n  async reload(): Promise<void> {\n    await this.discover();\n  }\n\n  getMiddlewares(): DiscoveredMiddleware[] {\n    return [...this.configMiddleware, ...this.middleware];\n  }\n\n  hasMiddleware(): boolean {\n    return this.configMiddleware.length > 0 || this.middleware.length > 0;\n  }\n\n  private matchRoutePath(\n    pathname: string,\n    middlewarePath: string,\n  ): { matched: boolean; params?: Record<string, string> } {\n    if (middlewarePath === \"/\") return { matched: true };\n\n    const exactMatch = this.matchPattern(middlewarePath, pathname);\n    if (exactMatch.matched) {\n      return exactMatch;\n    }\n\n    const nestedMatch = this.matchPattern(`${middlewarePath}/:__farmRest*`, pathname);\n    if (!nestedMatch.matched) {\n      return { matched: false };\n    }\n\n    const params = { ...nestedMatch.params };\n    delete params.__farmRest;\n    return {\n      matched: true,\n      params: Object.keys(params).length > 0 ? params : undefined,\n    };\n  }\n\n  private toMatcherList(matcher: MiddlewareConfig[\"matcher\"]): MiddlewareMatcher[] {\n    if (!matcher) return [];\n    return Array.isArray(matcher) ? matcher : [matcher];\n  }\n\n  private getConfigHandlers(\n    entry:\n      | MiddlewareConfig\n      | (MiddlewareConfig & {\n          handler?: MiddlewareFunction;\n          handlers?: MiddlewareFunction[];\n        }),\n  ): MiddlewareFunction[] {\n    const handlers: MiddlewareFunction[] = [];\n    if (\"handler\" in entry && typeof entry.handler === \"function\") {\n      handlers.push(entry.handler);\n    }\n    if (\"handlers\" in entry && Array.isArray(entry.handlers)) {\n      handlers.push(...entry.handlers.filter((handler) => typeof handler === \"function\"));\n    }\n    return handlers;\n  }\n\n  private toMiddlewareConfig(\n    entry: MiddlewareConfig & {\n      handler?: MiddlewareFunction;\n      handlers?: MiddlewareFunction[];\n    },\n  ): MiddlewareConfig {\n    const { matcher, exclude, runtime } = entry;\n    return { matcher, exclude, runtime };\n  }\n\n  private compilePathPattern(pattern: string): { regex: RegExp; params: string[] } {\n    const params: string[] = [];\n    const segments = pattern.split(\"/\").filter(Boolean);\n\n    if (segments.length === 0) {\n      return { regex: /^\\/$/, params };\n    }\n\n    const parts = segments.map((segment) => {\n      if (segment === \"**\") {\n        return \"(?:/.*)?\";\n      }\n\n      if (segment === \"*\") {\n        return \"/[^/]+\";\n      }\n\n      if (segment.startsWith(\":\")) {\n        const { name, modifier } = this.parseColonParam(segment);\n        params.push(name);\n\n        if (modifier === \"*\") {\n          return \"(?:/(.*))?\";\n        }\n        if (modifier === \"+\") {\n          return \"/(.+)\";\n        }\n        return \"/([^/]+)\";\n      }\n\n      if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n        params.push(segment.slice(4, -1));\n        return \"(?:/(.*))?\";\n      }\n\n      if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n        params.push(segment.slice(1, -1));\n        return \"/([^/]+)\";\n      }\n\n      return `/${this.escapeRegex(segment).replace(/\\\\\\*/g, \"[^/]*\")}`;\n    });\n\n    return {\n      regex: new RegExp(`^${parts.join(\"\")}$`),\n      params,\n    };\n  }\n\n  private parseColonParam(segment: string): { name: string; modifier?: string } {\n    const raw = segment.slice(1);\n    const last = raw[raw.length - 1];\n    const modifier = last === \"*\" || last === \"+\" || last === \"?\" ? last : undefined;\n    return {\n      name: modifier ? raw.slice(0, -1) : raw,\n      modifier,\n    };\n  }\n\n  private escapeRegex(value: string): string {\n    return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n  }\n}\n","import { readFileSync, writeFileSync } from \"node:fs\";\n\nexport function writeFileIfChanged(filePath: string, content: string): boolean {\n  try {\n    if (readFileSync(filePath, \"utf8\") === content) {\n      return false;\n    }\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n      throw error;\n    }\n  }\n\n  writeFileSync(filePath, content, \"utf8\");\n  return true;\n}\n","import { readFileSync, existsSync, readdirSync, mkdirSync } from \"fs\";\nimport { join, relative, dirname } from \"path\";\nimport { initSync, parse } from \"es-module-lexer\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\nimport { registerAPIRouteShape } from \"./api/route-shape\";\nimport { isFarmAPIRouteFileName } from \"./api/route-files\";\n\nlet moduleLexerInitialized = false;\n\nconst API_CLIENT_METHOD_SEGMENTS = new Set([\n  \"get\",\n  \"head\",\n  \"query\",\n  \"post\",\n  \"put\",\n  \"delete\",\n  \"patch\",\n  \"options\",\n]);\n\nexport interface APIRouteInfo {\n  path: string;\n  methods: string[];\n  filePath: string;\n  relativePath: string;\n}\n\nexport class APITypeGenerator {\n  private appDirs: string[];\n\n  constructor(appDir: string | readonly string[]) {\n    this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n  }\n\n  /**\n   * Scan all API route files and extract route information\n   */\n  scanAPIRoutes(): APIRouteInfo[] {\n    const methodSources = new Map<string, Map<string, APIRouteInfo>>();\n\n    for (const appDir of this.appDirs) {\n      const apiDir = join(appDir, \"api\");\n      if (!existsSync(apiDir)) continue;\n\n      const discovered: APIRouteInfo[] = [];\n      this.scanDirectory(apiDir, appDir, discovered);\n      for (const route of discovered) {\n        const routeMethods = methodSources.get(route.path) ?? new Map<string, APIRouteInfo>();\n        for (const method of route.methods) {\n          routeMethods.set(method, route);\n        }\n        methodSources.set(route.path, routeMethods);\n      }\n    }\n\n    const routes: APIRouteInfo[] = [];\n    for (const [routePath, methods] of methodSources) {\n      const routesByFile = new Map<string, APIRouteInfo>();\n      for (const [method, route] of methods) {\n        const existing = routesByFile.get(route.filePath);\n        if (existing) {\n          existing.methods.push(method);\n        } else {\n          routesByFile.set(route.filePath, {\n            ...route,\n            path: routePath,\n            methods: [method],\n          });\n        }\n      }\n      routes.push(...routesByFile.values());\n    }\n\n    return routes.sort(\n      (left, right) =>\n        left.path.localeCompare(right.path) || left.filePath.localeCompare(right.filePath),\n    );\n  }\n\n  private scanDirectory(dir: string, appDir: string, routes: APIRouteInfo[], basePath = \"\") {\n    const items = readdirSync(dir, { withFileTypes: true });\n\n    for (const item of items) {\n      const fullPath = join(dir, item.name);\n\n      if (item.isDirectory()) {\n        const newBasePath = basePath ? `${basePath}/${item.name}` : item.name;\n        this.scanDirectory(fullPath, appDir, routes, newBasePath);\n      } else if (isFarmAPIRouteFileName(item.name)) {\n        const routeInfo = this.extractRouteInfo(fullPath, appDir, basePath);\n        if (routeInfo) {\n          routes.push(routeInfo);\n        }\n      }\n    }\n  }\n\n  private extractRouteInfo(\n    filePath: string,\n    appDir: string,\n    basePath: string,\n  ): APIRouteInfo | null {\n    try {\n      const content = readFileSync(filePath, \"utf-8\");\n      const methods = this.extractExportedMethods(content);\n\n      if (methods.length === 0) {\n        return null;\n      }\n\n      const relativePath = relative(appDir, filePath);\n      const apiPath = basePath ? `/api/${basePath}` : \"/api\";\n\n      return {\n        path: apiPath,\n        methods,\n        filePath,\n        relativePath,\n      };\n    } catch (error) {\n      console.warn(`Failed to read route file ${filePath}:`, error);\n      return null;\n    }\n  }\n\n  private extractExportedMethods(content: string): string[] {\n    if (!moduleLexerInitialized) {\n      initSync();\n      moduleLexerInitialized = true;\n    }\n    const httpMethods = [\"GET\", \"HEAD\", \"QUERY\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"];\n    const [, exports] = parse(content);\n    const valueExports = new Set(\n      exports\n        .filter((specifier) => !this.isTypeOnlyExportSpecifier(content, specifier.s))\n        .map((specifier) => specifier.n),\n    );\n    return httpMethods.filter((method) => valueExports.has(method));\n  }\n\n  private isTypeOnlyExportSpecifier(content: string, exportNameStart: number): boolean {\n    let cursor = exportNameStart - 1;\n\n    while (cursor >= 0) {\n      while (cursor >= 0 && /\\s/.test(content[cursor])) cursor--;\n\n      if (content.slice(cursor - 1, cursor + 1) === \"*/\") {\n        const commentStart = content.lastIndexOf(\"/*\", cursor - 1);\n        if (commentStart >= 0) {\n          cursor = commentStart - 1;\n          continue;\n        }\n      }\n\n      const lineStart = content.lastIndexOf(\"\\n\", cursor) + 1;\n      const lineCommentStart = content.indexOf(\"//\", lineStart);\n      if (lineCommentStart >= 0 && lineCommentStart <= cursor) {\n        cursor = lineCommentStart - 1;\n        continue;\n      }\n\n      break;\n    }\n\n    const tokenEnd = cursor + 1;\n    while (cursor >= 0 && /[A-Za-z0-9_$]/.test(content[cursor])) cursor--;\n    return content.slice(cursor + 1, tokenEnd) === \"type\";\n  }\n\n  /**\n   * Generate TypeScript code for the API router\n   */\n  generateAPIRouter(\n    routes: APIRouteInfo[],\n    options: {\n      outFile?: string;\n      pluginConfigs?: readonly string[];\n      pluginRoutes?: readonly { path: string; method: string }[];\n    } = {},\n  ): string {\n    const imports: string[] = [];\n    const pluginTypes: string[] = [];\n    if (options.pluginConfigs?.length) {\n      imports.push('import type { PluginAPIRouter } from \"@farm.js/core/api\";');\n      options.pluginConfigs.forEach((filePath, index) => {\n        const importPath = this.getRouteImportPath({ filePath } as APIRouteInfo, options.outFile);\n        imports.push(`import type FarmPluginConfig${index} from ${JSON.stringify(importPath)};`);\n        pluginTypes.push(`PluginAPIRouter<typeof FarmPluginConfig${index}>`);\n      });\n    }\n\n    // Group routes by path to handle multiple methods\n    const routeGroups = new Map<string, APIRouteInfo[]>();\n\n    for (const route of routes) {\n      const key = route.path;\n      if (!routeGroups.has(key)) {\n        routeGroups.set(key, []);\n      }\n      routeGroups.get(key)!.push(route);\n    }\n\n    const routeMethodsByPath = new Map<string, Set<string>>();\n    for (const [routePath, routeList] of routeGroups) {\n      const cleanPath = routePath === \"/api\" ? \"\" : routePath.replace(/^\\/api\\//, \"\");\n      routeMethodsByPath.set(\n        cleanPath,\n        new Set(routeList.flatMap((route) => route.methods.map((method) => method.toLowerCase()))),\n      );\n    }\n    for (const route of options.pluginRoutes ?? []) {\n      const cleanPath = route.path === \"/api\" ? \"\" : route.path.replace(/^\\/api\\//, \"\");\n      const methods = routeMethodsByPath.get(cleanPath) ?? new Set<string>();\n      methods.add(route.method.toLowerCase());\n      routeMethodsByPath.set(cleanPath, methods);\n    }\n\n    // Build nested structure\n    const nestedStructure: any = {};\n    const usedRouteNames = new Map<string, number>();\n\n    for (const [path, routeList] of routeGroups) {\n      const routeName = this.uniqueRouteName(path, usedRouteNames);\n      const cleanPath = path === \"/api\" ? \"\" : path.replace(/^\\/api\\//, \"\");\n      const parts = cleanPath ? cleanPath.split(\"/\") : [];\n\n      // Keep the final source for each method, matching runtime layer precedence.\n      const methodSources = new Map<string, APIRouteInfo>();\n      for (const route of routeList) {\n        for (const method of route.methods) methodSources.set(method, route);\n      }\n      const allMethods = [...methodSources.keys()];\n\n      // Generate imports\n      for (const method of allMethods) {\n        const importPath = this.getRouteImportPath(methodSources.get(method)!, options.outFile);\n        const importName = `${method}_${routeName}`;\n        imports.push(\n          `import type { ${method} as ${importName} } from ${JSON.stringify(importPath)};`,\n        );\n      }\n\n      if (parts.length === 0) {\n        for (const method of allMethods) {\n          const importName = `${method}_${routeName}`;\n          const methodName = method.toLowerCase();\n          nestedStructure[methodName] = `typeof ${importName}`;\n        }\n      } else {\n        const hasMethodCollision = parts.some((part, index) => {\n          if (part === \"$params\" || (index === 0 && part === \"integrations\")) return true;\n          if (!API_CLIENT_METHOD_SEGMENTS.has(part)) return false;\n          const parentPath = parts.slice(0, index).join(\"/\");\n          return routeMethodsByPath.get(parentPath)?.has(part) === true;\n        });\n        const typePath = hasMethodCollision ? [`/${cleanPath}`] : parts;\n        // Build nested object\n        let current = nestedStructure;\n        for (let i = 0; i < typePath.length; i++) {\n          const part = typePath[i];\n          if (i === typePath.length - 1) {\n            // Last part - add methods\n            current[part] = {};\n            for (const method of allMethods) {\n              const importName = `${method}_${routeName}`;\n              const methodName = method.toLowerCase();\n              current[part][methodName] = `typeof ${importName}`;\n            }\n          } else {\n            // Intermediate part - create nested object\n            if (!current[part]) {\n              current[part] = {};\n            }\n            current = current[part];\n          }\n        }\n      }\n    }\n\n    // Convert nested structure to TypeScript code\n    const typeExports = this.structureToTypeString(nestedStructure, 1);\n    const manifest = new Map<string, Set<string>>();\n    const shapes = new Map();\n    for (const route of routes) {\n      registerAPIRouteShape(shapes, route.path, route.filePath, \"app\");\n      const methods = manifest.get(route.path) ?? new Set<string>();\n      for (const method of route.methods) methods.add(method);\n      manifest.set(route.path, methods);\n    }\n    for (const route of options.pluginRoutes ?? []) {\n      registerAPIRouteShape(shapes, route.path, `plugin:${route.path}`, \"app\");\n      const methods = manifest.get(route.path) ?? new Set<string>();\n      if (methods.has(route.method))\n        throw new Error(`Duplicate API route for ${route.method} ${route.path}`);\n      methods.add(route.method);\n      manifest.set(route.path, methods);\n    }\n    const routeManifest = [...manifest]\n      .sort(([a], [b]) => a.localeCompare(b))\n      .map(([path, methods]) => ({ path, methods: [...methods].sort() }));\n    const manifestSource = routeManifest.length\n      ? `[\\n${routeManifest\n          .map(\n            ({ path, methods }) =>\n              `  {\\n    path: ${JSON.stringify(path)},\\n    methods: [${methods.map((method) => JSON.stringify(method)).join(\", \")}],\\n  },`,\n          )\n          .join(\"\\n\")}\\n]`\n      : \"[]\";\n\n    return `/**\n * Auto-generated API router types\n * This file is automatically generated - do not edit manually\n *\n * Server modules are imported only as types. Runtime data contains paths and methods only.\n */\n\n${imports.join(\"\\n\")}\n\n// Type-only representation of your API routes\nexport type APIRouter = ${pluginTypes.length ? `${pluginTypes.join(\" & \")} & ` : \"\"}{\n${typeExports}\n};\n\n// Pass this schema-free manifest to createApiClients({ routes: apiRoutes }).\nexport const apiRoutes = ${manifestSource} as const;\n`;\n  }\n\n  private getRouteImportPath(route: APIRouteInfo, outFile?: string): string {\n    if (!outFile) {\n      return `../app/${route.relativePath.replace(/\\\\/g, \"/\").replace(/\\.(ts|tsx|js|jsx)$/, \"\")}`;\n    }\n\n    const relativeImport = relative(dirname(outFile), route.filePath)\n      .replace(/\\\\/g, \"/\")\n      .replace(/\\.(ts|tsx|js|jsx)$/, \"\");\n    return relativeImport.startsWith(\".\") ? relativeImport : `./${relativeImport}`;\n  }\n\n  private pathToRouteName(path: string): string {\n    // Replace (not strip) invalid identifier characters, so /api/id and\n    // /api/[id] do not normalize to the same name.\n    return (path === \"/api\" ? \"root\" : path.replace(/^\\/api\\//, \"\"))\n      .replace(/\\//g, \"_\")\n      .replace(/[^a-zA-Z0-9_]/g, \"_\");\n  }\n\n  private uniqueRouteName(path: string, usedNames: Map<string, number>): string {\n    const base = this.pathToRouteName(path);\n    const seen = usedNames.get(base);\n    usedNames.set(base, (seen ?? 0) + 1);\n    // Suffix any remaining collision so the generated import aliases are\n    // always distinct identifiers.\n    return seen ? `${base}_${seen + 1}` : base;\n  }\n\n  private structureToTypeString(obj: any, indent: number): string {\n    const spaces = \"  \".repeat(indent);\n    const lines: string[] = [];\n\n    for (const [key, value] of Object.entries(obj)) {\n      const propertyKey = this.toTypePropertyKey(key);\n\n      if (typeof value === \"string\") {\n        // It's a type reference\n        lines.push(`${spaces}${propertyKey}: ${value};`);\n      } else if (typeof value === \"object\") {\n        // It's a nested object\n        lines.push(`${spaces}${propertyKey}: {`);\n        lines.push(this.structureToTypeString(value, indent + 1));\n        lines.push(`${spaces}};`);\n      }\n    }\n\n    return lines.join(\"\\n\");\n  }\n\n  private toTypePropertyKey(key: string): string {\n    return /^[$A-Z_][0-9A-Z_$]*$/i.test(key) ? key : JSON.stringify(key);\n  }\n\n  private getBaseExportName(path: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n\n    if (cleanPath === \"\") {\n      return \"api\";\n    }\n\n    // Convert path to nested structure\n    // /api/auth/login -> ['auth', 'login']\n    return cleanPath;\n  }\n\n  private getExportName(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n\n    if (cleanPath === \"\") {\n      return method.toLowerCase();\n    }\n\n    const parts = cleanPath.split(\"/\");\n    if (parts.length === 1) {\n      // For single-level paths like /api/hello, just use the path name\n      return parts[0];\n    }\n\n    // For nested paths like /api/auth/login, create nested structure\n    // This matches the expected API client usage: api.auth.login()\n    return parts.join(\".\");\n  }\n\n  /**\n   * Generate the API index file\n   */\n  generateAPIIndex(outputPath: string): void {\n    const routes = this.scanAPIRoutes();\n    const content = this.generateAPIRouter(routes, { outFile: outputPath });\n\n    mkdirSync(dirname(outputPath), { recursive: true });\n    writeFileIfChanged(outputPath, content);\n    console.log(`✅ Generated API types for ${routes.length} routes`);\n  }\n}\n","import * as path from \"path\";\nimport * as fs from \"fs\";\nimport { parseRoutePath } from \"../utils\";\nimport { parseRouteSlotFile } from \"./route-slots\";\nimport type { ParsedRoute } from \"../types\";\nimport { discoverProgrammaticRoutePaths } from \"../routes.server\";\nimport type { FarmSourceRoot } from \"../layers\";\nimport { writeFileIfChanged } from \"../write-file-if-changed\";\nimport { resolveFarmComponentExtensions } from \"../renderer\";\n\nfunction routeSegmentsToTsTypeLiteral(segments: string[]): string {\n  if (segments.length === 0) return '\"/\"';\n  const hasDynamic = segments.some((s) => s.startsWith(\"[\"));\n  if (!hasDynamic) return JSON.stringify(\"/\" + segments.join(\"/\"));\n  const parts = segments.map((s) => {\n    if (s.startsWith(\"[[...\") || s.startsWith(\"[...\")) return \"${string}\";\n    if (s.startsWith(\"[\")) return \"${string}\";\n    return s;\n  });\n  return \"`/\" + parts.join(\"/\") + \"`\";\n}\n\nfunction routePatternToTsTypeLiterals(pattern: string): string[] {\n  if (pattern === \"/\") return ['\"/\"'];\n\n  let variants: string[][] = [[]];\n  for (const segment of pattern.slice(1).split(\"/\").filter(Boolean)) {\n    if (segment.startsWith(\"[[...\") && segment.endsWith(\"]]\")) {\n      variants = variants.flatMap((parts) => [parts, [...parts, segment]]);\n    } else {\n      variants = variants.map((parts) => [...parts, segment]);\n    }\n  }\n\n  return variants.map(routeSegmentsToTsTypeLiteral);\n}\n\nfunction routePatternToRouteLiteral(pattern: string): string {\n  return JSON.stringify(pattern);\n}\n\nfunction renderTypeUnion(values: readonly string[]): string {\n  return values.length <= 1 ? values[0] || \"never\" : `\\n  | ${values.join(\"\\n  | \")}`;\n}\n\nfunction renderTypeAlias(name: string, value: string): string {\n  return `export type ${name} =${value.startsWith(\"\\n\") ? \"\" : \" \"}${value};`;\n}\n\nfunction createRoutePattern(route: ParsedRoute): string {\n  if (route.segments.length === 0) return \"/\";\n  return (\n    \"/\" +\n    route.segments\n      .map((seg) => {\n        if (!seg.isDynamic) return seg.segment;\n        if (seg.isCatchAll) return seg.isOptional ? `[[...${seg.segment}]]` : `[...${seg.segment}]`;\n        return `[${seg.segment}]`;\n      })\n      .join(\"/\")\n  );\n}\n\nexport interface GenerateRouteTypesOptions {\n  root: string;\n  srcDir?: string;\n  outFile?: string;\n  extraRoutes?: string[];\n  /** Ordered layer roots followed by the project root. */\n  sourceRoots?: readonly FarmSourceRoot[];\n  /** When true, do not augment LinkDefaultRoute so Link href accepts any string (no route-type errors). */\n  suppressLintOnLink?: boolean;\n  /** Additional renderer-owned component extensions, such as `.vue` or `.svelte`. */\n  componentExtensions?: readonly string[];\n}\n\nconst DEFAULT_OUT_FILE = \"farm-routes.d.ts\";\n\n/**\n * Scan application route modules, generate page and module route unions,\n * and write a .d.ts file for typed Link hrefs and route component props.\n */\nexport async function generateRouteTypes(options: GenerateRouteTypesOptions): Promise<string> {\n  const root = path.resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const outFile = options.outFile || DEFAULT_OUT_FILE;\n  const outPath = path.isAbsolute(outFile) ? outFile : path.join(root, srcDir, outFile);\n  const content = await createRouteTypeDeclarations(options, outPath);\n\n  fs.mkdirSync(path.dirname(outPath), { recursive: true });\n  writeFileIfChanged(outPath, content);\n\n  return outPath;\n}\n\nexport async function createRouteTypeDeclarations(\n  options: GenerateRouteTypesOptions,\n  outPath: string,\n): Promise<string> {\n  const { root, srcDir = \"src\", extraRoutes = [], suppressLintOnLink = false } = options;\n  const sourceRoots = options.sourceRoots ?? [{ name: \"project\", root, srcDir, layer: false }];\n  const componentExtensions = resolveFarmComponentExtensions(options.componentExtensions).map(\n    (extension) => extension.slice(1),\n  );\n\n  const patterns = new Set<string>();\n  const routeModulePatterns = new Set<string>();\n\n  const glob = await import(\"fast-glob\");\n  for (const source of sourceRoots) {\n    const appDir = path.join(source.root, source.srcDir, \"app\");\n    if (fs.existsSync(appDir)) {\n      const routeModuleFiles = await glob.default(\n        `**/{page,layout,loading,error}.{${componentExtensions.join(\",\")},md,mdx}`,\n        {\n          cwd: appDir,\n          absolute: false,\n        },\n      );\n\n      for (const file of routeModuleFiles) {\n        if (parseRouteSlotFile(file)) continue;\n        const route = parseRoutePath(file);\n        const pattern = createRoutePattern(route);\n        routeModulePatterns.add(pattern);\n        if (route.type === \"page\") {\n          patterns.add(pattern);\n        }\n      }\n    }\n\n    for (const route of await discoverProgrammaticRoutePaths(source.root, source.srcDir)) {\n      patterns.add(route);\n      routeModulePatterns.add(route);\n    }\n  }\n\n  for (const route of extraRoutes) {\n    if (route.startsWith(\"/\")) {\n      patterns.add(route);\n      routeModulePatterns.add(route);\n    }\n  }\n\n  const sortedPatterns = Array.from(patterns).sort();\n  const typeLiterals = Array.from(new Set(sortedPatterns.flatMap(routePatternToTsTypeLiterals)));\n  const patternLiterals = sortedPatterns.map(routePatternToRouteLiteral);\n  const routeModulePatternLiterals = Array.from(routeModulePatterns)\n    .sort()\n    .map(routePatternToRouteLiteral);\n\n  const routePathType = suppressLintOnLink ? \"string\" : renderTypeUnion(typeLiterals);\n  const routePatternType = suppressLintOnLink ? \"string\" : renderTypeUnion(patternLiterals);\n  const routeModulePatternType = renderTypeUnion(routeModulePatternLiterals);\n  const routeTypesImportPath = `./${path.basename(outPath).replace(/\\.d\\.ts$/, \"\")}`;\n  const linkAugmentationBlock = suppressLintOnLink\n    ? \"\"\n    : `\ndeclare module \"@farm.js/core/client\" {\n  interface LinkDefaultRoute {\n    _: import(${JSON.stringify(routeTypesImportPath)}).RoutePath;\n    pattern: import(${JSON.stringify(routeTypesImportPath)}).RoutePattern;\n  }\n}\n\ndeclare module \"@farm.js/core\" {\n  interface LinkDefaultRoute {\n    _: import(${JSON.stringify(routeTypesImportPath)}).RoutePath;\n    pattern: import(${JSON.stringify(routeTypesImportPath)}).RoutePattern;\n  }\n  // Ensure root import (\"@farm.js/core\") uses the same typed Link signature as client entry.\n  const Link: typeof import(\"@farm.js/core/client\").Link;\n}\n\n// Internal declaration path used by @farm.js/core root type re-exports.\ndeclare module \"@farm.js/core/dist/client.js\" {\n  interface LinkDefaultRoute {\n    _: import(${JSON.stringify(routeTypesImportPath)}).RoutePath;\n    pattern: import(${JSON.stringify(routeTypesImportPath)}).RoutePattern;\n  }\n}\n`;\n\n  const routeModuleAugmentationBlock = `\ndeclare global {\n  namespace FarmJS {\n    interface RouteRegistry {\n      pattern: import(${JSON.stringify(routeTypesImportPath)}).RouteModulePattern;\n    }\n  }\n}\n`;\n\n  const content = `/**\n * Auto-generated route types from src/app.\n * Link href and route component props are typed automatically from generated declarations.\n * Regenerated on dev start and when routes change.\n * Set suppressLintOnLink: true in farm.config.ts to accept any string on Link href.\n */\n${renderTypeAlias(\"RoutePath\", routePathType)}\n${renderTypeAlias(\"RoutePattern\", routePatternType)}\n${renderTypeAlias(\"RouteModulePattern\", routeModulePatternType)}${linkAugmentationBlock}${routeModuleAugmentationBlock}\n`;\n\n  return content;\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\n\nexport interface GenerateEnvTypesOptions {\n  root: string;\n  srcDir?: string;\n  outFile?: string;\n  configPath?: string;\n  /** Lower-priority layer config files, ordered before the project config. */\n  layerConfigPaths?: readonly string[];\n}\n\nconst DEFAULT_OUT_FILE = \"farm-env.d.ts\";\nconst CONFIG_FILENAMES = [\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n];\n\nexport async function generateEnvTypes(options: GenerateEnvTypesOptions): Promise<string> {\n  const root = path.resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const outFile = options.outFile || DEFAULT_OUT_FILE;\n  const outPath = path.isAbsolute(outFile) ? outFile : path.join(root, srcDir, outFile);\n  const content = createEnvTypeDeclarations(options, outPath);\n\n  fs.mkdirSync(path.dirname(outPath), { recursive: true });\n  writeFileIfChanged(outPath, content);\n\n  return outPath;\n}\n\nexport function createEnvTypeDeclarations(\n  options: GenerateEnvTypesOptions,\n  outPath: string,\n): string {\n  const root = path.resolve(options.root);\n  const configPath = findConfigPath(root, options.configPath);\n  const configPaths = [\n    ...(options.layerConfigPaths ?? []).filter((value) => fs.existsSync(value)),\n    ...(configPath ? [configPath] : []),\n  ];\n  const content =\n    configPaths.length > 1\n      ? createLayeredConfigBackedEnvTypes(outPath, configPaths)\n      : configPaths.length === 1\n        ? createConfigBackedEnvTypes(outPath, configPaths[0])\n        : createEmptyEnvTypes();\n\n  return content;\n}\n\nfunction createLayeredConfigBackedEnvTypes(outPath: string, configPaths: string[]): string {\n  const imports = configPaths\n    .map(\n      (configPath, index) =>\n        `import type FarmConfig${index} from ${JSON.stringify(toTypeImportPath(outPath, configPath))};`,\n    )\n    .join(\"\\n\");\n  const resolvedTypes = configPaths\n    .map(\n      (_configPath, index) => `\ntype FarmConfigEnv${index} = typeof FarmConfig${index} extends { env?: infer TEnv }\n  ? NonNullable<TEnv>\n  : never;\ntype FarmResolvedEnv${index} = [FarmConfigEnv${index}] extends [never]\n  ? { server: {}; public: {} }\n  : InferEnv<FarmConfigEnv${index}>;`,\n    )\n    .join(\"\\n\");\n  const mergedTypes = configPaths\n    .slice(1)\n    .map(\n      (_configPath, index) =>\n        `type FarmMergedEnv${index + 1} = MergeFarmEnv<${index === 0 ? \"FarmResolvedEnv0\" : `FarmMergedEnv${index}`}, FarmResolvedEnv${index + 1}>;`,\n    )\n    .join(\"\\n\");\n  const finalType = `FarmMergedEnv${configPaths.length - 1}`;\n\n  return `/**\n * Auto-generated env types from Farm layers and farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\n${imports}\nimport type { InferEnv } from \"@farm.js/core/env\";\n\ntype MergeFarmEnv<TBase, TOverride> = {\n  server: Omit<TBase extends { server: infer T } ? T : {}, keyof (TOverride extends { server: infer T } ? T : {})> &\n    (TOverride extends { server: infer T } ? T : {});\n  public: Omit<TBase extends { public: infer T } ? T : {}, keyof (TOverride extends { public: infer T } ? T : {})> &\n    (TOverride extends { public: infer T } ? T : {});\n};\n${resolvedTypes}\n${mergedTypes}\n\ntype FarmResolvedEnv = ${finalType};\n\ndeclare module \"@farm.js/core/env\" {\n  interface FarmEnvTypes {\n    server: FarmResolvedEnv[\"server\"];\n    public: FarmResolvedEnv[\"public\"];\n  }\n}\n\ndeclare module \"@farm.js/core\" {\n  interface FarmEnvTypes {\n    server: FarmResolvedEnv[\"server\"];\n    public: FarmResolvedEnv[\"public\"];\n  }\n}\n\nexport {};\n`;\n}\n\nfunction findConfigPath(root: string, configPath?: string): string | null {\n  if (configPath) {\n    const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n    return fs.existsSync(resolvedPath) ? resolvedPath : null;\n  }\n\n  for (const filename of CONFIG_FILENAMES) {\n    const resolvedPath = path.join(root, filename);\n    if (fs.existsSync(resolvedPath)) {\n      return resolvedPath;\n    }\n  }\n\n  return null;\n}\n\nfunction createConfigBackedEnvTypes(outPath: string, configPath: string): string {\n  const configImportPath = toTypeImportPath(outPath, configPath);\n\n  return `/**\n * Auto-generated env types from farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\nimport type FarmConfig from ${JSON.stringify(configImportPath)};\nimport type { InferEnv } from \"@farm.js/core/env\";\n\ntype FarmConfigEnv = typeof FarmConfig extends { env?: infer TEnv } ? NonNullable<TEnv> : never;\ntype FarmResolvedEnv = [FarmConfigEnv] extends [never]\n  ? { server: {}; public: {} }\n  : InferEnv<FarmConfigEnv>;\n\ndeclare module \"@farm.js/core/env\" {\n  interface FarmEnvTypes {\n    server: FarmResolvedEnv[\"server\"];\n    public: FarmResolvedEnv[\"public\"];\n  }\n}\n\ndeclare module \"@farm.js/core\" {\n  interface FarmEnvTypes {\n    server: FarmResolvedEnv[\"server\"];\n    public: FarmResolvedEnv[\"public\"];\n  }\n}\n\nexport {};\n`;\n}\n\nfunction createEmptyEnvTypes(): string {\n  return `/**\n * Auto-generated env types from farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\ndeclare module \"@farm.js/core/env\" {\n  interface FarmEnvTypes {\n    server: {};\n    public: {};\n  }\n}\n\ndeclare module \"@farm.js/core\" {\n  interface FarmEnvTypes {\n    server: {};\n    public: {};\n  }\n}\n\nexport {};\n`;\n}\n\nfunction toTypeImportPath(outPath: string, targetPath: string): string {\n  const relativePath = path\n    .relative(path.dirname(outPath), targetPath)\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/, \"\");\n\n  return relativePath.startsWith(\".\") ? relativePath : `./${relativePath}`;\n}\n","import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\n\nexport const FARM_STATIC_IMAGE_EXTENSIONS = [\"avif\", \"gif\", \"jpeg\", \"jpg\", \"png\", \"webp\"] as const;\n\nexport interface GenerateFarmImageTypesOptions {\n  root: string;\n  srcDir?: string;\n  outFile?: string;\n}\n\nexport function generateFarmImageTypes(options: GenerateFarmImageTypesOptions): string {\n  const outputPath = options.outFile\n    ? path.resolve(options.root, options.outFile)\n    : path.join(options.root, options.srcDir || \"src\", \"farm-images.d.ts\");\n  mkdirSync(path.dirname(outputPath), { recursive: true });\n  writeFileIfChanged(outputPath, createFarmImageTypeDeclarations());\n  return outputPath;\n}\n\nexport function createFarmImageTypeDeclarations(): string {\n  const modules = FARM_STATIC_IMAGE_EXTENSIONS.map(\n    (extension) => `declare module \"*.${extension}\" {\n  const image: import(\"@farm.js/core/image\").StaticImageData;\n  export const src: string;\n  export const width: number;\n  export const height: number;\n  export const blurDataURL: string | undefined;\n  export default image;\n}`,\n  );\n\n  return `// Generated by Farm.js. Do not edit.\n${modules.join(\"\\n\\n\")}\n\ndeclare module \"*?url\" {\n  const src: string;\n  export default src;\n}\n`;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport interface CreateContentTypeDeclarationsOptions {\n  root: string;\n  configPath?: string;\n  /** Lower-priority layer config files, ordered before the project config. */\n  layerConfigPaths?: readonly string[];\n}\n\nconst CONFIG_FILENAMES = [\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n];\n\n/** Infer content collection names and entry data from content() in Farm config. */\nexport function createContentTypeDeclarations(\n  options: CreateContentTypeDeclarationsOptions,\n  outPath: string,\n): string {\n  const root = path.resolve(options.root);\n  const projectConfig = findConfigPath(root, options.configPath);\n  const configPaths = [\n    ...(options.layerConfigPaths ?? []).filter((value) => fs.existsSync(value)),\n    ...(projectConfig ? [projectConfig] : []),\n  ];\n\n  if (configPaths.length === 0) return createEmptyContentTypes();\n\n  const imports = configPaths\n    .map(\n      (configPath, index) =>\n        `import type FarmContentConfig${index} from ${JSON.stringify(toTypeImportPath(outPath, configPath))};`,\n    )\n    .join(\"\\n\");\n  const registries = configPaths\n    .map(\n      (_configPath, index) =>\n        `type FarmContentRegistry${index} = ContentRegistryFromConfig<typeof FarmContentConfig${index}>;`,\n    )\n    .join(\"\\n\");\n  const registryUnion = configPaths\n    .map((_configPath, index) => `FarmContentRegistry${index}`)\n    .join(\" | \");\n\n  return `/**\n * Auto-generated content collection types from Farm layers and farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\n${imports}\n\ntype FarmContentPluginFromConfig<TConfig> = TConfig extends {\n  plugins?: readonly (infer TPlugin)[];\n}\n  ? Extract<TPlugin, { readonly __farmContentRegistry: Record<string, unknown> }>\n  : never;\ntype ContentRegistryFromConfig<TConfig> =\n  FarmContentPluginFromConfig<TConfig> extends {\n    readonly __farmContentRegistry: infer TRegistry;\n  }\n    ? TRegistry\n    : never;\ntype FarmContentUnionToIntersection<TValue> = (\n  TValue extends unknown ? (value: TValue) => void : never\n) extends (value: infer TIntersection) => void\n  ? TIntersection\n  : never;\n${registries}\n\ntype FarmResolvedContentRegistry = [${registryUnion}] extends [never]\n  ? {}\n  : FarmContentUnionToIntersection<${registryUnion}>;\n\ndeclare global {\n  namespace FarmJS {\n    interface ContentRegistry {\n      collections: FarmResolvedContentRegistry;\n    }\n  }\n}\n\nexport {};\n`;\n}\n\nfunction createEmptyContentTypes(): string {\n  return `/**\n * Auto-generated content collection types from farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\ndeclare global {\n  namespace FarmJS {\n    interface ContentRegistry {\n      collections: {};\n    }\n  }\n}\n\nexport {};\n`;\n}\n\nfunction findConfigPath(root: string, configPath?: string): string | null {\n  if (configPath) {\n    const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n    return fs.existsSync(resolvedPath) ? resolvedPath : null;\n  }\n  for (const filename of CONFIG_FILENAMES) {\n    const resolvedPath = path.join(root, filename);\n    if (fs.existsSync(resolvedPath)) return resolvedPath;\n  }\n  return null;\n}\n\nfunction toTypeImportPath(outPath: string, targetPath: string): string {\n  const relativePath = path\n    .relative(path.dirname(outPath), targetPath)\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/, \"\");\n  return relativePath.startsWith(\".\") ? relativePath : `./${relativePath}`;\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n  readFarmI18nCatalogs,\n  type FarmI18nArgumentKind,\n  type FarmI18nMessageSignature,\n} from \"./catalog\";\nimport type { ResolvedFarmI18nConfig } from \"./types\";\nimport { writeFileIfChanged } from \"../write-file-if-changed\";\n\nexport interface GenerateFarmI18nTypesOptions {\n  root: string;\n  srcDir?: string;\n  config: ResolvedFarmI18nConfig;\n  outFile?: string;\n}\n\nexport async function generateFarmI18nTypes(\n  options: GenerateFarmI18nTypesOptions,\n): Promise<string | undefined> {\n  if (!options.config.enabled) return undefined;\n\n  const { signatures } = await readFarmI18nCatalogs(options.config);\n  const outFile = options.outFile\n    ? resolve(options.root, options.outFile)\n    : join(resolve(options.root), options.srcDir || \"src\", \"farm-i18n.d.ts\");\n  const content = renderFarmI18nTypes(options.config.locales, signatures);\n\n  mkdirSync(dirname(outFile), { recursive: true });\n  writeFileIfChanged(outFile, content);\n  return outFile;\n}\n\nexport function renderFarmI18nTypes(\n  locales: readonly string[],\n  signatures: Record<string, FarmI18nMessageSignature>,\n): string {\n  const localeEntries = locales.map((locale) => `    ${JSON.stringify(locale)}: true;`);\n  const messageEntries = Object.entries(signatures)\n    .sort(([a], [b]) => a.localeCompare(b))\n    .map(([key, signature]) => `    ${JSON.stringify(key)}: ${renderSignature(signature)};`);\n\n  return `// Generated by Farm.js. Do not edit.\nimport \"@farm.js/core/i18n\";\n\ndeclare module \"@farm.js/core/i18n\" {\n  interface FarmI18nLocaleRegistry {\n${localeEntries.join(\"\\n\")}\n  }\n\n  interface FarmI18nMessageRegistry {\n${messageEntries.join(\"\\n\")}\n  }\n}\n\nexport {};\n`;\n}\n\nfunction renderSignature(signature: FarmI18nMessageSignature): string {\n  const entries = Object.entries(signature).sort(([a], [b]) => a.localeCompare(b));\n  if (entries.length === 0) return \"Record<never, never>\";\n  return `{ ${entries\n    .map(([name, kind]) => `${JSON.stringify(name)}: ${argumentType(kind)}`)\n    .join(\"; \")} }`;\n}\n\nfunction argumentType(kind: FarmI18nArgumentKind): string {\n  switch (kind) {\n    case \"number\":\n      return \"number\";\n    case \"date\":\n      return \"Date | number\";\n    case \"rich\":\n      return \"(chunks: unknown[]) => unknown\";\n    case \"select\":\n    case \"string\":\n      return \"string\";\n  }\n}\n","import { existsSync, mkdirSync, readFileSync, unlinkSync } from \"fs\";\nimport { dirname, isAbsolute, join, resolve } from \"path\";\nimport { APITypeGenerator, type APIRouteInfo } from \"./type-generator\";\nimport {\n  createRouteTypeDeclarations,\n  generateRouteTypes,\n  type GenerateRouteTypesOptions,\n} from \"./routing/generate-route-types\";\nimport { createEnvTypeDeclarations, generateEnvTypes } from \"./env-types\";\nimport { createFarmImageTypeDeclarations, generateFarmImageTypes } from \"./image-types\";\nimport { createContentTypeDeclarations } from \"./content-types\";\nimport { generateFarmI18nTypes, renderFarmI18nTypes } from \"./i18n/type-generator\";\nimport { readFarmI18nCatalogs } from \"./i18n/catalog\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport { getFarmAppDirectories, getFarmSourceRoots, type ResolvedFarmLayer } from \"./layers\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\nimport type { FarmPlugin } from \"./plugin\";\nimport { resolvePluginRoutes } from \"./api/route\";\n\nexport { generateFarmI18nTypes };\n\nexport interface GenerateFarmTypeArtifactsOptions {\n  root: string;\n  srcDir?: string;\n  configPath?: string;\n  plugins?: readonly FarmPlugin[];\n  extraRoutes?: string[];\n  layers?: readonly ResolvedFarmLayer[];\n  suppressLintOnLink?: boolean;\n  componentExtensions?: readonly string[];\n  routeTypesOutFile?: string;\n  apiTypesOutFile?: string;\n  envTypesOutFile?: string;\n  imageTypesOutFile?: string;\n  i18nTypesOutFile?: string;\n  i18nConfig?: ResolvedFarmI18nConfig;\n  routes?: boolean;\n  api?: boolean;\n  env?: boolean;\n  images?: boolean;\n  i18n?: boolean;\n  /** Compare generated content with disk without writing files. */\n  check?: boolean;\n}\n\nexport interface GenerateFarmTypeArtifactsResult {\n  typesPath?: string;\n  routeTypesPath?: string;\n  apiTypesPath?: string;\n  envTypesPath?: string;\n  imageTypesPath?: string;\n  i18nTypesPath?: string;\n  apiRoutes: APIRouteInfo[];\n  /** Generated files whose checked-in content is missing or stale. */\n  stalePaths: string[];\n}\n\nexport async function generateFarmTypeArtifacts(\n  options: GenerateFarmTypeArtifactsOptions,\n): Promise<GenerateFarmTypeArtifactsResult> {\n  const root = resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const shouldGenerateRoutes = options.routes !== false;\n  const shouldGenerateApi = options.api !== false;\n  const shouldGenerateEnv = options.env !== false;\n  const shouldGenerateImages = options.images !== false;\n  const shouldGenerateI18n = options.i18n !== false && options.i18nConfig?.enabled;\n  const sourceRoots = getFarmSourceRoots({ root, srcDir, layers: options.layers });\n  const appDirs = getFarmAppDirectories({ root, srcDir, layers: options.layers });\n\n  const result: GenerateFarmTypeArtifactsResult = {\n    apiRoutes: [],\n    stalePaths: [],\n  };\n  const unifiedTypesPath = join(root, srcDir, \"farm.d.ts\");\n  const shouldRefreshUnifiedTypes =\n    (shouldGenerateRoutes && !options.routeTypesOutFile) ||\n    (shouldGenerateEnv && !options.envTypesOutFile) ||\n    (shouldGenerateI18n && !options.i18nTypesOutFile);\n  const unifiedSections: string[] = [];\n\n  if (shouldRefreshUnifiedTypes && !options.routeTypesOutFile) {\n    const routeOptions: GenerateRouteTypesOptions = {\n      root,\n      srcDir,\n      extraRoutes: options.extraRoutes || [],\n      suppressLintOnLink: options.suppressLintOnLink,\n      componentExtensions: options.componentExtensions,\n      sourceRoots,\n    };\n    unifiedSections.push(await createRouteTypeDeclarations(routeOptions, unifiedTypesPath));\n    result.routeTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateRoutes) {\n    const routeOptions = {\n      root,\n      srcDir,\n      outFile: options.routeTypesOutFile,\n      extraRoutes: options.extraRoutes || [],\n      suppressLintOnLink: options.suppressLintOnLink,\n      componentExtensions: options.componentExtensions,\n      sourceRoots,\n    } satisfies GenerateRouteTypesOptions;\n    if (options.check) {\n      const routeTypesPath = resolveGeneratedPath(root, srcDir, options.routeTypesOutFile!);\n      const content = await createRouteTypeDeclarations(routeOptions, routeTypesPath);\n      checkGeneratedFile(routeTypesPath, content, result.stalePaths);\n      result.routeTypesPath = routeTypesPath;\n    } else {\n      result.routeTypesPath = await generateRouteTypes(routeOptions);\n    }\n  }\n\n  if (shouldGenerateApi) {\n    const generator = new APITypeGenerator(appDirs);\n    const apiRoutes = generator.scanAPIRoutes();\n    const apiTypesPath = options.apiTypesOutFile\n      ? resolve(root, options.apiTypesOutFile)\n      : join(root, srcDir, \"lib\", \"api.generated.ts\");\n    const pluginRoutes = resolvePluginRoutes(options.plugins);\n    const configFiles = [\n      ...(options.layers ?? [])\n        .map((layer) => layer.configFile)\n        .filter((file): file is string => Boolean(file)),\n      options.configPath\n        ? resolve(root, options.configPath)\n        : [\n            \"farm.config.ts\",\n            \"farm.config.mts\",\n            \"farm.config.js\",\n            \"farm.config.mjs\",\n            \"farm.config.cts\",\n            \"farm.config.cjs\",\n            \"config.ts\",\n            \"config.js\",\n          ]\n            .map((name) => join(root, name))\n            .find((file) => existsSync(file)),\n    ].filter((file): file is string => Boolean(file));\n    if (pluginRoutes.length && !configFiles.length) {\n      throw new Error(\n        \"Cannot generate plugin API types without a Farm config file. Pass configPath.\",\n      );\n    }\n    const content = generator.generateAPIRouter(apiRoutes, {\n      outFile: apiTypesPath,\n      pluginConfigs: pluginRoutes.length ? [...new Set(configFiles)] : [],\n      pluginRoutes,\n    });\n\n    writeOrCheckGeneratedFile(apiTypesPath, content, options.check, result.stalePaths);\n\n    result.apiTypesPath = apiTypesPath;\n    result.apiRoutes = apiRoutes;\n  }\n\n  if (shouldRefreshUnifiedTypes && !options.envTypesOutFile) {\n    unifiedSections.push(\n      createEnvTypeDeclarations(\n        {\n          root,\n          srcDir,\n          configPath: options.configPath,\n          layerConfigPaths: (options.layers ?? [])\n            .map((layer) => layer.configFile)\n            .filter((configFile): configFile is string => Boolean(configFile)),\n        },\n        unifiedTypesPath,\n      ),\n    );\n    result.envTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateEnv) {\n    const envOptions = {\n      root,\n      srcDir,\n      outFile: options.envTypesOutFile,\n      configPath: options.configPath,\n      layerConfigPaths: (options.layers ?? [])\n        .map((layer) => layer.configFile)\n        .filter((configFile): configFile is string => Boolean(configFile)),\n    };\n    if (options.check) {\n      const envTypesPath = resolveGeneratedPath(root, srcDir, options.envTypesOutFile!);\n      checkGeneratedFile(\n        envTypesPath,\n        createEnvTypeDeclarations(envOptions, envTypesPath),\n        result.stalePaths,\n      );\n      result.envTypesPath = envTypesPath;\n    } else {\n      result.envTypesPath = await generateEnvTypes(envOptions);\n    }\n  }\n\n  // Static image modules are declared by @farm.js/core itself. Keep the\n  // explicit output option for callers that need a standalone declaration.\n  if (shouldGenerateImages && options.imageTypesOutFile) {\n    const imageTypesPath = resolveGeneratedPath(root, srcDir, options.imageTypesOutFile, false);\n    if (options.check) {\n      checkGeneratedFile(imageTypesPath, createFarmImageTypeDeclarations(), result.stalePaths);\n      result.imageTypesPath = imageTypesPath;\n    } else {\n      result.imageTypesPath = generateFarmImageTypes({\n        root,\n        srcDir,\n        outFile: options.imageTypesOutFile,\n      });\n    }\n  }\n\n  if (shouldRefreshUnifiedTypes && options.i18nConfig?.enabled && !options.i18nTypesOutFile) {\n    const { signatures } = await readFarmI18nCatalogs(options.i18nConfig);\n    unifiedSections.push(renderFarmI18nTypes(options.i18nConfig.locales, signatures));\n    result.i18nTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateI18n && options.i18nConfig) {\n    if (options.check) {\n      const i18nTypesPath = resolveGeneratedPath(root, srcDir, options.i18nTypesOutFile!, false);\n      const { signatures } = await readFarmI18nCatalogs(options.i18nConfig);\n      checkGeneratedFile(\n        i18nTypesPath,\n        renderFarmI18nTypes(options.i18nConfig.locales, signatures),\n        result.stalePaths,\n      );\n      result.i18nTypesPath = i18nTypesPath;\n    } else {\n      result.i18nTypesPath = await generateFarmI18nTypes({\n        root,\n        srcDir,\n        config: options.i18nConfig,\n        outFile: options.i18nTypesOutFile,\n      });\n    }\n  }\n\n  if (shouldRefreshUnifiedTypes) {\n    unifiedSections.push(\n      createContentTypeDeclarations(\n        {\n          root,\n          configPath: options.configPath,\n          layerConfigPaths: (options.layers ?? [])\n            .map((layer) => layer.configFile)\n            .filter((configFile): configFile is string => Boolean(configFile)),\n        },\n        unifiedTypesPath,\n      ),\n    );\n  }\n\n  if (shouldRefreshUnifiedTypes) {\n    writeOrCheckGeneratedFile(\n      unifiedTypesPath,\n      `/**\n * Generated by Farm.js. Do not edit.\n * Contains project-specific route, environment, content, and internationalization types.\n */\n\nimport \"@farm.js/core/image\";\nimport \"@farm.js/core/css\";\n\n${unifiedSections.map(normalizeUnifiedTypeSection).join(\"\\n\\n\")}\n`,\n      options.check,\n      result.stalePaths,\n    );\n    result.typesPath = unifiedTypesPath;\n    if (options.check) {\n      collectLegacyTypeArtifacts(root, srcDir, result.stalePaths);\n    } else {\n      removeLegacyTypeArtifacts(root, srcDir);\n    }\n  }\n\n  return result;\n}\n\nfunction normalizeUnifiedTypeSection(section: string): string {\n  // The unified artifact already imports Farm's asset types, so it is a module.\n  // Individual generators add this marker for standalone declaration files, but\n  // formatters remove the now-redundant export and make `farm generate --check`\n  // report a false stale-file failure.\n  return section.trimEnd().replace(/\\n+export \\{\\};$/, \"\");\n}\n\nfunction resolveGeneratedPath(\n  root: string,\n  srcDir: string,\n  outFile: string,\n  relativeToSrc = true,\n): string {\n  if (isAbsolute(outFile)) return resolve(outFile);\n  return resolve(root, relativeToSrc ? join(srcDir, outFile) : outFile);\n}\n\nfunction writeOrCheckGeneratedFile(\n  filePath: string,\n  content: string,\n  check: boolean | undefined,\n  stalePaths: string[],\n): void {\n  if (check) {\n    checkGeneratedFile(filePath, content, stalePaths);\n    return;\n  }\n\n  mkdirSync(dirname(filePath), { recursive: true });\n  writeFileIfChanged(filePath, content);\n}\n\nfunction checkGeneratedFile(filePath: string, content: string, stalePaths: string[]): void {\n  if (!existsSync(filePath) || readFileSync(filePath, \"utf8\") !== content) {\n    stalePaths.push(filePath);\n  }\n}\n\nconst LEGACY_TYPE_ARTIFACTS = [\n  [\"farm-routes.d.ts\", \"Auto-generated route types\"],\n  [\"farm-env.d.ts\", \"Auto-generated env types\"],\n  [\"farm-images.d.ts\", \"Generated by Farm.js\"],\n  [\"farm-i18n.d.ts\", \"Generated by Farm.js\"],\n] as const;\n\nfunction removeLegacyTypeArtifacts(root: string, srcDir: string): void {\n  for (const [fileName, marker] of LEGACY_TYPE_ARTIFACTS) {\n    const filePath = join(root, srcDir, fileName);\n    if (!existsSync(filePath)) continue;\n    const source = readFileSync(filePath, \"utf8\");\n    if (source.includes(marker)) {\n      unlinkSync(filePath);\n    }\n  }\n}\n\nfunction collectLegacyTypeArtifacts(root: string, srcDir: string, stalePaths: string[]): void {\n  for (const [fileName, marker] of LEGACY_TYPE_ARTIFACTS) {\n    const filePath = join(root, srcDir, fileName);\n    if (!existsSync(filePath)) continue;\n    if (readFileSync(filePath, \"utf8\").includes(marker)) stalePaths.push(filePath);\n  }\n}\n","import type { Plugin } from \"vite\";\nimport type { FarmEnvironment } from \"./environment\";\n\ntype EnvironmentFunctionKind = \"createServerOnlyFn\" | \"createClientOnlyFn\" | \"createIsomorphicFn\";\n\ninterface AstNode {\n  type: string;\n  start: number;\n  end: number;\n  [key: string]: unknown;\n}\n\ninterface EnvironmentCall {\n  node: AstNode;\n  kind: EnvironmentFunctionKind;\n}\n\ninterface Replacement {\n  start: number;\n  end: number;\n  code: string;\n}\n\nexport interface TransformEnvironmentFunctionsOptions {\n  code: string;\n  id: string;\n  environment: FarmEnvironment;\n  parse: (code: string) => AstNode;\n}\n\nexport interface TransformEnvironmentFunctionsResult {\n  code: string;\n}\n\nconst ENVIRONMENT_IMPORTS = new Set([\n  \"@farm.js/core\",\n  \"@farm.js/core/environment\",\n  \"@farm.js/core/server\",\n]);\nconst ENVIRONMENT_FUNCTIONS = new Set<EnvironmentFunctionKind>([\n  \"createServerOnlyFn\",\n  \"createClientOnlyFn\",\n  \"createIsomorphicFn\",\n]);\nconst MODULE_EXTENSION_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function transformEnvironmentFunctions(\n  options: TransformEnvironmentFunctionsOptions,\n): TransformEnvironmentFunctionsResult | null {\n  if (!isTransformableModule(options.id) || !containsEnvironmentFunction(options.code)) {\n    return null;\n  }\n\n  let output = options.code;\n  let transformed = false;\n\n  for (let pass = 0; pass < 20; pass++) {\n    const ast = options.parse(output);\n    const bindings = findEnvironmentFunctionBindings(ast);\n    if (bindings.named.size === 0 && bindings.namespaces.size === 0) break;\n\n    const calls = findEnvironmentCalls(ast, bindings);\n    if (calls.length === 0) break;\n\n    const innermostCalls = calls.filter(\n      (call) =>\n        !calls.some(\n          (candidate) =>\n            candidate !== call &&\n            candidate.node.start > call.node.start &&\n            candidate.node.end < call.node.end,\n        ),\n    );\n    const replacements = innermostCalls.map((call) =>\n      createReplacement(output, options.id, options.environment, call),\n    );\n\n    output = applyReplacements(output, replacements);\n    transformed = true;\n  }\n\n  if (!transformed) return null;\n\n  const remainingAst = options.parse(output);\n  const remainingBindings = findEnvironmentFunctionBindings(remainingAst);\n  if (findEnvironmentCalls(remainingAst, remainingBindings).length > 0) {\n    throw transformError(options.id, \"environment functions are nested too deeply\");\n  }\n\n  return { code: output };\n}\n\nexport function farmEnvironmentFunctionsPlugin(): Plugin {\n  return {\n    name: \"farm:environment-functions\",\n    enforce: \"post\",\n\n    transform(code, id, transformOptions) {\n      const result = transformEnvironmentFunctions({\n        code,\n        id,\n        environment: resolveBuildEnvironment(\n          this as unknown as { environment?: { name?: string } },\n          transformOptions?.ssr,\n        ),\n        parse: (source) => this.parse(source) as unknown as AstNode,\n      });\n\n      return result ? { code: result.code, map: null } : null;\n    },\n  };\n}\n\nfunction resolveBuildEnvironment(\n  context: { environment?: { name?: string } },\n  ssr: boolean | undefined,\n): FarmEnvironment {\n  if (context.environment?.name === \"client\") return \"client\";\n  if (context.environment?.name === \"rsc\" || context.environment?.name === \"ssr\") {\n    return \"server\";\n  }\n  return ssr ? \"server\" : \"client\";\n}\n\nfunction findEnvironmentFunctionBindings(ast: AstNode) {\n  const named = new Map<string, EnvironmentFunctionKind>();\n  const namespaces = new Set<string>();\n  const body = Array.isArray(ast.body) ? ast.body : [];\n\n  for (const statement of body) {\n    if (!isAstNode(statement) || statement.type !== \"ImportDeclaration\") continue;\n    const source = isAstNode(statement.source) ? statement.source.value : undefined;\n    if (typeof source !== \"string\" || !ENVIRONMENT_IMPORTS.has(source)) continue;\n\n    const specifiers = Array.isArray(statement.specifiers) ? statement.specifiers : [];\n    for (const specifier of specifiers) {\n      if (!isAstNode(specifier) || !isAstNode(specifier.local)) continue;\n      const localName = specifier.local.name;\n      if (typeof localName !== \"string\") continue;\n\n      if (specifier.type === \"ImportNamespaceSpecifier\") {\n        namespaces.add(localName);\n        continue;\n      }\n\n      if (specifier.type !== \"ImportSpecifier\" || !isAstNode(specifier.imported)) continue;\n      const importedName = specifier.imported.name ?? specifier.imported.value;\n      if (isEnvironmentFunctionKind(importedName)) {\n        named.set(localName, importedName);\n      }\n    }\n  }\n\n  return { named, namespaces };\n}\n\nfunction findEnvironmentCalls(\n  ast: AstNode,\n  bindings: ReturnType<typeof findEnvironmentFunctionBindings>,\n): EnvironmentCall[] {\n  const calls: EnvironmentCall[] = [];\n\n  walkAst(ast, (node, ancestors) => {\n    if (node.type !== \"CallExpression\" || !isAstNode(node.callee)) return;\n\n    if (node.callee.type === \"Identifier\" && typeof node.callee.name === \"string\") {\n      const kind = bindings.named.get(node.callee.name);\n      if (kind && !isNameShadowed(node.callee.name, ancestors)) calls.push({ node, kind });\n      return;\n    }\n\n    if (\n      node.callee.type !== \"MemberExpression\" ||\n      node.callee.computed === true ||\n      !isAstNode(node.callee.object) ||\n      !isAstNode(node.callee.property) ||\n      node.callee.object.type !== \"Identifier\" ||\n      node.callee.property.type !== \"Identifier\" ||\n      typeof node.callee.object.name !== \"string\" ||\n      typeof node.callee.property.name !== \"string\" ||\n      !bindings.namespaces.has(node.callee.object.name) ||\n      isNameShadowed(node.callee.object.name, ancestors) ||\n      !isEnvironmentFunctionKind(node.callee.property.name)\n    ) {\n      return;\n    }\n\n    calls.push({ node, kind: node.callee.property.name });\n  });\n\n  return calls;\n}\n\nfunction createReplacement(\n  code: string,\n  id: string,\n  environment: FarmEnvironment,\n  call: EnvironmentCall,\n): Replacement {\n  const args = Array.isArray(call.node.arguments) ? call.node.arguments : [];\n  if (args.length !== 1 || !isAstNode(args[0]) || args[0].type === \"SpreadElement\") {\n    throw transformError(id, `${call.kind}() requires exactly one static argument`);\n  }\n\n  let replacement: string;\n  if (call.kind === \"createIsomorphicFn\") {\n    replacement = selectIsomorphicImplementation(code, id, environment, args[0]);\n  } else {\n    const expected = call.kind === \"createServerOnlyFn\" ? \"server\" : \"client\";\n    replacement =\n      environment === expected\n        ? readNode(code, args[0])\n        : `(0, ${readNode(code, call.node.callee as AstNode)})(undefined, ${JSON.stringify(environment)})`;\n  }\n\n  return {\n    start: call.node.start,\n    end: call.node.end,\n    code: `(${replacement})`,\n  };\n}\n\nfunction selectIsomorphicImplementation(\n  code: string,\n  id: string,\n  environment: FarmEnvironment,\n  optionsNode: AstNode,\n): string {\n  if (optionsNode.type !== \"ObjectExpression\") {\n    throw transformError(id, \"createIsomorphicFn() requires an inline options object\");\n  }\n\n  const properties = Array.isArray(optionsNode.properties) ? optionsNode.properties : [];\n  if (properties.some((property) => isAstNode(property) && property.type === \"SpreadElement\")) {\n    throw transformError(id, \"createIsomorphicFn() does not support spread properties\");\n  }\n\n  let selectedProperty: AstNode | undefined;\n  for (const property of properties) {\n    if (!isAstNode(property) || property.type !== \"Property\" || property.computed === true) {\n      continue;\n    }\n    const key = readPropertyName(property.key);\n    if (key === environment) selectedProperty = property;\n  }\n\n  if (!selectedProperty || !isAstNode(selectedProperty.value)) {\n    throw transformError(id, `createIsomorphicFn() requires a ${environment} implementation`);\n  }\n  if (selectedProperty.kind !== undefined && selectedProperty.kind !== \"init\") {\n    throw transformError(id, \"createIsomorphicFn() does not support getters or setters\");\n  }\n\n  return selectedProperty.method === true\n    ? renderObjectMethod(code, id, selectedProperty.value)\n    : readNode(code, selectedProperty.value);\n}\n\nfunction renderObjectMethod(code: string, id: string, functionNode: AstNode): string {\n  if (!isAstNode(functionNode.body) || !Array.isArray(functionNode.params)) {\n    throw transformError(id, \"createIsomorphicFn() received an unsupported method\");\n  }\n\n  const params = functionNode.params.map((param) => {\n    if (!isAstNode(param)) {\n      throw transformError(id, \"createIsomorphicFn() received an unsupported parameter\");\n    }\n    return readNode(code, param);\n  });\n  const asyncPrefix = functionNode.async === true ? \"async \" : \"\";\n  const generatorMarker = functionNode.generator === true ? \"*\" : \"\";\n  return `${asyncPrefix}function${generatorMarker}(${params.join(\", \")}) ${readNode(code, functionNode.body)}`;\n}\n\nfunction applyReplacements(code: string, replacements: Replacement[]): string {\n  let output = code;\n  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n    output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n  }\n  return output;\n}\n\nfunction walkAst(\n  node: AstNode,\n  visit: (node: AstNode, ancestors: readonly AstNode[]) => void,\n  ancestors: readonly AstNode[] = [],\n) {\n  visit(node, ancestors);\n  const childAncestors = [...ancestors, node];\n\n  for (const [key, value] of Object.entries(node)) {\n    if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n    if (isAstNode(value)) {\n      walkAst(value, visit, childAncestors);\n    } else if (Array.isArray(value)) {\n      for (const item of value) {\n        if (isAstNode(item)) walkAst(item, visit, childAncestors);\n      }\n    }\n  }\n}\n\nfunction isNameShadowed(name: string, ancestors: readonly AstNode[]): boolean {\n  for (const [index, ancestor] of ancestors.entries()) {\n    if (isFunctionNode(ancestor)) {\n      const params = Array.isArray(ancestor.params) ? ancestor.params : [];\n      if (params.some((param) => patternContainsName(param, name))) return true;\n      if (patternContainsName(ancestor.id, name)) return true;\n      if (\n        isAstNode(ancestor.body) &&\n        ancestors.slice(index + 1).includes(ancestor.body) &&\n        functionBodyDeclaresVarName(ancestor.body, name)\n      ) {\n        return true;\n      }\n    }\n\n    if (ancestor.type === \"CatchClause\" && patternContainsName(ancestor.param, name)) {\n      return true;\n    }\n\n    if (\n      (ancestor.type === \"BlockStatement\" || ancestor.type === \"StaticBlock\") &&\n      blockDeclaresName(ancestor, name)\n    ) {\n      return true;\n    }\n\n    if (loopDeclaresName(ancestor, name)) return true;\n\n    if (\n      ancestor.type === \"SwitchStatement\" &&\n      ancestors.slice(index + 1).some((candidate) => candidate.type === \"SwitchCase\") &&\n      switchDeclaresName(ancestor, name)\n    ) {\n      return true;\n    }\n\n    if (\n      ancestor.type === \"ClassExpression\" &&\n      patternContainsName(ancestor.id, name) &&\n      ancestors.slice(index + 1).some((candidate) => candidate.type === \"ClassBody\")\n    ) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction functionBodyDeclaresVarName(body: AstNode, name: string): boolean {\n  if (body.type === \"VariableDeclaration\" && body.kind === \"var\") {\n    const declarations = Array.isArray(body.declarations) ? body.declarations : [];\n    if (\n      declarations.some(\n        (declaration) => isAstNode(declaration) && patternContainsName(declaration.id, name),\n      )\n    ) {\n      return true;\n    }\n  }\n\n  for (const [key, value] of Object.entries(body)) {\n    if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n    if (isAstNode(value)) {\n      if (isNestedVarScope(value)) continue;\n      if (functionBodyDeclaresVarName(value, name)) return true;\n    } else if (Array.isArray(value)) {\n      for (const item of value) {\n        if (!isAstNode(item) || isNestedVarScope(item)) continue;\n        if (functionBodyDeclaresVarName(item, name)) return true;\n      }\n    }\n  }\n\n  return false;\n}\n\nfunction isNestedVarScope(node: AstNode): boolean {\n  return (\n    isFunctionNode(node) || node.type === \"ClassDeclaration\" || node.type === \"ClassExpression\"\n  );\n}\n\nfunction loopDeclaresName(node: AstNode, name: string): boolean {\n  const declaration =\n    node.type === \"ForStatement\"\n      ? node.init\n      : node.type === \"ForInStatement\" || node.type === \"ForOfStatement\"\n        ? node.left\n        : undefined;\n  if (!isAstNode(declaration) || declaration.type !== \"VariableDeclaration\") return false;\n\n  const declarations = Array.isArray(declaration.declarations) ? declaration.declarations : [];\n  return declarations.some((item) => isAstNode(item) && patternContainsName(item.id, name));\n}\n\nfunction switchDeclaresName(node: AstNode, name: string): boolean {\n  const cases = Array.isArray(node.cases) ? node.cases : [];\n  return cases.some((switchCase) => {\n    if (!isAstNode(switchCase) || !Array.isArray(switchCase.consequent)) return false;\n    return switchCase.consequent.some((statement) => {\n      if (!isAstNode(statement)) return false;\n      if (\n        (statement.type === \"FunctionDeclaration\" || statement.type === \"ClassDeclaration\") &&\n        patternContainsName(statement.id, name)\n      ) {\n        return true;\n      }\n      if (statement.type !== \"VariableDeclaration\" || statement.kind === \"var\") return false;\n      const declarations = Array.isArray(statement.declarations) ? statement.declarations : [];\n      return declarations.some(\n        (declaration) => isAstNode(declaration) && patternContainsName(declaration.id, name),\n      );\n    });\n  });\n}\n\nfunction blockDeclaresName(block: AstNode, name: string): boolean {\n  const statements = Array.isArray(block.body) ? block.body : [];\n  for (const statement of statements) {\n    if (!isAstNode(statement)) continue;\n    if (\n      (statement.type === \"FunctionDeclaration\" || statement.type === \"ClassDeclaration\") &&\n      patternContainsName(statement.id, name)\n    ) {\n      return true;\n    }\n    if (statement.type !== \"VariableDeclaration\" || !Array.isArray(statement.declarations)) {\n      continue;\n    }\n    if (\n      statement.declarations.some(\n        (declaration) => isAstNode(declaration) && patternContainsName(declaration.id, name),\n      )\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction patternContainsName(value: unknown, name: string): boolean {\n  if (!isAstNode(value)) return false;\n  if (value.type === \"Identifier\") return value.name === name;\n\n  if (value.type === \"RestElement\") return patternContainsName(value.argument, name);\n  if (value.type === \"AssignmentPattern\") return patternContainsName(value.left, name);\n  if (value.type === \"Property\") return patternContainsName(value.value, name);\n\n  const elements = Array.isArray(value.elements)\n    ? value.elements\n    : Array.isArray(value.properties)\n      ? value.properties\n      : [];\n  return elements.some((element) => patternContainsName(element, name));\n}\n\nfunction isFunctionNode(node: AstNode): boolean {\n  return (\n    node.type === \"FunctionDeclaration\" ||\n    node.type === \"FunctionExpression\" ||\n    node.type === \"ArrowFunctionExpression\"\n  );\n}\n\nfunction readPropertyName(value: unknown): string | undefined {\n  if (!isAstNode(value)) return undefined;\n  if (value.type === \"Identifier\" && typeof value.name === \"string\") return value.name;\n  if (value.type === \"Literal\" && typeof value.value === \"string\") return value.value;\n  return undefined;\n}\n\nfunction readNode(code: string, node: AstNode): string {\n  return code.slice(node.start, node.end);\n}\n\nfunction isAstNode(value: unknown): value is AstNode {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as AstNode).type === \"string\" &&\n    typeof (value as AstNode).start === \"number\" &&\n    typeof (value as AstNode).end === \"number\"\n  );\n}\n\nfunction isEnvironmentFunctionKind(value: unknown): value is EnvironmentFunctionKind {\n  return typeof value === \"string\" && ENVIRONMENT_FUNCTIONS.has(value as EnvironmentFunctionKind);\n}\n\nfunction containsEnvironmentFunction(code: string): boolean {\n  return Array.from(ENVIRONMENT_FUNCTIONS).some((name) => code.includes(name));\n}\n\nfunction isTransformableModule(id: string): boolean {\n  const cleanId = id.split(\"?\", 1)[0];\n  return MODULE_EXTENSION_RE.test(cleanId) && !/\\.d\\.[cm]?ts$/.test(cleanId);\n}\n\nfunction transformError(id: string, message: string): Error {\n  return new Error(`[Farm environment functions] ${message} in ${id.split(\"?\", 1)[0]}`);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nexport type AfterCallback = () => void | Promise<void>;\n\n/** Runtime hooks supplied by a deployment adapter. */\nexport interface FarmAfterPlatformContext {\n  /** Keep a serverless invocation alive until the scheduled work settles. */\n  waitUntil?: (promise: Promise<void>) => void;\n  /** Register a callback that runs once the response has finished. */\n  onResponseFinished?: (callback: () => void) => void;\n}\n\ninterface AfterTask {\n  result: Promise<void>;\n  start: () => void;\n}\n\ninterface AfterRequestState {\n  completion: Promise<void>;\n  finishResponse: () => void;\n  phase: \"open\" | \"running\" | \"closed\";\n  reportError: (error: unknown) => void;\n  tasks: AfterTask[];\n}\n\nconst AFTER_STORAGE = Symbol.for(\"@farm.js/core/after-storage\");\n\nfunction getAfterStorage(): AsyncLocalStorage<AfterRequestState> {\n  const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n  const existing = runtime[AFTER_STORAGE];\n  if (existing instanceof AsyncLocalStorage) {\n    return existing as AsyncLocalStorage<AfterRequestState>;\n  }\n\n  const storage = new AsyncLocalStorage<AfterRequestState>();\n  runtime[AFTER_STORAGE] = storage;\n  return storage;\n}\n\nconst afterStorage = getAfterStorage();\n\nfunction defaultAfterErrorReporter(error: unknown): void {\n  console.error(\"[Farm.js] after() callback failed:\", error);\n}\n\nfunction reportAfterError(state: AfterRequestState, error: unknown): void {\n  try {\n    state.reportError(error);\n  } catch {\n    // Error reporting must never interrupt the remaining post-response work.\n  }\n}\n\nfunction createAfterRequestState(\n  reportError: (error: unknown) => void = defaultAfterErrorReporter,\n): AfterRequestState {\n  let resolveResponseFinished!: () => void;\n  let responseFinished = false;\n  const responseFinishedPromise = new Promise<void>((resolve) => {\n    resolveResponseFinished = resolve;\n  });\n\n  const state: AfterRequestState = {\n    completion: Promise.resolve(),\n    finishResponse: () => {\n      if (responseFinished) return;\n      responseFinished = true;\n      resolveResponseFinished();\n    },\n    phase: \"open\",\n    reportError,\n    tasks: [],\n  };\n\n  state.completion = responseFinishedPromise.then(() =>\n    afterStorage.run(state, async () => {\n      state.phase = \"running\";\n\n      for (let index = 0; index < state.tasks.length; index++) {\n        const task = state.tasks[index];\n        task.start();\n        try {\n          await task.result;\n        } catch (error) {\n          reportAfterError(state, error);\n        }\n      }\n\n      state.phase = \"closed\";\n    }),\n  );\n\n  return state;\n}\n\nfunction registerPlatformLifetime(\n  state: AfterRequestState,\n  context: FarmAfterPlatformContext | undefined,\n): void {\n  if (!context?.waitUntil) return;\n\n  try {\n    context.waitUntil(state.completion);\n  } catch (error) {\n    reportAfterError(state, error);\n  }\n}\n\nfunction registerResponseFinishedHook(\n  state: AfterRequestState,\n  context: FarmAfterPlatformContext | undefined,\n): boolean {\n  if (!context?.onResponseFinished) return false;\n\n  try {\n    context.onResponseFinished(state.finishResponse);\n    return true;\n  } catch (error) {\n    reportAfterError(state, error);\n    return false;\n  }\n}\n\nfunction finishSoon(state: AfterRequestState): void {\n  setTimeout(state.finishResponse, 0);\n}\n\nfunction wrapResponseBody(\n  response: Response,\n  request: Request,\n  state: AfterRequestState,\n): Response {\n  if (\n    request.method === \"HEAD\" ||\n    response.status < 200 ||\n    response.status > 599 ||\n    !response.body ||\n    response.bodyUsed ||\n    response.body.locked\n  ) {\n    finishSoon(state);\n    return response;\n  }\n\n  const reader = response.body.getReader();\n  let released = false;\n  const releaseReader = () => {\n    if (released) return;\n    released = true;\n    reader.releaseLock();\n  };\n\n  const body = new ReadableStream<Uint8Array>({\n    async pull(controller) {\n      try {\n        const chunk = await reader.read();\n        if (chunk.done) {\n          releaseReader();\n          controller.close();\n          finishSoon(state);\n          return;\n        }\n        controller.enqueue(chunk.value);\n      } catch (error) {\n        releaseReader();\n        controller.error(error);\n        finishSoon(state);\n      }\n    },\n    cancel(reason) {\n      try {\n        // Preserve the caller's cleanup promise, but response completion must\n        // not depend on whether producer-owned cancellation ever settles.\n        return reader.cancel(reason);\n      } finally {\n        releaseReader();\n        finishSoon(state);\n      }\n    },\n  });\n\n  return new Response(body, {\n    headers: response.headers,\n    status: response.status,\n    statusText: response.statusText,\n  });\n}\n\n/**\n * Schedule non-blocking work for after the current response finishes.\n *\n * Callbacks run in registration order. A callback failure is reported without\n * changing the response or preventing later callbacks from running.\n */\nexport function after(callback: AfterCallback): void {\n  if (typeof callback !== \"function\") {\n    throw new TypeError(\"after() expects a callback function.\");\n  }\n\n  const state = afterStorage.getStore();\n  if (!state) {\n    throw new Error(\"after() can only be used while Farm is handling a server request.\");\n  }\n  if (state.phase === \"closed\") {\n    throw new Error(\"after() cannot schedule work after the request lifecycle has completed.\");\n  }\n\n  let start!: () => void;\n  const ready = new Promise<void>((resolve) => {\n    start = resolve;\n  });\n\n  // Registering the continuation here preserves every request AsyncLocalStorage\n  // context that is active at the after() call site.\n  const result = ready.then(callback);\n  state.tasks.push({ result, start });\n}\n\n/** @internal Run a Web Request handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterRequest(\n  request: Request,\n  handler: () => Response | Promise<Response>,\n  context?: FarmAfterPlatformContext,\n): Promise<Response> {\n  if (afterStorage.getStore()) {\n    return await handler();\n  }\n\n  const state = createAfterRequestState();\n  registerPlatformLifetime(state, context);\n  const hasResponseHook = registerResponseFinishedHook(state, context);\n\n  try {\n    const response = await afterStorage.run(state, handler);\n    return hasResponseHook ? response : wrapResponseBody(response, request, state);\n  } catch (error) {\n    // The handler threw, so there is no successful response for a\n    // response-finished hook to fire on. Run the after-lifecycle now regardless\n    // of the hook; otherwise a spec-compliant adapter (whose hook only fires on\n    // a real response) never runs the registered after() callbacks and\n    // waitUntil(state.completion) hangs forever. finishResponse is idempotent,\n    // so a later hook firing (e.g. a Node error response's close) is a no-op.\n    finishSoon(state);\n    throw error;\n  }\n}\n\n/** @internal Run a Node response handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterNodeResponse<T>(\n  response: ServerResponse,\n  handler: () => T | Promise<T>,\n  context?: Pick<FarmAfterPlatformContext, \"waitUntil\">,\n): Promise<T> {\n  if (afterStorage.getStore()) {\n    return await handler();\n  }\n\n  const state = createAfterRequestState();\n  let finished = false;\n  const finish = () => {\n    if (finished) return;\n    finished = true;\n    response.off(\"finish\", finish);\n    response.off(\"close\", finish);\n    state.finishResponse();\n  };\n\n  response.once(\"finish\", finish);\n  response.once(\"close\", finish);\n  if (response.writableEnded) finishSoon(state);\n  registerPlatformLifetime(state, context);\n\n  return await afterStorage.run(state, handler);\n}\n\n/** @internal Add Farm's post-response lifecycle to a Node middleware. */\nexport function _withAfterNodeMiddleware(\n  handler: (\n    request: IncomingMessage,\n    response: ServerResponse,\n    next: (error?: unknown) => void,\n  ) => void | Promise<void>,\n): (\n  request: IncomingMessage,\n  response: ServerResponse,\n  next: (error?: unknown) => void,\n) => Promise<void> {\n  return async (request, response, next) => {\n    await _runWithAfterNodeResponse(response, () => handler(request, response, next));\n  };\n}\n","/** Browser-safe bridge: neither handlers nor Node.js imports cross this boundary. */\nexport interface APIRequestRuntime {\n  basePath: string;\n  dispatch(request: Request): Promise<Response>;\n}\n\nconst API_RUNTIME_RESOLVER = Symbol.for(\"farm.apiRequestRuntimeResolver\");\ntype RuntimeGlobal = typeof globalThis & {\n  [API_RUNTIME_RESOLVER]?: () => APIRequestRuntime | undefined;\n};\n\nexport function setAPIRequestRuntimeResolver(resolver: () => APIRequestRuntime | undefined): void {\n  (globalThis as RuntimeGlobal)[API_RUNTIME_RESOLVER] = resolver;\n}\n\nexport function resolveAPIRequestRuntime(): APIRequestRuntime | undefined {\n  return (globalThis as RuntimeGlobal)[API_RUNTIME_RESOLVER]?.();\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { setAPIRequestRuntimeResolver, type APIRequestRuntime } from \"./server-client-bridge\";\n\nconst API_RUNTIME_STORAGE = Symbol.for(\"@farm.js/core/api-request-storage\");\nconst runtimeGlobal = globalThis as typeof globalThis & {\n  [API_RUNTIME_STORAGE]?: AsyncLocalStorage<APIRequestRuntime>;\n};\nconst storage = (runtimeGlobal[API_RUNTIME_STORAGE] ??= new AsyncLocalStorage<APIRequestRuntime>());\nsetAPIRequestRuntimeResolver(() => storage.getStore());\n\n/** Bind the owning app's live route dispatcher, never a process-wide route table. */\nexport function _runWithAPIRequestRuntime<T>(runtime: APIRequestRuntime, run: () => T): T {\n  return storage.run(runtime, run);\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\n\ninterface DottedPathRouteMatcher {\n  matchRoute(pathname: string): { route: unknown } | null | undefined;\n  matchMetadataRoute(pathname: string): object | null;\n  matchMetadataImage(pathname: string): object | null;\n}\n\n/**\n * Decide whether the dev server should hand a dotted request path to the\n * static pipeline instead of Farm's renderer. Dotted paths are usually asset\n * requests, but they are also how page routes with dotted segments and\n * application metadata routes (/manifest.webmanifest, /sitemap.xml,\n * /robots.txt, generated metadata images) are addressed, so the router is\n * only bypassed when nothing in the app matches the pathname or a real file\n * shadows it.\n */\nexport function shouldBypassFarmRouterForDottedPath(\n  pathname: string,\n  routeManager: DottedPathRouteMatcher | null | undefined,\n  baseDirs: Array<string | false | undefined>,\n): boolean {\n  if (!pathname.includes(\".\") || pathname.endsWith(\".html\")) return false;\n  const matchesAppRoute = Boolean(\n    routeManager?.matchRoute(pathname)?.route ||\n    routeManager?.matchMetadataRoute(pathname) ||\n    routeManager?.matchMetadataImage(pathname),\n  );\n  return !matchesAppRoute || devServableFileExists(pathname, baseDirs);\n}\n\n/**\n * Route segments may legitimately contain dots (e.g. /kinfish/farm.js), so a\n * dot alone cannot classify a dev request as a static asset. A dotted path is\n * only treated as an asset when it maps to a real file under one of the\n * servable base dirs (project root, public dir), matching the\n * filesystem-first behavior of production hosting.\n */\nexport function devServableFileExists(\n  pathname: string,\n  baseDirs: Array<string | false | undefined>,\n): boolean {\n  let decodedPathname: string;\n  try {\n    decodedPathname = decodeURIComponent(pathname);\n  } catch {\n    return false;\n  }\n  const relativePathname = decodedPathname.replace(/^\\/+/, \"\");\n  if (!relativePathname) return false;\n  for (const baseDir of baseDirs) {\n    if (typeof baseDir !== \"string\" || baseDir.length === 0) continue;\n    const resolvedBase = path.resolve(baseDir);\n    const candidate = path.resolve(resolvedBase, relativePathname);\n    if (!candidate.startsWith(resolvedBase + path.sep)) continue;\n    try {\n      if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\n        return true;\n      }\n    } catch {\n      // Ignore filesystem errors and keep checking other base dirs.\n    }\n  }\n  return false;\n}\n","const SERVER_FN_FACTORIES = [\"createServerQuery\", \"createServerFn\"] as const;\n\nconst FARM_CORE_IMPORT_RE =\n  /import\\s*(?!type\\b)(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*([\"'])@farm\\.js\\/core(?:\\/[\\w./-]+)?\\2/g;\n\nexport type ServerFnBoundaryViolation = {\n  factory: (typeof SERVER_FN_FACTORIES)[number];\n};\n\n/**\n * Detect a module that defines a Farm server function (createServerQuery /\n * createServerFn) while being compiled for the client environment. Without\n * the server-function transform (@farm.js/plugin/rsc with\n * experimental.serverActions enabled) there is no client stub: the server\n * handler and its dependency graph would be bundled into the browser and\n * executed there, surfacing as confusing Vite externalization errors for\n * Node built-ins (#408).\n */\nexport function findClientServerFnViolation(\n  code: string,\n  id: string,\n): ServerFnBoundaryViolation | null {\n  if (id.startsWith(\"\\0\") || id.startsWith(\"virtual:\") || id.includes(\"node_modules\")) return null;\n  // Markdown modules never execute import statements: matched text is\n  // documentation (fenced code examples), not code, before and after the\n  // markdown transform (fences compile to string content).\n  if (/\\.(md|mdx)(\\?|$)/.test(id)) return null;\n  if (!code.includes(\"@farm.js/core\")) return null;\n\n  for (const match of code.matchAll(FARM_CORE_IMPORT_RE)) {\n    const specifiers = match[1];\n    for (const factory of SERVER_FN_FACTORIES) {\n      if (!new RegExp(`(?:^|[\\\\s{,])${factory}(?:[\\\\s},]|$)`).test(specifiers)) continue;\n      // Only a call site makes the module a server-function definition; a\n      // type-only or re-exported symbol never executes a handler.\n      if (new RegExp(`(?<![\\\\w$.])${factory}\\\\s*(?:<[^>]*>)?\\\\s*\\\\(`).test(code)) {\n        return { factory };\n      }\n    }\n  }\n  return null;\n}\n\nexport function formatServerFnBoundaryError(\n  violation: ServerFnBoundaryViolation,\n  id: string,\n): string {\n  return [\n    `${violation.factory} handlers run only on the server, but ${id} is being bundled into the client.`,\n    `Importing a ${violation.factory} module from client code executes the server handler (and its Node-only imports) in the browser.`,\n    `Either 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 keep the query on the server: call it from server components, or expose an API route and use createAPIClient from the client.`,\n  ].join(\"\\n\");\n}\n","/**\n * Diagnostics for server-only access in modules compiled for the client.\n *\n * A module entering the client graph runs in the browser. Module-scope reads\n * of non-public process.env values evaluate to undefined there and broke\n * layout hydration in #560, and node: builtin imports are silently stubbed\n * with empty objects by farm:browser-external-stub. Both deserve a clear\n * build-time warning naming the module instead of a runtime mystery (#1065).\n */\n\ntype EstreeNode = { type: string; [key: string]: unknown };\n\nconst FUNCTION_BODY_TYPES = new Set([\n  \"FunctionDeclaration\",\n  \"FunctionExpression\",\n  \"ArrowFunctionExpression\",\n]);\n\nexport function shouldInspectClientBoundary(id: string, code: string): boolean {\n  if (id.startsWith(\"\\0\") || id.startsWith(\"virtual:\") || id.includes(\"node_modules\")) return false;\n  return code.includes(\"process.env\") || code.includes(\"node:\");\n}\n\nexport interface ClientBoundaryFindings {\n  /** Non-public process.env keys read at module scope. */\n  envKeys: string[];\n  /**\n   * Declared-public keys read via process.env at module scope. The value is\n   * still undefined in the browser — only publicEnv is populated there — so\n   * these get their own warning pointing at the supported accessor.\n   */\n  publicEnvKeys: string[];\n  /** node: builtin specifiers imported into the module. */\n  builtinImports: string[];\n}\n\n/**\n * One walk over the module AST for both diagnostics.\n *\n * Reads and dynamic imports inside function bodies are skipped: they may be\n * server-gated at runtime — a lazy `await import(\"node:fs\")` behind a server\n * check is the recommended escape hatch — and flagging them would drown the\n * signal in noise. Static import/export-from declarations always execute at\n * module scope, so they are always flagged.\n */\nexport function analyzeClientBoundary(\n  program: EstreeNode,\n  publicKeys: ReadonlySet<string>,\n): ClientBoundaryFindings {\n  const envKeys = new Set<string>();\n  const publicEnvKeys = new Set<string>();\n  const builtinImports = new Set<string>();\n\n  const visit = (node: unknown, inFunction: boolean): void => {\n    if (!node || typeof node !== \"object\") return;\n    if (Array.isArray(node)) {\n      for (const entry of node) visit(entry, inFunction);\n      return;\n    }\n    const estree = node as EstreeNode;\n    if (typeof estree.type !== \"string\") return;\n\n    if (!inFunction) {\n      const builtin = readNodeBuiltinSource(estree);\n      if (builtin !== undefined) builtinImports.add(builtin);\n\n      const key = readProcessEnvKey(estree);\n      if (key !== undefined) {\n        if (key !== \"NODE_ENV\") {\n          (publicKeys.has(key) ? publicEnvKeys : envKeys).add(key);\n        }\n        return;\n      }\n    }\n\n    // Params and defaults evaluate at call time along with the body.\n    const nextInFunction = inFunction || FUNCTION_BODY_TYPES.has(estree.type);\n    for (const [childKey, value] of Object.entries(estree)) {\n      if (childKey === \"type\") continue;\n      visit(value, nextInFunction);\n    }\n  };\n\n  visit((program as { body?: unknown }).body, false);\n  return {\n    envKeys: [...envKeys],\n    publicEnvKeys: [...publicEnvKeys],\n    builtinImports: [...builtinImports],\n  };\n}\n\nfunction readNodeBuiltinSource(node: EstreeNode): string | undefined {\n  if (\n    node.type === \"ImportDeclaration\" ||\n    node.type === \"ExportNamedDeclaration\" ||\n    node.type === \"ExportAllDeclaration\" ||\n    node.type === \"ImportExpression\"\n  ) {\n    const value = (node.source as { value?: unknown } | null | undefined)?.value;\n    return typeof value === \"string\" && value.startsWith(\"node:\") ? value : undefined;\n  }\n  if (node.type === \"CallExpression\") {\n    const callee = node.callee as EstreeNode | undefined;\n    if (callee?.type === \"Identifier\" && (callee as { name?: string }).name === \"require\") {\n      const arg = (node.arguments as EstreeNode[] | undefined)?.[0];\n      const value = arg?.type === \"Literal\" ? (arg as { value?: unknown }).value : undefined;\n      return typeof value === \"string\" && value.startsWith(\"node:\") ? value : undefined;\n    }\n  }\n  return undefined;\n}\n\nfunction readProcessEnvKey(node: EstreeNode): string | undefined {\n  if (node.type !== \"MemberExpression\") return undefined;\n  const object = node.object as EstreeNode | undefined;\n  if (\n    !object ||\n    object.type !== \"MemberExpression\" ||\n    (object.object as EstreeNode | undefined)?.type !== \"Identifier\" ||\n    (object.object as { name?: string }).name !== \"process\" ||\n    (object.property as { name?: string })?.name !== \"env\"\n  ) {\n    return undefined;\n  }\n\n  const property = node.property as EstreeNode | undefined;\n  if (!property) return undefined;\n  if (!node.computed && property.type === \"Identifier\") {\n    return (property as { name?: string }).name;\n  }\n  if (node.computed && property.type === \"Literal\") {\n    const value = (property as { value?: unknown }).value;\n    return typeof value === \"string\" ? value : undefined;\n  }\n  return undefined;\n}\n\nexport function formatClientBoundaryWarning(id: string, findings: ClientBoundaryFindings): string {\n  const { envKeys, publicEnvKeys, builtinImports } = findings;\n  const lines = [`${id} is compiled for the client but uses server-only APIs:`];\n  if (envKeys.length > 0) {\n    lines.push(\n      `- module-scope read of process.env.${envKeys.join(\", process.env.\")} — undefined in the browser. Move the read behind a server boundary, or expose it through env.public in farm.config.ts.`,\n    );\n  }\n  if (publicEnvKeys.length > 0) {\n    lines.push(\n      `- module-scope read of process.env.${publicEnvKeys.join(\", process.env.\")} — process.env is not populated in the browser even for public keys. Read it through publicEnv from \"@farm.js/core/env\".`,\n    );\n  }\n  if (builtinImports.length > 0) {\n    lines.push(\n      `- import of ${builtinImports.join(\", \")} — stubbed with an empty object in the browser. Move the import into server-only code.`,\n    );\n  }\n  return lines.join(\"\\n\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { imageSize } from \"image-size\";\nimport type { Plugin } from \"vite\";\n\nconst FARM_IMAGE_ID_PREFIX = \"\\0farm:image:\";\nconst STATIC_IMAGE_RE = /\\.(?:avif|gif|jpe?g|png|webp)$/i;\nconst SCRIPT_IMPORTER_RE = /\\.(?:[cm]?[jt]sx?|mdx?)$/i;\n\nexport function farmImageImportsPlugin(): Plugin {\n  return {\n    name: \"farm-image-imports\",\n    enforce: \"pre\",\n\n    async resolveId(source, importer, options) {\n      if (\n        !importer ||\n        source.includes(\"?\") ||\n        !STATIC_IMAGE_RE.test(source) ||\n        !SCRIPT_IMPORTER_RE.test(importer.split(\"?\", 1)[0])\n      ) {\n        return null;\n      }\n\n      const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n      if (!resolved || resolved.external) return null;\n\n      return `${FARM_IMAGE_ID_PREFIX}${encodeURIComponent(resolved.id.split(\"?\", 1)[0])}`;\n    },\n\n    async load(id) {\n      if (!id.startsWith(FARM_IMAGE_ID_PREFIX)) return null;\n\n      const filePath = decodeURIComponent(id.slice(FARM_IMAGE_ID_PREFIX.length));\n      const assetRequest = `${filePath.replace(/\\\\/g, \"/\")}?url`;\n      return createStaticImageModule(filePath, `import src from ${JSON.stringify(assetRequest)};`);\n    },\n\n    async transform(code, id) {\n      const filePath = id.split(\"?\", 1)[0];\n      if (id.includes(\"?\") || !STATIC_IMAGE_RE.test(filePath)) return null;\n\n      const defaultExport = code.match(/^\\s*export\\s+default\\s+(.+?);?\\s*$/s)?.[1];\n      if (!defaultExport) return null;\n      return createStaticImageModule(filePath, `const src = ${defaultExport};`);\n    },\n  };\n}\n\nasync function createStaticImageModule(\n  filePath: string,\n  sourceDeclaration: string,\n): Promise<string> {\n  const bytes = await readFile(filePath);\n  const dimensions = imageSize(bytes);\n  if (!dimensions.width || !dimensions.height) {\n    throw new Error(`Could not determine image dimensions for ${filePath}`);\n  }\n\n  const blurDataURL = await createBlurDataURL(bytes);\n  return [\n    sourceDeclaration,\n    `const image = ${JSON.stringify({\n      width: dimensions.width,\n      height: dimensions.height,\n      ...(blurDataURL ? { blurDataURL } : {}),\n    })};`,\n    \"image.src = src;\",\n    \"export { src };\",\n    \"export const width = image.width;\",\n    \"export const height = image.height;\",\n    \"export const blurDataURL = image.blurDataURL;\",\n    \"export default image;\",\n  ].join(\"\\n\");\n}\n\nasync function createBlurDataURL(bytes: Buffer): Promise<string | undefined> {\n  try {\n    const { default: sharp } = await import(\"sharp\");\n    const placeholder = await sharp(bytes)\n      .rotate()\n      .resize({ width: 8, height: 8, fit: \"inside\", withoutEnlargement: true })\n      .webp({ quality: 35 })\n      .toBuffer();\n    return `data:image/webp;base64,${placeholder.toString(\"base64\")}`;\n  } catch {\n    return undefined;\n  }\n}\n\nexport function isFarmStaticImageFile(filePath: string): boolean {\n  return STATIC_IMAGE_RE.test(path.extname(filePath));\n}\n","export type FarmFontDisplay = \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n\nexport interface FarmFontSource {\n  /** Local file path or remote URL, depending on the loader. */\n  path: string;\n  /** A fixed weight (`400`) or variable range (`100 900`). */\n  weight?: number | string;\n  /** Font style for this source. */\n  style?: string;\n  /** Optional CSS unicode-range descriptor. */\n  unicodeRange?: string;\n}\n\nexport interface FarmFontOptions {\n  /** CSS font-family name. */\n  family: string;\n  /** A fixed weight (`400`) or variable range (`100 900`). */\n  weight?: number | string;\n  /** Font style. @default \"normal\" */\n  style?: string;\n  /** Browser loading behavior. @default \"swap\" */\n  display?: FarmFontDisplay;\n  /** CSS custom property populated by `variable`, for example `--font-sans`. */\n  variable?: `--${string}`;\n  /** Fallback family names appended to the generated stack. */\n  fallback?: string[];\n  /** Emit font preload hints. @default true */\n  preload?: boolean;\n}\n\nexport interface LocalFontOptions extends FarmFontOptions {\n  /**\n   * A file relative to this module, a package font specifier, or explicit\n   * sources for a multi-weight family.\n   */\n  src: string | FarmFontSource[];\n}\n\nexport interface RemoteFontSource extends FarmFontSource {\n  /** Optional integrity value for this source. Overrides the family-level value. */\n  integrity?: string;\n}\n\nexport interface RemoteFontOptions extends FarmFontOptions {\n  /** HTTPS font URL, or explicit remote sources for a multi-weight family. */\n  src: string | RemoteFontSource[];\n  /** Download and fingerprint the font during the build, or retain its URL. */\n  strategy?: \"self-host\" | \"external\";\n  /** Optional Subresource Integrity value checked while self-hosting. */\n  integrity?: string;\n}\n\nexport interface FarmFont {\n  /** Generated class that applies the font family and fallback stack. */\n  className: string;\n  /** Generated class that defines the configured CSS custom property. */\n  variable: string;\n  /** Inline-style equivalent of the generated family. */\n  style: Readonly<{\n    fontFamily: string;\n    fontStyle?: string;\n    fontWeight?: number | string;\n  }>;\n  /** Compiled resources that should be preloaded when this font is selected. */\n  preloads: readonly Readonly<{\n    href: string;\n    type: string;\n  }>[];\n}\n\n/** Semantic font roles inherited by framework-owned surfaces such as Farm Docs. */\nexport interface FarmLayoutFonts {\n  /** Default text and prose font. */\n  body?: FarmFont;\n  /** Code, keyboard input, and other technical UI font. */\n  code?: FarmFont;\n}\n\nexport interface FarmLayoutFontModule {\n  fonts?: FarmLayoutFonts;\n}\n\n/**\n * Define the semantic fonts exported by a layout.\n *\n * Layouts are resolved from the root toward the requested route. A nearer\n * layout overrides only the roles it defines, so it can replace `body` while\n * continuing to inherit `code` from a parent layout.\n */\nexport function defineLayoutFonts<const T extends FarmLayoutFonts>(fonts: T): T {\n  return fonts;\n}\n\n/** Resolve semantic font roles from root layout to nearest layout. */\nexport function resolveFarmLayoutFonts(\n  layouts: readonly FarmLayoutFontModule[],\n): FarmLayoutFonts | undefined {\n  let resolved: FarmLayoutFonts | undefined;\n\n  for (const layout of layouts) {\n    if (!layout.fonts) continue;\n    resolved = { ...resolved, ...layout.fonts };\n  }\n\n  return resolved;\n}\n\nfunction fontCompilerError(loader: string): never {\n  throw new Error(\n    `[Farm fonts] ${loader}() must be called at module scope with static options and compiled by the Farm Vite plugin.`,\n  );\n}\n\n/**\n * Compile local font files into hashed application assets and generated CSS.\n * The call is removed at build time and adds no font-loader runtime code.\n */\nexport function localFont(_options: LocalFontOptions): FarmFont {\n  return fontCompilerError(\"localFont\");\n}\n\n/**\n * Compile a remote font into a self-hosted application asset by default.\n * Use `strategy: \"external\"` only when the browser should retain the remote URL.\n */\nexport function remoteFont(_options: RemoteFontOptions): FarmFont {\n  return fontCompilerError(\"remoteFont\");\n}\n","import type {\n  FarmImageFormat,\n  FarmImageLocalPattern,\n  FarmImageRemotePattern,\n  ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { matchesFarmIfNoneMatch } from \"./server-http\";\n\nexport interface FarmImageTransformInput {\n  source: Uint8Array;\n  sourceUrl: URL;\n  sourceType: string;\n  width: number;\n  quality: number;\n  accept: string;\n  formats: readonly FarmImageFormat[];\n  signal: AbortSignal;\n  /**\n   * Byte ceiling for any source the transformer fetches itself. Supplied by the\n   * image handler; transformers that re-fetch the origin (Cloudflare) must\n   * enforce it, since they bypass the handler's bounded read.\n   */\n  maximumResponseBody?: number;\n}\n\nexport interface FarmImageTransformResult {\n  body: Uint8Array;\n  contentType: string;\n}\n\nexport type FarmImageTransformer = (\n  input: FarmImageTransformInput,\n) => Promise<FarmImageTransformResult>;\n\nexport interface CreateFarmImageHandlerOptions {\n  fetch?: typeof globalThis.fetch;\n  /** Node-only fetcher that validates the DNS result used for remote connections. @internal */\n  fetchRemote?: typeof globalThis.fetch;\n  transform: FarmImageTransformer;\n  validateRemoteUrl?: (url: URL) => void | Promise<void>;\n  onError?: (error: unknown, request: Request) => void;\n  cacheEntries?: number;\n}\n\nexport type FarmImageHandler = (request: Request) => Promise<Response | null>;\n\ntype OptimizedImage = FarmImageTransformResult & {\n  etag: string;\n  cacheControl: string;\n  expiresAt: number;\n};\n\ntype FarmImageRequestErrorCode =\n  | \"BODY_TOO_LARGE\"\n  | \"DISALLOWED_SOURCE\"\n  | \"INVALID_METHOD\"\n  | \"INVALID_PARAMETER\"\n  | \"PRIVATE_SOURCE\"\n  | \"TOO_MANY_REDIRECTS\"\n  | \"UNSUPPORTED_IMAGE\";\n\nexport class FarmImageRequestError extends Error {\n  readonly code: FarmImageRequestErrorCode;\n  readonly status: number;\n\n  constructor(code: FarmImageRequestErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"FarmImageRequestError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\nexport function createFarmImageHandler(\n  config: ResolvedFarmImageConfig,\n  options: CreateFarmImageHandlerOptions,\n): FarmImageHandler {\n  const fetcher = options.fetch ?? globalThis.fetch;\n  const cache = new FarmImageMemoryCache(options.cacheEntries ?? 100);\n  // Identical concurrent misses share one fetch + transform. Without this a\n  // burst for an uncached image (a new page going live, a CDN cold start)\n  // fetches the origin and runs the codec once per request.\n  const inflight = new Map<string, InflightOptimization>();\n  const allowedWidths = new Set([...config.deviceSizes, ...config.imageSizes]);\n  const allowedQualities = new Set(config.qualities);\n\n  return async function handleFarmImage(request): Promise<Response | null> {\n    const requestUrl = new URL(request.url);\n    if (requestUrl.pathname !== config.path) return null;\n\n    try {\n      if (config.provider === \"none\") {\n        throw new FarmImageRequestError(\n          \"DISALLOWED_SOURCE\",\n          404,\n          \"The Farm image optimizer is disabled\",\n        );\n      }\n      if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n        throw new FarmImageRequestError(\n          \"INVALID_METHOD\",\n          405,\n          \"The Farm image optimizer only accepts GET and HEAD\",\n        );\n      }\n\n      const sourceUrl = await resolveImageSourceUrl(requestUrl, config, options.validateRemoteUrl);\n      const width = parseAllowedInteger(requestUrl.searchParams.get(\"w\"), allowedWidths, \"width\");\n      const quality = parseAllowedInteger(\n        requestUrl.searchParams.get(\"q\"),\n        allowedQualities,\n        \"quality\",\n      );\n      const accept = request.headers.get(\"accept\") ?? \"\";\n      // Key on the format the Accept header negotiates to, not the header text.\n      // Both transformers derive their output from `selectOutputFormat(accept,\n      // formats)` alone, so every header that negotiates to the same format\n      // produces byte-identical output. Keying on the raw header let a caller\n      // vary it freely (`image/webp,*/*;q=0.8`, reordered lists, extra params)\n      // and force an uncached fetch and transform each time.\n      const negotiatedFormat = selectOutputFormat(accept, config.formats) ?? \"\";\n      const cacheKey = `${sourceUrl.href}\\n${width}\\n${quality}\\n${negotiatedFormat}`;\n      let optimized = cache.get(cacheKey);\n\n      if (!optimized) {\n        optimized = await runCoalesced(inflight, cacheKey, request.signal, async (signal) => {\n          const fetchedSource = await fetchImageSource(\n            sourceUrl,\n            requestUrl.origin,\n            config,\n            fetcher,\n            options.fetchRemote,\n            options.validateRemoteUrl,\n            signal,\n          );\n          const source = await readResponseWithLimit(\n            fetchedSource.response,\n            config.maximumResponseBody,\n          );\n          const sourceType = detectImageContentType(source);\n          validateSourceType(sourceType, config);\n          throwIfAborted(signal);\n\n          const result = await options.transform({\n            source,\n            sourceUrl: fetchedSource.url,\n            sourceType,\n            width,\n            quality,\n            accept,\n            formats: config.formats,\n            signal,\n            maximumResponseBody: config.maximumResponseBody,\n          });\n          throwIfAborted(signal);\n          validateTransformedResult(result, config);\n\n          const entry = {\n            ...result,\n            etag: createImageEtag(result.body),\n            cacheControl: `public, max-age=${config.minimumCacheTTL}, stale-while-revalidate=${Math.max(\n              config.minimumCacheTTL,\n              60,\n            )}`,\n            expiresAt: Date.now() + config.minimumCacheTTL * 1_000,\n          };\n          cache.set(cacheKey, entry);\n          return entry;\n        });\n      }\n\n      return createOptimizedImageResponse(request, optimized, config);\n    } catch (error) {\n      if (!(error instanceof FarmImageRequestError) && !isAbortError(error)) {\n        try {\n          options.onError?.(error, request);\n        } catch {\n          // Error reporting must not replace the optimizer's sanitized response.\n        }\n      }\n      return createFarmImageErrorResponse(error);\n    }\n  };\n}\n\n/** Mirrors the `images.maximumResponseBody` default (\"10mb\"). */\nconst DEFAULT_IMAGE_TRANSFORM_BODY_LIMIT = 10 * 1024 * 1024;\n\nexport function createCloudflareImageTransformer(\n  fetcher: typeof globalThis.fetch = globalThis.fetch,\n): FarmImageTransformer {\n  return async ({ sourceUrl, width, quality, accept, formats, signal, maximumResponseBody }) => {\n    const format = selectOutputFormat(accept, formats);\n    // Cloudflare resizing works by letting the edge fetch the origin, so this\n    // request cannot reuse the bytes the handler already read. It still must not\n    // be a weaker fetch than the validated one: `redirect: \"manual\"` keeps it\n    // from silently following a hop the handler never validated, and the body is\n    // read under the same ceiling as the handler's own read.\n    const response = await fetcher(sourceUrl, {\n      signal,\n      redirect: \"manual\",\n      headers: { accept: \"image/*\" },\n      cf: {\n        image: {\n          fit: \"scale-down\",\n          width,\n          quality,\n          ...(format ? { format: format === \"image/avif\" ? \"avif\" : \"webp\" } : {}),\n        },\n      },\n    } as RequestInit);\n\n    if (response.status >= 300 && response.status < 400) {\n      void cancelResponseBody(response);\n      throw new FarmImageRequestError(\n        \"UNSUPPORTED_IMAGE\",\n        502,\n        \"Source image redirected after validation\",\n      );\n    }\n\n    if (!response.ok) {\n      throw new FarmImageRequestError(\n        \"UNSUPPORTED_IMAGE\",\n        response.status === 404 ? 404 : 502,\n        \"Cloudflare could not transform the source image\",\n      );\n    }\n\n    const body = await readResponseWithLimit(\n      response,\n      maximumResponseBody ?? DEFAULT_IMAGE_TRANSFORM_BODY_LIMIT,\n    );\n    return {\n      body,\n      contentType:\n        normalizeImageContentType(response.headers.get(\"content-type\")) ||\n        detectImageContentType(body),\n    };\n  };\n}\n\nexport function selectOutputFormat(\n  accept: string,\n  formats: readonly FarmImageFormat[],\n): FarmImageFormat | undefined {\n  const qualityByFormat = new Map<string, number>();\n\n  for (const range of accept.split(\",\")) {\n    const [rawType, ...parameters] = range.split(\";\");\n    const type = rawType.trim().toLowerCase();\n    if (!type) continue;\n\n    let quality = 1;\n    for (const parameter of parameters) {\n      const [rawName, rawValue] = parameter.split(\"=\", 2);\n      if (rawName.trim().toLowerCase() !== \"q\") continue;\n      const parsed = Number(rawValue?.trim());\n      quality = Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? parsed : 0;\n      break;\n    }\n\n    qualityByFormat.set(type, Math.max(qualityByFormat.get(type) ?? 0, quality));\n  }\n\n  let selected: FarmImageFormat | undefined;\n  let selectedQuality = 0;\n  for (const format of formats) {\n    const quality = qualityByFormat.get(format) ?? 0;\n    if (quality > selectedQuality) {\n      selected = format;\n      selectedQuality = quality;\n    }\n  }\n  return selected;\n}\n\nexport function isPrivateImageAddress(address: string): boolean {\n  const value = address.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n  if (value === \"::\" || value === \"::1\") return true;\n  if (/^(?:fc|fd)[0-9a-f]{2}:/.test(value) || /^fe[89ab][0-9a-f]:/.test(value)) return true;\n  if (value.startsWith(\"::ffff:\")) return isPrivateImageAddress(value.slice(7));\n\n  const parts = value.split(\".\");\n  if (parts.length !== 4 || parts.some((part) => !/^\\d{1,3}$/.test(part))) return false;\n  const octets = parts.map(Number);\n  if (octets.some((part) => part > 255)) return false;\n\n  const [a, b] = octets;\n  return (\n    a === 0 ||\n    a === 10 ||\n    a === 127 ||\n    (a === 100 && b >= 64 && b <= 127) ||\n    (a === 169 && b === 254) ||\n    (a === 172 && b >= 16 && b <= 31) ||\n    (a === 192 && (b === 0 || b === 168)) ||\n    (a === 198 && (b === 18 || b === 19)) ||\n    a >= 224\n  );\n}\n\nfunction parseAllowedInteger(\n  raw: string | null,\n  allowed: ReadonlySet<number>,\n  name: string,\n): number {\n  if (!raw || !/^\\d+$/.test(raw)) {\n    throw new FarmImageRequestError(\n      \"INVALID_PARAMETER\",\n      400,\n      `Image ${name} must be an allowed integer`,\n    );\n  }\n  const value = Number(raw);\n  if (!allowed.has(value)) {\n    throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, `Image ${name} is not configured`);\n  }\n  return value;\n}\n\nasync function resolveImageSourceUrl(\n  requestUrl: URL,\n  config: ResolvedFarmImageConfig,\n  validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n): Promise<URL> {\n  const raw = requestUrl.searchParams.get(\"url\");\n  if (!raw || raw.length > 4096 || raw.startsWith(\"//\")) {\n    throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, \"Invalid image source URL\");\n  }\n\n  let sourceUrl: URL;\n  try {\n    sourceUrl = raw.startsWith(\"/\") ? new URL(raw, requestUrl.origin) : new URL(raw);\n  } catch {\n    throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, \"Invalid image source URL\");\n  }\n\n  await validateImageSourceUrl(sourceUrl, requestUrl.origin, config, validateRemoteUrl);\n  return sourceUrl;\n}\n\nasync function validateImageSourceUrl(\n  sourceUrl: URL,\n  requestOrigin: string,\n  config: ResolvedFarmImageConfig,\n  validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n): Promise<void> {\n  if (sourceUrl.protocol !== \"http:\" && sourceUrl.protocol !== \"https:\") {\n    throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Unsupported image protocol\");\n  }\n  if (sourceUrl.username || sourceUrl.password || sourceUrl.hash) {\n    throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Unsafe image source URL\");\n  }\n\n  if (sourceUrl.origin === requestOrigin) {\n    if (\n      sourceUrl.pathname === config.path ||\n      !matchesLocalPatterns(sourceUrl, config.localPatterns)\n    ) {\n      throw new FarmImageRequestError(\n        \"DISALLOWED_SOURCE\",\n        400,\n        \"Local image source is not allowed\",\n      );\n    }\n    return;\n  }\n\n  if (!matchesRemoteSource(sourceUrl, config)) {\n    throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Remote image source is not allowed\");\n  }\n  if (!config.dangerouslyAllowLocalIP && isPrivateImageAddress(sourceUrl.hostname)) {\n    throw new FarmImageRequestError(\"PRIVATE_SOURCE\", 400, \"Private image source is not allowed\");\n  }\n  if (!config.dangerouslyAllowLocalIP) {\n    await validateRemoteUrl?.(sourceUrl);\n  }\n}\n\nasync function fetchImageSource(\n  initialUrl: URL,\n  requestOrigin: string,\n  config: ResolvedFarmImageConfig,\n  fetcher: typeof globalThis.fetch,\n  fetchRemote: typeof globalThis.fetch | undefined,\n  validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n  signal: AbortSignal,\n): Promise<{ response: Response; url: URL }> {\n  let currentUrl = initialUrl;\n\n  for (let redirectCount = 0; ; redirectCount += 1) {\n    throwIfAborted(signal);\n    const sourceFetcher = currentUrl.origin === requestOrigin ? fetcher : (fetchRemote ?? fetcher);\n    const response = await sourceFetcher(currentUrl, {\n      method: \"GET\",\n      redirect: \"manual\",\n      signal,\n      headers: {\n        accept: \"image/avif,image/webp,image/*,*/*;q=0.8\",\n        \"user-agent\": \"Farm.js Image Optimizer\",\n      },\n    });\n\n    if (![301, 302, 303, 307, 308].includes(response.status)) {\n      if (!response.ok) {\n        await cancelResponseBody(response);\n        throw new FarmImageRequestError(\n          \"UNSUPPORTED_IMAGE\",\n          response.status === 404 ? 404 : 502,\n          \"Could not fetch source image\",\n        );\n      }\n      return { response, url: currentUrl };\n    }\n\n    if (redirectCount >= config.maximumRedirects) {\n      await cancelResponseBody(response);\n      throw new FarmImageRequestError(\n        \"TOO_MANY_REDIRECTS\",\n        400,\n        \"Source image exceeded the redirect limit\",\n      );\n    }\n    const location = response.headers.get(\"location\");\n    if (!location) {\n      await cancelResponseBody(response);\n      throw new FarmImageRequestError(\"UNSUPPORTED_IMAGE\", 502, \"Invalid image redirect\");\n    }\n    await cancelResponseBody(response);\n    currentUrl = new URL(location, currentUrl);\n    await validateImageSourceUrl(currentUrl, requestOrigin, config, validateRemoteUrl);\n  }\n}\n\ntype InflightOptimization = {\n  promise: Promise<OptimizedImage>;\n  controller: AbortController;\n  waiters: number;\n};\n\n/**\n * Share one in-flight optimization between identical concurrent requests.\n *\n * The shared work runs under its own AbortController rather than any single\n * request's signal, so one caller going away cannot cancel the image everyone\n * else is waiting for. The controller is aborted only when the last waiter\n * leaves, so an abandoned burst still stops promptly.\n */\nasync function runCoalesced(\n  inflight: Map<string, InflightOptimization>,\n  key: string,\n  requestSignal: AbortSignal,\n  run: (signal: AbortSignal) => Promise<OptimizedImage>,\n): Promise<OptimizedImage> {\n  let entry = inflight.get(key);\n  if (!entry) {\n    const controller = new AbortController();\n    const created: InflightOptimization = {\n      controller,\n      waiters: 0,\n      promise: undefined as unknown as Promise<OptimizedImage>,\n    };\n    created.promise = run(controller.signal).finally(() => {\n      if (inflight.get(key) === created) inflight.delete(key);\n    });\n    // Every waiter can detach before the shared work settles: an already\n    // aborted request returns early without ever attaching to this promise,\n    // and the last waiter leaving aborts the controller. Keep one no-op\n    // handler so that rejection is never reported as unhandled. Waiters still\n    // observe it, because this does not replace the promise they await.\n    created.promise.catch(() => {});\n    inflight.set(key, created);\n    entry = created;\n  }\n\n  const pending = entry;\n  pending.waiters += 1;\n  try {\n    return await raceRequestAbort(pending.promise, requestSignal);\n  } finally {\n    pending.waiters -= 1;\n    if (pending.waiters === 0 && inflight.get(key) === pending) {\n      inflight.delete(key);\n      pending.controller.abort();\n    }\n  }\n}\n\nfunction raceRequestAbort(\n  promise: Promise<OptimizedImage>,\n  signal: AbortSignal,\n): Promise<OptimizedImage> {\n  if (!signal) return promise;\n  if (signal.aborted) return Promise.reject(signal.reason ?? new Error(\"Aborted\"));\n\n  return new Promise<OptimizedImage>((resolve, reject) => {\n    const onAbort = () => reject(signal.reason ?? new Error(\"Aborted\"));\n    signal.addEventListener(\"abort\", onAbort, { once: true });\n    promise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n  });\n}\n\nasync function readResponseWithLimit(response: Response, limit: number): Promise<Uint8Array> {\n  const contentLength = response.headers.get(\"content-length\");\n  if (contentLength && Number(contentLength) > limit) {\n    // Cleanup (including an unread tee branch) must not delay the size rejection.\n    void cancelResponseBody(response);\n    throw new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Source image is too large\");\n  }\n\n  if (!response.body) return new Uint8Array();\n  const reader = response.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let byteLength = 0;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n      byteLength += value.byteLength;\n      if (byteLength > limit) {\n        const error = new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Source image is too large\");\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } finally {\n    reader.releaseLock();\n  }\n\n  const result = new Uint8Array(byteLength);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return result;\n}\n\nasync function cancelResponseBody(response: Response): Promise<void> {\n  try {\n    await response.body?.cancel();\n  } catch {\n    // Cleanup must not replace the request error or redirect result.\n  }\n}\n\nfunction detectImageContentType(bytes: Uint8Array): string {\n  if (\n    bytes.length >= 8 &&\n    bytes[0] === 0x89 &&\n    bytes[1] === 0x50 &&\n    bytes[2] === 0x4e &&\n    bytes[3] === 0x47\n  ) {\n    return \"image/png\";\n  }\n  if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n    return \"image/jpeg\";\n  }\n  if (bytes.length >= 6) {\n    const signature = new TextDecoder().decode(bytes.slice(0, 6));\n    if (signature === \"GIF87a\" || signature === \"GIF89a\") return \"image/gif\";\n  }\n  if (bytes.length >= 12) {\n    const riff = new TextDecoder().decode(bytes.slice(0, 4));\n    const webp = new TextDecoder().decode(bytes.slice(8, 12));\n    if (riff === \"RIFF\" && webp === \"WEBP\") return \"image/webp\";\n    const box = new TextDecoder().decode(bytes.slice(4, 12));\n    if (box.startsWith(\"ftypavif\") || box.startsWith(\"ftypavis\")) return \"image/avif\";\n  }\n\n  const prefix = new TextDecoder().decode(bytes.slice(0, 512)).trimStart().toLowerCase();\n  if (prefix.startsWith(\"<svg\") || (prefix.startsWith(\"<?xml\") && prefix.includes(\"<svg\"))) {\n    return \"image/svg+xml\";\n  }\n  return \"\";\n}\n\nfunction validateSourceType(type: string, config: ResolvedFarmImageConfig): void {\n  if (!type || (type === \"image/svg+xml\" && !config.dangerouslyAllowSVG)) {\n    throw new FarmImageRequestError(\"UNSUPPORTED_IMAGE\", 415, \"Unsupported source image\");\n  }\n}\n\nfunction validateTransformedResult(\n  result: FarmImageTransformResult,\n  config: ResolvedFarmImageConfig,\n): void {\n  if (!(result.body instanceof Uint8Array) || result.body.byteLength === 0) {\n    throw new Error(\"The image transformer returned an empty response\");\n  }\n  if (result.body.byteLength > config.maximumResponseBody) {\n    throw new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Optimized image is too large\");\n  }\n  const contentType = normalizeImageContentType(result.contentType);\n  if (!contentType || (contentType === \"image/svg+xml\" && !config.dangerouslyAllowSVG)) {\n    throw new Error(\"The image transformer returned an unsupported content type\");\n  }\n  result.contentType = contentType;\n}\n\nfunction normalizeImageContentType(value: string | null): string {\n  const type = value?.split(\";\", 1)[0].trim().toLowerCase() ?? \"\";\n  return type.startsWith(\"image/\") ? type : \"\";\n}\n\nfunction matchesRemoteSource(url: URL, config: ResolvedFarmImageConfig): boolean {\n  if (config.domains.includes(url.hostname.toLowerCase())) return true;\n  return config.remotePatterns.some((pattern) => matchesRemotePattern(url, pattern));\n}\n\nfunction matchesRemotePattern(url: URL, pattern: FarmImageRemotePattern): boolean {\n  return (\n    (!pattern.protocol || url.protocol === `${pattern.protocol}:`) &&\n    matchesHostname(url.hostname, pattern.hostname) &&\n    (pattern.port === undefined || url.port === pattern.port) &&\n    matchesGlob(url.pathname, pattern.pathname ?? \"/**\") &&\n    (pattern.search === undefined || url.search === pattern.search)\n  );\n}\n\nfunction matchesLocalPatterns(url: URL, patterns: readonly FarmImageLocalPattern[]): boolean {\n  return patterns.some(\n    (pattern) =>\n      matchesGlob(url.pathname, pattern.pathname) &&\n      (pattern.search === undefined || url.search === pattern.search),\n  );\n}\n\nfunction matchesHostname(hostname: string, pattern: string): boolean {\n  const normalizedHostname = hostname.toLowerCase();\n  const normalizedPattern = pattern.toLowerCase();\n  if (normalizedPattern.startsWith(\"**.\")) {\n    const suffix = normalizedPattern.slice(3);\n    return normalizedHostname === suffix || normalizedHostname.endsWith(`.${suffix}`);\n  }\n  if (normalizedPattern.startsWith(\"*.\")) {\n    const suffix = normalizedPattern.slice(2);\n    const prefix = normalizedHostname.slice(0, -(suffix.length + 1));\n    return normalizedHostname.endsWith(`.${suffix}`) && !!prefix && !prefix.includes(\".\");\n  }\n  return normalizedHostname === normalizedPattern;\n}\n\nfunction matchesGlob(value: string, pattern: string): boolean {\n  const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n  const source = escaped.replace(/\\*\\*/g, \"\\0\").replace(/\\*/g, \"[^/]*\").replace(/\\0/g, \".*\");\n  return new RegExp(`^${source}$`).test(value);\n}\n\nfunction createOptimizedImageResponse(\n  request: Request,\n  image: OptimizedImage,\n  config: ResolvedFarmImageConfig,\n): Response {\n  const headers = new Headers({\n    \"cache-control\": image.cacheControl,\n    \"content-type\": image.contentType,\n    \"content-length\": String(image.body.byteLength),\n    \"content-disposition\": \"inline\",\n    etag: image.etag,\n    vary: \"Accept\",\n    \"x-content-type-options\": \"nosniff\",\n  });\n  if (image.contentType === \"image/svg+xml\" && config.dangerouslyAllowSVG) {\n    headers.set(\"content-security-policy\", \"default-src 'none'; sandbox\");\n  }\n  if (matchesFarmIfNoneMatch(request.headers.get(\"if-none-match\"), image.etag)) {\n    headers.delete(\"content-length\");\n    return new Response(null, { status: 304, headers });\n  }\n  const body =\n    request.method === \"HEAD\"\n      ? null\n      : image.body.buffer.slice(\n          image.body.byteOffset,\n          image.body.byteOffset + image.body.byteLength,\n        );\n  return new Response(body as ArrayBuffer | null, { status: 200, headers });\n}\n\nfunction createFarmImageErrorResponse(error: unknown): Response {\n  const status =\n    error instanceof FarmImageRequestError ? error.status : isAbortError(error) ? 499 : 500;\n  const headers = new Headers({\n    \"cache-control\": \"no-store\",\n    \"content-type\": \"text/plain; charset=utf-8\",\n    \"x-content-type-options\": \"nosniff\",\n  });\n  if (status === 405) headers.set(\"allow\", \"GET, HEAD\");\n\n  const message =\n    status === 400\n      ? \"Invalid image request\"\n      : status === 404\n        ? \"Image not found\"\n        : status === 405\n          ? \"Method not allowed\"\n          : status === 413\n            ? \"Image is too large\"\n            : status === 415\n              ? \"Unsupported image\"\n              : status === 499\n                ? \"Image request cancelled\"\n                : \"Image optimization failed\";\n  return new Response(message, { status, headers });\n}\n\nfunction createImageEtag(bytes: Uint8Array): string {\n  let hash = 0x811c9dc5;\n  for (const byte of bytes) {\n    hash ^= byte;\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return `W/\"farm-${bytes.byteLength.toString(16)}-${(hash >>> 0).toString(16)}\"`;\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    throw signal.reason instanceof Error\n      ? signal.reason\n      : new DOMException(\"The image request was aborted\", \"AbortError\");\n  }\n}\n\nfunction isAbortError(error: unknown): boolean {\n  return error instanceof Error && error.name === \"AbortError\";\n}\n\nclass FarmImageMemoryCache {\n  private readonly entries = new Map<string, OptimizedImage>();\n\n  constructor(private readonly capacity: number) {}\n\n  get(key: string): OptimizedImage | undefined {\n    const value = this.entries.get(key);\n    if (!value) return undefined;\n    if (value.expiresAt <= Date.now()) {\n      this.entries.delete(key);\n      return undefined;\n    }\n    this.entries.delete(key);\n    this.entries.set(key, value);\n    return value;\n  }\n\n  set(key: string, value: OptimizedImage): void {\n    if (this.capacity <= 0) return;\n    this.entries.delete(key);\n    this.entries.set(key, value);\n    while (this.entries.size > this.capacity) {\n      const oldestKey = this.entries.keys().next().value as string | undefined;\n      if (oldestKey === undefined) break;\n      this.entries.delete(oldestKey);\n    }\n  }\n}\n","import path from \"node:path\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport type { FarmRenderer } from \"../renderer\";\n\nconst FARM_CLIENT_ENTRY_PATTERN =\n  \"**/{page,layout,loading,error,not-found,default}.{js,jsx,ts,tsx}\";\n\n/**\n * Client runtimes that must be optimized in the same generation as React.\n * Farm loads route modules dynamically, so Vite's HTML crawl cannot reliably\n * discover these linked-package entry points before hydration begins.\n */\nexport const FARM_CLIENT_OPTIMIZE_DEPS_INCLUDE = [\n  \"react\",\n  \"react-dom\",\n  \"react-dom/client\",\n  \"react/jsx-runtime\",\n  \"react/jsx-dev-runtime\",\n  \"@farm.js/core/client\",\n  \"@farm.js/core/plugin/client\",\n  \"@farm.js/core/deferred\",\n  \"@farm.js/core/deployment\",\n  \"@farm.js/core/i18n/client\",\n  \"@farm.js/core/query/client\",\n  \"@farm.js/core/server-fn/client\",\n  \"@farm.js/core/server-query/client\",\n] as const;\n\nexport function getFarmClientOptimizeDepsInclude(renderer?: FarmRenderer): string[] {\n  return Array.from(\n    new Set([...FARM_CLIENT_OPTIMIZE_DEPS_INCLUDE, ...(renderer?.optimizeDeps || [])]),\n  );\n}\n\nexport function createFarmClientOptimizeDepsEntries(\n  projectRoot: string,\n  appDirectories: readonly string[],\n): string[] {\n  const resolvedProjectRoot = path.resolve(projectRoot);\n\n  return appDirectories.map((appDirectory) => {\n    const relativeAppDirectory = path\n      .relative(resolvedProjectRoot, path.resolve(appDirectory))\n      .replace(/\\\\/g, \"/\");\n    const prefix = relativeAppDirectory || \".\";\n    return `${prefix}/${FARM_CLIENT_ENTRY_PATTERN}`;\n  });\n}\n\nexport function createFarmClientOptimizeDepsConfig(\n  entries?: readonly string[],\n  renderer?: FarmRenderer,\n): ViteUserConfig[\"optimizeDeps\"] {\n  return {\n    // Keep normal application dependency discovery for CJS-only packages, but\n    // seed every Farm browser runtime so React is present in the first crawl.\n    noDiscovery: false,\n    // Waiting for the crawl avoids serving a partial optimizer generation and\n    // then changing browser hashes while hydration is already in progress.\n    holdUntilCrawlEnd: true,\n    include: getFarmClientOptimizeDepsInclude(renderer),\n    // Farm's HTML boots through a virtual module and imports route UI lazily.\n    // Explicit entries let Vite finish that crawl before a navigation can\n    // rotate the optimizer hash underneath a hydrated React runtime.\n    ...(entries?.length ? { entries: [...entries] } : {}),\n  };\n}\n\n/**\n * Farm's application-source alias. Keep this shared by development, route\n * discovery, and production bundling so `@/…` always follows `srcDir`.\n */\nexport function createFarmSourceAlias(projectRoot: string, srcDir = \"src\"): Record<string, string> {\n  return {\n    \"@\": path.resolve(projectRoot, srcDir),\n  };\n}\n\ntype ViteNoExternal = NonNullable<NonNullable<ViteUserConfig[\"ssr\"]>[\"noExternal\"]>;\ntype ViteAlias = NonNullable<NonNullable<ViteUserConfig[\"resolve\"]>[\"alias\"]>;\n\nfunction mergeNoExternal(\n  farmValue: ViteNoExternal | undefined,\n  userValue: ViteNoExternal | undefined,\n): ViteNoExternal {\n  if (farmValue === true || userValue === true) return true;\n\n  const normalize = (value: ViteNoExternal | undefined): Array<string | RegExp> =>\n    value == null || value === true ? [] : Array.isArray(value) ? value : [value];\n\n  return Array.from(new Set([...normalize(farmValue), ...normalize(userValue)]));\n}\n\nfunction mergeAlias(farmValue: ViteAlias | undefined, userValue: ViteAlias | undefined): ViteAlias {\n  if (!farmValue) return userValue || {};\n  if (!userValue) return farmValue;\n\n  if (!Array.isArray(farmValue) && !Array.isArray(userValue)) {\n    return {\n      ...farmValue,\n      ...userValue,\n    };\n  }\n\n  const normalize = (value: ViteAlias): Exclude<ViteAlias, Record<string, string>> =>\n    Array.isArray(value)\n      ? [...value]\n      : Object.entries(value).map(([find, replacement]) => ({ find, replacement }));\n\n  // Vite uses the first matching array entry. Put application entries first\n  // so an explicit user alias can intentionally override a Farm default.\n  return [...normalize(userValue), ...normalize(farmValue)];\n}\n\nexport function mergeFarmViteConfig(\n  farmConfig: ViteUserConfig,\n  userConfig: ViteUserConfig = {},\n): ViteUserConfig {\n  const noDiscovery = userConfig.optimizeDeps?.noDiscovery ?? farmConfig.optimizeDeps?.noDiscovery;\n  const holdUntilCrawlEnd =\n    userConfig.optimizeDeps?.holdUntilCrawlEnd ??\n    (userConfig.optimizeDeps?.noDiscovery === true\n      ? false\n      : farmConfig.optimizeDeps?.holdUntilCrawlEnd);\n\n  return {\n    ...farmConfig,\n    ...userConfig,\n    plugins: [...(farmConfig.plugins || []), ...(userConfig.plugins || [])],\n    server: {\n      ...farmConfig.server,\n      ...userConfig.server,\n    },\n    resolve: {\n      ...farmConfig.resolve,\n      ...userConfig.resolve,\n      alias: mergeAlias(farmConfig.resolve?.alias, userConfig.resolve?.alias),\n      dedupe: Array.from(\n        new Set([...(farmConfig.resolve?.dedupe || []), ...(userConfig.resolve?.dedupe || [])]),\n      ),\n    },\n    optimizeDeps: {\n      ...farmConfig.optimizeDeps,\n      ...userConfig.optimizeDeps,\n      noDiscovery,\n      holdUntilCrawlEnd,\n      include: Array.from(\n        new Set([\n          ...(farmConfig.optimizeDeps?.include || []),\n          ...(userConfig.optimizeDeps?.include || []),\n        ]),\n      ),\n      exclude: Array.from(\n        new Set([\n          ...(farmConfig.optimizeDeps?.exclude || []),\n          ...(userConfig.optimizeDeps?.exclude || []),\n        ]),\n      ),\n    },\n    ssr: {\n      ...farmConfig.ssr,\n      ...userConfig.ssr,\n      noExternal: mergeNoExternal(farmConfig.ssr?.noExternal, userConfig.ssr?.noExternal),\n    },\n  };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface FarmDocsPublicFontAsset {\n  family: \"Geist Sans\" | \"Geist Mono\";\n  url: string;\n}\n\nexport interface FarmDocsFontAsset extends FarmDocsPublicFontAsset {\n  sourcePath: string;\n}\n\nconst FARM_DOCS_FONT_SOURCES = [\n  {\n    family: \"Geist Sans\",\n    packagePath: \"geist/dist/fonts/geist-sans/Geist-Variable.woff2\",\n  },\n  {\n    family: \"Geist Mono\",\n    packagePath: \"geist/dist/fonts/geist-mono/GeistMono-Variable.woff2\",\n  },\n] as const;\n\nexport function resolveFarmDocsFontAssets(root: string): FarmDocsFontAsset[] {\n  return FARM_DOCS_FONT_SOURCES.flatMap(({ family, packagePath }) => {\n    const sourcePath = path.join(root, \"node_modules\", packagePath);\n    if (!existsSync(sourcePath)) return [];\n\n    const source = readFileSync(sourcePath);\n    const fingerprint = createHash(\"sha256\").update(source).digest(\"hex\").slice(0, 12);\n    const extension = path.extname(packagePath);\n    const baseName = path.basename(packagePath, extension);\n\n    return [\n      {\n        family,\n        sourcePath,\n        url: `/assets/fonts/${baseName}-h${fingerprint}${extension}`,\n      },\n    ];\n  });\n}\n\nexport function toFarmDocsPublicFontAssets(\n  assets: readonly FarmDocsFontAsset[],\n): FarmDocsPublicFontAsset[] {\n  return assets.map(({ family, url }) => ({ family, url }));\n}\n","import type { Plugin } from \"vite\";\nimport { resolveFarmThemeConfig } from \"./config\";\nimport type { FarmThemeConfig, ResolvedFarmThemeConfig } from \"./types\";\n\nconst FARM_DARK_VARIANT =\n  '@custom-variant dark (&:where([data-theme=\"dark\"], [data-theme=\"dark\"] *));';\n\nexport function createFarmThemeCssPlugin(\n  input: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n): Plugin {\n  const config = resolveFarmThemeConfig(input, basePath);\n\n  return {\n    name: \"farm:theme-css\",\n    enforce: \"pre\",\n    transform(code, id) {\n      if (\n        !config.enabled ||\n        !/\\.css(?:\\?.*)?$/.test(id) ||\n        !/@import\\s+[\"']tailwindcss[\"']/.test(code) ||\n        /@custom-variant\\s+dark\\b/.test(code)\n      ) {\n        return null;\n      }\n\n      return {\n        code: `${code.trimEnd()}\\n\\n${FARM_DARK_VARIANT}\\n`,\n        map: null,\n      };\n    },\n  };\n}\n","import path from \"node:path\";\nimport type { FarmIntegrationProvider } from \"./integrations\";\nimport { isFarmIntegrationProviderComponentReference } from \"./integrations\";\nimport { toViteModuleId } from \"./utils\";\n\nexport type FarmIntegrationProviderClientCode = {\n  hasProviders: boolean;\n  imports: string;\n  runtime: string;\n};\n\nexport function generateFarmIntegrationProviderClientCode(\n  providers: FarmIntegrationProvider[],\n  root: string,\n): FarmIntegrationProviderClientCode {\n  const renderedProviders = providers.filter(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  const imports: string[] = [];\n  const registrations: string[] = [];\n  let hasClerkProvider = false;\n\n  renderedProviders.forEach((provider, index) => {\n    let componentExpression = \"null\";\n    if (isFarmIntegrationProviderComponentReference(provider.component)) {\n      const namespace = `FarmIntegrationProviderModule${index}`;\n      imports.push(\n        `import * as ${namespace} from ${JSON.stringify(resolveProviderModule(provider.component.module, root))};`,\n      );\n      componentExpression = `${namespace}[${JSON.stringify(provider.component.export || \"default\")}]`;\n    } else if (typeof provider.component === \"function\") {\n      throw new Error(\n        `Integration provider \"${provider.name}\" must use an importable component reference for client hydration, for example component: { module: \"@/components/provider\" }.`,\n      );\n    } else if (provider.type === \"clerk\") {\n      hasClerkProvider = true;\n      componentExpression = \"FarmClerkProvider\";\n    }\n\n    registrations.push(`{\n  name: ${JSON.stringify(provider.name)},\n  type: ${JSON.stringify(provider.type)},\n  props: ${JSON.stringify(provider.props || {})},\n  Component: ${componentExpression},\n}`);\n  });\n\n  if (hasClerkProvider) {\n    imports.unshift(`import { ClerkProvider as FarmClerkProvider } from \"@clerk/react\";`);\n  }\n\n  return {\n    hasProviders: renderedProviders.length > 0,\n    imports: imports.join(\"\\n\"),\n    runtime: `const integrationProviders = [${registrations.join(\",\\n\")}];\n\nfunction wrapWithIntegrationProviders(element) {\n  let wrapped = element;\n  for (let index = integrationProviders.length - 1; index >= 0; index--) {\n    const provider = integrationProviders[index];\n    if (!provider.Component) {\n      throw new Error(\"Integration provider \" + provider.name + \" did not export its configured component.\");\n    }\n    wrapped = React.createElement(provider.Component, provider.props || {}, wrapped);\n  }\n  return wrapped;\n}`,\n  };\n}\n\nexport function createFarmIntegrationProviderModuleKey(component: {\n  module: string;\n  export?: string;\n}): string {\n  return `${component.module}\\0${component.export || \"default\"}`;\n}\n\nexport function generateFarmIntegrationProviderServerModules(\n  providers: FarmIntegrationProvider[],\n  root: string,\n): { imports: string; entries: string; hasClerkProvider: boolean } {\n  const imports: string[] = [];\n  const entries: string[] = [];\n\n  providers.forEach((provider, index) => {\n    if (!isFarmIntegrationProviderComponentReference(provider.component)) return;\n    const namespace = `FarmServerIntegrationProviderModule${index}`;\n    imports.push(\n      `import * as ${namespace} from ${JSON.stringify(resolveProviderModule(provider.component.module, root))};`,\n    );\n    entries.push(\n      `[${JSON.stringify(createFarmIntegrationProviderModuleKey(provider.component))}, ${namespace}[${JSON.stringify(provider.component.export || \"default\")}]]`,\n    );\n  });\n\n  return {\n    imports: imports.join(\"\\n\"),\n    entries: entries.join(\",\\n\"),\n    hasClerkProvider: providers.some(\n      (provider) => provider.type === \"clerk\" && !provider.component,\n    ),\n  };\n}\n\nfunction resolveProviderModule(moduleId: string, root: string): string {\n  if (!moduleId.startsWith(\".\")) return moduleId;\n  return toViteModuleId(path.resolve(root, moduleId), root);\n}\n","import { isFarmNotFoundError } from \"../navigation-errors\";\n\nexport interface FarmPageDataFailure {\n  status: number;\n  payload: {\n    error: string;\n    message: string;\n    code?: string;\n  };\n}\n\n/**\n * Preserve expected route outcomes when a page-data render fails. Internal\n * navigation must report the same HTTP class as a full document render so a\n * missing resource never masquerades as a framework crash.\n */\nexport function resolveFarmPageDataFailure(error: unknown): FarmPageDataFailure {\n  if (isFarmNotFoundError(error)) {\n    return {\n      status: 404,\n      payload: {\n        error: \"Route not found\",\n        message: \"The requested route did not resolve to a resource.\",\n        code: \"FARM_NOT_FOUND\",\n      },\n    };\n  }\n\n  if (error instanceof Response) {\n    return {\n      status: error.status || 500,\n      payload: {\n        error: error.statusText || \"Page data request failed\",\n        message: error.statusText || `The route returned HTTP ${error.status || 500}.`,\n      },\n    };\n  }\n\n  return {\n    status: 500,\n    payload: {\n      error: \"Failed to load page data\",\n      message: error instanceof Error ? error.message : \"Unknown error\",\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { RewriteConfig } from \"../config\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport {\n  compileConfigRoutePattern,\n  interpolateConfigRouteDestination,\n  localizeConfigRouteDestination,\n  resolveConfigRoutePathname,\n} from \"./route-pattern\";\n\nexport const FARM_CONFIG_REWRITES_PLUGIN_NAME = \"farm:rewrites\";\n\nexport function createRewritesPlugin(\n  rewrites: RewriteConfig[],\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n    i18n,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    i18n?: ResolvedFarmI18nConfig;\n  } = {},\n): FarmPlugin {\n  const compiledRewrites = rewrites.map((rewrite) => ({\n    rewrite,\n    pattern: compileConfigRoutePattern(rewrite.source),\n  }));\n\n  return {\n    name: FARM_CONFIG_REWRITES_PLUGIN_NAME,\n    enforce: \"pre\",\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n      const url = resolveFarmRequestURL(req);\n      const routePath = resolveConfigRoutePathname(url.pathname, i18n);\n      const pathname = routePath.pathname;\n\n      for (const { rewrite, pattern } of compiledRewrites) {\n        const match = pathname.match(pattern.regex);\n        if (match) {\n          const newPath = localizeConfigRouteDestination(\n            interpolateConfigRouteDestination(rewrite.destination, match, pattern.tokens),\n            routePath.locale,\n            i18n,\n          );\n          const destinationUrl = new URL(newPath, url);\n          if (!destinationUrl.search && url.search) {\n            destinationUrl.search = url.search;\n          }\n          req.url =\n            destinationUrl.origin === url.origin\n              ? destinationUrl.pathname + destinationUrl.search\n              : destinationUrl.href;\n          break;\n        }\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import { logger } from \"../utils\";\n\ninterface OpenAPIDevStatusLogger {\n  success(message: string): void;\n  warn(message: string): void;\n}\n\nexport function reportOpenAPIDevGenerationResult(\n  spec: unknown,\n  output: OpenAPIDevStatusLogger = logger,\n): void {\n  if (spec) {\n    output.success(\"✅ OpenAPI documentation enabled\");\n    return;\n  }\n\n  output.warn(\"OpenAPI documentation is enabled, but its specification failed to generate.\");\n}\n","export const FARM_NAVIGATION_HEAD_SELECTOR = [\n  \"meta[name]\",\n  \"meta[property]\",\n  \"meta[http-equiv]\",\n  \"meta[charset]\",\n  \"meta[itemprop]\",\n  'link[rel~=\"author\"]',\n  'link[rel~=\"canonical\"]',\n  'link[rel~=\"alternate\"]',\n  'link[rel~=\"icon\"]',\n  'link[rel~=\"apple-touch-icon\"]',\n  'link[rel~=\"manifest\"]',\n  'link[rel~=\"search\"]',\n  'link[rel~=\"next\"]',\n  'link[rel~=\"prev\"]',\n  'link[rel~=\"publisher\"]',\n  'link[rel~=\"license\"]',\n  'link[rel~=\"help\"]',\n  'link[rel~=\"me\"]',\n  'link[rel~=\"pingback\"]',\n  'link[rel~=\"privacy-policy\"]',\n  'link[rel~=\"terms-of-service\"]',\n].join(\",\");\n\nexport function reconcileFarmDocumentHead(nextDocument: Document): void {\n  const nextTitle = nextDocument.querySelector(\"title\");\n  document.title = nextTitle?.textContent || \"\";\n\n  document.head.querySelectorAll(FARM_NAVIGATION_HEAD_SELECTOR).forEach((node) => node.remove());\n  nextDocument.head\n    .querySelectorAll(FARM_NAVIGATION_HEAD_SELECTOR)\n    .forEach((node) => document.head.appendChild(document.importNode(node, true)));\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const FARM_DOCS_LAST_MODIFIED_MANIFEST = \".farm-docs-last-modified.json\";\n\nexport interface FarmDocsLastModifiedManifest {\n  version: 1;\n  pages: Record<string, string>;\n}\n\nexport interface CreateFarmDocsLastModifiedManifestOptions {\n  fallback?: \"mtime\" | \"now\";\n  now?: Date;\n}\n\nconst COMMIT_MARKER = \"__FARM_DOCS_COMMIT__\";\nconst DOCS_FILE_EXTENSIONS = new Set([\".md\", \".mdx\"]);\nconst manifestCache = new Map<\n  string,\n  {\n    signature: string;\n    manifest: FarmDocsLastModifiedManifest;\n  }\n>();\n\nfunction normalizeRelativePath(value: string): string {\n  return value.replace(/\\\\/g, \"/\").replace(/^\\.\\/+/, \"\");\n}\n\nfunction resolveExistingPath(filePath: string): string {\n  try {\n    return realpathSync(filePath);\n  } catch {\n    return path.resolve(filePath);\n  }\n}\n\nfunction isDocsSourceFile(filePath: string): boolean {\n  return DOCS_FILE_EXTENSIONS.has(path.extname(filePath).toLowerCase());\n}\n\nfunction discoverDocsSourceFiles(contentDir: string): string[] {\n  const files: string[] = [];\n\n  const visit = (dir: string) => {\n    for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>\n      a.name.localeCompare(b.name),\n    )) {\n      if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\n      const absolutePath = path.join(dir, entry.name);\n      if (entry.isDirectory()) {\n        visit(absolutePath);\n      } else if (entry.isFile() && isDocsSourceFile(absolutePath)) {\n        files.push(absolutePath);\n      }\n    }\n  };\n\n  if (existsSync(contentDir)) visit(contentDir);\n  return files;\n}\n\nfunction getGitLastModifiedDates(contentDir: string): Record<string, string> {\n  try {\n    const gitRoot = execFileSync(\"git\", [\"-C\", contentDir, \"rev-parse\", \"--show-toplevel\"], {\n      encoding: \"utf8\",\n      stdio: [\"ignore\", \"pipe\", \"ignore\"],\n    }).trim();\n    if (!gitRoot) return {};\n\n    const contentPathspec = normalizeRelativePath(path.relative(gitRoot, contentDir)) || \".\";\n    const contentPrefix = contentPathspec === \".\" ? \"\" : `${contentPathspec}/`;\n    const history = execFileSync(\n      \"git\",\n      [\n        \"-C\",\n        gitRoot,\n        \"-c\",\n        \"core.quotePath=false\",\n        \"log\",\n        `--format=${COMMIT_MARKER}%cI`,\n        \"--name-only\",\n        \"--\",\n        contentPathspec,\n      ],\n      {\n        encoding: \"utf8\",\n        stdio: [\"ignore\", \"pipe\", \"ignore\"],\n        maxBuffer: 32 * 1024 * 1024,\n      },\n    );\n\n    const pages: Record<string, string> = {};\n    let commitDate: string | undefined;\n\n    for (const rawLine of history.split(/\\r?\\n/)) {\n      const line = normalizeRelativePath(rawLine.trim());\n      if (!line) continue;\n\n      if (line.startsWith(COMMIT_MARKER)) {\n        commitDate = line.slice(COMMIT_MARKER.length);\n        continue;\n      }\n      if (!commitDate || (contentPrefix && !line.startsWith(contentPrefix))) continue;\n\n      const relativePath = contentPrefix ? line.slice(contentPrefix.length) : line;\n      if (isDocsSourceFile(relativePath) && !pages[relativePath]) {\n        pages[relativePath] = commitDate;\n      }\n    }\n\n    return pages;\n  } catch {\n    return {};\n  }\n}\n\nfunction readManifest(contentDir: string): FarmDocsLastModifiedManifest | null {\n  const manifestPath = path.join(contentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n  if (!existsSync(manifestPath)) return null;\n\n  try {\n    const parsed = JSON.parse(\n      readFileSync(manifestPath, \"utf8\"),\n    ) as Partial<FarmDocsLastModifiedManifest>;\n    if (parsed.version !== 1 || !parsed.pages || typeof parsed.pages !== \"object\") return null;\n\n    const pages = Object.fromEntries(\n      Object.entries(parsed.pages).filter(\n        (entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1].length > 0,\n      ),\n    );\n    return { version: 1, pages };\n  } catch {\n    return null;\n  }\n}\n\nexport function createFarmDocsLastModifiedManifest(\n  contentDir: string,\n  options: CreateFarmDocsLastModifiedManifestOptions = {},\n): FarmDocsLastModifiedManifest {\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const gitDates = getGitLastModifiedDates(resolvedContentDir);\n  const fallbackDate = (options.now ?? new Date()).toISOString();\n  const pages: Record<string, string> = {};\n\n  for (const sourcePath of discoverDocsSourceFiles(resolvedContentDir)) {\n    const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, sourcePath));\n    pages[relativePath] =\n      gitDates[relativePath] ||\n      (options.fallback === \"now\" ? fallbackDate : statSync(sourcePath).mtime.toISOString());\n  }\n\n  return { version: 1, pages };\n}\n\nfunction getLastModifiedManifest(contentDir: string): FarmDocsLastModifiedManifest {\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const manifestPath = path.join(resolvedContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n  const manifestStat = existsSync(manifestPath) ? statSync(manifestPath) : null;\n  const signature = manifestStat\n    ? `file:${manifestStat.mtimeMs}:${manifestStat.size}`\n    : \"generated\";\n  const cached = manifestCache.get(resolvedContentDir);\n  if (cached?.signature === signature) return cached.manifest;\n\n  const manifest =\n    readManifest(resolvedContentDir) ?? createFarmDocsLastModifiedManifest(resolvedContentDir);\n  manifestCache.set(resolvedContentDir, { signature, manifest });\n  return manifest;\n}\n\nexport function resolveFarmDocsPageLastModified(\n  contentDir: string,\n  sourcePath: string,\n  frontmatter: Record<string, string>,\n): string {\n  const configured =\n    frontmatter.lastModified ||\n    frontmatter.lastmod ||\n    frontmatter.lastUpdated ||\n    frontmatter.updatedAt;\n  if (configured) return configured;\n\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const resolvedSourcePath = resolveExistingPath(sourcePath);\n  const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, resolvedSourcePath));\n  const isInsideContentDir =\n    relativePath !== \"..\" && !relativePath.startsWith(\"../\") && !path.isAbsolute(relativePath);\n\n  if (isInsideContentDir) {\n    const generated = getLastModifiedManifest(resolvedContentDir).pages[relativePath];\n    if (generated) return generated;\n  }\n\n  return statSync(resolvedSourcePath).mtime.toISOString();\n}\n","import { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\nexport function isFarmDocsSearchEnabled(docs: FarmDocsResolvedConfig | undefined): boolean {\n  if (!docs?.enabled) return false;\n\n  const search = docs.config.search;\n  if (search === false) return false;\n  return !(search && typeof search === \"object\" && search.enabled === false);\n}\n\nexport function resolveFarmDocsSearchClientModule(root: string): string | undefined {\n  try {\n    const requireFromApp = createRequire(path.join(path.resolve(root), \"package.json\"));\n    const themeEntry = requireFromApp.resolve(\"@farming-labs/theme\");\n    const commandSearchModule = path.join(path.dirname(themeEntry), \"docs-command-search.mjs\");\n    if (existsSync(commandSearchModule)) return commandSearchModule;\n  } catch {\n    // The public package entry remains a compatible fallback.\n  }\n\n  return undefined;\n}\n\nexport function generateFarmDocsSearchBootstrapRuntime(): string {\n  return `(()=>{if(window.__farmDocsSearchBootstrap)return;window.__farmDocsSearchBootstrap=true;const queue=(trigger,event)=>{if(window.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__)return;event.preventDefault();event.stopPropagation();event.stopImmediatePropagation();window.__FARM_DOCS_SEARCH_PENDING__=trigger;window.__FARM_MOUNT_DOCS_SEARCH__?.()};document.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"[data-search-full]\"):null;if(target)queue(\"button\",event)},true);document.addEventListener(\"keydown\",(event)=>{if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()===\"k\")queue(\"keyboard\",event)},true)})();`;\n}\n\nexport function generateFarmDocsSearchClientRuntime(enabled: boolean, moduleId?: string): string {\n  if (!enabled || !moduleId) {\n    return `\nfunction isFarmDocsSearchPage() {\n  return false;\n}\n\nasync function mountFarmDocsSearch() {\n  return false;\n}\n`;\n  }\n\n  return `\nlet farmDocsSearchRoot = null;\nlet farmDocsSearchContainer = null;\nlet farmDocsSearchModulePromise = null;\nlet farmDocsSearchPendingTrigger = window.__FARM_DOCS_SEARCH_PENDING__ === 'keyboard'\n  ? 'keyboard'\n  : window.__FARM_DOCS_SEARCH_PENDING__\n    ? 'button'\n    : null;\nlet farmDocsSearchReady = false;\n\nfunction isFarmDocsSearchPage() {\n  return document.querySelector('[data-farm-docs-search-root]') instanceof HTMLElement;\n}\n\nfunction replayFarmDocsSearchOpen() {\n  const pendingTrigger = farmDocsSearchPendingTrigger;\n  farmDocsSearchPendingTrigger = null;\n  window.__FARM_DOCS_SEARCH_PENDING__ = null;\n  if (!pendingTrigger) return;\n\n  queueMicrotask(() => {\n    if (pendingTrigger === 'keyboard') {\n      document.dispatchEvent(\n        new KeyboardEvent('keydown', {\n          key: 'k',\n          metaKey: true,\n          bubbles: true,\n          cancelable: true,\n        }),\n      );\n    } else {\n      const trigger = document.querySelector('[data-search-full]');\n      if (trigger instanceof HTMLElement) trigger.click();\n    }\n  });\n}\n\nfunction FarmDocsSearchBridge({ component, api }) {\n  React.useEffect(() => {\n    farmDocsSearchReady = true;\n    replayFarmDocsSearchOpen();\n    return () => {\n      farmDocsSearchReady = false;\n    };\n  }, []);\n\n  return React.createElement(component, { api });\n}\n\nfunction queueFarmDocsSearchOpen(trigger, event) {\n  if (farmDocsSearchReady) return;\n  event.preventDefault();\n  event.stopPropagation();\n  event.stopImmediatePropagation();\n  farmDocsSearchPendingTrigger = trigger;\n  window.__FARM_DOCS_SEARCH_PENDING__ = trigger;\n  void mountFarmDocsSearch();\n}\n\ndocument.addEventListener(\n  'click',\n  (event) => {\n    const target = event.target instanceof Element\n      ? event.target.closest('[data-search-full]')\n      : null;\n    if (target) queueFarmDocsSearchOpen('button', event);\n  },\n  true,\n);\n\ndocument.addEventListener(\n  'keydown',\n  (event) => {\n    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {\n      queueFarmDocsSearchOpen('keyboard', event);\n    }\n  },\n  true,\n);\n\nwindow.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__ = true;\n\nasync function mountFarmDocsSearch() {\n  const container = document.querySelector('[data-farm-docs-search-root]');\n  if (!(container instanceof HTMLElement)) return false;\n  if (farmDocsSearchContainer === container && farmDocsSearchRoot) return true;\n\n  try {\n    farmDocsSearchModulePromise ||= import(${JSON.stringify(moduleId)});\n    const { DocsCommandSearch } = await farmDocsSearchModulePromise;\n    if (!container.isConnected) return false;\n\n    if (farmDocsSearchRoot) {\n      farmDocsSearchReady = false;\n      try {\n        farmDocsSearchRoot.unmount();\n      } catch {}\n    }\n\n    farmDocsSearchContainer = container;\n    farmDocsSearchRoot = createRoot(container);\n    farmDocsSearchRoot.render(\n      React.createElement(FarmDocsSearchBridge, {\n        component: DocsCommandSearch,\n        api: container.dataset.api || '/api/docs',\n      }),\n    );\n    return true;\n  } catch (error) {\n    farmDocsSearchModulePromise = null;\n    console.error('[Farm.js] Could not load docs search:', error);\n    return false;\n  }\n}\n\nwindow.__FARM_MOUNT_DOCS_SEARCH__ = mountFarmDocsSearch;\n`;\n}\n","import { createHash } from \"node:crypto\";\nimport type { LoadedFarmDocsPage } from \"./handler\";\nimport type {\n  FarmDocsResolvedConfig,\n  FarmDocsSocialImageConfig,\n  FarmDocsSocialImageFonts,\n} from \"./types\";\n\nexport const FARM_DOCS_SOCIAL_IMAGE_WIDTH = 1200;\nexport const FARM_DOCS_SOCIAL_IMAGE_HEIGHT = 630;\n\nexport interface FarmDocsSocialImageDescriptor {\n  title: string;\n  description: string;\n  section: string;\n  siteName: string;\n  brand: string;\n  pageHref: string;\n  pageUrl: string;\n  imagePath: string;\n  imageUrl: string;\n  imageAlt: string;\n  illustration: FarmDocsSocialImageIllustration;\n  fonts?: FarmDocsSocialImageFonts;\n  hash: string;\n}\n\nexport type FarmDocsSocialImageIllustration =\n  | \"auth\"\n  | \"cache\"\n  | \"cli\"\n  | \"integrations\"\n  | \"project\"\n  | \"routing\"\n  | \"runtime\";\n\nconst FARM_DOCS_SOCIAL_IMAGE_VERSION = 3;\n\nfunction normalizeEntry(entry: string): string {\n  if (!entry || entry === \"/\") return \"\";\n  return `/${entry.replace(/^\\/+|\\/+$/g, \"\")}`;\n}\n\nfunction encodeSlugPath(slug: string): string {\n  return slug\n    .split(\"/\")\n    .filter(Boolean)\n    .map((segment) => encodeURIComponent(segment))\n    .join(\"/\");\n}\n\nfunction getSocialImageConfig(docs: FarmDocsResolvedConfig): FarmDocsSocialImageConfig | undefined {\n  return typeof docs.config.socialImage === \"object\" && docs.config.socialImage\n    ? docs.config.socialImage\n    : undefined;\n}\n\nfunction getNavTitle(docs: FarmDocsResolvedConfig): string {\n  if (typeof docs.config.nav !== \"object\" || !docs.config.nav || !(\"title\" in docs.config.nav)) {\n    return \"Farm.js\";\n  }\n  return String((docs.config.nav as { title?: unknown }).title || \"Farm.js\");\n}\n\nfunction isFalse(value: string | undefined): boolean {\n  return value ? /^(false|no|none|off|disabled)$/i.test(value.trim()) : false;\n}\n\nfunction isExternalOrRootPath(value: string): boolean {\n  return /^(https?:)?\\/\\//i.test(value) || value.startsWith(\"/\");\n}\n\nexport function isFarmDocsSocialImageEnabled(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n): boolean {\n  if (docs.config.socialImage === false || getSocialImageConfig(docs)?.enabled === false) {\n    return false;\n  }\n  return !isFalse(page.frontmatter.socialImage);\n}\n\nexport function getFarmDocsCustomSocialImage(page: LoadedFarmDocsPage): string | undefined {\n  const value =\n    page.frontmatter.socialImage || page.frontmatter.openGraphImage || page.frontmatter.ogImage;\n  return value && !isFalse(value) && isExternalOrRootPath(value) ? value : undefined;\n}\n\nfunction resolveIllustration(page: LoadedFarmDocsPage): FarmDocsSocialImageIllustration {\n  const explicit = page.frontmatter.socialIllustration?.toLowerCase();\n  if (\n    explicit === \"auth\" ||\n    explicit === \"cache\" ||\n    explicit === \"cli\" ||\n    explicit === \"integrations\" ||\n    explicit === \"project\" ||\n    explicit === \"routing\" ||\n    explicit === \"runtime\"\n  ) {\n    return explicit;\n  }\n\n  const source = `${page.slug} ${page.title} ${page.section || \"\"}`.toLowerCase();\n  if (/auth|session|security|csrf/.test(source)) return \"auth\";\n  if (/cache|ppr|render|static|revalid|stream/.test(source)) return \"cache\";\n  if (/integration|stripe|prisma|better.auth|email|job|workflow/.test(source)) {\n    return \"integrations\";\n  }\n  if (/cli|test|deploy|preview|upgrade|migration|install/.test(source)) return \"cli\";\n  if (/project|structure|config|environment|markdown|docs.engine/.test(source)) {\n    return \"project\";\n  }\n  if (/rout|endpoint|middleware|navigation|server.function|server.action|api/.test(source)) {\n    return \"routing\";\n  }\n  return \"runtime\";\n}\n\nfunction createHashValue(value: unknown): string {\n  return createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\").slice(0, 16);\n}\n\nfunction resolveBaseUrl(requestUrl: URL, config: FarmDocsSocialImageConfig | undefined): URL {\n  return config?.baseUrl ? new URL(config.baseUrl) : new URL(requestUrl.origin);\n}\n\nexport function createFarmDocsSocialImageDescriptor(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n  requestUrl: URL,\n): FarmDocsSocialImageDescriptor {\n  const config = getSocialImageConfig(docs);\n  const siteName = config?.siteName || getNavTitle(docs);\n  const brand = config?.brand || siteName;\n  const title = page.frontmatter.socialTitle || page.title;\n  const description =\n    page.frontmatter.socialDescription ||\n    page.description ||\n    docs.config.metadata?.description ||\n    `Documentation for ${siteName}`;\n  const section = page.frontmatter.section || page.section || \"Documentation\";\n  const illustration = resolveIllustration(page);\n  const entry = normalizeEntry(docs.entry);\n  const slugPath = encodeSlugPath(page.slug) || \"index\";\n  const imagePath = `${entry}/_social/${slugPath}/opengraph-image.svg`;\n  const baseUrl = resolveBaseUrl(requestUrl, config);\n  const pageUrl = new URL(page.href, baseUrl).href;\n  const imageAlt = `${title} — ${siteName} documentation`;\n  const hash = createHashValue({\n    version: FARM_DOCS_SOCIAL_IMAGE_VERSION,\n    title,\n    description,\n    section,\n    siteName,\n    brand,\n    pageHref: page.href,\n    illustration,\n    fonts: config?.fonts,\n  });\n\n  return {\n    title,\n    description,\n    section,\n    siteName,\n    brand,\n    pageHref: page.href,\n    pageUrl,\n    imagePath,\n    imageUrl: new URL(`${imagePath}?v=${hash}`, baseUrl).href,\n    imageAlt,\n    illustration,\n    fonts: config?.fonts,\n    hash,\n  };\n}\n\nexport function getFarmDocsSocialImageSlug(\n  docs: FarmDocsResolvedConfig,\n  requestUrl: URL,\n): string | null {\n  const entry = normalizeEntry(docs.entry);\n  const prefix = `${entry}/_social/`;\n  const suffix = \"/opengraph-image.svg\";\n  if (!requestUrl.pathname.startsWith(prefix) || !requestUrl.pathname.endsWith(suffix)) {\n    return null;\n  }\n\n  const rawSlug = requestUrl.pathname.slice(prefix.length, -suffix.length);\n  if (!rawSlug) return null;\n  try {\n    const slug = rawSlug\n      .split(\"/\")\n      .map((segment) => decodeURIComponent(segment))\n      .join(\"/\");\n    if (slug.split(\"/\").some((segment) => !segment || segment === \"..\" || segment === \".\")) {\n      return null;\n    }\n    return slug === \"index\" ? \"\" : slug;\n  } catch {\n    return null;\n  }\n}\n\nfunction escapeXml(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&apos;\");\n}\n\nfunction truncate(value: string, length: number): string {\n  if (value.length <= length) return value;\n  return `${value.slice(0, Math.max(0, length - 1)).trimEnd()}…`;\n}\n\nfunction wrapText(value: string, maxCharacters: number, maxLines: number): string[] {\n  const words = value.trim().split(/\\s+/).filter(Boolean);\n  const lines: string[] = [];\n  let current = \"\";\n  let consumedWords = 0;\n\n  for (const word of words) {\n    const candidate = current ? `${current} ${word}` : word;\n    if (candidate.length <= maxCharacters || !current) {\n      current = candidate;\n      consumedWords += 1;\n      continue;\n    }\n    lines.push(current);\n    if (lines.length === maxLines) break;\n    current = word;\n    consumedWords += 1;\n  }\n\n  if (current && lines.length < maxLines) lines.push(current);\n  if (consumedWords < words.length && lines.length) {\n    lines[lines.length - 1] = truncate(`${lines[lines.length - 1]}…`, maxCharacters);\n  }\n  return lines;\n}\n\nfunction renderTextLines(\n  lines: string[],\n  x: number,\n  y: number,\n  lineHeight: number,\n  attributes: string,\n): string {\n  return lines\n    .map(\n      (line, index) =>\n        `<text x=\"${x}\" y=\"${y + index * lineHeight}\" ${attributes}>${escapeXml(line)}</text>`,\n    )\n    .join(\"\");\n}\n\nfunction renderEmbeddedFont(name: string, source: string | undefined, weight: string): string {\n  if (!source) return \"\";\n  return `@font-face{font-family:\"${name}\";src:url(\"${escapeXml(source)}\") format(\"woff2\");font-style:normal;font-weight:${weight};font-display:block;}`;\n}\n\nfunction renderArrow(x1: number, y: number, x2: number, color = \"#8b8b8b\"): string {\n  return `<path d=\"M${x1} ${y}H${x2 - 9}\" fill=\"none\" stroke=\"${color}\"/><path d=\"m${x2 - 9} ${y - 5} 9 5-9 5\" fill=\"none\" stroke=\"${color}\"/>`;\n}\n\nfunction renderPanelHeader(label: string, status: string): string {\n  return `<text x=\"819\" y=\"171\" class=\"label\">${escapeXml(label)}</text><text x=\"1134\" y=\"171\" class=\"label bright\" text-anchor=\"end\">${escapeXml(status)}</text>`;\n}\n\nfunction renderRoutingIllustration(): string {\n  return `${renderPanelHeader(\"ROUTE BLUEPRINT\", \"TYPED\")}\n    <rect x=\"819\" y=\"296\" width=\"92\" height=\"54\" fill=\"#a3a3a3\"/>\n    <text x=\"832\" y=\"327\" class=\"diagram-title ink\">src/app</text>\n    <path d=\"M911 323h41M952 232v181M952 232h44M952 323h44M952 413h44\" fill=\"none\" stroke=\"#696969\"/>\n    <rect x=\"996\" y=\"205\" width=\"138\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#414141\"/>\n    <text x=\"1010\" y=\"228\" class=\"diagram-title\">/</text><text x=\"1010\" y=\"246\" class=\"micro\">STATIC</text>\n    <rect x=\"996\" y=\"296\" width=\"138\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#414141\"/>\n    <text x=\"1010\" y=\"319\" class=\"diagram-title\">/blog/:slug</text><text x=\"1010\" y=\"337\" class=\"micro\">DYNAMIC</text>\n    <rect x=\"996\" y=\"386\" width=\"138\" height=\"55\" fill=\"#f0f0f0\"/>\n    <text x=\"1010\" y=\"410\" class=\"diagram-title ink\">/docs/:path*</text><text x=\"1010\" y=\"428\" class=\"micro ink-muted\">CATCH-ALL</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">FILE ROUTES</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">TYPES INCLUDED</text>`;\n}\n\nfunction renderAuthIllustration(): string {\n  return `${renderPanelHeader(\"REQUEST GUARD\", \"SERVER VERIFIED\")}\n    <rect x=\"819\" y=\"269\" width=\"86\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#454545\"/>\n    <text x=\"837\" y=\"292\" class=\"micro bright\">REQUEST</text><text x=\"837\" y=\"310\" class=\"diagram-title\">GET /app</text>\n    ${renderArrow(905, 296, 943)}\n    <rect x=\"943\" y=\"224\" width=\"104\" height=\"118\" fill=\"#f0f0f0\"/>\n    <path d=\"M974 271v-12a21 21 0 0 1 42 0v12M968 271h54v45h-54z\" fill=\"#050505\"/>\n    <circle cx=\"995\" cy=\"292\" r=\"4\" fill=\"#f0f0f0\"/><path d=\"M995 296v8\" stroke=\"#f0f0f0\" stroke-width=\"3\"/>\n    <text x=\"995\" y=\"332\" class=\"micro ink\" text-anchor=\"middle\">auth()</text>\n    ${renderArrow(1047, 296, 1071)}\n    <rect x=\"1071\" y=\"269\" width=\"63\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#454545\"/>\n    <text x=\"1082\" y=\"292\" class=\"micro bright\">ALLOW</text><text x=\"1082\" y=\"310\" class=\"micro\">/app</text>\n    <rect x=\"819\" y=\"372\" width=\"315\" height=\"38\" fill=\"#090909\" stroke=\"#3d3d3d\"/>\n    <rect x=\"832\" y=\"385\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/>\n    <text x=\"856\" y=\"395\" class=\"code\">session.user / verified</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">SESSION TYPED</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">CSRF PROTECTED</text>`;\n}\n\nfunction renderCacheIllustration(): string {\n  return `${renderPanelHeader(\"PAGE / PRODUCT\", \"CACHE + PPR\")}\n    <rect x=\"819\" y=\"204\" width=\"315\" height=\"54\" fill=\"#f0f0f0\"/>\n    <text x=\"836\" y=\"235\" class=\"diagram-title ink\">STATIC SHELL</text><text x=\"1116\" y=\"235\" class=\"micro ink-muted\" text-anchor=\"end\">BUILD</text>\n    <rect x=\"819\" y=\"271\" width=\"198\" height=\"76\" fill=\"#a3a3a3\"/>\n    <text x=\"836\" y=\"301\" class=\"diagram-title ink\">CACHED DATA</text><text x=\"836\" y=\"326\" class=\"micro ink-muted\">tag: products</text>\n    <rect x=\"1029\" y=\"271\" width=\"105\" height=\"76\" fill=\"#0a0a0a\" stroke=\"#555\"/>\n    <text x=\"1045\" y=\"301\" class=\"diagram-title\">LIVE</text><text x=\"1045\" y=\"326\" class=\"micro\">stream</text>\n    <path d=\"M1081 347v43m-8-9 8 9 8-9\" fill=\"none\" stroke=\"#d4d4d4\"/>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">STATIC FIRST</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">DYNAMIC WHERE NEEDED</text>`;\n}\n\nfunction renderIntegrationsIllustration(): string {\n  return `${renderPanelHeader(\"INTEGRATION GRAPH\", \"ONE PRODUCT\")}\n    <path d=\"M976 309H879V247M976 309H879v87M1030 309h93V247M1030 309h93v87\" fill=\"none\" stroke=\"#4a4a4a\"/>\n    <rect x=\"819\" y=\"214\" width=\"120\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"839\" y=\"247\" class=\"diagram-title\">BETTER AUTH</text>\n    <rect x=\"819\" y=\"368\" width=\"120\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"851\" y=\"401\" class=\"diagram-title\">PRISMA</text>\n    <rect x=\"1061\" y=\"214\" width=\"73\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"1077\" y=\"247\" class=\"diagram-title\">STRIPE</text>\n    <rect x=\"1061\" y=\"368\" width=\"73\" height=\"57\" fill=\"#a3a3a3\"/><text x=\"1075\" y=\"401\" class=\"diagram-title ink\">VERCEL</text>\n    <rect x=\"976\" y=\"277\" width=\"94\" height=\"64\" fill=\"#f0f0f0\"/>\n    <text x=\"994\" y=\"304\" class=\"diagram-title ink\">FARM.JS</text><text x=\"994\" y=\"324\" class=\"micro ink-muted\">CORE</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">BRING YOUR STACK</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">CONNECTED ONCE</text>`;\n}\n\nfunction renderCliIllustration(): string {\n  return `${renderPanelHeader(\"TERMINAL\", \"PRODUCTION OUTPUT\")}\n    <rect x=\"819\" y=\"203\" width=\"315\" height=\"213\" fill=\"#050505\" stroke=\"#555\"/>\n    <line x1=\"819\" y1=\"236\" x2=\"1134\" y2=\"236\" stroke=\"#555\"/>\n    <circle cx=\"837\" cy=\"220\" r=\"4\" fill=\"#5d5d5d\"/><circle cx=\"850\" cy=\"220\" r=\"4\" fill=\"#7a7a7a\"/><circle cx=\"863\" cy=\"220\" r=\"4\" fill=\"#a3a3a3\"/>\n    <text x=\"837\" y=\"273\" class=\"code bright\"><tspan fill=\"#7a7a7a\">$</tspan> farm build</text>\n    <rect x=\"837\" y=\"293\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/><path d=\"m839 298 3 3 6-7\" fill=\"none\" stroke=\"#050505\" stroke-width=\"1.5\"/>\n    <text x=\"861\" y=\"303\" class=\"code\">64 routes discovered</text>\n    <rect x=\"837\" y=\"320\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/><path d=\"m839 325 3 3 6-7\" fill=\"none\" stroke=\"#050505\" stroke-width=\"1.5\"/>\n    <text x=\"861\" y=\"330\" class=\"code\">client + server bundles</text>\n    <rect x=\"837\" y=\"355\" width=\"126\" height=\"30\" fill=\"#f0f0f0\"/><text x=\"853\" y=\"374\" class=\"micro ink\">BUILD COMPLETE</text>\n    <text x=\"1115\" y=\"374\" class=\"micro\" text-anchor=\"end\">/dist</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">REAL COMMANDS</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">842MS</text>`;\n}\n\nfunction renderProjectIllustration(): string {\n  return `${renderPanelHeader(\"PROJECT MAP\", \"CONVENTION TYPED\")}\n    <rect x=\"819\" y=\"202\" width=\"315\" height=\"216\" fill=\"#050505\" stroke=\"#555\"/>\n    <text x=\"837\" y=\"227\" class=\"diagram-title bright\">my-app/</text>\n    <path d=\"M847 243v143M847 259h23M847 293h23M847 327h23M847 361h23\" fill=\"none\" stroke=\"#666\"/>\n    <rect x=\"870\" y=\"243\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"264\" class=\"code\">src/app</text><text x=\"1098\" y=\"264\" class=\"micro\" text-anchor=\"end\">ROUTES</text>\n    <rect x=\"870\" y=\"277\" width=\"246\" height=\"33\" fill=\"#f0f0f0\"/><text x=\"886\" y=\"298\" class=\"code ink\">src/app/page.tsx</text>\n    <rect x=\"870\" y=\"311\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"332\" class=\"code\">src/app/api/users/route.ts</text><text x=\"1098\" y=\"332\" class=\"micro\" text-anchor=\"end\">API</text>\n    <rect x=\"870\" y=\"345\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"366\" class=\"code\">farm.config.ts</text><text x=\"1098\" y=\"366\" class=\"micro\" text-anchor=\"end\">CONFIG</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">FILES BECOME FEATURES</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">ONE CONFIG</text>`;\n}\n\nfunction renderRuntimeIllustration(): string {\n  return `${renderPanelHeader(\"PRODUCT ARCHITECTURE\", \"FULL STACK\")}\n    <rect x=\"819\" y=\"211\" width=\"315\" height=\"55\" fill=\"#f0f0f0\"/>\n    <text x=\"836\" y=\"244\" class=\"diagram-title ink\">PRODUCT SURFACE</text><text x=\"1116\" y=\"244\" class=\"micro ink-muted\" text-anchor=\"end\">UI + ROUTES</text>\n    <path d=\"M976 266v20m0 61v20\" stroke=\"#727272\"/>\n    <rect x=\"855\" y=\"286\" width=\"242\" height=\"61\" fill=\"#a3a3a3\"/>\n    <text x=\"874\" y=\"314\" class=\"diagram-title ink\">APPLICATION CORE</text><text x=\"874\" y=\"334\" class=\"micro ink-muted\">APIS · MIDDLEWARE</text>\n    <rect x=\"819\" y=\"367\" width=\"315\" height=\"55\" fill=\"#4c4c4c\"/>\n    <text x=\"836\" y=\"400\" class=\"diagram-title bright\">CONNECTED STACK</text><text x=\"1116\" y=\"400\" class=\"micro\" text-anchor=\"end\">DATA · AUTH · DEPLOY</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">ONE FRAMEWORK</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">ONE DEPLOYMENT MODEL</text>`;\n}\n\nfunction renderIllustration(type: FarmDocsSocialImageIllustration): string {\n  switch (type) {\n    case \"auth\":\n      return renderAuthIllustration();\n    case \"cache\":\n      return renderCacheIllustration();\n    case \"cli\":\n      return renderCliIllustration();\n    case \"integrations\":\n      return renderIntegrationsIllustration();\n    case \"project\":\n      return renderProjectIllustration();\n    case \"routing\":\n      return renderRoutingIllustration();\n    default:\n      return renderRuntimeIllustration();\n  }\n}\n\nexport function renderFarmDocsSocialImageSvg(descriptor: FarmDocsSocialImageDescriptor): string {\n  const titleLines = wrapText(descriptor.title, 22, 2);\n  const longestTitleLine = Math.max(...titleLines.map((line) => line.length));\n  const titleSize = titleLines.length === 1 ? (longestTitleLine > 17 ? 62 : 74) : 56;\n  const titleLineHeight = Math.round(titleSize * 0.98);\n  const titleY = titleLines.length === 1 ? 294 : 266;\n  const descriptionY = titleY + (titleLines.length - 1) * titleLineHeight + 59;\n  const descriptionLines = wrapText(descriptor.description, 68, 2);\n  const routeY = Math.max(418, descriptionY + descriptionLines.length * 29 + 24);\n  const section = truncate(descriptor.section.toUpperCase(), 27);\n  const route = truncate(descriptor.pageHref, 42);\n  const footerUrl = truncate(descriptor.pageUrl.replace(/^https?:\\/\\//, \"\"), 70);\n  const brand = truncate(descriptor.brand.toUpperCase(), 25);\n  const titleId = `farm-docs-og-${descriptor.hash}`;\n\n  return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"${FARM_DOCS_SOCIAL_IMAGE_WIDTH}\" height=\"${FARM_DOCS_SOCIAL_IMAGE_HEIGHT}\" viewBox=\"0 0 ${FARM_DOCS_SOCIAL_IMAGE_WIDTH} ${FARM_DOCS_SOCIAL_IMAGE_HEIGHT}\" role=\"img\" aria-labelledby=\"${titleId}-title ${titleId}-description\">\n  <title id=\"${titleId}-title\">${escapeXml(descriptor.imageAlt)}</title>\n  <desc id=\"${titleId}-description\">${escapeXml(descriptor.description)}</desc>\n  <metadata>${escapeXml(JSON.stringify({ generator: \"Farm.js docs\", page: descriptor.pageUrl, illustration: descriptor.illustration }))}</metadata>\n  <style type=\"text/css\">\n    ${renderEmbeddedFont(\"Farm Sans\", descriptor.fonts?.sans, \"100 900\")}\n    ${renderEmbeddedFont(\"Farm Mono\", descriptor.fonts?.mono, \"100 900\")}\n    ${renderEmbeddedFont(\"Farm Pixel\", descriptor.fonts?.display, \"400 700\")}\n    .sans{font-family:\"Farm Sans\",\"Arial\",sans-serif}.mono,.label,.code,.diagram-title,.micro{font-family:\"Farm Mono\",\"Menlo\",\"DejaVu Sans Mono\",monospace}.pixel{font-family:\"Farm Pixel\",\"Farm Mono\",monospace}.label{fill:#8b8b8b;font-size:10px;font-weight:600;letter-spacing:1.2px}.code{fill:#8b8b8b;font-size:11px}.diagram-title{fill:#e7e7e7;font-size:11px;font-weight:650}.micro{fill:#777;font-size:8px;letter-spacing:.45px}.bright{fill:#f5f5f4}.ink{fill:#050505}.ink-muted{fill:#4c4c4c}\n  </style>\n  <defs>\n    <pattern id=\"canvas-grid\" width=\"40\" height=\"40\" patternUnits=\"userSpaceOnUse\"><path d=\"M40 0H0V40\" fill=\"none\" stroke=\"#151515\"/></pattern>\n    <pattern id=\"diagonal\" width=\"12\" height=\"12\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\"><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"12\" stroke=\"#171717\" stroke-width=\"2\"/></pattern>\n    <clipPath id=\"frame-clip\"><rect x=\"28\" y=\"28\" width=\"1144\" height=\"574\"/></clipPath>\n  </defs>\n  <rect width=\"1200\" height=\"630\" fill=\"#050505\"/>\n  <rect width=\"1200\" height=\"630\" fill=\"url(#canvas-grid)\"/>\n  <g clip-path=\"url(#frame-clip)\">\n    <rect x=\"28\" y=\"28\" width=\"1144\" height=\"574\" fill=\"#020202\"/>\n    <rect x=\"782\" y=\"114\" width=\"390\" height=\"411\" fill=\"url(#diagonal)\"/>\n  </g>\n  <rect x=\"28.5\" y=\"28.5\" width=\"1143\" height=\"573\" fill=\"none\" stroke=\"#323232\"/>\n  <path d=\"M28 114.5h1144M28 525.5h1144M781.5 114v411\" fill=\"none\" stroke=\"#303030\"/>\n\n  <g transform=\"translate(71 51)\">\n    <rect width=\"11\" height=\"11\" rx=\"1\" fill=\"#f5f5f4\"/><rect x=\"15\" width=\"28\" height=\"11\" rx=\"1\" fill=\"#f5f5f4\"/>\n    <rect y=\"15\" width=\"11\" height=\"11\" rx=\"1\" fill=\"#9b9b9b\"/><rect x=\"15\" y=\"15\" width=\"28\" height=\"11\" rx=\"1\" fill=\"#9b9b9b\"/>\n    <rect y=\"30\" width=\"11\" height=\"11\" rx=\"1\" fill=\"#5f5f5f\"/><rect x=\"15\" y=\"30\" width=\"20\" height=\"11\" rx=\"1\" fill=\"#5f5f5f\"/>\n    <text x=\"61\" y=\"24\" class=\"mono bright\" font-size=\"24\" font-weight=\"550\">FARM<tspan fill=\"#777\">.JS</tspan></text>\n    <text x=\"61\" y=\"43\" class=\"label\">BY FARMING LABS</text>\n  </g>\n  <text x=\"1134\" y=\"72\" class=\"label\" text-anchor=\"end\">${escapeXml(brand)} · DOCUMENTATION</text>\n\n  <text x=\"71\" y=\"198\" class=\"mono bright\" font-size=\"13\" font-weight=\"650\">DOCS</text>\n  <line x1=\"117\" y1=\"193\" x2=\"155\" y2=\"193\" stroke=\"#696969\"/>\n  <text x=\"166\" y=\"198\" class=\"mono\" fill=\"#9b9b9b\" font-size=\"13\">${escapeXml(section)}</text>\n  ${renderTextLines(titleLines, 71, titleY, titleLineHeight, `class=\"pixel bright\" font-size=\"${titleSize}\" font-weight=\"500\" letter-spacing=\"-2.4\"`)}\n  ${renderTextLines(descriptionLines, 71, descriptionY, 29, 'class=\"sans\" fill=\"#a3a3a3\" font-size=\"20\" font-weight=\"430\" letter-spacing=\"-.3\"')}\n  <rect x=\"71\" y=\"${routeY}\" width=\"${Math.min(390, 56 + route.length * 8)}\" height=\"36\" fill=\"#050505\" stroke=\"#3c3c3c\"/>\n  <text x=\"85\" y=\"${routeY + 23}\" class=\"mono bright\" font-size=\"11\" font-weight=\"600\">GET</text>\n  <text x=\"119\" y=\"${routeY + 23}\" class=\"mono\" fill=\"#898989\" font-size=\"11\">${escapeXml(route)}</text>\n\n  ${renderIllustration(descriptor.illustration)}\n\n  <text x=\"71\" y=\"570\" class=\"mono bright\" font-size=\"13\" font-weight=\"550\">${escapeXml(footerUrl)}</text>\n  <text x=\"1134\" y=\"570\" class=\"mono\" fill=\"#9b9b9b\" font-size=\"12\" text-anchor=\"end\">FARM.JS DOCUMENTATION</text>\n  <path d=\"M20 20h10M20 20v10M1180 20h-10M1180 20v10M20 610h10M20 610v-10M1180 610h-10M1180 610v-10\" fill=\"none\" stroke=\"#9b9b9b\"/>\n</svg>`;\n}\n\nexport function renderFarmDocsSocialMetadata(\n  descriptor: FarmDocsSocialImageDescriptor,\n  customImage?: string,\n): string {\n  const imageUrl = customImage\n    ? new URL(customImage, descriptor.pageUrl).href\n    : descriptor.imageUrl;\n  const customExtension = customImage?.toLowerCase().split(/[?#]/, 1)[0];\n  const imageType = customExtension?.endsWith(\".webp\")\n    ? \"image/webp\"\n    : customExtension?.endsWith(\".png\")\n      ? \"image/png\"\n      : customExtension?.match(/\\.jpe?g$/)\n        ? \"image/jpeg\"\n        : \"image/svg+xml\";\n  const tag = (property: string, content: string, name = false) =>\n    `<meta ${name ? \"name\" : \"property\"}=\"${property}\" content=\"${escapeXml(content)}\">`;\n\n  return [\n    tag(\"og:type\", \"article\"),\n    tag(\"og:site_name\", descriptor.siteName),\n    tag(\"og:title\", descriptor.title),\n    tag(\"og:description\", descriptor.description),\n    tag(\"og:url\", descriptor.pageUrl),\n    tag(\"og:image\", imageUrl),\n    tag(\"og:image:type\", imageType),\n    ...(customImage\n      ? []\n      : [\n          tag(\"og:image:width\", String(FARM_DOCS_SOCIAL_IMAGE_WIDTH)),\n          tag(\"og:image:height\", String(FARM_DOCS_SOCIAL_IMAGE_HEIGHT)),\n        ]),\n    tag(\"og:image:alt\", descriptor.imageAlt),\n    tag(\"twitter:card\", \"summary_large_image\", true),\n    tag(\"twitter:title\", descriptor.title, true),\n    tag(\"twitter:description\", descriptor.description, true),\n    tag(\"twitter:image\", imageUrl, true),\n    tag(\"twitter:image:alt\", descriptor.imageAlt, true),\n  ].join(\"\\n  \");\n}\n","import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n  buildDocsAgentDiscoverySpec,\n  buildDocsSitemapManifest,\n  isDocsAgentDiscoveryRequest,\n  isDocsAgentsRequest,\n  isDocsSkillRequest,\n  renderDocsAgentsDocument,\n  renderDocsLlmsTxt,\n  renderDocsMarkdownDocument,\n  renderDocsRobotsTxt,\n  renderDocsSitemapMarkdown,\n  renderDocsSitemapXml,\n  renderDocsSkillDocument,\n  resolveDocsLlmsTxtFormat,\n  resolveDocsRobotsRequest,\n  resolveDocsSitemapRequest,\n  type DocsLlmsTxtPageInput,\n  type DocsMarkdownPage,\n  type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { marked, Renderer } from \"marked\";\nimport { highlight } from \"sugar-high\";\nimport { FARM_NAVIGATION_HEAD_SELECTOR } from \"../client/document-head\";\nimport type { FarmLayoutFonts } from \"../font\";\nimport { matchesFarmIfNoneMatch } from \"../server-http\";\nimport {\n  resolveFarmDocsFontAssets,\n  toFarmDocsPublicFontAssets,\n  type FarmDocsPublicFontAsset,\n} from \"./fonts\";\nimport { resolveFarmDocsPageLastModified } from \"./last-modified\";\nimport { generateFarmDocsSearchBootstrapRuntime, isFarmDocsSearchEnabled } from \"./search-client\";\nimport {\n  createFarmDocsSocialImageDescriptor,\n  getFarmDocsCustomSocialImage,\n  getFarmDocsSocialImageSlug,\n  isFarmDocsSocialImageEnabled,\n  renderFarmDocsSocialImageSvg,\n  renderFarmDocsSocialMetadata,\n} from \"./social-image\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\nexport interface FarmDocsHandlerOptions {\n  root: string;\n  srcDir?: string;\n  clientEntry?: string;\n  fontAssets?: readonly FarmDocsPublicFontAsset[];\n  /** Resolve semantic fonts from the layouts that apply to the requested docs route. */\n  resolveLayoutFonts?: (\n    pathname: string,\n  ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n  /** Stylesheet containing the `@font-face` rules generated by Farm's font compiler. */\n  fontStylesheetHref?: string;\n  /** Application-owned global stylesheet, including the selected docs theme CSS import. */\n  globalStylesheetHref?: string;\n}\n\nexport interface FarmDocsPage {\n  slug: string;\n  title: string;\n  description?: string;\n  section?: string;\n  href: string;\n  sourcePath: string;\n  lastModified?: string;\n}\n\nexport interface LoadedFarmDocsPage extends FarmDocsPage {\n  body: string;\n  frontmatter: Record<string, string>;\n}\n\nconst DOCS_FILE_NAMES = [\"page.mdx\", \"page.md\", \"index.mdx\", \"index.md\"];\nconst DOCS_FILE_EXTENSIONS = [\".mdx\", \".md\"];\nconst FARM_DOCS_FALLBACK_FAVICON =\n  \"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='black'/%3E%3Cpath d='M7 8h18v3H10v5h12v3H10v5H7z' fill='white'/%3E%3C/svg%3E\";\nconst FARM_DOCS_FAVICON_FILES = [\"favicon.svg\", \"favicon.ico\", \"favicon.png\"];\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction normalizeEntry(entry: string | undefined): string {\n  if (!entry || entry === \"/\") return \"/\";\n  return `/${trimSlashes(entry)}`;\n}\n\nfunction decodeDocsPath(value: string): string {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    // Malformed percent-encoding in a request path must resolve to a\n    // non-matching slug (a 404), not throw out of the handler.\n    return value;\n  }\n}\n\nfunction normalizeSlug(value: string): string {\n  return trimSlashes(decodeDocsPath(value)).replace(/\\.(mdx?|markdown)$/i, \"\");\n}\n\nfunction resolveFarmDocsFavicon(\n  docs: FarmDocsResolvedConfig | undefined,\n  options: FarmDocsHandlerOptions,\n): string {\n  const configuredFavicon = docs?.config.favicon;\n  if (typeof configuredFavicon === \"string\" && configuredFavicon.trim()) {\n    return configuredFavicon.trim();\n  }\n\n  const publicDir = path.join(path.resolve(options.root), \"public\");\n\n  for (const fileName of FARM_DOCS_FAVICON_FILES) {\n    const faviconPath = path.join(publicDir, fileName);\n    if (existsSync(faviconPath) && statSync(faviconPath).isFile()) {\n      return `/${fileName}`;\n    }\n  }\n\n  return FARM_DOCS_FALLBACK_FAVICON;\n}\n\nfunction renderFarmDocsFaviconLink(faviconHref: string): string {\n  const normalizedHref = faviconHref.split(/[?#]/, 1)[0]?.toLowerCase() || \"\";\n  const type =\n    normalizedHref.endsWith(\".svg\") || faviconHref.startsWith(\"data:image/svg+xml\")\n      ? \"image/svg+xml\"\n      : normalizedHref.endsWith(\".png\")\n        ? \"image/png\"\n        : normalizedHref.endsWith(\".ico\")\n          ? \"image/x-icon\"\n          : undefined;\n  const metadata =\n    type === \"image/svg+xml\" ? ' sizes=\"any\" type=\"image/svg+xml\"' : type ? ` type=\"${type}\"` : \"\";\n\n  return `<link rel=\"icon\" href=\"${escapeAttribute(faviconHref)}\"${metadata}>`;\n}\n\nfunction renderFarmDocsBrandMark(): string {\n  return `<svg class=\"sidebar-brand-logo\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\">\n    <rect x=\"2\" y=\"2\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\"></rect>\n    <path d=\"M9.75 2h11.5c.41 0 .75.34.75.75v3.5c0 .41-.34.75-.75.75H9.75A.75.75 0 0 1 9 6.25v-3.5c0-.41.34-.75.75-.75Zm9.75 1.62a.38.38 0 0 0-.38.38v1c0 .21.17.38.38.38h.75c.21 0 .38-.17.38-.38V4a.38.38 0 0 0-.38-.38h-.75Z\" fill=\"currentColor\"></path>\n    <rect x=\"2\" y=\"9.5\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.64\"></rect>\n    <rect x=\"9\" y=\"9.5\" width=\"13\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.64\"></rect>\n    <rect x=\"2\" y=\"17\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.34\"></rect>\n    <rect x=\"9\" y=\"17\" width=\"7.5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.34\"></rect>\n  </svg>`;\n}\n\nfunction renderFarmDocsBrandTitle(navTitle: string): string {\n  const suffix = navTitle.match(/\\.js$/i)?.[0];\n\n  if (!suffix) {\n    return `<span class=\"sidebar-brand-title\">${escapeHtml(navTitle)}</span>`;\n  }\n\n  const productName = navTitle.slice(0, -suffix.length);\n  return `<span class=\"sidebar-brand-title\">${escapeHtml(productName)}<span class=\"sidebar-brand-suffix\">${escapeHtml(suffix)}</span></span>`;\n}\n\nfunction isSafeSegment(segment: string): boolean {\n  return segment !== \"..\" && !segment.includes(\"/\") && !segment.includes(\"\\\\\");\n}\n\nfunction resolveInside(root: string, target: string): string | null {\n  const resolvedRoot = path.resolve(root);\n  const resolvedTarget = path.resolve(target);\n  const relative = path.relative(resolvedRoot, resolvedTarget);\n  if (relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative))) {\n    return resolvedTarget;\n  }\n  return null;\n}\n\nfunction resolveExistingFileInside(root: string, target: string): string | null {\n  const safePath = resolveInside(root, target);\n  if (!safePath) return null;\n\n  try {\n    const realRoot = realpathSync(root);\n    const realTarget = realpathSync(safePath);\n    const containedTarget = resolveInside(realRoot, realTarget);\n    return containedTarget && statSync(containedTarget).isFile() ? containedTarget : null;\n  } catch {\n    return null;\n  }\n}\n\nexport function isFarmDocsRequest(docs: FarmDocsResolvedConfig | undefined, request: Request) {\n  if (!docs?.enabled) return false;\n  if (request.method !== \"GET\" && request.method !== \"HEAD\") return false;\n\n  const pathname = new URL(request.url).pathname;\n  const entry = normalizeEntry(docs.entry);\n  if (entry === \"/\") return true;\n\n  return pathname === entry || pathname === `${entry}.md` || pathname.startsWith(`${entry}/`);\n}\n\nexport function resolveFarmDocsContentDir(\n  docs: FarmDocsResolvedConfig,\n  options: FarmDocsHandlerOptions,\n): string {\n  const root = path.resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const configuredContentDir = docs.contentDir || docs.config.contentDir;\n\n  if (configuredContentDir) {\n    return path.isAbsolute(configuredContentDir)\n      ? configuredContentDir\n      : path.join(root, configuredContentDir);\n  }\n\n  const entryDir = docs.config.entry || trimSlashes(docs.entry) || \"docs\";\n  const appDocsDir = path.join(root, srcDir, \"app\", entryDir);\n  if (existsSync(appDocsDir)) return appDocsDir;\n\n  return path.join(root, entryDir);\n}\n\nexport function getFarmDocsRouteTypeEntries(docs: FarmDocsResolvedConfig | undefined): string[] {\n  if (!docs?.enabled) return [];\n  const entry = normalizeEntry(docs.entry);\n  if (entry === \"/\") return [\"/\", \"/[...docs]\"];\n  return [entry, `${entry}/[...docs]`];\n}\n\nexport function getFarmDocsDocumentNavigationMatchers(\n  docs: FarmDocsResolvedConfig | undefined,\n): string[] {\n  if (!docs?.enabled) return [];\n  const entry = normalizeEntry(docs.entry);\n  return [entry === \"/\" ? \"/(.*)\" : `${entry}(.*)`];\n}\n\nfunction getRequestSlug(docs: FarmDocsResolvedConfig, request: Request): string {\n  const pathname = new URL(request.url).pathname;\n  const entry = normalizeEntry(docs.entry);\n\n  if (entry === \"/\") return normalizeSlug(pathname);\n  if (pathname === entry || pathname === `${entry}.md`) return \"\";\n\n  return normalizeSlug(pathname.slice(entry.length));\n}\n\nfunction findDocsPageFile(contentDir: string, slug: string): string | null {\n  const segments = slug ? slug.split(\"/\").filter(Boolean) : [];\n  if (!segments.every(isSafeSegment)) return null;\n\n  const slugDir = path.join(contentDir, ...segments);\n  const candidates =\n    segments.length === 0\n      ? DOCS_FILE_NAMES.map((filename) => path.join(contentDir, filename))\n      : [\n          ...DOCS_FILE_NAMES.map((filename) => path.join(slugDir, filename)),\n          ...DOCS_FILE_EXTENSIONS.map((extension) => path.join(contentDir, `${slug}${extension}`)),\n        ];\n\n  for (const candidate of candidates) {\n    const safePath = resolveExistingFileInside(contentDir, candidate);\n    if (safePath) {\n      return safePath;\n    }\n  }\n\n  return null;\n}\n\nfunction parseFrontmatter(source: string): {\n  frontmatter: Record<string, string>;\n  body: string;\n} {\n  if (!source.startsWith(\"---\")) {\n    return { frontmatter: {}, body: source };\n  }\n\n  const endIndex = source.indexOf(\"\\n---\", 3);\n  if (endIndex === -1) return { frontmatter: {}, body: source };\n\n  const frontmatterSource = source.slice(3, endIndex).trim();\n  const body = source.slice(source.indexOf(\"\\n\", endIndex + 1) + 1);\n  const frontmatter: Record<string, string> = {};\n\n  for (const line of frontmatterSource.split(/\\r?\\n/)) {\n    const separator = line.indexOf(\":\");\n    if (separator === -1) continue;\n    const key = line.slice(0, separator).trim();\n    const value = line\n      .slice(separator + 1)\n      .trim()\n      .replace(/^[\"']|[\"']$/g, \"\");\n    if (key && value) frontmatter[key] = value;\n  }\n\n  return { frontmatter, body };\n}\n\nfunction titleFromSlug(slug: string): string {\n  const lastSegment = slug.split(\"/\").filter(Boolean).pop() || \"Docs\";\n  return lastSegment\n    .split(/[-_]/)\n    .filter(Boolean)\n    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n    .join(\" \");\n}\n\nfunction titleFromMarkdown(body: string, fallback: string): string {\n  const heading = body.match(/^#\\s+(.+)$/m)?.[1]?.trim();\n  return heading || fallback;\n}\n\nexport function loadFarmDocsPage(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n  slug: string,\n): LoadedFarmDocsPage | null {\n  const sourcePath = findDocsPageFile(contentDir, slug);\n  if (!sourcePath) return null;\n\n  const source = readFileSync(sourcePath, \"utf8\");\n  const { frontmatter, body } = parseFrontmatter(source);\n  const title = frontmatter.title || titleFromMarkdown(body, titleFromSlug(slug));\n  const href = createDocsHref(docs.entry, slug);\n\n  return {\n    slug,\n    title,\n    description: frontmatter.description,\n    section: frontmatter.section,\n    href,\n    sourcePath,\n    lastModified: resolveFarmDocsPageLastModified(contentDir, sourcePath, frontmatter),\n    frontmatter,\n    body,\n  };\n}\n\nfunction createDocsHref(entry: string, slug: string): string {\n  const normalizedEntry = normalizeEntry(entry);\n  const normalizedSlug = trimSlashes(slug);\n  if (normalizedEntry === \"/\") return normalizedSlug ? `/${normalizedSlug}` : \"/\";\n  return normalizedSlug ? `${normalizedEntry}/${normalizedSlug}` : normalizedEntry;\n}\n\nfunction pathToSlug(contentDir: string, filePath: string): string | null {\n  const relative = path.relative(contentDir, filePath).replace(/\\\\/g, \"/\");\n  if (relative.startsWith(\"..\")) return null;\n\n  const extension = path.extname(relative);\n  if (!DOCS_FILE_EXTENSIONS.includes(extension)) return null;\n\n  const withoutExtension = relative.slice(0, -extension.length);\n  if (withoutExtension === \"page\" || withoutExtension === \"index\") return \"\";\n  if (withoutExtension.endsWith(\"/page\") || withoutExtension.endsWith(\"/index\")) {\n    return withoutExtension.replace(/\\/(page|index)$/, \"\");\n  }\n  return withoutExtension;\n}\n\nfunction loadPage(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n  request: Request,\n): LoadedFarmDocsPage | null {\n  return loadFarmDocsPage(contentDir, docs, getRequestSlug(docs, request));\n}\n\nexport function discoverFarmDocsPages(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n): FarmDocsPage[] {\n  if (!existsSync(contentDir)) return [];\n\n  const pages: FarmDocsPage[] = [];\n  const visit = (dir: string) => {\n    for (const entry of readdirSync(dir, { withFileTypes: true })) {\n      if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n      const absolutePath = path.join(dir, entry.name);\n      if (entry.isDirectory()) {\n        visit(absolutePath);\n        continue;\n      }\n      if (!entry.isFile()) continue;\n\n      const slug = pathToSlug(contentDir, absolutePath);\n      if (slug === null) continue;\n\n      const source = readFileSync(absolutePath, \"utf8\");\n      const { frontmatter, body } = parseFrontmatter(source);\n      pages.push({\n        slug,\n        title: frontmatter.title || titleFromMarkdown(body, titleFromSlug(slug)),\n        description: frontmatter.description,\n        section: frontmatter.section,\n        href: createDocsHref(docs.entry, slug),\n        sourcePath: absolutePath,\n        lastModified: resolveFarmDocsPageLastModified(contentDir, absolutePath, frontmatter),\n      });\n    }\n  };\n\n  visit(contentDir);\n  return pages.sort((a, b) => a.href.localeCompare(b.href));\n}\n\nexport function toFarmDocsMarkdownPage(page: LoadedFarmDocsPage): DocsMarkdownPage {\n  const lastModified =\n    page.lastModified || page.frontmatter.lastModified || page.frontmatter.lastmod;\n\n  return {\n    slug: page.slug,\n    url: page.href,\n    title: page.title,\n    description: page.description,\n    lastModified,\n    lastmod: lastModified,\n    content: page.body,\n    rawContent: page.body,\n  };\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n  return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n    ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n    : \"Documentation\";\n}\n\nfunction getDocsDescription(docs: FarmDocsResolvedConfig): string | undefined {\n  return docs.config.metadata?.description;\n}\n\nfunction getLoadedDocsPages(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n): LoadedFarmDocsPage[] {\n  return discoverFarmDocsPages(contentDir, docs)\n    .map((page) => loadFarmDocsPage(contentDir, docs, page.slug))\n    .filter((page): page is LoadedFarmDocsPage => Boolean(page));\n}\n\nfunction toDocsLlmsPage(page: LoadedFarmDocsPage): DocsLlmsTxtPageInput {\n  return toFarmDocsMarkdownPage(page);\n}\n\nfunction toDocsSitemapPage(page: LoadedFarmDocsPage): DocsSitemapPageInput {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\ntype CopyMarkdownActionConfig = {\n  format: \"markdown\" | \"text\";\n  includeTitle: boolean;\n  label: string;\n  copiedLabel: string;\n};\n\ntype LastUpdatedDisplayConfig = {\n  enabled: boolean;\n  label: string;\n  position: \"footer\" | \"below-title\";\n};\n\ntype ReadingTimeDisplayConfig = {\n  wordsPerMinute: number;\n  format: \"long\" | \"short\";\n  includeCode: boolean;\n};\n\nfunction resolvePageActionsConfig(docs: FarmDocsResolvedConfig): Record<string, unknown> {\n  return isObjectRecord(docs.config.pageActions) ? docs.config.pageActions : {};\n}\n\nfunction resolvePageActionsAlignment(docs: FarmDocsResolvedConfig): \"left\" | \"right\" {\n  return resolvePageActionsConfig(docs).alignment === \"right\" ? \"right\" : \"left\";\n}\n\nfunction resolveCopyMarkdownActionConfig(\n  docs: FarmDocsResolvedConfig,\n): CopyMarkdownActionConfig | null {\n  const raw = resolvePageActionsConfig(docs).copyMarkdown;\n  if (raw === undefined || raw === false) return null;\n\n  const options = isObjectRecord(raw) ? raw : {};\n  if (isObjectRecord(raw) && raw.enabled === false) return null;\n\n  return {\n    format: options.format === \"text\" ? \"text\" : \"markdown\",\n    includeTitle: options.includeTitle === true,\n    label: readString(options.label) ?? \"Copy page\",\n    copiedLabel: readString(options.copiedLabel) ?? \"Copied!\",\n  };\n}\n\nfunction resolveLastUpdatedDisplayConfig(docs: FarmDocsResolvedConfig): LastUpdatedDisplayConfig {\n  const raw = docs.config.lastUpdated;\n  const options = isObjectRecord(raw) ? raw : {};\n\n  return {\n    enabled: raw !== false && (!isObjectRecord(raw) || raw.enabled !== false),\n    label: typeof options.label === \"string\" ? options.label : \"Last updated\",\n    position: options.position === \"below-title\" ? \"below-title\" : \"footer\",\n  };\n}\n\nfunction formatLastModifiedDate(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n\n  const date = new Date(value);\n  if (Number.isNaN(date.getTime())) return value;\n\n  return new Intl.DateTimeFormat(\"en\", {\n    day: \"numeric\",\n    month: \"long\",\n    year: \"numeric\",\n  }).format(date);\n}\n\nfunction renderLastUpdatedText(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n  position: \"footer\" | \"below-title\",\n): string {\n  const config = resolveLastUpdatedDisplayConfig(docs);\n  const formatted = formatLastModifiedDate(page.lastModified);\n  if (!config.enabled || config.position !== position || !formatted) return \"\";\n\n  const time = `<time datetime=\"${escapeAttribute(page.lastModified || \"\")}\">${escapeHtml(formatted)}</time>`;\n  const label = config.label.trim();\n  return label ? `${escapeHtml(label)} ${time}` : time;\n}\n\nfunction resolveReadingTimeDisplayConfig(\n  docs: FarmDocsResolvedConfig,\n): ReadingTimeDisplayConfig | null {\n  const raw = docs.config.readingTime;\n  if (raw === undefined || raw === false) return null;\n\n  const options = isObjectRecord(raw) ? raw : {};\n  if (isObjectRecord(raw) && options.enabled === false) return null;\n\n  const wordsPerMinute =\n    typeof options.wordsPerMinute === \"number\" && options.wordsPerMinute > 0\n      ? options.wordsPerMinute\n      : 220;\n\n  return {\n    wordsPerMinute,\n    format: options.format === \"short\" ? \"short\" : \"long\",\n    includeCode: options.includeCode === true,\n  };\n}\n\nfunction countMarkdownWords(body: string, includeCode: boolean): number {\n  const readable = (\n    includeCode ? body : body.replace(/```[\\s\\S]*?```/g, \" \").replace(/`[^`]*`/g, \" \")\n  )\n    .replace(/!\\[[^\\]]*]\\([^)]*\\)/g, \" \")\n    .replace(/\\[([^\\]]+)]\\([^)]*\\)/g, \"$1\")\n    .replace(/<[^>]+>/g, \" \")\n    .replace(/[#>*_~`|:-]/g, \" \");\n\n  return readable.match(/[A-Za-z0-9]+(?:[-'][A-Za-z0-9]+)*/g)?.length ?? 0;\n}\n\nfunction renderReadingTimeMeta(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const config = resolveReadingTimeDisplayConfig(docs);\n  if (!config) return \"\";\n\n  const words = countMarkdownWords(page.body, config.includeCode);\n  const minutes = Math.max(1, Math.ceil(words / config.wordsPerMinute));\n  const label = config.format === \"short\" ? `${minutes} min` : `${minutes} min read`;\n\n  return `<div class=\"fd-page-meta not-prose\" data-page-reading-time>\n  <span class=\"fd-page-meta-dot\" aria-hidden=\"true\">·</span>\n  <span class=\"fd-page-meta-item\">${escapeHtml(label)}</span>\n</div>`;\n}\n\nfunction renderPixelPageActions(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const copyMarkdown = resolveCopyMarkdownActionConfig(docs);\n  if (!copyMarkdown) return \"\";\n\n  const markdownUrl = `${page.href}.md`;\n  const includeTitle = copyMarkdown.includeTitle ? \"true\" : \"false\";\n\n  return `<div class=\"fd-page-actions\" data-page-actions data-actions-alignment=\"${resolvePageActionsAlignment(docs)}\">\n  <button\n    type=\"button\"\n    class=\"fd-page-action-btn\"\n    data-page-action=\"copy-markdown\"\n    data-copied=\"false\"\n    data-markdown-url=\"${escapeAttribute(markdownUrl)}\"\n    data-copy-markdown-format=\"${copyMarkdown.format}\"\n    data-copy-markdown-include-title=\"${includeTitle}\"\n    data-copy-label=\"${escapeAttribute(copyMarkdown.label)}\"\n    data-copied-label=\"${escapeAttribute(copyMarkdown.copiedLabel)}\"\n    aria-label=\"${escapeAttribute(copyMarkdown.label)}\"\n    title=\"${escapeAttribute(copyMarkdown.label)}\"\n  >\n    <svg class=\"fd-page-action-copy-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg>\n    <svg class=\"fd-page-action-check-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M20 6 9 17l-5-5\"></path></svg>\n    <span data-page-action-label>${escapeHtml(copyMarkdown.label)}</span>\n  </button>\n</div>`;\n}\n\nfunction renderBelowTitleMeta(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const lastUpdated = renderLastUpdatedText(page, docs, \"below-title\");\n  const actions = renderPixelPageActions(page, docs);\n  const readingTime = renderReadingTimeMeta(page, docs);\n  if (!lastUpdated && !actions && !readingTime) return \"\";\n\n  return `<div class=\"fd-below-title-block not-prose\">\n  ${lastUpdated ? `<p class=\"fd-last-updated-inline\">${lastUpdated}</p>` : \"\"}\n  ${actions}\n  ${readingTime}\n</div>`;\n}\n\nfunction renderMarkdownHtmlWithTitleMeta(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const html = renderMarkdownHtml(page.body);\n  const meta = renderBelowTitleMeta(page, docs);\n  if (!meta) return html;\n\n  const withTitleMeta = html.replace(/(<h1\\b[\\s\\S]*?<\\/h1>)/, `$1\\n${meta}`);\n  return withTitleMeta === html ? `${meta}\\n${html}` : withTitleMeta;\n}\n\nfunction renderPixelPageFooter(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  const lastUpdated = renderLastUpdatedText(page, docs, \"footer\");\n  if (!lastUpdated) return \"\";\n\n  return `<div class=\"not-prose fd-page-footer\">\n  <span class=\"fd-last-updated-footer\">${lastUpdated}</span>\n</div>`;\n}\n\nfunction getDocsLlmsOptions(docs: FarmDocsResolvedConfig, request: Request) {\n  const configured =\n    typeof docs.config.llmsTxt === \"object\" && docs.config.llmsTxt !== null\n      ? docs.config.llmsTxt\n      : {};\n  return {\n    enabled: true,\n    baseUrl: new URL(request.url).origin,\n    siteTitle: getDocsTitle(docs),\n    siteDescription: getDocsDescription(docs),\n    ...configured,\n  };\n}\n\nfunction getDocsDiscoveryOptions(docs: FarmDocsResolvedConfig, request: Request) {\n  return {\n    origin: new URL(request.url).origin,\n    entry: docs.entry,\n    i18n: null,\n    search: docs.config.search ?? true,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n    feedback: undefined,\n    llms: getDocsLlmsOptions(docs, request),\n    sitemap: docs.config.sitemap ?? true,\n    robots: docs.config.robots ?? true,\n    openapi: undefined,\n    markdown: {\n      acceptHeader: true,\n      signatureAgentHeader: true,\n    },\n  };\n}\n\nfunction createFarmDocsPublicResponse(\n  contentDir: string,\n  docs: FarmDocsResolvedConfig,\n  request: Request,\n): Response | null {\n  const url = new URL(request.url);\n  let loadedPages: LoadedFarmDocsPage[] | undefined;\n  const getPages = () => (loadedPages ??= getLoadedDocsPages(contentDir, docs));\n  const sitemapManifest = () =>\n    buildDocsSitemapManifest({\n      pages: getPages().map(toDocsSitemapPage),\n      entry: docs.entry,\n      siteTitle: getDocsTitle(docs),\n      baseUrl: url.origin,\n    });\n  const textHeaders = (contentType: string) => ({\n    \"Content-Type\": contentType,\n    \"Cache-Control\": \"public, max-age=60\",\n  });\n\n  const llmsFormat = resolveDocsLlmsTxtFormat(url);\n  if (llmsFormat) {\n    const generated = renderDocsLlmsTxt(\n      getPages().map(toDocsLlmsPage),\n      getDocsLlmsOptions(docs, request),\n    );\n    return new Response(llmsFormat === \"llms-full\" ? generated.llmsFullTxt : generated.llmsTxt, {\n      status: 200,\n      headers: textHeaders(\"text/plain; charset=utf-8\"),\n    });\n  }\n\n  const sitemapFormat = resolveDocsSitemapRequest(url, docs.config.sitemap ?? true);\n  if (sitemapFormat === \"xml\") {\n    return new Response(\n      renderDocsSitemapXml(sitemapManifest(), {\n        baseUrl: url.origin,\n        includeLastmod: true,\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"application/xml; charset=utf-8\"),\n      },\n    );\n  }\n  if (sitemapFormat === \"markdown\") {\n    return new Response(\n      renderDocsSitemapMarkdown(sitemapManifest(), {\n        includeDescriptions: true,\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"text/markdown; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (resolveDocsRobotsRequest(url, docs.config.robots ?? true)) {\n    return new Response(\n      renderDocsRobotsTxt({\n        entry: docs.entry,\n        sitemap: docs.config.sitemap ?? true,\n        robots: docs.config.robots ?? true,\n        baseUrl: url.origin,\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"text/plain; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (isDocsAgentDiscoveryRequest(url)) {\n    const spec = buildDocsAgentDiscoverySpec(getDocsDiscoveryOptions(docs, request));\n    const title = getDocsTitle(docs);\n    return new Response(\n      JSON.stringify({\n        ...spec,\n        name: title,\n        site: {\n          ...spec.site,\n          title,\n          description: getDocsDescription(docs),\n          entry: docs.entry,\n        },\n      }),\n      {\n        status: 200,\n        headers: textHeaders(\"application/json; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (isDocsAgentsRequest(url)) {\n    return new Response(\n      `${renderDocsAgentsDocument(getDocsDiscoveryOptions(docs, request)).trim()}\\n`,\n      {\n        status: 200,\n        headers: textHeaders(\"text/markdown; charset=utf-8\"),\n      },\n    );\n  }\n\n  if (isDocsSkillRequest(url)) {\n    return new Response(\n      `${renderDocsSkillDocument(getDocsDiscoveryOptions(docs, request)).trim()}\\n`,\n      {\n        status: 200,\n        headers: textHeaders(\"text/markdown; charset=utf-8\"),\n      },\n    );\n  }\n\n  return null;\n}\n\nfunction omitFarmDocsHeadBody(request: Request, response: Response): Response {\n  if (request.method !== \"HEAD\") return response;\n  return new Response(null, {\n    status: response.status,\n    statusText: response.statusText,\n    headers: response.headers,\n  });\n}\n\nfunction escapeHtml(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\");\n}\n\nfunction shouldReturnMarkdown(request: Request): boolean {\n  const url = new URL(request.url);\n  return (\n    url.pathname.endsWith(\".md\") ||\n    request.headers.get(\"accept\")?.includes(\"text/markdown\") === true ||\n    request.headers.get(\"accept\")?.includes(\"text/plain\") === true\n  );\n}\n\nfunction escapeAttribute(value: string): string {\n  return escapeHtml(value).replace(/'/g, \"&#39;\");\n}\n\nfunction slugify(value: string): string {\n  return value\n    .toLowerCase()\n    .replace(/<[^>]+>/g, \"\")\n    .replace(/`([^`]+)`/g, \"$1\")\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-|-$/g, \"\");\n}\n\nfunction createSlugger() {\n  const seen = new Map<string, number>();\n\n  return (value: string) => {\n    const base = slugify(value) || \"section\";\n    const count = seen.get(base) || 0;\n    seen.set(base, count + 1);\n    return count === 0 ? base : `${base}-${count + 1}`;\n  };\n}\n\nfunction stripHtml(value: string): string {\n  return value.replace(/<[^>]+>/g, \"\");\n}\n\nfunction getCodeFence(line: string): { marker: \"`\" | \"~\"; length: number } | null {\n  const match = /^(?: {0,3})(`{3,}|~{3,})/.exec(line);\n  const value = match?.[1];\n  if (!value) return null;\n  return { marker: value[0] as \"`\" | \"~\", length: value.length };\n}\n\nfunction isClosingCodeFence(line: string, fence: { marker: \"`\" | \"~\"; length: number }): boolean {\n  const trimmed = line.trim();\n  return (\n    trimmed.length >= fence.length && Array.from(trimmed).every((char) => char === fence.marker)\n  );\n}\n\nfunction stripMdxRuntimeSyntax(body: string): string {\n  const output: string[] = [];\n  let fence: { marker: \"`\" | \"~\"; length: number } | null = null;\n\n  for (const line of body.split(\"\\n\")) {\n    const nextFence = getCodeFence(line);\n    if (fence) {\n      output.push(line);\n      if (nextFence && nextFence.marker === fence.marker && isClosingCodeFence(line, fence)) {\n        fence = null;\n      }\n      continue;\n    }\n\n    if (nextFence) {\n      fence = nextFence;\n      output.push(line);\n      continue;\n    }\n\n    if (/^\\s*import\\s.+$/.test(line) || /^\\s*export\\s+(const|default)\\s.+$/.test(line)) {\n      continue;\n    }\n\n    output.push(line);\n  }\n\n  return output.join(\"\\n\");\n}\n\nfunction unescapeHtml(value: string): string {\n  return value\n    .replace(/&quot;/g, '\"')\n    .replace(/&#39;/g, \"'\")\n    .replace(/&lt;/g, \"<\")\n    .replace(/&gt;/g, \">\")\n    .replace(/&amp;/g, \"&\");\n}\n\nconst CODE_LANGUAGE_LABELS = new Set([\n  \"bash\",\n  \"cjs\",\n  \"cmd\",\n  \"console\",\n  \"css\",\n  \"html\",\n  \"javascript\",\n  \"js\",\n  \"json\",\n  \"jsx\",\n  \"md\",\n  \"mdx\",\n  \"shell\",\n  \"sh\",\n  \"terminal\",\n  \"text\",\n  \"ts\",\n  \"tsx\",\n  \"txt\",\n  \"typescript\",\n  \"yaml\",\n  \"yml\",\n  \"zsh\",\n]);\n\nconst EXTENSIONLESS_CODE_FILENAMES = new Set([\n  \"dockerfile\",\n  \"makefile\",\n  \"procfile\",\n  \"readme\",\n  \"license\",\n]);\n\nfunction isCodePathLabel(label: string): boolean {\n  const trimmed = label.trim();\n  if (!trimmed || /\\s/.test(trimmed)) return false;\n\n  const lower = trimmed.toLowerCase();\n  if (CODE_LANGUAGE_LABELS.has(lower)) return false;\n\n  const fileName = trimmed.split(/[\\\\/]/).filter(Boolean).pop() || trimmed;\n  const lowerFileName = fileName.toLowerCase();\n  if (EXTENSIONLESS_CODE_FILENAMES.has(lowerFileName)) return true;\n  if (fileName.startsWith(\".\") && fileName.length > 1) return true;\n\n  return /\\.[a-z0-9][a-z0-9-]*$/i.test(fileName);\n}\n\nfunction parseCodeInfo(info: string | undefined): {\n  language: string;\n  label: string;\n  hasExplicitLabel: boolean;\n} {\n  const source = (info || \"\").trim();\n  const language = source.match(/^\\S+/)?.[0] || \"text\";\n  const explicitLabel = source\n    .match(/\\b(?:title|filename|file|label|name)=[\"']([^\"']+)[\"']/)?.[1]\n    ?.trim();\n  return { language, label: explicitLabel || language, hasExplicitLabel: Boolean(explicitLabel) };\n}\n\nfunction getStandaloneCodeLabel(line: string): string | null {\n  const trimmed = line.trim();\n  const match = /^(?:\\*\\*([^*]+)\\*\\*|__([^_]+)__|`([^`]+)`)$/u.exec(trimmed);\n  const label = match?.[1] || match?.[2] || match?.[3];\n  return label?.trim() || null;\n}\n\nfunction hasCodeFenceTitle(info: string): boolean {\n  return /\\b(?:title|filename|file|label|name)=[\"'][^\"']+[\"']/.test(info);\n}\n\nfunction escapeCodeFenceTitle(value: string): string {\n  return value.replace(/\"/g, \"&quot;\");\n}\n\nfunction addTitleToCodeFence(line: string, title: string): string {\n  const match = /^(\\s{0,3})(`{3,}|~{3,})(.*)$/u.exec(line);\n  if (!match) return line;\n  const [, indent, marker, infoSource] = match;\n  const info = infoSource.trim();\n  if (hasCodeFenceTitle(info)) return line;\n  const suffix = `title=\"${escapeCodeFenceTitle(title)}\"`;\n  return `${indent}${marker}${info ? `${info} ${suffix}` : `text ${suffix}`}`;\n}\n\nfunction attachCodeBlockLabels(body: string): string {\n  const lines = body.split(\"\\n\");\n  const output: string[] = [];\n  let fence: { marker: \"`\" | \"~\"; length: number } | null = null;\n\n  for (let index = 0; index < lines.length; index += 1) {\n    const line = lines[index] || \"\";\n    const nextFence = getCodeFence(line);\n\n    if (fence) {\n      output.push(line);\n      if (nextFence && nextFence.marker === fence.marker && isClosingCodeFence(line, fence)) {\n        fence = null;\n      }\n      continue;\n    }\n\n    if (nextFence) {\n      fence = nextFence;\n      output.push(line);\n      continue;\n    }\n\n    const label = getStandaloneCodeLabel(line);\n    if (!label) {\n      output.push(line);\n      continue;\n    }\n\n    let fenceIndex = index + 1;\n    while (fenceIndex < lines.length && (lines[fenceIndex] || \"\").trim() === \"\") {\n      fenceIndex += 1;\n    }\n\n    const labeledFence = getCodeFence(lines[fenceIndex] || \"\");\n    if (!labeledFence) {\n      output.push(line);\n      continue;\n    }\n\n    output.push(addTitleToCodeFence(lines[fenceIndex] || \"\", label));\n    fence = labeledFence;\n    index = fenceIndex;\n  }\n\n  return output.join(\"\\n\");\n}\n\nfunction highlightCodeBlock(code: string): string {\n  return highlight(code.replace(/\\n$/, \"\")).replace(/<\\/span>\\n<span/g, \"</span><span\");\n}\n\nfunction renderCodeCopyButton(className = \"code-copy\"): string {\n  return `<button class=\"${className}\" type=\"button\" data-copied=\"false\" aria-label=\"Copy code\" title=\"Copy code\" onclick=\"navigator.clipboard?.writeText(this.closest('figure').querySelector('code').innerText); this.dataset.copied='true'; this.setAttribute('aria-label','Copied'); this.title='Copied'; clearTimeout(this._copyTimer); this._copyTimer=setTimeout(() => { this.dataset.copied='false'; this.setAttribute('aria-label','Copy code'); this.title='Copy code'; }, 4500);\"><svg class=\"code-copy-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg><svg class=\"code-copy-check\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M20 6 9 17l-5-5\"></path></svg></button>`;\n}\n\nfunction renderMarkdownHtml(body: string): string {\n  const slug = createSlugger();\n  const renderer = new Renderer();\n\n  renderer.heading = (text, level, raw) => {\n    const id = slug(raw || stripHtml(text));\n    return `<h${level} id=\"${escapeAttribute(id)}\"><a class=\"heading-anchor\" href=\"#${escapeAttribute(id)}\">${text}</a></h${level}>\\n`;\n  };\n\n  renderer.code = (code, infostring, escaped) => {\n    const { language, label, hasExplicitLabel } = parseCodeInfo(infostring);\n    const rawCode = escaped ? unescapeHtml(code) : code;\n    const highlighted = highlightCodeBlock(rawCode);\n    const shouldRenderHeader = hasExplicitLabel && isCodePathLabel(label);\n    const header = shouldRenderHeader\n      ? `<div class=\"code-block-header\">\n    <span class=\"code-block-title\">${escapeHtml(label)}</span>\n    ${renderCodeCopyButton()}\n  </div>`\n      : renderCodeCopyButton(\"code-copy code-copy-floating\");\n\n    return `<figure class=\"shiki code-block ${shouldRenderHeader ? \"code-block-framed\" : \"code-block-plain\"}\" data-language=\"${escapeAttribute(language)}\">\n  ${header}\n  <pre><code class=\"sh-code language-${escapeAttribute(language)}\">${highlighted}</code></pre>\n</figure>\\n`;\n  };\n\n  renderer.table = (header, body) =>\n    `<div class=\"fd-table-wrapper table-wrap relative overflow-auto prose-no-margin my-6\"><table><thead>${header}</thead><tbody>${body}</tbody></table></div>\\n`;\n\n  renderer.blockquote = (quote) => `<blockquote>${quote}</blockquote>\\n`;\n  renderer.codespan = (code) => `<code>${escapeHtml(code)}</code>`;\n\n  renderer.link = (href, title, text) => {\n    const safeHref = href || \"\";\n    const titleAttribute = title ? ` title=\"${escapeAttribute(title)}\"` : \"\";\n    return `<a href=\"${escapeAttribute(safeHref)}\"${titleAttribute}>${text}</a>`;\n  };\n\n  renderer.image = (href, title, text) => {\n    const titleAttribute = title ? ` title=\"${escapeAttribute(title)}\"` : \"\";\n    return `<img src=\"${escapeAttribute(href)}\" alt=\"${escapeAttribute(text)}\"${titleAttribute}>`;\n  };\n\n  const html = marked(attachCodeBlockLabels(stripMdxRuntimeSyntax(body)), {\n    async: false,\n    breaks: false,\n    gfm: true,\n    renderer,\n  }) as string;\n\n  return html.trim();\n}\n\ninterface TocItem {\n  id: string;\n  title: string;\n  level: number;\n}\n\nfunction extractTocItems(body: string, depth: number): TocItem[] {\n  const slug = createSlugger();\n  const maxLevel = Math.max(2, Math.min(depth, 6));\n  const items: TocItem[] = [];\n  // Track fenced code blocks so a `##` line inside a fence is not treated as a\n  // heading. marked skips those when rendering, so counting them here would\n  // produce phantom TOC links with no matching anchor. Mirrors the fence\n  // tracking in stripMdxRuntimeSyntax / attachCodeBlockLabels.\n  let fence: { marker: \"`\" | \"~\"; length: number } | null = null;\n\n  for (const line of body.split(/\\r?\\n/)) {\n    const nextFence = getCodeFence(line);\n    if (fence) {\n      if (nextFence && nextFence.marker === fence.marker && isClosingCodeFence(line, fence)) {\n        fence = null;\n      }\n      continue;\n    }\n    if (nextFence) {\n      fence = nextFence;\n      continue;\n    }\n\n    const match = line.match(/^(#{2,6})\\s+(.+)$/);\n    if (!match) continue;\n\n    const title = match[2].trim();\n    const id = slug(title);\n    const level = match[1].length;\n    if (level <= maxLevel) {\n      items.push({ id, title, level });\n    }\n  }\n\n  return items;\n}\n\nfunction getThemeUI(docs: FarmDocsResolvedConfig): Record<string, any> {\n  const theme = docs.config.theme;\n  return theme && typeof theme === \"object\" && \"ui\" in theme && typeof theme.ui === \"object\"\n    ? (theme.ui as Record<string, any>)\n    : {};\n}\n\nfunction getThemeName(docs: FarmDocsResolvedConfig): string {\n  const theme = docs.config.theme;\n  return theme && typeof theme === \"object\" && \"name\" in theme\n    ? String((theme as { name?: unknown }).name || \"farm-docs\")\n    : \"farm-docs\";\n}\n\nfunction getThemeTocDepth(docs: FarmDocsResolvedConfig): number {\n  const toc = getThemeUI(docs).layout?.toc;\n  return toc && typeof toc === \"object\" && typeof toc.depth === \"number\" ? toc.depth : 3;\n}\n\nconst SIDEBAR_SECTION_ORDER = [\n  \"Start\",\n  \"Core\",\n  \"Data and APIs\",\n  \"Integrations\",\n  \"Runtime\",\n  \"Content\",\n  \"Extending\",\n  \"Reference\",\n];\n\nconst SIDEBAR_PAGE_ORDER = new Map(\n  [\n    \"\",\n    \"getting-started\",\n    \"project-structure\",\n    \"configuration\",\n    \"routing\",\n    \"layouts\",\n    \"server-rendering\",\n    \"middleware\",\n    \"query\",\n    \"api-routes\",\n    \"api-client\",\n    \"storage\",\n    \"integrations\",\n    \"integrations/stripe\",\n    \"integrations/autumn\",\n    \"integrations/polar\",\n    \"integrations/auth\",\n    \"integrations/email\",\n    \"integrations/jobs\",\n    \"integrations/unkey\",\n    \"integrations/ui-registry\",\n    \"integrations/orm-storage\",\n    \"cache-ppr\",\n    \"observability\",\n    \"deployment\",\n    \"docs-engine\",\n    \"markdown\",\n    \"openapi\",\n    \"plugins\",\n    \"plugins/create-plugin\",\n    \"cli\",\n    \"examples\",\n    \"reference\",\n  ].map((slug, index) => [slug, index]),\n);\n\ntype SidebarNavigationItem = {\n  label?: string;\n  icon?: string;\n  slug?: string;\n  href?: string;\n  children: SidebarNavigationItem[];\n};\n\nfunction isSidebarNavigationItem(\n  value: SidebarNavigationItem | null,\n): value is SidebarNavigationItem {\n  return value !== null;\n}\n\nfunction compareSidebarPages(a: FarmDocsPage, b: FarmDocsPage): number {\n  const aOrder = SIDEBAR_PAGE_ORDER.get(a.slug) ?? 1000;\n  const bOrder = SIDEBAR_PAGE_ORDER.get(b.slug) ?? 1000;\n  return aOrder - bOrder || a.title.localeCompare(b.title);\n}\n\nfunction getSidebarSection(page: FarmDocsPage): string {\n  if (page.section) return page.section;\n  if (page.slug.startsWith(\"integrations/\")) return \"Integrations\";\n  if (page.slug.startsWith(\"plugins/\")) return \"Extending\";\n  return \"Reference\";\n}\n\nfunction sidebarIdFor(section: string): string {\n  return `sidebar-${slugify(section)}`;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction readString(value: unknown): string | undefined {\n  return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction readOptionalString(value: unknown): string | undefined {\n  return typeof value === \"string\" ? value.trim() : undefined;\n}\n\nfunction normalizeSidebarSlug(value: string): string {\n  if (value === \"/\" || value === \".\") return \"\";\n  return trimSlashes(value);\n}\n\nfunction getSidebarNavigation(docs: FarmDocsResolvedConfig): SidebarNavigationItem[] {\n  const navigation = docs.config.navigation;\n  if (!isObjectRecord(navigation) || !Array.isArray(navigation.sidebar)) return [];\n  return navigation.sidebar.map(normalizeSidebarNavigationItem).filter(isSidebarNavigationItem);\n}\n\nfunction normalizeSidebarNavigationItem(value: unknown): SidebarNavigationItem | null {\n  if (!isObjectRecord(value)) return null;\n\n  const label = readString(value.label) ?? readString(value.title);\n  const icon = readString(value.icon);\n  const slug = readOptionalString(value.slug) ?? readOptionalString(value.path);\n  const href = readString(value.href) ?? readString(value.url);\n  const rawChildren = Array.isArray(value.children)\n    ? value.children\n    : Array.isArray(value.items)\n      ? value.items\n      : [];\n  const children = rawChildren.map(normalizeSidebarNavigationItem).filter(isSidebarNavigationItem);\n\n  if (!label && !slug && !href && children.length === 0) return null;\n  return {\n    ...(label ? { label } : {}),\n    ...(icon ? { icon } : {}),\n    ...(slug !== undefined ? { slug: normalizeSidebarSlug(slug) } : {}),\n    ...(href ? { href } : {}),\n    children,\n  };\n}\n\nfunction createSidebarPageMaps(pages: FarmDocsPage[]) {\n  return {\n    bySlug: new Map(pages.map((page) => [page.slug, page])),\n    byHref: new Map(pages.map((page) => [page.href, page])),\n  };\n}\n\nfunction resolveConfiguredSidebarPage(\n  item: SidebarNavigationItem,\n  maps: ReturnType<typeof createSidebarPageMaps>,\n): FarmDocsPage | undefined {\n  if (item.slug !== undefined) return maps.bySlug.get(item.slug);\n  if (item.href) return maps.byHref.get(item.href);\n  return undefined;\n}\n\nfunction getSidebarIconRegistry(docs: FarmDocsResolvedConfig): Record<string, unknown> {\n  return isObjectRecord(docs.config.icons) ? docs.config.icons : {};\n}\n\nfunction renderConfiguredIconSvg(value: unknown): string {\n  if (typeof value !== \"string\") return \"\";\n  const icon = value.trim();\n  if (!icon) return \"\";\n  if (/^<svg[\\s>]/i.test(icon)) return icon;\n  if (/^<(path|circle|rect|line|polyline|polygon|ellipse|g)\\b/i.test(icon)) {\n    return `<svg viewBox=\"0 0 24 24\" focusable=\"false\">${icon}</svg>`;\n  }\n  return \"\";\n}\n\nfunction renderSidebarIcon(\n  docs: FarmDocsResolvedConfig,\n  icon: string | undefined,\n  className = \"sidebar-icon fd-sidebar-icon\",\n): string {\n  if (!icon) return \"\";\n  const iconRegistry = getSidebarIconRegistry(docs);\n  const configuredIcon = iconRegistry[icon] ?? icon;\n  const svg = renderConfiguredIconSvg(configuredIcon);\n  if (!svg) return \"\";\n  return `<span class=\"${className}\" data-sidebar-icon=\"${escapeAttribute(icon)}\" aria-hidden=\"true\">${svg}</span>`;\n}\n\nfunction renderSidebarLabel(\n  docs: FarmDocsResolvedConfig,\n  icon: string | undefined,\n  label: string,\n  className: string,\n): string {\n  return `<span class=\"${className}\">${renderSidebarIcon(docs, icon)}<span class=\"sidebar-label-text\">${escapeHtml(label)}</span></span>`;\n}\n\nfunction getSidebarPageLabel(item: FarmDocsPage, configured?: SidebarNavigationItem): string {\n  if (configured?.label) return configured.label;\n  if (item.slug === \"\") return \"Why?\";\n  if (item.slug === \"integrations\") return \"Overview\";\n  if (item.slug === \"integrations/ui-registry\") return \"UI Registry\";\n  if (item.slug === \"integrations/orm-storage\") return \"ORM Storage\";\n  if (item.slug.startsWith(\"integrations/\")) {\n    return item.title.replace(/\\s+Integrations?$/i, \"\");\n  }\n  return item.title;\n}\n\nfunction renderSidebarLink(\n  item: FarmDocsPage,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n  configured?: SidebarNavigationItem,\n): string {\n  const active = item.href === activeHref;\n  return `<a class=\"fd-sidebar-link${active ? \" fd-sidebar-link-active\" : \"\"}\" data-active=\"${active ? \"true\" : \"false\"}\" href=\"${escapeAttribute(item.href)}\">${renderSidebarLabel(docs, configured?.icon, getSidebarPageLabel(item, configured), \"sidebar-link-label fd-sidebar-link-label\")}</a>`;\n}\n\nfunction collectConfiguredSidebarPages(\n  items: SidebarNavigationItem[],\n  maps: ReturnType<typeof createSidebarPageMaps>,\n  seen = new Set<string>(),\n): FarmDocsPage[] {\n  const ordered: FarmDocsPage[] = [];\n  for (const item of items) {\n    const page = resolveConfiguredSidebarPage(item, maps);\n    if (page && !seen.has(page.slug)) {\n      seen.add(page.slug);\n      ordered.push(page);\n    }\n    ordered.push(...collectConfiguredSidebarPages(item.children, maps, seen));\n  }\n  return ordered;\n}\n\nfunction getOrderedSidebarPages(\n  pages: FarmDocsPage[],\n  docs?: FarmDocsResolvedConfig,\n): FarmDocsPage[] {\n  if (!docs) return [...pages].sort(compareSidebarPages);\n\n  const maps = createSidebarPageMaps(pages);\n  const configuredPages = collectConfiguredSidebarPages(getSidebarNavigation(docs), maps);\n  if (configuredPages.length === 0) return [...pages].sort(compareSidebarPages);\n\n  const configuredSlugs = new Set(configuredPages.map((page) => page.slug));\n  const remainingPages = pages\n    .filter((page) => !configuredSlugs.has(page.slug))\n    .sort(compareSidebarPages);\n  return [...configuredPages, ...remainingPages];\n}\n\nfunction renderExternalSidebarLink(\n  item: SidebarNavigationItem,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  if (!item.href || !item.label) return \"\";\n  const active = item.href === activeHref;\n  return `<a class=\"fd-sidebar-link${active ? \" fd-sidebar-link-active\" : \"\"}\" data-active=\"${active ? \"true\" : \"false\"}\" href=\"${escapeAttribute(item.href)}\">${renderSidebarLabel(docs, item.icon, item.label, \"sidebar-link-label fd-sidebar-link-label\")}</a>`;\n}\n\nfunction renderConfiguredSidebarSubgroup(\n  item: SidebarNavigationItem,\n  childHtml: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const label = item.label;\n  if (!label) return childHtml;\n  return `<div class=\"sidebar-subgroup fd-sidebar-folder\" data-sidebar-subgroup=\"${escapeAttribute(slugify(label))}\">\n  <div class=\"sidebar-subgroup-title fd-sidebar-folder-trigger\">${renderSidebarLabel(docs, item.icon, label, \"sidebar-subgroup-label\")}</div>\n  <div class=\"sidebar-subgroup-content fd-sidebar-folder-content\">\n${childHtml}\n  </div>\n</div>`;\n}\n\nfunction renderConfiguredSidebarItems(\n  items: SidebarNavigationItem[],\n  maps: ReturnType<typeof createSidebarPageMaps>,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const renderedItems: string[] = [];\n  for (const item of items) {\n    const page = resolveConfiguredSidebarPage(item, maps);\n    const childHtml = renderConfiguredSidebarItems(item.children, maps, activeHref, docs);\n\n    if (item.children.length > 0) {\n      renderedItems.push(renderConfiguredSidebarSubgroup(item, childHtml, docs));\n      continue;\n    }\n\n    const linkHtml = page\n      ? renderSidebarLink(page, activeHref, docs, item)\n      : renderExternalSidebarLink(item, activeHref, docs);\n    if (linkHtml) renderedItems.push(linkHtml);\n  }\n  return renderedItems.join(\"\\n\");\n}\n\nfunction renderConfiguredSidebarSection(\n  section: SidebarNavigationItem,\n  maps: ReturnType<typeof createSidebarPageMaps>,\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const label = section.label || \"Docs\";\n  const id = sidebarIdFor(label);\n  const links = renderConfiguredSidebarItems(section.children, maps, activeHref, docs);\n  return `<div class=\"sidebar-folder fd-sidebar-folder\" data-state=\"open\">\n  <button class=\"text-fd-muted-foreground sidebar-folder-trigger fd-sidebar-folder-trigger\" type=\"button\" aria-controls=\"${escapeAttribute(id)}\" aria-expanded=\"true\">${renderSidebarLabel(docs, section.icon, label, \"sidebar-folder-label\")}</button>\n  <div id=\"${escapeAttribute(id)}\" class=\"overflow-hidden sidebar-folder-content fd-sidebar-folder-content\" data-state=\"open\">\n${links}\n  </div>\n</div>`;\n}\n\nfunction renderAutoSidebarSectionItems(\n  items: FarmDocsPage[],\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  return [...items]\n    .sort(compareSidebarPages)\n    .map((item) => renderSidebarLink(item, activeHref, docs))\n    .join(\"\\n\");\n}\n\nfunction renderPixelNavItems(\n  pages: FarmDocsPage[],\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const configuredSidebar = getSidebarNavigation(docs);\n  if (configuredSidebar.length > 0) {\n    const maps = createSidebarPageMaps(pages);\n    const renderedSections = configuredSidebar\n      .map((section) => {\n        if (section.children.length > 0) {\n          return renderConfiguredSidebarSection(section, maps, activeHref, docs);\n        }\n        const page = resolveConfiguredSidebarPage(section, maps);\n        return page\n          ? renderSidebarLink(page, activeHref, docs, section)\n          : renderExternalSidebarLink(section, activeHref, docs);\n      })\n      .filter(Boolean)\n      .join(\"\\n\");\n\n    return `<div class=\"sidebar-scroll overscroll-contain fd-sidebar-nav\">\n  <div class=\"sidebar-tree\">\n${renderedSections}\n  </div>\n</div>`;\n  }\n\n  const groups = new Map<string, FarmDocsPage[]>();\n  for (const item of pages) {\n    const group = item.slug === \"\" ? \"Start\" : getSidebarSection(item);\n    const entries = groups.get(group) ?? [];\n    entries.push(item);\n    groups.set(group, entries);\n  }\n\n  const renderedSections = Array.from(groups.entries())\n    .sort(([a], [b]) => {\n      const aOrder = SIDEBAR_SECTION_ORDER.indexOf(a);\n      const bOrder = SIDEBAR_SECTION_ORDER.indexOf(b);\n      return (aOrder === -1 ? 100 : aOrder) - (bOrder === -1 ? 100 : bOrder) || a.localeCompare(b);\n    })\n    .map(([section, items]) => {\n      const id = sidebarIdFor(section);\n      const links = renderAutoSidebarSectionItems(items, activeHref, docs);\n      return `<div class=\"sidebar-folder fd-sidebar-folder\" data-state=\"open\">\n  <button class=\"text-fd-muted-foreground sidebar-folder-trigger fd-sidebar-folder-trigger\" type=\"button\" aria-controls=\"${escapeAttribute(id)}\" aria-expanded=\"true\">${renderSidebarLabel(docs, undefined, section, \"sidebar-folder-label\")}</button>\n  <div id=\"${escapeAttribute(id)}\" class=\"overflow-hidden sidebar-folder-content fd-sidebar-folder-content\" data-state=\"open\">\n${links}\n  </div>\n</div>`;\n    })\n    .join(\"\\n\");\n\n  return `<div class=\"sidebar-scroll overscroll-contain fd-sidebar-nav\">\n  <div class=\"sidebar-tree\">\n${renderedSections}\n  </div>\n</div>`;\n}\n\nfunction renderPixelPageNav(\n  pages: FarmDocsPage[],\n  activeHref: string,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const orderedPages = getOrderedSidebarPages(pages, docs);\n  const activeIndex = orderedPages.findIndex((item) => item.href === activeHref);\n  if (activeIndex === -1) return \"\";\n\n  const previous = orderedPages[activeIndex - 1];\n  const next = orderedPages[activeIndex + 1];\n  if (!previous && !next) return \"\";\n\n  const renderChevron = (direction: \"prev\" | \"next\") =>\n    `<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><polyline points=\"${direction === \"prev\" ? \"15 18 9 12 15 6\" : \"9 18 15 12 9 6\"}\" /></svg>`;\n  const renderCard = (item: FarmDocsPage, direction: \"prev\" | \"next\") =>\n    `<a class=\"fd-page-nav-card fd-page-nav-${direction}\" href=\"${escapeAttribute(item.href)}\">\n  <span class=\"fd-page-nav-title fd-page-nav-title-${direction}\">${direction === \"prev\" ? `${renderChevron(direction)}${escapeHtml(item.title)}` : `${escapeHtml(item.title)}${renderChevron(direction)}`}</span>\n  <span class=\"fd-page-nav-description\">${direction === \"prev\" ? \"Previous Page\" : \"Next Page\"}</span>\n</a>`;\n\n  return `<nav class=\"not-prose fd-page-nav\" aria-label=\"Page navigation\">\n  ${previous ? renderCard(previous, \"prev\") : \"\"}\n  ${next ? renderCard(next, \"next\") : \"\"}\n</nav>`;\n}\n\nfunction titleizePathSegment(value: string): string {\n  return value.replace(/[-_]+/g, \" \").replace(/\\b\\w/g, (character) => character.toUpperCase());\n}\n\nfunction isBreadcrumbEnabled(docs: FarmDocsResolvedConfig): boolean {\n  const breadcrumb = docs.config.breadcrumb;\n  if (breadcrumb === false) return false;\n  if (breadcrumb && typeof breadcrumb === \"object\" && \"enabled\" in breadcrumb) {\n    return (breadcrumb as { enabled?: unknown }).enabled !== false;\n  }\n  return true;\n}\n\nfunction renderPixelBreadcrumb(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n  if (!isBreadcrumbEnabled(docs)) return \"\";\n\n  const segments = trimSlashes(page.slug).split(\"/\").filter(Boolean);\n  if (segments.length < 2) return \"\";\n\n  const parentSegments = segments.slice(0, -1);\n  const parentSegment = parentSegments[parentSegments.length - 1];\n  const currentSegment = segments[segments.length - 1];\n  const entry = normalizeEntry(docs.entry);\n  const parentPath = parentSegments.join(\"/\");\n  const parentHref = entry === \"/\" ? `/${parentPath}` : `${entry}/${parentPath}`;\n\n  return `<nav class=\"fd-breadcrumb\" aria-label=\"Breadcrumb\">\n  <span class=\"fd-breadcrumb-item\">\n    <a class=\"fd-breadcrumb-parent fd-breadcrumb-link\" href=\"${escapeAttribute(parentHref)}\">${escapeHtml(titleizePathSegment(parentSegment))}</a>\n  </span>\n  <span class=\"fd-breadcrumb-item\">\n    <span class=\"fd-breadcrumb-sep\">/</span>\n    <span class=\"fd-breadcrumb-current\">${escapeHtml(titleizePathSegment(currentSegment))}</span>\n  </span>\n</nav>`;\n}\n\nfunction renderDocsSearchTrigger(showIcon = true, className = \"\"): string {\n  return `<button class=\"fd-docs-search-trigger ${className}\" type=\"button\" data-search-full=\"\" aria-label=\"Search documentation\" aria-haspopup=\"dialog\" aria-keyshortcuts=\"Meta+K Control+K\">\n  ${showIcon ? '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><circle cx=\"11\" cy=\"11\" r=\"7\"></circle><path d=\"m20 20-4-4\"></path></svg>' : \"\"}\n  <kbd><span>⌘</span><span>K</span></kbd>\n</button>`;\n}\n\nfunction renderDocsSearchMount(clientEntry: string): string {\n  return `<div id=\"farm-docs-search-root\" data-farm-docs-search-root data-api=\"/api/docs\"></div>\n  <script type=\"module\" src=\"${escapeAttribute(clientEntry)}\"></script>`;\n}\n\nfunction renderDocsSearchBootstrapScript(): string {\n  return `<script>${generateFarmDocsSearchBootstrapRuntime()}</script>`;\n}\n\nfunction renderPixelToc(items: TocItem[]): string {\n  if (items.length === 0) return '<p class=\"toc-empty\">No sections</p>';\n  return `<div class=\"toc-track fd-toc-list\">\n  <div class=\"toc-thumb\" data-toc-thumb style=\"clip-path: polygon(0 0px, 100% 0px, 100% 32px, 0 32px);\"></div>\n  <div class=\"toc-links\">\n${items\n  .map(\n    (item) =>\n      `<a class=\"toc-link fd-toc-link${items[0] === item ? \" fd-toc-link-active\" : \"\"}\" data-active=\"${items[0] === item ? \"true\" : \"false\"}\" data-toc-item data-depth=\"${item.level}\" href=\"#${escapeAttribute(item.id)}\">${escapeHtml(item.title)}</a>`,\n  )\n  .join(\"\\n\")}\n  </div>\n</div>`;\n}\n\nfunction renderDocsRuntimeScript(docs: FarmDocsResolvedConfig): string {\n  const docsEntry = JSON.stringify(normalizeEntry(docs.entry));\n  const reconcileHeadRuntime = `const farmNavigationHeadSelector=${JSON.stringify(FARM_NAVIGATION_HEAD_SELECTOR)};const reconcileDocsHead=(nextDoc)=>{const nextTitle=nextDoc.querySelector(\"title\");document.title=nextTitle?.textContent||\"\";document.head.querySelectorAll(farmNavigationHeadSelector).forEach((node)=>node.remove());nextDoc.head.querySelectorAll(farmNavigationHeadSelector).forEach((node)=>document.head.appendChild(document.importNode(node,true)))}`;\n  return `<script>(()=>{if(window.__farmDocsRuntime)return;window.__farmDocsRuntime=true;document.documentElement.dataset.farmDocsRuntime=\"true\";document.documentElement.dataset.farmDocsRuntimeId=Math.random().toString(36).slice(2);${reconcileHeadRuntime};const docsEntry=${docsEntry};let cleanupToc=()=>{};let closeMobileSidebar=()=>{};const normalizePath=(path)=>path.length>1?path.replace(/\\\\/+$/,\"\"):path;const isDocsPath=(path)=>{const next=normalizePath(path);const entry=normalizePath(docsEntry);if(next.endsWith(\".md\"))return false;if(entry===\"/\")return true;return next===entry||next.startsWith(entry+\"/\")};const initToc=()=>{cleanupToc();const toc=document.getElementById(\"nd-toc\");if(!toc){cleanupToc=()=>{};return}const links=Array.from(toc.querySelectorAll(\"[data-toc-item]\"));const thumb=toc.querySelector(\"[data-toc-thumb]\");const pairs=links.map((link)=>{let id=link.hash.slice(1);try{id=decodeURIComponent(id)}catch{}return{link,heading:document.getElementById(id)}}).filter((item)=>item.heading);const setActive=(active)=>{for(const {link} of pairs){const selected=link===active.link;link.dataset.active=selected?\"true\":\"false\";link.classList.toggle(\"fd-toc-link-active\",selected)}if(!thumb)return;const styles=getComputedStyle(active.link);const top=active.link.offsetTop+parseFloat(styles.paddingTop||\"0\");const bottom=active.link.offsetTop+active.link.clientHeight-parseFloat(styles.paddingBottom||\"0\");thumb.style.clipPath=\"polygon(0 \"+top+\"px,100% \"+top+\"px,100% \"+bottom+\"px,0 \"+bottom+\"px)\"};const update=()=>{if(pairs.length===0)return;const offset=Math.min(window.innerHeight*0.3,160);let active=pairs[0];for(const pair of pairs){if(pair.heading.getBoundingClientRect().top<=offset)active=pair;else break}setActive(active)};let frame=0;const schedule=()=>{if(frame)return;frame=requestAnimationFrame(()=>{frame=0;update()})};const onHashChange=()=>setTimeout(schedule,0);window.addEventListener(\"scroll\",schedule,{passive:true});window.addEventListener(\"resize\",schedule);window.addEventListener(\"hashchange\",onHashChange);cleanupToc=()=>{window.removeEventListener(\"scroll\",schedule);window.removeEventListener(\"resize\",schedule);window.removeEventListener(\"hashchange\",onHashChange);if(frame)cancelAnimationFrame(frame);frame=0};update()};const getSidebar=()=>document.getElementById(\"nd-sidebar\");const ensureActiveVisible=()=>{const sidebar=getSidebar();if(!sidebar)return;const active=sidebar.querySelector('a[data-active=\"true\"]');if(!(active instanceof HTMLElement))return;const activeRect=active.getBoundingClientRect();const sidebarRect=sidebar.getBoundingClientRect();if(activeRect.top<sidebarRect.top||activeRect.bottom>sidebarRect.bottom)sidebar.scrollTop+=activeRect.top-sidebarRect.top-(sidebar.clientHeight-activeRect.height)/2};const setSidebarActive=(path)=>{const sidebar=getSidebar();if(!sidebar)return;const current=normalizePath(path);for(const link of Array.from(sidebar.querySelectorAll(\"a[href]\"))){try{link.dataset.active=normalizePath(new URL(link.href,location.href).pathname)===current?\"true\":\"false\"}catch{}}ensureActiveVisible()};const initMobileSidebar=()=>{const layout=document.getElementById(\"nd-docs-layout\");const sidebar=getSidebar();const toggle=document.querySelector(\"[data-sidebar-toggle]\");const backdrop=document.querySelector(\"[data-sidebar-backdrop]\");if(!layout||!sidebar||!(toggle instanceof HTMLButtonElement))return;const setOpen=(open)=>{layout.dataset.sidebarOpen=open?\"true\":\"false\";sidebar.classList.toggle(\"fd-sidebar-open\",open);document.documentElement.dataset.farmDocsSidebar=open?\"open\":\"closed\";toggle.setAttribute(\"aria-expanded\",open?\"true\":\"false\");toggle.setAttribute(\"aria-label\",open?\"Close menu\":\"Open menu\")};const toggleOpen=()=>setOpen(layout.dataset.sidebarOpen!==\"true\");closeMobileSidebar=()=>setOpen(false);toggle.addEventListener(\"click\",(event)=>{event.preventDefault();toggleOpen()});backdrop?.addEventListener(\"click\",()=>closeMobileSidebar());document.addEventListener(\"keydown\",(event)=>{if(event.key===\"Escape\")closeMobileSidebar()});sidebar.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(target)closeMobileSidebar()});closeMobileSidebar()};const initSidebarScroll=()=>{const sidebar=getSidebar();if(!sidebar)return;const key=\"farmdocs:sidebar-scroll:\"+location.origin;const getStorage=()=>{try{return window.sessionStorage}catch{return null}};const readSaved=()=>{try{const raw=getStorage()?.getItem(key);if(!raw)return null;const parsed=JSON.parse(raw);return parsed&&typeof parsed===\"object\"?parsed:null}catch{return null}};const save=(path=location.pathname)=>{try{getStorage()?.setItem(key,JSON.stringify({path,scrollTop:sidebar.scrollTop}))}catch{}};const saved=readSaved();if(saved?.path===location.pathname&&Number.isFinite(Number(saved.scrollTop)))sidebar.scrollTop=Number(saved.scrollTop);ensureActiveVisible();save();sidebar.addEventListener(\"scroll\",()=>save(),{passive:true});sidebar.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(!target)return;try{save(new URL(target.href,location.href).pathname)}catch{save()}});window.addEventListener(\"beforeunload\",()=>save())};let navigateController=null;const getPageKey=(root)=>{const article=root.getElementById(\"nd-page\");if(!article)return\"\";return article.querySelector(\"h1\")?.textContent?.trim()||article.textContent?.replace(/\\\\s+/g,\" \").trim().slice(0,160)||\"\"};const swapDocsPage=(html,url)=>{const nextDoc=new DOMParser().parseFromString(html,\"text/html\");const nextArticle=nextDoc.getElementById(\"nd-page\");const currentArticle=document.getElementById(\"nd-page\");if(!nextArticle||!currentArticle)return false;const nextKey=getPageKey(nextDoc);const importedArticle=document.importNode(nextArticle,true);currentArticle.replaceWith(importedArticle);const renderedArticle=document.getElementById(\"nd-page\");if(!renderedArticle||renderedArticle===currentArticle||(nextKey&&getPageKey(document)!==nextKey))return false;const nextToc=nextDoc.getElementById(\"nd-toc\");const currentToc=document.getElementById(\"nd-toc\");if(nextToc&&currentToc)currentToc.replaceWith(document.importNode(nextToc,true));reconcileDocsHead(nextDoc);setSidebarActive(url.pathname);initToc();closeMobileSidebar();return true};const navigateDocs=async(url,{replace=false,scroll=true}={})=>{if(!isDocsPath(url.pathname))return false;if(navigateController)navigateController.abort();const controller=new AbortController();navigateController=controller;document.documentElement.dataset.farmDocsNavigating=\"true\";try{const response=await fetch(url.href,{cache:\"no-store\",headers:{accept:\"text/html\",\"x-farm-docs-navigate\":\"1\"},signal:controller.signal});if(!response.ok||!((response.headers.get(\"content-type\")||\"\").includes(\"text/html\")))return false;const html=await response.text();if(!swapDocsPage(html,url))return false;if(replace)history.replaceState({farmDocs:true},\"\",url.href);else history.pushState({farmDocs:true},\"\",url.href);if(scroll){if(url.hash){let id=url.hash.slice(1);try{id=decodeURIComponent(id)}catch{}document.getElementById(id)?.scrollIntoView({block:\"start\"})}else window.scrollTo({top:0,left:0})}return true}catch(error){if(error?.name===\"AbortError\")return true;return false}finally{if(navigateController===controller){delete document.documentElement.dataset.farmDocsNavigating;navigateController=null}}};const initClientNavigation=()=>{document.addEventListener(\"click\",(event)=>{if(event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(!target||target.target||target.hasAttribute(\"download\"))return;let url;try{url=new URL(target.href,location.href)}catch{return}if(url.origin!==location.origin||!isDocsPath(url.pathname))return;if(normalizePath(url.pathname)===normalizePath(location.pathname)&&url.hash)return;event.preventDefault();navigateDocs(url).then((handled)=>{if(!handled)location.href=url.href})});window.addEventListener(\"popstate\",()=>{navigateDocs(new URL(location.href),{replace:true,scroll:false}).then((handled)=>{if(!handled)location.reload()})})};const init=()=>{initToc();initMobileSidebar();initSidebarScroll();initClientNavigation()};if(document.readyState===\"loading\")document.addEventListener(\"DOMContentLoaded\",init,{once:true});else init()})();</script>`;\n}\n\nfunction renderDocsPageActionsRuntimeScript(): string {\n  return `<script>(()=>{if(window.__farmDocsPageActionsRuntime)return;window.__farmDocsPageActionsRuntime=true;const readArticleText=()=>{const article=document.getElementById(\"nd-page\");if(!article)return\"\";const clone=article.cloneNode(true);if(!(clone instanceof HTMLElement))return article.innerText||\"\";clone.querySelectorAll(\"[data-page-actions],.fd-page-footer,.fd-page-nav\").forEach((node)=>node.remove());return clone.innerText||\"\"};const withTitle=(content,format,includeTitle)=>{if(!includeTitle)return content;const title=document.querySelector(\"#nd-page h1\")?.textContent?.trim()||document.title.trim();if(!title)return content;const trimmed=content.trimStart();if(trimmed.startsWith(title)||trimmed.startsWith(\"# \"+title))return content;return format===\"markdown\"?\"# \"+title+\"\\\\n\\\\n\"+content:title+\"\\\\n\\\\n\"+content};const writeClipboard=async(text)=>{if(navigator.clipboard?.writeText){try{await navigator.clipboard.writeText(text);return}catch{}}const textarea=document.createElement(\"textarea\");textarea.value=text;textarea.setAttribute(\"readonly\",\"\");textarea.style.position=\"fixed\";textarea.style.opacity=\"0\";textarea.style.pointerEvents=\"none\";document.body.appendChild(textarea);textarea.select();document.execCommand(\"copy\");textarea.remove()};const markCopied=(button)=>{const label=button.querySelector(\"[data-page-action-label]\");button.dataset.copied=\"true\";button.setAttribute(\"aria-label\",button.dataset.copiedLabel||\"Copied!\");button.title=button.dataset.copiedLabel||\"Copied!\";if(label)label.textContent=button.dataset.copiedLabel||\"Copied!\";const previous=Number(button.dataset.copyTimeout||0);if(previous)clearTimeout(previous);button.dataset.copyTimeout=String(setTimeout(()=>{button.dataset.copied=\"false\";button.setAttribute(\"aria-label\",button.dataset.copyLabel||\"Copy page\");button.title=button.dataset.copyLabel||\"Copy page\";if(label)label.textContent=button.dataset.copyLabel||\"Copy page\";button.dataset.copyTimeout=\"0\"},4500))};document.addEventListener(\"click\",async(event)=>{const target=event.target instanceof Element?event.target.closest('[data-page-action=\"copy-markdown\"]'):null;if(!(target instanceof HTMLButtonElement))return;event.preventDefault();const format=target.dataset.copyMarkdownFormat===\"text\"?\"text\":\"markdown\";const includeTitle=target.dataset.copyMarkdownIncludeTitle===\"true\";let content=\"\";target.disabled=true;try{if(format===\"markdown\"&&target.dataset.markdownUrl){try{const response=await fetch(target.dataset.markdownUrl,{headers:{Accept:\"text/markdown\"}});if(response.ok)content=await response.text()}catch{}}if(!content)content=readArticleText();content=withTitle(content,format,includeTitle);if(content.trim()){await writeClipboard(content);markCopied(target)}}finally{target.disabled=false}})})();</script>`;\n}\n\nfunction renderDocsHashRuntimeScript(): string {\n  return `<script>(()=>{if(window.__farmDocsHashRuntime)return;window.__farmDocsHashRuntime=true;const scrollToHash=()=>{if(!location.hash)return;let id=location.hash.slice(1);try{id=decodeURIComponent(id)}catch{}document.getElementById(id)?.scrollIntoView({block:\"start\"})};const schedule=()=>requestAnimationFrame(()=>requestAnimationFrame(scrollToHash));if(document.readyState===\"loading\")document.addEventListener(\"DOMContentLoaded\",schedule,{once:true});else schedule();window.addEventListener(\"load\",schedule,{once:true});window.addEventListener(\"hashchange\",schedule)})();</script>`;\n}\n\nfunction renderDocsRuntimeScripts(docs: FarmDocsResolvedConfig): string {\n  return `${renderDocsRuntimeScript(docs)}\n${renderDocsHashRuntimeScript()}\n${renderDocsPageActionsRuntimeScript()}`;\n}\n\nfunction renderFarmDocsFontPreloads(fontAssets: readonly FarmDocsPublicFontAsset[]): string {\n  return fontAssets\n    .map(\n      ({ url }) =>\n        `<link rel=\"preload\" href=\"${escapeAttribute(url)}\" as=\"font\" type=\"font/woff2\" crossorigin>`,\n    )\n    .join(\"\\n  \");\n}\n\nfunction renderFarmDocsFontPreloadHeader(fontAssets: readonly FarmDocsPublicFontAsset[]): string {\n  return fontAssets\n    .map(({ url }) => `<${url}>; rel=preload; as=font; type=font/woff2; crossorigin`)\n    .join(\", \");\n}\n\nfunction getFarmLayoutFontPreloads(layoutFonts?: FarmLayoutFonts) {\n  const seen = new Set<string>();\n  return [layoutFonts?.body, layoutFonts?.code].flatMap((font) =>\n    (font?.preloads || []).filter(({ href }) => {\n      if (seen.has(href)) return false;\n      seen.add(href);\n      return true;\n    }),\n  );\n}\n\nfunction renderFarmLayoutFontPreloadHeader(layoutFonts?: FarmLayoutFonts): string {\n  return getFarmLayoutFontPreloads(layoutFonts)\n    .map(({ href, type }) => `<${href}>; rel=preload; as=font; type=${type}; crossorigin`)\n    .join(\", \");\n}\n\nfunction renderPixelDocsHtml(\n  page: LoadedFarmDocsPage,\n  pages: FarmDocsPage[],\n  docs: FarmDocsResolvedConfig,\n  clientEntry: string,\n  faviconHref: string,\n  requestUrl: URL,\n  fontAssets: readonly FarmDocsPublicFontAsset[],\n  fontStylesheetHref?: string,\n  globalStylesheetHref?: string,\n): string {\n  const navTitle =\n    typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n      ? String((docs.config.nav as { title?: unknown }).title || \"Docs\")\n      : \"Docs\";\n  const description = page.description || docs.config.metadata?.description || \"\";\n  const tocItems = extractTocItems(page.body, getThemeTocDepth(docs));\n  const themeName = getThemeName(docs);\n  const searchEnabled = isFarmDocsSearchEnabled(docs);\n  const socialMetadata = isFarmDocsSocialImageEnabled(page, docs)\n    ? renderFarmDocsSocialMetadata(\n        createFarmDocsSocialImageDescriptor(page, docs, requestUrl),\n        getFarmDocsCustomSocialImage(page),\n      )\n    : \"\";\n\n  return `<!DOCTYPE html>\n<html class=\"dark\" lang=\"en\" data-docs-theme=\"${escapeAttribute(themeName)}\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"generator\" content=\"@farming-labs/docs via Farm.js\">\n  <title>${escapeHtml(page.title)}</title>\n  ${renderFarmDocsFaviconLink(faviconHref)}\n  ${renderFarmDocsFontPreloads(fontAssets)}\n  ${fontStylesheetHref ? `<link rel=\"stylesheet\" href=\"${escapeAttribute(fontStylesheetHref)}\">` : \"\"}\n  ${globalStylesheetHref ? `<link rel=\"stylesheet\" href=\"${escapeAttribute(globalStylesheetHref)}\">` : \"\"}\n  ${description ? `<meta name=\"description\" content=\"${escapeHtml(description)}\">` : \"\"}\n  ${socialMetadata}\n  ${searchEnabled ? renderDocsSearchBootstrapScript() : \"\"}\n</head>\n<body>\n  <div id=\"nd-docs-layout\" class=\"fd-layout\" data-fd-framework=\"farmjs\">\n    <header class=\"mobile-topbar fd-header\" aria-label=\"Mobile docs navigation\">\n      <button class=\"fd-mobile-nav-btn fd-menu-btn\" type=\"button\" data-sidebar-toggle aria-controls=\"nd-sidebar\" aria-expanded=\"false\" aria-label=\"Open menu\">\n        <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><line x1=\"3\" y1=\"6\" x2=\"21\" y2=\"6\"></line><line x1=\"3\" y1=\"12\" x2=\"21\" y2=\"12\"></line><line x1=\"3\" y1=\"18\" x2=\"21\" y2=\"18\"></line></svg>\n      </button>\n      <a class=\"fd-header-title\" href=\"/\">${escapeHtml(navTitle)}</a>\n      <div class=\"mobile-topbar-actions\">\n        ${searchEnabled ? renderDocsSearchTrigger(true, \"fd-search-trigger-mobile\") : \"\"}\n        <a class=\"mobile-topbar-link\" href=\"/llms.txt\">llms.txt</a>\n      </div>\n    </header>\n    <aside id=\"nd-sidebar\" class=\"fd-sidebar\">\n      <div class=\"sidebar-brand fd-sidebar-header\">\n        <a class=\"fd-sidebar-title\" href=\"/\">${renderFarmDocsBrandMark()}${renderFarmDocsBrandTitle(navTitle)}</a>\n        <span>/ docs</span>\n      </div>\n      ${searchEnabled ? `<div class=\"fd-sidebar-search\">${renderDocsSearchTrigger(true, \"fd-sidebar-search-btn\")}</div>` : \"\"}\n      ${renderPixelNavItems(pages, page.href, docs)}\n    </aside>\n    <div class=\"sidebar-backdrop fd-sidebar-overlay\" data-sidebar-backdrop></div>\n    <main class=\"fd-main\">\n      <div class=\"fd-page\">\n      <article id=\"nd-page\" class=\"prose fd-page-article fd-page-body fd-docs-content\">\n        ${renderPixelBreadcrumb(page, docs)}\n${renderMarkdownHtmlWithTitleMeta(page, docs)}\n        ${renderPixelPageFooter(page, docs)}\n        ${renderPixelPageNav(pages, page.href, docs)}\n      </article>\n      <nav id=\"nd-toc\" class=\"fd-toc sticky top-(--fd-docs-row-1) h-[calc(var(--fd-docs-height)-var(--fd-docs-row-1))] flex flex-col [grid-area:toc] w-(--fd-toc-width) pt-12 pe-4 pb-2 max-xl:hidden\" data-toc aria-labelledby=\"toc-title\">\n      <div class=\"fd-toc-inner\">\n        <h3 id=\"toc-title\" class=\"fd-toc-title inline-flex items-center gap-1.5 text-sm text-fd-muted-foreground\"><svg class=\"size-4\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 7h16\"></path><path d=\"M4 12h16\"></path><path d=\"M4 17h16\"></path></svg>On this page</h3>\n        <div class=\"toc-scroll\">\n          ${renderPixelToc(tocItems)}\n        </div>\n      </div>\n    </nav>\n      </div>\n    </main>\n  </div>\n  ${searchEnabled ? renderDocsSearchMount(clientEntry) : \"\"}\n  ${renderDocsRuntimeScripts(docs)}\n</body>\n</html>`;\n}\n\nexport function createFarmDocsHandler(\n  docs: FarmDocsResolvedConfig | undefined,\n  options: FarmDocsHandlerOptions,\n) {\n  const faviconHref = resolveFarmDocsFavicon(docs, options);\n  const fontAssets =\n    options.fontAssets ?? toFarmDocsPublicFontAssets(resolveFarmDocsFontAssets(options.root));\n  const fallbackFontPreloadHeader = renderFarmDocsFontPreloadHeader(fontAssets);\n\n  return async function handleFarmDocsRequest(request: Request): Promise<Response | null> {\n    if (!docs?.enabled || (request.method !== \"GET\" && request.method !== \"HEAD\")) return null;\n\n    const contentDir = resolveFarmDocsContentDir(docs, options);\n    const requestUrl = new URL(request.url);\n    const socialImageSlug = getFarmDocsSocialImageSlug(docs, requestUrl);\n    if (socialImageSlug !== null) {\n      const socialImagePage = loadFarmDocsPage(contentDir, docs, socialImageSlug);\n      if (\n        !socialImagePage ||\n        !isFarmDocsSocialImageEnabled(socialImagePage, docs) ||\n        getFarmDocsCustomSocialImage(socialImagePage)\n      ) {\n        return null;\n      }\n\n      const descriptor = createFarmDocsSocialImageDescriptor(socialImagePage, docs, requestUrl);\n      if (requestUrl.pathname !== descriptor.imagePath) return null;\n\n      const etag = `\"${descriptor.hash}\"`;\n      const immutable = requestUrl.searchParams.get(\"v\") === descriptor.hash;\n      const headers = new Headers({\n        \"Content-Type\": \"image/svg+xml; charset=utf-8\",\n        \"Cache-Control\": immutable\n          ? \"public, max-age=31536000, immutable\"\n          : \"public, max-age=0, must-revalidate\",\n        ETag: etag,\n        \"X-Content-Type-Options\": \"nosniff\",\n      });\n      if (matchesFarmIfNoneMatch(request.headers.get(\"if-none-match\"), etag)) {\n        return new Response(null, { status: 304, headers });\n      }\n      if (request.method === \"HEAD\") return new Response(null, { status: 200, headers });\n\n      return new Response(renderFarmDocsSocialImageSvg(descriptor), { status: 200, headers });\n    }\n\n    const publicResponse = createFarmDocsPublicResponse(contentDir, docs, request);\n    if (publicResponse) return omitFarmDocsHeadBody(request, publicResponse);\n\n    if (!isFarmDocsRequest(docs, request)) return null;\n\n    const page = loadPage(contentDir, docs, request);\n    if (!page) return null;\n\n    if (shouldReturnMarkdown(request)) {\n      const origin = new URL(request.url).origin;\n      return omitFarmDocsHeadBody(\n        request,\n        new Response(\n          renderDocsMarkdownDocument(toFarmDocsMarkdownPage(page), {\n            origin,\n            llms: docs.config.llmsTxt ?? true,\n            sitemap: docs.config.sitemap,\n          }),\n          {\n            status: 200,\n            headers: {\n              \"Content-Type\": \"text/markdown; charset=utf-8\",\n              \"Cache-Control\": \"public, max-age=60\",\n            },\n          },\n        ),\n      );\n    }\n\n    const pathname = new URL(request.url).pathname;\n    const layoutFonts = await options.resolveLayoutFonts?.(pathname);\n    const usesLayoutFonts = Boolean(layoutFonts?.body || layoutFonts?.code);\n    const activeFontAssets = usesLayoutFonts ? [] : fontAssets;\n    const fontPreloadHeader = usesLayoutFonts\n      ? renderFarmLayoutFontPreloadHeader(layoutFonts)\n      : fallbackFontPreloadHeader;\n\n    return omitFarmDocsHeadBody(\n      request,\n      new Response(\n        renderPixelDocsHtml(\n          page,\n          discoverFarmDocsPages(contentDir, docs),\n          docs,\n          options.clientEntry || \"/farm-client.js\",\n          faviconHref,\n          requestUrl,\n          activeFontAssets,\n          usesLayoutFonts ? options.fontStylesheetHref : undefined,\n          options.globalStylesheetHref,\n        ),\n        {\n          status: 200,\n          headers: {\n            \"Content-Type\": \"text/html; charset=utf-8\",\n            \"Cache-Control\": \"public, s-maxage=60, stale-while-revalidate=300\",\n            ...(fontPreloadHeader ? { Link: fontPreloadHeader } : {}),\n          },\n        },\n      ),\n    );\n  };\n}\n","import type { FarmLayoutFonts } from \"../font\";\nimport { resolveFarmDocsContentDir } from \"./handler\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\ninterface FarmDocsAdapterServerModule {\n  createFarmDocsRuntimeHandler?: (\n    config: Record<string, unknown>,\n    options: {\n      rootDir: string;\n      clientEntry: string;\n      stylesheets: string[];\n      resolveLayoutFonts?: (\n        pathname: string,\n      ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n      loadReactModule?: () => Promise<any>;\n    },\n  ) => (request: Request) => Promise<Response | null>;\n}\n\nexport interface FarmDocsAdapterHandlerOptions {\n  root: string;\n  srcDir?: string;\n  clientEntry: string;\n  fontStylesheetHref?: string;\n  globalStylesheetHref?: string;\n  resolveLayoutFonts?: (\n    pathname: string,\n  ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n  loadModule: (specifier: string) => Promise<any>;\n}\n\nexport function hasFarmDocsRuntimeAdapter(\n  docs: FarmDocsResolvedConfig | undefined,\n): docs is FarmDocsResolvedConfig & { adapter: NonNullable<FarmDocsResolvedConfig[\"adapter\"]> } {\n  return Boolean(docs?.enabled && docs.adapter?.server && docs.adapter.react);\n}\n\n/**\n * Load a documentation runtime through the versioned adapter descriptor.\n *\n * Core deliberately knows nothing about the adapter's DOM or theme. It only\n * supplies host assets and Vite's module loader; the adapter returns the final\n * Web Request handler.\n */\nexport async function createFarmDocsAdapterHandler(\n  docs: FarmDocsResolvedConfig,\n  options: FarmDocsAdapterHandlerOptions,\n): Promise<(request: Request) => Promise<Response | null>> {\n  if (!hasFarmDocsRuntimeAdapter(docs)) {\n    throw new Error(\"Farm docs adapter requires server and react runtime entrypoints.\");\n  }\n\n  const serverModule = (await options.loadModule(\n    docs.adapter.server,\n  )) as FarmDocsAdapterServerModule;\n  if (typeof serverModule.createFarmDocsRuntimeHandler !== \"function\") {\n    const adapterId = JSON.stringify(docs.adapter.id);\n    const serverEntry = JSON.stringify(docs.adapter.server);\n    throw new Error(\n      `Farm docs adapter ${adapterId} does not export createFarmDocsRuntimeHandler from ${serverEntry}. ` +\n        \"Upgrade the adapter to a runtime-enabled release.\",\n    );\n  }\n\n  const runtimeConfig = {\n    ...docs.config,\n    entry: docs.config.entry || docs.entry.replace(/^\\/+|\\/+$/g, \"\") || \"docs\",\n    docsPath: docs.entry,\n    contentDir: resolveFarmDocsContentDir(docs, {\n      root: options.root,\n      srcDir: options.srcDir,\n    }),\n  };\n\n  return serverModule.createFarmDocsRuntimeHandler(runtimeConfig as Record<string, unknown>, {\n    rootDir: options.root,\n    clientEntry: options.clientEntry,\n    stylesheets: [options.fontStylesheetHref, options.globalStylesheetHref].filter(\n      (value): value is string => typeof value === \"string\" && value.length > 0,\n    ),\n    resolveLayoutFonts: options.resolveLayoutFonts,\n    loadReactModule: () => options.loadModule(docs.adapter.react!),\n  });\n}\n","import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmDocsAdapterDescriptor, FarmDocsUserConfig } from \"./types\";\n\nconst FRAMEWORK_PACKAGE = \"@farming-labs/farmjs\";\nconst FRAMEWORK_CONFIG_ENTRY = \"@farming-labs/farmjs/config\";\n\n/**\n * The adapter descriptor protocol this core release knows how to drive.\n * Auto-detection must never wire up a descriptor from a future framework\n * release that this core cannot interpret; explicit withDocs() usage stays\n * the user's own call.\n */\nconst SUPPORTED_ADAPTER_PROTOCOL = 1;\n\nexport interface FarmDocsFrameworkDetectionOptions {\n  root: string;\n  log?: (message: string) => void;\n  warn?: (message: string) => void;\n}\n\n/**\n * Delegation triggers only for a dependency the app declared itself. A copy\n * that is merely resolvable through hoisting or a transitive dependency must\n * not silently change how the app's docs are served.\n */\nasync function frameworkDeclaredByApp(root: string): Promise<boolean> {\n  try {\n    const raw = await readFile(path.join(root, \"package.json\"), \"utf8\");\n    const manifest = JSON.parse(raw) as Record<string, unknown>;\n    for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n      const section = manifest[field];\n      if (section && typeof section === \"object\" && FRAMEWORK_PACKAGE in section) {\n        return true;\n      }\n    }\n  } catch {\n    // Unreadable manifest: treat as not declared and keep the embedded renderer.\n  }\n  return false;\n}\n\nconst emittedNotices = new Set<string>();\n\n/** Test hook: notices are once-per-process so dev-server restarts stay quiet. */\nexport function resetFarmDocsFrameworkDetectionNotices(): void {\n  emittedNotices.clear();\n}\n\nfunction noticeOnce(key: string, emit: (message: string) => void, message: string): void {\n  if (emittedNotices.has(key)) return;\n  emittedNotices.add(key);\n  emit(message);\n}\n\nfunction docsWantsFrameworkDetection(docs: FarmDocsUserConfig | undefined): boolean {\n  if (docs === true) return true;\n  if (!docs || typeof docs !== \"object\") return false;\n  if (docs.enabled === false) return false;\n  // An explicit descriptor means the app already wired an adapter; an\n  // explicit `false` is the opt-out that pins the embedded renderer.\n  if (docs.adapter !== undefined) return false;\n  return true;\n}\n\nfunction isSupportedAdapterDescriptor(value: unknown): value is FarmDocsAdapterDescriptor {\n  if (!value || typeof value !== \"object\") return false;\n  const descriptor = value as Partial<FarmDocsAdapterDescriptor>;\n  return (\n    descriptor.protocol === SUPPORTED_ADAPTER_PROTOCOL &&\n    typeof descriptor.server === \"string\" &&\n    descriptor.server.length > 0 &&\n    typeof descriptor.react === \"string\" &&\n    descriptor.react.length > 0\n  );\n}\n\n/**\n * Delegate `docs: {}` to the @farming-labs/farmjs docs framework when the app\n * has it installed (#483 phase 1).\n *\n * Detection applies the framework's own withDocs() to the user config, so the\n * result is byte-for-byte what a manual `withDocs(defineConfig(...))` produces:\n * the MDX Vite plugin plus the versioned adapter descriptor. When the package\n * is absent the embedded renderer keeps serving, with a one-time migration\n * notice. Any failure falls back to the embedded renderer instead of breaking\n * a working app.\n */\nexport async function applyFarmDocsFrameworkAutoDetection<\n  T extends { docs?: FarmDocsUserConfig; vite?: unknown },\n>(userConfig: T, options: FarmDocsFrameworkDetectionOptions): Promise<T> {\n  if (!docsWantsFrameworkDetection(userConfig.docs)) return userConfig;\n\n  const log = options.log ?? ((message: string) => console.log(message));\n  const warn = options.warn ?? ((message: string) => console.warn(message));\n  const root = path.resolve(options.root || process.cwd());\n\n  if (!(await frameworkDeclaredByApp(root))) {\n    noticeOnce(\n      \"embedded-fallback\",\n      warn,\n      `[farm] docs is served by the embedded renderer, which is being replaced by the ${FRAMEWORK_PACKAGE} docs framework. ` +\n        `Install ${FRAMEWORK_PACKAGE} (with @farming-labs/docs and @farming-labs/theme) to migrate now, ` +\n        \"or set docs.adapter = false to keep the embedded renderer and silence this notice.\",\n    );\n    return userConfig;\n  }\n\n  let configEntryPath: string;\n  try {\n    const requireFromApp = createRequire(path.join(root, \"package.json\"));\n    configEntryPath = requireFromApp.resolve(FRAMEWORK_CONFIG_ENTRY);\n  } catch {\n    noticeOnce(\n      \"declared-not-installed\",\n      warn,\n      `[farm] ${FRAMEWORK_PACKAGE} is declared in package.json but could not be resolved; ` +\n        \"keeping the embedded docs renderer. Run your package manager's install to enable docs delegation.\",\n    );\n    return userConfig;\n  }\n\n  try {\n    const frameworkConfig = await import(/* @vite-ignore */ pathToFileURL(configEntryPath).href);\n    const withDocs = frameworkConfig?.withDocs;\n    if (typeof withDocs !== \"function\") {\n      noticeOnce(\n        \"missing-withdocs\",\n        warn,\n        `[farm] ${FRAMEWORK_CONFIG_ENTRY} does not export withDocs(); keeping the embedded docs renderer.`,\n      );\n      return userConfig;\n    }\n\n    const applied = withDocs(userConfig);\n    const adapter = (applied as { docs?: { adapter?: unknown } } | undefined)?.docs?.adapter;\n    if (!isSupportedAdapterDescriptor(adapter)) {\n      noticeOnce(\n        \"unsupported-descriptor\",\n        warn,\n        `[farm] The installed ${FRAMEWORK_PACKAGE} release publishes a docs adapter this Farm version cannot drive ` +\n          `(need protocol ${SUPPORTED_ADAPTER_PROTOCOL}); keeping the embedded docs renderer. ` +\n          \"Upgrading @farm.js/core usually resolves this.\",\n      );\n      return userConfig;\n    }\n\n    noticeOnce(\n      \"delegated\",\n      log,\n      `[farm] docs: delegated to ${FRAMEWORK_PACKAGE} (detected in this app). ` +\n        \"Set docs.adapter = false to keep the embedded renderer.\",\n    );\n    return applied as T;\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    noticeOnce(\n      \"detect-failed\",\n      warn,\n      `[farm] Failed to load ${FRAMEWORK_CONFIG_ENTRY} (${message}); keeping the embedded docs renderer.`,\n    );\n    return userConfig;\n  }\n}\n","import type { FarmUserConfig } from \"./config\";\n\n/** Define a Farm application config while preserving literal types. */\nexport function defineConfig<const TConfig extends FarmUserConfig>(config: TConfig): TConfig {\n  return config;\n}\n\n/** @deprecated Use {@link defineConfig}. */\nexport const defineFarmConfig = defineConfig;\n\nexport type { FarmUserConfig };\n","import type {\n  FarmConfig as BaseFarmConfig,\n  FarmMigrationCommand,\n  FarmMigrationsConfig,\n  FarmMigrationsUserConfig,\n  ResolvedFarmMigrationsConfig,\n} from \"./types\";\nimport type { DocsConfig } from \"@farming-labs/docs\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./docs/types\";\nimport type { FarmIntegrationsUserConfig } from \"./integrations\";\nimport type { FarmMarkdownResolvedConfig, FarmMarkdownUserConfig } from \"./markdown\";\nimport type { FarmObservabilityUserConfig } from \"./observability\";\nimport type { FarmMiddlewareConfig } from \"./middleware/types\";\nimport type { FarmPlugin } from \"./plugin\";\nimport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nimport type { FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nimport type { FarmEnvConfig, ResolvedFarmEnv } from \"./env\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport { resolveIntegrationPlugins } from \"./integrations\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig } from \"./workflows\";\nimport { resolveCronConfig } from \"./cron\";\nimport { resolveEnv, setEnv } from \"./env\";\nimport {\n  resolveMdxConfig,\n  type FarmMdxResolvedConfig,\n  type FarmMdxUserConfig,\n} from \"./app-markdown-config\";\nimport {\n  normalizeRouteRules,\n  routeRulesToHeaders,\n  routeRulesToRedirects,\n  type FarmRouteRules,\n} from \"./route-rules\";\nimport {\n  resolveServerActionsConfig,\n  type FarmServerActionsConfig,\n  type ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nimport {\n  resolveFarmServerConfig,\n  type FarmServerConfig,\n  type ResolvedFarmServerConfig,\n} from \"./server-http\";\nimport {\n  loadFarmConfigFile,\n  resolveFarmLayers,\n  type FarmLayerEntry,\n  type ResolvedFarmLayer,\n} from \"./layers\";\nimport path from \"path\";\nimport { logger } from \"./utils\";\nimport { normalizeFarmDeploymentId } from \"./deployment\";\nimport { normalizeFarmConfigBasePath } from \"./base-path\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n  resolveFarmDevIndicatorsConfig,\n  type FarmDevIndicatorsConfig,\n  type ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nimport {\n  resolveFarmImageConfig,\n  type FarmImageConfig,\n  type ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport type { FarmI18nUserConfig, ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport type { FarmCacheUserConfig } from \"./cache\";\nimport {\n  resolveFarmAuthConfig,\n  resolveFarmAuthIntegration,\n  type FarmAuthUserConfig,\n  type ResolvedFarmAuthConfig,\n} from \"./auth-config\";\nimport { resolveFarmPerformanceConfig, type ResolvedFarmPerformanceConfig } from \"./preload\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  getFarmSecurityHeader,\n  resolveFarmSecurityConfig,\n  type FarmCspConfig,\n  type FarmCspDirectives,\n  type FarmCspDirectiveValue,\n  type FarmCspOptions,\n  type FarmSecurityConfig,\n  type ResolvedFarmCspConfig,\n  type ResolvedFarmSecurityConfig,\n} from \"./security\";\nimport { isFarmRedirectStatus } from \"./navigation-errors\";\nimport { resolveFarmThemeConfig } from \"./theme/config\";\nimport { resolveFarmAgentConfig, type ResolvedFarmAgentConfig } from \"./agent-config\";\nimport type { ResolvedFarmThemeConfig } from \"./theme/types\";\nimport { isReactRenderer, resolveFarmRenderer } from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { applyFarmDocsFrameworkAutoDetection } from \"./docs/framework-detect\";\nimport { resolveFarmAPIConfig, type ResolvedFarmAPIConfig } from \"./api/config\";\n\nconst FARM_RESOLVED_CUSTOM_CONTEXT = Symbol.for(\"farm.resolvedCustomContext\");\n\nexport type {\n  FarmDocsConfigInput,\n  FarmDocsNavigationConfig,\n  FarmDocsResolvedConfig,\n  FarmDocsSidebarItem,\n  FarmDocsUserConfig,\n} from \"./docs/types\";\nexport type {\n  FarmMarkdownResolvedConfig,\n  FarmMarkdownRouteInput,\n  FarmMarkdownUserConfig,\n} from \"./markdown\";\nexport type {\n  FarmMdxComponents,\n  FarmMdxResolvedConfig,\n  FarmMdxUserConfig,\n} from \"./app-markdown-config\";\nexport type {\n  FarmMigrationCommand,\n  FarmMigrationsConfig,\n  FarmMigrationsUserConfig,\n  ResolvedFarmMigrationsConfig,\n} from \"./types\";\nexport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nexport type { FarmCronJobConfig, FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nexport type {\n  FarmRouteRule,\n  FarmRouteRuleCors,\n  FarmRouteRuleRedirect,\n  FarmRouteRuleRenderMode,\n  FarmRouteRules,\n} from \"./route-rules\";\nexport type {\n  FarmServerActionsConfig,\n  ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nexport type {\n  FarmServerConfig,\n  FarmServerDuration,\n  FarmServerHealthConfig,\n  ResolvedFarmServerConfig,\n  ResolvedFarmServerHealthConfig,\n} from \"./server-http\";\nexport type { FarmLayerEntry, ResolvedFarmLayer } from \"./layers\";\nexport type {\n  FarmDevtoolsConfig,\n  FarmDevtoolsUserConfig,\n  ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\nexport type {\n  FarmBuildActivityPosition,\n  FarmDevIndicatorsConfig,\n  ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nexport type {\n  FarmPerformanceConfig,\n  FarmPreloadMode,\n  FarmPreloadUserConfig,\n  ResolvedFarmPerformanceConfig,\n  ResolvedFarmPreloadConfig,\n} from \"./preload\";\nexport type {\n  FarmImageConfig,\n  FarmImageFormat,\n  FarmImageLocalPattern,\n  FarmImageProvider,\n  FarmImageRemotePattern,\n  ResolvedFarmImageConfig,\n} from \"./image-config\";\nexport type {\n  FarmI18nCookieConfig,\n  FarmI18nDetectionSignal,\n  FarmI18nDirection,\n  FarmI18nRouting,\n  FarmI18nUserConfig,\n  ResolvedFarmI18nConfig,\n} from \"./i18n/types\";\nexport type {\n  FarmAuthConfig,\n  FarmAuthDatabaseConfig,\n  FarmAuthEmailAndPasswordConfig,\n  FarmAuthSessionConfig,\n  FarmAuthUserConfig,\n  ResolvedFarmAuthConfig,\n} from \"./auth-config\";\nexport type {\n  FarmCspConfig,\n  FarmCspDirectives,\n  FarmCspDirectiveValue,\n  FarmCspOptions,\n  FarmSecurityConfig,\n  ResolvedFarmCspConfig,\n  ResolvedFarmSecurityConfig,\n} from \"./security\";\nexport type {\n  FarmRenderer,\n  FarmRendererCapabilities,\n  FarmRendererCapabilitiesInput,\n  FarmRendererStreamingCapabilities,\n} from \"./renderer\";\nexport { defineRenderer } from \"./renderer\";\nexport type {\n  FarmAPIConfig,\n  FarmAPIConfigResolverContext,\n  FarmAPIConfigValue,\n  ResolvedFarmAPIConfig,\n} from \"./api/config\";\n\nexport interface RedirectConfig {\n  source: string;\n  destination: string;\n  permanent?: boolean;\n  statusCode?: import(\"./navigation-errors\").FarmRedirectStatus;\n}\n\nexport interface HeaderConfig {\n  source: string;\n  headers: Array<{\n    key: string;\n    value: string;\n  }>;\n}\n\nexport interface RewriteConfig {\n  source: string;\n  destination: string;\n}\n\n/** @deprecated Use FarmImageConfig. */\nexport type ImageConfig = FarmImageConfig;\n\n/** @deprecated Use FarmI18nUserConfig. */\nexport type I18nConfig = FarmI18nUserConfig;\n\nexport interface OpenAPIConfig {\n  enabled?: boolean;\n  route?: string;\n  /**\n   * Path where the raw OpenAPI spec is served as JSON, so agents and API tools\n   * can fetch it at a predictable URL. Set to `false` to disable.\n   *\n   * @default \"/openapi.json\"\n   */\n  specRoute?: string | false;\n  title?: string;\n  description?: string;\n  version?: string;\n  servers?: Array<{\n    url: string;\n    description?: string;\n  }>;\n  contact?: {\n    name?: string;\n    email?: string;\n    url?: string;\n  };\n  license?: {\n    name: string;\n    url?: string;\n  };\n}\n\nexport type MiddlewareConfig = FarmMiddlewareConfig;\n\nexport interface NotFoundConfig {\n  /** Path to a custom 404 page component (e.g., \"./src/app/not-found.tsx\") */\n  component?: string;\n}\n\nexport type FarmDeployTarget = \"vercel\" | \"cloudflare\" | \"netlify\" | \"node\" | string;\n\nexport interface FarmDeployConfig {\n  /**\n   * Deployment platform. When present, Farm picks the matching Nitro preset and\n   * output directory unless explicitly overridden.\n   */\n  target?: FarmDeployTarget;\n  /** Nitro preset override. Usually inferred from target. */\n  preset?: BaseFarmConfig[\"preset\"];\n  /** Deployable output directory, relative to project root unless absolute. */\n  outputDir?: string;\n  /** Alias for outputDir for terser config. */\n  output?: string;\n  /** Cloudflare Pages project name used by `farm deploy --cloudflare`. */\n  projectName?: string;\n  vercel?: {\n    outputDirectory?: string;\n    buildCommand?: string;\n    installCommand?: string;\n    framework?: string | null;\n  };\n  cloudflare?: {\n    outputDir?: string;\n    projectName?: string;\n  };\n  netlify?: {\n    outputDir?: string;\n    site?: string;\n  };\n}\n\nexport interface ResolvedFarmDeployConfig extends Omit<FarmDeployConfig, \"output\"> {\n  target?: FarmDeployTarget;\n  preset: BaseFarmConfig[\"preset\"];\n  outputDir: string;\n}\n\nexport interface FarmUserConfig extends Omit<BaseFarmConfig, \"vite\" | \"docs\" | \"env\" | \"layers\"> {\n  /** Reusable Farm directories or installed packages, applied from left to right. */\n  extends?: readonly FarmLayerEntry[];\n  /** Global plugins. Integration-bound plugins must be contributed through an integration. */\n  plugins?: FarmPlugin<any, any, any, any, unknown, false>[];\n  integrations?: FarmIntegrationsUserConfig;\n  /**\n   * Farm-native authentication. `true` enables email/password auth with\n   * server helpers from `@farm.js/auth/server` and React APIs from\n   * `@farm.js/auth/client`.\n   */\n  auth?: FarmAuthUserConfig;\n  /** Shared application data, route, ISR, and PPR cache. */\n  cache?: FarmCacheUserConfig;\n  migrations?: FarmMigrationsUserConfig;\n  /** Map portable cron schedules to ordinary GET API routes. */\n  cron?: FarmCronUserConfig | FarmCronResolvedConfig | false;\n  workflows?: FarmWorkflowsUserConfig | boolean;\n  preset?: BaseFarmConfig[\"preset\"];\n  deploy?: FarmDeployConfig;\n  docs?: FarmDocsUserConfig;\n  md?: FarmMarkdownUserConfig | boolean;\n  mdx?: FarmMdxUserConfig;\n  observability?: FarmObservabilityUserConfig;\n  trailingSlash?: boolean;\n  redirects?: () => Promise<RedirectConfig[]> | RedirectConfig[];\n  rewrites?: () => Promise<RewriteConfig[]> | RewriteConfig[];\n  headers?: () => Promise<HeaderConfig[]> | HeaderConfig[];\n\n  images?: ImageConfig;\n  publicDir?: string;\n\n  i18n?: FarmI18nUserConfig | false;\n  openapi?: OpenAPIConfig;\n\n  middleware?: FarmMiddlewareConfig;\n  routeRules?: FarmRouteRules;\n  context?: BaseFarmConfig[\"context\"];\n  /** Server ingress and trusted-proxy policy. */\n  server?: FarmServerConfig;\n  serverActions?: FarmServerActionsConfig;\n  /** Build identifier used to detect and recover from deployment version skew. */\n  deploymentId?: string;\n\n  notFound?: NotFoundConfig;\n\n  distDir?: string;\n  generateBuildId?: () => string | Promise<string>;\n  compress?: boolean;\n\n  devIndicators?: FarmDevIndicatorsConfig;\n\n  serverRuntimeConfig?: Record<string, any>;\n  publicRuntimeConfig?: Record<string, any>;\n\n  env?: FarmEnvConfig<any, any>;\n\n  vite?: ViteUserConfig | ((config: ViteUserConfig) => ViteUserConfig);\n\n  [key: string]: any;\n}\n\nexport interface ResolvedFarmConfig extends Required<\n  Omit<\n    FarmUserConfig,\n    | \"extends\"\n    | \"plugins\"\n    | \"vite\"\n    | \"deploy\"\n    | \"docs\"\n    | \"md\"\n    | \"mdx\"\n    | \"migrations\"\n    | \"cron\"\n    | \"workflows\"\n    | \"api\"\n    | \"env\"\n    | \"server\"\n    | \"serverActions\"\n    | \"devtools\"\n    | \"devIndicators\"\n    | \"images\"\n    | \"i18n\"\n    | \"auth\"\n    | \"performance\"\n    | \"security\"\n    | \"theme\"\n    | \"renderer\"\n    | \"agent\"\n  >\n> {\n  agent: ResolvedFarmAgentConfig;\n  /** @internal Tracks whether `context` came from user/layer config instead of the default noop. */\n  [FARM_RESOLVED_CUSTOM_CONTEXT]?: boolean;\n  root: string;\n  extends: readonly FarmLayerEntry[];\n  layers: ResolvedFarmLayer[];\n  plugins: FarmPlugin[];\n  vite: ViteUserConfig;\n  deploy: ResolvedFarmDeployConfig;\n  docs: FarmDocsResolvedConfig;\n  md: FarmMarkdownResolvedConfig;\n  mdx: FarmMdxResolvedConfig;\n  migrations: ResolvedFarmMigrationsConfig;\n  cron: FarmCronResolvedConfig;\n  workflows: FarmWorkflowsResolvedConfig;\n  api: ResolvedFarmAPIConfig;\n  env: ResolvedFarmEnv;\n  server: ResolvedFarmServerConfig;\n  serverActions: ResolvedFarmServerActionsConfig;\n  devtools: ResolvedFarmDevtoolsConfig;\n  devIndicators: ResolvedFarmDevIndicatorsConfig;\n  images: ResolvedFarmImageConfig;\n  i18n: ResolvedFarmI18nConfig;\n  auth: ResolvedFarmAuthConfig;\n  performance: ResolvedFarmPerformanceConfig;\n  security: ResolvedFarmSecurityConfig;\n  theme: ResolvedFarmThemeConfig;\n  renderer: FarmRenderer;\n  routeRules: FarmRouteRules;\n  notFound: NotFoundConfig;\n}\n\nexport function hasCustomFarmRouteContext(config: ResolvedFarmConfig): boolean {\n  return config[FARM_RESOLVED_CUSTOM_CONTEXT] === true;\n}\n\nexport type FarmLayerConfig = Omit<\n  FarmUserConfig,\n  | \"root\"\n  | \"outDir\"\n  | \"distDir\"\n  | \"deploy\"\n  | \"preset\"\n  | \"publicDir\"\n  | \"generateBuildId\"\n  | \"deploymentId\"\n>;\n\nexport { defineConfig, defineFarmConfig } from \"./config-entry\";\n\nexport function normalizeDeployTarget(target?: FarmDeployTarget): FarmDeployTarget | undefined {\n  if (!target) return undefined;\n  if (target === \"cloudflare-pages\" || target === \"cloudflare_pages\") return \"cloudflare\";\n  if (target === \"node-server\" || target === \"nitro\") return \"node\";\n  return target;\n}\n\nexport function getPresetForDeployTarget(\n  target?: FarmDeployTarget,\n): BaseFarmConfig[\"preset\"] | undefined {\n  switch (normalizeDeployTarget(target)) {\n    case \"vercel\":\n      return \"vercel\";\n    case \"cloudflare\":\n      return \"cloudflare-pages\";\n    case \"netlify\":\n      return \"netlify\";\n    case \"node\":\n      return \"node-server\";\n    default:\n      return undefined;\n  }\n}\n\nexport function getDeployTargetForPreset(preset?: string): FarmDeployTarget | undefined {\n  if (!preset) return undefined;\n  if (preset === \"vercel\" || preset === \"vercel-edge\") return \"vercel\";\n  if (preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\") {\n    return \"cloudflare\";\n  }\n  if (preset === \"netlify\" || preset === \"netlify-edge\") return \"netlify\";\n  if (preset === \"node-server\") return \"node\";\n  return undefined;\n}\n\nexport function getDefaultDeployOutputDir(\n  target: FarmDeployTarget | undefined,\n  preset: string | undefined,\n  distDir: string,\n): string {\n  const normalizedTarget = normalizeDeployTarget(target) || getDeployTargetForPreset(preset);\n  if (normalizedTarget === \"vercel\") return \".vercel/output\";\n  return `${distDir}/.output`;\n}\n\nexport function resolveDeployOutputPath(root: string, outputDir: string): string {\n  return path.isAbsolute(outputDir) ? outputDir : path.join(root, outputDir);\n}\n\nconst PLATFORM_BUILD_ENV_TARGETS: ReadonlyArray<[string, FarmDeployTarget]> = [\n  [\"VERCEL\", \"vercel\"],\n  [\"NETLIFY\", \"netlify\"],\n  [\"CF_PAGES\", \"cloudflare\"],\n];\n\n/**\n * Deploy target announced by the build environment (VERCEL=1, NETLIFY=true,\n * CF_PAGES=1), or undefined outside platform CI.\n */\nexport function detectPlatformDeployTarget(\n  env: NodeJS.ProcessEnv = process.env,\n): FarmDeployTarget | undefined {\n  for (const [key, target] of PLATFORM_BUILD_ENV_TARGETS) {\n    if (env[key]) return target;\n  }\n  return undefined;\n}\n\nconst warnedPlatformMismatches = new Set<string>();\n\nexport function resolveDeployConfig(\n  config: Pick<FarmUserConfig, \"deploy\" | \"preset\" | \"distDir\">,\n  overrides: {\n    target?: FarmDeployTarget;\n    preset?: BaseFarmConfig[\"preset\"];\n    outputDir?: string;\n    /** Build environment consulted for platform detection. Tests inject this. */\n    env?: NodeJS.ProcessEnv;\n  } = {},\n): ResolvedFarmDeployConfig {\n  const deploy = config.deploy || {};\n  const distDir = config.distDir || \".farm\";\n  // An explicit preset override replaces the deployment plan, so the\n  // configured platform target must not keep steering the output. Otherwise\n  // `farm build --preset node-server` on an app configured for Vercel writes\n  // a node server into .vercel/output — a directory Vercel will deploy as\n  // Build Output API content.\n  const overrideTarget = normalizeDeployTarget(overrides.target);\n  let target = overrideTarget\n    ? overrideTarget\n    : overrides.preset\n      ? getDeployTargetForPreset(overrides.preset)\n      : normalizeDeployTarget(deploy.target);\n\n  // A platform build environment (Vercel, Netlify, Cloudflare Pages) can only\n  // deploy its own output shape. When nothing selects a preset, the\n  // node-server fallback would build an artifact the platform cannot serve,\n  // so honor the detected platform instead. An explicit configuration always\n  // wins; it just gets a warning when it cannot run where it is being built.\n  const detectedTarget = detectPlatformDeployTarget(overrides.env);\n  if (detectedTarget) {\n    const hasExplicitSelection = Boolean(\n      target || overrides.preset || deploy.preset || config.preset,\n    );\n    if (!hasExplicitSelection) {\n      target = detectedTarget;\n      if (!warnedPlatformMismatches.has(`select:${detectedTarget}`)) {\n        warnedPlatformMismatches.add(`select:${detectedTarget}`);\n        logger.info(\n          `Detected ${detectedTarget} build environment; using the ${detectedTarget} preset. Set deploy.target in farm.config.ts to override.`,\n        );\n      }\n    }\n  }\n  // A CLI --target override governs the preset too: keep a configured preset\n  // only when it targets the same platform, otherwise derive the preset from\n  // the override target. Mirrors how a --preset override recomputes the target\n  // above, so `farm build --target netlify` never ships Vercel-shaped output.\n  const configuredPreset = deploy.preset || config.preset;\n  const overrideTargetPreset =\n    overrideTarget && getDeployTargetForPreset(configuredPreset) !== overrideTarget\n      ? getPresetForDeployTarget(overrideTarget)\n      : undefined;\n  const preset =\n    overrides.preset ||\n    overrideTargetPreset ||\n    configuredPreset ||\n    getPresetForDeployTarget(target) ||\n    \"node-server\";\n  const resolvedTarget = target || getDeployTargetForPreset(preset);\n  if (detectedTarget && resolvedTarget !== detectedTarget) {\n    const mismatchKey = `mismatch:${resolvedTarget}:${detectedTarget}`;\n    if (!warnedPlatformMismatches.has(mismatchKey)) {\n      warnedPlatformMismatches.add(mismatchKey);\n      logger.warn(\n        `The configured deploy target \"${resolvedTarget ?? preset}\" cannot be served by ${detectedTarget}, but this build is running in a ${detectedTarget} build environment. Set deploy.target: \"${detectedTarget}\" in farm.config.ts to deploy there.`,\n      );\n    }\n  }\n  const platformOutput =\n    resolvedTarget === \"vercel\"\n      ? deploy.vercel?.outputDirectory\n      : resolvedTarget === \"cloudflare\"\n        ? deploy.cloudflare?.outputDir\n        : resolvedTarget === \"netlify\"\n          ? deploy.netlify?.outputDir\n          : undefined;\n  const outputDir =\n    overrides.outputDir ||\n    deploy.outputDir ||\n    deploy.output ||\n    platformOutput ||\n    getDefaultDeployOutputDir(resolvedTarget, preset, distDir);\n\n  return {\n    ...deploy,\n    target: resolvedTarget,\n    preset,\n    outputDir,\n  };\n}\n\nexport function resolveMigrationsConfig(\n  migrations: FarmMigrationsUserConfig | undefined,\n): ResolvedFarmMigrationsConfig {\n  if (!migrations) return { commands: [] };\n  if (Array.isArray(migrations)) return { commands: migrations };\n  return { commands: migrations.commands || [] };\n}\n\nexport const DOCS_CONFIG_FILENAMES = [\n  \"docs.config.ts\",\n  \"docs.config.tsx\",\n  \"docs.config.mts\",\n  \"docs.config.cts\",\n  \"docs.config.js\",\n  \"docs.config.jsx\",\n  \"docs.config.mjs\",\n  \"docs.config.cjs\",\n  \"docs.json\",\n];\n\nfunction normalizeDocsRoute(value: string | undefined, fallback = \"/docs\"): string {\n  const raw = (value || fallback).trim();\n  if (!raw || raw === \"/\") return \"/\";\n  const normalized = raw\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\/+/g, \"/\")\n    .replace(/^\\/?/, \"/\")\n    .replace(/\\/+$/, \"\");\n  return normalized || \"/\";\n}\n\nfunction docsRouteToEntry(route: string): string {\n  const entry = route.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  return entry || \"docs\";\n}\n\nfunction normalizeDocsContentDir(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n  const normalized = value.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  return normalized || undefined;\n}\n\nasync function inferDocsContentDir(\n  root: string,\n  srcDir: string,\n  entry: string,\n): Promise<string | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const contentDir = path.resolve(root, srcDir, \"app\", entry);\n  if (!existsSync(contentDir)) return undefined;\n\n  const relativeContentDir = path.relative(root, contentDir);\n  if (relativeContentDir.startsWith(\"..\") || path.isAbsolute(relativeContentDir)) return undefined;\n\n  return normalizeDocsContentDir(relativeContentDir);\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction cloneSerializable(value: unknown, seen = new WeakSet<object>()): any {\n  if (value === null) return null;\n\n  const valueType = typeof value;\n  if (valueType === \"string\" || valueType === \"number\" || valueType === \"boolean\") {\n    return value;\n  }\n  if (valueType === \"undefined\" || valueType === \"function\" || valueType === \"symbol\") {\n    return undefined;\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) => cloneSerializable(item, seen)).filter((item) => item !== undefined);\n  }\n  if (value instanceof Date) {\n    return value.toISOString();\n  }\n  if (isRecord(value)) {\n    if (seen.has(value)) return undefined;\n    seen.add(value);\n\n    const output: Record<string, any> = {};\n    for (const [key, nestedValue] of Object.entries(value)) {\n      const clonedValue = cloneSerializable(nestedValue, seen);\n      if (clonedValue !== undefined) {\n        output[key] = clonedValue;\n      }\n    }\n    return output;\n  }\n\n  return undefined;\n}\n\nfunction sanitizeDocsConfig(config: Partial<DocsConfig>): Partial<DocsConfig> {\n  return cloneSerializable(config) || {};\n}\n\nexport async function findDocsConfigPath(\n  rootDir: string,\n  configPath?: string,\n): Promise<string | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const root = path.resolve(rootDir || process.cwd());\n\n  if (configPath) {\n    const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n    if (!existsSync(resolvedPath)) {\n      throw new Error(`Could not find docs config at ${configPath}.`);\n    }\n    return path.resolve(resolvedPath);\n  }\n\n  for (const filename of DOCS_CONFIG_FILENAMES) {\n    const resolvedPath = path.join(root, filename);\n    if (existsSync(resolvedPath)) {\n      return resolvedPath;\n    }\n  }\n\n  return undefined;\n}\n\nexport async function loadDocsConfig(\n  rootDir: string,\n  configPath?: string,\n): Promise<{ config: Partial<DocsConfig>; configPath: string } | undefined> {\n  const fs = await import(\"fs/promises\");\n  const { pathToFileURL } = await import(\"url\");\n  const root = path.resolve(rootDir || process.cwd());\n  const resolvedPath = await findDocsConfigPath(root, configPath);\n\n  if (!resolvedPath) return undefined;\n\n  try {\n    if (resolvedPath.endsWith(\".json\")) {\n      const content = await fs.readFile(resolvedPath, \"utf8\");\n      return { config: JSON.parse(content), configPath: resolvedPath };\n    }\n\n    const { build } = await import(\"esbuild\");\n    const configCacheDir = path.join(root, \".farm\", \".config-loader\");\n    await fs.mkdir(configCacheDir, { recursive: true });\n    const modulePath = path.join(\n      configCacheDir,\n      `docs-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n    );\n\n    await build({\n      absWorkingDir: root,\n      entryPoints: [resolvedPath],\n      outfile: modulePath,\n      bundle: true,\n      format: \"esm\",\n      platform: \"node\",\n      target: `node${process.versions.node.split(\".\")[0]}`,\n      packages: \"external\",\n      jsx: \"automatic\",\n      logLevel: \"silent\",\n      sourcemap: \"inline\",\n    });\n\n    const moduleUrl = pathToFileURL(modulePath).href + `?t=${Date.now()}`;\n    let importedConfig: any;\n\n    try {\n      importedConfig = await import(/* @vite-ignore */ moduleUrl);\n    } finally {\n      await fs.unlink(modulePath).catch(() => undefined);\n    }\n\n    return {\n      config: importedConfig.default || importedConfig,\n      configPath: resolvedPath,\n    };\n  } catch (error: any) {\n    const relativePath = path.relative(root, resolvedPath) || resolvedPath;\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Failed to load docs config from ${relativePath}: ${message}`);\n  }\n}\n\nexport async function resolveDocsConfig(\n  userDocs: FarmDocsUserConfig | undefined,\n  options: {\n    root?: string;\n    srcDir?: string;\n  } = {},\n): Promise<FarmDocsResolvedConfig> {\n  const root = options.root || process.cwd();\n\n  if (userDocs === false) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const docsOptions = isRecord(userDocs) ? userDocs : {};\n  if (docsOptions.enabled === false) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const loadedConfig = await loadDocsConfig(root, docsOptions.configPath);\n  const hasExplicitDocsConfig = userDocs === true || isRecord(userDocs);\n\n  if (!hasExplicitDocsConfig && !loadedConfig) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const inlineDocsConfig = sanitizeDocsConfig(docsOptions.config || {});\n  const directDocsConfig = sanitizeDocsConfig({\n    ...docsOptions,\n    adapter: undefined,\n    enabled: undefined,\n    config: undefined,\n    configPath: undefined,\n  } as Partial<DocsConfig>);\n  const loadedDocsConfig = sanitizeDocsConfig(loadedConfig?.config || {});\n  const mergedDocsConfig: Partial<DocsConfig> = {\n    ...loadedDocsConfig,\n    ...inlineDocsConfig,\n    ...directDocsConfig,\n  };\n\n  const explicitRoute = typeof docsOptions.entry === \"string\" ? docsOptions.entry : undefined;\n  const configuredDocsPath =\n    typeof mergedDocsConfig.docsPath === \"string\" ? mergedDocsConfig.docsPath : undefined;\n  const configuredEntry =\n    typeof mergedDocsConfig.entry === \"string\" ? mergedDocsConfig.entry : undefined;\n  const entryRoute = normalizeDocsRoute(\n    configuredDocsPath || explicitRoute || (configuredEntry ? `/${configuredEntry}` : undefined),\n  );\n  const docsEntry =\n    explicitRoute && explicitRoute.startsWith(\"/\")\n      ? docsRouteToEntry(explicitRoute)\n      : docsRouteToEntry(configuredEntry || entryRoute);\n  const configuredContentDir = normalizeDocsContentDir(\n    docsOptions.contentDir || mergedDocsConfig.contentDir,\n  );\n  const contentDir =\n    configuredContentDir || (await inferDocsContentDir(root, options.srcDir || \"src\", docsEntry));\n\n  return {\n    enabled: true,\n    entry: entryRoute,\n    ...(docsOptions.adapter ? { adapter: docsOptions.adapter } : {}),\n    contentDir,\n    configPath: loadedConfig?.configPath,\n    config: {\n      ...mergedDocsConfig,\n      entry: docsEntry,\n      docsPath: entryRoute,\n      ...(contentDir ? { contentDir } : {}),\n    },\n  };\n}\n\nfunction validateRedirectConfigs(redirects: RedirectConfig[], field: string): RedirectConfig[] {\n  for (const [index, redirect] of redirects.entries()) {\n    validateConfigRouteSource(redirect.source, `${field}[${index}].source`);\n    if (redirect.statusCode !== undefined && !isFarmRedirectStatus(redirect.statusCode)) {\n      throw new RangeError(\n        `${field}[${index}].statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n  }\n  return redirects;\n}\n\nfunction validateConfigRouteSources<T extends { source: string }>(routes: T[], field: string): T[] {\n  for (const [index, route] of routes.entries()) {\n    validateConfigRouteSource(route.source, `${field}[${index}].source`);\n  }\n  return routes;\n}\n\nexport async function resolveConfig(\n  userConfig: FarmUserConfig,\n  mode: \"development\" | \"production\",\n): Promise<ResolvedFarmConfig> {\n  const projectRoot = userConfig.root || process.cwd();\n  const layerResolution = await resolveFarmLayers(userConfig, {\n    root: projectRoot,\n    mode,\n  });\n  userConfig = layerResolution.config;\n\n  if ((userConfig as Record<string, unknown>).typescript !== undefined) {\n    logger.warn(\n      'The top-level \"typescript\" option is not supported and has no effect. Configure TypeScript in `tsconfig.json` and run `tsc --noEmit` separately when builds must enforce project type errors.',\n    );\n  }\n\n  if ((userConfig as Record<string, unknown>).output !== undefined) {\n    logger.warn(\n      'The top-level \"output\" option is not supported and has no effect. Configure `deploy.target`, `deploy.preset`, or `deploy.outputDir` for deployment output, and use route rendering configuration for static pages.',\n    );\n  }\n\n  // The docs adapter runtime is React-only today; other renderers keep the\n  // embedded docs handler without any migration notice.\n  if (isReactRenderer(resolveFarmRenderer(userConfig.renderer))) {\n    userConfig = await applyFarmDocsFrameworkAutoDetection(userConfig, {\n      root: userConfig.root || projectRoot,\n    });\n  }\n\n  const redirects = validateRedirectConfigs(\n    typeof userConfig.redirects === \"function\"\n      ? await userConfig.redirects()\n      : userConfig.redirects || [],\n    \"redirects\",\n  );\n\n  const rewrites =\n    typeof userConfig.rewrites === \"function\"\n      ? await userConfig.rewrites()\n      : userConfig.rewrites || [];\n  validateConfigRouteSources(rewrites, \"rewrites\");\n\n  const headers =\n    typeof userConfig.headers === \"function\"\n      ? await userConfig.headers()\n      : userConfig.headers || [];\n  validateConfigRouteSources(headers, \"headers\");\n  const routeRules = normalizeRouteRules(userConfig.routeRules);\n  const routeRuleRedirects = routeRulesToRedirects(routeRules);\n  const routeRuleHeaders = routeRulesToHeaders(routeRules);\n  const security = resolveFarmSecurityConfig(userConfig.security);\n  const securityHeader = getFarmSecurityHeader(security);\n\n  const deploy = resolveDeployConfig(userConfig);\n  const root = userConfig.root || process.cwd();\n  const srcDir = userConfig.srcDir || \"src\";\n  const docs = await resolveDocsConfig(userConfig.docs, { root, srcDir });\n  const md = resolveMarkdownConfig(userConfig.md);\n  const mdx = resolveMdxConfig(userConfig.mdx);\n  const env = resolveEnv(userConfig.env, process.env);\n  setEnv(env);\n  const api = await resolveFarmAPIConfig(userConfig.api, { root, mode, env });\n  const auth = resolveFarmAuthConfig(userConfig.auth);\n  if (auth.enabled && userConfig.integrations?.auth) {\n    throw new Error(\n      \"Choose either the top-level `auth` config or `integrations.auth`; they cannot both own the auth route.\",\n    );\n  }\n  const nativeAuthIntegration = await resolveFarmAuthIntegration(auth, {\n    root,\n    mode,\n  });\n  const integrations = nativeAuthIntegration\n    ? { ...userConfig.integrations, auth: nativeAuthIntegration }\n    : userConfig.integrations || {};\n  const generateBuildId = userConfig.generateBuildId || (() => `build-${Date.now()}`);\n  const deploymentId = normalizeFarmDeploymentId(\n    userConfig.deploymentId ||\n      process.env.FARM_DEPLOYMENT_ID ||\n      process.env.VERCEL_GIT_COMMIT_SHA ||\n      process.env.CF_PAGES_COMMIT_SHA ||\n      (mode === \"production\" ? await generateBuildId() : \"development\"),\n  );\n  const basePath = normalizeFarmConfigBasePath(userConfig.basePath);\n  const openapi = {\n    enabled: false,\n    route: \"/docs/reference\",\n    specRoute: \"/openapi.json\" as string | false,\n    title: \"API Documentation\",\n    description: \"Auto-generated API documentation\",\n    version: \"1.0.0\",\n    servers: [{ url: \"http://localhost:3000\", description: \"Development server\" }],\n    ...userConfig.openapi,\n  };\n  if (openapi.route !== undefined) validateConfigRouteSource(openapi.route, \"openapi.route\");\n  if (openapi.specRoute) validateConfigRouteSource(openapi.specRoute, \"openapi.specRoute\");\n\n  const resolved: ResolvedFarmConfig = {\n    [FARM_RESOLVED_CUSTOM_CONTEXT]: typeof userConfig.context === \"function\",\n    root,\n    srcDir,\n    extends: userConfig.extends || [],\n    layers: layerResolution.layers,\n    outDir: userConfig.outDir || \"dist\",\n    basePath,\n    renderer: resolveFarmRenderer(userConfig.renderer),\n    preset: deploy.preset || \"node-server\",\n    deploy,\n    docs,\n    md,\n    mdx,\n    migrations: resolveMigrationsConfig(userConfig.migrations),\n    cron: resolveCronConfig(userConfig.cron),\n    workflows: resolveWorkflowsConfig(userConfig.workflows),\n    api,\n    observability: userConfig.observability ?? false,\n    telemetry: userConfig.telemetry !== false,\n    devtools: resolveFarmDevtoolsConfig(userConfig.devtools, mode),\n    storage: userConfig.storage || {},\n    cache: userConfig.cache || {},\n    auth,\n    suppressLintOnLink: userConfig.suppressLintOnLink ?? false,\n    experimental: {\n      serverComponents: false,\n      serverActions: false,\n      isolatedClientHydration: \"off\",\n      ppr: false,\n      ...userConfig.experimental,\n    },\n    agent: resolveFarmAgentConfig(userConfig.agent),\n    plugins: [...resolveIntegrationPlugins(integrations), ...(userConfig.plugins || [])],\n    integrations,\n    trailingSlash: userConfig.trailingSlash ?? false,\n    redirects: () => [...redirects, ...routeRuleRedirects],\n    rewrites: () => rewrites,\n    headers: () => [\n      ...headers,\n      ...routeRuleHeaders,\n      ...(securityHeader ? [{ source: \"/*\", headers: [securityHeader] }] : []),\n    ],\n    routeRules,\n    images: resolveFarmImageConfig(userConfig.images),\n    performance: resolveFarmPerformanceConfig(userConfig.performance),\n    theme: resolveFarmThemeConfig(userConfig.theme, basePath),\n    publicDir: userConfig.publicDir || \"public\",\n    i18n: resolveFarmI18nConfig(userConfig.i18n, { root, mode, basePath }),\n    openapi,\n    middleware: userConfig.middleware || {},\n    notFound: userConfig.notFound || {},\n    context: userConfig.context || (() => undefined),\n    server: resolveFarmServerConfig(userConfig.server),\n    serverActions: resolveServerActionsConfig(userConfig.serverActions),\n    security,\n    deploymentId,\n    distDir: userConfig.distDir || \".farm\",\n    generateBuildId,\n    compress: userConfig.compress ?? true,\n    devIndicators: resolveFarmDevIndicatorsConfig(userConfig.devIndicators, mode),\n    serverRuntimeConfig: userConfig.serverRuntimeConfig || {},\n    publicRuntimeConfig: userConfig.publicRuntimeConfig || {},\n    env,\n    vite: typeof userConfig.vite === \"function\" ? userConfig.vite({}) : userConfig.vite || {},\n  };\n\n  return resolved;\n}\n\nexport async function loadConfig(\n  rootDir?: string,\n  configPath?: string,\n  mode = process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n  loadEnvironment?: (typeof import(\"vite\"))[\"loadEnv\"],\n): Promise<FarmUserConfig | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const loadEnv = loadEnvironment || (await import(\"vite\")).loadEnv;\n\n  const root = rootDir || process.cwd();\n  const loadedEnv = loadEnv(mode, root, \"\");\n  for (const [key, value] of Object.entries(loadedEnv)) {\n    if (process.env[key] === undefined) {\n      process.env[key] = value;\n    }\n  }\n  // An explicitly supplied config path must resolve — silently falling back\n  // to the default config would run against the wrong configuration.\n  if (configPath) {\n    const explicitPath = path.resolve(\n      path.isAbsolute(configPath) ? configPath : path.join(root, configPath),\n    );\n    if (!existsSync(explicitPath)) {\n      throw new Error(`Config file not found at ${configPath} (resolved to ${explicitPath}).`);\n    }\n  }\n\n  const searchPaths = [\n    configPath,\n    \"farm.config.ts\",\n    \"farm.config.mts\",\n    \"farm.config.js\",\n    \"farm.config.mjs\",\n    \"config.ts\",\n    \"config.mts\",\n    \"config.js\",\n    \"config.mjs\",\n  ].filter(Boolean) as string[];\n\n  for (const relativePath of searchPaths) {\n    try {\n      // Use path.join for proper path construction\n      const absolutePath = path.isAbsolute(relativePath)\n        ? relativePath\n        : path.join(root, relativePath);\n\n      // Normalize the path to handle any issues\n      const normalizedPath = path.resolve(absolutePath);\n\n      // Check if file exists before trying to import\n      if (!existsSync(normalizedPath)) {\n        continue;\n      }\n\n      const loadedConfig = await loadFarmConfigFile<FarmUserConfig>(normalizedPath, { root });\n      return loadedConfig.root === undefined ? { ...loadedConfig, root } : loadedConfig;\n    } catch (error: any) {\n      const message = error instanceof Error ? error.message : String(error);\n      throw new Error(`Failed to load config from ${relativePath}: ${message}`);\n    }\n  }\n  return undefined;\n}\n","import {\n  buildDocsAgentDiscoverySpec,\n  buildDocsConfigMap,\n  buildDocsDiagnostics as buildFarmingDocsDiagnostics,\n  buildDocsSitemapManifest,\n  performDocsSearch,\n  renderDocsAgentsDocument,\n  renderDocsLlmsTxt,\n  renderDocsMarkdownDocument,\n  renderDocsRobotsTxt,\n  renderDocsSitemapMarkdown,\n  renderDocsSitemapXml,\n  renderDocsSkillDocument,\n  type DocsConfig,\n  type DocsLlmsTxtPageInput,\n  type DocsSearchSourcePage,\n  type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { resolveDocsConfig } from \"../config\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./types\";\nimport {\n  discoverFarmDocsPages,\n  type LoadedFarmDocsPage,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n  toFarmDocsMarkdownPage,\n} from \"./handler\";\n\nexport interface FarmDocsAPIOptions {\n  rootDir?: string;\n  root?: string;\n  srcDir?: string;\n  docs?: FarmDocsUserConfig | FarmDocsResolvedConfig;\n  config?: Partial<DocsConfig>;\n  configPath?: string;\n  entry?: string;\n  docsPath?: string;\n  contentDir?: string;\n}\n\nexport interface FarmDocsCloudRouteOptions {\n  locale?: string;\n  publicBaseUrl?: string;\n}\n\nexport interface FarmDocsCloudServer {\n  handleRequest(request: Request, options?: FarmDocsCloudRouteOptions): Promise<Response>;\n}\n\nexport type FarmDocsCloudIntegration =\n  | FarmDocsCloudServer\n  | (FarmDocsCloudRouteOptions & { docsCloud?: FarmDocsCloudServer });\n\nexport interface FarmDocsAPIRouteHandlers {\n  GET(request: Request): Promise<Response>;\n  POST(request: Request): Promise<Response>;\n}\n\nexport type FarmDocsAPIHandler = (request: Request) => Promise<Response | null>;\n\ninterface FarmDocsAPIContext {\n  root: string;\n  srcDir: string;\n  docs: FarmDocsResolvedConfig;\n  contentDir: string;\n}\n\ntype JsonRecord = Record<string, unknown>;\ntype DocsAPIPathTarget = {\n  format?: string;\n  slug?: string;\n};\ntype FarmDocsRuntimeConfig = {\n  root?: string;\n  srcDir?: string;\n  docs?: FarmDocsResolvedConfig;\n};\n\ndeclare global {\n  // Injected by Farm's generated server entry so route wrappers can stay zero-config.\n  // eslint-disable-next-line no-var\n  var __FARM_DOCS_RUNTIME_CONFIG__: FarmDocsRuntimeConfig | undefined;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isResolvedDocsConfig(value: unknown): value is FarmDocsResolvedConfig {\n  return (\n    isRecord(value) &&\n    typeof value.enabled === \"boolean\" &&\n    typeof value.entry === \"string\" &&\n    isRecord(value.config)\n  );\n}\n\nexport function isFarmDocsAPIRequest(requestOrPathname: Request | string): boolean {\n  const pathname =\n    typeof requestOrPathname === \"string\"\n      ? requestOrPathname\n      : new URL(requestOrPathname.url).pathname;\n\n  return pathname === \"/api/docs\" || pathname.startsWith(\"/api/docs/\");\n}\n\nfunction json(data: unknown, init: ResponseInit = {}): Response {\n  const headers = new Headers(init.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json\");\n  }\n  return new Response(JSON.stringify(data), { ...init, headers });\n}\n\nfunction text(content: string, contentType: string, init: ResponseInit = {}): Response {\n  const headers = new Headers(init.headers);\n  headers.set(\"Content-Type\", contentType);\n  return new Response(content, { ...init, headers });\n}\n\nfunction omitHeadBody(response: Response): Response {\n  return new Response(null, {\n    status: response.status,\n    statusText: response.statusText,\n    headers: response.headers,\n  });\n}\n\nfunction normalizeAction(value: string | null | undefined): string | undefined {\n  return value?.trim().toLowerCase().replace(/_/g, \"-\") || undefined;\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n  return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n    ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n    : \"Documentation\";\n}\n\nfunction isDocsCloudServer(value: unknown): value is FarmDocsCloudServer {\n  return isRecord(value) && typeof value.handleRequest === \"function\";\n}\n\nfunction resolveDocsCloudIntegration(\n  integration?: FarmDocsCloudIntegration,\n): { docsCloud: FarmDocsCloudServer; routeOptions: FarmDocsCloudRouteOptions } | undefined {\n  if (!integration) return undefined;\n\n  if (isDocsCloudServer(integration)) {\n    return { docsCloud: integration, routeOptions: {} };\n  }\n\n  if (!integration.docsCloud) return undefined;\n\n  return {\n    docsCloud: integration.docsCloud,\n    routeOptions: {\n      locale: integration.locale,\n      publicBaseUrl: integration.publicBaseUrl,\n    },\n  };\n}\n\nfunction isDocsCloudGetRequest(request: Request): boolean {\n  const url = new URL(request.url);\n  const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n  const action = normalizeAction(url.searchParams.get(\"action\"));\n  const format = normalizeAction(url.searchParams.get(\"format\"));\n\n  return (\n    cloud === \"config\" ||\n    cloud === \"public-config\" ||\n    action === \"cloud-config\" ||\n    action === \"docs-cloud-config\" ||\n    format === \"cloud-config\" ||\n    format === \"docs-cloud-config\"\n  );\n}\n\nfunction isDocsCloudAction(action: string | undefined): boolean {\n  return Boolean(\n    action &&\n    [\"analytics\", \"track\", \"track-event\", \"event\", \"ask-ai\", \"ai\", \"chat\", \"docs-cloud\"].includes(\n      action,\n    ),\n  );\n}\n\nasync function readJson(request: Request): Promise<unknown> {\n  try {\n    return await request.clone().json();\n  } catch {\n    return undefined;\n  }\n}\n\nasync function isDocsCloudPostRequest(request: Request): Promise<boolean> {\n  const url = new URL(request.url);\n  const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n  const action = normalizeAction(url.searchParams.get(\"action\"));\n\n  if (isDocsCloudAction(cloud) || isDocsCloudAction(action)) return true;\n\n  const body = await readJson(request);\n  if (!isRecord(body)) return false;\n\n  const bodyAction = normalizeAction(typeof body.action === \"string\" ? body.action : undefined);\n  if (isDocsCloudAction(bodyAction)) return true;\n\n  if (typeof body.type === \"string\") return true;\n  if (isRecord(body.event) && typeof body.event.type === \"string\") return true;\n  if (isRecord(body.payload) && typeof body.payload.type === \"string\") return true;\n\n  return false;\n}\n\nfunction normalizeDocsApiSlug(\n  value: string | null | undefined,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const entry = docs.entry.replace(/^\\/+|\\/+$/g, \"\");\n  let slug = (value || \"\").trim().replace(/^\\/+|\\/+$/g, \"\");\n\n  if (entry && slug === entry) return \"\";\n  if (entry && slug.startsWith(`${entry}/`)) {\n    slug = slug.slice(entry.length + 1);\n  }\n\n  let decoded = slug;\n  try {\n    decoded = decodeURIComponent(slug);\n  } catch {\n    // Malformed percent-encoding resolves to a non-matching slug (404),\n    // not an exception out of the handler.\n  }\n  return decoded.replace(/\\.(mdx?|markdown)$/i, \"\");\n}\n\nfunction getDocsAPIPathTarget(request: Request): DocsAPIPathTarget {\n  const pathname = new URL(request.url).pathname.replace(/\\/+$/, \"\") || \"/\";\n  const prefix = \"/api/docs\";\n\n  if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return {};\n\n  const rawValue = pathname === prefix ? \"\" : pathname.slice(prefix.length + 1);\n  const value = rawValue.replace(/^\\/+|\\/+$/g, \"\");\n  const normalizedValue = normalizeAction(value);\n\n  if (!value) return {};\n  if (\n    normalizedValue === \"agent\" ||\n    normalizedValue === \"agent.json\" ||\n    normalizedValue === \"agent/spec\"\n  ) {\n    return { format: \"agent-spec\" };\n  }\n  if (\n    normalizedValue === \"agents\" ||\n    normalizedValue === \"agents.md\" ||\n    normalizedValue === \"agent.md\"\n  ) {\n    return { format: \"agents\" };\n  }\n  if (normalizedValue === \"skill\" || normalizedValue === \"skill.md\") return { format: \"skill\" };\n  if (normalizedValue === \"llms.txt\") return { format: \"llms\" };\n  if (normalizedValue === \"llms-full.txt\") return { format: \"llms-full\" };\n  if (normalizedValue === \"sitemap.md\") return { format: \"sitemap-md\" };\n  if (normalizedValue === \"sitemap.xml\") return { format: \"sitemap-xml\" };\n  if (normalizedValue === \"robots.txt\") return { format: \"robots\" };\n  if (/\\.(mdx?|markdown)$/i.test(value)) return { format: \"markdown\", slug: value };\n\n  return { slug: value };\n}\n\nfunction getDocsAPIFormat(request: Request): string | undefined {\n  const url = new URL(request.url);\n  return (\n    normalizeAction(url.searchParams.get(\"format\") || url.searchParams.get(\"type\")) ||\n    getDocsAPIPathTarget(request).format\n  );\n}\n\nfunction getDocsDescription(docs: FarmDocsResolvedConfig): string | undefined {\n  return docs.config.metadata?.description;\n}\n\nfunction getLoadedDocsPages(context: FarmDocsAPIContext): LoadedFarmDocsPage[] {\n  return discoverFarmDocsPages(context.contentDir, context.docs)\n    .map((page) => loadFarmDocsPage(context.contentDir, context.docs, page.slug))\n    .filter((page): page is LoadedFarmDocsPage => Boolean(page));\n}\n\nfunction toDocsSourcePage(page: LoadedFarmDocsPage): DocsSearchSourcePage {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\nfunction toDocsSitemapPage(page: LoadedFarmDocsPage): DocsSitemapPageInput {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\nfunction toDocsLlmsPage(page: LoadedFarmDocsPage): DocsLlmsTxtPageInput {\n  return toFarmDocsMarkdownPage(page);\n}\n\nfunction getDocsLlmsOptions(context: FarmDocsAPIContext, request: Request) {\n  const configured = isRecord(context.docs.config.llmsTxt) ? context.docs.config.llmsTxt : {};\n  return {\n    enabled: true,\n    baseUrl: new URL(request.url).origin,\n    siteTitle: getDocsTitle(context.docs),\n    siteDescription: getDocsDescription(context.docs),\n    ...configured,\n  };\n}\n\nfunction getDocsDiscoveryOptions(context: FarmDocsAPIContext, request: Request) {\n  const origin = new URL(request.url).origin;\n\n  return {\n    origin,\n    entry: context.docs.entry,\n    i18n: null,\n    search: context.docs.config.search ?? true,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(context.docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n    feedback: undefined,\n    llms: getDocsLlmsOptions(context, request),\n    sitemap: context.docs.config.sitemap ?? true,\n    robots: context.docs.config.robots ?? true,\n    openapi: context.docs.config.apiReference,\n    markdown: {\n      acceptHeader: true,\n      signatureAgentHeader: true,\n    },\n  };\n}\n\nfunction buildSitemapManifest(context: FarmDocsAPIContext, request: Request) {\n  const origin = new URL(request.url).origin;\n  return buildDocsSitemapManifest({\n    pages: getLoadedDocsPages(context).map(toDocsSitemapPage),\n    entry: context.docs.entry,\n    siteTitle: getDocsTitle(context.docs),\n    baseUrl: origin,\n  });\n}\n\nfunction renderLlmsTxt(context: FarmDocsAPIContext, request: Request, full: boolean): string {\n  const generated = renderDocsLlmsTxt(\n    getLoadedDocsPages(context).map(toDocsLlmsPage),\n    getDocsLlmsOptions(context, request),\n  );\n\n  return full ? generated.llmsFullTxt : generated.llmsTxt;\n}\n\nfunction renderSkillDocument(context: FarmDocsAPIContext, request: Request): string {\n  const farmAliases = [\n    \"## Farm API Route Aliases\",\n    \"\",\n    \"- Search JSON: /api/docs?query=<term>\",\n    \"- Config JSON: /api/docs?format=config\",\n    \"- Markdown by query: /api/docs?format=markdown&path=<slug>\",\n    \"- Markdown by path: /api/docs/<slug>.md\",\n    \"- LLM summary: /api/docs?format=llms\",\n    \"- Full LLM document: /api/docs?format=llms-full\",\n    \"- Sitemap XML: /api/docs?format=sitemap-xml\",\n    \"- Agent spec JSON: /api/docs/agent/spec\",\n  ].join(\"\\n\");\n\n  return `${renderDocsSkillDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n\\n${farmAliases}\\n`;\n}\n\nfunction renderAgentsDocument(context: FarmDocsAPIContext, request: Request): string {\n  return `${renderDocsAgentsDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n`;\n}\n\nfunction buildAgentSpec(context: FarmDocsAPIContext, request: Request) {\n  const url = new URL(request.url);\n  const origin = url.origin;\n  const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n  const spec = buildDocsAgentDiscoverySpec(getDocsDiscoveryOptions(context, request));\n  const title = getDocsTitle(context.docs);\n\n  return {\n    ...spec,\n    name: title,\n    site: {\n      ...spec.site,\n      title,\n      description: getDocsDescription(context.docs),\n      entry: context.docs.entry,\n    },\n    entry: context.docs.entry,\n    routes: {\n      docs: `${origin}${context.docs.entry}`,\n      config: `${origin}/api/docs?format=config`,\n      search: `${origin}/api/docs?query=<term>`,\n      markdown: `${origin}/api/docs/<slug>.md`,\n      markdownQuery: `${origin}/api/docs?format=markdown&path=<slug>`,\n      llms: `${origin}/api/docs?format=llms`,\n      llmsFull: `${origin}/api/docs?format=llms-full`,\n      sitemapXml: `${origin}/api/docs?format=sitemap-xml`,\n      sitemapMarkdown: `${origin}/api/docs?format=sitemap-md`,\n      robots: `${origin}/api/docs?format=robots`,\n      skill: `${origin}/api/docs?format=skill`,\n      agents: `${origin}/api/docs?format=agents`,\n      agentSpec: `${origin}/api/docs/agent/spec`,\n    },\n    capabilities: {\n      ...spec.capabilities,\n      search: spec.capabilities.search,\n      markdown: spec.capabilities.markdownRoutes,\n      llms: spec.capabilities.llms,\n      sitemap: spec.capabilities.sitemap,\n      robots: spec.capabilities.robots,\n      post: false,\n    },\n    pages,\n  };\n}\n\nfunction buildDiagnostics(context: FarmDocsAPIContext) {\n  const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n  const diagnostics = buildFarmingDocsDiagnostics(context.docs.config, {\n    entry: context.docs.entry,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(context.docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n  });\n\n  return {\n    ...diagnostics,\n    enabled: context.docs.enabled,\n    entry: context.docs.entry,\n    root: context.root,\n    srcDir: context.srcDir,\n    contentDir: context.contentDir,\n    configPath: context.docs.configPath || null,\n    pageCount: pages.length,\n    pages,\n  };\n}\n\nasync function searchDocs(context: FarmDocsAPIContext, request: Request, query: string) {\n  const loadedPages = getLoadedDocsPages(context);\n  const sourcePages = loadedPages.map(toDocsSourcePage);\n  const sourcePageByUrl = new Map(sourcePages.map((page) => [page.url, page]));\n  const resultLimit =\n    isRecord(context.docs.config.search) &&\n    typeof context.docs.config.search.maxResults === \"number\"\n      ? context.docs.config.search.maxResults\n      : undefined;\n\n  const results = await performDocsSearch({\n    pages: sourcePages,\n    query,\n    search: context.docs.config.search ?? true,\n    pathname: new URL(request.url).pathname,\n    siteTitle: getDocsTitle(context.docs),\n    limit: resultLimit,\n  });\n\n  return results.map((result) => {\n    const pageUrl = result.url.split(\"#\")[0];\n    const page = sourcePageByUrl.get(pageUrl);\n    return {\n      ...result,\n      title: page?.title || result.content,\n      href: page?.url || pageUrl,\n      description: result.description || page?.description,\n    };\n  });\n}\n\nasync function resolveAPIContext(options: FarmDocsAPIOptions): Promise<FarmDocsAPIContext> {\n  const runtimeConfig = globalThis.__FARM_DOCS_RUNTIME_CONFIG__;\n  const root = options.rootDir || options.root || runtimeConfig?.root || process.cwd();\n  const srcDir = options.srcDir || runtimeConfig?.srcDir || \"src\";\n  const canUseRuntimeDocs =\n    options.docs === undefined &&\n    options.config === undefined &&\n    options.configPath === undefined &&\n    options.entry === undefined &&\n    options.docsPath === undefined &&\n    options.contentDir === undefined &&\n    options.root === undefined &&\n    options.rootDir === undefined &&\n    options.srcDir === undefined;\n  const docsInput =\n    options.docs ??\n    (canUseRuntimeDocs ? runtimeConfig?.docs : undefined) ??\n    ({\n      enabled: true,\n      entry: options.entry,\n      docsPath: options.docsPath,\n      contentDir: options.contentDir,\n      config: options.config,\n      configPath: options.configPath,\n    } satisfies Exclude<FarmDocsUserConfig, boolean>);\n  const docs = isResolvedDocsConfig(docsInput)\n    ? docsInput\n    : await resolveDocsConfig(docsInput, { root, srcDir });\n\n  return {\n    root,\n    srcDir,\n    docs,\n    contentDir: resolveFarmDocsContentDir(docs, { root, srcDir }),\n  };\n}\n\nasync function handleDocsAPIGet(request: Request, context: FarmDocsAPIContext): Promise<Response> {\n  if (!context.docs.enabled) {\n    return json({ error: \"Docs are disabled\" }, { status: 404 });\n  }\n\n  const url = new URL(request.url);\n  const format = getDocsAPIFormat(request);\n  const pathTarget = getDocsAPIPathTarget(request);\n\n  if (format === \"config\" || format === \"docs-config\") {\n    return json({\n      entry: context.docs.entry,\n      contentDir: context.docs.contentDir || context.docs.config.contentDir || null,\n      config: context.docs.config,\n      map: buildDocsConfigMap(context.docs.config, {\n        file: context.docs.configPath || \"farm.config.ts\",\n      }),\n    });\n  }\n\n  if (format === \"skill\")\n    return text(renderSkillDocument(context, request), \"text/markdown; charset=utf-8\");\n  if (format === \"agents\")\n    return text(renderAgentsDocument(context, request), \"text/markdown; charset=utf-8\");\n  if (format === \"agent\" || format === \"agent-spec\") return json(buildAgentSpec(context, request));\n  if (format === \"diagnostics\") return json(buildDiagnostics(context));\n  if (format === \"llms\")\n    return text(renderLlmsTxt(context, request, false), \"text/plain; charset=utf-8\");\n  if (format === \"llms-full\")\n    return text(renderLlmsTxt(context, request, true), \"text/plain; charset=utf-8\");\n  if (format === \"sitemap-md\") {\n    return text(\n      renderDocsSitemapMarkdown(buildSitemapManifest(context, request), {\n        includeDescriptions: true,\n      }),\n      \"text/markdown; charset=utf-8\",\n    );\n  }\n  if (format === \"sitemap-xml\" || format === \"sitemap\") {\n    const origin = new URL(request.url).origin;\n    return text(\n      renderDocsSitemapXml(buildSitemapManifest(context, request), {\n        baseUrl: origin,\n        includeLastmod: true,\n      }),\n      \"application/xml; charset=utf-8\",\n    );\n  }\n  if (format === \"robots\") {\n    return text(\n      renderDocsRobotsTxt({\n        entry: context.docs.entry,\n        sitemap: context.docs.config.sitemap ?? true,\n        robots: context.docs.config.robots ?? true,\n        baseUrl: new URL(request.url).origin,\n      }),\n      \"text/plain; charset=utf-8\",\n    );\n  }\n\n  if (format === \"markdown\" || url.pathname.endsWith(\".md\")) {\n    const pathParam = url.searchParams.get(\"path\") || url.searchParams.get(\"slug\");\n    const slug = normalizeDocsApiSlug(pathParam ?? pathTarget.slug ?? \"\", context.docs);\n    const page = loadFarmDocsPage(context.contentDir, context.docs, slug);\n    if (!page) return text(\"Docs page not found\\n\", \"text/plain; charset=utf-8\", { status: 404 });\n    return text(\n      renderDocsMarkdownDocument(toFarmDocsMarkdownPage(page), {\n        origin: new URL(request.url).origin,\n        llms: getDocsLlmsOptions(context, request),\n        sitemap: context.docs.config.sitemap,\n      }),\n      \"text/markdown; charset=utf-8\",\n    );\n  }\n\n  const query = url.searchParams.get(\"query\") || url.searchParams.get(\"q\") || \"\";\n  if (!query.trim()) return json([]);\n  return json(await searchDocs(context, request, query));\n}\n\nexport function createDocsAPI(\n  options: FarmDocsAPIOptions = {},\n  cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIRouteHandlers {\n  let contextPromise: Promise<FarmDocsAPIContext> | undefined;\n  const getContext = () => {\n    contextPromise ??= resolveAPIContext(options);\n    return contextPromise;\n  };\n  const integration = resolveDocsCloudIntegration(cloudIntegration);\n\n  return {\n    async GET(request: Request) {\n      if (integration && isDocsCloudGetRequest(request)) {\n        return integration.docsCloud.handleRequest(request, integration.routeOptions);\n      }\n\n      return handleDocsAPIGet(request, await getContext());\n    },\n    async POST(request: Request) {\n      if (integration && (await isDocsCloudPostRequest(request))) {\n        return integration.docsCloud.handleRequest(request, integration.routeOptions);\n      }\n\n      return json(\n        {\n          error: \"AI is not enabled for this Farm docs API route yet.\",\n        },\n        { status: 501 },\n      );\n    },\n  };\n}\n\nexport function createFarmDocsAPIHandler(\n  options: FarmDocsAPIOptions = {},\n  cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIHandler {\n  const handlers = createDocsAPI(options, cloudIntegration);\n\n  return async function handleFarmDocsAPIRequest(request: Request): Promise<Response | null> {\n    if (!isFarmDocsAPIRequest(request)) return null;\n\n    const method = request.method.toUpperCase();\n    if (method === \"GET\" || method === \"HEAD\") {\n      const response = await handlers.GET(request);\n      return method === \"HEAD\" ? omitHeadBody(response) : response;\n    }\n    if (method === \"POST\") {\n      return handlers.POST(request);\n    }\n\n    return json(\n      {\n        error: \"Method Not Allowed\",\n      },\n      {\n        status: 405,\n        headers: {\n          Allow: \"GET, HEAD, POST\",\n        },\n      },\n    );\n  };\n}\n","export {\n  createFarmDocsHandler,\n  discoverFarmDocsPages,\n  getFarmDocsDocumentNavigationMatchers,\n  getFarmDocsRouteTypeEntries,\n  isFarmDocsRequest,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n} from \"./handler\";\nexport {\n  createFarmDocsAdapterHandler,\n  hasFarmDocsRuntimeAdapter,\n  type FarmDocsAdapterHandlerOptions,\n} from \"./adapter\";\nexport { createDocsAPI, createFarmDocsAPIHandler, isFarmDocsAPIRequest } from \"./api\";\nexport type { FarmDocsHandlerOptions, FarmDocsPage, LoadedFarmDocsPage } from \"./handler\";\nexport type {\n  FarmDocsAPIHandler,\n  FarmDocsAPIOptions,\n  FarmDocsAPIRouteHandlers,\n  FarmDocsCloudIntegration,\n  FarmDocsCloudRouteOptions,\n  FarmDocsCloudServer,\n} from \"./api\";\nexport type {\n  FarmDocsConfigInput,\n  FarmDocsNavigationConfig,\n  FarmDocsResolvedConfig,\n  FarmDocsSocialImageConfig,\n  FarmDocsSocialImageFonts,\n  FarmDocsSidebarItem,\n  FarmDocsUserConfig,\n} from \"./types\";\n","import type { OpenAPIConfig } from \"../config\";\nimport type { APIRouteInfo } from \"../type-generator\";\nimport * as z from \"zod\";\n\nexport interface OpenAPISpec {\n  openapi: string;\n  info: {\n    title: string;\n    description?: string;\n    version: string;\n    contact?: {\n      name?: string;\n      email?: string;\n      url?: string;\n    };\n    license?: {\n      name: string;\n      url?: string;\n    };\n  };\n  servers?: Array<{\n    url: string;\n    description?: string;\n  }>;\n  paths: Record<string, any>;\n  components?: {\n    schemas?: Record<string, any>;\n    securitySchemes?: Record<string, any>;\n  };\n}\n\ntype AllowedType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\nconst allowedType = new Set([\"string\", \"number\", \"boolean\", \"array\", \"object\"]);\n\nexport class OpenAPIGenerator {\n  private config: OpenAPIConfig;\n  private appDir: string;\n\n  constructor(appDir: string, config: OpenAPIConfig) {\n    this.appDir = appDir;\n    this.config = config;\n  }\n\n  /**\n   * Get type from Zod type\n   */\n  private getTypeFromZodType(zodType: z.ZodType<any>): AllowedType {\n    const tag = (zodType as any)._def?.type;\n    return typeof tag === \"string\" && allowedType.has(tag) ? (tag as AllowedType) : \"string\";\n  }\n\n  /**\n   * Process Zod type to OpenAPI schema\n   */\n  private processZodType(zodType: z.ZodType<any>): any {\n    // Handle ZodOptional and ZodNullable\n    if (zodType instanceof z.ZodOptional || zodType instanceof z.ZodNullable) {\n      const innerType = (zodType as any)._def.innerType;\n      const innerSchema = this.processZodType(innerType);\n      return {\n        ...innerSchema,\n        nullable: true,\n      };\n    }\n\n    // Handle ZodDefault. The value is always present after parsing, so the\n    // documented type is the wrapped one.\n    if (zodType instanceof z.ZodDefault) {\n      return this.processZodType((zodType as any)._def.innerType);\n    }\n\n    // Handle ZodObject\n    if (zodType instanceof z.ZodObject) {\n      const shape = (zodType as any).shape;\n      if (shape) {\n        const properties: Record<string, any> = {};\n        const required: string[] = [];\n        Object.entries(shape).forEach(([key, value]) => {\n          if (value instanceof z.ZodType) {\n            properties[key] = this.processZodType(value as z.ZodType<any>);\n            if (!(value instanceof z.ZodOptional)) {\n              required.push(key);\n            }\n          }\n        });\n        return {\n          type: \"object\",\n          properties,\n          ...(required.length > 0 ? { required } : {}),\n          description: (zodType as any).description,\n        };\n      }\n    }\n\n    // Handle ZodArray\n    if (zodType instanceof z.ZodArray) {\n      return {\n        type: \"array\",\n        items: this.processZodType((zodType as any)._def.element),\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodEnum\n    if (zodType instanceof z.ZodEnum) {\n      return {\n        type: \"string\",\n        enum: (zodType as any).options,\n        description: (zodType as any).description,\n      };\n    }\n\n    // For primitive types\n    const baseSchema: any = {\n      type: this.getTypeFromZodType(zodType),\n      description: (zodType as any).description,\n    };\n\n    // Add constraints if available. `min`/`max` are methods rather than values, so\n    // the bounds are read from `minValue`/`maxValue`. An absent bound is reported as\n    // `null` or as an infinity depending on the schema, and neither belongs in the\n    // document; a finite check keeps a `0` bound and drops both.\n    const constraints: Array<[string, unknown]> = [\n      [\"minLength\", (zodType as any).minLength],\n      [\"maxLength\", (zodType as any).maxLength],\n      [\"minimum\", (zodType as any).minValue],\n      [\"maximum\", (zodType as any).maxValue],\n    ];\n    for (const [key, value] of constraints) {\n      // Zod 4's .int() implies bounds of +/-Number.MAX_SAFE_INTEGER; those are\n      // implementation details of the safe-integer range, not author-declared\n      // constraints, and would otherwise stamp every integer field with\n      // maximum: 9007199254740991.\n      if (Number.isFinite(value) && Math.abs(value as number) !== Number.MAX_SAFE_INTEGER) {\n        baseSchema[key] = value;\n      }\n    }\n\n    return baseSchema;\n  }\n\n  /**\n   * Generate standard error responses\n   */\n  private getStandardResponses(): Record<string, any> {\n    return {\n      \"200\": {\n        description: \"Successful response\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              description: \"Response data\",\n            },\n          },\n        },\n      },\n      \"400\": {\n        description: \"Bad Request. Usually due to missing parameters, or invalid parameters.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n                error: { type: \"string\" },\n              },\n              required: [\"message\"],\n            },\n          },\n        },\n      },\n      \"401\": {\n        description: \"Unauthorized. Due to missing or invalid authentication.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n              required: [\"message\"],\n            },\n          },\n        },\n      },\n      \"403\": {\n        description:\n          \"Forbidden. You do not have permission to access this resource or to perform this action.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n      \"404\": {\n        description: \"Not Found. The requested resource was not found.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n      \"429\": {\n        description: \"Too Many Requests. You have exceeded the rate limit. Try again later.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n      \"500\": {\n        description:\n          \"Internal Server Error. This is a problem with the server that you cannot fix.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n                error: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n    };\n  }\n\n  /**\n   * Generate OpenAPI spec from API routes\n   */\n  async generateSpec(routes: APIRouteInfo[]): Promise<OpenAPISpec> {\n    const spec: OpenAPISpec = {\n      openapi: \"3.0.3\",\n      info: {\n        title: this.config.title || \"API Documentation\",\n        description: this.config.description || \"Auto-generated API documentation\",\n        version: this.config.version || \"1.0.0\",\n        ...(this.config.contact && { contact: this.config.contact }),\n        ...(this.config.license && { license: this.config.license }),\n      },\n      servers: this.config.servers || [\n        { url: \"http://localhost:3000\", description: \"Development server\" },\n      ],\n      paths: {},\n      components: {\n        schemas: {},\n        securitySchemes: {\n          bearerAuth: {\n            type: \"http\",\n            scheme: \"bearer\",\n            description: \"Bearer token authentication\",\n          },\n          apiKeyCookie: {\n            type: \"apiKey\",\n            in: \"cookie\",\n            name: \"session\",\n            description: \"API Key authentication via cookie\",\n          },\n        },\n      },\n    };\n\n    // Group routes by path\n    const routeGroups = new Map<string, APIRouteInfo[]>();\n    for (const route of routes) {\n      const key = route.path;\n      if (!routeGroups.has(key)) {\n        routeGroups.set(key, []);\n      }\n      routeGroups.get(key)!.push(route);\n    }\n\n    // Generate paths\n    for (const [path, routeList] of routeGroups) {\n      const openAPIPath = this.convertToOpenAPIPath(path);\n      spec.paths[openAPIPath] = {};\n\n      for (const route of routeList) {\n        for (const method of route.methods) {\n          const operation = await this.generateOperation(route, method);\n          if (method === \"QUERY\") {\n            const additionalOperations =\n              spec.paths[openAPIPath][\"x-oai-additionalOperations\"] ?? {};\n            additionalOperations.QUERY = operation;\n            spec.paths[openAPIPath][\"x-oai-additionalOperations\"] = additionalOperations;\n          } else {\n            spec.paths[openAPIPath][method.toLowerCase()] = operation;\n          }\n        }\n      }\n    }\n\n    return spec;\n  }\n\n  /**\n   * Convert Farm.js API path to OpenAPI path format\n   */\n  private convertToOpenAPIPath(path: string): string {\n    // Convert /api/auth/login to /auth/login\n    return path.replace(/^\\/api/, \"\");\n  }\n\n  /**\n   * Extract request body schema from endpoint\n   */\n  private async getRequestBody(route: APIRouteInfo, method: string): Promise<any> {\n    if (![\"QUERY\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method)) {\n      return undefined;\n    }\n\n    try {\n      // Try to dynamically load the route module\n      const modulePath = route.filePath;\n      const routeModule = await import(/* @vite-ignore */ modulePath);\n\n      // Get the method handler (GET, POST, etc.)\n      const handler = routeModule[method];\n\n      // Check for Farm.js endpoint format: handler.__types.body\n      if (handler && handler.__types && handler.__types.body) {\n        const bodySchema = handler.__types.body;\n\n        if (bodySchema instanceof z.ZodObject || bodySchema instanceof z.ZodOptional) {\n          const shape = (bodySchema as any).shape || (bodySchema as any)._def?.innerType?.shape;\n          if (shape) {\n            const properties: Record<string, any> = {};\n            const required: string[] = [];\n\n            Object.entries(shape).forEach(([key, value]) => {\n              if (value instanceof z.ZodType) {\n                properties[key] = this.processZodType(value as z.ZodType<any>);\n                if (!(value instanceof z.ZodOptional)) {\n                  required.push(key);\n                }\n              }\n            });\n            return {\n              required: bodySchema instanceof z.ZodOptional ? false : true,\n              content: {\n                \"application/json\": {\n                  schema: {\n                    type: \"object\",\n                    properties,\n                    ...(required.length > 0 ? { required } : {}),\n                  },\n                },\n              },\n            };\n          }\n        }\n      }\n\n      // Fallback: Check for better-call format: handler._type.body\n      if (handler && handler._type && handler._type.body) {\n        const bodySchema = handler._type.body;\n\n        if (bodySchema instanceof z.ZodObject || bodySchema instanceof z.ZodOptional) {\n          const shape = (bodySchema as any).shape || (bodySchema as any)._def?.innerType?.shape;\n          if (shape) {\n            const properties: Record<string, any> = {};\n            const required: string[] = [];\n\n            Object.entries(shape).forEach(([key, value]) => {\n              if (value instanceof z.ZodType) {\n                properties[key] = this.processZodType(value as z.ZodType<any>);\n                if (!(value instanceof z.ZodOptional)) {\n                  required.push(key);\n                }\n              }\n            });\n\n            return {\n              required: bodySchema instanceof z.ZodOptional ? false : true,\n              content: {\n                \"application/json\": {\n                  schema: {\n                    type: \"object\",\n                    properties,\n                    ...(required.length > 0 ? { required } : {}),\n                  },\n                },\n              },\n            };\n          }\n        }\n      }\n    } catch (error) {\n      // If we can't load the module, return generic schema\n      console.warn(`Could not extract schema from ${route.filePath}:`, error);\n    }\n\n    // Fallback to generic schema\n    return {\n      required: true,\n      content: {\n        \"application/json\": {\n          schema: {\n            type: \"object\",\n            description: \"Request body\",\n          },\n        },\n      },\n    };\n  }\n\n  /**\n   * Extract query parameters from endpoint\n   */\n  private async getParameters(route: APIRouteInfo, method: string): Promise<any[]> {\n    const parameters: any[] = [];\n\n    try {\n      // Try to dynamically load the route module\n      const modulePath = route.filePath;\n      const routeModule = await import(/* @vite-ignore */ modulePath);\n\n      // Get the method handler\n      const handler = routeModule[method];\n\n      // Check for Farm.js endpoint format: handler.__types.query\n      if (handler && handler.__types && handler.__types.query) {\n        const querySchema = handler.__types.query;\n\n        if (querySchema instanceof z.ZodObject) {\n          Object.entries((querySchema as any).shape).forEach(([key, value]) => {\n            if (value instanceof z.ZodType) {\n              parameters.push({\n                name: key,\n                in: \"query\",\n                required: !(value instanceof z.ZodOptional),\n                schema: this.processZodType(value as z.ZodType<any>),\n              });\n            }\n          });\n        }\n      }\n\n      // Fallback: Check for better-call format: handler._type.query\n      if (handler && handler._type && handler._type.query) {\n        const querySchema = handler._type.query;\n\n        if (querySchema instanceof z.ZodObject) {\n          Object.entries((querySchema as any).shape).forEach(([key, value]) => {\n            if (value instanceof z.ZodType) {\n              parameters.push({\n                name: key,\n                in: \"query\",\n                required: !(value instanceof z.ZodOptional),\n                schema: this.processZodType(value as z.ZodType<any>),\n              });\n            }\n          });\n        }\n      }\n    } catch (error) {\n      console.warn(`Could not extract query params from ${route.filePath}:`, error);\n    }\n\n    return parameters;\n  }\n\n  /**\n   * Generate OpenAPI operation from route info\n   */\n  private async generateOperation(route: APIRouteInfo, method: string): Promise<any> {\n    const operation: any = {\n      summary: this.generateSummary(route.path, method),\n      description: this.generateDescription(route.path, method),\n      operationId: this.generateOperationId(route.path, method),\n      tags: this.generateTags(route.path),\n      security: [{ bearerAuth: [] }, { apiKeyCookie: [] }],\n      responses: this.getStandardResponses(),\n    };\n\n    // Add query parameters\n    const parameters = await this.getParameters(route, method);\n    if (parameters.length > 0) {\n      operation.parameters = parameters;\n    }\n\n    // QUERY and mutation methods can carry typed request content.\n    if ([\"QUERY\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method)) {\n      operation.requestBody = await this.getRequestBody(route, method);\n    }\n\n    return operation;\n  }\n\n  /**\n   * Generate operation summary\n   */\n  private generateSummary(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n    const pathParts = cleanPath.split(\"/\");\n    const lastPart = pathParts[pathParts.length - 1];\n\n    const action =\n      method === \"GET\"\n        ? \"Get\"\n        : method === \"QUERY\"\n          ? \"Query\"\n          : method === \"POST\"\n            ? \"Create\"\n            : method === \"PUT\"\n              ? \"Update\"\n              : method === \"DELETE\"\n                ? \"Delete\"\n                : method === \"PATCH\"\n                  ? \"Update\"\n                  : method;\n\n    return `${action} ${lastPart}`;\n  }\n\n  /**\n   * Generate operation description\n   */\n  private generateDescription(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n    return `${method} ${cleanPath} endpoint`;\n  }\n\n  /**\n   * Generate operation ID\n   */\n  private generateOperationId(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\").replace(/\\//g, \"_\");\n    return `${method.toLowerCase()}_${cleanPath}`;\n  }\n\n  /**\n   * Generate tags for grouping operations\n   */\n  private generateTags(path: string): string[] {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n    const pathParts = cleanPath.split(\"/\");\n\n    if (pathParts.length > 1) {\n      return [pathParts[0]]; // Use first part as tag\n    }\n\n    return [\"default\"];\n  }\n\n  /**\n   * Generate OpenAPI spec file\n   */\n  async generateSpecFile(routes: APIRouteInfo[], outputPath: string): Promise<void> {\n    const spec = await this.generateSpec(routes);\n    const fs = require(\"fs\");\n    const path = require(\"path\");\n\n    // Ensure directory exists\n    const dir = path.dirname(outputPath);\n    if (!fs.existsSync(dir)) {\n      fs.mkdirSync(dir, { recursive: true });\n    }\n\n    // Write spec file\n    fs.writeFileSync(outputPath, JSON.stringify(spec, null, 2));\n  }\n}\n","import { OpenAPIGenerator, type OpenAPISpec } from \"./generator\";\nimport { APITypeGenerator } from \"../type-generator\";\nimport type { OpenAPIConfig } from \"../config\";\n\nfunction escapeHTML(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&#39;\");\n}\n\nexport function renderOpenAPIReferenceHTML(spec: OpenAPISpec, config: OpenAPIConfig): string {\n  return `\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>${escapeHTML(config.title || \"API Documentation\")}</title>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <link rel=\"icon\" href=\"data:,\" />\n  </head>\n  <body>\n    <script\n      id=\"api-reference\"\n      data-url=\"data:application/json;base64,${Buffer.from(JSON.stringify(spec)).toString(\"base64\")}\"\n    ></script>\n    <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n  </body>\n</html>\n    `;\n}\n\nexport class OpenAPIManager {\n  private generator: OpenAPIGenerator;\n  private apiTypeGenerator: APITypeGenerator;\n  private config: OpenAPIConfig;\n  private appDir: string;\n  private specCache: any = null;\n\n  constructor(appDir: string | readonly string[], config: OpenAPIConfig) {\n    const appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n    this.appDir = appDirs[appDirs.length - 1];\n    this.config = config;\n    this.generator = new OpenAPIGenerator(this.appDir, config);\n    this.apiTypeGenerator = new APITypeGenerator(appDirs);\n  }\n\n  /**\n   * Generate OpenAPI spec from API routes\n   */\n  async generateSpec(): Promise<any> {\n    try {\n      // Get API routes using the existing type generator\n      const routes = this.apiTypeGenerator.scanAPIRoutes();\n\n      // Generate OpenAPI spec (now async)\n      const spec = await this.generator.generateSpec(routes);\n\n      // Cache the spec\n      this.specCache = spec;\n\n      return spec;\n    } catch (error) {\n      console.error(\"Failed to generate OpenAPI spec:\", error);\n      return null;\n    }\n  }\n\n  /**\n   * Get cached spec or generate new one\n   */\n  async getSpec(): Promise<any> {\n    if (this.specCache) {\n      return this.specCache;\n    }\n\n    return await this.generateSpec();\n  }\n\n  /**\n   * Generate and save OpenAPI spec file\n   */\n  async generateSpecFile(): Promise<void> {\n    try {\n      const routes = this.apiTypeGenerator.scanAPIRoutes();\n      const outputPath = `${this.appDir}/lib/openapi.spec.json`;\n\n      await this.generator.generateSpecFile(routes, outputPath);\n      console.log(\"✅ OpenAPI spec generated at:\", outputPath);\n    } catch (error) {\n      console.error(\"Failed to generate OpenAPI spec file:\", error);\n    }\n  }\n\n  /**\n   * Invalidate cache and regenerate spec\n   */\n  async invalidateCache(): Promise<void> {\n    this.specCache = null;\n    await this.generateSpec();\n  }\n\n  /**\n   * Get the docs route handler\n   */\n  getDocsRouteHandler() {\n    return async (req: any, res: any) => {\n      try {\n        const method = String(req.method || \"GET\").toUpperCase();\n        if (method !== \"GET\" && method !== \"HEAD\") {\n          res.statusCode = 405;\n          res.setHeader(\"Allow\", \"GET, HEAD\");\n          res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n          res.end(\"Method Not Allowed\");\n          return;\n        }\n\n        const spec = await this.getSpec();\n\n        if (!spec) {\n          res.statusCode = 500;\n          res.setHeader(\"Content-Type\", \"text/html\");\n          res.end(`\n            <html>\n              <body>\n                <h1>Error</h1>\n                <p>Failed to generate OpenAPI specification</p>\n              </body>\n            </html>\n          `);\n          return;\n        }\n\n        // Set headers for HTML response\n        res.statusCode = 200;\n        res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n        res.setHeader(\"Cache-Control\", \"public, max-age=0, must-revalidate\");\n        res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n\n        // Generate HTML with Scalar\n        res.end(method === \"HEAD\" ? undefined : renderOpenAPIReferenceHTML(spec, this.config));\n      } catch (error) {\n        console.error(\"Error serving docs route:\", error);\n        res.statusCode = 500;\n        res.setHeader(\"Content-Type\", \"text/html\");\n        res.end(`\n          <html>\n            <body>\n              <h1>Error</h1>\n              <p>Failed to load API documentation</p>\n            </body>\n          </html>\n        `);\n      }\n    };\n  }\n}\n","import path from \"node:path\";\nimport { getDeployTargetForPreset } from \"./config\";\nimport { resolveCronConfig, type FarmCronJob } from \"./cron\";\nimport {\n  mergeFarmRouteRuntimeConfigs,\n  resolveFarmRouteRuleRuntimeConfig,\n  resolveFarmRouteRuntimeConfig,\n  type ResolvedFarmRouteRuntimeConfig,\n} from \"./route-runtime\";\nimport type { FarmConfig } from \"./types\";\nimport type { FarmDiscoveredWorkflow } from \"./workflows\";\n\ntype RouteMapEntry = {\n  pattern: string;\n  modulePath: string;\n};\n\ntype RouteManagerLike = {\n  getRoutes(): Map<string, RouteMapEntry>;\n  getLayouts(): Map<string, RouteMapEntry>;\n  getLoadings(): Map<string, RouteMapEntry>;\n  getErrors(): Map<string, RouteMapEntry>;\n  resolveRouteRuntimeConfig?(\n    pattern: string,\n  ): Promise<ResolvedFarmRouteRuntimeConfig> | ResolvedFarmRouteRuntimeConfig;\n};\n\ntype APIRouteManagerLike = {\n  getRoutes(): Map<\n    string,\n    {\n      path: string;\n      filePath: string;\n      methods: string[];\n      runtime?: \"auto\" | \"node\" | \"edge\";\n      regions?: \"auto\" | readonly string[];\n      maxDuration?: \"auto\" | number;\n    }\n  >;\n};\n\ntype MiddlewareManagerLike = {\n  getMiddlewares(): Array<{\n    path: string;\n    filePath: string;\n    handlers: unknown[];\n    source?: \"config\" | \"file\";\n  }>;\n};\n\ntype IntegrationLike = {\n  kind?: string;\n  type?: string;\n  category?: string;\n  serverRuntime?: boolean;\n  routes?: ReadonlyArray<{\n    path: string;\n    method?: string;\n    methods?: readonly string[];\n  }>;\n  middleware?: readonly unknown[];\n  providers?: readonly unknown[];\n  schema?: {\n    models?: Record<string, unknown>;\n  };\n};\n\nexport type FarmDevtoolsRuntime = {\n  runtime: \"auto\" | \"node\" | \"edge\";\n  regions?: string[];\n  maxDuration?: number;\n};\n\nexport type FarmDevtoolsDiagnostic = {\n  severity: \"error\" | \"warning\" | \"info\";\n  code: string;\n  title: string;\n  message: string;\n  action?: string;\n};\n\nexport type FarmDevtoolsSnapshot = {\n  generatedAt: string;\n  health: \"ready\" | \"attention\" | \"error\";\n  project: {\n    name: string;\n    root: string;\n    srcDir: string;\n    basePath: string;\n    deploymentId: string;\n  };\n  deployment: {\n    target: string;\n    preset: string;\n    outputDir?: string;\n  };\n  counts: {\n    pages: number;\n    layouts: number;\n    loadingBoundaries: number;\n    errorBoundaries: number;\n    apiRoutes: number;\n    middleware: number;\n    integrations: number;\n    storageMounts: number;\n    cronJobs: number;\n    workflows: number;\n    layers: number;\n    diagnostics: number;\n  };\n  routes: Array<{\n    kind: \"page\" | \"layout\" | \"loading\" | \"error\";\n    pattern: string;\n    filePath: string;\n    runtime?: FarmDevtoolsRuntime;\n  }>;\n  apiRoutes: Array<{\n    path: string;\n    methods: string[];\n    filePath: string;\n    runtime: FarmDevtoolsRuntime;\n  }>;\n  middleware: Array<{\n    path: string;\n    source: \"config\" | \"file\";\n    filePath: string;\n    handlerCount: number;\n  }>;\n  integrations: Array<{\n    key: string;\n    type: string;\n    category: string;\n    serverRuntime: boolean;\n    routes: Array<{ path: string; methods: string[] }>;\n    middlewareCount: number;\n    providerCount: number;\n    schemaModelCount: number;\n  }>;\n  storage: Array<{\n    mount: string;\n    driver: string;\n    default: boolean;\n  }>;\n  cron: FarmCronJob[];\n  workflows: Array<{\n    id: string;\n    filePath: string;\n    routePath: string;\n    schedule: string[];\n    timezone?: string;\n  }>;\n  layers: Array<{\n    name: string;\n    source: string;\n    srcDir: string;\n  }>;\n  environment: {\n    server: string[];\n    public: string[];\n  };\n  docs: {\n    enabled: boolean;\n    entry?: string;\n  };\n  features: {\n    openapi: boolean;\n    markdown: boolean;\n    serverComponents: boolean;\n    serverActions: boolean;\n    optimizedBoundary: boolean;\n    observability: boolean;\n  };\n  diagnostics: FarmDevtoolsDiagnostic[];\n};\n\nexport interface CreateFarmDevtoolsSnapshotInput {\n  root: string;\n  srcDir: string;\n  routeManager: RouteManagerLike;\n  apiRouteManager: APIRouteManagerLike;\n  middlewareManager: MiddlewareManagerLike;\n  config?: FarmConfig & { openapi?: { enabled?: boolean } };\n  workflows?: readonly FarmDiscoveredWorkflow[];\n  now?: () => Date;\n  env?: Record<string, string | undefined>;\n}\n\nfunction normalizePath(value: string): string {\n  return value.replace(/\\\\/g, \"/\");\n}\n\nfunction toProjectPath(root: string, filePath: string): string {\n  const normalizedRoot = normalizePath(root).replace(/\\/$/, \"\");\n  const normalizedFile = normalizePath(filePath);\n  if (normalizedFile.startsWith(normalizedRoot + \"/\")) {\n    return normalizedFile.slice(normalizedRoot.length + 1);\n  }\n  return normalizedFile;\n}\n\nfunction sortByPath<T extends { path?: string; pattern?: string }>(items: T[]): T[] {\n  return [...items].sort((a, b) =>\n    (a.path || a.pattern || \"\").localeCompare(b.path || b.pattern || \"\"),\n  );\n}\n\nfunction toRuntime(value: ResolvedFarmRouteRuntimeConfig): FarmDevtoolsRuntime {\n  return {\n    runtime: value.runtime,\n    ...(value.regions ? { regions: [...value.regions] } : {}),\n    ...(value.maxDuration ? { maxDuration: value.maxDuration } : {}),\n  };\n}\n\nasync function collectRoutes(\n  root: string,\n  kind: FarmDevtoolsSnapshot[\"routes\"][number][\"kind\"],\n  routes: Map<string, RouteMapEntry>,\n  routeManager: RouteManagerLike,\n  diagnostics: FarmDevtoolsDiagnostic[],\n): Promise<FarmDevtoolsSnapshot[\"routes\"]> {\n  return Promise.all(\n    Array.from(routes.values()).map(async (route) => {\n      let runtime: FarmDevtoolsRuntime | undefined;\n      if (kind === \"page\" && routeManager.resolveRouteRuntimeConfig) {\n        try {\n          runtime = toRuntime(await routeManager.resolveRouteRuntimeConfig(route.pattern));\n        } catch (error) {\n          diagnostics.push({\n            severity: \"warning\",\n            code: \"ROUTE_RUNTIME_UNRESOLVED\",\n            title: `Could not inspect ${route.pattern}`,\n            message: error instanceof Error ? error.message : String(error),\n            action: \"Check the route and inherited layout runtime exports.\",\n          });\n        }\n      }\n\n      return {\n        kind,\n        pattern: route.pattern,\n        filePath: toProjectPath(root, route.modulePath),\n        ...(runtime ? { runtime } : {}),\n      };\n    }),\n  );\n}\n\nfunction collectIntegrations(integrations: FarmConfig[\"integrations\"] | undefined) {\n  if (!integrations || typeof integrations !== \"object\") return [];\n\n  return Object.entries(integrations)\n    .filter((entry): entry is [string, NonNullable<(typeof entry)[1]>] => Boolean(entry[1]))\n    .map(([key, value]) => {\n      const integration = value as IntegrationLike;\n      const routes = (integration.routes || []).map((route) => ({\n        path: route.path,\n        methods: [...(route.methods || (route.method ? [route.method] : [\"ALL\"]))]\n          .map((method) => method.toUpperCase())\n          .sort(),\n      }));\n\n      return {\n        key,\n        type: integration.type || key,\n        category: integration.category || \"custom\",\n        serverRuntime: integration.serverRuntime !== false,\n        routes: sortByPath(routes),\n        middlewareCount: integration.middleware?.length || 0,\n        providerCount: integration.providers?.length || 0,\n        schemaModelCount: Object.keys(integration.schema?.models || {}).length,\n      };\n    })\n    .sort((a, b) => a.key.localeCompare(b.key));\n}\n\nfunction collectStorage(storage: FarmConfig[\"storage\"] | undefined): {\n  entries: FarmDevtoolsSnapshot[\"storage\"];\n  configured: boolean;\n} {\n  if (!storage || typeof storage !== \"object\") {\n    return {\n      entries: [{ mount: \"root\", driver: \"memory\", default: true }],\n      configured: false,\n    };\n  }\n\n  const value = storage as Record<string, any>;\n  if (value.kind === \"farm-storage-client\") {\n    return {\n      entries: [{ mount: \"root\", driver: \"storage client\", default: false }],\n      configured: true,\n    };\n  }\n\n  const configured = Object.keys(value).length > 0;\n  const rootDriver = value.client\n    ? describeStorageDriver(value.client)\n    : describeStorageDriver(value.driver);\n  const entries: FarmDevtoolsSnapshot[\"storage\"] = [\n    {\n      mount: \"root\",\n      driver: rootDriver,\n      default: !configured,\n    },\n  ];\n\n  if (value.mounts && typeof value.mounts === \"object\") {\n    for (const [mount, mountConfig] of Object.entries(value.mounts)) {\n      entries.push({\n        mount,\n        driver: describeStorageDriver(mountConfig),\n        default: false,\n      });\n    }\n  }\n\n  return {\n    entries: entries.sort((a, b) => {\n      if (a.mount === \"root\") return -1;\n      if (b.mount === \"root\") return 1;\n      return a.mount.localeCompare(b.mount);\n    }),\n    configured,\n  };\n}\n\nfunction describeStorageDriver(value: unknown): string {\n  if (!value) return \"memory\";\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"function\") return \"custom\";\n  if (typeof value !== \"object\") return \"custom\";\n\n  const record = value as Record<string, unknown>;\n  if (record.kind === \"farm-storage-client\") return \"storage client\";\n  if (typeof record.driver === \"string\") return record.driver;\n  if (typeof record.driver === \"function\") return \"custom\";\n  return \"custom\";\n}\n\nfunction featureEnabled(value: unknown): boolean {\n  if (!value) return false;\n  if (typeof value === \"object\" && \"enabled\" in value) {\n    return (value as { enabled?: boolean }).enabled !== false;\n  }\n  return value !== false;\n}\n\nfunction collectEnvironmentKeys(config: FarmConfig | undefined) {\n  const env = config?.env as\n    | { server?: Record<string, unknown>; public?: Record<string, unknown> }\n    | undefined;\n  return {\n    server: Object.keys(env?.server || {}).sort(),\n    public: Object.keys(env?.public || {}).sort(),\n  };\n}\n\nfunction resolveHealth(diagnostics: FarmDevtoolsDiagnostic[]): FarmDevtoolsSnapshot[\"health\"] {\n  if (diagnostics.some((diagnostic) => diagnostic.severity === \"error\")) return \"error\";\n  if (diagnostics.some((diagnostic) => diagnostic.severity === \"warning\")) return \"attention\";\n  return \"ready\";\n}\n\nexport async function createFarmDevtoolsSnapshot(\n  input: CreateFarmDevtoolsSnapshotInput,\n): Promise<FarmDevtoolsSnapshot> {\n  const config = input.config || {};\n  const diagnostics: FarmDevtoolsDiagnostic[] = [];\n  const pageRoutes = await collectRoutes(\n    input.root,\n    \"page\",\n    input.routeManager.getRoutes(),\n    input.routeManager,\n    diagnostics,\n  );\n  const layoutRoutes = await collectRoutes(\n    input.root,\n    \"layout\",\n    input.routeManager.getLayouts(),\n    input.routeManager,\n    diagnostics,\n  );\n  const loadingRoutes = await collectRoutes(\n    input.root,\n    \"loading\",\n    input.routeManager.getLoadings(),\n    input.routeManager,\n    diagnostics,\n  );\n  const errorRoutes = await collectRoutes(\n    input.root,\n    \"error\",\n    input.routeManager.getErrors(),\n    input.routeManager,\n    diagnostics,\n  );\n  const apiRoutes = sortByPath(\n    Array.from(input.apiRouteManager.getRoutes().values()).map((route) => {\n      const runtime = resolveFarmRouteRuntimeConfig(\n        mergeFarmRouteRuntimeConfigs(\n          resolveFarmRouteRuleRuntimeConfig(route.path, config.routeRules),\n          route,\n        ),\n        `API route \"${route.path}\"`,\n      );\n      return {\n        path: route.path,\n        methods: [...route.methods].sort(),\n        filePath: toProjectPath(input.root, route.filePath),\n        runtime: toRuntime(runtime),\n      };\n    }),\n  );\n  const middleware = sortByPath(\n    input.middlewareManager.getMiddlewares().map((entry) => ({\n      path: entry.path,\n      source: entry.source || \"file\",\n      filePath: toProjectPath(input.root, entry.filePath),\n      handlerCount: entry.handlers.length,\n    })),\n  );\n  const integrations = collectIntegrations(config.integrations);\n  const storage = collectStorage(config.storage);\n  const cron = resolveCronConfig(config.cron);\n  const workflows = (input.workflows || [])\n    .map((workflow) => ({\n      id: workflow.id,\n      filePath: toProjectPath(input.root, workflow.filePath),\n      routePath: workflow.routePath,\n      schedule: [...workflow.schedule],\n      ...(workflow.timezone ? { timezone: workflow.timezone } : {}),\n    }))\n    .sort((a, b) => a.id.localeCompare(b.id));\n  const layers = (config.layers || []).map((layer) => ({\n    name: layer.name,\n    source: layer.source,\n    srcDir: layer.srcDir,\n  }));\n  const deploymentPreset = String(config.deploy?.preset || config.preset || \"node-server\");\n  const deploymentTarget = String(\n    config.deploy?.target || getDeployTargetForPreset(deploymentPreset) || \"node\",\n  );\n  const env = input.env || process.env;\n\n  if (pageRoutes.length === 0) {\n    diagnostics.push({\n      severity: \"warning\",\n      code: \"NO_PAGE_ROUTES\",\n      title: \"No page routes found\",\n      message: `Farm did not discover a page under ${input.srcDir}/app.`,\n      action: `Add ${input.srcDir}/app/page.tsx or a programmatic page route.`,\n    });\n  }\n  if (layoutRoutes.length === 0) {\n    diagnostics.push({\n      severity: \"warning\",\n      code: \"ROOT_LAYOUT_MISSING\",\n      title: \"Root layout is missing\",\n      message: \"The application has no shared root layout.\",\n      action: `Add ${input.srcDir}/app/layout.tsx for shared metadata and application chrome.`,\n    });\n  }\n\n  const apiPaths = new Set(apiRoutes.map((route) => route.path));\n  for (const job of cron.jobs) {\n    if (!apiPaths.has(job.path)) {\n      diagnostics.push({\n        severity: \"warning\",\n        code: \"CRON_ROUTE_MISSING\",\n        title: `Cron route ${job.path} was not found`,\n        message: `${job.name} is scheduled, but its GET API route is not registered.`,\n        action: \"Add the target API route or update the cron path in farm.config.ts.\",\n      });\n    }\n  }\n  if (cron.jobs.length > 0 && !env[cron.secretEnv]) {\n    diagnostics.push({\n      severity: \"info\",\n      code: \"CRON_SECRET_NOT_SET\",\n      title: `${cron.secretEnv} is not set`,\n      message: \"Local manual runs remain available, but production cron routes fail closed.\",\n      action: `Set ${cron.secretEnv} in the deployment environment before production.`,\n    });\n  }\n  if (\n    storage.configured &&\n    storage.entries[0]?.driver === \"memory\" &&\n    [\"vercel\", \"cloudflare\", \"netlify\"].includes(deploymentTarget)\n  ) {\n    diagnostics.push({\n      severity: \"warning\",\n      code: \"EPHEMERAL_PRODUCTION_STORAGE\",\n      title: \"Production storage is in memory\",\n      message: `${deploymentTarget} instances do not preserve in-memory data across executions.`,\n      action: \"Configure a durable storage driver or mount for production state.\",\n    });\n  }\n\n  const environment = collectEnvironmentKeys(config);\n  const docs = config.docs;\n  const docsEnabled = featureEnabled(docs);\n  const allRoutes = sortByPath([...pageRoutes, ...layoutRoutes, ...loadingRoutes, ...errorRoutes]);\n\n  return {\n    generatedAt: (input.now?.() || new Date()).toISOString(),\n    health: resolveHealth(diagnostics),\n    project: {\n      name: path.basename(path.resolve(input.root)),\n      root: input.root,\n      srcDir: input.srcDir,\n      basePath: config.basePath || \"/\",\n      deploymentId: config.deploymentId || \"development\",\n    },\n    deployment: {\n      target: deploymentTarget,\n      preset: deploymentPreset,\n      ...(config.deploy?.outputDir ? { outputDir: config.deploy.outputDir } : {}),\n    },\n    counts: {\n      pages: pageRoutes.length,\n      layouts: layoutRoutes.length,\n      loadingBoundaries: loadingRoutes.length,\n      errorBoundaries: errorRoutes.length,\n      apiRoutes: apiRoutes.length,\n      middleware: middleware.length,\n      integrations: integrations.length,\n      storageMounts: storage.entries.length,\n      cronJobs: cron.jobs.length,\n      workflows: workflows.length,\n      layers: layers.length,\n      diagnostics: diagnostics.length,\n    },\n    routes: allRoutes,\n    apiRoutes,\n    middleware,\n    integrations,\n    storage: storage.entries,\n    cron: cron.jobs,\n    workflows,\n    layers,\n    environment,\n    docs: {\n      enabled: docsEnabled,\n      entry:\n        docsEnabled && docs && typeof docs === \"object\" && \"entry\" in docs\n          ? String(docs.entry)\n          : undefined,\n    },\n    features: {\n      openapi: Boolean(config.openapi?.enabled),\n      markdown: featureEnabled(config.md),\n      serverComponents: Boolean(config.experimental?.serverComponents),\n      serverActions: Boolean(config.experimental?.serverActions),\n      optimizedBoundary: Boolean(config.experimental?.optimizedBoundary),\n      observability: featureEnabled(config.observability),\n    },\n    diagnostics,\n  };\n}\n","import type { FarmDevtoolsDiagnostic, FarmDevtoolsRuntime, FarmDevtoolsSnapshot } from \"./devtools\";\n\ntype IconName =\n  | \"activity\"\n  | \"api\"\n  | \"app\"\n  | \"blocks\"\n  | \"book\"\n  | \"clock\"\n  | \"chevron\"\n  | \"close\"\n  | \"copy\"\n  | \"database\"\n  | \"external\"\n  | \"layers\"\n  | \"overview\"\n  | \"refresh\"\n  | \"route\"\n  | \"runtime\"\n  | \"search\"\n  | \"shield\"\n  | \"terminal\";\n\nconst ICON_PATHS: Record<IconName, string> = {\n  activity: '<path d=\"M22 12h-4l-3 9L9 3l-3 9H2\"/>',\n  api: '<path d=\"M8 3H7a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2 2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1\"/><path d=\"M16 3h1a2 2 0 0 1 2 2v4a2 2 0 0 0 2 2 2 2 0 0 0-2 2v4a2 2 0 0 1-2 2h-1\"/>',\n  app: '<path d=\"M15 3h6v6\"/><path d=\"M10 14 21 3\"/><path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"/>',\n  blocks:\n    '<rect width=\"7\" height=\"7\" x=\"3\" y=\"3\"/><rect width=\"7\" height=\"7\" x=\"14\" y=\"3\"/><rect width=\"7\" height=\"7\" x=\"14\" y=\"14\"/><rect width=\"7\" height=\"7\" x=\"3\" y=\"14\"/>',\n  book: '<path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\"/><path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\"/>',\n  clock: '<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M12 7v5l3 2\"/>',\n  chevron: '<path d=\"m9 18 6-6-6-6\"/>',\n  close: '<path d=\"M18 6 6 18M6 6l12 12\"/>',\n  copy: '<rect width=\"14\" height=\"14\" x=\"8\" y=\"8\"/><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"/>',\n  database:\n    '<ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\"/><path d=\"M3 5v14c0 1.7 4 3 9 3s9-1.3 9-3V5\"/><path d=\"M3 12c0 1.7 4 3 9 3s9-1.3 9-3\"/>',\n  external:\n    '<path d=\"M15 3h6v6\"/><path d=\"M10 14 21 3\"/><path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"/>',\n  layers:\n    '<path d=\"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z\"/><path d=\"m22 12.5-9.17 4.17a2 2 0 0 1-1.66 0L2 12.5\"/><path d=\"m22 17.5-9.17 4.17a2 2 0 0 1-1.66 0L2 17.5\"/>',\n  overview:\n    '<rect width=\"7\" height=\"9\" x=\"3\" y=\"3\"/><rect width=\"7\" height=\"5\" x=\"14\" y=\"3\"/><rect width=\"7\" height=\"9\" x=\"14\" y=\"12\"/><rect width=\"7\" height=\"5\" x=\"3\" y=\"16\"/>',\n  refresh:\n    '<path d=\"M20 11a8.1 8.1 0 0 0-15.5-2M4 4v5h5\"/><path d=\"M4 13a8.1 8.1 0 0 0 15.5 2M20 20v-5h-5\"/>',\n  route:\n    '<circle cx=\"6\" cy=\"19\" r=\"3\"/><path d=\"M9 19h5.5a3.5 3.5 0 0 0 0-7h-5a3.5 3.5 0 0 1 0-7H18\"/><circle cx=\"18\" cy=\"5\" r=\"3\"/>',\n  runtime:\n    '<rect width=\"20\" height=\"14\" x=\"2\" y=\"3\"/><line x1=\"8\" x2=\"16\" y1=\"21\" y2=\"21\"/><line x1=\"12\" x2=\"12\" y1=\"17\" y2=\"21\"/>',\n  search: '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/>',\n  shield: '<path d=\"M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3z\"/><path d=\"m9 12 2 2 4-4\"/>',\n  terminal: '<polyline points=\"4 17 10 11 4 5\"/><line x1=\"12\" x2=\"20\" y1=\"19\" y2=\"19\"/>',\n};\n\nfunction icon(name: IconName, className = \"\"): string {\n  return `<svg class=\"icon ${className}\" data-lucide=\"${name}\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${ICON_PATHS[name]}</svg>`;\n}\n\nfunction escapeHtml(value: unknown): string {\n  return String(value ?? \"\")\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&#39;\");\n}\n\nfunction escapeAttribute(value: unknown): string {\n  return escapeHtml(value).replace(/`/g, \"&#96;\");\n}\n\nfunction renderBadge(value: string, tone = \"neutral\"): string {\n  return `<span class=\"badge badge-${tone}\">${escapeHtml(value)}</span>`;\n}\n\nfunction renderRuntime(runtime: FarmDevtoolsRuntime | undefined): string {\n  if (!runtime) return '<span class=\"muted\">Inherited</span>';\n  const details = [\n    runtime.regions?.length ? runtime.regions.join(\", \") : null,\n    runtime.maxDuration ? `${runtime.maxDuration}s` : null,\n  ].filter(Boolean);\n  return `<span class=\"runtime-value\">${renderBadge(runtime.runtime, runtime.runtime)}${\n    details.length ? `<small>${escapeHtml(details.join(\" / \"))}</small>` : \"\"\n  }</span>`;\n}\n\nfunction renderEmpty(title: string, detail: string): string {\n  return `<div class=\"empty-state\">\n    ${icon(\"activity\")}\n    <strong>${escapeHtml(title)}</strong>\n    <span>${escapeHtml(detail)}</span>\n  </div>`;\n}\n\nfunction renderFilter(id: string, placeholder: string): string {\n  return `<label class=\"filter-control\">\n    ${icon(\"search\")}\n    <span class=\"sr-only\">${escapeHtml(placeholder)}</span>\n    <input type=\"search\" placeholder=\"${escapeAttribute(placeholder)}\" data-filter=\"${escapeAttribute(id)}\" autocomplete=\"off\">\n    <kbd>/</kbd>\n  </label>`;\n}\n\nfunction renderDiagnostics(diagnostics: FarmDevtoolsDiagnostic[]): string {\n  if (diagnostics.length === 0) {\n    return `<div class=\"diagnostic diagnostic-ready\">\n      <span class=\"diagnostic-mark\">${icon(\"shield\")}</span>\n      <div><strong>Framework checks passed</strong><p>Routes and configured systems are internally consistent.</p></div>\n      ${renderBadge(\"ready\", \"ready\")}\n    </div>`;\n  }\n\n  return diagnostics\n    .map(\n      (diagnostic) => `<article class=\"diagnostic diagnostic-${diagnostic.severity}\">\n        <span class=\"diagnostic-mark\">${icon(\n          diagnostic.severity === \"error\" ? \"activity\" : \"shield\",\n        )}</span>\n        <div>\n          <span class=\"diagnostic-code\">${escapeHtml(diagnostic.code)}</span>\n          <strong>${escapeHtml(diagnostic.title)}</strong>\n          <p>${escapeHtml(diagnostic.message)}</p>\n          ${diagnostic.action ? `<small>${escapeHtml(diagnostic.action)}</small>` : \"\"}\n        </div>\n        ${renderBadge(diagnostic.severity, diagnostic.severity)}\n      </article>`,\n    )\n    .join(\"\");\n}\n\nfunction renderSystemRows(snapshot: FarmDevtoolsSnapshot): string {\n  const rows = [\n    [\"Integrations\", snapshot.counts.integrations, \"Configured product adapters\", \"blocks\"],\n    [\"Storage\", snapshot.counts.storageMounts, \"Root driver and named mounts\", \"database\"],\n    [\"Cron\", snapshot.counts.cronJobs, \"Portable scheduled API routes\", \"clock\"],\n    [\"Workflows\", snapshot.counts.workflows, \"Discovered workflow modules\", \"activity\"],\n    [\"Docs\", snapshot.docs.enabled ? \"On\" : \"Off\", snapshot.docs.entry || \"No docs route\", \"book\"],\n  ] as const;\n\n  return rows\n    .map(\n      ([label, value, detail, rowIcon]) => `<div class=\"system-row\">\n        <span class=\"system-icon\">${icon(rowIcon)}</span>\n        <div><strong>${escapeHtml(label)}</strong><small>${escapeHtml(detail)}</small></div>\n        <span class=\"system-value\">${escapeHtml(value)}</span>\n      </div>`,\n    )\n    .join(\"\");\n}\n\nfunction renderIntegrations(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.integrations.length === 0) {\n    return renderEmpty(\n      \"No integrations configured\",\n      \"Register product systems through farm.config.ts when the app needs them.\",\n    );\n  }\n\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Registry key</th><th>Adapter</th><th>Routes</th><th>Runtime surface</th></tr></thead>\n    <tbody>${snapshot.integrations\n      .map(\n        (integration) => `<tr>\n          <td><code>${escapeHtml(integration.key)}</code><small class=\"cell-detail\">${escapeHtml(\n            integration.category,\n          )}</small></td>\n          <td>${escapeHtml(integration.type)}</td>\n          <td>${\n            integration.routes.length\n              ? integration.routes\n                  .map(\n                    (route) =>\n                      `<span class=\"route-operation\"><code>${escapeHtml(\n                        route.path,\n                      )}</code><small>${escapeHtml(route.methods.join(\", \"))}</small></span>`,\n                  )\n                  .join(\"\")\n              : '<span class=\"muted\">No HTTP routes</span>'\n          }</td>\n          <td><span class=\"runtime-facts\">${renderBadge(\n            integration.serverRuntime ? \"server\" : \"platform\",\n          )}<span>${integration.middlewareCount} middleware</span><span>${\n            integration.providerCount\n          } providers</span><span>${integration.schemaModelCount} models</span></span></td>\n        </tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderMiddleware(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.middleware.length === 0) {\n    return renderEmpty(\"No middleware configured\", \"Requests currently enter routes directly.\");\n  }\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Path</th><th>Source</th><th>Handlers</th><th>File</th></tr></thead>\n    <tbody>${snapshot.middleware\n      .map(\n        (entry) =>\n          `<tr><td><code>${escapeHtml(entry.path)}</code></td><td>${renderBadge(\n            entry.source,\n          )}</td><td>${entry.handlerCount}</td><td class=\"file-cell\">${escapeHtml(\n            entry.filePath,\n          )}</td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderStorage(snapshot: FarmDevtoolsSnapshot): string {\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Mount</th><th>Driver</th><th>State</th></tr></thead>\n    <tbody>${snapshot.storage\n      .map(\n        (entry) =>\n          `<tr><td><code>${escapeHtml(entry.mount)}</code></td><td>${escapeHtml(\n            entry.driver,\n          )}</td><td>${renderBadge(entry.default ? \"default\" : \"configured\")}</td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderCron(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.cron.length === 0) {\n    return renderEmpty(\n      \"No cron routes configured\",\n      \"Add named schedules under cron in farm.config.ts.\",\n    );\n  }\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Name</th><th>Schedule (UTC)</th><th>Target</th></tr></thead>\n    <tbody>${snapshot.cron\n      .map(\n        (job) =>\n          `<tr><td><code>${escapeHtml(job.name)}</code></td><td>${job.schedule\n            .map((schedule) => `<code class=\"schedule\">${escapeHtml(schedule)}</code>`)\n            .join(\"\")}</td><td><code>${escapeHtml(job.path)}</code></td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderWorkflows(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.workflows.length === 0) {\n    return renderEmpty(\n      \"No workflows discovered\",\n      \"Workflow directories are enabled but currently empty.\",\n    );\n  }\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Workflow</th><th>Schedule</th><th>Endpoint</th><th>Source</th></tr></thead>\n    <tbody>${snapshot.workflows\n      .map(\n        (workflow) =>\n          `<tr><td><code>${escapeHtml(workflow.id)}</code></td><td>${\n            workflow.schedule.length\n              ? workflow.schedule.map((schedule) => `<code>${escapeHtml(schedule)}</code>`).join(\"\")\n              : '<span class=\"muted\">Manual</span>'\n          }</td><td><code>${escapeHtml(workflow.routePath)}</code></td><td class=\"file-cell\">${escapeHtml(\n            workflow.filePath,\n          )}</td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderFeatureMatrix(snapshot: FarmDevtoolsSnapshot): string {\n  const features = [\n    [\"OpenAPI\", snapshot.features.openapi],\n    [\"Markdown\", snapshot.features.markdown],\n    [\"Server components\", snapshot.features.serverComponents],\n    [\"Server actions\", snapshot.features.serverActions],\n    [\"Optimized boundary\", snapshot.features.optimizedBoundary],\n    [\"Observability\", snapshot.features.observability],\n  ] as const;\n  return `<div class=\"feature-matrix\">${features\n    .map(\n      ([label, enabled]) =>\n        `<div><span>${escapeHtml(label)}</span>${renderBadge(\n          enabled ? \"enabled\" : \"disabled\",\n          enabled ? \"ready\" : \"neutral\",\n        )}</div>`,\n    )\n    .join(\"\")}</div>`;\n}\n\nfunction renderEnvironment(snapshot: FarmDevtoolsSnapshot): string {\n  const renderKeys = (keys: string[]) =>\n    keys.length\n      ? `<div class=\"key-list\">${keys.map((key) => `<code>${escapeHtml(key)}</code>`).join(\"\")}</div>`\n      : '<span class=\"muted\">No validated keys</span>';\n  return `<div class=\"environment-grid\">\n    <div><span class=\"mini-label\">Server keys</span>${renderKeys(snapshot.environment.server)}</div>\n    <div><span class=\"mini-label\">Public keys</span>${renderKeys(snapshot.environment.public)}</div>\n  </div>`;\n}\n\nfunction renderLayers(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.layers.length === 0) {\n    return renderEmpty(\n      \"No layers extended\",\n      \"This project owns its complete route and config surface.\",\n    );\n  }\n  return `<div class=\"layer-list\">${snapshot.layers\n    .map(\n      (layer) =>\n        `<div><span>${icon(\"layers\")}<strong>${escapeHtml(\n          layer.name,\n        )}</strong></span><code>${escapeHtml(layer.source)}</code><small>${escapeHtml(\n          layer.srcDir,\n        )}</small></div>`,\n    )\n    .join(\"\")}</div>`;\n}\n\ntype InspectorEntry = {\n  id: string;\n  label: string;\n  description: string;\n  icon: IconName;\n  value?: string | number;\n  searchValue?: string;\n  detailMeta?: string;\n  content: string;\n};\n\nfunction renderPropertyList(entries: Array<[label: string, value: string]>): string {\n  return `<dl class=\"property-list\">${entries\n    .map(([label, value]) => `<div><dt>${escapeHtml(label)}</dt><dd>${value}</dd></div>`)\n    .join(\"\")}</dl>`;\n}\n\nfunction renderDetailIntro(\n  label: string,\n  title: string,\n  description: string,\n  detailIcon: IconName,\n): string {\n  return `<div class=\"detail-intro\">\n    <span class=\"detail-icon\">${icon(detailIcon)}</span>\n    <div><span class=\"mini-label\">${escapeHtml(label)}</span><h2>${escapeHtml(\n      title,\n    )}</h2><p>${escapeHtml(description)}</p></div>\n  </div>`;\n}\n\nfunction renderInspector(\n  scope: string,\n  title: string,\n  entries: InspectorEntry[],\n  filterPlaceholder?: string,\n): string {\n  if (entries.length === 0) {\n    return `<div class=\"single-pane\">\n      <header class=\"pane-header\"><strong>${escapeHtml(title)}</strong><span>0 items</span></header>\n      ${renderEmpty(`No ${title.toLowerCase()} found`, \"Farm has no runtime data for this surface yet.\")}\n    </div>`;\n  }\n\n  return `<div class=\"split-view\" data-inspector=\"${escapeAttribute(scope)}\">\n    <section class=\"pane pane-list\">\n      <header class=\"pane-header\"><strong>${escapeHtml(title)}</strong><span>${entries.length} ${\n        entries.length === 1 ? \"item\" : \"items\"\n      }</span></header>\n      ${\n        filterPlaceholder\n          ? `<div class=\"pane-tools\">${renderFilter(scope, filterPlaceholder)}</div>`\n          : \"\"\n      }\n      <div class=\"pane-scroll inspector-list\" data-filter-rows=\"${escapeAttribute(scope)}\">\n        ${entries\n          .map(\n            (\n              entry,\n              index,\n            ) => `<button type=\"button\" class=\"inspector-row\" data-detail-trigger=\"${escapeAttribute(\n              scope,\n            )}\" data-detail-id=\"${escapeAttribute(entry.id)}\" data-search-value=\"${escapeAttribute(\n              entry.searchValue || `${entry.label} ${entry.description}`,\n            )}\" aria-selected=\"${index === 0 ? \"true\" : \"false\"}\">\n              <span class=\"inspector-row-copy\"><strong>${escapeHtml(\n                entry.label,\n              )}</strong><small>${escapeHtml(entry.description)}</small></span>\n              ${entry.value === undefined ? \"\" : `<span class=\"inspector-row-value\">${escapeHtml(entry.value)}</span>`}\n            </button>`,\n          )\n          .join(\"\")}\n        <div class=\"filtered-empty\" data-filter-empty=\"${escapeAttribute(\n          scope,\n        )}\" hidden>No items match this filter.</div>\n      </div>\n    </section>\n    <section class=\"pane pane-detail\">\n      ${entries\n        .map(\n          (entry, index) => `<article class=\"detail-panel\" data-detail-panel=\"${escapeAttribute(\n            scope,\n          )}\" data-detail-id=\"${escapeAttribute(entry.id)}\"${index === 0 ? \"\" : \" hidden\"}>\n            <header class=\"pane-header\"><strong>${escapeHtml(entry.label)}</strong><span>${escapeHtml(\n              entry.detailMeta || entry.description,\n            )}</span></header>\n            <div class=\"detail-scroll\">${entry.content}</div>\n          </article>`,\n        )\n        .join(\"\")}\n    </section>\n  </div>`;\n}\n\nfunction renderJson(value: unknown): string {\n  return `<pre class=\"json-viewer\"><code>${escapeHtml(JSON.stringify(value, null, 2))}</code></pre>`;\n}\n\nfunction renderOverviewInspector(\n  snapshot: FarmDevtoolsSnapshot,\n  healthLabel: string,\n  generatedTime: string,\n): string {\n  const scheduledCount = snapshot.counts.cronJobs + snapshot.counts.workflows;\n  return renderInspector(\"overview\", \"Project\", [\n    {\n      id: \"diagnostics\",\n      label: \"Diagnostics\",\n      description: \"Actionable framework checks\",\n      icon: \"shield\",\n      value: snapshot.counts.diagnostics,\n      detailMeta: healthLabel,\n      content: `${renderDetailIntro(\n        \"Project health\",\n        healthLabel,\n        snapshot.diagnostics.length\n          ? \"Farm found configuration details that deserve attention before production.\"\n          : \"Routes and configured systems are internally consistent.\",\n        \"shield\",\n      )}<div class=\"detail-section\">${renderDiagnostics(snapshot.diagnostics)}</div>`,\n    },\n    {\n      id: \"project\",\n      label: snapshot.project.name,\n      description: snapshot.project.root,\n      icon: \"app\",\n      value: snapshot.project.srcDir,\n      detailMeta: \"Active project\",\n      content: `${renderDetailIntro(\n        \"Active project\",\n        snapshot.project.name,\n        \"The application currently resolved by the Farm development server.\",\n        \"app\",\n      )}${renderPropertyList([\n        [\"Root\", `<code>${escapeHtml(snapshot.project.root)}</code>`],\n        [\"Source directory\", `<code>${escapeHtml(snapshot.project.srcDir)}</code>`],\n        [\"Base path\", `<code>${escapeHtml(snapshot.project.basePath)}</code>`],\n        [\"Deployment ID\", `<code>${escapeHtml(snapshot.project.deploymentId)}</code>`],\n        [\"Snapshot\", `<span class=\"mono\">${escapeHtml(generatedTime)}</span>`],\n      ])}`,\n    },\n    {\n      id: \"routes\",\n      label: \"Route surface\",\n      description: \"Pages, boundaries, and typed endpoints\",\n      icon: \"route\",\n      value: snapshot.counts.pages + snapshot.counts.apiRoutes,\n      detailMeta: `${snapshot.counts.pages} pages / ${snapshot.counts.apiRoutes} API`,\n      content: `${renderDetailIntro(\n        \"Application routing\",\n        `${snapshot.counts.pages + snapshot.counts.apiRoutes} registered routes`,\n        \"Farm resolves page boundaries and server endpoints from the same application tree.\",\n        \"route\",\n      )}${renderPropertyList([\n        [\"Pages\", `<strong>${snapshot.counts.pages}</strong>`],\n        [\"Layouts\", `<strong>${snapshot.counts.layouts}</strong>`],\n        [\"Loading boundaries\", `<strong>${snapshot.counts.loadingBoundaries}</strong>`],\n        [\"Error boundaries\", `<strong>${snapshot.counts.errorBoundaries}</strong>`],\n        [\"API routes\", `<strong>${snapshot.counts.apiRoutes}</strong>`],\n      ])}`,\n    },\n    {\n      id: \"systems\",\n      label: \"Connected systems\",\n      description: \"Integrations, storage, and request layers\",\n      icon: \"blocks\",\n      value: snapshot.counts.integrations,\n      detailMeta: \"Configured surfaces\",\n      content: `${renderDetailIntro(\n        \"System map\",\n        \"Application services\",\n        \"Product integrations and framework services visible to the running application.\",\n        \"blocks\",\n      )}<div class=\"detail-section\">${renderSystemRows(snapshot)}</div>`,\n    },\n    {\n      id: \"deployment\",\n      label: \"Runtime\",\n      description: `${snapshot.deployment.target} / ${snapshot.deployment.preset}`,\n      icon: \"runtime\",\n      value: scheduledCount,\n      detailMeta: \"Deployment controls\",\n      content: `${renderDetailIntro(\n        \"Deployment runtime\",\n        snapshot.deployment.target,\n        \"The resolved deployment adapter, output contract, and enabled framework surfaces.\",\n        \"runtime\",\n      )}${renderPropertyList([\n        [\"Target\", `<code>${escapeHtml(snapshot.deployment.target)}</code>`],\n        [\"Nitro preset\", `<code>${escapeHtml(snapshot.deployment.preset)}</code>`],\n        [\n          \"Output\",\n          `<code>${escapeHtml(snapshot.deployment.outputDir || \"Framework default\")}</code>`,\n        ],\n        [\"Scheduled work\", `<strong>${scheduledCount}</strong>`],\n      ])}<div class=\"detail-section\">${renderFeatureMatrix(snapshot)}</div>`,\n    },\n  ]);\n}\n\nfunction renderRoutesInspector(snapshot: FarmDevtoolsSnapshot): string {\n  return renderInspector(\n    \"routes\",\n    \"Routes\",\n    snapshot.routes.map((route, index) => ({\n      id: `route-${index}`,\n      label: route.pattern,\n      description: route.filePath,\n      icon: \"route\",\n      value: route.kind,\n      searchValue: `${route.kind} ${route.pattern} ${route.filePath} ${\n        route.runtime?.runtime || \"inherited\"\n      }`,\n      detailMeta: route.kind,\n      content: `${renderDetailIntro(\n        `${route.kind} route`,\n        route.pattern,\n        route.filePath,\n        \"route\",\n      )}${renderPropertyList([\n        [\"Kind\", renderBadge(route.kind, route.kind)],\n        [\"Pattern\", `<code>${escapeHtml(route.pattern)}</code>`],\n        [\"Runtime\", renderRuntime(route.runtime)],\n        [\"Source\", `<code>${escapeHtml(route.filePath)}</code>`],\n      ])}`,\n    })),\n    \"Filter routes or files\",\n  );\n}\n\nfunction renderApiInspector(snapshot: FarmDevtoolsSnapshot): string {\n  return renderInspector(\n    \"api\",\n    \"API routes\",\n    snapshot.apiRoutes.map((route, index) => ({\n      id: `api-${index}`,\n      label: route.path,\n      description: route.filePath,\n      icon: \"api\",\n      value: route.methods.length,\n      searchValue: `${route.path} ${route.methods.join(\" \")} ${route.filePath} ${\n        route.runtime.runtime\n      }`,\n      detailMeta: route.methods.join(\" / \"),\n      content: `${renderDetailIntro(\n        \"Server endpoint\",\n        route.path,\n        route.filePath,\n        \"api\",\n      )}${renderPropertyList([\n        [\n          \"Methods\",\n          `<span class=\"method-list\">${route.methods\n            .map((method) => renderBadge(method, \"method\"))\n            .join(\"\")}</span>`,\n        ],\n        [\"Runtime\", renderRuntime(route.runtime)],\n        [\"Source\", `<code>${escapeHtml(route.filePath)}</code>`],\n      ])}`,\n    })),\n    \"Filter endpoints or methods\",\n  );\n}\n\nfunction renderSystemsInspector(snapshot: FarmDevtoolsSnapshot): string {\n  return renderInspector(\"systems\", \"Systems\", [\n    {\n      id: \"integrations\",\n      label: \"Integrations\",\n      description: \"Configured product adapters\",\n      icon: \"blocks\",\n      value: snapshot.integrations.length,\n      content: renderIntegrations(snapshot),\n    },\n    {\n      id: \"middleware\",\n      label: \"Middleware\",\n      description: \"Request layers and source modules\",\n      icon: \"shield\",\n      value: snapshot.middleware.length,\n      content: renderMiddleware(snapshot),\n    },\n    {\n      id: \"storage\",\n      label: \"Storage mounts\",\n      description: \"Root driver and named namespaces\",\n      icon: \"database\",\n      value: snapshot.storage.length,\n      content: renderStorage(snapshot),\n    },\n    {\n      id: \"docs\",\n      label: \"Documentation\",\n      description: snapshot.docs.entry || \"No docs route\",\n      icon: \"book\",\n      value: snapshot.docs.enabled ? \"on\" : \"off\",\n      content: `${renderDetailIntro(\n        \"Documentation\",\n        snapshot.docs.enabled ? \"Docs enabled\" : \"Docs disabled\",\n        \"Farm can serve application documentation from the same development runtime.\",\n        \"book\",\n      )}${renderPropertyList([\n        [\"State\", renderBadge(snapshot.docs.enabled ? \"enabled\" : \"disabled\")],\n        [\"Entry\", `<code>${escapeHtml(snapshot.docs.entry || \"Not configured\")}</code>`],\n      ])}`,\n    },\n  ]);\n}\n\nfunction renderRuntimeInspector(snapshot: FarmDevtoolsSnapshot): string {\n  return renderInspector(\"runtime\", \"Runtime\", [\n    {\n      id: \"deployment\",\n      label: \"Deployment\",\n      description: `${snapshot.deployment.target} / ${snapshot.deployment.preset}`,\n      icon: \"runtime\",\n      content: `${renderDetailIntro(\n        \"Deployment target\",\n        snapshot.deployment.target,\n        \"Resolved platform adapter and build output for this application.\",\n        \"runtime\",\n      )}${renderPropertyList([\n        [\"Target\", `<code>${escapeHtml(snapshot.deployment.target)}</code>`],\n        [\"Nitro preset\", `<code>${escapeHtml(snapshot.deployment.preset)}</code>`],\n        [\n          \"Output directory\",\n          `<code>${escapeHtml(snapshot.deployment.outputDir || \"Framework default\")}</code>`,\n        ],\n      ])}`,\n    },\n    {\n      id: \"cron\",\n      label: \"Cron routes\",\n      description: \"Portable scheduled API routes\",\n      icon: \"clock\",\n      value: snapshot.cron.length,\n      content: renderCron(snapshot),\n    },\n    {\n      id: \"workflows\",\n      label: \"Workflows\",\n      description: \"Discovered workflow modules\",\n      icon: \"activity\",\n      value: snapshot.workflows.length,\n      content: renderWorkflows(snapshot),\n    },\n    {\n      id: \"features\",\n      label: \"Framework features\",\n      description: \"Resolved configuration switches\",\n      icon: \"blocks\",\n      content: renderFeatureMatrix(snapshot),\n    },\n    {\n      id: \"environment\",\n      label: \"Environment\",\n      description: \"Validated key names only\",\n      icon: \"shield\",\n      value: snapshot.environment.server.length + snapshot.environment.public.length,\n      content: renderEnvironment(snapshot),\n    },\n    {\n      id: \"layers\",\n      label: \"Layers\",\n      description: \"Extended source roots\",\n      icon: \"layers\",\n      value: snapshot.layers.length,\n      content: renderLayers(snapshot),\n    },\n  ]);\n}\n\nfunction renderRawInspector(snapshot: FarmDevtoolsSnapshot): string {\n  return renderInspector(\"raw\", \"Raw snapshot\", [\n    {\n      id: \"snapshot\",\n      label: \"Snapshot\",\n      description: \"Complete serialized runtime state\",\n      icon: \"terminal\",\n      content: renderJson(snapshot),\n    },\n    {\n      id: \"routes\",\n      label: \"Routes\",\n      description: \"Pages and route boundaries\",\n      icon: \"route\",\n      value: snapshot.routes.length,\n      content: renderJson(snapshot.routes),\n    },\n    {\n      id: \"api\",\n      label: \"API\",\n      description: \"Typed server endpoints\",\n      icon: \"api\",\n      value: snapshot.apiRoutes.length,\n      content: renderJson(snapshot.apiRoutes),\n    },\n    {\n      id: \"systems\",\n      label: \"Systems\",\n      description: \"Integrations, middleware, and storage\",\n      icon: \"blocks\",\n      content: renderJson({\n        integrations: snapshot.integrations,\n        middleware: snapshot.middleware,\n        storage: snapshot.storage,\n      }),\n    },\n    {\n      id: \"diagnostics\",\n      label: \"Diagnostics\",\n      description: \"Framework health findings\",\n      icon: \"shield\",\n      value: snapshot.diagnostics.length,\n      content: renderJson(snapshot.diagnostics),\n    },\n  ]);\n}\n\nfunction renderNavigationItem(view: string, label: string): string {\n  return `<button type=\"button\" class=\"nav-item\" data-view-trigger=\"${view}\" aria-selected=\"false\">\n    <span>${escapeHtml(label)}</span>\n  </button>`;\n}\n\nexport function renderFarmDevtoolsHtml(snapshot: FarmDevtoolsSnapshot): string {\n  const healthLabel =\n    snapshot.health === \"ready\" ? \"Ready\" : snapshot.health === \"error\" ? \"Error\" : \"Attention\";\n  const generatedTime = new Date(snapshot.generatedAt).toLocaleTimeString(\"en-US\", {\n    hour: \"2-digit\",\n    minute: \"2-digit\",\n    second: \"2-digit\",\n    hour12: false,\n  });\n\n  return `<!doctype html>\n<html lang=\"en\" class=\"devtools-frame\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"color-scheme\" content=\"dark\">\n  <title>Farm Devtools - ${escapeHtml(snapshot.project.name)}</title>\n  <style>\n    :root {\n      color-scheme: dark;\n      --background: #000;\n      --surface: #050505;\n      --surface-raised: #090909;\n      --foreground: #f5f5f5;\n      --muted: #858585;\n      --muted-strong: #a8a8a8;\n      --line: rgb(255 255 255 / 0.12);\n      --line-soft: rgb(255 255 255 / 0.065);\n      --line-strong: rgb(255 255 255 / 0.22);\n      --font-sans: \"Geist Sans\", Geist, Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n      --font-mono: \"Geist Mono\", \"SFMono-Regular\", Consolas, \"Liberation Mono\", Menlo, monospace;\n    }\n    * { box-sizing: border-box; }\n    html { min-width: 320px; min-height: 100%; background: var(--background); }\n    body { min-height: 100vh; min-height: 100dvh; margin: 0; overflow: hidden; background: #030303; color: var(--foreground); font-family: var(--font-sans); font-size: 14px; letter-spacing: 0; text-rendering: optimizeLegibility; }\n    button, input { color: inherit; font: inherit; letter-spacing: 0; }\n    button, a { -webkit-tap-highlight-color: transparent; }\n    button { cursor: pointer; }\n    a { color: inherit; }\n    [hidden] { display: none !important; }\n    code, kbd, .badge, .mono, .mini-label, .metric-label, .metric-detail, .section-index, .diagnostic-code, th, .statusbar, .eyebrow { font-family: var(--font-mono); letter-spacing: 0; }\n    .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }\n    .icon { width: 16px; height: 16px; flex: 0 0 auto; }\n    .stage { display: grid; min-height: 100vh; min-height: 100dvh; place-items: center; padding: 20px; }\n    .shell { display: flex; width: min(1280px, 100%); height: min(780px, calc(100dvh - 40px)); min-height: 560px; min-width: 0; flex-direction: column; overflow: hidden; border: 1px solid var(--line-strong); background: var(--background); box-shadow: 0 24px 80px rgb(0 0 0 / 0.72); }\n    .topbar { z-index: 30; display: flex; min-height: 42px; flex: 0 0 auto; align-items: stretch; border-bottom: 1px solid var(--line); background: var(--background); }\n    .brand { display: flex; min-width: 170px; align-items: center; gap: 8px; padding: 0 12px; border-right: 1px solid var(--line); text-decoration: none; font-family: var(--font-mono); font-size: 10px; text-transform: uppercase; white-space: nowrap; }\n    .brand-mark { display: grid; width: 18px; height: 18px; place-items: center; border: 1px solid var(--line-strong); color: #fff; font-family: var(--font-sans); font-size: 9px; font-weight: 650; }\n    .brand-slash { color: #555; }\n    .brand-product { color: var(--muted-strong); }\n    .tabbar { display: flex; min-width: 0; flex: 1 1 auto; align-items: stretch; overflow-x: auto; scrollbar-width: none; }\n    .tabbar::-webkit-scrollbar { display: none; }\n    .nav-item { position: relative; display: flex; min-width: max-content; min-height: 41px; align-items: center; gap: 7px; padding: 0 11px; border: 0; background: transparent; color: var(--muted); font-family: var(--font-mono); font-size: 10px; text-transform: uppercase; transition: background-color 140ms ease-out, color 140ms ease-out; }\n    .nav-item::after { position: absolute; right: 10px; bottom: -1px; left: 10px; height: 1px; background: transparent; content: \"\"; }\n    .nav-item:hover, .nav-item:focus-visible { background: rgb(255 255 255 / 0.035); color: var(--foreground); outline: none; }\n    .nav-item[aria-selected=\"true\"] { color: #fff; }\n    .nav-item[aria-selected=\"true\"]::after { background: #fff; }\n    .nav-item .icon { width: 13px; height: 13px; }\n    .nav-item small { color: #666; font-size: 9px; font-weight: 400; }\n    .topbar-meta { display: flex; flex: 0 0 auto; margin-left: auto; border-left: 1px solid var(--line); }\n    .deprecation-tag { display: inline-flex; align-items: center; padding: 0 10px; border-right: 1px solid var(--line); color: #d9a626; font-family: var(--font-mono); font-size: 10px; text-transform: uppercase; white-space: nowrap; }\n    .topbar-status { display: flex; min-width: max-content; align-items: center; gap: 7px; padding: 0 11px; color: var(--muted-strong); font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; }\n    .status-dot { width: 5px; height: 5px; background: #fff; box-shadow: 0 0 0 3px rgb(255 255 255 / 0.06); }\n    .status-dot-attention { background: #909090; animation: status-pulse 1.8s ease-in-out infinite; }\n    .status-dot-error { background: transparent; border: 1px solid #fff; }\n    .topbar-actions { display: flex; }\n    .action { display: inline-flex; width: 40px; min-height: 41px; align-items: center; justify-content: center; padding: 0; border: 0; border-left: 1px solid var(--line); background: transparent; color: var(--muted-strong); text-decoration: none; transition: background-color 140ms ease-out, color 140ms ease-out; }\n    .action:hover, .action:focus-visible { background: #fff; color: #000; outline: none; }\n    .action[data-copied=\"true\"] { background: #fff; color: #000; }\n    .workspace { min-height: 0; flex: 1 1 auto; }\n    .eyebrow { display: block; color: var(--muted); font-size: 9px; font-weight: 400; text-transform: uppercase; }\n    .content { height: 100%; min-width: 0; }\n    .view { height: 100%; min-width: 0; overflow: hidden; }\n    .split-view { display: grid; height: 100%; min-height: 0; grid-template-columns: clamp(230px, 28%, 300px) minmax(0, 1fr); }\n    .pane { min-width: 0; min-height: 0; overflow: hidden; background: var(--background); }\n    .pane-list { display: flex; flex-direction: column; border-right: 1px solid var(--line); }\n    .pane-detail { position: relative; }\n    .pane-header { display: flex; min-height: 38px; align-items: center; justify-content: space-between; gap: 12px; padding: 0 12px; border-bottom: 1px solid var(--line); background: var(--surface); }\n    .pane-header strong { overflow: hidden; font-size: 11px; font-weight: 520; text-overflow: ellipsis; white-space: nowrap; }\n    .pane-header span { overflow: hidden; color: var(--muted); font-family: var(--font-mono); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }\n    .pane-tools { border-bottom: 1px solid var(--line); }\n    .pane-tools .filter-control { width: 100%; min-height: 36px; border: 0; }\n    .pane-scroll, .detail-scroll { min-height: 0; overflow: auto; overscroll-behavior: contain; }\n    .pane-scroll { flex: 1 1 auto; }\n    .inspector-list { scrollbar-width: thin; scrollbar-color: var(--line-strong) transparent; }\n    .inspector-row { position: relative; display: grid; width: 100%; min-height: 54px; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; padding: 8px 11px; border: 0; border-bottom: 1px solid var(--line-soft); background: transparent; color: var(--muted); text-align: left; transition: background-color 120ms ease-out, color 120ms ease-out; }\n    .inspector-row::before { position: absolute; inset: 0 auto 0 0; width: 1px; background: transparent; content: \"\"; }\n    .inspector-row:hover, .inspector-row:focus-visible { background: rgb(255 255 255 / 0.035); color: var(--foreground); outline: none; }\n    .inspector-row[aria-selected=\"true\"] { background: rgb(255 255 255 / 0.075); color: #fff; }\n    .inspector-row[aria-selected=\"true\"]::before { background: #fff; }\n    .inspector-row-icon { display: grid; color: var(--muted-strong); place-items: center; }\n    .inspector-row-icon .icon { width: 14px; height: 14px; }\n    .inspector-row-copy { min-width: 0; }\n    .inspector-row-copy strong, .inspector-row-copy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n    .inspector-row-copy strong { color: inherit; font-size: 11px; font-weight: 520; }\n    .inspector-row-copy small { margin-top: 3px; color: var(--muted); font-family: var(--font-mono); font-size: 9px; }\n    .inspector-row-value { color: var(--muted-strong); font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; }\n    .detail-panel { display: flex; height: 100%; min-height: 0; flex-direction: column; }\n    .detail-scroll { flex: 1 1 auto; }\n    .detail-intro { display: grid; min-height: 132px; grid-template-columns: 34px minmax(0, 1fr); align-items: start; gap: 14px; padding: 22px; border-bottom: 1px solid var(--line); }\n    .detail-icon { display: grid; width: 32px; height: 32px; border: 1px solid var(--line); color: var(--muted-strong); place-items: center; }\n    .detail-icon .icon { width: 15px; height: 15px; }\n    .detail-intro .mini-label { margin: 1px 0 8px; }\n    .detail-intro h2 { margin: 0; overflow-wrap: anywhere; font-size: 20px; font-weight: 530; line-height: 1.2; }\n    .detail-intro p { max-width: 680px; margin: 8px 0 0; color: var(--muted); font-size: 11px; line-height: 1.55; }\n    .detail-section { border-top: 1px solid var(--line); }\n    .detail-intro + .detail-section { border-top: 0; }\n    .property-list { margin: 0; }\n    .property-list > div { display: grid; min-height: 48px; grid-template-columns: minmax(120px, 0.32fr) minmax(0, 1fr); align-items: center; gap: 18px; padding: 9px 16px; border-bottom: 1px solid var(--line-soft); }\n    .property-list dt { color: var(--muted); font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; }\n    .property-list dd { min-width: 0; margin: 0; overflow-wrap: anywhere; color: var(--muted-strong); font-size: 11px; }\n    .property-list dd > code { color: var(--foreground); font-size: 10px; }\n    .single-pane { height: 100%; min-height: 0; }\n    .json-viewer { min-height: 100%; margin: 0; padding: 16px; overflow: auto; background: #000; color: var(--muted-strong); font-family: var(--font-mono); font-size: 10px; line-height: 1.65; tab-size: 2; white-space: pre-wrap; word-break: break-word; }\n    .diagnostic { display: grid; grid-template-columns: 32px minmax(0, 1fr) auto; align-items: start; gap: 12px; min-height: 88px; padding: 16px 18px; border-bottom: 1px solid var(--line-soft); }\n    .diagnostic:last-child { border-bottom: 0; }\n    .diagnostic-mark { display: grid; width: 28px; height: 28px; place-items: center; border: 1px solid var(--line); color: var(--muted-strong); }\n    .diagnostic-code { display: block; margin-bottom: 5px; color: var(--muted); font-size: 9px; }\n    .diagnostic strong { display: block; font-size: 12px; font-weight: 540; }\n    .diagnostic p { margin: 5px 0 0; color: var(--muted-strong); font-size: 11px; line-height: 1.5; }\n    .diagnostic small { display: block; margin-top: 6px; color: var(--muted); font-size: 10px; line-height: 1.5; }\n    .diagnostic-warning { box-shadow: inset 1px 0 var(--line-strong); }\n    .system-row { display: grid; grid-template-columns: 32px minmax(0, 1fr) auto; min-height: 64px; align-items: center; gap: 10px; padding: 11px 16px; border-bottom: 1px solid var(--line-soft); }\n    .system-row:last-child { border-bottom: 0; }\n    .system-icon { display: grid; width: 28px; height: 28px; place-items: center; color: var(--muted-strong); }\n    .system-row strong, .system-row small { display: block; }\n    .system-row strong { font-size: 12px; font-weight: 520; }\n    .system-row small { margin-top: 3px; overflow: hidden; color: var(--muted); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }\n    .system-value { font-family: var(--font-mono); font-size: 11px; }\n    .filter-control { display: flex; width: min(280px, 34vw); min-height: 34px; align-items: center; gap: 8px; padding: 0 9px; border: 1px solid var(--line); background: #000; color: var(--muted); }\n    .filter-control:focus-within { border-color: var(--line-strong); color: #fff; }\n    .filter-control input { min-width: 0; flex: 1; border: 0; outline: 0; background: transparent; color: var(--foreground); font-family: var(--font-mono); font-size: 10px; }\n    .filter-control input::placeholder { color: #666; }\n    .filter-control kbd { padding: 1px 5px; border: 1px solid var(--line); color: var(--muted); font-size: 9px; }\n    .table-scroll { width: 100%; overflow-x: auto; }\n    table { width: 100%; border-collapse: collapse; table-layout: auto; }\n    th { height: 36px; padding: 0 16px; border-bottom: 1px solid var(--line); background: #030303; color: var(--muted); font-size: 9px; font-weight: 400; text-align: left; text-transform: uppercase; white-space: nowrap; }\n    td { min-height: 48px; padding: 12px 16px; border-bottom: 1px solid var(--line-soft); color: var(--muted-strong); font-size: 11px; line-height: 1.55; vertical-align: top; }\n    tr:last-child td { border-bottom: 0; }\n    tbody tr { transition: background-color 120ms ease-out; }\n    tbody tr:hover { background: rgb(255 255 255 / 0.035); }\n    td code { color: var(--foreground); font-size: 10px; white-space: nowrap; }\n    .file-cell { max-width: 420px; overflow: hidden; font-family: var(--font-mono); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }\n    .badge { display: inline-flex; min-height: 20px; align-items: center; padding: 1px 6px; border: 1px solid var(--line); color: var(--muted-strong); font-size: 9px; font-weight: 400; text-transform: uppercase; white-space: nowrap; }\n    .badge-ready, .badge-page, .badge-node { border-color: var(--line-strong); color: #fff; }\n    .badge-warning, .badge-attention, .badge-edge { border-style: dashed; color: #fff; }\n    .badge-error { background: #fff; color: #000; }\n    .badge-method { min-width: 36px; justify-content: center; border-color: var(--line-soft); color: #d0d0d0; }\n    .method-list, .runtime-value, .runtime-facts { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }\n    .runtime-value small, .runtime-facts span { color: var(--muted); font-family: var(--font-mono); font-size: 9px; }\n    .cell-detail { display: block; margin-top: 4px; color: var(--muted); font-family: var(--font-mono); font-size: 9px; }\n    .route-operation { display: flex; align-items: center; justify-content: space-between; gap: 12px; }\n    .route-operation + .route-operation { margin-top: 5px; }\n    .route-operation small { color: var(--muted); font-family: var(--font-mono); font-size: 9px; white-space: nowrap; }\n    .schedule { display: block; }\n    .schedule + .schedule { margin-top: 4px; }\n    .muted { color: var(--muted); }\n    .empty-state { display: grid; min-height: 156px; place-items: center; align-content: center; gap: 7px; padding: 24px; color: var(--muted); text-align: center; }\n    .empty-state strong { color: var(--muted-strong); font-size: 12px; font-weight: 520; }\n    .empty-state span { max-width: 420px; font-size: 10px; line-height: 1.5; }\n    .filtered-empty { padding: 24px; color: var(--muted); font-family: var(--font-mono); font-size: 10px; text-align: center; }\n    .feature-matrix > div { display: flex; min-height: 45px; align-items: center; justify-content: space-between; gap: 16px; padding: 9px 16px; border-bottom: 1px solid var(--line-soft); }\n    .feature-matrix > div:last-child { border-bottom: 0; }\n    .feature-matrix span:first-child { font-size: 11px; }\n    .environment-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }\n    .environment-grid > div { min-height: 128px; padding: 16px; }\n    .environment-grid > div + div { border-left: 1px solid var(--line); }\n    .mini-label { display: block; margin-bottom: 12px; color: var(--muted); font-size: 9px; text-transform: uppercase; }\n    .key-list { display: flex; flex-wrap: wrap; gap: 6px; }\n    .key-list code { padding: 4px 6px; border: 1px solid var(--line-soft); color: var(--muted-strong); font-size: 9px; }\n    .layer-list > div { display: grid; grid-template-columns: minmax(120px, 0.7fr) minmax(0, 1fr) auto; min-height: 52px; align-items: center; gap: 14px; padding: 10px 16px; border-bottom: 1px solid var(--line-soft); }\n    .layer-list > div:last-child { border-bottom: 0; }\n    .layer-list span { display: flex; align-items: center; gap: 8px; }\n    .layer-list strong { font-size: 11px; font-weight: 520; }\n    .layer-list code, .layer-list small { color: var(--muted); font-size: 9px; }\n    .statusbar { display: flex; min-height: 29px; flex: 0 0 auto; align-items: center; justify-content: space-between; gap: 16px; padding: 0 10px; border-top: 1px solid var(--line); background: var(--surface); color: var(--muted); font-size: 9px; text-transform: uppercase; }\n    .statusbar span { display: flex; align-items: center; gap: 7px; }\n    @keyframes status-pulse { 0%, 100% { opacity: 0.4; } 50% { opacity: 1; } }\n    @media (max-width: 1100px) {\n      .topbar-status { display: none; }\n    }\n    @media (max-width: 840px) {\n      .stage { display: block; padding: 0; }\n      .shell { width: 100%; height: 100dvh; min-height: 0; border: 0; }\n      .topbar { flex-wrap: wrap; }\n      .brand { min-width: auto; height: 40px; border-right: 0; }\n      .brand-product, .brand-slash { display: none; }\n      .tabbar { order: 3; width: 100%; flex-basis: 100%; border-top: 1px solid var(--line); }\n      .topbar-meta { height: 40px; }\n      .nav-item { min-height: 39px; }\n      .split-view { grid-template-columns: 1fr; grid-template-rows: minmax(150px, 34%) minmax(0, 1fr); }\n      .pane-list { border-right: 0; border-bottom: 1px solid var(--line); }\n      .filter-control { width: 100%; }\n    }\n    @media (max-width: 560px) {\n      .detail-intro { min-height: 112px; padding: 16px; }\n      .detail-intro h2 { font-size: 17px; }\n      .property-list > div { grid-template-columns: minmax(98px, 0.38fr) minmax(0, 1fr); gap: 12px; padding-inline: 12px; }\n      .environment-grid { grid-template-columns: 1fr; }\n      .environment-grid > div + div { border-top: 1px solid var(--line); border-left: 0; }\n      .statusbar span:last-child { display: none; }\n    }\n    @media (prefers-reduced-motion: reduce) {\n      html { scroll-behavior: auto; }\n      *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }\n    }\n  </style>\n  <style data-assistant-ui-layout>\n    :root {\n      --background: #0a0a0a;\n      --surface: #0a0a0a;\n      --surface-raised: #111111;\n      --foreground: #ededed;\n      --muted: #929299;\n      --muted-strong: #b4b4ba;\n      --line: rgb(255 255 255 / 0.11);\n      --line-soft: rgb(255 255 255 / 0.075);\n      --line-strong: rgb(255 255 255 / 0.16);\n      --accent: #1c1c1e;\n    }\n    html, body { width: 100%; height: 100%; background: #080808; }\n    body { position: relative; min-height: 100dvh; overflow: hidden; font-size: 13px; }\n    .stage {\n      position: fixed;\n      inset: 0;\n      z-index: 2;\n      display: grid;\n      min-height: 0;\n      padding: 20px;\n      place-items: center;\n      pointer-events: none;\n    }\n    .shell {\n      width: min(960px, 92vw);\n      height: min(560px, 80dvh);\n      min-width: 0;\n      min-height: 0;\n      border: 1px solid var(--line-strong);\n      border-radius: 12px;\n      background: var(--background);\n      box-shadow: 0 24px 80px rgb(0 0 0 / 0.72), 0 4px 18px rgb(0 0 0 / 0.45);\n      pointer-events: auto;\n      animation: devtools-window-in 180ms cubic-bezier(0.175, 0.885, 0.32, 1.08);\n    }\n    .topbar {\n      min-height: 40px;\n      height: 40px;\n      align-items: center;\n      justify-content: space-between;\n      flex-wrap: nowrap;\n      border-bottom-color: var(--line);\n      background: var(--background);\n    }\n    .brand { display: none; }\n    .tabbar {\n      height: 100%;\n      flex: 1 1 auto;\n      align-items: stretch;\n      order: initial;\n      width: auto;\n      flex-basis: auto;\n      padding-inline-start: 8px;\n      border-top: 0;\n    }\n    .nav-item {\n      min-height: 39px;\n      height: 39px;\n      gap: 0;\n      padding: 0 12px;\n      border-radius: 0;\n      color: var(--muted);\n      font-family: var(--font-sans);\n      font-size: 13px;\n      font-weight: 500;\n      text-transform: none;\n    }\n    .nav-item::after {\n      right: 8px;\n      bottom: -1px;\n      left: 8px;\n      height: 2px;\n      border-radius: 999px;\n    }\n    .nav-item:hover, .nav-item:focus-visible { background: transparent; color: var(--foreground); }\n    .nav-item[aria-selected=\"true\"] { color: var(--foreground); }\n    .topbar-meta {\n      height: 100%;\n      align-items: center;\n      gap: 8px;\n      margin-left: 0;\n      padding: 0 8px 0 4px;\n      border-left: 0;\n    }\n    .project-select {\n      display: inline-flex;\n      height: 28px;\n      min-width: 0;\n      align-items: center;\n      gap: 5px;\n      padding: 0 9px;\n      border: 1px solid var(--line);\n      border-radius: 8px;\n      color: var(--muted-strong);\n      font-size: 12px;\n      white-space: nowrap;\n    }\n    .project-select .icon { width: 12px; height: 12px; transform: rotate(90deg); }\n    .topbar-status {\n      min-width: max-content;\n      gap: 6px;\n      padding: 0;\n      color: var(--muted);\n      font-family: var(--font-sans);\n      font-size: 11px;\n      text-transform: none;\n    }\n    .status-dot {\n      width: 6px;\n      height: 6px;\n      border: 0;\n      border-radius: 999px;\n      background: #2dd4bf;\n      box-shadow: none;\n    }\n    .status-dot-attention { background: #f59e0b; animation: none; }\n    .status-dot-error { background: #ef4444; }\n    .close-action {\n      display: inline-flex;\n      width: 28px;\n      height: 28px;\n      flex: 0 0 auto;\n      align-items: center;\n      justify-content: center;\n      padding: 0;\n      border: 0;\n      border-radius: 6px;\n      background: transparent;\n      color: var(--muted);\n      text-decoration: none;\n      transition: background-color 120ms ease-out, color 120ms ease-out;\n    }\n    .close-action:hover, .close-action:focus-visible { background: var(--accent); color: var(--foreground); outline: none; }\n    .close-action .icon { width: 14px; height: 14px; }\n    .workspace, .content, .view { min-height: 0; }\n    .split-view {\n      grid-template-columns: clamp(14rem, 28%, 18rem) minmax(0, 1fr);\n      grid-template-rows: minmax(0, 1fr);\n    }\n    .pane { background: var(--background); }\n    .pane-list { border-right: 1px solid var(--line); border-bottom: 0; }\n    .pane-header {\n      min-height: 32px;\n      height: 32px;\n      max-height: 32px;\n      flex: 0 0 32px;\n      padding: 0 12px;\n      border-bottom-color: var(--line);\n      background: var(--background);\n    }\n    .pane-header strong {\n      color: var(--muted);\n      font-size: 11px;\n      font-weight: 400;\n      line-height: 1;\n    }\n    .pane-header span {\n      color: var(--muted);\n      font-family: var(--font-sans);\n      font-size: 10px;\n      line-height: 1;\n    }\n    .pane-tools { border-bottom-color: var(--line); }\n    .pane-tools .filter-control { min-height: 32px; height: 32px; }\n    .filter-control {\n      min-height: 32px;\n      gap: 7px;\n      padding: 0 10px;\n      border-color: var(--line);\n      border-radius: 0;\n      background: var(--background);\n    }\n    .filter-control .icon { width: 13px; height: 13px; }\n    .filter-control input { font-family: var(--font-sans); font-size: 11px; }\n    .filter-control input::placeholder { color: var(--muted); }\n    .filter-control kbd {\n      padding: 1px 5px;\n      border-color: var(--line);\n      border-radius: 4px;\n      color: var(--muted);\n      font-size: 9px;\n    }\n    .inspector-row {\n      min-height: 44px;\n      grid-template-columns: minmax(0, 1fr) auto;\n      gap: 8px;\n      padding: 6px 11px 6px 12px;\n      border: 0;\n      border-left: 2px solid transparent;\n      border-radius: 0;\n      color: var(--muted-strong);\n    }\n    .inspector-row::before { display: none; }\n    .inspector-row:hover, .inspector-row:focus-visible { background: rgb(255 255 255 / 0.035); color: var(--foreground); }\n    .inspector-row[aria-selected=\"true\"] {\n      border-left-color: var(--foreground);\n      background: var(--accent);\n      color: var(--foreground);\n    }\n    .inspector-row-copy strong { font-size: 12px; font-weight: 500; }\n    .inspector-row-copy small {\n      margin-top: 2px;\n      color: var(--muted);\n      font-family: var(--font-sans);\n      font-size: 10px;\n    }\n    .inspector-row-value {\n      padding: 2px 6px;\n      border: 1px solid var(--line);\n      border-radius: 999px;\n      background: rgb(255 255 255 / 0.035);\n      color: var(--muted);\n      font-family: var(--font-sans);\n      font-size: 9px;\n      line-height: 1.2;\n      text-transform: none;\n    }\n    .detail-intro {\n      display: block;\n      min-height: 0;\n      padding: 12px;\n      border-bottom-color: var(--line-soft);\n    }\n    .detail-icon { display: none; }\n    .detail-intro .mini-label { margin: 0 0 8px; }\n    .detail-intro h2 { font-size: 13px; font-weight: 500; line-height: 1.3; }\n    .detail-intro p { margin-top: 6px; font-size: 11px; line-height: 1.5; }\n    .detail-section, .detail-intro + .detail-section { border-top-color: var(--line); }\n    .property-list > div {\n      min-height: 36px;\n      grid-template-columns: minmax(96px, 0.28fr) minmax(0, 1fr);\n      gap: 14px;\n      padding: 7px 12px;\n      border-bottom-color: var(--line-soft);\n    }\n    .property-list dt { font-family: var(--font-sans); font-size: 10px; text-transform: none; }\n    .property-list dd { color: var(--foreground); font-size: 11px; }\n    .property-list dd > code { font-size: 10px; }\n    .json-viewer {\n      padding: 12px;\n      background: var(--background);\n      color: var(--muted-strong);\n      font-size: 10px;\n      line-height: 1.55;\n    }\n    .diagnostic {\n      min-height: 68px;\n      grid-template-columns: 24px minmax(0, 1fr) auto;\n      gap: 10px;\n      padding: 11px 12px;\n      border-bottom-color: var(--line-soft);\n    }\n    .diagnostic-mark { width: 22px; height: 22px; border: 0; }\n    .diagnostic-mark .icon { width: 13px; height: 13px; }\n    .diagnostic-code { margin-bottom: 3px; font-size: 9px; }\n    .diagnostic strong { font-size: 11px; font-weight: 500; }\n    .diagnostic p { margin-top: 3px; font-size: 10px; line-height: 1.45; }\n    .diagnostic small { margin-top: 4px; font-size: 9px; }\n    .diagnostic-warning { box-shadow: none; }\n    .system-row {\n      min-height: 48px;\n      grid-template-columns: 24px minmax(0, 1fr) auto;\n      gap: 8px;\n      padding: 8px 12px;\n      border-bottom-color: var(--line-soft);\n    }\n    .system-icon { width: 20px; height: 20px; }\n    .system-icon .icon { width: 13px; height: 13px; }\n    .system-row strong { font-size: 11px; font-weight: 500; }\n    .system-row small { margin-top: 2px; font-size: 10px; }\n    .system-value { color: var(--muted); font-size: 10px; }\n    table { font-size: 11px; }\n    th {\n      height: 32px;\n      padding: 0 12px;\n      background: var(--background);\n      font-family: var(--font-sans);\n      font-size: 10px;\n      font-weight: 400;\n      text-transform: none;\n    }\n    td { min-height: 40px; padding: 9px 12px; font-size: 10px; }\n    td code, .file-cell { font-size: 9px; }\n    .badge {\n      min-height: 18px;\n      padding: 1px 6px;\n      border-radius: 999px;\n      background: rgb(255 255 255 / 0.04);\n      font-family: var(--font-sans);\n      font-size: 9px;\n      text-transform: none;\n    }\n    .badge-error { background: var(--foreground); color: var(--background); }\n    .badge-warning, .badge-attention, .badge-edge { border-style: solid; }\n    .empty-state { min-height: 100%; padding: 24px; gap: 6px; }\n    .empty-state .icon { display: none; }\n    .empty-state strong { font-size: 12px; font-weight: 400; }\n    .empty-state span { font-size: 11px; }\n    .feature-matrix > div { min-height: 36px; padding: 7px 12px; border-bottom-color: var(--line-soft); }\n    .feature-matrix span:first-child { font-size: 11px; }\n    .environment-grid > div { min-height: 104px; padding: 12px; }\n    .mini-label { margin-bottom: 8px; font-family: var(--font-sans); font-size: 10px; text-transform: none; }\n    .key-list code { border-radius: 4px; font-size: 9px; }\n    .layer-list > div { min-height: 44px; padding: 8px 12px; border-bottom-color: var(--line-soft); }\n    .layer-list strong { font-size: 11px; font-weight: 500; }\n    .statusbar { display: none; }\n    html.devtools-frame .stage { position: static; width: 100%; height: 100%; min-height: 100%; padding: 0; }\n    html.devtools-frame .shell { width: 100%; height: 100%; border-radius: 12px; box-shadow: none; animation: none; }\n    @keyframes devtools-window-in {\n      from { opacity: 0; transform: scale(0.985) translateY(4px); }\n      to { opacity: 1; transform: scale(1) translateY(0); }\n    }\n    @media (max-width: 700px) {\n      .stage { display: grid; padding: 0; }\n      .shell {\n        width: 100%;\n        height: 100%;\n        min-height: 0;\n        border: 1px solid var(--line-strong);\n        border-radius: 10px;\n      }\n      .topbar { flex-wrap: nowrap; }\n      .tabbar {\n        order: initial;\n        width: auto;\n        flex-basis: auto;\n        border-top: 0;\n        padding-inline-start: 4px;\n      }\n      .topbar-meta { height: 40px; }\n      .nav-item { min-height: 39px; height: 39px; padding-inline: 9px; }\n      .split-view { grid-template-columns: 1fr; grid-template-rows: minmax(148px, 36%) minmax(0, 1fr); }\n      .pane-list { border-right: 0; border-bottom: 1px solid var(--line); }\n    }\n    @media (max-width: 560px) {\n      .project-select { display: none; }\n      .topbar-status { display: none; }\n      .topbar-meta { gap: 4px; padding-left: 0; }\n      .status-label { display: none; }\n      .detail-intro { min-height: 0; padding: 12px; }\n      .detail-intro h2 { font-size: 13px; }\n      .property-list > div { grid-template-columns: minmax(82px, 0.34fr) minmax(0, 1fr); gap: 10px; padding-inline: 10px; }\n    }\n    @media (prefers-reduced-motion: reduce) {\n      .shell { animation: none; }\n    }\n  </style>\n</head>\n<body>\n  <div class=\"stage\">\n    <div class=\"shell\" role=\"dialog\" aria-modal=\"true\" aria-label=\"Farm.js DevTools\">\n      <header class=\"topbar\">\n        <nav class=\"tabbar\" aria-label=\"Devtools views\">\n          ${renderNavigationItem(\"overview\", \"Overview\")}\n          ${renderNavigationItem(\"routes\", \"Routes\")}\n          ${renderNavigationItem(\"api\", \"API\")}\n          ${renderNavigationItem(\"systems\", \"Systems\")}\n          ${renderNavigationItem(\"runtime\", \"Runtime\")}\n          ${renderNavigationItem(\"raw\", \"Raw\")}\n        </nav>\n        <div class=\"topbar-meta\">\n          <span class=\"deprecation-tag\" title=\"The built-in dashboard is deprecated. Install @farm.js/devtools for the maintained workspace.\">Deprecated &middot; use @farm.js/devtools</span>\n          <span class=\"project-select\">${escapeHtml(snapshot.project.name)} ${icon(\n            \"chevron\",\n          )}</span>\n          <span class=\"topbar-status\"><span class=\"status-dot\"></span><span class=\"status-label\">1 instance</span></span>\n          <button class=\"close-action\" type=\"button\" data-close-devtools aria-label=\"Close DevTools\" title=\"Close DevTools\">${icon(\n            \"close\",\n          )}</button>\n        </div>\n      </header>\n      <div class=\"workspace\">\n        <main class=\"content\">\n          <section class=\"view\" data-view-panel=\"overview\">${renderOverviewInspector(\n            snapshot,\n            healthLabel,\n            generatedTime,\n          )}</section>\n          <section class=\"view\" data-view-panel=\"routes\" hidden>${renderRoutesInspector(\n            snapshot,\n          )}</section>\n          <section class=\"view\" data-view-panel=\"api\" hidden>${renderApiInspector(\n            snapshot,\n          )}</section>\n          <section class=\"view\" data-view-panel=\"systems\" hidden>${renderSystemsInspector(\n            snapshot,\n          )}</section>\n          <section class=\"view\" data-view-panel=\"runtime\" hidden>${renderRuntimeInspector(\n            snapshot,\n          )}</section>\n          <section class=\"view\" data-view-panel=\"raw\" hidden>${renderRawInspector(snapshot)}</section>\n        </main>\n      </div>\n    </div>\n  </div>\n  <script>\n    (() => {\n      const embedded = window.parent !== window;\n      const closeDevtools = () => {\n        if (embedded && window.parent !== window) {\n          window.parent.postMessage({ type: \"farm:devtools:close\" }, location.origin);\n          return;\n        }\n        location.assign(\"/\");\n      };\n      document.querySelector(\"[data-close-devtools]\")?.addEventListener(\"click\", closeDevtools);\n      document.addEventListener(\"keydown\", (event) => {\n        if (event.key === \"Escape\") {\n          event.preventDefault();\n          closeDevtools();\n          return;\n        }\n        if (embedded && window.parent !== window) {\n          window.parent.postMessage(\n            {\n              type: \"farm:devtools:keydown\",\n              event: {\n                key: event.key,\n                code: event.code,\n                altKey: event.altKey,\n                ctrlKey: event.ctrlKey,\n                metaKey: event.metaKey,\n                shiftKey: event.shiftKey,\n                repeat: event.repeat,\n              },\n            },\n            location.origin,\n          );\n        }\n      });\n\n      const validViews = new Set([\"overview\", \"routes\", \"api\", \"systems\", \"runtime\", \"raw\"]);\n      const triggers = Array.from(document.querySelectorAll(\"[data-view-trigger]\"));\n      const panels = Array.from(document.querySelectorAll(\"[data-view-panel]\"));\n      const selectView = (view, updateHash = true) => {\n        const nextView = validViews.has(view) ? view : \"overview\";\n        triggers.forEach((trigger) => {\n          trigger.setAttribute(\"aria-selected\", String(trigger.dataset.viewTrigger === nextView));\n        });\n        panels.forEach((panel) => {\n          panel.hidden = panel.dataset.viewPanel !== nextView;\n        });\n        if (updateHash) {\n          history.replaceState(null, \"\", nextView === \"overview\" ? location.pathname : \"#\" + nextView);\n          const activePanel = panels.find((panel) => panel.dataset.viewPanel === nextView);\n          if (activePanel) activePanel.scrollTop = 0;\n        }\n      };\n      triggers.forEach((trigger) => trigger.addEventListener(\"click\", () => selectView(trigger.dataset.viewTrigger)));\n      window.addEventListener(\"hashchange\", () => selectView(location.hash.slice(1), false));\n      selectView(location.hash.slice(1), false);\n\n      document.querySelectorAll(\"[data-detail-trigger]\").forEach((trigger) => {\n        trigger.addEventListener(\"click\", () => {\n          const scope = trigger.dataset.detailTrigger;\n          const id = trigger.dataset.detailId;\n          document.querySelectorAll('[data-detail-trigger=\"' + scope + '\"]').forEach((row) => {\n            row.setAttribute(\"aria-selected\", String(row.dataset.detailId === id));\n          });\n          document.querySelectorAll('[data-detail-panel=\"' + scope + '\"]').forEach((panel) => {\n            panel.hidden = panel.dataset.detailId !== id;\n          });\n        });\n      });\n\n      document.querySelectorAll(\"[data-filter]\").forEach((input) => {\n        input.addEventListener(\"input\", () => {\n          const id = input.dataset.filter;\n          const query = input.value.trim().toLowerCase();\n          const rows = Array.from(document.querySelectorAll('[data-filter-rows=\"' + id + '\"] [data-search-value]'));\n          let visible = 0;\n          rows.forEach((row) => {\n            const matches = !query || (row.dataset.searchValue || \"\").toLowerCase().includes(query);\n            row.hidden = !matches;\n            if (matches) visible += 1;\n          });\n          const selected = rows.find((row) => row.getAttribute(\"aria-selected\") === \"true\");\n          if (selected?.hidden) rows.find((row) => !row.hidden)?.click();\n          const empty = document.querySelector('[data-filter-empty=\"' + id + '\"]');\n          if (empty) empty.hidden = visible !== 0;\n        });\n      });\n\n      document.addEventListener(\"keydown\", (event) => {\n        if (event.key !== \"/\" || event.metaKey || event.ctrlKey || event.altKey) return;\n        const active = document.activeElement;\n        if (active && (active.tagName === \"INPUT\" || active.tagName === \"TEXTAREA\")) return;\n        const panel = document.querySelector(\"[data-view-panel]:not([hidden])\");\n        const input = panel?.querySelector(\"[data-filter]\");\n        if (input) {\n          event.preventDefault();\n          input.focus();\n        }\n      });\n\n      document.querySelector(\"[data-refresh]\")?.addEventListener(\"click\", () => location.reload());\n      document.querySelector(\"[data-copy-snapshot]\")?.addEventListener(\"click\", async (event) => {\n        const button = event.currentTarget;\n        const label = button.querySelector(\"[data-copy-label]\");\n        try {\n          const response = await fetch(\"/__farm/devtools.json\", { cache: \"no-store\" });\n          const value = JSON.stringify(await response.json(), null, 2);\n          if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(value);\n          else {\n            const textarea = document.createElement(\"textarea\");\n            textarea.value = value;\n            document.body.appendChild(textarea);\n            textarea.select();\n            document.execCommand(\"copy\");\n            textarea.remove();\n          }\n          button.dataset.copied = \"true\";\n          if (label) label.textContent = \"Copied\";\n          setTimeout(() => {\n            button.dataset.copied = \"false\";\n            if (label) label.textContent = \"Copy JSON\";\n          }, 1600);\n        } catch {\n          if (label) label.textContent = \"Copy failed\";\n        }\n      });\n    })();\n  </script>\n</body>\n</html>`;\n}\n","import {\n  FARM_DEVTOOLS_LAUNCH_PARAM,\n  FARM_DEVTOOLS_PATH,\n  type ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\n\ntype ParsedShortcut = {\n  key: string;\n  alt: boolean;\n  ctrl: boolean;\n  meta: boolean;\n  mod: boolean;\n  shift: boolean;\n};\n\nfunction parseShortcut(shortcut: string): ParsedShortcut | null {\n  const tokens = shortcut\n    .toLowerCase()\n    .split(\"+\")\n    .map((token) => token.trim())\n    .filter(Boolean);\n  const key = tokens.find(\n    (token) =>\n      ![\"alt\", \"ctrl\", \"control\", \"meta\", \"cmd\", \"command\", \"mod\", \"shift\"].includes(token),\n  );\n\n  if (!key) {\n    return null;\n  }\n\n  return {\n    key,\n    alt: tokens.includes(\"alt\"),\n    ctrl: tokens.includes(\"ctrl\") || tokens.includes(\"control\"),\n    meta: tokens.includes(\"meta\") || tokens.includes(\"cmd\") || tokens.includes(\"command\"),\n    mod: tokens.includes(\"mod\"),\n    shift: tokens.includes(\"shift\"),\n  };\n}\n\nexport function generateFarmDevtoolsClientRuntime(config: ResolvedFarmDevtoolsConfig): string {\n  if (!config.enabled) {\n    return \"\";\n  }\n\n  const shortcut = config.shortcut ? parseShortcut(config.shortcut) : null;\n  const overlayStyles = `\n    #__farm_devtools_overlay__ {\n      position: fixed;\n      inset: 0;\n      z-index: 2147483646;\n      display: grid;\n      place-items: center;\n      box-sizing: border-box;\n      padding: 20px;\n      background: rgb(0 0 0 / 0);\n      backdrop-filter: blur(6px);\n      -webkit-backdrop-filter: blur(6px);\n      overscroll-behavior: none;\n      isolation: isolate;\n      opacity: 0;\n      pointer-events: none;\n      transition: opacity 150ms ease-out;\n    }\n    #__farm_devtools_overlay__[data-open=\"true\"] {\n      background: rgb(0 0 0 / 0.32);\n      opacity: 1;\n      pointer-events: auto;\n    }\n    #__farm_devtools_overlay__ > iframe {\n      display: block;\n      width: min(1100px, calc(100vw - 48px));\n      height: min(720px, calc(100dvh - 48px));\n      border: 0;\n      border-radius: 12px;\n      background: transparent;\n      box-shadow: 0 24px 80px rgb(0 0 0 / 0.48), 0 4px 18px rgb(0 0 0 / 0.24);\n      transform: scale(0.985) translateY(4px);\n      transition: transform 150ms ease-out;\n    }\n    #__farm_devtools_overlay__[data-open=\"true\"] > iframe {\n      transform: scale(1) translateY(0);\n    }\n    @media (max-width: 700px) {\n      #__farm_devtools_overlay__ { padding: 8px; }\n      #__farm_devtools_overlay__ > iframe {\n        width: calc(100vw - 16px);\n        height: calc(100dvh - 16px);\n        border-radius: 12px;\n      }\n    }\n    @media (prefers-reduced-motion: reduce) {\n      #__farm_devtools_overlay__, #__farm_devtools_overlay__ > iframe { transition: none; }\n    }\n  `;\n\n  return `\n(() => {\n  const overlayId = \"__farm_devtools_overlay__\";\n  const styleId = \"__farm_devtools_overlay_styles__\";\n  const runtimeKey = \"__FARM_DEVTOOLS_RUNTIME__\";\n  const launchParam = ${JSON.stringify(FARM_DEVTOOLS_LAUNCH_PARAM)};\n  const devtoolsPath = ${JSON.stringify(FARM_DEVTOOLS_PATH)};\n  const validViews = new Set([\"overview\", \"routes\", \"api\", \"systems\", \"runtime\", \"raw\", \"inspect\", \"diagnostics\"]);\n  const shortcut = ${JSON.stringify(shortcut)};\n  const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform);\n  let returnFocus = null;\n  let restorePage = null;\n  let closeTimer = null;\n\n  const lockPage = () => {\n    const styles = [];\n    for (const element of [document.documentElement, document.body]) {\n      for (const [property, value] of [[\"overflow-x\", \"hidden\"], [\"overflow-y\", \"hidden\"], [\"overscroll-behavior\", \"none\"]]) {\n        const previous = element.style.getPropertyValue(property);\n        const priority = element.style.getPropertyPriority(property);\n        element.style.setProperty(property, value, \"important\");\n        styles.push({ element, property, value, previous, priority });\n      }\n    }\n    return () => {\n      for (const { element, property, value, previous, priority } of styles) {\n        // Do not overwrite a newer style set by the application while the panel was open.\n        if (element.style.getPropertyValue(property) !== value || element.style.getPropertyPriority(property) !== \"important\") continue;\n        if (previous) element.style.setProperty(property, previous, priority);\n        else element.style.removeProperty(property);\n      }\n    };\n  };\n\n  const matchesShortcut = (event) => {\n    if (!shortcut || event.repeat) return false;\n    const expectedCtrl = shortcut.ctrl || (shortcut.mod && !isMac);\n    const expectedMeta = shortcut.meta || (shortcut.mod && isMac);\n    if (\n      Boolean(event.altKey) !== shortcut.alt ||\n      Boolean(event.ctrlKey) !== expectedCtrl ||\n      Boolean(event.metaKey) !== expectedMeta ||\n      Boolean(event.shiftKey) !== shortcut.shift\n    ) return false;\n\n    if (shortcut.key === \".\" || shortcut.key === \"period\") return event.code === \"Period\";\n    if (shortcut.key === \",\" || shortcut.key === \"comma\") return event.code === \"Comma\";\n    if (shortcut.key === \"/\" || shortcut.key === \"slash\") return event.code === \"Slash\";\n    return String(event.key || \"\").toLowerCase() === shortcut.key;\n  };\n\n  const ensureStyles = () => {\n    if (document.getElementById(styleId)) return;\n    const style = document.createElement(\"style\");\n    style.id = styleId;\n    style.textContent = ${JSON.stringify(overlayStyles)};\n    document.head.appendChild(style);\n  };\n\n  const finishClose = () => {\n    if (closeTimer !== null) window.clearTimeout(closeTimer);\n    closeTimer = null;\n    const overlay = document.getElementById(overlayId);\n    overlay?.remove();\n    restorePage?.();\n    restorePage = null;\n    const focusTarget = returnFocus;\n    returnFocus = null;\n    focusTarget?.focus?.({ preventScroll: true });\n  };\n\n  const close = () => {\n    const overlay = document.getElementById(overlayId);\n    if (!overlay || closeTimer !== null) return;\n    overlay.dataset.open = \"false\";\n    closeTimer = window.setTimeout(finishClose, 160);\n  };\n\n  const open = (view = \"overview\") => {\n    if (closeTimer !== null) finishClose();\n    if (document.getElementById(overlayId)) return;\n    ensureStyles();\n    returnFocus = document.activeElement;\n    restorePage = lockPage();\n    const overlay = document.createElement(\"div\");\n    overlay.id = overlayId;\n    overlay.setAttribute(\"role\", \"dialog\");\n    overlay.setAttribute(\"aria-modal\", \"true\");\n    overlay.setAttribute(\"aria-label\", \"Farm.js DevTools overlay\");\n    const frame = document.createElement(\"iframe\");\n    const resolvedView = validViews.has(view) ? view : \"overview\";\n    frame.src = devtoolsPath + \"?embedded=1\" + (resolvedView === \"overview\" ? \"\" : \"#\" + resolvedView);\n    frame.title = \"Farm.js DevTools\";\n    frame.addEventListener(\"load\", () => frame.contentWindow?.focus(), { once: true });\n    overlay.appendChild(frame);\n    overlay.addEventListener(\"pointerdown\", (event) => {\n      if (event.target === overlay) close();\n    });\n    overlay.addEventListener(\"wheel\", (event) => event.preventDefault(), { passive: false });\n    overlay.addEventListener(\"touchmove\", (event) => event.preventDefault(), { passive: false });\n    document.body.appendChild(overlay);\n    requestAnimationFrame(() => {\n      if (overlay.isConnected && closeTimer === null) overlay.dataset.open = \"true\";\n    });\n  };\n\n  const toggle = () => {\n    if (document.getElementById(overlayId)) close();\n    else open();\n  };\n\n  const onKeydown = (event) => {\n    if (event.key === \"Escape\" && document.getElementById(overlayId)) {\n      event.preventDefault();\n      close();\n      return;\n    }\n    if (!matchesShortcut(event)) return;\n    event.preventDefault();\n    event.stopPropagation();\n    toggle();\n  };\n\n  const onMessage = (event) => {\n    if (event.origin !== location.origin) return;\n    const frame = document.querySelector(\"#\" + overlayId + \" > iframe\");\n    if (!frame || event.source !== frame.contentWindow) return;\n    if (event.data?.type === \"farm:devtools:close\") close();\n    if (event.data?.type === \"farm:devtools:keydown\" && matchesShortcut(event.data.event || {})) close();\n  };\n\n  window[runtimeKey]?.dispose?.();\n  window.addEventListener(\"keydown\", onKeydown, true);\n  window.addEventListener(\"message\", onMessage);\n  window[runtimeKey] = {\n    dispose() {\n      finishClose();\n      window.removeEventListener(\"keydown\", onKeydown, true);\n      window.removeEventListener(\"message\", onMessage);\n    },\n  };\n  window.__FARM_DEVTOOLS__ = { open, close, toggle };\n\n  const launchUrl = new URL(location.href);\n  const launchRequest = launchUrl.searchParams.get(launchParam);\n  if (launchRequest !== null) {\n    const hashView = launchUrl.hash.slice(1);\n    const launchView = validViews.has(launchRequest)\n      ? launchRequest\n      : validViews.has(hashView)\n        ? hashView\n        : \"overview\";\n    launchUrl.searchParams.delete(launchParam);\n    if (validViews.has(hashView)) launchUrl.hash = \"\";\n    history.replaceState(\n      history.state,\n      \"\",\n      launchUrl.pathname + launchUrl.search + launchUrl.hash,\n    );\n    const launch = () => requestAnimationFrame(() => open(launchView));\n    if (document.readyState === \"loading\") {\n      document.addEventListener(\"DOMContentLoaded\", launch, { once: true });\n    } else {\n      launch();\n    }\n  }\n})();\n`;\n}\n","import type { ResolvedFarmImageConfig } from \"./image-config\";\nimport {\n  FarmImageRequestError,\n  isPrivateImageAddress,\n  selectOutputFormat,\n  type FarmImageTransformer,\n} from \"./image-server\";\n\ntype NodeImageDnsLookup = (\n  hostname: string,\n  options: { all: true; verbatim: true },\n  callback: (\n    error: NodeJS.ErrnoException | null,\n    addresses: Array<{ address: string; family: number }>,\n  ) => void,\n) => void;\n\nexport function createSharpImageTransformer(): FarmImageTransformer {\n  return async ({ source, sourceType, width, quality, accept, formats, signal }) => {\n    // Sharp is an optional native runtime. Load it only when an image request\n    // actually needs a transform so disabled/unused image pipelines do not add\n    // a startup dependency or native-module initialization cost.\n    const { default: sharp } = await import(\"sharp\");\n    throwIfAborted(signal);\n    const outputFormat = selectOutputFormat(accept, formats);\n    let pipeline = sharp(source, {\n      animated: sourceType === \"image/gif\" || sourceType === \"image/webp\",\n      failOn: \"warning\",\n      limitInputPixels: 268_402_689,\n    })\n      .rotate()\n      .resize({ width, fit: \"inside\", withoutEnlargement: true });\n\n    // When the Accept header matches none of the configured formats, keep the\n    // source's own format (svg rasterizes to png) instead of forcing JPEG —\n    // that preserved neither transparency nor the truth of the content type.\n    let encodedType: string;\n    if (outputFormat === \"image/avif\") {\n      pipeline = pipeline.avif({ quality });\n      encodedType = \"image/avif\";\n    } else if (outputFormat === \"image/webp\") {\n      pipeline = pipeline.webp({ quality });\n      encodedType = \"image/webp\";\n    } else if (sourceType === \"image/png\" || sourceType === \"image/svg+xml\") {\n      pipeline = pipeline.png();\n      encodedType = \"image/png\";\n    } else if (sourceType === \"image/gif\") {\n      pipeline = pipeline.gif();\n      encodedType = \"image/gif\";\n    } else if (sourceType === \"image/webp\") {\n      pipeline = pipeline.webp({ quality });\n      encodedType = \"image/webp\";\n    } else if (sourceType === \"image/avif\") {\n      pipeline = pipeline.avif({ quality });\n      encodedType = \"image/avif\";\n    } else {\n      pipeline = pipeline.jpeg({ quality });\n      encodedType = \"image/jpeg\";\n    }\n\n    const body = await pipeline.toBuffer();\n    throwIfAborted(signal);\n    return {\n      body,\n      contentType: encodedType,\n    };\n  };\n}\n\nexport function createNodeImageUrlValidator(config: ResolvedFarmImageConfig) {\n  return async function validateNodeImageUrl(url: URL): Promise<void> {\n    if (config.dangerouslyAllowLocalIP) return;\n\n    let addresses: Array<{ address: string; family: number }>;\n    try {\n      // DNS is only needed by remote image requests. Keeping it out of the\n      // initial server module graph reduces normal page/API startup work.\n      const { lookup } = await import(\"node:dns/promises\");\n      addresses = await lookup(url.hostname, { all: true, verbatim: true });\n    } catch {\n      throw new FarmImageRequestError(\n        \"PRIVATE_SOURCE\",\n        400,\n        \"Could not safely resolve the image source\",\n      );\n    }\n    if (addresses.length === 0 || addresses.some(({ address }) => isPrivateImageAddress(address))) {\n      throw new FarmImageRequestError(\"PRIVATE_SOURCE\", 400, \"Private image source is not allowed\");\n    }\n  };\n}\n\n/**\n * Create a remote image fetcher whose socket lookup rejects private addresses.\n * Validation and connection share this lookup, closing the DNS-rebinding gap\n * left by resolving a hostname before a separate global fetch.\n */\nexport function createNodeImageFetcher(\n  config: Pick<ResolvedFarmImageConfig, \"dangerouslyAllowLocalIP\">,\n  lookup?: NodeImageDnsLookup,\n): typeof globalThis.fetch {\n  if (config.dangerouslyAllowLocalIP) return globalThis.fetch.bind(globalThis);\n\n  return (async (input: RequestInfo | URL, init: RequestInit = {}) => {\n    const inputRequest = input instanceof Request ? input : undefined;\n    const url = input instanceof URL ? input : new URL(inputRequest?.url ?? String(input));\n    if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n      throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Unsupported image protocol\");\n    }\n\n    const [{ request }, { Readable }, dns] = await Promise.all([\n      url.protocol === \"https:\" ? import(\"node:https\") : import(\"node:http\"),\n      import(\"node:stream\"),\n      lookup ? Promise.resolve(null) : import(\"node:dns\"),\n    ]);\n    const resolveHostname = lookup ?? (dns!.lookup as unknown as NodeImageDnsLookup);\n    const headers = new Headers(inputRequest?.headers);\n    new Headers(init.headers).forEach((value, name) => headers.set(name, value));\n    if (!headers.has(\"accept-encoding\")) headers.set(\"accept-encoding\", \"identity\");\n\n    return new Promise<Response>((resolve, reject) => {\n      const nodeRequest = request(\n        url,\n        {\n          method: init.method ?? inputRequest?.method ?? \"GET\",\n          headers: Object.fromEntries(headers.entries()),\n          signal: init.signal ?? inputRequest?.signal,\n          lookup(hostname, options, callback) {\n            resolveHostname(hostname, { all: true, verbatim: true }, (error, addresses) => {\n              if (error) {\n                callback(error, \"\", 4);\n                return;\n              }\n              if (\n                addresses.length === 0 ||\n                addresses.some(({ address }) => isPrivateImageAddress(address))\n              ) {\n                callback(\n                  new FarmImageRequestError(\n                    \"PRIVATE_SOURCE\",\n                    400,\n                    \"Private image source is not allowed\",\n                  ),\n                  \"\",\n                  4,\n                );\n                return;\n              }\n\n              if (options.all) {\n                (\n                  callback as unknown as (\n                    error: null,\n                    addresses: Array<{ address: string; family: number }>,\n                  ) => void\n                )(null, addresses);\n                return;\n              }\n              const address = addresses[0]!;\n              callback(null, address.address, address.family);\n            });\n          },\n        },\n        (nodeResponse) => {\n          const status = nodeResponse.statusCode ?? 500;\n          if (status < 200 || status > 599) {\n            nodeResponse.resume();\n            reject(\n              new FarmImageRequestError(\n                \"UNSUPPORTED_IMAGE\",\n                502,\n                \"Image source returned an invalid HTTP status\",\n              ),\n            );\n            return;\n          }\n          const responseHeaders = new Headers();\n          for (let index = 0; index < nodeResponse.rawHeaders.length; index += 2) {\n            responseHeaders.append(\n              nodeResponse.rawHeaders[index]!,\n              nodeResponse.rawHeaders[index + 1]!,\n            );\n          }\n          const body =\n            status === 204 || status === 205 || status === 304\n              ? null\n              : (Readable.toWeb(nodeResponse) as ReadableStream);\n          resolve(\n            new Response(body, {\n              status,\n              statusText: nodeResponse.statusMessage,\n              headers: responseHeaders,\n            }),\n          );\n        },\n      );\n      nodeRequest.once(\"error\", reject);\n      nodeRequest.end();\n    });\n  }) as typeof globalThis.fetch;\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    throw signal.reason instanceof Error\n      ? signal.reason\n      : new DOMException(\"The image request was aborted\", \"AbortError\");\n  }\n}\n","import type { ConfigEnv, Plugin, UserConfig, ViteDevServer, HmrContext, Connect } from \"vite\";\nimport type { FarmConfig, FarmRequest } from \"./types\";\nimport { FarmApp } from \"./app\";\nimport { logger, toPosixPath, toViteModuleId } from \"./utils\";\nimport { defaultGlobalCSS } from \"./default-styles\";\nimport {\n  FARM_NODE_RESPONSE_END_PENDING,\n  type FarmPlugin,\n  type FarmPluginRuntimeSession,\n  type PluginManager,\n} from \"./plugin\";\nimport { generateFarmClientPluginEntryCode } from \"./client-plugin-build\";\nimport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n  type ClientCachePersistenceEntryCode,\n} from \"./client-cache-persistence-build\";\n\nexport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n} from \"./client-cache-persistence-build\";\nexport type { ClientCachePersistenceEntryCode } from \"./client-cache-persistence-build\";\nimport { APIRouteManager } from \"./api/route-manager\";\nimport { DEFAULT_FARM_API_BASE_PATH } from \"./api/config\";\nimport { resolveFarmAPIServerBasePath } from \"./api/server-path\";\nimport { isFarmAPIPathname } from \"./api/runtime\";\nimport type { OpenAPIManager } from \"./openapi/manager\";\nimport { MiddlewareManager } from \"./middleware/manager\";\nimport { generateFarmTypeArtifacts, type GenerateFarmTypeArtifactsOptions } from \"./type-artifacts\";\nimport {\n  isProgrammaticRoutesFileName,\n  parseProgrammaticRouteModuleId,\n  scanProgrammaticPagePaths,\n} from \"./routes-shared\";\nimport type { FarmDocsAPIHandler } from \"./docs\";\nimport { createMarkdownMirrorResponse, resolveMarkdownMirrorTarget } from \"./markdown\";\nimport {\n  FARM_MARKDOWN_CONTENT_TYPE,\n  createFarmMarkdownErrorBody,\n  createFarmMarkdownSourceResponse,\n  farmRequestWantsMarkdown,\n  isFarmMarkdownPageFile,\n  normalizeFarmMarkdownRoutePath,\n} from \"./app-markdown\";\nimport { applyWebResponseHeaders, sendWebResponse } from \"./server/response\";\nimport {\n  getClientModuleMetadata,\n  getIslandStrategyExport,\n  hasUseClientDirective,\n  isIsolatableClientBoundarySource,\n  resolveFarmIsolatedClientHydrationMode,\n  stripUseClientDirective,\n} from \"./utils/client-component\";\nimport {\n  dispatchIntegrationRequest,\n  getFarmIntegrationPluginOwner,\n  getIntegrationDocumentNavigationMatchers,\n  getIntegrationProviders,\n  matchIntegrationRoute,\n} from \"./integrations\";\nimport type { FarmDiscoveredWorkflow } from \"./workflows\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"./route-context\";\nimport {\n  FARM_DEVTOOLS_LAUNCH_PARAM,\n  FARM_DEVTOOLS_PATH,\n  resolveFarmDevtoolsConfig,\n} from \"./devtools-config\";\nimport { generateFarmDevIndicatorsClientRuntime } from \"./dev-indicators\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmUserConfig } from \"./config\";\nimport { getFarmAppDirectories, getFarmLayerAliases, getFarmSourceRoots } from \"./layers\";\nimport { farmEnvironmentFunctionsPlugin } from \"./environment-vite\";\nimport { FARM_VERSION } from \"./version\";\nimport { createDeferredDataResponse } from \"./deferred\";\nimport { _withAfterNodeMiddleware } from \"./after\";\nimport { _runWithAPIRequestRuntime } from \"./api/server-context\";\nimport type { APIRequestRuntime } from \"./api/server-client-bridge\";\nimport { shouldBypassFarmRouterForDottedPath } from \"./dev-static\";\nimport { findClientServerFnViolation, formatServerFnBoundaryError } from \"./server-query-boundary\";\nimport {\n  analyzeClientBoundary,\n  formatClientBoundaryWarning,\n  shouldInspectClientBoundary,\n} from \"./client-boundary-env\";\nimport {\n  createFarmDeploymentMismatchResponse,\n  FARM_DEPLOYMENT_ID_HEADER,\n  getFarmDeploymentMismatch,\n} from \"./deployment\";\nimport { getPublicFarmImageConfig, resolveFarmImageConfig } from \"./image-config\";\nimport { farmImageImportsPlugin } from \"./image-vite\";\nimport { farmFontImportsPlugin } from \"./font-vite\";\nimport { resolveFarmLayoutFonts } from \"./font\";\nimport { createFarmImageHandler, type FarmImageHandler } from \"./image-server\";\nimport { getFarmI18nClientSnapshot } from \"./i18n/server\";\nimport { localizeFarmPathname } from \"./i18n/routing\";\nimport type { FarmI18nClientSnapshot } from \"./i18n/types\";\nimport {\n  createFarmClientOptimizeDepsConfig,\n  createFarmClientOptimizeDepsEntries,\n  createFarmSourceAlias,\n} from \"./server/vite-config\";\nimport { resolveFarmDocsFontAssets, toFarmDocsPublicFontAssets } from \"./docs/fonts\";\nimport {\n  createFarmNodeRequestAbortSignal,\n  createFarmRequestBodyErrorResponse,\n  readNodeRequestBody,\n  resolveFarmServerConfig,\n} from \"./server-http\";\nimport { createCliColors } from \"./cli-colors\";\nimport { createFarmThemeCssPlugin } from \"./theme/vite\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { emitFarmEvent, runWithFarmRequestSpan } from \"./observability\";\nimport {\n  isReactRenderer,\n  loadFarmRendererVitePlugins,\n  REACT_RENDERER,\n  resolveFarmRenderer,\n} from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { generateFarmIntegrationProviderClientCode } from \"./integration-provider-build\";\nimport type { FarmIslandStrategy } from \"./island\";\nimport { resolveRouteRenderingConfig } from \"./ssg\";\nimport {\n  createFarmRouteRenderPlan,\n  getSharedLayoutPrefixLength,\n  getFarmFragmentCacheControl,\n  parseFarmLayoutChainHeader,\n} from \"./navigation/render-plan\";\nimport { resolveFarmPageDataFailure } from \"./navigation/page-data-error\";\nimport { FARM_CONFIG_REWRITES_PLUGIN_NAME } from \"./plugins/rewrites\";\nimport { resolveFarmRequestURL } from \"./server/request\";\nimport { reportOpenAPIDevGenerationResult } from \"./openapi/dev-status\";\n\ninterface FarmVitePluginOptions extends FarmConfig {\n  openapi?: FarmUserConfig[\"openapi\"];\n  images?: FarmUserConfig[\"images\"];\n  publicDir?: FarmUserConfig[\"publicDir\"];\n  /** @internal Modules selected by the compiled isolated-hydration ownership plan. */\n  isolatedClientBoundaryModules?: ReadonlySet<string>;\n}\n\ntype TypeArtifactSelection = Pick<\n  GenerateFarmTypeArtifactsOptions,\n  \"routes\" | \"api\" | \"env\" | \"images\" | \"i18n\"\n>;\n\nconst ALL_TYPE_ARTIFACTS: TypeArtifactSelection = {\n  routes: true,\n  api: true,\n  env: true,\n  images: false,\n  i18n: true,\n};\n\nconst createEmptyTypeArtifactSelection = (): TypeArtifactSelection => ({\n  routes: false,\n  api: false,\n  env: false,\n  images: false,\n  i18n: false,\n});\n\nconst FARM_I18N_CLIENT_BRIDGE_ID = \"\\0farm-i18n-client-bridge\";\n\n// The @farm.js/devtools plugin serves this path itself; reaching the built-in\n// dashboard render means the app is still on the deprecated core UI.\nlet warnedDeprecatedDevtoolsDashboard = false;\nconst EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME = `\nfunction isFarmDocsSearchPage() {\n  return false;\n}\n\nasync function mountFarmDocsSearch() {\n  return false;\n}\n`;\n\nfunction loadFarmDocsDevRuntime() {\n  return import(\"./docs\");\n}\n\nfunction loadFarmDocsSearchDevRuntime() {\n  return import(\"./docs/search-client\");\n}\n\nfunction loadFarmOpenAPIDevRuntime() {\n  return import(\"./openapi/manager\");\n}\n\nfunction loadFarmWorkflowsDevRuntime() {\n  return import(\"./workflows\");\n}\n\nfunction loadFarmDevtoolsSnapshotRuntime() {\n  return import(\"./devtools\");\n}\n\nfunction loadFarmDevtoolsUIRuntime() {\n  return import(\"./devtools-ui\");\n}\n\nfunction loadFarmDevtoolsClientRuntime() {\n  return import(\"./devtools-client\");\n}\n\nexport function farmI18nClientBridgePlugin(): Plugin {\n  return {\n    name: \"farm:i18n-client-bridge\",\n    enforce: \"pre\",\n    resolveId(id, _importer, options) {\n      if (id === \"@farm.js/core/i18n/server\" && !options?.ssr) {\n        return FARM_I18N_CLIENT_BRIDGE_ID;\n      }\n      return null;\n    },\n    load(id) {\n      if (id !== FARM_I18N_CLIENT_BRIDGE_ID) return null;\n      return 'export { createTranslator, format, getLocale, getLocaleSource, t } from \"@farm.js/core/i18n/client\";';\n    },\n  };\n}\n\nconst FARM_CONFIG_FILENAMES = new Set([\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n]);\n\nfunction serializeFarmInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeFarmHtmlAttribute(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nfunction renderFarmI18nStaticHead(\n  requestPath: string,\n  snapshot: FarmI18nClientSnapshot | undefined,\n): string {\n  if (!snapshot) return \"\";\n  const runtime = `<script>window.__FARM_I18N__ = ${serializeFarmInlineValue(snapshot)};</script>`;\n  if (snapshot.routing === \"none\") return runtime;\n\n  const links = snapshot.locales.map(\n    (locale) =>\n      `<link rel=\"alternate\" hreflang=\"${escapeFarmHtmlAttribute(locale)}\" href=\"${escapeFarmHtmlAttribute(\n        localizeFarmPathname(requestPath, locale, snapshot),\n      )}\">`,\n  );\n  links.push(\n    `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeFarmHtmlAttribute(\n      localizeFarmPathname(requestPath, snapshot.defaultLocale, snapshot),\n    )}\">`,\n  );\n  return `${links.join(\"\")}${runtime}`;\n}\n\nfunction getPublicEnvDefine(config: FarmVitePluginOptions): Record<string, unknown> {\n  const publicEnv = (config as any).env?.public;\n  if (!isResolvedEnvScope(publicEnv)) {\n    return {};\n  }\n\n  return publicEnv;\n}\n\nfunction createRequestFromNodeRequest(\n  req: {\n    method?: string;\n    headers: Record<string, string | string[] | undefined>;\n  },\n  url: URL,\n  signal?: AbortSignal,\n): Request {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (Array.isArray(value)) {\n      for (const item of value) headers.append(key, item);\n    } else if (value !== undefined) {\n      headers.set(key, value);\n    }\n  }\n\n  return new Request(url.toString(), {\n    method: req.method || \"GET\",\n    headers,\n    signal,\n  });\n}\n\nexport { createFarmNodeRequestAbortSignal } from \"./server-http\";\n\n/** Exported for tests: the request boundary all Farm dev middlewares share. */\nexport function withFarmRequestTracing(\n  handler: Parameters<typeof _withAfterNodeMiddleware>[0],\n  apiRuntime?: APIRequestRuntime,\n): Connect.NextHandleFunction {\n  const middleware = _withAfterNodeMiddleware(handler);\n  return (req, res, next) => {\n    const traceUrl = new URL(`http://${req.headers.host || \"localhost:3000\"}${req.url || \"/\"}`);\n    const traceRequest = createRequestFromNodeRequest(req, traceUrl);\n    const run = () =>\n      runWithFarmRequestSpan(traceRequest, () => middleware(req, res, next), {\n        getStatusCode: () => res.statusCode || 200,\n      });\n    const result = apiRuntime ? _runWithAPIRequestRuntime(apiRuntime, run) : run();\n    // connect ignores returned promises, so a rejection from the handler\n    // becomes an unhandled rejection and kills the dev server process. A\n    // throw from one request must cost that request a 500, not an outage.\n    return Promise.resolve(result).catch((error) => {\n      console.error(\n        `[FARM] Unhandled error while handling ${req.method || \"GET\"} ${req.url || \"/\"}:`,\n        error,\n      );\n      if (res.writableEnded) {\n        return;\n      }\n      if (res.headersSent) {\n        res.destroy?.(error instanceof Error ? error : new Error(String(error)));\n        return;\n      }\n      res.statusCode = 500;\n      res.setHeader(\"Content-Type\", \"application/json\");\n      res.end(JSON.stringify({ error: \"Internal server error\" }));\n    });\n  };\n}\n\nfunction toRequestBody(body: Buffer | undefined): ArrayBuffer | undefined {\n  if (!body) return undefined;\n  const copy = new Uint8Array(body.byteLength);\n  copy.set(body);\n  return copy.buffer;\n}\n\nfunction applyWebRequestToNodeRequest(\n  request: Request,\n  req: {\n    method?: string;\n    url?: string;\n    headers: Record<string, string | string[] | undefined>;\n  },\n): void {\n  const url = new URL(request.url);\n  req.method = request.method;\n  req.url = `${url.pathname}${url.search}`;\n\n  for (const key of Object.keys(req.headers)) {\n    delete req.headers[key];\n  }\n  request.headers.forEach((value, key) => {\n    req.headers[key] = value;\n  });\n}\n\nfunction createHeadersFromNodeResponse(res: {\n  getHeaders(): Record<string, string | number | string[] | undefined>;\n}): Headers {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(res.getHeaders())) {\n    if (Array.isArray(value)) {\n      for (const item of value) headers.append(key, item);\n    } else if (value !== undefined) {\n      headers.set(key, String(value));\n    }\n  }\n  return headers;\n}\n\nfunction applyWebResponseToNodeResponse(\n  response: Response,\n  res: {\n    statusCode: number;\n    headersSent: boolean;\n    getHeaderNames(): string[];\n    removeHeader(name: string): void;\n    setHeader(name: string, value: string): void;\n  },\n): void {\n  if (res.headersSent) return;\n\n  res.statusCode = response.status;\n  for (const name of res.getHeaderNames()) {\n    res.removeHeader(name);\n  }\n  applyWebResponseHeaders(res as any, response.headers);\n}\n\nfunction toNodeResponseBuffer(chunk: unknown, encoding?: unknown): Buffer | undefined {\n  if (chunk === undefined || chunk === null || typeof chunk === \"function\") return undefined;\n  if (Buffer.isBuffer(chunk)) return chunk;\n  if (chunk instanceof Uint8Array) return Buffer.from(chunk);\n  return Buffer.from(\n    String(chunk),\n    typeof encoding === \"string\" ? (encoding as BufferEncoding) : \"utf8\",\n  );\n}\n\nfunction applyNodeWriteHeadHeaders(res: any, headers: unknown): void {\n  if (Array.isArray(headers)) {\n    const grouped = new Map<string, { name: string; values: Array<string | number> }>();\n    for (let index = 0; index + 1 < headers.length; index += 2) {\n      const name = String(headers[index]);\n      const key = name.toLowerCase();\n      const entry = grouped.get(key) ?? { name, values: [] };\n      const value = headers[index + 1];\n      entry.values.push(...(Array.isArray(value) ? value : [value]).map(String));\n      grouped.set(key, entry);\n    }\n    for (const { name, values } of grouped.values()) {\n      res.setHeader(name, values.length === 1 ? values[0] : values);\n    }\n    return;\n  }\n\n  if (!headers || typeof headers !== \"object\") return;\n  for (const [name, value] of Object.entries(headers)) {\n    if (value !== undefined) res.setHeader(name, value);\n  }\n}\n\nfunction interceptFarmDevPageResponse(options: {\n  req: any;\n  res: any;\n  pm: PluginManager;\n  runtimeSession?: FarmPluginRuntimeSession;\n  hasRuntimeAfterHook: boolean;\n  hasAfterResponseHook: boolean;\n  hasHTMLTransformHook: boolean;\n  renderPayload: Record<string, unknown>;\n  method: string;\n  urlPath: string;\n  pathname: string;\n  startTime: number;\n  logResponse(method: string, path: string, status: number, durationMs: number, type: \"PAGE\"): void;\n  emitError(error: unknown): Promise<void>;\n}): { isEnded(): boolean } {\n  const {\n    req,\n    res,\n    pm,\n    runtimeSession,\n    hasRuntimeAfterHook,\n    hasAfterResponseHook,\n    hasHTMLTransformHook,\n    renderPayload,\n    method,\n    urlPath,\n    startTime,\n  } = options;\n  const originalWrite = res.write.bind(res);\n  const originalEnd = res.end.bind(res);\n  const originalWriteHead = res.writeHead.bind(res);\n  const originalFlushHeaders = res.flushHeaders?.bind(res);\n  let afterResponseCalled = false;\n  let interceptedEnd = false;\n  const htmlChunks: Buffer[] = [];\n  const responseChunks: Buffer[] = [];\n  let didStreamHtml = false;\n  const bufferPluginResponse = Boolean(\n    hasHTMLTransformHook || (runtimeSession && hasRuntimeAfterHook),\n  );\n  const shouldBufferCurrentResponse = () => {\n    const contentTypeHeader = res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n    const contentType = typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n    return contentType.includes(\"text/html\")\n      ? bufferPluginResponse\n      : Boolean(runtimeSession && hasRuntimeAfterHook);\n  };\n\n  res.writeHead = ((statusCode: number, ...args: unknown[]) => {\n    const statusMessage = typeof args[0] === \"string\" ? args[0] : undefined;\n    const headers = statusMessage === undefined ? args[0] : args[1];\n    res.statusCode = statusCode;\n    if (statusMessage !== undefined) res.statusMessage = statusMessage;\n    applyNodeWriteHeadHeaders(res, headers);\n\n    if (shouldBufferCurrentResponse()) return res;\n    return statusMessage === undefined\n      ? originalWriteHead(statusCode)\n      : originalWriteHead(statusCode, statusMessage);\n  }) as any;\n\n  if (originalFlushHeaders) {\n    res.flushHeaders = (() =>\n      shouldBufferCurrentResponse() ? undefined : originalFlushHeaders()) as any;\n  }\n\n  res.write = ((chunk: unknown, ...args: unknown[]) => {\n    const contentTypeHeader = res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n    const contentType = typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n    const isHtmlResponse = contentType.includes(\"text/html\");\n    const bufferChunk = toNodeResponseBuffer(chunk, args[0]);\n\n    if (isHtmlResponse && bufferChunk) {\n      htmlChunks.push(bufferChunk);\n      didStreamHtml = true;\n    } else if (runtimeSession && hasRuntimeAfterHook && bufferChunk) {\n      responseChunks.push(bufferChunk);\n    }\n\n    const shouldBufferResponse = isHtmlResponse\n      ? bufferPluginResponse\n      : Boolean(runtimeSession && hasRuntimeAfterHook);\n    if (shouldBufferResponse) {\n      const callback = args.find((arg) => typeof arg === \"function\") as (() => void) | undefined;\n      callback?.();\n      return true;\n    }\n\n    const writeResult = originalWrite(chunk, ...args);\n    if (isHtmlResponse && typeof res.flush === \"function\") res.flush();\n    return writeResult;\n  }) as any;\n\n  res.end = ((...args: unknown[]) => {\n    interceptedEnd = true;\n    res[FARM_NODE_RESPONSE_END_PENDING] = true;\n    if (afterResponseCalled) return res;\n\n    afterResponseCalled = true;\n    options.logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, \"PAGE\");\n    const originalEndArgs = [...args];\n    const callback =\n      typeof originalEndArgs[originalEndArgs.length - 1] === \"function\"\n        ? (originalEndArgs[originalEndArgs.length - 1] as () => void)\n        : undefined;\n    const contentTypeHeader = res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n    const contentType = typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n    const isHtmlResponse = contentType.includes(\"text/html\");\n    const finalChunk = toNodeResponseBuffer(args[0], args[1]);\n    if (finalChunk) {\n      if (isHtmlResponse) htmlChunks.push(finalChunk);\n      else if (runtimeSession && hasRuntimeAfterHook) responseChunks.push(finalChunk);\n    }\n\n    Promise.resolve()\n      .then(async () => {\n        if (isHtmlResponse) {\n          const fullHtml = Buffer.concat(htmlChunks).toString(\"utf8\");\n          if (!didStreamHtml || bufferPluginResponse) {\n            let html = await pm.runHookSerial(\"transformHTML\", fullHtml);\n            html = await pm.runHookSerial(\"afterRender\", html, renderPayload);\n            originalEndArgs.length = 0;\n            originalEndArgs.push(html);\n            if (callback) originalEndArgs.push(callback);\n          } else {\n            await pm.runHookSerial(\"transformHTML\", fullHtml);\n            await pm.runHookSerial(\"afterRender\", fullHtml, renderPayload);\n          }\n        }\n\n        if (runtimeSession) {\n          pm.copyRequestContext(req, runtimeSession.request);\n          const status = res.statusCode || 200;\n          const canHaveBody =\n            method !== \"HEAD\" && status !== 204 && status !== 205 && status !== 304;\n          const firstArg = originalEndArgs[0];\n          const responseBody = canHaveBody\n            ? isHtmlResponse\n              ? didStreamHtml && !bufferPluginResponse\n                ? Buffer.concat(htmlChunks)\n                : toNodeResponseBuffer(firstArg, originalEndArgs[1])\n              : hasRuntimeAfterHook\n                ? Buffer.concat(responseChunks)\n                : toNodeResponseBuffer(firstArg, originalEndArgs[1])\n            : null;\n          const runtimeResponse = await pm.endRuntimeRequest(\n            runtimeSession,\n            new Response(responseBody ? toRequestBody(responseBody) : responseBody, {\n              status,\n              headers: createHeadersFromNodeResponse(res),\n            }),\n          );\n          applyWebResponseToNodeResponse(runtimeResponse, res);\n\n          const canReplaceOutput = isHtmlResponse\n            ? !didStreamHtml || bufferPluginResponse\n            : hasRuntimeAfterHook;\n          if (canReplaceOutput) {\n            const body = runtimeResponse.body\n              ? Buffer.from(await runtimeResponse.arrayBuffer())\n              : undefined;\n            originalEndArgs.length = 0;\n            if (body) originalEndArgs.push(body);\n            if (callback) originalEndArgs.push(callback);\n          }\n        }\n      })\n      .then(() =>\n        hasAfterResponseHook ? pm.runHookParallel(\"afterResponse\", req, res) : undefined,\n      )\n      .then(() => {\n        res.write = originalWrite;\n        res.end = originalEnd;\n        res.writeHead = originalWriteHead;\n        if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;\n        delete res[FARM_NODE_RESPONSE_END_PENDING];\n        originalEnd(...originalEndArgs);\n      })\n      .catch((error) => {\n        void options.emitError(error);\n        console.error(\"Error in afterResponse hook:\", error);\n        const shouldBufferResponse = isHtmlResponse\n          ? bufferPluginResponse\n          : Boolean(runtimeSession && hasRuntimeAfterHook);\n        if (shouldBufferResponse) {\n          const body = Buffer.concat(isHtmlResponse ? htmlChunks : responseChunks);\n          res.write = originalWrite;\n          res.end = originalEnd;\n          res.writeHead = originalWriteHead;\n          if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;\n          delete res[FARM_NODE_RESPONSE_END_PENDING];\n          originalEnd(body, callback);\n        } else {\n          res.write = originalWrite;\n          res.end = originalEnd;\n          res.writeHead = originalWriteHead;\n          if (originalFlushHeaders) res.flushHeaders = originalFlushHeaders;\n          delete res[FARM_NODE_RESPONSE_END_PENDING];\n          originalEnd(...originalEndArgs);\n        }\n      });\n\n    return res;\n  }) as any;\n\n  return {\n    isEnded: () => interceptedEnd || res.writableEnded,\n  };\n}\n\nfunction getFullEnvDefine(config: FarmVitePluginOptions): {\n  server: Record<string, unknown>;\n  public: Record<string, unknown>;\n} {\n  const env = (config as any).env;\n  if (!env || typeof env !== \"object\") {\n    return { server: {}, public: {} };\n  }\n\n  return {\n    server: isResolvedEnvScope(env.server) ? env.server : {},\n    public: isResolvedEnvScope(env.public) ? env.public : {},\n  };\n}\n\nfunction getEnvDefines(\n  config: FarmVitePluginOptions,\n  configEnv?: ConfigEnv,\n): Record<string, string> {\n  const defines: Record<string, string> = {\n    __FARM_API_BASE_URL__: JSON.stringify(getFarmAPIBaseURLDefine(config)),\n    __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),\n    __FARM_IMAGE_CONFIG__: JSON.stringify(\n      getPublicFarmImageConfig(resolveFarmImageConfig(config.images)),\n    ),\n  };\n\n  if (configEnv?.isSsrBuild) {\n    defines.__FARM_ENV__ = JSON.stringify(getFullEnvDefine(config));\n  }\n\n  return defines;\n}\n\nfunction getFarmAPIBaseURLDefine(config: FarmVitePluginOptions): string {\n  const baseURL = config.api?.baseURL;\n  return typeof baseURL === \"string\" && baseURL ? baseURL : DEFAULT_FARM_API_BASE_PATH;\n}\n\nfunction isResolvedEnvScope(value: unknown): value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    return false;\n  }\n\n  return !Object.values(value).some(\n    (entry) =>\n      typeof entry === \"function\" ||\n      (!!entry && typeof entry === \"object\" && typeof (entry as any).parse === \"function\"),\n  );\n}\n\nfunction isPotentialProgrammaticRouteSourceFile(\n  normalizedFile: string,\n  srcDirSlug: string,\n): boolean {\n  return (\n    normalizedFile.startsWith(`${srcDirSlug}/`) &&\n    /\\.(ts|tsx|js|jsx)$/.test(normalizedFile) &&\n    !normalizedFile.endsWith(\".d.ts\") &&\n    !normalizedFile.endsWith(\"/farm-routes.d.ts\") &&\n    !normalizedFile.endsWith(\"/farm-env.d.ts\") &&\n    !normalizedFile.endsWith(\"/lib/api.generated.ts\")\n  );\n}\n\nfunction fileContainsProgrammaticPageRoute(file: string): boolean {\n  if (!fs.existsSync(file)) {\n    return false;\n  }\n\n  try {\n    return scanProgrammaticPagePaths(fs.readFileSync(file, \"utf8\")).length > 0;\n  } catch {\n    return false;\n  }\n}\n\ninterface FarmModuleAstNode {\n  type: string;\n  start: number;\n  end: number;\n  [key: string]: unknown;\n}\n\nexport function rewriteEarlySsrRelativeImports(options: {\n  code: string;\n  id: string;\n  root: string;\n  parse: (code: string) => FarmModuleAstNode;\n}): string | null {\n  const cleanId = options.id.split(\"?\", 1)[0];\n  if (!path.isAbsolute(cleanId) || cleanId.replace(/\\\\/g, \"/\").includes(\"/node_modules/\")) {\n    return null;\n  }\n\n  const replacements: Array<{ start: number; end: number; code: string }> = [];\n  let ast: FarmModuleAstNode;\n  try {\n    ast = options.parse(options.code);\n  } catch {\n    return null;\n  }\n\n  walkModuleAst(ast, (node) => {\n    if (\n      node.type !== \"ImportDeclaration\" &&\n      node.type !== \"ExportNamedDeclaration\" &&\n      node.type !== \"ExportAllDeclaration\" &&\n      node.type !== \"ImportExpression\"\n    ) {\n      return;\n    }\n\n    const source = node.source;\n    if (!isFarmModuleAstNode(source) || typeof source.value !== \"string\") return;\n    if (!source.value.startsWith(\".\")) return;\n\n    const suffixIndex = source.value.search(/[?#]/);\n    const sourcePath = suffixIndex === -1 ? source.value : source.value.slice(0, suffixIndex);\n    const suffix = suffixIndex === -1 ? \"\" : source.value.slice(suffixIndex);\n    const resolvedPath = path.resolve(path.dirname(cleanId), sourcePath);\n\n    replacements.push({\n      start: source.start,\n      end: source.end,\n      code: JSON.stringify(`${toViteModuleId(resolvedPath, options.root)}${suffix}`),\n    });\n  });\n\n  if (replacements.length === 0) return null;\n\n  let output = options.code;\n  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n    output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n  }\n  return output;\n}\n\nexport function transformIsolatedClientBoundaryModule(options: {\n  code: string;\n  moduleReference: string;\n  islandStrategy: FarmIslandStrategy;\n  parse: (code: string) => FarmModuleAstNode;\n}): string | null {\n  let ast: FarmModuleAstNode;\n  try {\n    ast = options.parse(options.code);\n  } catch {\n    return null;\n  }\n\n  const body = Array.isArray((ast as any).body) ? ((ast as any).body as any[]) : [];\n  const replacements: Array<{ start: number; end: number; code: string }> = [];\n  const wrapperStatements: string[] = [];\n  const originalEntries: string[] = [];\n  let transformedExports = 0;\n\n  const addWrapper = (localName: string, exportName: string, isDefault = false) => {\n    const safeName = exportName.replace(/[^A-Za-z0-9_$]/g, \"_\");\n    const wrapperName = `__farm_isolated_boundary_${safeName || \"default\"}__`;\n    wrapperStatements.push(\n      `const ${wrapperName} = __farm_create_isolated_boundary__(__farm_isolated_react__, ${localName}, ${JSON.stringify(options.moduleReference)}, ${JSON.stringify(exportName)}, ${JSON.stringify(options.islandStrategy)});`,\n    );\n    wrapperStatements.push(\n      isDefault ? `export default ${wrapperName};` : `export { ${wrapperName} as ${exportName} };`,\n    );\n    originalEntries.push(`${JSON.stringify(exportName)}: ${localName}`);\n    transformedExports++;\n  };\n\n  for (const node of body) {\n    if (node?.type === \"ExportDefaultDeclaration\" && node.declaration) {\n      const declaration = node.declaration;\n      if (\n        (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\n        declaration.id?.name\n      ) {\n        replacements.push({\n          start: node.start,\n          end: node.end,\n          code: options.code.slice(declaration.start, declaration.end),\n        });\n        addWrapper(declaration.id.name, \"default\", true);\n      } else {\n        const originalName = \"__farm_isolated_original_default__\";\n        replacements.push({\n          start: node.start,\n          end: node.end,\n          code: `const ${originalName} = (${options.code.slice(declaration.start, declaration.end)});`,\n        });\n        addWrapper(originalName, \"default\", true);\n      }\n      continue;\n    }\n\n    if (node?.type !== \"ExportNamedDeclaration\" || !node.declaration) continue;\n    const declaration = node.declaration;\n    const declaredNames: string[] = [];\n    if (\n      (declaration.type === \"FunctionDeclaration\" || declaration.type === \"ClassDeclaration\") &&\n      declaration.id?.name\n    ) {\n      declaredNames.push(declaration.id.name);\n    } else if (declaration.type === \"VariableDeclaration\") {\n      for (const declarator of declaration.declarations || []) {\n        if (declarator.id?.type === \"Identifier\") declaredNames.push(declarator.id.name);\n      }\n    }\n    const componentNames = declaredNames.filter((name) => /^[A-Z]/.test(name));\n    if (componentNames.length === 0) continue;\n\n    replacements.push({\n      start: node.start,\n      end: node.end,\n      code: options.code.slice(declaration.start, declaration.end),\n    });\n    for (const name of declaredNames) {\n      if (/^[A-Z]/.test(name)) addWrapper(name, name);\n      else wrapperStatements.push(`export { ${name} };`);\n    }\n  }\n\n  if (transformedExports === 0) return null;\n  let output = options.code;\n  for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n    output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n  }\n\n  return `import * as __farm_isolated_react__ from \"react\";\\nimport { createFarmIsolatedClientBoundary as __farm_create_isolated_boundary__ } from \"@farm.js/core/internal/isolated-boundary\";\\n${output}\\n${wrapperStatements.join(\"\\n\")}\\nexport const __farm_client_boundary_originals__ = Object.freeze({ ${originalEntries.join(\", \")} });\\n`;\n}\n\nfunction walkModuleAst(node: FarmModuleAstNode, visit: (node: FarmModuleAstNode) => void): void {\n  visit(node);\n\n  for (const [key, value] of Object.entries(node)) {\n    if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n    if (isFarmModuleAstNode(value)) {\n      walkModuleAst(value, visit);\n      continue;\n    }\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        if (isFarmModuleAstNode(item)) walkModuleAst(item, visit);\n      }\n    }\n  }\n}\n\nfunction isFarmModuleAstNode(value: unknown): value is FarmModuleAstNode {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as FarmModuleAstNode).type === \"string\" &&\n    typeof (value as FarmModuleAstNode).start === \"number\" &&\n    typeof (value as FarmModuleAstNode).end === \"number\"\n  );\n}\n\nfunction isFarmConfigFile(file: string, root: string): boolean {\n  const normalized = file.replace(/\\\\/g, \"/\");\n  const rootSlug = root.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n  const relative = normalized.startsWith(`${rootSlug}/`)\n    ? normalized.slice(rootSlug.length + 1)\n    : normalized;\n\n  return FARM_CONFIG_FILENAMES.has(relative);\n}\n\nconst warnedClientBoundaryIds = new Set<string>();\n\n/**\n * Warn once per module about server-only access in client-compiled code:\n * module-scope non-public process.env reads (undefined in the browser, #560)\n * and node: builtin imports (silently stubbed by farm:browser-external-stub).\n * Diagnostics only; behavior is unchanged (#1065).\n */\nfunction warnClientBoundaryOnce(\n  context: { parse(code: string): unknown },\n  id: string,\n  code: string,\n  config: FarmVitePluginOptions,\n): void {\n  if (warnedClientBoundaryIds.has(id)) return;\n\n  let program: unknown;\n  try {\n    program = context.parse(code);\n  } catch {\n    // Unparseable at this stage; another transform will surface the error.\n    return;\n  }\n  const publicKeys = new Set(Object.keys((config as any).env?.public ?? {}));\n  const findings = analyzeClientBoundary(program as any, publicKeys);\n\n  if (\n    findings.envKeys.length === 0 &&\n    findings.publicEnvKeys.length === 0 &&\n    findings.builtinImports.length === 0\n  ) {\n    return;\n  }\n  warnedClientBoundaryIds.add(id);\n  logger.warn(formatClientBoundaryWarning(id, findings));\n}\n\nexport function farmPlugin(\n  options: FarmVitePluginOptions = {},\n  initialPluginManager?: PluginManager,\n): Plugin {\n  const imageImports = farmImageImportsPlugin();\n  const fontImports = farmFontImportsPlugin({\n    root: options.root,\n    basePath: options.basePath,\n    publicDir: options.publicDir,\n  });\n  let farmApp: FarmApp;\n  let server: ViteDevServer;\n  let apiRouteManager: APIRouteManager;\n  let openAPIManager: OpenAPIManager | null = null;\n  let middlewareManager: MiddlewareManager;\n  let refreshRouteDiscovery: ((reason: string) => Promise<void>) | null = null;\n  let workflowHandler: ((request: Request) => Promise<Response | null>) | null = null;\n  const logUpdate = (tag: \"PAGE\" | \"API\" | \"MIDDLEWARE\" | \"TYPE\", message: string) => {\n    const pc = createCliColors();\n    const log = [\n      pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.cyan(tag)) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.yellow(\"UPDATE\")) + pc.dim(\"]\"),\n      pc.gray(message),\n    ].join(\" \");\n    console.log(log);\n  };\n\n  return {\n    name: \"farm\",\n\n    config(_userConfig, configEnv) {\n      const layerAliases = getFarmLayerAliases(options.layers);\n      const layerRoots = (options.layers ?? []).map((layer) => layer.root);\n      return {\n        // Honor Farm's publicDir so the dev server serves the same static\n        // directory the production client build emits.\n        ...(options.publicDir ? { publicDir: options.publicDir } : {}),\n        define: getEnvDefines(options, configEnv),\n        resolve: {\n          alias: layerAliases,\n        },\n        ...(layerRoots.length\n          ? {\n              server: {\n                fs: {\n                  allow: [path.resolve(options.root || process.cwd()), ...layerRoots],\n                },\n              },\n            }\n          : {}),\n      };\n    },\n\n    async configResolved(config) {\n      if (typeof fontImports.configResolved === \"function\") {\n        await fontImports.configResolved.call(this, config);\n      }\n      // Defer Farm application initialization until Vite server is available.\n    },\n\n    async configureServer(viteServer) {\n      if (typeof fontImports.configureServer === \"function\") {\n        await fontImports.configureServer.call(this, viteServer);\n      }\n      server = viteServer;\n\n      // Store the plugin manager passed during creation\n      const pm = initialPluginManager;\n      const emitPluginError = async (\n        phase: string,\n        error: unknown,\n        meta?: Record<string, unknown>,\n      ) => {\n        if (!pm) return;\n        try {\n          await pm.runHookParallel(\"onError\", { phase, error, meta });\n        } catch {\n          // Ignore plugin error reporter failures\n        }\n      };\n\n      farmApp = new FarmApp(\n        {\n          root: server.config.root,\n          ...options,\n        },\n        server,\n      );\n\n      const globalsCSSPath = path.join(server.config.root, \"src/app/globals.css\");\n      if (!fs.existsSync(globalsCSSPath)) {\n        const appDir = path.join(server.config.root, \"src/app\");\n        if (!fs.existsSync(appDir)) {\n          fs.mkdirSync(appDir, { recursive: true });\n        }\n        fs.writeFileSync(globalsCSSPath, defaultGlobalCSS);\n      }\n\n      await farmApp.initialize();\n\n      const farmConfig = farmApp.getConfig();\n      const apiServerBasePath = resolveFarmAPIServerBasePath(farmConfig.api);\n      const serverConfig = resolveFarmServerConfig(farmConfig.server);\n      let imageHandler: FarmImageHandler | null = null;\n      if (farmConfig.images.provider !== \"none\") {\n        const { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } =\n          await import(\"./image-sharp\");\n        imageHandler = createFarmImageHandler(farmConfig.images, {\n          transform: createSharpImageTransformer(),\n          fetchRemote: createNodeImageFetcher(farmConfig.images),\n          validateRemoteUrl: createNodeImageUrlValidator(farmConfig.images),\n          onError(error) {\n            logger.error(\n              `Image optimization failed: ${error instanceof Error ? error.message : String(error)}`,\n            );\n          },\n        });\n      }\n      const sourceRoots = getFarmSourceRoots(farmConfig);\n      server.watcher.add(sourceRoots.map((source) => path.join(source.root, source.srcDir)));\n      if (farmConfig.i18n.enabled) {\n        server.watcher.add(\n          farmConfig.i18n.messages.includes(\"{locale}\")\n            ? path.dirname(farmConfig.i18n.messages)\n            : farmConfig.i18n.messages,\n        );\n      }\n      const workflowConfig = farmConfig.workflows;\n      const farmDocsDevRuntime = farmConfig.docs.enabled ? await loadFarmDocsDevRuntime() : null;\n      const getExtraRouteTypes = () => [\n        ...(options.openapi?.enabled && options.openapi.route ? [options.openapi.route] : []),\n        ...(farmDocsDevRuntime?.getFarmDocsRouteTypeEntries(farmConfig.docs) ?? []),\n      ];\n      const appDirSlugs = sourceRoots.map((source) =>\n        path.join(source.root, source.srcDir, \"app\").replace(/\\\\/g, \"/\"),\n      );\n      const generateTypeArtifacts = async (\n        reason: string,\n        selection: TypeArtifactSelection = ALL_TYPE_ARTIFACTS,\n        log = false,\n      ) => {\n        try {\n          const result = await generateFarmTypeArtifacts({\n            root: farmConfig.root,\n            srcDir: farmConfig.srcDir,\n            layers: farmConfig.layers,\n            plugins: farmConfig.plugins,\n            extraRoutes: getExtraRouteTypes(),\n            suppressLintOnLink: farmConfig.suppressLintOnLink,\n            componentExtensions: farmConfig.renderer.componentExtensions,\n            i18nConfig: farmConfig.i18n,\n            ...selection,\n          });\n          if (log) {\n            const refreshed = [\n              selection.routes !== false && \"route\",\n              selection.api !== false && \"API\",\n              selection.env !== false && \"env\",\n              selection.images !== false && \"image\",\n              selection.i18n !== false && farmConfig.i18n.enabled && \"i18n\",\n            ].filter(Boolean);\n            logUpdate(\n              \"TYPE\",\n              `${reason} - refreshed ${refreshed.join(\", \")} types${\n                selection.api !== false\n                  ? ` (${result.apiRoutes.length} API route${result.apiRoutes.length === 1 ? \"\" : \"s\"})`\n                  : \"\"\n              }`,\n            );\n          }\n          if (openAPIManager) {\n            await openAPIManager.invalidateCache();\n          }\n        } catch (e) {\n          const message = e instanceof Error ? e.message : String(e);\n          logger.warn(`Route type generation failed (farm.d.ts may be stale): ${message}`);\n          if (pm) {\n            await emitPluginError(\"type-artifact-generation\", e, { reason });\n          }\n        }\n      };\n      await generateTypeArtifacts(\"startup\");\n\n      const srcDirSlugs = sourceRoots.map((source) =>\n        path.join(source.root, source.srcDir).replace(/\\\\/g, \"/\"),\n      );\n      const layerConfigFiles = new Set(\n        farmConfig.layers\n          .map((layer) => layer.configFile?.replace(/\\\\/g, \"/\"))\n          .filter((file): file is string => Boolean(file)),\n      );\n      const isPageFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/`)) &&\n          /page\\.(ts|tsx|js|jsx|md|mdx)$/.test(normalized)\n        );\n      };\n      const isApiRouteFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/api/`)) &&\n          /route\\.(ts|tsx|js|jsx)$/.test(normalized)\n        );\n      };\n      const isProgrammaticRouteFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          srcDirSlugs.some((srcDir) => normalized.startsWith(`${srcDir}/`)) &&\n          isProgrammaticRoutesFileName(normalized)\n        );\n      };\n      const isProgrammaticRouteSourceFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return srcDirSlugs.some((srcDir) =>\n          isPotentialProgrammaticRouteSourceFile(normalized, srcDir),\n        );\n      };\n      const isAppRuntimeFile = (file: string) => {\n        const normalized = file.replace(/\\\\/g, \"/\");\n        return (\n          appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/`)) &&\n          /\\/(?:page|default|layout|loading|error|middleware|route)\\.(?:ts|tsx|js|jsx|md|mdx)$|\\/(?:sitemap|robots|manifest)\\.(?:ts|js)$|\\/(?:opengraph-image|twitter-image)(?:\\.(?:ts|tsx|js|jsx|png|jpg|jpeg|gif|webp)|\\.alt\\.txt)$/.test(\n            normalized,\n          )\n        );\n      };\n      const isStaticMetadataImageFile = (file: string) =>\n        /\\/(?:opengraph-image|twitter-image)(?:\\.(?:png|jpg|jpeg|gif|webp)|\\.alt\\.txt)$/.test(\n          file.replace(/\\\\/g, \"/\"),\n        );\n      const isI18nCatalogFile = (file: string) =>\n        farmConfig.i18n.enabled &&\n        file\n          .replace(/\\\\/g, \"/\")\n          .startsWith(farmConfig.i18n.messages.replace(/\\\\/g, \"/\").replace(\"{locale}\", \"\"));\n      let typeArtifactGenScheduled: ReturnType<typeof setTimeout> | null = null;\n      let pendingTypeArtifacts = createEmptyTypeArtifactSelection();\n      let pendingTypeArtifactReason = \"\";\n      let routeRefreshScheduled: ReturnType<typeof setTimeout> | null = null;\n      const scheduleTypeArtifactGen = (\n        file: string,\n        event: string,\n        selection: TypeArtifactSelection,\n      ) => {\n        const normalizedFile = toPosixPath(file);\n        for (const [artifact, enabled] of Object.entries(selection)) {\n          if (enabled) {\n            pendingTypeArtifacts[artifact as keyof TypeArtifactSelection] = true;\n          }\n        }\n        pendingTypeArtifactReason ||= `${event} ${normalizedFile.split(\"/app/\")[1] || normalizedFile}`;\n        if (typeArtifactGenScheduled) return;\n        typeArtifactGenScheduled = setTimeout(() => {\n          typeArtifactGenScheduled = null;\n          const artifacts = pendingTypeArtifacts;\n          const reason = pendingTypeArtifactReason;\n          pendingTypeArtifacts = createEmptyTypeArtifactSelection();\n          pendingTypeArtifactReason = \"\";\n          generateTypeArtifacts(reason, artifacts, true).catch(() => {});\n        }, 100);\n      };\n      [\"add\", \"change\", \"unlink\"].forEach((ev) => {\n        server.watcher.on(ev as \"add\", (file: string) => {\n          const normalizedFile = file.replace(/\\\\/g, \"/\");\n          const configChanged =\n            isFarmConfigFile(file, farmConfig.root) || layerConfigFiles.has(normalizedFile);\n          const programmaticRouteChanged =\n            isProgrammaticRouteFile(file) ||\n            (isProgrammaticRouteSourceFile(file) &&\n              (ev === \"unlink\" || fileContainsProgrammaticPageRoute(file)));\n          const typeArtifacts: TypeArtifactSelection = configChanged\n            ? ALL_TYPE_ARTIFACTS\n            : {\n                routes: (ev !== \"change\" && isPageFile(file)) || programmaticRouteChanged,\n                api: isApiRouteFile(file) || programmaticRouteChanged,\n                env: false,\n                images: false,\n                i18n: isI18nCatalogFile(file),\n              };\n          if (Object.values(typeArtifacts).some(Boolean)) {\n            scheduleTypeArtifactGen(file, ev, typeArtifacts);\n          }\n          if (isI18nCatalogFile(file)) {\n            farmApp\n              ?.getI18nRuntime()\n              .reload()\n              .then(() => server.ws.send({ type: \"full-reload\", path: \"*\" }))\n              .catch((error) => logger.warn(`i18n catalog reload failed: ${error.message}`));\n          }\n          if (\n            (ev !== \"change\" || isStaticMetadataImageFile(file)) &&\n            (isAppRuntimeFile(file) ||\n              isProgrammaticRouteFile(file) ||\n              (isProgrammaticRouteSourceFile(file) &&\n                (ev === \"unlink\" || fileContainsProgrammaticPageRoute(file)))) &&\n            !routeRefreshScheduled\n          ) {\n            routeRefreshScheduled = setTimeout(() => {\n              routeRefreshScheduled = null;\n              Promise.all([\n                refreshRouteDiscovery?.(`${ev} ${file}`),\n                file.includes(\"middleware.\") ? middlewareManager?.reload() : undefined,\n              ])\n                .then(() => server.ws.send({ type: \"full-reload\", path: \"*\" }))\n                .catch((error) => logger.warn(`Route refresh failed: ${error.message}`));\n            }, 50);\n          }\n        });\n      });\n\n      // Initialize API route manager\n      const appDirs = getFarmAppDirectories(farmConfig);\n      const routeManager = farmApp.getRouteManager();\n      const discoveredRoutes: Array<{\n        kind: \"page\" | \"layout\";\n        pattern: string;\n        modulePath: string;\n      }> = [];\n      for (const [pattern, entry] of routeManager.getRoutes()) {\n        discoveredRoutes.push({\n          kind: \"page\",\n          pattern,\n          modulePath: entry.modulePath,\n        });\n      }\n      for (const [pattern, entry] of routeManager.getLayouts()) {\n        discoveredRoutes.push({\n          kind: \"layout\",\n          pattern,\n          modulePath: entry.modulePath,\n        });\n      }\n      if (pm) {\n        for (const route of discoveredRoutes) {\n          await pm.runHookParallel(\"routeDiscovered\", route);\n        }\n        await pm.runHookParallel(\"routesGenerated\", {\n          routes: discoveredRoutes,\n          pageCount: discoveredRoutes.filter((r) => r.kind === \"page\").length,\n          layoutCount: discoveredRoutes.filter((r) => r.kind === \"layout\").length,\n        });\n      }\n\n      apiRouteManager = new APIRouteManager(appDirs, server, {\n        plugins: farmConfig.plugins,\n        i18n: farmApp.getI18nRuntime(),\n        bodySizeLimit: serverConfig.bodySizeLimit,\n        basePath: apiServerBasePath,\n      });\n      await apiRouteManager.discoverRoutes();\n      let discoveredWorkflows: FarmDiscoveredWorkflow[] = [];\n      const hasWorkflowDirectory =\n        workflowConfig.enabled &&\n        workflowConfig.dirs.some((dir) =>\n          fs.existsSync(path.isAbsolute(dir) ? dir : path.join(farmConfig.root, dir)),\n        );\n      if (hasWorkflowDirectory) {\n        const { createFarmWorkflowRequestHandler, discoverFarmWorkflows } =\n          await loadFarmWorkflowsDevRuntime();\n        discoveredWorkflows = await discoverFarmWorkflows(\n          { ...farmConfig, workflows: workflowConfig },\n          {\n            loadModule: async (filePath) =>\n              server.ssrLoadModule(filePath) as Promise<Record<string, any>>,\n          },\n        );\n        if (discoveredWorkflows.length > 0) {\n          workflowHandler = createFarmWorkflowRequestHandler({\n            workflows: discoveredWorkflows,\n            config: workflowConfig,\n            loadModule: async (workflow: FarmDiscoveredWorkflow) =>\n              server.ssrLoadModule(workflow.filePath) as Promise<Record<string, any>>,\n            server: farmConfig.server,\n          });\n          logger.success(`✅ Discovered ${discoveredWorkflows.length} Farm workflow task(s)`);\n        }\n      }\n      if (pm) {\n        for (const [, apiRoute] of apiRouteManager.getRoutes()) {\n          await pm.runHookParallel(\"apiRouteDiscovered\", {\n            path: apiRoute.path,\n            filePath: apiRoute.filePath,\n            methods: apiRoute.methods,\n          });\n        }\n      }\n\n      middlewareManager = new MiddlewareManager(\n        appDirs,\n        server,\n        farmConfig.middleware,\n        farmConfig.i18n,\n        farmConfig.server,\n      );\n      await middlewareManager.discover();\n      if (pm) {\n        for (const middleware of middlewareManager.getMiddlewares()) {\n          await pm.runHookParallel(\"middlewareDiscovered\", {\n            path: middleware.path,\n            filePath: middleware.filePath,\n            handlerCount: middleware.handlers.length,\n          });\n        }\n      }\n\n      // Initialize OpenAPI manager if enabled\n      if (options.openapi?.enabled) {\n        const { OpenAPIManager } = await loadFarmOpenAPIDevRuntime();\n        openAPIManager = new OpenAPIManager(appDirs, options.openapi);\n        const spec = await openAPIManager.generateSpec();\n        reportOpenAPIDevGenerationResult(spec);\n      }\n\n      refreshRouteDiscovery = async (reason: string) => {\n        await routeManager.discoverRoutes();\n        await apiRouteManager.discoverRoutes();\n        const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n        if (manifestModule) {\n          server.moduleGraph.invalidateModule(manifestModule);\n        }\n        if (openAPIManager) {\n          await openAPIManager.invalidateCache();\n        }\n        if (process.env.FARM_VERBOSE) {\n          logger.info(`Refreshed routes: ${reason}`);\n        }\n      };\n\n      const farmDocsFontAssetList = farmDocsDevRuntime\n        ? resolveFarmDocsFontAssets(farmConfig.root)\n        : [];\n      const resolveDocsLayoutFonts = async (pathname: string) => {\n        const layouts = routeManager.matchRoute(pathname).layouts;\n        const layoutModules = await Promise.all(\n          layouts.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n        );\n        return resolveFarmLayoutFonts(layoutModules);\n      };\n      const farmDocsHandler = farmDocsDevRuntime\n        ? farmDocsDevRuntime.hasFarmDocsRuntimeAdapter(farmConfig.docs)\n          ? await farmDocsDevRuntime.createFarmDocsAdapterHandler(farmConfig.docs, {\n              root: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              clientEntry: \"/@farm/client.js\",\n              resolveLayoutFonts: resolveDocsLayoutFonts,\n              fontStylesheetHref: \"/@farm/fonts.css\",\n              globalStylesheetHref: \"/src/app/globals.css\",\n              loadModule: async (specifier) => {\n                const resolved = await server.pluginContainer.resolveId(specifier, undefined, {\n                  ssr: true,\n                });\n                if (specifier === farmConfig.docs.adapter?.server && resolved?.id) {\n                  return import(/* @vite-ignore */ pathToFileURL(resolved.id).href);\n                }\n                return server.ssrLoadModule(resolved?.id ?? specifier);\n              },\n            })\n          : farmDocsDevRuntime.createFarmDocsHandler(farmConfig.docs, {\n              root: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              clientEntry: \"/@farm/client.js\",\n              fontAssets: toFarmDocsPublicFontAssets(farmDocsFontAssetList),\n              resolveLayoutFonts: resolveDocsLayoutFonts,\n              fontStylesheetHref: \"/@farm/fonts.css\",\n              globalStylesheetHref: \"/src/app/globals.css\",\n            })\n        : null;\n      const wrapFarmDocsResponseWithLayouts = async (\n        request: Request,\n        response: Response,\n      ): Promise<Response> => {\n        if (\n          request.method === \"HEAD\" ||\n          response.headers.has(\"x-farm-docs-adapter\") ||\n          !response.headers.get(\"content-type\")?.toLowerCase().includes(\"text/html\")\n        ) {\n          return response;\n        }\n\n        const pathname = new URL(request.url).pathname;\n        const matchedRoute = routeManager.matchRoute(pathname);\n        const layoutEntries = matchedRoute.layouts.map((layout) => ({\n          ...layout,\n          metadata: getClientModuleMetadata(layout.modulePath, farmConfig.root),\n        }));\n        if (!layoutEntries.some((layout) => layout.metadata.shouldHydrate)) {\n          return response;\n        }\n\n        const source = await response.text();\n        const bodyMatch = source.match(/<body([^>]*)>([\\s\\S]*?)<\\/body>/i);\n        if (!bodyMatch) {\n          return new Response(source, {\n            status: response.status,\n            statusText: response.statusText,\n            headers: response.headers,\n          });\n        }\n\n        const [React, ReactDOMServer, layoutModules] = await Promise.all([\n          import(\"react\"),\n          import(\"react-dom/server\"),\n          Promise.all(\n            layoutEntries.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n          ),\n        ]);\n        const hydrationStrategies = layoutEntries.flatMap((layout) =>\n          layout.metadata.shouldHydrate && layout.metadata.islandStrategy\n            ? [layout.metadata.islandStrategy]\n            : [],\n        );\n        const islandStrategy = hydrationStrategies.every(\n          (strategy) => strategy === hydrationStrategies[0],\n        )\n          ? (hydrationStrategies[0] ?? \"load\")\n          : \"load\";\n        const params = matchedRoute.params || {};\n        const toUrlPath = (absolutePath: string) => toViteModuleId(absolutePath, farmConfig.root);\n        const clientLayouts = Object.fromEntries(\n          layoutEntries.map((layout) => [\n            layout.pattern,\n            {\n              modulePath: toUrlPath(layout.modulePath),\n              pattern: layout.pattern,\n              shouldHydrate: layout.metadata.shouldHydrate,\n              islandStrategy: layout.metadata.islandStrategy,\n              preloads: [toUrlPath(layout.modulePath)],\n              assets: [],\n            },\n          ]),\n        );\n        const inlineValue = (value: unknown) =>\n          JSON.stringify(value).replace(/</g, \"\\\\u003c\").replace(/>/g, \"\\\\u003e\");\n        const pageModulePath = matchedRoute.route?.modulePath\n          ? toUrlPath(matchedRoute.route.modulePath)\n          : \"\";\n        const bootstrapScript = `<script>\nwindow.__FARM_PROPS__ = ${inlineValue({ params })};\nwindow.__FARM_ROUTE_SLOTS__ = [];\nwindow.__FARM_DEPLOYMENT_ID__ = ${inlineValue(farmConfig.deploymentId)};\nwindow.__FARM_PATH__ = ${inlineValue(pathname)};\nwindow.__FARM_IS_CLIENT__ = false;\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = false;\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = true;\nwindow.__FARM_SHOULD_HYDRATE__ = true;\nwindow.__FARM_ISLAND_STRATEGY__ = ${inlineValue(islandStrategy)};\nwindow.__FARM_PAGE_MODULE__ = ${inlineValue(pageModulePath)};\nwindow.__FARM_LOADING_MODULE__ = null;\nwindow.__FARM_MANIFEST__ = ${inlineValue({\n          routes: {},\n          layouts: clientLayouts,\n          slots: [],\n          clientEntry: \"/@farm/client.js\",\n          sharedAssets: [],\n        })};\n</script>`;\n\n        let wrappedElement: any = React.createElement(\"div\", {\n          id: \"__farm_page__\",\n          \"data-farm-client\": \"false\",\n          \"data-farm-layout-client\": \"true\",\n          \"data-farm-island\": \"page\",\n          \"data-farm-island-strategy\": islandStrategy,\n          dangerouslySetInnerHTML: { __html: bootstrapScript + bodyMatch[2] },\n        });\n        for (let index = layoutModules.length - 1; index >= 0; index--) {\n          const LayoutComponent = layoutModules[index].default;\n          if (LayoutComponent) {\n            wrappedElement = React.createElement(LayoutComponent, {\n              children: wrappedElement,\n              params,\n            });\n          }\n        }\n\n        const rootMarkup = ReactDOMServer.renderToString(\n          React.createElement(\"div\", { id: \"root\" }, wrappedElement),\n        );\n        const html = source.replace(bodyMatch[0], `<body${bodyMatch[1]}>${rootMarkup}</body>`);\n        const headers = new Headers(response.headers);\n        headers.delete(\"content-length\");\n        headers.delete(\"etag\");\n        return new Response(html, {\n          status: response.status,\n          statusText: response.statusText,\n          headers,\n        });\n      };\n      const farmDocsAPIHandler: FarmDocsAPIHandler | null =\n        farmDocsDevRuntime && !farmDocsDevRuntime.hasFarmDocsRuntimeAdapter(farmConfig.docs)\n          ? farmDocsDevRuntime.createFarmDocsAPIHandler({\n              rootDir: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              docs: farmConfig.docs,\n            })\n          : null;\n      const farmDocsFontAssets = new Map(\n        farmDocsFontAssetList.map(({ url, sourcePath }) => [url, sourcePath]),\n      );\n      const logResponse = (\n        method: string,\n        urlPath: string,\n        status: number,\n        duration: number,\n        tag: \"API\" | \"PAGE\",\n      ) => {\n        // In dev, browsers can trigger bursts of identical requests (reload/prefetch).\n        // Collapse near-identical page logs to keep terminal output readable.\n        const now = Date.now();\n        const dedupeKey = `${tag}:${method}:${urlPath}:${status}`;\n        const dedupeWindowMs = 250;\n        const last = (logResponse as any).__last as { key: string; ts: number } | undefined;\n        if (tag === \"PAGE\" && last && last.key === dedupeKey && now - last.ts < dedupeWindowMs) {\n          return;\n        }\n        (logResponse as any).__last = { key: dedupeKey, ts: now };\n\n        const pc = createCliColors();\n        let statusColor = pc.green;\n        if (status >= 500) statusColor = pc.red;\n        else if (status >= 400) statusColor = pc.yellow;\n        else if (status >= 300) statusColor = pc.cyan;\n\n        const log = [\n          pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n          pc.dim(\"[\") + pc.bold(pc.cyan(tag)) + pc.dim(\"]\"),\n          pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n          pc.gray(urlPath),\n          pc.dim(\"-\"),\n          statusColor(status.toString()),\n          pc.dim(`(${duration}ms)`),\n        ].join(\" \");\n        console.log(log);\n      };\n\n      // Register middleware directly (not in return function) to ensure it runs early\n      const withAPIRequestTracing = (handler: Parameters<typeof withFarmRequestTracing>[0]) =>\n        withFarmRequestTracing(handler, {\n          basePath: apiServerBasePath,\n          dispatch: async (request) => {\n            // Resolve at call time so HMR never leaves a captured endpoint map.\n            const handler = apiRouteManager.getHandler();\n            return handler\n              ? handler(request)\n              : Response.json({ error: \"Not Found\" }, { status: 404 });\n          },\n        });\n      server.middlewares.use(\n        withAPIRequestTracing(async (req, res, next) => {\n          const requestUrl = req.url || \"/\";\n          const requestMethod = req.method || \"GET\";\n          const currentConfig = farmApp?.getConfig() ?? options;\n          const currentServerConfig = resolveFarmServerConfig(currentConfig.server);\n          const parsedRequestUrl = resolveFarmRequestURL(req as FarmRequest, {\n            trustProxy: currentServerConfig.trustProxy,\n          });\n          const fullUrl = parsedRequestUrl.toString();\n          const requestPathname = parsedRequestUrl.pathname;\n\n          if (imageHandler && requestPathname === farmConfig.images.path) {\n            const imageResponse = await imageHandler(\n              createRequestFromNodeRequest(req, new URL(fullUrl)),\n            );\n            if (imageResponse) {\n              await sendWebResponse(res, imageResponse);\n              return;\n            }\n          }\n\n          const farmDocsFontPath = farmDocsFontAssets.get(requestPathname);\n          if (\n            (requestMethod === \"GET\" || requestMethod === \"HEAD\") &&\n            farmDocsFontPath &&\n            fs.existsSync(farmDocsFontPath)\n          ) {\n            res.statusCode = 200;\n            res.setHeader(\"Content-Type\", \"font/woff2\");\n            res.setHeader(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n            if (requestMethod === \"HEAD\") res.end();\n            else fs.createReadStream(farmDocsFontPath).pipe(res);\n            return;\n          }\n\n          if (\n            requestMethod === \"GET\" &&\n            (requestPathname === FARM_DEVTOOLS_PATH ||\n              requestPathname === `${FARM_DEVTOOLS_PATH}.json`)\n          ) {\n            if (!farmConfig.devtools.enabled) {\n              res.statusCode = 404;\n              res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n              res.setHeader(\"Cache-Control\", \"no-store\");\n              res.end(\"Farm DevTools are disabled.\");\n              return;\n            }\n\n            if (\n              requestPathname === FARM_DEVTOOLS_PATH &&\n              parsedRequestUrl.searchParams.get(\"embedded\") !== \"1\"\n            ) {\n              let launchUrl = new URL(farmConfig.basePath || \"/\", parsedRequestUrl.origin);\n              const referrer = req.headers.referer;\n              if (referrer) {\n                try {\n                  const referrerUrl = new URL(referrer);\n                  if (\n                    referrerUrl.origin === parsedRequestUrl.origin &&\n                    !referrerUrl.pathname.startsWith(FARM_DEVTOOLS_PATH)\n                  ) {\n                    launchUrl = referrerUrl;\n                  }\n                } catch {\n                  // Ignore malformed referrers and return to the application root.\n                }\n              }\n              launchUrl.searchParams.set(FARM_DEVTOOLS_LAUNCH_PARAM, \"1\");\n              res.statusCode = 302;\n              res.setHeader(\n                \"Location\",\n                `${launchUrl.pathname}${launchUrl.search}${launchUrl.hash}`,\n              );\n              res.setHeader(\"Cache-Control\", \"no-store\");\n              res.setHeader(\"Vary\", \"Referer\");\n              res.end();\n              return;\n            }\n\n            const { createFarmDevtoolsSnapshot } = await loadFarmDevtoolsSnapshotRuntime();\n            const snapshot = await createFarmDevtoolsSnapshot({\n              root: farmConfig.root,\n              srcDir: farmConfig.srcDir,\n              routeManager: farmApp.getRouteManager(),\n              apiRouteManager,\n              middlewareManager,\n              config: {\n                ...currentConfig,\n                openapi: options.openapi,\n              },\n              workflows: discoveredWorkflows,\n            });\n\n            res.statusCode = 200;\n            res.setHeader(\n              \"Content-Type\",\n              requestPathname.endsWith(\".json\")\n                ? \"application/json; charset=utf-8\"\n                : \"text/html; charset=utf-8\",\n            );\n            res.setHeader(\"Cache-Control\", \"no-store\");\n            if (requestPathname.endsWith(\".json\")) {\n              res.end(JSON.stringify(snapshot, null, 2));\n            } else {\n              if (!warnedDeprecatedDevtoolsDashboard) {\n                warnedDeprecatedDevtoolsDashboard = true;\n                logger.warn(\n                  \"The built-in DevTools dashboard is deprecated. Install @farm.js/devtools and add devtools() to plugins in farm.config.ts.\",\n                );\n              }\n              const { renderFarmDevtoolsHtml } = await loadFarmDevtoolsUIRuntime();\n              res.end(renderFarmDevtoolsHtml(snapshot));\n            }\n            return;\n          }\n\n          // Serve the raw OpenAPI spec as JSON at a predictable URL for agents\n          // and API tooling.\n          if (\n            openAPIManager &&\n            options.openapi?.specRoute &&\n            requestPathname === options.openapi.specRoute\n          ) {\n            if (requestMethod !== \"GET\" && requestMethod !== \"HEAD\") {\n              res.statusCode = 405;\n              res.setHeader(\"Allow\", \"GET, HEAD\");\n              res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n              res.end(\"Method Not Allowed\");\n              return;\n            }\n            const spec = await openAPIManager.getSpec();\n            const body = JSON.stringify(spec);\n            res.statusCode = 200;\n            res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n            res.setHeader(\"Cache-Control\", \"no-store\");\n            res.end(requestMethod === \"HEAD\" ? undefined : body);\n            return;\n          }\n\n          // Handle OpenAPI docs route\n          if (openAPIManager && requestPathname === options.openapi?.route) {\n            const docsHandler = openAPIManager.getDocsRouteHandler();\n            return docsHandler(req, res);\n          }\n\n          const docsHeaders = new Headers();\n          for (const [key, value] of Object.entries(req.headers)) {\n            if (value) {\n              docsHeaders.set(key, Array.isArray(value) ? value.join(\", \") : value);\n            }\n          }\n          // Docs and raw markdown-source responses expose page content, so app\n          // middleware must pass before they are sent — matching the production\n          // entry, where these handlers run after the middleware runner.\n          const runAppMiddlewareForContentRoute = async (): Promise<boolean> => {\n            if (!middlewareManager?.hasMiddleware()) return false;\n            const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));\n            return farmApp\n              .getServerRenderer()\n              .runWithRequestContext(middlewareRequest, () => middlewareManager!.execute(req, res));\n          };\n          if (farmDocsHandler) {\n            const docsRequest = new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            });\n            const docsResponse = await farmDocsHandler(docsRequest.clone());\n            if (docsResponse) {\n              if (await runAppMiddlewareForContentRoute()) return;\n              await sendWebResponse(\n                res,\n                await wrapFarmDocsResponseWithLayouts(docsRequest, docsResponse),\n              );\n              return;\n            }\n          }\n\n          const markdownSourceResponse = await createFarmMarkdownSourceResponse({\n            request: new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            }),\n            config: farmApp.getConfig().mdx,\n            resolveSource: async (pathname) => {\n              const match = farmApp.getRouteManager().matchRoute(pathname);\n              const sourcePath =\n                match.route?.markdownSourcePath ||\n                (match.route && isFarmMarkdownPageFile(match.route.modulePath)\n                  ? match.route.modulePath\n                  : null);\n              if (!sourcePath) {\n                return null;\n              }\n              return {\n                source: await fs.promises.readFile(sourcePath, \"utf8\"),\n                filePath: sourcePath,\n              };\n            },\n          });\n          if (markdownSourceResponse) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            await sendWebResponse(res, markdownSourceResponse);\n            return;\n          }\n\n          const markdownResponse = await createMarkdownMirrorResponse({\n            request: new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            }),\n            config: farmApp.getConfig().md,\n            routeExists: (pathname) =>\n              Boolean(farmApp.getRouteManager().matchRoute(pathname).route),\n            renderPage: async (request) => fetch(request),\n          });\n          if (markdownResponse) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            await sendWebResponse(res, markdownResponse);\n            return;\n          }\n\n          // No Markdown source or mirror matched. When the client explicitly\n          // asked for Markdown (a `.md` URL or `Accept: text/markdown`) and no\n          // page route exists, return a Markdown 404 body rather than letting a\n          // `.md` request fall through to a static-asset 404 or an HTML shell.\n          if (farmRequestWantsMarkdown(requestPathname, req.headers.accept)) {\n            const markdownRoute = farmApp\n              .getRouteManager()\n              .matchRoute(normalizeFarmMarkdownRoutePath(requestPathname));\n            if (!markdownRoute.route) {\n              res.statusCode = 404;\n              res.setHeader(\"Content-Type\", FARM_MARKDOWN_CONTENT_TYPE);\n              res.setHeader(\"X-Farm-Markdown-Error\", \"404\");\n              res.setHeader(\"Cache-Control\", \"no-store\");\n              res.end(\n                createFarmMarkdownErrorBody(404, requestPathname, farmConfig.basePath || \"/\"),\n              );\n              return;\n            }\n          }\n\n          const markdownPageTarget = resolveMarkdownMirrorTarget(\n            farmApp.getConfig().md,\n            requestPathname,\n            {\n              accept: \"text/markdown\",\n            },\n          );\n          if (\n            markdownPageTarget &&\n            farmApp.getRouteManager().matchRoute(markdownPageTarget.pathname).route\n          ) {\n            const vary = res.getHeader(\"Vary\");\n            const varyValues = String(vary || \"\")\n              .split(\",\")\n              .map((value) => value.trim())\n              .filter(Boolean);\n            if (!varyValues.some((value) => value.toLowerCase() === \"accept\")) {\n              res.setHeader(\"Vary\", [...varyValues, \"Accept\"].join(\", \"));\n            }\n            const alternatePath =\n              markdownPageTarget.pathname === \"/\"\n                ? \"/index.md\"\n                : `${markdownPageTarget.pathname}.md`;\n            const alternateLink = `<${alternatePath}>; rel=\"alternate\"; type=\"text/markdown\"`;\n            const currentLink = res.getHeader(\"Link\");\n            res.setHeader(\n              \"Link\",\n              currentLink ? `${String(currentLink)}, ${alternateLink}` : alternateLink,\n            );\n          }\n\n          if (\n            workflowHandler &&\n            (requestPathname === workflowConfig.route ||\n              requestPathname.startsWith(`${workflowConfig.route}/`))\n          ) {\n            let workflowBody: Buffer | undefined;\n            try {\n              if (requestMethod !== \"GET\" && requestMethod !== \"HEAD\") {\n                workflowBody = await readNodeRequestBody(\n                  req as any,\n                  currentServerConfig.bodySizeLimit,\n                );\n              }\n            } catch (error) {\n              const response = createFarmRequestBodyErrorResponse(error);\n              if (!response) throw error;\n              await sendWebResponse(res, response);\n              return;\n            }\n            const workflowResponse = await workflowHandler(\n              new Request(fullUrl, {\n                method: requestMethod,\n                headers: docsHeaders,\n                body: toRequestBody(workflowBody),\n              }),\n            );\n            if (workflowResponse) {\n              await sendWebResponse(res, workflowResponse);\n              return;\n            }\n          }\n\n          const configuredIntegrations = currentConfig.integrations;\n\n          const tryConfiguredIntegrationRoute = async () => {\n            const matchedRoute = matchIntegrationRoute(configuredIntegrations, {\n              pathname: requestPathname,\n              method: requestMethod,\n            });\n\n            if (!matchedRoute) {\n              return false;\n            }\n\n            const startTime = Date.now();\n\n            try {\n              if (pm) {\n                await pm.runHookParallelFiltered(\n                  \"beforeRequest\",\n                  (plugin) => {\n                    const owner = getFarmIntegrationPluginOwner(plugin);\n                    return (\n                      plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME &&\n                      (owner?.source !== \"lifecycle\" || owner.key !== matchedRoute.key)\n                    );\n                  },\n                  req,\n                  res,\n                );\n              }\n\n              if (res.writableEnded) {\n                const duration = Date.now() - startTime;\n                logResponse(requestMethod, requestUrl, res.statusCode || 200, duration, \"API\");\n                return true;\n              }\n\n              const headers = new Headers();\n              for (const [key, value] of Object.entries(req.headers)) {\n                if (value) {\n                  headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                }\n              }\n\n              let body: Buffer | undefined;\n              if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n              }\n\n              const integrationRequest = new Request(fullUrl, {\n                method: req.method,\n                headers,\n                body: toRequestBody(body),\n              });\n\n              const dispatchIntegration = async (request: Request) => {\n                const result = await dispatchIntegrationRequest(\n                  {\n                    integration: matchedRoute.integration,\n                    config: currentConfig,\n                    isDev: true,\n                    isProd: false,\n                  },\n                  request,\n                );\n                if (!result) {\n                  throw new Error(`Matched integration route did not return a response`);\n                }\n                return result;\n              };\n              const response = pm\n                ? await pm.runRuntimeRequest(integrationRequest, dispatchIntegration, {\n                    kind: \"integration\",\n                    route: {\n                      pathname: requestPathname,\n                      pattern: matchedRoute.route.path,\n                    },\n                  })\n                : await dispatchIntegration(integrationRequest);\n\n              if (!response) {\n                return false;\n              }\n\n              const duration = Date.now() - startTime;\n              logResponse(requestMethod, requestUrl, response.status, duration, \"API\");\n\n              await sendWebResponse(res, response);\n              return true;\n            } catch (error) {\n              const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n              if (bodyErrorResponse) {\n                await sendWebResponse(res, bodyErrorResponse);\n                return true;\n              }\n              const duration = Date.now() - startTime;\n              logResponse(requestMethod, requestUrl, 500, duration, \"API\");\n              await emitPluginError(\"integration-handler\", error, {\n                pathname: requestPathname,\n                routePath: requestUrl,\n                method: requestMethod,\n                integration: matchedRoute.key,\n              });\n              logger.error(`Integration route error: ${error}`);\n              if (!res.writableEnded) {\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n              }\n              return true;\n            }\n          };\n\n          if (await tryConfiguredIntegrationRoute()) {\n            return;\n          }\n\n          const redirectMatch = farmApp\n            .getRouteManager()\n            .matchRedirect(requestPathname, parsedRequestUrl.search);\n          if (redirectMatch) {\n            res.statusCode = redirectMatch.statusCode;\n            res.setHeader(\"Location\", redirectMatch.destination);\n            res.end(`Redirecting to ${redirectMatch.destination}`);\n            return;\n          }\n\n          // Handle API routes first\n          const matchedApiRoute = apiRouteManager.matchRoute(requestPathname);\n          const hasMatchedApiRoute = Boolean(matchedApiRoute);\n          if (hasMatchedApiRoute || isFarmAPIPathname(requestPathname, apiServerBasePath)) {\n            const startTime = Date.now();\n            const method = req.method || \"GET\";\n            const urlPath = req.url || \"/\";\n            const pathname = new URL(urlPath, `http://${req.headers.host || \"localhost:3000\"}`)\n              .pathname;\n\n            try {\n              if (pm) {\n                if (hasMatchedApiRoute) {\n                  await pm.runHookParallelFiltered(\n                    \"beforeRequest\",\n                    (plugin) => plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,\n                    req,\n                    res,\n                  );\n                } else {\n                  await pm.runHookParallel(\"beforeRequest\", req, res);\n                }\n              }\n\n              if (res.writableEnded) {\n                const duration = Date.now() - startTime;\n                logResponse(method, urlPath, res.statusCode || 200, duration, \"API\");\n                return;\n              }\n            } catch (error) {\n              await emitPluginError(\"before-request\", error, {\n                urlPath,\n                method,\n              });\n              logger.error(`Request hook error: ${error}`);\n              res.statusCode = 500;\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify({ error: \"Internal server error\" }));\n              return;\n            }\n\n            // Let this request boundary observe endpoint failures before it\n            // converts them into the development 500 response below.\n            const apiHandler = apiRouteManager.getHandler({ throwOnError: true });\n            const hasExplicitAPIRoute =\n              hasMatchedApiRoute || Boolean(apiRouteManager.matchRoute(pathname));\n            if (apiHandler && hasExplicitAPIRoute) {\n              const apiRoutePattern =\n                matchedApiRoute?.route.path ||\n                apiRouteManager.matchRoute(pathname)?.route.path ||\n                urlPath;\n              emitFarmEvent({\n                type: \"route.matched\",\n                pathname,\n                route: apiRoutePattern,\n              });\n              emitFarmEvent({\n                type: \"api.request.start\",\n                pathname,\n                route: apiRoutePattern,\n                method,\n              });\n              try {\n                // Convert Node.js request to Web Request\n                const url = `http://${req.headers.host || \"localhost:3000\"}${req.url}`;\n                const headers = new Headers();\n                for (const [key, value] of Object.entries(req.headers)) {\n                  if (value) {\n                    headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                  }\n                }\n\n                // Get body for POST/PUT/PATCH\n                let body: Buffer | undefined;\n                if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                  body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n                }\n\n                const request = new Request(url, {\n                  method: req.method,\n                  headers,\n                  body: toRequestBody(body),\n                });\n\n                const apiLifecyclePayload = {\n                  pathname: new URL(url).pathname,\n                  method,\n                  routePath: apiRoutePattern,\n                };\n                const invokeAPIHandler = async (runtimeRequest: Request) => {\n                  const handledRequest: Request = pm\n                    ? await pm.runHookSerial(\n                        \"beforeApiHandler\",\n                        runtimeRequest,\n                        apiLifecyclePayload,\n                      )\n                    : runtimeRequest;\n\n                  const response = await apiHandler(handledRequest);\n                  return pm\n                    ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n                    : response;\n                };\n                const handledResponse: Response = pm\n                  ? await pm.runRuntimeRequest(request, invokeAPIHandler, {\n                      kind: \"api\",\n                      route: {\n                        pathname: apiLifecyclePayload.pathname,\n                        pattern: apiLifecyclePayload.routePath,\n                      },\n                    })\n                  : await invokeAPIHandler(request);\n\n                const duration = Date.now() - startTime;\n                emitFarmEvent({\n                  type: \"api.request.complete\",\n                  pathname,\n                  route: apiRoutePattern,\n                  method,\n                  status: handledResponse.status,\n                  durationMs: duration,\n                });\n                logResponse(method, urlPath, handledResponse.status, duration, \"API\");\n\n                // Send response\n                await sendWebResponse(res, handledResponse);\n                return;\n              } catch (error) {\n                const duration = Date.now() - startTime;\n                emitFarmEvent({\n                  type: \"api.error\",\n                  pathname,\n                  route: apiRoutePattern,\n                  method,\n                  durationMs: duration,\n                  error,\n                });\n                const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n                if (bodyErrorResponse) {\n                  logResponse(method, urlPath, bodyErrorResponse.status, duration, \"API\");\n                  await sendWebResponse(res, bodyErrorResponse);\n                  return;\n                }\n                await emitPluginError(\"api-handler\", error, {\n                  urlPath,\n                  method,\n                });\n                logger.error(`API route error: ${error}`);\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n                return;\n              }\n            }\n\n            if (farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname)) {\n              try {\n                const url = `http://${req.headers.host || \"localhost:3000\"}${req.url}`;\n                const headers = new Headers();\n                for (const [key, value] of Object.entries(req.headers)) {\n                  if (value) {\n                    headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                  }\n                }\n\n                let body: Buffer | undefined;\n                if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                  body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n                }\n\n                const request = new Request(url, {\n                  method: req.method,\n                  headers,\n                  body: toRequestBody(body),\n                });\n\n                const apiLifecyclePayload = {\n                  pathname,\n                  method,\n                  routePath: urlPath,\n                };\n                const invokeDocsAPIHandler = async (runtimeRequest: Request) => {\n                  const handledRequest: Request = pm\n                    ? await pm.runHookSerial(\n                        \"beforeApiHandler\",\n                        runtimeRequest,\n                        apiLifecyclePayload,\n                      )\n                    : runtimeRequest;\n                  const response = await farmDocsAPIHandler(handledRequest);\n                  if (!response) {\n                    return new Response(null, { status: 404 });\n                  }\n                  return pm\n                    ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n                    : response;\n                };\n                const docsResponse = pm\n                  ? await pm.runRuntimeRequest(request, invokeDocsAPIHandler, {\n                      kind: \"docs\",\n                      route: {\n                        pathname,\n                        pattern: apiLifecyclePayload.routePath,\n                      },\n                    })\n                  : await invokeDocsAPIHandler(request);\n                if (docsResponse) {\n                  const duration = Date.now() - startTime;\n                  logResponse(method, urlPath, docsResponse.status, duration, \"API\");\n                  await sendWebResponse(res, docsResponse);\n                  return;\n                }\n              } catch (error) {\n                const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n                if (bodyErrorResponse) {\n                  await sendWebResponse(res, bodyErrorResponse);\n                  return;\n                }\n                await emitPluginError(\"docs-api-handler\", error, {\n                  urlPath,\n                  method,\n                });\n                logger.error(`Docs API route error: ${error}`);\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n                return;\n              }\n            }\n\n            const duration = Date.now() - startTime;\n            logResponse(method, urlPath, 404, duration, \"API\");\n            res.statusCode = 404;\n            res.setHeader(\"Content-Type\", \"application/json\");\n            res.end(JSON.stringify({ error: \"API route not found\", pathname }));\n            return;\n          }\n\n          // Skip internal Vite requests\n          if (req.url?.startsWith(\"/@\") || req.url?.startsWith(\"/node_modules\")) {\n            return next();\n          }\n\n          // Dotted paths are usually static assets (modules, images, source\n          // maps), but dots are also valid inside route segments and in\n          // application metadata routes (/manifest.webmanifest, /sitemap.xml,\n          // /robots.txt, metadata images). Only skip the router when the\n          // request maps to a real file on disk or nothing in the app matches\n          // the pathname.\n          if (\n            shouldBypassFarmRouterForDottedPath(requestPathname, farmApp?.getRouteManager(), [\n              server.config.publicDir,\n              server.config.root,\n            ])\n          ) {\n            return next();\n          }\n\n          // Handle SPA page-data requests for client-side navigation\n          if (req.url?.startsWith(\"/__farm/page-data\")) {\n            const urlObj = parsedRequestUrl;\n            const targetPath = urlObj.searchParams.get(\"path\") || \"/\";\n\n            try {\n              const request = createRequestFromNodeRequest(\n                req,\n                urlObj,\n                createFarmNodeRequestAbortSignal(req, res),\n              );\n              const deploymentMismatch = getFarmDeploymentMismatch(\n                request,\n                farmConfig.deploymentId,\n              );\n              if (deploymentMismatch) {\n                await sendWebResponse(\n                  res,\n                  createFarmDeploymentMismatchResponse(deploymentMismatch),\n                );\n                return;\n              }\n\n              const targetRequestUrl = new URL(targetPath, request.url);\n              const targetRequest = new Request(targetRequestUrl, {\n                method: \"GET\",\n                headers: request.headers,\n                signal: request.signal,\n              });\n              await farmApp.getServerRenderer().runWithRequestContext(targetRequest, async () => {\n                const routeManager = farmApp.getRouteManager();\n                if (pm) {\n                  await pm.runHookParallel(\"beforeRouteMatch\", {\n                    pathname: targetPath,\n                    method: req.method || \"GET\",\n                  });\n                }\n                const interceptFromHeader =\n                  request.headers.get(\"x-farm-intercept-from\") || undefined;\n                const match = routeManager.matchRoute(targetRequestUrl.pathname, {\n                  interceptFrom: interceptFromHeader,\n                });\n                if (pm) {\n                  await pm.runHookParallel(\"afterRouteMatch\", {\n                    pathname: targetPath,\n                    matched: !!match?.route,\n                    routePattern: match?.route?.pattern || null,\n                    params: match?.params || {},\n                    layoutPatterns: (match?.layouts || []).map((l) => l.pattern),\n                  });\n                }\n\n                if (!match) {\n                  res.statusCode = 404;\n                  res.setHeader(\"Content-Type\", \"application/json\");\n                  res.end(JSON.stringify({ error: \"Route not found\" }));\n                  return;\n                }\n\n                const { route, params, layouts, slots } = match;\n\n                // Check if route was found\n                if (!route) {\n                  res.statusCode = 404;\n                  res.setHeader(\"Content-Type\", \"application/json\");\n                  res.end(JSON.stringify({ error: \"Route not found\" }));\n                  return;\n                }\n\n                // Load route module to get metadata\n                const routeModule = await routeManager.loadRouteModule(route.modulePath);\n                const loadingBoundary = routeManager.getMatchingLoading(targetRequestUrl.pathname);\n                const loadingModule = loadingBoundary\n                  ? await routeManager.loadRouteModule(loadingBoundary.modulePath)\n                  : null;\n\n                const navigationManifest = routeManager.generateClientManifest(server.config.root);\n                const moduleMetadata =\n                  navigationManifest.routes.find((entry) => entry.pattern === route.pattern) ??\n                  getClientModuleMetadata(route.modulePath, server.config.root);\n                const isClientComponent = moduleMetadata.isClientComponent;\n                const shouldHydrate = moduleMetadata.shouldHydrate;\n\n                // Collect metadata from layouts and page\n                let mergedMetadata: Record<string, any> = {};\n                const layoutModules = await Promise.all(\n                  layouts.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n                );\n                const layoutHydrationMetadata = layouts.map(\n                  (layout) =>\n                    navigationManifest.layouts.find((entry) => entry.pattern === layout.pattern) ??\n                    getClientModuleMetadata(layout.modulePath, server.config.root),\n                );\n                const shouldHydrateLayout = layoutHydrationMetadata.some(\n                  (metadata) => metadata.shouldHydrate,\n                );\n                const hydrationStrategies = [\n                  ...(shouldHydrate && moduleMetadata.islandStrategy\n                    ? [moduleMetadata.islandStrategy]\n                    : []),\n                  ...layoutHydrationMetadata.flatMap((metadata) =>\n                    metadata.shouldHydrate && metadata.islandStrategy\n                      ? [metadata.islandStrategy]\n                      : [],\n                  ),\n                ];\n                const hydrationIslandStrategy = hydrationStrategies.every(\n                  (strategy) => strategy === hydrationStrategies[0],\n                )\n                  ? (hydrationStrategies[0] ?? \"load\")\n                  : \"load\";\n\n                for (const layoutModule of layoutModules) {\n                  if ((layoutModule as any).metadata) {\n                    mergedMetadata = {\n                      ...mergedMetadata,\n                      ...(layoutModule as any).metadata,\n                    };\n                  }\n                }\n\n                if ((routeModule as any).metadata) {\n                  mergedMetadata = {\n                    ...mergedMetadata,\n                    ...(routeModule as any).metadata,\n                  };\n                }\n\n                // Build search params\n                const targetUrl = new URL(targetPath, \"http://localhost\");\n                const searchParams = searchParamsToObject(targetUrl.searchParams);\n                const routeContext = await resolveFarmRouteContext(farmApp.getConfig(), {\n                  request: targetRequest,\n                  params,\n                  search: searchParams,\n                  path: targetUrl.pathname,\n                });\n                const routeProps = await parseRouteModuleProps(routeModule as RouteModuleLike, {\n                  props: withFarmRouteContext(\n                    {\n                      params,\n                      searchParams: Promise.resolve(searchParams),\n                      path: targetUrl.pathname,\n                    },\n                    routeContext,\n                  ),\n                  search: searchParams,\n                  routePath: route.pattern,\n                });\n                const routeSlots = await Promise.all(\n                  slots.map(async (slot) => {\n                    const slotModule = await routeManager.loadRouteModule(slot.route.modulePath);\n                    const slotMetadata =\n                      navigationManifest.slots.find(\n                        (entry) =>\n                          entry.name === slot.name &&\n                          entry.ownerPattern === slot.ownerPattern &&\n                          entry.pattern === slot.route.pattern,\n                      ) ?? getClientModuleMetadata(slot.route.modulePath, server.config.root);\n                    const slotContext = await resolveFarmRouteContext(farmApp.getConfig(), {\n                      request: targetRequest,\n                      params: slot.params,\n                      search: searchParams,\n                      path: targetUrl.pathname,\n                    });\n                    const slotProps = await parseRouteModuleProps(slotModule as RouteModuleLike, {\n                      props: withFarmRouteContext(\n                        {\n                          params: slot.params,\n                          searchParams: Promise.resolve(searchParams),\n                          path: targetUrl.pathname,\n                        },\n                        slotContext,\n                      ),\n                      search: searchParams,\n                      routePath: slot.route.pattern,\n                    });\n\n                    return {\n                      name: slot.name,\n                      ownerPattern: slot.ownerPattern,\n                      containerId: slot.containerId,\n                      interception: slot.interception,\n                      fallback: slot.fallback,\n                      modulePath: slot.route.modulePath,\n                      renderModule: slotModule,\n                      isClientComponent: slotMetadata.isClientComponent,\n                      shouldHydrate: slotMetadata.shouldHydrate,\n                      props: {\n                        params: slotProps.params,\n                        search: (slotProps as any).search,\n                        searchParams: (slotProps as any).search,\n                        ...(\"data\" in slotProps ? { data: (slotProps as any).data } : {}),\n                        ...((slotProps as any).__farmCanonicalPath\n                          ? {\n                              __farmCanonicalPath: (slotProps as any).__farmCanonicalPath,\n                            }\n                          : {}),\n                        ...((slotProps as any).__farmRoutePropsResolved\n                          ? { __farmRoutePropsResolved: true }\n                          : {}),\n                        path: targetUrl.pathname,\n                      },\n                    };\n                  }),\n                );\n\n                // Convert absolute paths to URL paths (relative to project root)\n                const projectRoot = server.config.root;\n                const toUrlPath = (absolutePath: string) =>\n                  toViteModuleId(absolutePath, projectRoot);\n\n                const renderPlan = createFarmRouteRenderPlan({\n                  pageShouldHydrate: shouldHydrate,\n                  layoutShouldHydrate: shouldHydrateLayout,\n                  islandStrategy: hydrationIslandStrategy,\n                  rendering: resolveRouteRenderingConfig(routeModule as any),\n                });\n                const destinationLayoutPatterns = layouts.map((layout) => layout.pattern);\n                const layoutStartIndex = getSharedLayoutPrefixLength(\n                  parseFarmLayoutChainHeader(request.headers.get(\"x-farm-layout-chain\")),\n                  destinationLayoutPatterns,\n                );\n                const fragmentHtml = await farmApp.getServerRenderer().renderNavigationFragment({\n                  PageComponent: (routeModule as any).default,\n                  LoadingComponent: (loadingModule as any)?.default,\n                  pageProps: routeProps as Record<string, unknown>,\n                  params,\n                  layouts: layouts.map((layout, index) => ({\n                    pattern: layout.pattern,\n                    module: layoutModules[index] as any,\n                  })),\n                  layoutStartIndex,\n                  slots: routeSlots.map((slot) => ({\n                    name: slot.name,\n                    ownerPattern: slot.ownerPattern,\n                    containerId: slot.containerId,\n                    module: slot.renderModule as any,\n                    props: slot.props,\n                  })),\n                  pageShouldHydrate: shouldHydrate,\n                  layoutShouldHydrate: shouldHydrateLayout,\n                  islandStrategy: hydrationIslandStrategy,\n                });\n\n                // Return page data for SPA navigation\n                const pageData = {\n                  props: {\n                    params: routeProps.params,\n                    search: (routeProps as any).search,\n                    searchParams: (routeProps as any).search,\n                    ...(\"data\" in routeProps ? { data: (routeProps as any).data } : {}),\n                    ...((routeProps as any).__farmCanonicalPath\n                      ? {\n                          __farmCanonicalPath: (routeProps as any).__farmCanonicalPath,\n                        }\n                      : {}),\n                    ...((routeProps as any).__farmRoutePropsResolved\n                      ? { __farmRoutePropsResolved: true }\n                      : {}),\n                  },\n                  canonicalPath: (routeProps as any).__farmCanonicalPath,\n                  modulePath: toUrlPath(route.modulePath),\n                  loadingModulePath: loadingBoundary ? toUrlPath(loadingBoundary.modulePath) : null,\n                  isClientComponent: routeSlots.length > 0 ? false : isClientComponent,\n                  pageShouldHydrate: shouldHydrate,\n                  layoutShouldHydrate: shouldHydrateLayout,\n                  shouldHydrate:\n                    shouldHydrate ||\n                    shouldHydrateLayout ||\n                    routeSlots.some((slot) => slot.isClientComponent || slot.shouldHydrate),\n                  islandStrategy: hydrationIslandStrategy,\n                  renderPlan,\n                  fragment: {\n                    html: fragmentHtml,\n                    layoutPatterns: destinationLayoutPatterns,\n                  },\n                  metadata: {\n                    title: mergedMetadata.title,\n                    description: mergedMetadata.description,\n                  },\n                  layoutModules: layouts.map((l) => toUrlPath(l.modulePath)),\n                  routeSlots: routeSlots.map(({ renderModule: _renderModule, ...slot }) => ({\n                    ...slot,\n                    modulePath: toUrlPath(slot.modulePath),\n                  })),\n                  interception: routeSlots.some((slot) => slot.interception)\n                    ? {\n                        from: interceptFromHeader,\n                        slots: routeSlots\n                          .filter((slot) => slot.interception)\n                          .map((slot) => slot.name),\n                      }\n                    : undefined,\n                  i18n: getFarmI18nClientSnapshot(),\n                };\n\n                await sendWebResponse(\n                  res,\n                  createDeferredDataResponse(\n                    pageData,\n                    {\n                      status: 200,\n                      headers: {\n                        \"Cache-Control\": getFarmFragmentCacheControl(renderPlan),\n                        \"X-Farm-Navigation\": \"html-fragment\",\n                        Vary: \"X-Farm-Layout-Chain\",\n                        [FARM_DEPLOYMENT_ID_HEADER]: farmConfig.deploymentId,\n                      },\n                    },\n                    {\n                      onError(error, id) {\n                        logger.error(`Deferred route data ${id} failed: ${error}`);\n                      },\n                    },\n                  ),\n                );\n                return;\n              });\n              return;\n            } catch (error) {\n              const failure = resolveFarmPageDataFailure(error);\n              if (failure.status >= 500) {\n                await emitPluginError(\"page-data\", error, {\n                  path: targetPath,\n                });\n                console.error(\"[Farm.js] Page data error:\", error);\n              }\n              res.statusCode = failure.status;\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify(failure.payload));\n              return;\n            }\n          }\n\n          const startTime = Date.now();\n          const method = req.method || \"GET\";\n          const urlPath = req.url || \"/\";\n          const pathname = new URL(urlPath, `http://${req.headers.host || \"localhost:3000\"}`)\n            .pathname;\n          const routeManager = farmApp.getRouteManager();\n          const hasBeforeRouteMatchHook = pm?.hasHook(\"beforeRouteMatch\") ?? false;\n          const hasAfterRouteMatchHook = pm?.hasHook(\"afterRouteMatch\") ?? false;\n          const hasBeforeRequestHook = pm?.hasHook(\"beforeRequest\") ?? false;\n          const hasBeforeRenderHook = pm?.hasHook(\"beforeRender\") ?? false;\n          const hasAfterResponseHook = pm?.hasHook(\"afterResponse\") ?? false;\n          const hasHTMLTransformHook =\n            (pm?.hasHook(\"transformHTML\") ?? false) || (pm?.hasHook(\"afterRender\") ?? false);\n          const hasRuntimeRequestHooks = pm?.hasRuntimeRequestHooks() ?? false;\n          const hasRuntimeAfterHook = pm?.hasRuntimeHook(\"after\") ?? false;\n\n          if (pm && hasBeforeRouteMatchHook) {\n            await pm.runHookParallel(\"beforeRouteMatch\", {\n              pathname,\n              method,\n            });\n          }\n          const routeMatch = routeManager.matchRoute(pathname);\n          if (pm && hasAfterRouteMatchHook) {\n            await pm.runHookParallel(\"afterRouteMatch\", {\n              pathname,\n              matched: !!routeMatch?.route,\n              routePattern: routeMatch?.route?.pattern || null,\n              params: routeMatch?.params || {},\n              layoutPatterns: (routeMatch?.layouts || []).map((l) => l.pattern),\n            });\n          }\n          const renderPayload = {\n            pathname,\n            method,\n            routePattern: routeMatch?.route?.pattern || null,\n            params: routeMatch?.params || {},\n          };\n          let runtimeSession: FarmPluginRuntimeSession | undefined;\n          if (pm && hasRuntimeRequestHooks) {\n            try {\n              runtimeSession = await pm.beginRuntimeRequest(\n                createRequestFromNodeRequest(req, new URL(fullUrl)),\n                {\n                  kind: \"page\",\n                  route: {\n                    pathname,\n                    pattern: renderPayload.routePattern,\n                    params: renderPayload.params,\n                  },\n                },\n              );\n              pm.copyRequestContext(runtimeSession.request, req);\n              applyWebRequestToNodeRequest(runtimeSession.request, req);\n\n              if (runtimeSession.response) {\n                const response = await pm.endRuntimeRequest(\n                  runtimeSession,\n                  runtimeSession.response,\n                );\n                await sendWebResponse(res, response);\n                return;\n              }\n            } catch (error) {\n              await emitPluginError(\"runtime-before\", error, { pathname });\n              res.statusCode = 500;\n              res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n              res.end(\"Internal Server Error\");\n              return;\n            }\n          }\n\n          // Runtime response transforms need the complete byte stream, including\n          // responses completed by middleware or beforeRequest hooks.\n          const shouldInterceptResponse = Boolean(\n            pm &&\n            (hasAfterResponseHook ||\n              hasHTMLTransformHook ||\n              (runtimeSession && hasRuntimeAfterHook)),\n          );\n          const responseInterceptor =\n            pm && shouldInterceptResponse\n              ? interceptFarmDevPageResponse({\n                  req,\n                  res,\n                  pm,\n                  runtimeSession,\n                  hasRuntimeAfterHook,\n                  hasAfterResponseHook,\n                  hasHTMLTransformHook,\n                  renderPayload,\n                  method,\n                  urlPath,\n                  pathname,\n                  startTime,\n                  logResponse,\n                  emitError: (error) => emitPluginError(\"response-end\", error, { pathname }),\n                })\n              : undefined;\n\n          try {\n            if (middlewareManager?.hasMiddleware()) {\n              const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));\n              const handled = await farmApp\n                .getServerRenderer()\n                .runWithRequestContext(middlewareRequest, () =>\n                  middlewareManager!.execute(req, res),\n                );\n              if (handled) {\n                if (!responseInterceptor?.isEnded()) {\n                  const duration = Date.now() - startTime;\n                  logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n                }\n                return; // Middleware handled the response\n              }\n            }\n\n            // Run beforeRequest hooks\n            if (pm && hasBeforeRequestHook) {\n              const currentPathname = new URL(\n                req.url || \"/\",\n                `http://${req.headers.host || \"localhost:3000\"}`,\n              ).pathname;\n              const hasLocalPageRoute = Boolean(routeManager.matchRoute(currentPathname)?.route);\n              await pm.runHookParallelFiltered(\n                \"beforeRequest\",\n                (plugin) => !hasLocalPageRoute || plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,\n                req,\n                res,\n              );\n            }\n\n            if (res.writableEnded || responseInterceptor?.isEnded()) {\n              if (!responseInterceptor?.isEnded()) {\n                const duration = Date.now() - startTime;\n                logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n              }\n              return;\n            }\n\n            // Note: __FARM_PROPS__ is set by the renderer with actual page props (params, searchParams)\n\n            const renderer = farmApp.getServerRenderer();\n            if (pm && hasBeforeRenderHook) {\n              await pm.runHookParallel(\"beforeRender\", renderPayload);\n            }\n            await renderer.renderPage(req as any, res as any);\n            if (!shouldInterceptResponse) {\n              logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, \"PAGE\");\n            }\n          } catch (error) {\n            // Log error response\n            const duration = Date.now() - startTime;\n            logResponse(method, urlPath, 500, duration, \"PAGE\");\n            if (pm && runtimeSession) {\n              await pm.failRuntimeRequest(runtimeSession, error);\n            }\n            await emitPluginError(\"render-page\", error, { pathname });\n            next(error);\n          }\n        }),\n      );\n    },\n\n    async resolveId(id, importer, resolveOptions) {\n      if (typeof fontImports.resolveId === \"function\") {\n        const fontId = await fontImports.resolveId.call(this, id, importer, resolveOptions);\n        if (fontId) return fontId;\n      }\n\n      if (typeof imageImports.resolveId === \"function\") {\n        const imageId = await imageImports.resolveId.call(this, id, importer, resolveOptions);\n        if (imageId) return imageId;\n      }\n\n      if (parseProgrammaticRouteModuleId(id)) {\n        return id;\n      }\n\n      if (isFarmClientVirtualId(id)) {\n        return id;\n      }\n\n      if (id === \"/@farm/server\") {\n        return id;\n      }\n\n      // Virtual manifest module - TanStack Start pattern\n      if (id === \"virtual:farm-manifest\" || id === \"/@farm/manifest\") {\n        return \"/@farm/manifest\";\n      }\n    },\n\n    async load(id) {\n      if (typeof fontImports.load === \"function\") {\n        const fontModule = await fontImports.load.call(this, id);\n        if (fontModule) return fontModule;\n      }\n\n      if (typeof imageImports.load === \"function\") {\n        const imageModule = await imageImports.load.call(this, id);\n        if (imageModule) return imageModule;\n      }\n\n      if (parseProgrammaticRouteModuleId(id)) {\n        const renderer = farmApp?.getConfig().renderer || resolveFarmRenderer(options.renderer);\n        return generateProgrammaticRouteModule(id, server?.config.root || options.root, renderer);\n      }\n\n      if (isFarmClientVirtualId(id)) {\n        const resolvedConfig = farmApp?.getConfig();\n        const renderer = resolvedConfig?.renderer || resolveFarmRenderer(options.renderer);\n        const integrations = resolvedConfig?.integrations || options.integrations;\n        const root = resolvedConfig?.root || server?.config.root || process.cwd();\n        const docs = resolvedConfig?.docs;\n        const adapterOwnsDocsRuntime = Boolean(\n          isReactRenderer(renderer) && docs?.adapter?.server && docs.adapter.react,\n        );\n        const devtools = resolvedConfig?.devtools ?? resolveFarmDevtoolsConfig(false, \"production\");\n        const [docsRuntime, docsSearchRuntime, devtoolsClientRuntime] = await Promise.all([\n          docs?.enabled ? loadFarmDocsDevRuntime() : null,\n          docs?.enabled && !adapterOwnsDocsRuntime ? loadFarmDocsSearchDevRuntime() : null,\n          devtools.enabled ? loadFarmDevtoolsClientRuntime() : null,\n        ]);\n        const docsSearchEnabled = docsSearchRuntime?.isFarmDocsSearchEnabled(docs) ?? false;\n        const generatedDocsSearchRuntime = docsSearchRuntime\n          ? docsSearchRuntime.generateFarmDocsSearchClientRuntime(\n              docsSearchEnabled,\n              docsSearchEnabled\n                ? docsSearchRuntime.resolveFarmDocsSearchClientModule(root)\n                : undefined,\n            )\n          : EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME;\n        const generatedDevtoolsClientRuntime = devtoolsClientRuntime\n          ? devtoolsClientRuntime.generateFarmDevtoolsClientRuntime(devtools)\n          : \"\";\n        const generatedDevIndicatorsClientRuntime = farmApp\n          ? generateFarmDevIndicatorsClientRuntime(farmApp.getConfig().devIndicators)\n          : \"\";\n        const integrationProviders = isReactRenderer(renderer)\n          ? getIntegrationProviders(integrations)\n          : [];\n        const isolatedHydrationMode = resolveFarmIsolatedClientHydrationMode(\n          resolvedConfig?.experimental?.isolatedClientHydration,\n          {\n            serverComponents: resolvedConfig?.experimental?.serverComponents === true,\n            hasUnsupportedIntegrationProvider: integrationProviders\n              .filter((provider) => provider.component || provider.type === \"clerk\")\n              .some((provider) => provider.supportsIsolatedHydration !== true),\n          },\n        );\n\n        return generateClientCode(\n          integrationProviders,\n          [\n            ...getIntegrationDocumentNavigationMatchers(integrations),\n            ...(docsRuntime?.getFarmDocsDocumentNavigationMatchers(docs) ?? []),\n          ],\n          generatedDocsSearchRuntime,\n          `${generatedDevtoolsClientRuntime}\\n${generatedDevIndicatorsClientRuntime}`,\n          resolvedConfig?.plugins || [],\n          root,\n          resolvedConfig?.srcDir || options.srcDir || \"src\",\n          resolvedConfig?.publicRuntimeConfig || options.publicRuntimeConfig,\n          isReactRenderer(renderer) ? docs?.adapter?.react : undefined,\n          renderer,\n          isolatedHydrationMode === \"enabled\",\n          resolvedConfig?.trailingSlash ?? false,\n          resolvedConfig?.basePath ?? \"/\",\n          generateClientCachePersistenceCode(\n            resolveFarmClientCacheAdapterEntry(root, resolvedConfig?.cache),\n          ),\n        );\n      }\n\n      if (id === \"/@farm/server\") {\n        return generateServerCode();\n      }\n\n      // Virtual manifest module - TanStack Start pattern\n      // Manifest is generated at build time and inlined\n      if (id === \"/@farm/manifest\") {\n        const routeManager = farmApp?.getRouteManager();\n        if (!routeManager) {\n          return `\nexport const getManifest = () => ({\n  routes: {},\n  layouts: {},\n  slots: [],\n  clientEntry: \"/@farm/client.js\",\n  sharedAssets: []\n});\n`;\n        }\n\n        const manifest = routeManager.generateClientManifest(server.config.root);\n\n        // Convert to full manifest format\n        const fullManifest = {\n          clientEntry: \"/@farm/client.js\",\n          routes: {} as Record<string, any>,\n          layouts: {} as Record<string, any>,\n          slots: [] as Array<Record<string, any>>,\n          sharedAssets: [\n            {\n              tag: \"link\",\n              attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n            },\n          ],\n        };\n\n        // Convert routes array to object keyed by pattern\n        for (const route of manifest.routes) {\n          fullManifest.routes[route.pattern] = {\n            modulePath: route.modulePath,\n            pattern: route.pattern,\n            segments: route.segments,\n            search: route.search,\n            isClientComponent: route.isClientComponent,\n            shouldHydrate: route.shouldHydrate,\n            islandStrategy: route.islandStrategy,\n            renderPlan: route.renderPlan,\n            preloads: [route.modulePath], // In dev, preload is just the module\n            assets: [],\n          };\n        }\n\n        // Convert layouts array to object keyed by pattern\n        for (const layout of manifest.layouts) {\n          fullManifest.layouts[layout.pattern] = {\n            modulePath: layout.modulePath,\n            pattern: layout.pattern,\n            shouldHydrate: layout.shouldHydrate,\n            islandStrategy: layout.islandStrategy,\n            preloads: [layout.modulePath],\n            assets: [],\n          };\n        }\n\n        for (const slot of manifest.slots) {\n          fullManifest.slots.push({\n            ...slot,\n            preloads: [slot.modulePath],\n            assets: [],\n          });\n        }\n\n        return `\n// Auto-generated manifest for SPA navigation (TanStack Start pattern)\n// This manifest is inlined in the server bundle - no file on disk\n// Client receives this via window.__FARM_MANIFEST__ in HTML\nexport const getManifest = () => (${JSON.stringify(fullManifest, null, 2)});\nexport const manifest = getManifest();\n`;\n      }\n    },\n\n    async transform(code, id, transformOptions) {\n      if (!transformOptions?.ssr) {\n        const currentConfig = (farmApp?.getConfig() ?? options) as FarmVitePluginOptions;\n        if (currentConfig.experimental?.serverActions !== true) {\n          // Without the server-function transform there is no client stub for\n          // server queries: bundling the defining module into the browser\n          // executes the server handler there. Fail with an actionable\n          // boundary error instead of Vite's Node-builtin externalization\n          // failure at runtime.\n          const violation = findClientServerFnViolation(code, id);\n          if (violation) {\n            this.error(formatServerFnBoundaryError(violation, id));\n          }\n        }\n      }\n\n      if (!transformOptions?.ssr && shouldInspectClientBoundary(id, code)) {\n        warnClientBoundaryOnce(this, id, code, farmApp?.getConfig() ?? options);\n      }\n\n      if (typeof imageImports.transform === \"function\") {\n        const imageModule = await imageImports.transform.call(this, code, id, transformOptions);\n        if (imageModule) return imageModule;\n      }\n\n      let transformedCode = code;\n      let transformed = false;\n\n      if (typeof fontImports.transform === \"function\") {\n        const fontResult = await fontImports.transform.call(\n          this,\n          transformedCode,\n          id,\n          transformOptions,\n        );\n        const fontCode = typeof fontResult === \"string\" ? fontResult : fontResult?.code;\n        if (fontCode) {\n          transformedCode = fontCode;\n          transformed = true;\n        }\n      }\n\n      if (transformOptions?.ssr && server) {\n        const rewrittenImports = rewriteEarlySsrRelativeImports({\n          code: transformedCode,\n          id,\n          root: server.config.root,\n          parse: (source) => this.parse(source) as unknown as FarmModuleAstNode,\n        });\n        if (rewrittenImports) {\n          transformedCode = rewrittenImports;\n          transformed = true;\n        }\n      }\n\n      if (hasUseClientDirective(transformedCode)) {\n        const clientBoundarySource = transformedCode;\n        const moduleInfo = this.getModuleInfo(id);\n        if (moduleInfo) {\n          (moduleInfo as any).isClientComponent = true;\n        }\n\n        transformedCode = stripUseClientDirective(transformedCode);\n        transformed = true;\n\n        const currentConfig = (farmApp?.getConfig() ?? options) as FarmVitePluginOptions;\n        const configuredProviders = getIntegrationProviders(currentConfig.integrations).filter(\n          (provider) => provider.component || provider.type === \"clerk\",\n        );\n        const isolatedHydrationEnabled =\n          resolveFarmIsolatedClientHydrationMode(\n            currentConfig.experimental?.isolatedClientHydration,\n            {\n              serverComponents: currentConfig.experimental?.serverComponents === true,\n              hasUnsupportedIntegrationProvider: configuredProviders.some(\n                (provider) => provider.supportsIsolatedHydration !== true,\n              ),\n            },\n          ) === \"enabled\" && isReactRenderer(resolveFarmRenderer(currentConfig.renderer));\n        let isolatedModuleReference: string | null = null;\n        const root = currentConfig.root || server?.config.root || process.cwd();\n        const cleanId = id.split(\"?\", 1)[0];\n        const selectedIsolatedModules =\n          options.isolatedClientBoundaryModules ??\n          farmApp?.getRouteManager().getIsolatedClientBoundaryModules(root);\n        const selectedForIsolatedHydration =\n          selectedIsolatedModules?.has(path.resolve(cleanId)) === true;\n        if (\n          isolatedHydrationEnabled &&\n          selectedForIsolatedHydration &&\n          isIsolatableClientBoundarySource(clientBoundarySource)\n        ) {\n          isolatedModuleReference = toViteModuleId(cleanId, root);\n          const transformedBoundary = transformIsolatedClientBoundaryModule({\n            code: transformedCode,\n            moduleReference: isolatedModuleReference,\n            islandStrategy: getIslandStrategyExport(clientBoundarySource) ?? \"load\",\n            parse: (source) => this.parse(source) as unknown as FarmModuleAstNode,\n          });\n          if (!transformedBoundary) {\n            this.error(\n              `[Farm.js] Could not compile isolated client boundary ${cleanId}. ` +\n                `Use experimental.isolatedClientHydration = \"analyze\" to inspect eligibility ` +\n                `or \"off\" to retain route-wide hydration.`,\n            );\n          }\n          transformedCode = transformedBoundary;\n        }\n\n        // Store client component for later injection\n        if (!farmApp) {\n          return {\n            code: transformedCode,\n            map: null,\n          };\n        }\n\n        const clientComponents = (farmApp as any).__clientComponents__ || new Set();\n        clientComponents.add(id);\n        (farmApp as any).__clientComponents__ = clientComponents;\n\n        // Add HMR support for client components\n        // This ensures React re-renders when the component updates\n        const isolatedHmrUpdate = isolatedModuleReference\n          ? `\n    if (\n      newModule &&\n      newModule.__farm_client_boundary_originals__ &&\n      window.__FARM_ISOLATED_HYDRATION_RUNTIME__\n    ) {\n      window.__FARM_ISOLATED_HYDRATION_RUNTIME__.updateModule(\n        ${JSON.stringify(isolatedModuleReference)},\n        newModule,\n      );\n      return;\n    }`\n          : \"\";\n        const hmrCode = `\nif (import.meta.hot) {\n  import.meta.hot.accept((newModule) => {\n    ${isolatedHmrUpdate}\n    if (newModule && newModule.default && window.__FARM_REACT_ROOT__) {\n      // Re-render with the new component\n      const React = window.__FARM_REACT__;\n      const props = window.__FARM_PROPS__ || {};\n      const nextElement = React.createElement(newModule.default, props);\n      const wrapProviders = window.__FARM_WRAP_PROVIDERS__;\n      const wrapClientGraph = window.__FARM_WRAP_CLIENT_GRAPH__;\n      Promise.resolve(\n        typeof wrapProviders === 'function' ? wrapProviders(nextElement) : nextElement\n      ).then((wrappedElement) => {\n        window.__FARM_REACT_ROOT__.render(\n          typeof wrapClientGraph === 'function'\n            ? wrapClientGraph(wrappedElement)\n            : wrappedElement\n        );\n      });\n    }\n  });\n}\n`;\n        return {\n          code: transformedCode + \"\\n\" + hmrCode,\n          map: null,\n        };\n      }\n\n      return transformed ? { code: transformedCode, map: null } : null;\n    },\n\n    async generateBundle(options, bundle) {\n      if (typeof fontImports.generateBundle === \"function\") {\n        await fontImports.generateBundle.call(this, options, bundle, false);\n      }\n      const clientManifest = generateClientManifest(bundle);\n      this.emitFile({\n        type: \"asset\",\n        fileName: \"farm-client-manifest.json\",\n        source: JSON.stringify(clientManifest, null, 2),\n      });\n    },\n\n    async closeBundle() {\n      // SSG: Pre-render static pages at build time\n      if (!farmApp) return;\n\n      try {\n        const routeManager = farmApp.getRouteManager();\n        if (!routeManager) return;\n\n        const { ssg: ssgPages, ssr: ssrRoutes } = await routeManager.collectSSGPages();\n\n        if (ssgPages.length === 0) {\n          logger.info(\"No SSG pages found - all pages will use SSR\");\n          return;\n        }\n\n        logger.info(`Found ${ssgPages.length} SSG pages, ${ssrRoutes.length} SSR routes`);\n        logger.info(\"Pre-rendering SSG pages...\");\n\n        const outDir = path.join(server?.config.root || process.cwd(), options.outDir || \"dist\");\n        const clientDir = path.join(outDir, \"client\");\n\n        // Pre-render each SSG page\n        for (const page of ssgPages) {\n          try {\n            const staticRequest = new Request(new URL(page.urlPath, \"http://farm.static\"));\n            await farmApp.getServerRenderer().runWithRequestContext(staticRequest, async () => {\n              // Load the route module\n              const mod = await routeManager.loadRouteModule(page.filePath);\n              if (!mod?.default) return;\n\n              // Find matching layouts\n              const { layouts } = routeManager.matchRoute(page.urlPath);\n              const layoutModules = await Promise.all(\n                layouts.map((l) => routeManager.loadLayoutModule(l.modulePath)),\n              );\n\n              // Render the page\n              const React = await import(\"react\");\n              const { renderToString } = await import(\"react-dom/server\");\n\n              const PageComponent = mod.default;\n              const pageProps = {\n                params: page.params,\n                searchParams: Promise.resolve({}),\n                path: page.urlPath,\n              };\n\n              let pageElement = React.createElement(\n                PageComponent as React.ComponentType<unknown>,\n                pageProps as React.Attributes,\n              );\n\n              // Wrap with layouts\n              for (let i = layoutModules.length - 1; i >= 0; i--) {\n                const layoutModule = layoutModules[i];\n                const LayoutComponent = layoutModule.default;\n                pageElement = React.createElement(\n                  LayoutComponent as React.ComponentType<unknown>,\n                  {\n                    children: pageElement,\n                    params: page.params,\n                  } as React.Attributes,\n                );\n              }\n\n              const html = renderToString(pageElement);\n\n              // Generate full HTML with proper structure\n              const i18nSnapshot = getFarmI18nClientSnapshot();\n              const i18nHead = renderFarmI18nStaticHead(page.urlPath, i18nSnapshot);\n              const fullHtml = `<!DOCTYPE html>\n<html lang=\"${escapeFarmHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n                i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n              }>\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <link rel=\"icon\" href=\"data:,\">\n  <link rel=\"stylesheet\" href=\"/assets/globals.css\">\n  ${page.revalidate ? `<meta name=\"x-farm-revalidate\" content=\"${page.revalidate}\">` : \"\"}\n  ${i18nHead}\n</head>\n<body>\n  <div id=\"root\">${html}</div>\n  <script type=\"module\" src=\"/assets/client.js\"></script>\n</body>\n</html>`;\n\n              // Write to output directory\n              const outputPath =\n                page.urlPath === \"/\"\n                  ? path.join(clientDir, \"index.html\")\n                  : path.join(clientDir, page.urlPath + \".html\");\n\n              fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n              fs.writeFileSync(outputPath, fullHtml);\n\n              const revalidateInfo = page.revalidate ? ` (revalidate: ${page.revalidate}s)` : \"\";\n              logger.success(`  ✓ ${page.urlPath}${revalidateInfo}`);\n            });\n          } catch (error) {\n            logger.error(`  ✗ ${page.urlPath}: ${error}`);\n          }\n        }\n\n        // Write SSG manifest for server to know which pages are pre-rendered\n        const manifestPath = path.join(outDir, \"__ssg_manifest.json\");\n        fs.writeFileSync(\n          manifestPath,\n          JSON.stringify(\n            ssgPages.map((p) => ({\n              urlPath: p.urlPath,\n              params: p.params,\n              revalidate: p.revalidate,\n            })),\n            null,\n            2,\n          ),\n        );\n\n        logger.success(`SSG complete: ${ssgPages.length} pages pre-rendered`);\n      } catch (error) {\n        logger.error(`SSG build failed: ${error}`);\n      }\n    },\n\n    async handleHotUpdate(ctx: HmrContext) {\n      const { file, server, modules } = ctx;\n      if (initialPluginManager) {\n        try {\n          await initialPluginManager.runHookParallel(\"hmrUpdate\", {\n            file,\n            modules: modules.map((m) => m.id || m.url || \"\").filter(Boolean),\n          });\n        } catch (error) {\n          await initialPluginManager.runHookParallel(\"onError\", {\n            phase: \"hmrUpdate\",\n            error,\n            meta: { file },\n          });\n        }\n      }\n\n      const currentFarmConfig = farmApp?.getConfig();\n      const normalizedFile = file.replace(/\\\\/g, \"/\");\n      if (\n        currentFarmConfig &&\n        /\\/route\\.(?:ts|tsx|js|jsx)$/.test(normalizedFile) &&\n        getFarmAppDirectories(currentFarmConfig).some((appDir) =>\n          normalizedFile.startsWith(`${toPosixPath(appDir)}/api/`),\n        )\n      ) {\n        // Vite has not invalidated these modules yet. Refreshing only generated\n        // types leaves both HTTP and direct server calls bound to old handlers.\n        for (const mod of modules) server.moduleGraph.invalidateModule(mod);\n        await refreshRouteDiscovery?.(`updated ${file}`);\n        server.ws.send({ type: \"full-reload\", path: \"*\" });\n        return [];\n      }\n      const currentSrcRoot = currentFarmConfig\n        ? getFarmSourceRoots(currentFarmConfig)\n            .map((source) => path.join(source.root, source.srcDir).replace(/\\\\/g, \"/\"))\n            .find((sourceRoot) => normalizedFile.startsWith(`${sourceRoot}/`)) || null\n        : null;\n      if (\n        currentSrcRoot &&\n        normalizedFile.startsWith(`${currentSrcRoot}/`) &&\n        isProgrammaticRoutesFileName(normalizedFile)\n      ) {\n        logUpdate(\"PAGE\", `updated ${path.basename(file)}`);\n\n        for (const mod of modules) {\n          server.moduleGraph.invalidateModule(mod);\n        }\n\n        await refreshRouteDiscovery?.(`updated ${file}`);\n\n        server.ws.send({\n          type: \"full-reload\",\n          path: \"*\",\n        });\n\n        return [];\n      }\n\n      if (\n        currentSrcRoot &&\n        isPotentialProgrammaticRouteSourceFile(normalizedFile, currentSrcRoot) &&\n        fileContainsProgrammaticPageRoute(file)\n      ) {\n        const shortPath = normalizedFile.slice(currentSrcRoot.length + 1);\n        logUpdate(\"PAGE\", `updated ${shortPath}`);\n\n        for (const mod of modules) {\n          server.moduleGraph.invalidateModule(mod);\n        }\n\n        await refreshRouteDiscovery?.(`updated ${file}`);\n\n        server.ws.send({\n          type: \"full-reload\",\n          path: \"*\",\n        });\n\n        return [];\n      }\n\n      const isolatedHydrationMode = currentFarmConfig?.experimental?.isolatedClientHydration;\n      if (\n        currentSrcRoot &&\n        (isolatedHydrationMode === \"enabled\" || isolatedHydrationMode === \"analyze\") &&\n        /\\.[cm]?[jt]sx?$/.test(normalizedFile)\n      ) {\n        const routeManager = farmApp?.getRouteManager();\n        if (routeManager) {\n          const previousPlan = JSON.stringify(\n            routeManager.generateClientManifest(currentFarmConfig.root),\n          );\n          routeManager.invalidateClientManifest();\n          const nextPlan = JSON.stringify(\n            routeManager.generateClientManifest(currentFarmConfig.root),\n          );\n          const planChanged = previousPlan !== nextPlan;\n          const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n          if (manifestModule) server.moduleGraph.invalidateModule(manifestModule);\n          if (planChanged) {\n            for (const mod of modules) server.moduleGraph.invalidateModule(mod);\n            server.ws.send({ type: \"full-reload\", path: \"*\" });\n            return [];\n          }\n        }\n      }\n\n      if (normalizedFile.includes(\"/app/\")) {\n        // Hot reload middleware changes\n        if (normalizedFile.includes(\"middleware.\")) {\n          if (middlewareManager) {\n            await middlewareManager.reload();\n            logger.success(\"✅ Middleware reloaded!\");\n            if (initialPluginManager) {\n              for (const middleware of middlewareManager.getMiddlewares()) {\n                await initialPluginManager.runHookParallel(\"middlewareDiscovered\", {\n                  path: middleware.path,\n                  filePath: middleware.filePath,\n                  handlerCount: middleware.handlers.length,\n                });\n              }\n            }\n          }\n\n          return [];\n        }\n\n        farmApp?.getRouteManager().invalidateClientManifest();\n        const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n        if (manifestModule) {\n          server.moduleGraph.invalidateModule(manifestModule);\n        }\n\n        if (normalizedFile.includes(\"page.\") || normalizedFile.includes(\"layout.\")) {\n          const shortPath = normalizedFile.split(\"/app/\")[1] || normalizedFile;\n          logUpdate(\"PAGE\", `updated ${shortPath}`);\n\n          for (const mod of modules) {\n            server.moduleGraph.invalidateModule(mod);\n          }\n\n          server.ws.send({\n            type: \"full-reload\",\n            path: \"*\",\n          });\n\n          return [];\n        }\n      }\n\n      return modules;\n    },\n  };\n}\n\nfunction isFarmClientVirtualId(id: string): boolean {\n  const pathname = id.split(\"?\", 1)[0];\n  return pathname === \"/@farm/client\" || pathname === \"/@farm/client.js\";\n}\n\nfunction generateProgrammaticRouteModule(\n  moduleId: string,\n  root?: string,\n  renderer: FarmRenderer = REACT_RENDERER,\n): string {\n  const parsed = parseProgrammaticRouteModuleId(moduleId);\n  if (!parsed) {\n    return \"\";\n  }\n\n  const routeFile = toProgrammaticRouteImportSpecifier(parsed.filePath, root);\n\n  if (parsed.kind === \"api\") {\n    return generateProgrammaticApiRouteModule(parsed.routePath, routeFile);\n  }\n\n  return `\nimport {\n  createElement as __farmCreateElement,\n  Suspense as __farmSuspense,\n} from ${JSON.stringify(renderer.server)};\nimport {\n  createLayoutModuleFromProgrammaticLayout as __farmCreateLayoutRouteModule,\n  createRouteModuleFromProgrammaticPage as __farmCreatePageRouteModule,\n} from \"@farm.js/core/routes\";\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n  value &&\n  typeof value === \"object\" &&\n  (\n    value.kind === \"page\" ||\n    value.kind === \"layout\" ||\n    value.kind === \"api\" ||\n    value.kind === \"redirect\"\n  )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n  if (Array.isArray(candidate)) return candidate;\n  if (Array.isArray(candidate?.routes)) return candidate.routes;\n  if (__farmIsRouteDefinition(candidate)) return [candidate];\n  return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n  __farmGetRouteExport(\"default\"),\n  __farmGetRouteExport(\"routes\"),\n  __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n  __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n  if (__farmRoutes.length > 0) break;\n}\n\nif (__farmRoutes.length === 0) {\n  __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (routePath) => {\n  const withSlash = routePath && routePath.startsWith(\"/\") ? routePath : \"/\" + (routePath || \"\");\n  const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n  return withoutTrailing || \"/\";\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n  route &&\n  route.kind === ${JSON.stringify(parsed.kind)} &&\n  __farmNormalizeRoutePath(route.path) === ${JSON.stringify(parsed.routePath)}\n));\n\nif (!__farmRoute) {\n  throw new Error(${JSON.stringify(\n    `Programmatic ${parsed.kind} route \"${parsed.routePath}\" was not found in ${routeFile}.`,\n  )});\n}\n\nconst __farmRouteModule = __farmRoute.kind === \"layout\"\n  ? __farmCreateLayoutRouteModule(__farmRoute)\n  : __farmCreatePageRouteModule(__farmRoute, {\n      createElement: __farmCreateElement,\n      Suspense: __farmSuspense,\n    });\n\nexport const metadata = __farmRouteModule.metadata;\nexport const generateMetadata = __farmRouteModule.generateMetadata;\nconst __farmIsSearchSchema = (value) => value && typeof value.parse === \"function\";\nconst __farmGetSearchSchema = (search) => __farmIsSearchSchema(search) ? search : search?.schema;\nconst __farmGetSearchOptions = (search) => __farmIsSearchSchema(search) ? undefined : search;\nconst __farmSearchSchema = __farmGetSearchSchema(__farmRoute.search);\nconst __farmSearchOptions = __farmGetSearchOptions(__farmRoute.search);\nexport const __farmRouteSchemas = __farmRouteModule.__farmRouteSchemas;\nexport const __farmRouteSearch = __farmRouteModule.__farmRouteSearch;\nexport const __farmRouteData = __farmRouteModule.__farmRouteData;\nexport const __farmRouteGuard = __farmRouteModule.__farmRouteGuard;\nexport const __farmRouteParsesProps = __farmRouteModule.__farmRouteParsesProps;\nexport const __farmRouteComponents = __farmRouteModule.__farmRouteComponents;\nexport const __farmResolveRouteCanonicalPath =\n  __farmRouteModule.__farmResolveRouteCanonicalPath;\nexport const ssg = __farmRouteModule.ssg;\nexport const dynamic = __farmRouteModule.dynamic;\nexport const revalidate = __farmRouteModule.revalidate;\nexport const ppr = __farmRouteModule.ppr;\nexport const getStaticPaths = __farmRouteModule.getStaticPaths;\n\nconst __farmParseSchema = (schema, value, label) => {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    throw new Error(\"Invalid \" + label + \" for route \" + JSON.stringify(__farmRoute.path) + \": \" + (error?.message || String(error)));\n  }\n};\n\nconst __farmMarkRoutePropsResolved = (props) => ({\n  ...props,\n  __farmRoutePropsResolved: true,\n});\n\nconst __farmAddCanonicalPath = (props, canonicalPath) => (\n  canonicalPath ? { ...props, __farmCanonicalPath: canonicalPath } : props\n);\n\nconst __farmStripRoutePropsMarker = (props) => {\n  if (!props || props.__farmRoutePropsResolved !== true) {\n    return props;\n  }\n\n  const {\n    __farmRoutePropsResolved,\n    __farmCanonicalPath,\n    __farmRoutePropsPromise,\n    ...componentProps\n  } = props;\n  return componentProps;\n};\n\nconst __farmCreateSearchParams = (value) => {\n  const params = new URLSearchParams();\n  for (const [key, item] of Object.entries(value || {})) {\n    if (item == null) continue;\n    const values = Array.isArray(item) ? item : [item];\n    for (const entry of values) {\n      if (entry != null) params.append(key, String(entry));\n    }\n  }\n  return params;\n};\n\nconst __farmComparable = (value) => {\n  if (Array.isArray(value)) return value.map(__farmComparable);\n  if (value && typeof value === \"object\") {\n    return Object.keys(value).sort().reduce((output, key) => {\n      output[key] = __farmComparable(value[key]);\n      return output;\n    }, {});\n  }\n  return value;\n};\n\nconst __farmEqual = (left, right) => (\n  JSON.stringify(__farmComparable(left)) === JSON.stringify(__farmComparable(right))\n);\n\nconst __farmReadSearchValue = (value, key) => (\n  value && typeof value === \"object\" ? value[key] : undefined\n);\n\nconst __farmParseDefaultSearch = () => {\n  if (!__farmSearchSchema) return undefined;\n  try {\n    const value = __farmSearchSchema.parse({});\n    return value && typeof value === \"object\" ? value : undefined;\n  } catch {\n    return undefined;\n  }\n};\n\nconst __farmResolveCanonicalPath = (rawSearch, parsedSearch, path) => {\n  if (!__farmSearchOptions?.temporary?.length && !__farmSearchOptions?.stripDefaults) {\n    return undefined;\n  }\n\n  const params = __farmCreateSearchParams(rawSearch);\n  const original = params.toString();\n\n  for (const key of __farmSearchOptions.temporary || []) {\n    params.delete(key);\n  }\n\n  if (__farmSearchOptions.stripDefaults) {\n    const defaults = __farmParseDefaultSearch();\n    if (defaults) {\n      const keys = __farmSearchOptions.stripDefaults === true\n        ? Array.from(new Set(Array.from(params.keys())))\n        : [...__farmSearchOptions.stripDefaults];\n      for (const key of keys) {\n        if (params.has(key) && __farmEqual(__farmReadSearchValue(parsedSearch, key), __farmReadSearchValue(defaults, key))) {\n          params.delete(key);\n        }\n      }\n    }\n  }\n\n  const next = params.toString();\n  if (next === original) return undefined;\n  return next ? path + \"?\" + next : path;\n};\n\nexport async function __farmResolveRouteProps(props) {\n  return typeof __farmRouteModule.__farmResolveRouteProps === \"function\"\n    ? __farmRouteModule.__farmResolveRouteProps(props)\n    : props;\n}\n\nconst __farmNeedsPageWrapper = __farmRoute.kind === \"page\" && !!(\n  __farmRoute.params ||\n  __farmRoute.search ||\n  __farmRoute.data\n);\n\nasync function __farmProgrammaticPage(props) {\n  const deferredRouteProps = props?.__farmRoutePropsPromise;\n  const resolvedProps = props?.__farmRoutePropsResolved === true\n    ? props\n    : deferredRouteProps && typeof deferredRouteProps.then === \"function\"\n      ? await deferredRouteProps\n      : await __farmResolveRouteProps(props);\n\n  return __farmCreateElement(\n    __farmRoute.component,\n    __farmStripRoutePropsMarker(resolvedProps)\n  );\n}\n\nexport default __farmRouteModule.default;\n`;\n}\n\nfunction generateProgrammaticApiRouteModule(routePath: string, routeFile: string): string {\n  return `\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n  value && typeof value === \"object\" && (\n    value.kind === \"page\" ||\n    value.kind === \"layout\" ||\n    value.kind === \"api\" ||\n    value.kind === \"redirect\"\n  )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n  if (Array.isArray(candidate)) return candidate;\n  if (Array.isArray(candidate?.routes)) return candidate.routes;\n  if (__farmIsRouteDefinition(candidate)) return [candidate];\n  return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n  __farmGetRouteExport(\"default\"),\n  __farmGetRouteExport(\"routes\"),\n  __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n  __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n  if (__farmRoutes.length > 0) break;\n}\nif (__farmRoutes.length === 0) {\n  __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (value) => {\n  const withSlash = value && value.startsWith(\"/\") ? value : \"/\" + (value || \"\");\n  return withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n  route?.kind === \"api\" &&\n  __farmNormalizeRoutePath(route.path) === ${JSON.stringify(routePath)}\n));\n\nif (!__farmRoute) {\n  throw new Error(${JSON.stringify(\n    `Programmatic api route \"${routePath}\" was not found in ${routeFile}.`,\n  )});\n}\n\nexport const GET = __farmRoute.methods.GET;\nexport const HEAD = __farmRoute.methods.HEAD;\nexport const QUERY = __farmRoute.methods.QUERY;\nexport const POST = __farmRoute.methods.POST;\nexport const PUT = __farmRoute.methods.PUT;\nexport const DELETE = __farmRoute.methods.DELETE;\nexport const PATCH = __farmRoute.methods.PATCH;\nexport const OPTIONS = __farmRoute.methods.OPTIONS;\n`.trim();\n}\n\nfunction toProgrammaticRouteImportSpecifier(filePath: string, root?: string): string {\n  return root ? toViteModuleId(filePath, root) : filePath;\n}\n\ntype RouteModuleLike = {\n  __farmRouteParsesProps?: boolean;\n  __farmResolveRouteProps?: (props: {\n    params: Record<string, string>;\n    searchParams: Promise<Record<string, string | string[] | undefined>>;\n    path: string;\n    [key: string]: unknown;\n  }) => Promise<Record<string, unknown>>;\n  __farmRouteSchemas?: {\n    params?: { parse?: (value: unknown) => unknown };\n    search?: { parse?: (value: unknown) => unknown };\n  };\n};\n\nasync function parseRouteModuleProps(\n  routeModule: RouteModuleLike,\n  input: {\n    props: {\n      params: Record<string, string>;\n      searchParams: Promise<Record<string, string | string[] | undefined>>;\n      path: string;\n      [key: string]: unknown;\n    };\n    search: Record<string, string | string[] | undefined>;\n    routePath: string;\n  },\n): Promise<Record<string, unknown>> {\n  if (typeof routeModule.__farmResolveRouteProps === \"function\") {\n    return await routeModule.__farmResolveRouteProps(input.props);\n  }\n\n  if (routeModule.__farmRouteParsesProps) {\n    return {\n      ...input.props,\n      search: input.search,\n    };\n  }\n\n  const schemas = routeModule.__farmRouteSchemas;\n  const params = parseRouteModuleSchema(\n    schemas?.params,\n    input.props.params,\n    \"params\",\n    input.routePath,\n  );\n  const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n  return {\n    ...input.props,\n    params,\n    search,\n    searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n  };\n}\n\nfunction parseRouteModuleSchema(\n  schema: { parse?: (value: unknown) => unknown } | undefined,\n  value: unknown,\n  label: string,\n  routePath: string,\n): unknown {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n  }\n}\n\nfunction generateClientCode(\n  integrationProviders: ReturnType<typeof getIntegrationProviders> = [],\n  documentNavigationMatchers: string[] = [],\n  docsSearchClientRuntime = EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME,\n  devtoolsClientRuntime = \"\",\n  plugins: readonly FarmPlugin[] = [],\n  root = process.cwd(),\n  srcDir = \"src\",\n  publicRuntimeConfig: Record<string, unknown> | undefined = undefined,\n  docsAdapterReact?: string,\n  renderer: FarmRenderer = REACT_RENDERER,\n  isolatedHydrationEnabled = false,\n  trailingSlash = false,\n  basePath = \"/\",\n  clientCachePersistence: ClientCachePersistenceEntryCode = { imports: \"\", init: \"\" },\n): string {\n  const providerClientCode = generateFarmIntegrationProviderClientCode(integrationProviders, root);\n  const clientPluginEntry = generateFarmClientPluginEntryCode(\n    plugins,\n    root,\n    srcDir,\n    publicRuntimeConfig,\n  );\n  const rendererClientImports = isReactRenderer(renderer)\n    ? `import React from 'react'\\nimport { hydrateRoot, createRoot } from 'react-dom/client'`\n    : `import React, { hydrateRoot, createRoot } from ${JSON.stringify(renderer.client)}`;\n  const isolatedHydrationImport = isolatedHydrationEnabled\n    ? `import { createFarmIsolatedHydrationRuntime, wrapFarmIsolatedClientGraph } from '@farm.js/core/internal/isolated-boundary'`\n    : \"\";\n  const docsAdapterImportBlock = docsAdapterReact\n    ? `import * as FarmDocsAdapterReact from ${JSON.stringify(docsAdapterReact)};\n\nasync function hydrateFarmDocsAdapterRuntime() {\n  const runtime = window.__FARM_DOCS_ADAPTER__;\n  if (!runtime) return false;\n  if (typeof FarmDocsAdapterReact.hydrateFarmDocs !== 'function') {\n    throw new Error('The configured Farm docs adapter does not export hydrateFarmDocs().');\n  }\n  FarmDocsAdapterReact.hydrateFarmDocs({\n    config: runtime.config || {},\n    data: runtime.data,\n  });\n  return true;\n}`\n    : `async function hydrateFarmDocsAdapterRuntime() { return false; }`;\n  const isolatedHydrationRuntime = isolatedHydrationEnabled\n    ? `const farmIsolatedHydrationRuntime = createFarmIsolatedHydrationRuntime({\n  ReactRuntime: React,\n  hydrateRoot,\n  load: (reference) => import(/* @vite-ignore */ reference),\n  schedule: scheduleFarmIslandHydration,\n  wrap: wrapWithIntegrationProviders,\n});\nwindow.__FARM_ISOLATED_HYDRATION_RUNTIME__ = farmIsolatedHydrationRuntime;\n\nfunction disposeFarmIsolatedClientBoundaries(scope) {\n  farmIsolatedHydrationRuntime.dispose(scope);\n}\n\nasync function hydrateFarmIsolatedClientBoundaries(scope = document, signal) {\n  await farmIsolatedHydrationRuntime.hydrate(scope, signal);\n}`\n    : \"\";\n\n  return `\n${rendererClientImports}\n${isolatedHydrationImport}\nimport { installChunkErrorRecovery, SPARouter } from '@farm.js/core/client'\nimport { createClientPluginManager } from '@farm.js/core/plugin/client'\nimport { isFarmRouteActive } from '@farm.js/core/router'\nimport { scheduleFarmIslandHydration, searchParamsToObject, setFarmBasePath, setFarmTrailingSlashPreference, stripFarmBasePath } from '@farm.js/core/internal/client-runtime'\nimport { reviveDeferredData } from '@farm.js/core/deferred'\nimport {\n  createFarmDeploymentMismatchError,\n  createFarmDeploymentRequestHeaders,\n  isFarmDeploymentMismatchResponse,\n} from '@farm.js/core/deployment'\n${providerClientCode.imports}\n${clientPluginEntry.imports}\n${clientCachePersistence.imports}\n${docsSearchClientRuntime}\n${devtoolsClientRuntime}\n${docsAdapterImportBlock}\n\n// ⭐ Farm.js SPA Client Runtime (TanStack Start pattern)\n// Uses manifest-based chunk loading - NO HTML fetching!\n// Manifest is inlined in HTML via window.__FARM_MANIFEST__\n\n// Expose React for HMR\nwindow.__FARM_REACT__ = React;\nconst integrationDocumentNavigationMatchers = ${JSON.stringify(documentNavigationMatchers)};\n\nsetFarmBasePath(${JSON.stringify(basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(trailingSlash)});\ninstallChunkErrorRecovery();\n${clientCachePersistence.init}\n\nlet reactRoot = null;\n${isolatedHydrationRuntime}\n\nfunction matchesDocumentNavigation(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  return integrationDocumentNavigationMatchers.some((matcher) => {\n    if (matcher === '/(.*)' || matcher === '*') {\n      return true;\n    }\n    if (matcher.endsWith('(.*)')) {\n      const prefix = matcher.slice(0, -4);\n      return pathname === prefix || pathname.startsWith(prefix + '/');\n    }\n    return matcher === pathname;\n  });\n}\n\n${providerClientCode.runtime}\n\nwindow.__FARM_WRAP_PROVIDERS__ = wrapWithIntegrationProviders;\n${isolatedHydrationEnabled ? \"window.__FARM_WRAP_CLIENT_GRAPH__ = (element) => wrapFarmIsolatedClientGraph(React, element);\" : \"\"}\n\n// Get manifest from window (inlined by server in HTML)\n// Fallback to empty manifest if not available yet\nconst getManifest = () => window.__FARM_MANIFEST__ || { routes: {}, layouts: {}, slots: [], clientEntry: '', sharedAssets: [] };\n\n// ====== CLIENT-SIDE ROUTE MATCHING ======\n// Matches URL to route using manifest (no server request!)\n\nfunction matchSegment(urlSegment, routeSegment) {\n  if (!routeSegment.isDynamic) {\n    return urlSegment === routeSegment.segment ? {} : null;\n  }\n  if (routeSegment.isCatchAll) {\n    return { [routeSegment.segment]: urlSegment };\n  }\n  return { [routeSegment.segment]: urlSegment };\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction matchRoute(pathname, routeSegments) {\n  const normalizedPath = pathname === '/' ? '' : pathname.replace(/^\\\\//, '').replace(/\\\\/$/, '');\n  const pathSegments = normalizedPath ? normalizedPath.split('/').map(decodeRouteSegment) : [];\n  \n  // Handle catch-all routes\n  const hasCatchAll = routeSegments.some(s => s.isCatchAll);\n  \n  if (!hasCatchAll && pathSegments.length !== routeSegments.length) {\n    return null;\n  }\n  \n  const params = {};\n  \n  for (let i = 0; i < routeSegments.length; i++) {\n    const routeSeg = routeSegments[i];\n    const pathSeg = pathSegments[i];\n\n    if (routeSeg.isCatchAll) {\n      // Collect remaining segments\n      params[routeSeg.segment] = pathSegments.slice(i).join('/');\n      return params;\n    }\n    \n    if (pathSeg === undefined) {\n      if (routeSeg.isOptional) continue;\n      return null;\n    }\n    \n    const match = matchSegment(pathSeg, routeSeg);\n    if (match === null) return null;\n    Object.assign(params, match);\n  }\n  \n  return params;\n}\n\nfunction findRoute(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  const manifest = getManifest();\n  const routes = Object.values(manifest.routes);\n  \n  for (const route of routes) {\n    const params = matchRoute(pathname, route.segments);\n    if (params !== null) {\n      return { route, params };\n    }\n  }\n  return null;\n}\n\nfunction findLayouts(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  const manifest = getManifest();\n  const layouts = Object.values(manifest.layouts);\n  const matchingLayouts = [];\n  \n  for (const layout of layouts) {\n    if (layout.pattern === '/' || isFarmRouteActive(layout.pattern, pathname, { exact: false })) {\n      matchingLayouts.push(layout);\n    }\n  }\n  \n  return matchingLayouts.sort((a, b) => a.pattern.length - b.pattern.length);\n}\n\n// ====== SPA ROUTER ======\n// Client-side router - no server requests needed!\n\nclass LegacyManifestSPARouter {\n  constructor() {\n    this.moduleCache = new Map();\n    this.prefetchingUrls = new Set();\n    this.observers = new Map();\n    \n    if (typeof window !== 'undefined') {\n      window.addEventListener('popstate', this.handlePopState.bind(this));\n    }\n  }\n\n  setNavigationHandler(handler) {\n    this.onNavigate = handler;\n  }\n\n  async navigate(href, options = {}) {\n    const { replace = false, scroll = true } = options;\n    const url = new URL(href, window.location.origin);\n    const pathname = url.pathname;\n    const search = url.search;\n    const fullPath = pathname + search;\n\n    if (matchesDocumentNavigation(pathname)) {\n      if (replace) {\n        window.location.replace(url.toString());\n      } else {\n        window.location.assign(url.toString());\n      }\n      return;\n    }\n\n    // Same page - update fragment history without loading route data.\n    if (pathname === window.location.pathname && search === window.location.search) {\n      if (url.hash === window.location.hash) return;\n      if (replace) {\n        window.history.replaceState(window.history.state, '', url);\n      } else {\n        window.history.pushState(window.history.state, '', url);\n      }\n      if (scroll) {\n        if (url.hash) document.querySelector(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      }\n      return;\n    }\n\n    // Save scroll position\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n\n    try {\n      // CLIENT-SIDE route matching - no server request!\n      const match = findRoute(pathname);\n      if (!match) {\n        console.warn('[Farm.js] Route not found:', pathname);\n        window.location.href = href;\n        return;\n      }\n\n      const { route, params } = match;\n\n      // Parse search params\n      const searchParams = searchParamsToObject(url.searchParams);\n\n      // Build page data from manifest (no server request!)\n      const pageData = {\n        route: route, // Full route entry from manifest\n        params,\n        searchParams,\n        layouts: findLayouts(pathname),\n      };\n\n      // Update URL\n      if (replace) {\n        window.history.replaceState({ path: fullPath }, '', fullPath);\n      } else {\n        window.history.pushState({ path: fullPath }, '', fullPath);\n      }\n\n      // Navigate using the handler\n      if (this.onNavigate) {\n        await this.onNavigate(pageData);\n      }\n      applyCanonicalPathFromProps(currentPageProps);\n\n      // Handle scroll\n      if (scroll) {\n        if (url.hash) {\n          const element = document.querySelector(url.hash);\n          if (element) element.scrollIntoView();\n        } else {\n          window.scrollTo(0, 0);\n        }\n      }\n    } catch (error) {\n      console.error('[Farm.js] Navigation error:', error);\n      window.location.href = href; // Fallback\n    }\n  }\n\n  async prefetch(href) {\n    // Prefetching disabled in dev mode to avoid Vite dep optimization issues\n    // In production, assets are already bundled and prefetched via link tags\n    if (import.meta.env?.DEV) return;\n    \n    const url = new URL(href, window.location.origin);\n    const pathname = url.pathname;\n\n    if (this.prefetchingUrls.has(pathname)) return;\n\n    // Find route in manifest\n    const match = findRoute(pathname);\n    if (!match) return;\n\n    // Only prefetch routes that will hydrate on the client.\n    if (!match.route.isClientComponent && !match.route.shouldHydrate) return;\n    if (match.route.islandStrategy && match.route.islandStrategy !== 'load') return;\n\n    const modulePath = match.route.modulePath;\n    if (this.moduleCache.has(modulePath)) return;\n\n    this.prefetchingUrls.add(pathname);\n    try {\n      // Prefetch by importing the module (Vite caches it)\n      const module = await import(/* @vite-ignore */ modulePath);\n      this.moduleCache.set(modulePath, module);\n      pageModuleCache.set(modulePath, module);\n    } catch (error) {\n      // Silently fail for prefetch\n    } finally {\n      this.prefetchingUrls.delete(pathname);\n    }\n  }\n\n  observeForPrefetch(element) {\n    if (typeof IntersectionObserver === 'undefined') return;\n    const href = element.getAttribute('href');\n    if (!href || this.isExternalUrl(href)) return;\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) {\n          if (entry.isIntersecting) {\n            setTimeout(() => this.prefetch(href), 100);\n            observer.unobserve(element);\n            this.observers.delete(element);\n          }\n        }\n      },\n      { rootMargin: '200px' }\n    );\n    observer.observe(element);\n    this.observers.set(element, observer);\n  }\n\n  unobserveForPrefetch(element) {\n    const observer = this.observers.get(element);\n    if (observer) {\n      observer.unobserve(element);\n      this.observers.delete(element);\n    }\n  }\n\n  async handlePopState(event) {\n    if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n    const pathname = window.location.pathname;\n    const search = window.location.search;\n    \n    try {\n      // Client-side route matching for back/forward\n      const match = findRoute(pathname);\n      if (!match) {\n        window.location.reload();\n        return;\n      }\n\n      const { route, params } = match;\n      const url = new URL(window.location.href);\n      const searchParams = searchParamsToObject(url.searchParams);\n\n      const pageData = {\n        route: route,\n        params,\n        searchParams,\n        layouts: findLayouts(pathname),\n      };\n\n      if (this.onNavigate) await this.onNavigate(pageData);\n      this.restoreScrollPosition(pathname + search);\n    } catch (error) {\n      console.error('[Farm.js] Popstate error:', error);\n      window.location.reload();\n    }\n  }\n\n  isExternalUrl(href) {\n    return href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//');\n  }\n\n  saveScrollPosition(path) {\n    try {\n      sessionStorage.setItem('farm-scroll-' + path, JSON.stringify({ x: window.scrollX, y: window.scrollY }));\n    } catch {}\n  }\n\n  restoreScrollPosition(path) {\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  }\n}\n\n// Initialize the SPA router\nconst spaRouter = new SPARouter({\n  shouldUseDocumentNavigation: matchesDocumentNavigation,\n});\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nconst farmClientRuntime = createClientPluginManager(\n  ${clientPluginEntry.registrations},\n  {\n    router: spaRouter,\n    isDev: import.meta.env?.DEV === true,\n    isProd: import.meta.env?.PROD === true,\n    deploymentId: window.__FARM_DEPLOYMENT_ID__,\n  },\n);\nspaRouter.setClientPluginManager(farmClientRuntime);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\nif (import.meta.hot) {\n  import.meta.hot.dispose(() => {\n    void farmClientRuntime.close('hmr');\n  });\n}\n\n// Cache for loaded page modules\nconst pageModuleCache = new Map();\n\n// Current page state for React rendering\nlet currentPageComponent = null;\nlet currentPageProps = {};\nlet appRoot = null;\n\n// Layout modules are cached independently so nested client-aware layouts are\n// composed with the same root-to-leaf structure that the server rendered.\nconst layoutComponentCache = new Map();\n\n// Track if we've taken over rendering from SSR\nlet hasClientTakenOver = false;\nconst routeSlotRoots = new Map();\nconst routeSlotDefinitions = new Map();\nlet activeRouteInterception = null;\nlet pendingPageHydrationController = null;\n\nfunction cancelPendingPageHydration() {\n  pendingPageHydrationController?.abort();\n  pendingPageHydrationController = null;\n}\n\nfunction normalizeServerProps(rawProps) {\n  const props = rawProps && typeof rawProps === 'object' ? { ...rawProps } : {};\n  if (props.middleware && props.middleware.data && !(props.middleware.data instanceof Map)) {\n    props.middleware = { ...props.middleware, data: new Map(Object.entries(props.middleware.data)) };\n  }\n  if (props.context && props.context.data && !(props.context.data instanceof Map)) {\n    props.context = { ...props.context, data: new Map(Object.entries(props.context.data)) };\n  }\n  return props;\n}\n\nfunction getRouteSlotKey(slot) {\n  return slot.ownerPattern + ':' + slot.name;\n}\n\nasync function renderRouteSlot(slot, mode = 'render') {\n  const container = document.getElementById(slot.containerId);\n  if (!container || !slot.modulePath) return false;\n  if (mode === 'intercept' && !slot.isClientComponent && !slot.shouldHydrate) {\n    return false;\n  }\n\n  let slotModule = pageModuleCache.get(slot.modulePath);\n  if (!slotModule) {\n    slotModule = await import(/* @vite-ignore */ slot.modulePath);\n    pageModuleCache.set(slot.modulePath, slotModule);\n  }\n  const SlotComponent = slotModule?.default;\n  if (!SlotComponent) return false;\n\n  const props = reviveDeferredData(\n    normalizeServerProps(slot.props || {}),\n    window.__FARM_DEFERRED_DATA__ || {},\n  );\n  let element = wrapWithIntegrationProviders(React.createElement(SlotComponent, props));\n  ${isolatedHydrationEnabled ? \"element = wrapFarmIsolatedClientGraph(React, element);\" : \"\"}\n  const key = getRouteSlotKey(slot);\n  const existingRoot = routeSlotRoots.get(key);\n\n  if (mode === 'hydrate') {\n    if (existingRoot) return true;\n    const root = hydrateRoot(container, element);\n    routeSlotRoots.set(key, root);\n  } else {\n    if (existingRoot) {\n      try { existingRoot.unmount(); } catch (error) {}\n    }\n    const root = createRoot(container);\n    root.render(element);\n    routeSlotRoots.set(key, root);\n  }\n\n  routeSlotDefinitions.set(key, slot);\n  return true;\n}\n\nasync function hydrateInitialRouteSlots() {\n  const slots = Array.isArray(window.__FARM_ROUTE_SLOTS__)\n    ? window.__FARM_ROUTE_SLOTS__\n    : [];\n  let hydrated = false;\n\n  for (const slot of slots) {\n    routeSlotDefinitions.set(getRouteSlotKey(slot), slot);\n    if (!slot.isClientComponent && !slot.shouldHydrate) continue;\n    try {\n      const slotHydrated = await renderRouteSlot(slot, 'hydrate');\n      hydrated = slotHydrated || hydrated;\n      if (slotHydrated) {\n        replayPreHydrationClicks(document.getElementById(slot.containerId));\n      }\n    } catch (error) {\n      console.warn('[Farm.js] Could not hydrate route slot:', slot.name, error);\n    }\n  }\n\n  return hydrated;\n}\n\nasync function renderRouteInterception(pageData) {\n  const slots = Array.isArray(pageData.routeSlots)\n    ? pageData.routeSlots.filter((slot) => slot.interception)\n    : [];\n  if (!pageData.interception || slots.length === 0) return false;\n\n  const previous = new Map();\n  for (const slot of slots) {\n    const key = getRouteSlotKey(slot);\n    previous.set(key, routeSlotDefinitions.get(key) || null);\n    if (!(await renderRouteSlot(slot, 'intercept'))) {\n      return false;\n    }\n  }\n\n  activeRouteInterception = {\n    from: pageData.interception.from,\n    slots,\n    previous,\n  };\n  return true;\n}\n\nasync function clearRouteInterception(destination) {\n  if (!activeRouteInterception) return false;\n  const active = activeRouteInterception;\n  activeRouteInterception = null;\n\n  for (const slot of active.slots) {\n    const key = getRouteSlotKey(slot);\n    const root = routeSlotRoots.get(key);\n    if (root) {\n      try { root.unmount(); } catch (error) {}\n      routeSlotRoots.delete(key);\n    }\n\n    const previous = active.previous.get(key);\n    if (previous && (previous.isClientComponent || previous.shouldHydrate)) {\n      await renderRouteSlot(previous, 'render');\n    } else {\n      const container = document.getElementById(slot.containerId);\n      if (container) container.replaceChildren();\n      if (previous) routeSlotDefinitions.set(key, previous);\n      else routeSlotDefinitions.delete(key);\n    }\n  }\n\n  if (!active.from) return false;\n  const background = new URL(active.from, window.location.origin);\n  return destination === background.pathname + background.search;\n}\n\nfunction applyCanonicalPathFromProps(props) {\n  const canonicalPath = props && typeof props.__farmCanonicalPath === 'string'\n    ? props.__farmCanonicalPath\n    : null;\n  if (!canonicalPath) return;\n  const currentPath = window.location.pathname + window.location.search;\n  if (canonicalPath === currentPath) return;\n  window.history.replaceState({ ...(window.history.state || {}), path: canonicalPath }, '', canonicalPath);\n}\n\nfunction replayPreHydrationClicks(container = null) {\n  if (!container) {\n    markFarmHydrated();\n  } else {\n    container.dataset.farmIslandHydrated = 'true';\n  }\n\n  const queue = Array.isArray(window.__FARM_PREHYDRATION_CLICK_QUEUE__)\n    ? window.__FARM_PREHYDRATION_CLICK_QUEUE__\n    : [];\n  if (queue.length === 0) return;\n\n  const queuedClicks = [];\n  const remainingClicks = [];\n  for (const queuedClick of queue) {\n    const target = queuedClick?.target;\n    if (!container || (target instanceof Node && container.contains(target))) {\n      queuedClicks.push(queuedClick);\n    } else {\n      remainingClicks.push(queuedClick);\n    }\n  }\n  queue.splice(0, queue.length, ...remainingClicks);\n  for (const queuedClick of queuedClicks) {\n    const target = queuedClick?.target;\n    if (!target || typeof target.click !== 'function') continue;\n    if (target.isConnected === false) continue;\n    setTimeout(() => target.click(), 0);\n  }\n}\n\nfunction markFarmHydrated() {\n  window.__FARM_HYDRATED__ = true;\n  document.documentElement.dataset.farmHydrated = 'true';\n}\n\nasync function buildClientHydrationElement(\n  PageComponent,\n  pageProps,\n  loadingModuleOverride,\n) {\n  let element = React.createElement(PageComponent, pageProps);\n  const loadingModulePath = loadingModuleOverride === undefined\n    ? window.__FARM_LOADING_MODULE__\n    : loadingModuleOverride;\n\n  if (loadingModulePath) {\n    try {\n      const loadingModule = await import(/* @vite-ignore */ loadingModulePath);\n      const LoadingComponent = loadingModule?.default;\n      if (LoadingComponent) {\n        const loadingFallback = React.createElement(LoadingComponent, {\n          params: pageProps?.params || {},\n          path: pageProps?.path || window.location.pathname,\n        });\n        element = React.createElement(React.Suspense, { fallback: loadingFallback }, element);\n      }\n    } catch (error) {\n      console.error(\n        '[Farm.js] Loading boundary failed to load and was skipped: ' + loadingModulePath,\n        error,\n      );\n    }\n  }\n\n  return element;\n}\n\nasync function loadLayoutComponents(layouts = []) {\n  const loadedLayouts = [];\n\n  for (const layout of layouts) {\n    if (!layout?.modulePath) continue;\n    try {\n      let LayoutComponent = layoutComponentCache.get(layout.modulePath);\n      if (!LayoutComponent) {\n        const layoutModule = await import(/* @vite-ignore */ layout.modulePath);\n        LayoutComponent = layoutModule.default;\n        if (LayoutComponent) {\n          layoutComponentCache.set(layout.modulePath, LayoutComponent);\n        }\n      }\n      if (LayoutComponent) loadedLayouts.push({ ...layout, Component: LayoutComponent });\n    } catch (error) {\n      // Skipping the layout leaves the client tree different from the server's,\n      // so React discards the server rendered markup for this branch, including\n      // whatever the layout drew. Losing visible UI deserves more than a warning.\n      console.error(\n        '[Farm.js] Layout failed to load and was skipped: ' + layout.modulePath +\n          '. The client tree no longer matches the server, so React will discard the ' +\n          'server rendered markup for this route, including anything this layout renders.',\n        error,\n      );\n    }\n  }\n\n  return loadedLayouts;\n}\n\nfunction wrapWithLoadedLayouts(element, loadedLayouts, params) {\n  let wrapped = element;\n  for (let index = loadedLayouts.length - 1; index >= 0; index--) {\n    const layout = loadedLayouts[index];\n    wrapped = React.createElement(layout.Component, {\n      children: wrapped,\n      params,\n    });\n    wrapped = React.createElement('div', {\n      'data-farm-layout-boundary': 'true',\n      'data-farm-layout-pattern': layout.pattern,\n      style: { display: 'contents' },\n    }, wrapped);\n  }\n  return wrapped;\n}\n\nfunction getCurrentSearchParams() {\n  const url = new URL(window.location.href);\n  return searchParamsToObject(url.searchParams);\n}\n\nfunction parseClientRouteSchema(schema, value, label) {\n  if (!schema || typeof schema.parse !== 'function') {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    throw new Error('Invalid route ' + label + ': ' + (error?.message || String(error)));\n  }\n}\n\nasync function buildRouteComponentProps(pageModule, params, searchParams, path, existingProps) {\n  if (existingProps?.__farmRoutePropsResolved === true) {\n    const revivedProps = reviveDeferredData(\n      existingProps,\n      window.__FARM_DEFERRED_DATA__ || {},\n    );\n    window.__FARM_PROPS__ = revivedProps;\n    return {\n      ...revivedProps,\n      searchParams: Promise.resolve(revivedProps.search ?? revivedProps.searchParams ?? {}),\n      path: revivedProps.path || path,\n    };\n  }\n\n  if (typeof pageModule?.__farmResolveRouteProps === 'function') {\n    const rawProps = {\n      ...(existingProps || {}),\n      params,\n      searchParams: Promise.resolve(searchParams),\n      path,\n    };\n    // Keep top-level route errors inside the router's navigation transaction.\n    // Explicit defer() values can still suspend nested UI after this resolves.\n    return await pageModule.__farmResolveRouteProps(rawProps);\n  }\n\n  const schemas = pageModule?.__farmRouteSchemas;\n  const parsedParams = parseClientRouteSchema(schemas?.params, params, 'params');\n  const parsedSearch = parseClientRouteSchema(schemas?.search, searchParams, 'search');\n\n  return {\n    ...(existingProps || {}),\n    params: parsedParams,\n    search: parsedSearch,\n    searchParams: schemas ? Promise.resolve(parsedSearch) : parsedSearch,\n    path,\n  };\n}\n\nasync function buildWrappedHydrationElement(PageComponent, pageProps, layouts = []) {\n  const loadedLayouts = await loadLayoutComponents(layouts);\n  const pageElement = await buildClientHydrationElement(PageComponent, pageProps);\n  const wrappedTree = wrapWithLoadedLayouts(\n    pageElement,\n    loadedLayouts,\n    pageProps?.params || {},\n  );\n  return wrapWithIntegrationProviders(wrappedTree);\n}\n\nfunction createLayoutPageBoundary(\n  pageShouldHydrate,\n  islandStrategy,\n  pageElement,\n  serverHtml,\n) {\n  const props = {\n    id: '__farm_page__',\n    'data-farm-client': pageShouldHydrate ? 'true' : 'false',\n    'data-farm-layout-client': 'true',\n    'data-farm-island': 'page',\n    'data-farm-island-strategy': islandStrategy || 'load',\n  };\n  if (typeof serverHtml === 'string') {\n    props.suppressHydrationWarning = true;\n    props.dangerouslySetInnerHTML = { __html: serverHtml };\n    return React.createElement('div', props);\n  }\n  return React.createElement('div', props, pageElement);\n}\n\nasync function tryHydrateImportedPage(\n  container,\n  route,\n  params,\n  layouts,\n  useHydrate = false,\n  existingProps = null,\n  signal = null,\n  hydrationOptions = {},\n) {\n  const modulePath = route?.modulePath;\n  if (!modulePath || signal?.aborted) {\n    return false;\n  }\n\n  const pageShouldHydrate = hydrationOptions.pageShouldHydrate !== false;\n  const layoutShouldHydrate = hydrationOptions.layoutShouldHydrate === true;\n  const islandStrategy = hydrationOptions.islandStrategy || route.islandStrategy || 'load';\n  let pageElement = null;\n\n  if (pageShouldHydrate) {\n    let pageModule = pageModuleCache.get(modulePath);\n    if (!pageModule) {\n      pageModule = await import(/* @vite-ignore */ modulePath);\n      pageModuleCache.set(modulePath, pageModule);\n    }\n    if (signal?.aborted || !container?.isConnected) return false;\n\n    const PageComponent = pageModule?.default;\n    if (!PageComponent) return false;\n\n    if (\n      typeof PageComponent === 'function' &&\n      PageComponent.constructor &&\n      PageComponent.constructor.name === 'AsyncFunction'\n    ) {\n      console.warn(\n        '[Farm.js] Skipping hydration for ' + modulePath +\n        ': async server components cannot run in the browser. ' +\n        'Server-rendered HTML is preserved; move interactive UI into a \"use client\" child of a synchronous page.'\n      );\n      return false;\n    }\n\n    currentPageComponent = PageComponent;\n    currentPageProps = await buildRouteComponentProps(\n      pageModule,\n      params,\n      getCurrentSearchParams(),\n      window.location.pathname,\n      existingProps,\n    );\n    pageElement = await buildClientHydrationElement(\n      PageComponent,\n      currentPageProps,\n      hydrationOptions.loadingModulePath,\n    );\n  } else if (layoutShouldHydrate) {\n    currentPageProps = existingProps || { params };\n    const serverPage = document.getElementById('__farm_page__');\n    pageElement = createLayoutPageBoundary(\n      false,\n      islandStrategy,\n      null,\n      typeof hydrationOptions.serverHtml === 'string'\n        ? hydrationOptions.serverHtml\n        : serverPage ? serverPage.innerHTML : '',\n    );\n  }\n  if (signal?.aborted || !container?.isConnected || !pageElement) return false;\n\n  let wrappedElement;\n  if (layoutShouldHydrate) {\n    const loadedLayouts = await loadLayoutComponents(layouts);\n    if (pageShouldHydrate) {\n      pageElement = createLayoutPageBoundary(true, islandStrategy, pageElement);\n    }\n    const wrappedTree = wrapWithLoadedLayouts(pageElement, loadedLayouts, params);\n    wrappedElement = wrapWithIntegrationProviders(wrappedTree);\n  } else if (useHydrate && container?.id === '__farm_page__') {\n    wrappedElement = wrapWithIntegrationProviders(pageElement);\n  } else {\n    wrappedElement = await buildWrappedHydrationElement(\n      currentPageComponent,\n      currentPageProps,\n      layouts,\n    );\n  }\n  if (signal?.aborted || !container?.isConnected) return false;\n\n  ${isolatedHydrationEnabled ? \"wrappedElement = wrapFarmIsolatedClientGraph(React, wrappedElement);\" : \"\"}\n\n  if (useHydrate) {\n    try {\n      reactRoot = hydrateRoot(container, wrappedElement);\n      window.__FARM_REACT_ROOT__ = reactRoot;\n      return true;\n    } catch (error) {\n      appRoot = createRoot(container);\n      appRoot.render(wrappedElement);\n      window.__FARM_REACT_ROOT__ = appRoot;\n      hasClientTakenOver = true;\n      return true;\n    }\n  }\n\n  hasClientTakenOver = true;\n  const existingRoot = appRoot || reactRoot;\n  if (existingRoot && layoutShouldHydrate) {\n    existingRoot.render(wrappedElement);\n    appRoot = existingRoot;\n    reactRoot = null;\n    window.__FARM_REACT_ROOT__ = appRoot;\n    return true;\n  }\n  if (reactRoot) { try { reactRoot.unmount(); } catch (e) {} reactRoot = null; }\n  if (appRoot) { try { appRoot.unmount(); } catch (e) {} appRoot = null; }\n  appRoot = createRoot(container);\n  window.__FARM_REACT_ROOT__ = appRoot;\n  appRoot.render(wrappedElement);\n  return true;\n}\n\nfunction findLayoutBoundary(root, pattern) {\n  const boundaries = root.querySelectorAll\n    ? root.querySelectorAll('[data-farm-layout-boundary=\"true\"]')\n    : [];\n  for (const boundary of boundaries) {\n    if (boundary.getAttribute('data-farm-layout-pattern') === pattern) return boundary;\n  }\n  return null;\n}\n\nfunction readActiveLayoutPatterns() {\n  return Array.from(document.querySelectorAll('[data-farm-layout-boundary=\"true\"]'))\n    .map((element) => element.getAttribute('data-farm-layout-pattern'))\n    .filter(Boolean);\n}\n\nfunction activateFragmentScripts(root) {\n  for (const script of Array.from(root.querySelectorAll?.('script') || [])) {\n    const freshScript = document.createElement('script');\n    for (const attribute of Array.from(script.attributes)) {\n      freshScript.setAttribute(attribute.name, attribute.value);\n    }\n    freshScript.textContent = script.textContent || '';\n    script.replaceWith(freshScript);\n  }\n}\n\nfunction parseNavigationFragment(html) {\n  const template = document.createElement('template');\n  template.innerHTML = html;\n  return template.content;\n}\n\nfunction replaceNavigationBoundary(container, fragment, currentPatterns, nextPatterns) {\n  let sharedCount = 0;\n  while (\n    sharedCount < currentPatterns.length &&\n    sharedCount < nextPatterns.length &&\n    currentPatterns[sharedCount] === nextPatterns[sharedCount]\n  ) {\n    sharedCount++;\n  }\n\n  const fragmentTreeRoot = nextPatterns.length > 0\n    ? findLayoutBoundary(fragment, nextPatterns[0])\n    : fragment.querySelector('#__farm_page__');\n  const currentTarget = sharedCount < currentPatterns.length\n    ? findLayoutBoundary(container, currentPatterns[sharedCount])\n    : container.querySelector('#__farm_page__');\n  const nextTarget = sharedCount < nextPatterns.length\n    ? findLayoutBoundary(fragment, nextPatterns[sharedCount])\n    : fragment.querySelector('#__farm_page__');\n\n  if (!currentTarget || !nextTarget) {\n    ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(container);\" : \"\"}\n    container.replaceChildren(fragment);\n    activateFragmentScripts(container);\n    return container;\n  }\n\n  ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(currentTarget);\" : \"\"}\n  currentTarget.replaceWith(nextTarget);\n  activateFragmentScripts(nextTarget);\n  if (fragmentTreeRoot && fragmentTreeRoot !== nextTarget) fragmentTreeRoot.remove();\n\n  // React's completed streaming markup can include reveal instructions next\n  // to the route tree. Execute those support nodes after the boundary exists.\n  if (fragment.childNodes.length > 0) {\n    const support = document.createElement('div');\n    support.hidden = true;\n    support.dataset.farmFragmentSupport = 'true';\n    support.append(fragment);\n    document.body.appendChild(support);\n    activateFragmentScripts(support);\n    setTimeout(() => support.remove(), 0);\n  }\n  return nextTarget;\n}\n\nlet activeLayoutPatterns = readActiveLayoutPatterns();\nlet activeLayoutShouldHydrate = window.__FARM_LAYOUT_SHOULD_HYDRATE__ === true;\n\n// ====== MANIFEST-DRIVEN HTML-FRAGMENT NAVIGATION ======\n// One page-data response carries both server HTML and the hydration plan.\nasync function renderPage(pageData) {\n  const container = document.getElementById('root');\n  if (!container) return;\n  cancelPendingPageHydration();\n  const destination = window.location.pathname + window.location.search;\n\n  if (pageData.interception) {\n    if (await renderRouteInterception(pageData)) return;\n    window.location.assign(destination);\n    return;\n  }\n\n  if (await clearRouteInterception(destination)) {\n    return;\n  }\n\n  const manifestRoute = findRoute(window.location.pathname)?.route;\n  const renderPlan = pageData.renderPlan || manifestRoute?.renderPlan;\n  const hydrationMode = renderPlan?.hydration;\n  const route = {\n    modulePath: pageData.modulePath,\n    isClientComponent: pageData.isClientComponent === true,\n    pageShouldHydrate:\n      hydrationMode === 'route-island' ||\n      hydrationMode === 'route-and-layout-islands' ||\n      pageData.pageShouldHydrate === true,\n    layoutShouldHydrate:\n      hydrationMode === 'layout-island' ||\n      hydrationMode === 'route-and-layout-islands' ||\n      pageData.layoutShouldHydrate === true,\n    shouldHydrate: pageData.shouldHydrate === true,\n    islandStrategy: renderPlan?.islandStrategy || pageData.islandStrategy || 'load',\n    loadingModulePath: pageData.loadingModulePath,\n  };\n  const params = pageData.props?.params || {};\n  const nextLayoutPatterns = Array.isArray(pageData.fragment?.layoutPatterns)\n    ? pageData.fragment.layoutPatterns\n    : [];\n  const layouts = (pageData.layoutModules || []).map((modulePath, index) => ({\n    modulePath,\n    pattern: nextLayoutPatterns[index] || (index === 0 ? '/' : modulePath),\n  }));\n  const path = window.location.pathname + window.location.search;\n\n  // A legacy server may omit the fragment. Keep one compatibility fallback,\n  // but current servers send HTML in the page-data response and avoid this\n  // second network round trip.\n  const fetchAndSwapHTML = async () => {\n    let fragmentHtml = pageData.fragment?.html;\n    let layoutPatterns = nextLayoutPatterns;\n\n    if (typeof fragmentHtml !== 'string') {\n      const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n      const response = await fetch(path, {\n        headers: createFarmDeploymentRequestHeaders(deploymentId, { 'Accept': 'text/html' }),\n      });\n      if (isFarmDeploymentMismatchResponse(response, deploymentId)) {\n        const error = createFarmDeploymentMismatchError(response, deploymentId || 'unknown');\n        window.dispatchEvent(new CustomEvent('farm:deployment-mismatch', { detail: error }));\n        window.location.assign(path);\n        return false;\n      }\n      const documentHtml = await response.text();\n      const doc = new DOMParser().parseFromString(documentHtml, 'text/html');\n      const nextRoot = doc.getElementById('root');\n      if (!nextRoot) return false;\n      fragmentHtml = nextRoot.innerHTML;\n      layoutPatterns = Array.from(\n        nextRoot.querySelectorAll('[data-farm-layout-boundary=\"true\"]'),\n      ).map((element) => element.getAttribute('data-farm-layout-pattern')).filter(Boolean);\n    }\n\n    const fragment = parseNavigationFragment(fragmentHtml);\n    const nextPage = fragment.querySelector('#__farm_page__');\n    const pageShouldHydrate = route.pageShouldHydrate || route.isClientComponent;\n    const layoutShouldHydrate = route.layoutShouldHydrate;\n    ${\n      isolatedHydrationEnabled\n        ? `const hasIsolatedClientBoundaries = Boolean(\n      fragment.querySelector('farm-client-boundary[data-farm-client-boundary]'),\n    );\n    const shouldHydrate =\n      pageShouldHydrate || layoutShouldHydrate || (route.shouldHydrate && !hasIsolatedClientBoundaries);`\n        : \"const shouldHydrate = route.shouldHydrate || pageShouldHydrate || layoutShouldHydrate;\"\n    }\n\n    // A React-owned layout can update in place. Rendering the same layout\n    // component chain preserves its state while changing only the route child.\n    if (activeLayoutShouldHydrate && layoutShouldHydrate && (appRoot || reactRoot)) {\n      await tryHydrateImportedPage(\n        container,\n        route,\n        params,\n        layouts,\n        false,\n        pageData.props,\n        null,\n        {\n          pageShouldHydrate,\n          layoutShouldHydrate,\n          islandStrategy: route.islandStrategy,\n          serverHtml: nextPage ? nextPage.innerHTML : '',\n          loadingModulePath: route.loadingModulePath,\n        },\n      );\n    } else {\n      ${isolatedHydrationEnabled ? \"let isolatedHydrationScope = container;\" : \"\"}\n      if (activeLayoutShouldHydrate) {\n        ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(container);\" : \"\"}\n        if (appRoot) { try { appRoot.unmount(); } catch (error) {} appRoot = null; }\n        if (reactRoot) { try { reactRoot.unmount(); } catch (error) {} reactRoot = null; }\n        container.replaceChildren(fragment);\n        activateFragmentScripts(container);\n      } else {\n        if (appRoot) { try { appRoot.unmount(); } catch (error) {} appRoot = null; }\n        if (reactRoot) { try { reactRoot.unmount(); } catch (error) {} reactRoot = null; }\n        delete window.__FARM_REACT_ROOT__;\n        ${\n          isolatedHydrationEnabled\n            ? \"isolatedHydrationScope = replaceNavigationBoundary(container, fragment, activeLayoutPatterns, layoutPatterns) || container;\"\n            : \"replaceNavigationBoundary(container, fragment, activeLayoutPatterns, layoutPatterns);\"\n        }\n      }\n\n      const hydrationController = new AbortController();\n      if (\n        shouldHydrate${\n          isolatedHydrationEnabled\n            ? \" || (hasIsolatedClientBoundaries && !layoutShouldHydrate)\"\n            : \"\"\n        }\n      ) {\n        pendingPageHydrationController = hydrationController;\n      }\n      if (shouldHydrate) {\n        const hydrationContainer = layoutShouldHydrate\n          ? container\n          : document.getElementById('__farm_page__') || container;\n        const scheduledHydration = scheduleFarmIslandHydration({\n          container: hydrationContainer,\n          strategy: route.islandStrategy,\n          signal: hydrationController.signal,\n          hydrate: async () => {\n            await tryHydrateImportedPage(\n              hydrationContainer,\n              route,\n              params,\n              layouts,\n              true,\n              pageData.props,\n              hydrationController.signal,\n              {\n                pageShouldHydrate,\n                layoutShouldHydrate,\n                islandStrategy: route.islandStrategy,\n                loadingModulePath: route.loadingModulePath,\n              },\n            );\n          },\n        });\n        if (route.islandStrategy === 'load') {\n          await scheduledHydration;\n        } else {\n          void scheduledHydration.catch((error) => {\n            console.warn('[Farm.js] Deferred island hydration failed:', error);\n          });\n        }\n      }\n      ${\n        isolatedHydrationEnabled\n          ? `if (hasIsolatedClientBoundaries && !layoutShouldHydrate) {\n        await hydrateFarmIsolatedClientBoundaries(\n          isolatedHydrationScope,\n          hydrationController.signal,\n        );\n        if (hydrationController.signal.aborted) return;\n      }`\n          : \"\"\n      }\n    }\n\n    activeLayoutPatterns = layoutPatterns;\n    activeLayoutShouldHydrate = layoutShouldHydrate;\n    window.__FARM_LOADING_MODULE__ = route.loadingModulePath || null;\n    return true;\n  };\n\n  try {\n    await fetchAndSwapHTML();\n  } catch (error) {\n    console.error('[Farm.js] Render error:', error);\n    // Fallback to full navigation\n    window.location.href = path;\n  }\n}\n\n// Set up the navigation handler\nspaRouter.setNavigationHandler(renderPage);\n\nasync function hydrate() {\n  await farmClientRuntime.start();\n\n  if (isFarmDocsSearchPage()) {\n    await mountFarmDocsSearch();\n  }\n\n  if (await hydrateFarmDocsAdapterRuntime()) {\n    return;\n  }\n\n  const rootContainer = document.getElementById('root')\n  \n  if (!rootContainer) {\n    console.error('[Farm.js] Root container not found')\n    return\n  }\n\n  try {\n    // Check if this is a client component (set by SSR)\n    const isClientComponent = window.__FARM_IS_CLIENT__ === true;\n    const modulePath = window.__FARM_PAGE_MODULE__;\n    ${\n      isolatedHydrationEnabled\n        ? `const hasIsolatedClientBoundaries =\n      window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true ||\n      Boolean(rootContainer.querySelector('farm-client-boundary[data-farm-client-boundary]'));`\n        : \"\"\n    }\n\n    let pageProps = normalizeServerProps(window.__FARM_PROPS__);\n    applyCanonicalPathFromProps(pageProps);\n\n    const pageShouldHydrate =\n      typeof window.__FARM_PAGE_SHOULD_HYDRATE__ === 'boolean'\n        ? window.__FARM_PAGE_SHOULD_HYDRATE__\n        : isClientComponent ||\n          findRoute(window.location.pathname)?.route?.shouldHydrate === true;\n    const layoutShouldHydrate = window.__FARM_LAYOUT_SHOULD_HYDRATE__ === true;\n    const shouldHydrate =\n      window.__FARM_SHOULD_HYDRATE__ === true ||\n      pageShouldHydrate ||\n      layoutShouldHydrate;\n    const hydratedSlots = await hydrateInitialRouteSlots();\n    ${\n      isolatedHydrationEnabled\n        ? `if (hasIsolatedClientBoundaries && !pageShouldHydrate && !layoutShouldHydrate) {\n      const hydrationController = new AbortController();\n      pendingPageHydrationController = hydrationController;\n      await hydrateFarmIsolatedClientBoundaries(rootContainer, hydrationController.signal);\n      if (hydrationController.signal.aborted) return;\n      return;\n    }`\n        : \"\"\n    }\n    if (!shouldHydrate) {\n      if (hydratedSlots) replayPreHydrationClicks();\n      return\n    }\n    if (!modulePath) {\n      console.error('[Farm.js] No page module path found')\n      return\n    }\n\n    // Get props - either from server-injected props or by matching the current URL\n    if (!pageProps || !pageProps.params || Object.keys(pageProps.params).length === 0) {\n      // Extract params from URL using manifest route matching (fallback)\n      const pathname = window.location.pathname;\n      const foundRoute = findRoute(pathname);\n      pageProps = normalizeServerProps({\n        params: foundRoute?.params || {},\n        search: getCurrentSearchParams(),\n        searchParams: getCurrentSearchParams(),\n        path: pathname,\n      });\n    }\n    currentPageProps = pageProps;\n\n    // Prefer the exact root-to-leaf layout chain selected by the server. The\n    // manifest lookup remains a fallback for generated/static responses.\n    const layouts = Array.isArray(window.__FARM_LAYOUTS__)\n      ? window.__FARM_LAYOUTS__\n      : findLayouts(window.location.pathname);\n    const pageContainer = layoutShouldHydrate\n      ? rootContainer\n      : document.getElementById('__farm_page__') || rootContainer;\n\n    if (!pageContainer) {\n      return\n    }\n\n    const currentRoute = findRoute(window.location.pathname)?.route;\n    const islandStrategy = window.__FARM_ISLAND_STRATEGY__ || currentRoute?.islandStrategy || 'load';\n    pageContainer.dataset.farmIsland = 'page';\n    pageContainer.dataset.farmIslandStrategy = islandStrategy;\n\n    const hydrationPathname = window.location.pathname;\n    const hydrationController = new AbortController();\n    pendingPageHydrationController = hydrationController;\n    try {\n      const pageHydration = scheduleFarmIslandHydration({\n        container: pageContainer,\n        strategy: islandStrategy,\n        signal: hydrationController.signal,\n        hydrate: async () => {\n          if (\n            hydrationController.signal.aborted ||\n            !pageContainer.isConnected ||\n            window.location.pathname !== hydrationPathname\n          ) {\n            return;\n          }\n\n          const hydrationSession = await farmClientRuntime.beginHydration({\n            container: pageContainer,\n            mode: shouldHydrate ? 'hydrate' : 'render',\n          });\n\n          let hydrated = false;\n          try {\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) {\n              await farmClientRuntime.failHydration(\n                hydrationSession,\n                new DOMException('Route hydration was cancelled', 'AbortError'),\n              );\n              return;\n            }\n            hydrated = await tryHydrateImportedPage(\n              pageContainer,\n              { modulePath },\n              currentPageProps.params || {},\n              layouts,\n              shouldHydrate,\n              currentPageProps,\n              hydrationController.signal,\n              {\n                pageShouldHydrate,\n                layoutShouldHydrate,\n                islandStrategy,\n              },\n            );\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) {\n              await farmClientRuntime.failHydration(\n                hydrationSession,\n                new DOMException('Route hydration was cancelled', 'AbortError'),\n              );\n              return;\n            }\n            await farmClientRuntime.completeHydration(hydrationSession);\n          } catch (error) {\n            await farmClientRuntime.failHydration(hydrationSession, error);\n            throw error;\n          }\n\n          if (hydrated) {\n            // The scheduler owns queue draining and exactly-once click replay.\n            markFarmHydrated();\n            return;\n          }\n        },\n      });\n      ${\n        isolatedHydrationEnabled\n          ? `const isolatedHydration =\n        hasIsolatedClientBoundaries &&\n        !layoutShouldHydrate\n          ? hydrateFarmIsolatedClientBoundaries(rootContainer, hydrationController.signal)\n          : Promise.resolve();\n      await Promise.all([pageHydration, isolatedHydration]);`\n          : \"await pageHydration;\"\n      }\n    } finally {\n      if (pendingPageHydrationController === hydrationController) {\n        pendingPageHydrationController = null;\n      }\n    }\n  } catch (error) {\n    console.error('[Farm.js] Hydration error:', error)\n  }\n}\n\nif (document.readyState === 'loading') {\n  document.addEventListener('DOMContentLoaded', hydrate)\n} else {\n  hydrate()\n}\n\n// ====== EVENT DELEGATION FOR LINKS ======\n// This catches all link clicks even without React hydration\n// This is essential for server component pages where React doesn't hydrate\n\nfunction isModifierEvent(e) {\n  return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);\n}\n\nfunction hasAbsoluteNavigationHref(href) {\n  return /^[a-zA-Z][a-zA-Z\\\\d+.-]*:/.test(href) || href.startsWith('//');\n}\n\ndocument.addEventListener('click', function(event) {\n  if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n  // Find the closest anchor element\n  let target = event.target;\n  while (target && target.tagName !== 'A') {\n    target = target.parentElement;\n  }\n  \n  if (!target || target.tagName !== 'A') return;\n  \n  const href = target.getAttribute('href');\n  if (!href) return;\n  if (target.hasAttribute('download')) return;\n  \n  // Leave absolute URLs and non-HTTP schemes to the browser.\n  if (hasAbsoluteNavigationHref(href)) return;\n  \n  // Don't intercept hash-only links\n  if (href.startsWith('#')) return;\n  \n  // Don't intercept if target is set to open in new window\n  const linkTarget = target.getAttribute('target');\n  if (linkTarget && linkTarget !== '_self') return;\n  \n  // Don't intercept modifier clicks (Ctrl+Click = new tab)\n  if (isModifierEvent(event)) return;\n  \n  // Don't intercept non-left clicks\n  if (event.button !== 0) return;\n  \n  // Don't intercept if already prevented\n  if (event.defaultPrevented) return;\n  \n  // Use SPA router\n  event.preventDefault();\n  const replace = target.hasAttribute('data-replace');\n  const scroll = !target.hasAttribute('data-no-scroll');\n  const viewTransitionValue = target.getAttribute('data-view-transition');\n  const viewTransition = viewTransitionValue === 'auto'\n    ? 'auto'\n    : viewTransitionValue === 'true';\n  \n  spaRouter.navigate(href, { replace, scroll, viewTransition });\n});\n\nif (import.meta.hot) {\n  import.meta.hot.on('vite:beforeUpdate', () => {\n    // Clear module cache on HMR to pick up changes\n    pageModuleCache.clear();\n  })\n}\n`;\n}\n\nfunction generateServerCode(): string {\n  return `\nexport { FarmApp, createFarmApp } from './app'\nexport { ServerRenderer } from './server/renderer'\nexport { RouteManager } from './routing/route-manager'\nexport * from './types'\n`;\n}\n\nfunction generateClientManifest(bundle: any): Record<string, any> {\n  const manifest: Record<string, any> = {};\n\n  for (const [fileName, chunk] of Object.entries(bundle)) {\n    if ((chunk as any).type === \"chunk\") {\n      manifest[fileName] = {\n        id: fileName,\n        chunks: [fileName],\n        name: (chunk as any).name || fileName,\n      };\n    }\n  }\n\n  return manifest;\n}\n\nexport async function defineConfig(config: FarmVitePluginOptions = {}): Promise<UserConfig> {\n  const tailwindcss = (await import(\"@tailwindcss/vite\")).default;\n  const appRoot = path.resolve(config.root || process.cwd());\n  if (config.extends?.length) {\n    const { config: layeredConfig } = await import(\"./layers\").then(({ resolveFarmLayers }) =>\n      resolveFarmLayers(config, {\n        root: appRoot,\n        mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      }),\n    );\n    config = layeredConfig;\n  }\n  config.renderer = resolveFarmRenderer(config.renderer);\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, appRoot, {\n    ssr: true,\n  });\n  // Node.js built-in module stubs for browser\n  const nodeBuiltinStubs: Record<string, string> = {\n    \"node:string_decoder\":\n      \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n    \"node:buffer\":\n      \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n    \"node:stream\":\n      \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n    \"node:util\":\n      \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n    \"node:events\":\n      \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n    \"node:path\":\n      \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n    \"node:fs\": \"data:text/javascript,export default {};\",\n    \"node:url\":\n      \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n    \"node:crypto\":\n      \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n    \"node:os\":\n      \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n    \"node:child_process\": \"data:text/javascript,export default {};\",\n    \"node:http\": \"data:text/javascript,export default {};\",\n    \"node:https\": \"data:text/javascript,export default {};\",\n    \"node:net\": \"data:text/javascript,export default {};\",\n    \"node:tls\": \"data:text/javascript,export default {};\",\n    \"node:zlib\": \"data:text/javascript,export default {};\",\n    \"node:async_hooks\":\n      \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n    \"node:worker_threads\": \"data:text/javascript,export default {};\",\n    \"node:perf_hooks\":\n      \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n    string_decoder:\n      \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n    buffer:\n      \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n    stream:\n      \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n    util: \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n    events:\n      \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n    path: \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n    fs: \"data:text/javascript,export default {};\",\n    url: \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n    crypto:\n      \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n    os: \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n    child_process: \"data:text/javascript,export default {};\",\n    http: \"data:text/javascript,export default {};\",\n    https: \"data:text/javascript,export default {};\",\n    net: \"data:text/javascript,export default {};\",\n    tls: \"data:text/javascript,export default {};\",\n    zlib: \"data:text/javascript,export default {};\",\n    async_hooks:\n      \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n    worker_threads: \"data:text/javascript,export default {};\",\n    perf_hooks:\n      \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n  };\n\n  // Plugin to intercept __vite-browser-external requests\n  const viteBrowserExternalPlugin = {\n    name: \"farm:browser-external-stub\",\n    enforce: \"pre\" as const,\n    resolveId(id: string) {\n      // Handle Vite's browser external markers\n      if (id.includes(\"__vite-browser-external:\")) {\n        const moduleName = id.replace(/__vite-browser-external:/, \"\");\n        const stub = nodeBuiltinStubs[moduleName];\n        if (stub) return stub;\n        // Generic stub for unknown node modules\n        return \"data:text/javascript,export default {};\";\n      }\n      // Handle direct node: imports\n      if (id.startsWith(\"node:\")) {\n        const stub = nodeBuiltinStubs[id];\n        if (stub) return stub;\n        return \"data:text/javascript,export default {};\";\n      }\n      return null;\n    },\n  };\n\n  // Custom logger to replace Vite's default logs with Farm.js branding\n  const pc = createCliColors();\n  let serverStarted = false;\n  let startTime = Date.now();\n\n  const farmLogger = {\n    info: (msg: string) => {\n      // Suppress ALL Vite startup messages - we print our own Farm.js branded output\n      if (\n        msg.includes(\"VITE\") ||\n        msg.includes(\"vite\") ||\n        msg.includes(\"ready in\") ||\n        msg.includes(\"Local:\") ||\n        msg.includes(\"Network:\") ||\n        msg.includes(\"➜\") ||\n        msg.includes(\"Port\") ||\n        msg.includes(\"trying another\")\n      ) {\n        return;\n      }\n      // Pass through other info messages\n      console.log(msg);\n    },\n    warn: (msg: string) => console.warn(pc.yellow(msg)),\n    warnOnce: (msg: string) => console.warn(pc.yellow(msg)),\n    error: (msg: string) => console.error(pc.red(msg)),\n    clearScreen: () => {},\n    hasErrorLogged: () => false,\n    hasWarned: false,\n  };\n\n  // Plugin to print Farm.js branding after server starts\n  const farmBrandingPlugin = {\n    name: \"farm:branding\",\n    enforce: \"pre\" as const,\n    configureServer(server: ViteDevServer) {\n      startTime = Date.now();\n\n      const originalListen = server.listen.bind(server);\n      server.listen = async (port?: number, ...args: any[]) => {\n        const result = await originalListen(port, ...args);\n        if (!serverStarted) {\n          serverStarted = true;\n          const elapsed = Date.now() - startTime;\n          const address = server.httpServer?.address();\n          const resolvedPort =\n            typeof address === \"object\" && address\n              ? address.port\n              : server.config.server.port || port || 3000;\n          const hostConfig = server.config.server.host;\n          const isExposed = hostConfig === true || hostConfig === \"0.0.0.0\";\n\n          console.log(\"\");\n          console.log(\n            `  ${pc.bold(pc.green(\"Farm.js\"))} ${pc.dim(`v${FARM_VERSION}`)} ${pc.dim(`ready in ${elapsed}ms`)}`,\n          );\n          console.log(\"\");\n          console.log(\n            `  ${pc.dim(\"➜\")}  ${pc.bold(\"Local:\")}   ${pc.cyan(`http://localhost:${resolvedPort}/`)}`,\n          );\n          if (isExposed) {\n            // Get actual network address\n            const os = require(\"os\");\n            const interfaces = os.networkInterfaces();\n            for (const name of Object.keys(interfaces)) {\n              for (const iface of interfaces[name] || []) {\n                if (iface.family === \"IPv4\" && !iface.internal) {\n                  console.log(\n                    `  ${pc.dim(\"➜\")}  ${pc.bold(\"Network:\")} ${pc.cyan(`http://${iface.address}:${resolvedPort}/`)}`,\n                  );\n                  break;\n                }\n              }\n            }\n          } else {\n            console.log(\n              `  ${pc.dim(\"➜\")}  ${pc.bold(\"Network:\")} ${pc.dim(\"use --host to expose\")}`,\n            );\n          }\n          console.log(\"\");\n        }\n        return result;\n      };\n    },\n  };\n\n  return {\n    plugins: [\n      createFarmThemeCssPlugin(config.theme, config.basePath),\n      tailwindcss(),\n      ...(rendererVitePlugins as any[]),\n      viteBrowserExternalPlugin,\n      farmI18nClientBridgePlugin(),\n      farmPlugin(config),\n      farmEnvironmentFunctionsPlugin(),\n      farmBrandingPlugin,\n    ],\n    customLogger: farmLogger,\n    clearScreen: false,\n    optimizeDeps: {\n      ...createFarmClientOptimizeDepsConfig(\n        createFarmClientOptimizeDepsEntries(\n          appRoot,\n          getFarmAppDirectories({ ...config, root: appRoot }),\n        ),\n        config.renderer,\n      ),\n      // Pre-bundle every framework client-runtime entry with the renderer. Without\n      // this, Vite can discover a linked Farm entry after the page has loaded,\n      // regenerate the optimizer browser hash, and leave the browser runtime\n      // holding a different renderer instance from a client component.\n      // Exclude server-side packages from browser bundling\n      exclude: [\n        \"@farm.js/core/server\",\n        \"@farm.js/core/api\",\n        \"@farm.js/core/middleware\",\n        \"@farm.js/core/config\",\n        \"nitro\",\n        \"h3\",\n        \"vite\",\n        \"esbuild\",\n        \"rollup\",\n        \"fsevents\",\n        \"nf3\",\n        \"better-call\",\n        \"zod\",\n        \"supports-color\",\n        \"node-fetch\",\n        \"consola\",\n        \"mock-aws-s3\",\n        \"aws-sdk\",\n        \"nock\",\n      ],\n    },\n    ssr: {\n      noExternal: [\"farm\", \"@farm.js/core\"],\n      // Externalize the renderer to prevent multiple runtime instances during SSR.\n      external: [...(config.renderer.dedupe || [])],\n    },\n    resolve: {\n      // Ensure one renderer instance across application and framework modules.\n      dedupe: [...(config.renderer.dedupe || [])],\n      // Stub out problematic server-only modules during dev mode\n      alias: {\n        ...getFarmLayerAliases(config.layers),\n        ...createFarmSourceAlias(appRoot, config.srcDir),\n        // Nitro internals that should not be resolved in browser\n        \"supports-color\":\n          \"data:text/javascript,export default false; export const supportsColor = false; export const stdout = false; export const stderr = false;\",\n        \"@poppinss/dumper\": \"data:text/javascript,export default {};\",\n        \"@poppinss/dumper/html\":\n          \"data:text/javascript,export const createScript = () => ''; export const createStyleSheet = () => '';\",\n        \"consola/basic\":\n          \"data:text/javascript,export default { log: console.log, info: console.info, warn: console.warn, error: console.error };\",\n        youch:\n          \"data:text/javascript,export default class Youch { toJSON() { return {}; } toHTML() { return ''; } };\",\n        // Add all node stubs to alias as well\n        ...nodeBuiltinStubs,\n      },\n    },\n    define: {\n      __FARM_DEV__: JSON.stringify(process.env.NODE_ENV === \"development\"),\n      __FARM_API_BASE_URL__: JSON.stringify(getFarmAPIBaseURLDefine(config)),\n      __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),\n    },\n  };\n}\n","import type { PluginRoutes, PluginRoutesFactory } from \"./api/route\";\n// Plugin factories must emit declarations through public exports, never bundled\n// declaration chunk paths, even when they only import @farm.js/core/plugin.\nexport type { PluginRoutes, PluginRoutesFactory, RouteDefinition } from \"./api/route\";\nimport type { FarmConfig, FarmRequest, FarmResponse } from \"./types\";\nimport type { ViteDevServer } from \"vite\";\nimport type { FarmClientPlugin } from \"./client/plugin\";\nimport { getResolvedEnv, type ResolvedFarmEnv } from \"./env\";\nimport {\n  clearRequestContext,\n  deleteRequestContext,\n  getRequestContext,\n  getRequestContextSnapshot,\n  hasRequestContext,\n  setRequestContext,\n} from \"./request-context\";\nimport { getFarmPluginIntegrationContext } from \"./plugin-integration-context\";\n\ntype MaybePromise<T> = T | Promise<T>;\n/** @internal Marks a Node response whose intercepted end is awaiting response hooks. */\nexport const FARM_NODE_RESPONSE_END_PENDING = Symbol.for(\"farm.nodeResponseEndPending\");\ndeclare const FARM_PLUGIN_INTEGRATION_INSTANCE: unique symbol;\ndeclare const FARM_PLUGIN_INTEGRATION_BOUND: unique symbol;\n\nexport interface FarmPluginIntegrationContext<TInstance = unknown> {\n  /** Key used to register the integration in farm.config.ts. */\n  readonly key: string;\n  readonly category: string;\n  readonly type: string;\n  readonly instance: TInstance;\n  readonly serverRuntime: boolean;\n}\n\nexport class FarmRuntimeShutdownError extends Error {\n  readonly errors: readonly unknown[];\n\n  constructor(message: string, errors: readonly unknown[]) {\n    super(message);\n    this.name = \"FarmRuntimeShutdownError\";\n    this.errors = errors;\n  }\n}\n\nexport interface PluginRequestContext {\n  set: (\n    target: FarmRequest | Request,\n    key: string,\n    value: any,\n    options?: { exposeToPage?: boolean },\n  ) => void;\n  get: <T = any>(target: FarmRequest | Request, key: string) => T | undefined;\n  has: (target: FarmRequest | Request, key: string) => boolean;\n  delete: (target: FarmRequest | Request, key: string) => boolean;\n  clear: (target: FarmRequest | Request) => void;\n  getAll: (target: FarmRequest | Request, options?: { exposedOnly?: boolean }) => Map<string, any>;\n}\n\nexport interface FarmRequestStore {\n  set(key: string, value: unknown, options?: { exposeToPage?: boolean }): void;\n  get<T = unknown>(key: string): T | undefined;\n  has(key: string): boolean;\n  delete(key: string): boolean;\n  clear(): void;\n  snapshot(options?: { exposedOnly?: boolean }): Map<string, unknown>;\n}\n\nexport interface FarmPluginContext<TIntegrationInstance = unknown> {\n  config: FarmConfig;\n  viteServer?: ViteDevServer;\n  isDev: boolean;\n  isProd: boolean;\n  /** The owning integration when this plugin is contributed through `integration.plugins`. */\n  readonly integration?: Readonly<FarmPluginIntegrationContext<TIntegrationInstance>>;\n  /** Register resource cleanup that must run when the application runtime closes. */\n  lifecycle: FarmPluginLifecycle;\n  /** @deprecated Use `ctx.req` inside request hooks. */\n  requestContext: PluginRequestContext;\n}\n\ntype FarmPluginHookContext<\n  TContext,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = TIntegrationBound extends true\n  ? Omit<TContext, \"integration\"> & {\n      /** The owning integration bound by `definePlugin.forIntegration<T>()`. */\n      readonly integration: Readonly<FarmPluginIntegrationContext<TIntegrationInstance>>;\n    }\n  : TContext;\n\nexport interface FarmPluginLifecycle {\n  /**\n   * Register a database, storage, queue, or other resource disposer.\n   * Disposers run once in reverse registration order after plugin shutdown hooks.\n   */\n  onShutdown(dispose: () => void | Promise<void>): () => void;\n}\n\nexport interface FarmRequestPluginContext<\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  /** Request-scoped values for the current hook invocation. */\n  readonly req: FarmRequestStore;\n}\n\nexport interface RouteDiscoveredPayload {\n  kind: \"page\" | \"layout\";\n  pattern: string;\n  modulePath: string;\n}\n\nexport interface RoutesGeneratedPayload {\n  routes: RouteDiscoveredPayload[];\n  pageCount: number;\n  layoutCount: number;\n}\n\nexport interface MiddlewareDiscoveredPayload {\n  path: string;\n  filePath: string;\n  handlerCount: number;\n}\n\nexport interface APIRouteDiscoveredPayload {\n  path: string;\n  filePath: string;\n  methods: string[];\n}\n\nexport interface RouteMatchPayload {\n  pathname: string;\n  method?: string;\n}\n\nexport interface RouteMatchResultPayload {\n  pathname: string;\n  matched: boolean;\n  routePattern: string | null;\n  params: Record<string, string>;\n  layoutPatterns: string[];\n}\n\nexport interface RenderLifecyclePayload {\n  pathname: string;\n  method: string;\n  routePattern: string | null;\n  params: Record<string, string>;\n}\n\nexport interface APIHandlerLifecyclePayload {\n  pathname: string;\n  method: string;\n  routePath?: string;\n}\n\nexport interface ErrorLifecyclePayload {\n  phase: string;\n  error: unknown;\n  meta?: Record<string, unknown>;\n}\n\nexport interface HMRUpdatePayload {\n  file: string;\n  modules: string[];\n}\n\nexport interface BundleLifecyclePayload {\n  root: string;\n  preset: string;\n  universal: boolean;\n  distDir: string;\n  outputDir?: string;\n}\n\nexport interface BundleResultPayload extends BundleLifecyclePayload {\n  success: boolean;\n}\n\nexport interface NitroBuildLifecyclePayload {\n  root: string;\n  preset: string;\n  distDir: string;\n  outputDir: string;\n}\n\nexport interface ShutdownPayload {\n  reason: string;\n}\n\nexport type FarmPluginRuntimeKind =\n  | \"request\"\n  | \"page\"\n  | \"api\"\n  | \"action\"\n  | \"integration\"\n  | \"docs\"\n  | \"asset\"\n  | (string & {});\n\nexport interface FarmPluginRouteRuntimePayload {\n  pathname: string;\n  pattern?: string | null;\n  params?: Record<string, string>;\n}\n\nexport interface FarmPluginSetupContext<\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  env: ResolvedFarmEnv;\n}\n\nexport interface FarmPluginStateContext<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  state: TState;\n}\n\nexport interface FarmPluginRuntimeBaseEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> extends FarmPluginStateContext<TState, TIntegrationInstance> {\n  request: Request;\n  /** Request-scoped values shared by plugin hooks. */\n  req: FarmRequestStore;\n  kind: FarmPluginRuntimeKind;\n  route?: FarmPluginRouteRuntimePayload;\n  signal: AbortSignal;\n  waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginRuntimeContextEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> = FarmPluginRuntimeBaseEvent<TState, TIntegrationInstance>;\n\nexport interface FarmPluginRuntimeBeforeEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBaseEvent<TState, TIntegrationInstance> {\n  ctx: Readonly<TRequestContext>;\n}\n\nexport interface FarmPluginRuntimeAfterEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance> {\n  response: Response;\n  durationMs: number;\n}\n\nexport interface FarmPluginRuntimeErrorEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance> {\n  error: unknown;\n  durationMs: number;\n}\n\nexport type FarmPluginRuntimeStartEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> = FarmPluginStateContext<TState, TIntegrationInstance>;\n\nexport interface FarmPluginRuntimeCloseEvent<TState = unknown, TIntegrationInstance = unknown>\n  extends FarmPluginStateContext<TState, TIntegrationInstance>, ShutdownPayload {}\n\ntype FarmPluginContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmRequestPluginContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmRequestPluginContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginSetupContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginSetupContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginStateContextFor<\n  TState,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginStateContext<TState, TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginRuntimeEventFor<\n  TEvent,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<TEvent, TIntegrationInstance, TIntegrationBound>;\n\nexport interface FarmPluginRuntimeHooks<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  start?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeStartEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n  context?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeContextEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<TRequestContext>;\n  before?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<Request | Response | void>;\n  after?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeAfterEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<Response | void>;\n  error?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeErrorEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n  close?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeCloseEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginRuntimeRequestOptions {\n  kind?: FarmPluginRuntimeKind;\n  route?: FarmPluginRouteRuntimePayload;\n  waitUntil?: (promise: Promise<unknown>) => void;\n}\n\nexport type FarmPluginRuntimeRequestHandler = (request: Request) => MaybePromise<Response>;\n\nexport interface FarmPluginRuntimeSession {\n  request: Request;\n  response?: Response;\n  ctx: Readonly<Record<string, unknown>>;\n  startedAt: number;\n  options: FarmPluginRuntimeRequestOptions;\n  waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginDiscoveredRoute =\n  | RouteDiscoveredPayload\n  | ({ kind: \"middleware\" } & MiddlewareDiscoveredPayload)\n  | ({ kind: \"api\" } & APIRouteDiscoveredPayload);\n\nexport interface FarmPluginRouterHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  discovered?(\n    route: FarmPluginDiscoveredRoute,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  generated?(\n    routes: RoutesGeneratedPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  before?(\n    route: RouteMatchPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  after?(\n    result: RouteMatchResultPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginRenderHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  before?(\n    render: RenderLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  html?(\n    html: string,\n    render: RenderLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<string | void>;\n}\n\nexport interface FarmPluginBuildHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  before?(\n    bundle: BundleLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  configure?(\n    buildConfig: any,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<any>;\n  after?(\n    result: BundleResultPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginDevHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  server?(\n    viteServer: ViteDevServer,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  update?(\n    update: HMRUpdatePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginClientConfig<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPlugin<TState, TPublic> {\n  /** Explicitly public, JSON-safe data embedded in the browser bundle. */\n  public?: TPublic;\n}\n\nexport interface FarmPlugin<\n  TState = any,\n  TRequestContext extends object = Record<string, unknown>,\n  TClientState = any,\n  TClientPublic = any,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n  TRoutes extends PluginRoutes = PluginRoutes,\n> {\n  name: string;\n  version?: string;\n  enforce?: \"pre\" | \"post\";\n  /** Declarative API routes, mounted through the normal dev and production API pipeline. */\n  routes?: PluginRoutesFactory<TRoutes>;\n\n  /** Transform Farm config before the development or production pipeline is created. */\n  configure?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => MaybePromise<FarmConfig | void>;\n  /** Initialize private plugin state once for this plugin manager. */\n  setup?: (\n    context: FarmPluginSetupContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => MaybePromise<TState>;\n\n  runtime?: FarmPluginRuntimeHooks<\n    TState,\n    TRequestContext,\n    TIntegrationInstance,\n    TIntegrationBound\n  >;\n  router?: FarmPluginRouterHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  render?: FarmPluginRenderHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  build?: FarmPluginBuildHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  dev?: FarmPluginDevHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  /** Optional browser lifecycle for this logical plugin. */\n  client?: FarmPluginClientConfig<TClientState, TClientPublic>;\n\n  /** @internal Carries the expected integration instance type without runtime data. */\n  readonly [FARM_PLUGIN_INTEGRATION_INSTANCE]?: (instance: TIntegrationInstance) => void;\n  /** @internal Prevents integration-bound plugins from being registered globally. */\n  readonly [FARM_PLUGIN_INTEGRATION_BOUND]?: TIntegrationBound;\n\n  /** @deprecated Use `setup` instead. */\n  init?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `runtime.start` instead. */\n  ready?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `dev.server` instead. */\n  devServerCreated?: (\n    viteServer: ViteDevServer,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use `configure` instead. */\n  config?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => FarmConfig | Promise<FarmConfig>;\n  configResolved?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.before` instead. */\n  buildStart?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.after` instead. */\n  buildEnd?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use `router.discovered` instead. */\n  routeDiscovered?: (\n    route: RouteDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.generated` instead. */\n  routesGenerated?: (\n    routes: RoutesGeneratedPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.discovered` instead. */\n  middlewareDiscovered?: (\n    middleware: MiddlewareDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.discovered` instead. */\n  apiRouteDiscovered?: (\n    route: APIRouteDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.before` instead. */\n  beforeRouteMatch?: (\n    route: RouteMatchPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.after` instead. */\n  afterRouteMatch?: (\n    result: RouteMatchResultPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `render.before` instead. */\n  beforeRender?: (\n    render: RenderLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `render.html` instead. */\n  afterRender?: (\n    html: string,\n    render: RenderLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => string | Promise<string> | void | Promise<void>;\n  /** @deprecated Use `runtime.before` instead. */\n  beforeApiHandler?: (\n    request: Request,\n    api: APIHandlerLifecyclePayload,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => Request | Promise<Request> | void | Promise<void>;\n  /** @deprecated Use `runtime.after` instead. */\n  afterApiHandler?: (\n    response: Response,\n    api: APIHandlerLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => Response | Promise<Response> | void | Promise<void>;\n  onError?: (\n    error: ErrorLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `dev.update` instead. */\n  hmrUpdate?: (\n    update: HMRUpdatePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.before` instead. */\n  beforeBundle?: (\n    bundle: BundleLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.after` instead. */\n  afterBundle?: (\n    result: BundleResultPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.configure` instead. */\n  beforeNitroBuild?: (\n    nitroConfig: any,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => any | Promise<any>;\n  afterNitroBuild?: (\n    payload: NitroBuildLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `runtime.close` instead. */\n  shutdown?: (\n    payload: ShutdownPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use the Web Request based `runtime.before` hook instead. */\n  beforeRequest?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use the Web Response based `runtime.after` hook instead. */\n  afterResponse?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  // Transform hooks\n  /** @deprecated Use `render.html` instead. */\n  transformHTML?: (\n    html: string,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => string | Promise<string>;\n  /** @deprecated Use `render.before` or `render.html` instead. */\n  transformPage?: (\n    component: any,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => any | Promise<any>;\n}\n\nexport class PluginManager {\n  private plugins: FarmPlugin[] = [];\n  private hookPresence = new Map<keyof FarmPlugin, boolean>();\n  private runtimeHookPresence = new Map<\"context\" | \"before\" | \"after\" | \"error\", boolean>();\n  private context: FarmPluginContext;\n  private pluginStates = new Map<FarmPlugin, unknown>();\n  private setupComplete = false;\n  private initialized = false;\n  private runtimeReady = false;\n  private runtimeClosed = false;\n  private runtimeStartPromise?: Promise<void>;\n  private runtimeClosePromise?: Promise<void>;\n  private runtimeShutdownHooksRunning = false;\n  private runtimeDisposers: Array<() => void | Promise<void>> = [];\n  private runtimeRequestContexts = new WeakMap<Request, Readonly<Record<string, unknown>>>();\n  private failedRuntimeSessions = new WeakSet<FarmPluginRuntimeSession>();\n\n  constructor(context: Omit<FarmPluginContext, \"requestContext\" | \"lifecycle\">) {\n    this.context = {\n      ...context,\n      lifecycle: {\n        onShutdown: (dispose) => {\n          if (typeof dispose !== \"function\") {\n            throw new TypeError(\"Farm lifecycle.onShutdown requires a cleanup function\");\n          }\n          if (this.runtimeClosePromise || this.runtimeClosed) {\n            throw new Error(\"Farm runtime cleanup cannot be registered after shutdown begins\");\n          }\n\n          this.runtimeDisposers.push(dispose);\n          let registered = true;\n          return () => {\n            if (!registered) return;\n            registered = false;\n            const index = this.runtimeDisposers.indexOf(dispose);\n            if (index >= 0) this.runtimeDisposers.splice(index, 1);\n          };\n        },\n      },\n      requestContext: {\n        set(target, key, value, options) {\n          setRequestContext(target as object, key, value, options);\n        },\n        get(target, key) {\n          return getRequestContext(target as object, key);\n        },\n        has(target, key) {\n          return hasRequestContext(target as object, key);\n        },\n        delete(target, key) {\n          return deleteRequestContext(target as object, key);\n        },\n        clear(target) {\n          clearRequestContext(target as object);\n        },\n        getAll(target, options) {\n          return getRequestContextSnapshot(target as object, options);\n        },\n      },\n    };\n  }\n\n  private createPluginHookContext(\n    plugin: FarmPlugin,\n    context: FarmPluginContext = this.context,\n  ): FarmPluginContext {\n    const integration = getFarmPluginIntegrationContext(plugin);\n    return integration ? { ...context, integration } : context;\n  }\n\n  private createRequestHookContext(\n    target: FarmRequest | Request,\n    plugin: FarmPlugin,\n  ): FarmRequestPluginContext {\n    const requestContext = this.context.requestContext;\n\n    return {\n      ...this.createPluginHookContext(plugin),\n      req: {\n        set(key, value, options) {\n          requestContext.set(target, key, value, options);\n        },\n        get(key) {\n          return requestContext.get(target, key);\n        },\n        has(key) {\n          return requestContext.has(target, key);\n        },\n        delete(key) {\n          return requestContext.delete(target, key);\n        },\n        clear() {\n          requestContext.clear(target);\n        },\n        snapshot(options) {\n          return requestContext.getAll(target, options);\n        },\n      },\n    };\n  }\n\n  private copyRequestStore(source: FarmRequest | Request, target: FarmRequest | Request): void {\n    const requestContext = this.context.requestContext;\n    const values = requestContext.getAll(source);\n    const exposed = requestContext.getAll(source, { exposedOnly: true });\n\n    for (const [key, value] of values) {\n      requestContext.set(target, key, value, {\n        exposeToPage: exposed.has(key),\n      });\n    }\n  }\n\n  private copyRuntimeRequestContext(source: Request, target: Request): void {\n    const runtimeContext = this.runtimeRequestContexts.get(source);\n    if (runtimeContext) {\n      this.runtimeRequestContexts.set(target, runtimeContext);\n    }\n  }\n\n  private createRuntimeBaseEvent(\n    plugin: FarmPlugin,\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): FarmPluginRuntimeBaseEvent {\n    return {\n      ...this.createStateHookContext(plugin),\n      request,\n      req: this.createRequestHookContext(request, plugin).req,\n      kind: options.kind ?? \"request\",\n      route: options.route,\n      signal: request.signal,\n      waitUntil,\n    };\n  }\n\n  private async createRuntimeRequestContext(\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): Promise<Readonly<Record<string, unknown>>> {\n    const values: Record<string, unknown> = {};\n    const owners = new Map<string, string>();\n\n    for (const plugin of this.getSortedPlugins()) {\n      const createContext = plugin.runtime?.context;\n      if (!createContext) continue;\n\n      const result = await createContext(\n        this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n      );\n      if (result === undefined) continue;\n      if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n        throw new TypeError(`Farm plugin \"${plugin.name}\" runtime.context must return an object`);\n      }\n\n      for (const [key, value] of Object.entries(result)) {\n        const owner = owners.get(key);\n        if (owner) {\n          throw new Error(\n            `Farm plugin context key \"${key}\" from \"${plugin.name}\" conflicts with \"${owner}\"`,\n          );\n        }\n        owners.set(key, plugin.name);\n        values[key] = value;\n      }\n    }\n\n    const runtimeContext = Object.freeze(values);\n    this.runtimeRequestContexts.set(request, runtimeContext);\n    return runtimeContext;\n  }\n\n  private async runRuntimeErrorHooks(\n    request: Request,\n    error: unknown,\n    ctx: Readonly<Record<string, unknown>>,\n    durationMs: number,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): Promise<void> {\n    for (const plugin of this.getSortedPlugins()) {\n      const onError = plugin.runtime?.error;\n      if (!onError) continue;\n\n      try {\n        await onError({\n          ...this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n          ctx,\n          error,\n          durationMs,\n        });\n      } catch (hookError) {\n        console.error(`Farm plugin \"${plugin.name}\" runtime.error failed:`, hookError);\n      }\n    }\n\n    try {\n      await this.runHookParallel(\"onError\", {\n        phase: \"runtime\",\n        error,\n        meta: {\n          kind: options.kind ?? \"request\",\n          pathname: new URL(request.url).pathname,\n          durationMs,\n        },\n      });\n    } catch (hookError) {\n      console.error(\"Farm plugin onError hook failed:\", hookError);\n    }\n  }\n\n  private createStateHookContext(\n    plugin: FarmPlugin,\n    context: FarmPluginContext = this.context,\n  ): FarmPluginStateContext {\n    return {\n      ...this.createPluginHookContext(plugin, context),\n      state: this.pluginStates.get(plugin),\n    };\n  }\n\n  private getPluginHooks(\n    plugin: FarmPlugin,\n    hookName: keyof FarmPlugin,\n  ): Array<(...args: any[]) => any> {\n    const hooks: Array<(...args: any[]) => any> = [];\n    const legacyHook = plugin[hookName];\n    if (typeof legacyHook === \"function\") {\n      hooks.push(legacyHook);\n    }\n\n    const withState = (context: FarmPluginContext) => this.createStateHookContext(plugin, context);\n\n    switch (hookName) {\n      case \"config\":\n        if (plugin.configure) {\n          hooks.push((config: FarmConfig, context: FarmPluginContext) =>\n            plugin.configure?.(config, context),\n          );\n        }\n        break;\n      case \"ready\":\n        if (plugin.runtime?.start) {\n          hooks.push((context: FarmPluginContext) => plugin.runtime?.start?.(withState(context)));\n        }\n        break;\n      case \"shutdown\":\n        if (plugin.runtime?.close) {\n          hooks.push((payload: ShutdownPayload, context: FarmPluginContext) =>\n            plugin.runtime?.close?.({\n              ...withState(context),\n              reason: payload.reason,\n            }),\n          );\n        }\n        break;\n      case \"routeDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: RouteDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.(route, withState(context)),\n          );\n        }\n        break;\n      case \"middlewareDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: MiddlewareDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.({ kind: \"middleware\", ...route }, withState(context)),\n          );\n        }\n        break;\n      case \"apiRouteDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: APIRouteDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.({ kind: \"api\", ...route }, withState(context)),\n          );\n        }\n        break;\n      case \"routesGenerated\":\n        if (plugin.router?.generated) {\n          hooks.push((routes: RoutesGeneratedPayload, context: FarmPluginContext) =>\n            plugin.router?.generated?.(routes, withState(context)),\n          );\n        }\n        break;\n      case \"beforeRouteMatch\":\n        if (plugin.router?.before) {\n          hooks.push((route: RouteMatchPayload, context: FarmPluginContext) =>\n            plugin.router?.before?.(route, withState(context)),\n          );\n        }\n        break;\n      case \"afterRouteMatch\":\n        if (plugin.router?.after) {\n          hooks.push((result: RouteMatchResultPayload, context: FarmPluginContext) =>\n            plugin.router?.after?.(result, withState(context)),\n          );\n        }\n        break;\n      case \"beforeRender\":\n        if (plugin.render?.before) {\n          hooks.push((render: RenderLifecyclePayload, context: FarmPluginContext) =>\n            plugin.render?.before?.(render, withState(context)),\n          );\n        }\n        break;\n      case \"afterRender\":\n        if (plugin.render?.html) {\n          hooks.push((html: string, render: RenderLifecyclePayload, context: FarmPluginContext) =>\n            plugin.render?.html?.(html, render, withState(context)),\n          );\n        }\n        break;\n      case \"beforeBundle\":\n        if (plugin.build?.before) {\n          hooks.push((bundle: BundleLifecyclePayload, context: FarmPluginContext) =>\n            plugin.build?.before?.(bundle, withState(context)),\n          );\n        }\n        break;\n      case \"beforeNitroBuild\":\n        if (plugin.build?.configure) {\n          hooks.push((buildConfig: any, context: FarmPluginContext) =>\n            plugin.build?.configure?.(buildConfig, withState(context)),\n          );\n        }\n        break;\n      case \"afterBundle\":\n        if (plugin.build?.after) {\n          hooks.push((result: BundleResultPayload, context: FarmPluginContext) =>\n            plugin.build?.after?.(result, withState(context)),\n          );\n        }\n        break;\n      case \"devServerCreated\":\n        if (plugin.dev?.server) {\n          hooks.push((server: ViteDevServer, context: FarmPluginContext) =>\n            plugin.dev?.server?.(server, withState(context)),\n          );\n        }\n        break;\n      case \"hmrUpdate\":\n        if (plugin.dev?.update) {\n          hooks.push((update: HMRUpdatePayload, context: FarmPluginContext) =>\n            plugin.dev?.update?.(update, withState(context)),\n          );\n        }\n        break;\n    }\n\n    return hooks;\n  }\n\n  private getHookContext(\n    plugin: FarmPlugin,\n    hookName: keyof FarmPlugin,\n    args: any[],\n  ): FarmPluginContext {\n    if (\n      hookName === \"beforeRequest\" ||\n      hookName === \"afterResponse\" ||\n      hookName === \"beforeApiHandler\"\n    ) {\n      const target = args[0];\n      if (target && typeof target === \"object\") {\n        return this.createRequestHookContext(target, plugin);\n      }\n    }\n\n    return this.createPluginHookContext(plugin);\n  }\n\n  addPlugin(plugin: FarmPlugin) {\n    this.plugins.push(plugin);\n    this.hookPresence.clear();\n    this.runtimeHookPresence.clear();\n  }\n\n  addPlugins(plugins: FarmPlugin[]) {\n    for (const plugin of plugins) {\n      this.addPlugin(plugin);\n    }\n  }\n\n  getPlugins(): FarmPlugin[] {\n    return [...this.plugins];\n  }\n\n  getSortedPlugins(): FarmPlugin[] {\n    const pre = this.plugins.filter((p) => p.enforce === \"pre\");\n    const normal = this.plugins.filter((p) => !p.enforce);\n    const post = this.plugins.filter((p) => p.enforce === \"post\");\n    return [...pre, ...normal, ...post];\n  }\n\n  hasHook(hookName: keyof FarmPlugin): boolean {\n    const cached = this.hookPresence.get(hookName);\n    if (cached !== undefined) return cached;\n\n    const present = this.plugins.some((plugin) => this.getPluginHooks(plugin, hookName).length > 0);\n    this.hookPresence.set(hookName, present);\n    return present;\n  }\n\n  hasRuntimeHook(hookName: \"context\" | \"before\" | \"after\" | \"error\"): boolean {\n    const cached = this.runtimeHookPresence.get(hookName);\n    if (cached !== undefined) return cached;\n\n    const present = this.plugins.some((plugin) => typeof plugin.runtime?.[hookName] === \"function\");\n    this.runtimeHookPresence.set(hookName, present);\n    return present;\n  }\n\n  hasRuntimeRequestHooks(): boolean {\n    return (\n      this.hasRuntimeHook(\"context\") ||\n      this.hasRuntimeHook(\"before\") ||\n      this.hasRuntimeHook(\"after\") ||\n      this.hasRuntimeHook(\"error\")\n    );\n  }\n\n  copyRequestContext(source: FarmRequest | Request, target: FarmRequest | Request): void {\n    this.copyRequestStore(source, target);\n    if (source instanceof Request && target instanceof Request) {\n      this.copyRuntimeRequestContext(source, target);\n    }\n  }\n\n  async setupPlugins(): Promise<void> {\n    if (this.setupComplete) return;\n\n    for (const plugin of this.getSortedPlugins()) {\n      if (!plugin.setup) continue;\n      const state = await plugin.setup({\n        ...this.createPluginHookContext(plugin),\n        env: getResolvedEnv(),\n      });\n      this.pluginStates.set(plugin, state);\n    }\n\n    this.setupComplete = true;\n  }\n\n  async startRuntime(): Promise<void> {\n    if (this.runtimeReady) return;\n    if (this.runtimeStartPromise) return this.runtimeStartPromise;\n\n    this.runtimeStartPromise = (async () => {\n      if (!this.initialized) {\n        await this.runHookParallel(\"init\");\n      }\n      await this.setupPlugins();\n      if (!this.runtimeReady) {\n        await this.runHookParallel(\"ready\");\n      }\n    })();\n\n    try {\n      await this.runtimeStartPromise;\n    } catch (error) {\n      this.runtimeStartPromise = undefined;\n      throw error;\n    }\n  }\n\n  async closeRuntime(reason = \"runtime-closed\"): Promise<void> {\n    if (this.runtimeClosePromise) return this.runtimeClosePromise;\n    if (this.runtimeClosed) return;\n\n    this.runtimeClosePromise = (async () => {\n      const errors: unknown[] = [];\n      this.runtimeShutdownHooksRunning = true;\n      try {\n        await this.runHookParallel(\"shutdown\", { reason });\n      } catch (error) {\n        if (error instanceof FarmRuntimeShutdownError) errors.push(...error.errors);\n        else errors.push(error);\n      } finally {\n        this.runtimeShutdownHooksRunning = false;\n      }\n\n      const disposers = this.runtimeDisposers.splice(0).reverse();\n      for (const dispose of disposers) {\n        try {\n          await dispose();\n        } catch (error) {\n          errors.push(error);\n        }\n      }\n\n      this.runtimeClosed = true;\n      if (errors.length > 0) {\n        throw new FarmRuntimeShutdownError(\"Farm runtime shutdown failed\", errors);\n      }\n    })();\n    return this.runtimeClosePromise;\n  }\n\n  async beginRuntimeRequest(\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions = {},\n  ): Promise<FarmPluginRuntimeSession> {\n    await this.startRuntime();\n\n    const startedAt = Date.now();\n    const waitUntil = options.waitUntil\n      ? (promise: Promise<unknown>) => options.waitUntil?.(Promise.resolve(promise))\n      : (promise: Promise<unknown>) => {\n          void Promise.resolve(promise).catch(() => {});\n        };\n    let activeRequest = request;\n    let runtimeContext: Readonly<Record<string, unknown>> = Object.freeze({});\n\n    try {\n      runtimeContext = await this.createRuntimeRequestContext(activeRequest, options, waitUntil);\n\n      let response: Response | undefined;\n      for (const plugin of this.getSortedPlugins()) {\n        const before = plugin.runtime?.before;\n        if (!before) continue;\n\n        const result = await before({\n          ...this.createRuntimeBaseEvent(plugin, activeRequest, options, waitUntil),\n          ctx: runtimeContext,\n        });\n\n        if (result instanceof Request) {\n          this.copyRequestStore(activeRequest, result);\n          this.copyRuntimeRequestContext(activeRequest, result);\n          activeRequest = result;\n          continue;\n        }\n        if (result instanceof Response) {\n          response = result;\n          break;\n        }\n        if (result !== undefined) {\n          throw new TypeError(\n            `Farm plugin \"${plugin.name}\" runtime.before must return a Request, Response, or undefined`,\n          );\n        }\n      }\n\n      return {\n        request: activeRequest,\n        response,\n        ctx: runtimeContext,\n        startedAt,\n        options,\n        waitUntil,\n      };\n    } catch (error) {\n      await this.runRuntimeErrorHooks(\n        activeRequest,\n        error,\n        runtimeContext,\n        Date.now() - startedAt,\n        options,\n        waitUntil,\n      );\n      throw error;\n    }\n  }\n\n  async endRuntimeRequest(\n    session: FarmPluginRuntimeSession,\n    initialResponse: Response,\n  ): Promise<Response> {\n    let response = initialResponse;\n\n    try {\n      for (const plugin of this.getSortedPlugins()) {\n        const after = plugin.runtime?.after;\n        if (!after) continue;\n\n        const result = await after({\n          ...this.createRuntimeBaseEvent(\n            plugin,\n            session.request,\n            session.options,\n            session.waitUntil,\n          ),\n          ctx: session.ctx,\n          response,\n          durationMs: Date.now() - session.startedAt,\n        });\n        if (result !== undefined) {\n          if (!(result instanceof Response)) {\n            throw new TypeError(\n              `Farm plugin \"${plugin.name}\" runtime.after must return a Response or undefined`,\n            );\n          }\n          response = result;\n        }\n      }\n\n      return response;\n    } catch (error) {\n      await this.failRuntimeRequest(session, error);\n      throw error;\n    }\n  }\n\n  async failRuntimeRequest(session: FarmPluginRuntimeSession, error: unknown): Promise<void> {\n    if (this.failedRuntimeSessions.has(session)) return;\n    this.failedRuntimeSessions.add(session);\n    await this.runRuntimeErrorHooks(\n      session.request,\n      error,\n      session.ctx,\n      Date.now() - session.startedAt,\n      session.options,\n      session.waitUntil,\n    );\n  }\n\n  async runRuntimeRequest(\n    request: Request,\n    handler: FarmPluginRuntimeRequestHandler,\n    options: FarmPluginRuntimeRequestOptions = {},\n  ): Promise<Response> {\n    const session = await this.beginRuntimeRequest(request, options);\n    try {\n      const response = session.response ?? (await handler(session.request));\n      if (!(response instanceof Response)) {\n        throw new TypeError(\"Farm plugin runtime handlers must return a Response\");\n      }\n      return await this.endRuntimeRequest(session, response);\n    } catch (error) {\n      await this.failRuntimeRequest(session, error);\n      throw error;\n    }\n  }\n\n  async runHook<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<any> {\n    const plugins = this.getSortedPlugins();\n\n    for (const plugin of plugins) {\n      for (const hook of this.getPluginHooks(plugin, hookName)) {\n        const hookContext = this.getHookContext(plugin, hookName, args);\n        const result = await (hook as any).apply(plugin, [...args, hookContext]);\n        if (result !== undefined) {\n          return result;\n        }\n      }\n    }\n  }\n\n  async runHookSerial<K extends keyof FarmPlugin>(\n    hookName: K,\n    initialValue: any,\n    ...args: any[]\n  ): Promise<any> {\n    const plugins = this.getSortedPlugins();\n    let value = initialValue;\n\n    for (const plugin of plugins) {\n      for (const hook of this.getPluginHooks(plugin, hookName)) {\n        const hookArgs = [value, ...args];\n        const hookContext = this.getHookContext(plugin, hookName, hookArgs);\n        const result = await (hook as any).apply(plugin, [...hookArgs, hookContext]);\n        if (result !== undefined) {\n          if (\n            hookName === \"beforeApiHandler\" &&\n            result !== value &&\n            value &&\n            result &&\n            typeof value === \"object\" &&\n            typeof result === \"object\"\n          ) {\n            this.copyRequestStore(value as FarmRequest | Request, result as FarmRequest | Request);\n          }\n          value = result;\n        }\n      }\n    }\n\n    return value;\n  }\n\n  async runHookParallel<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<boolean> {\n    return this.runHookParallelFiltered(hookName, () => true, ...args);\n  }\n\n  /** @internal Runs hooks for only the plugins selected by the runtime adapter. */\n  async runHookParallelFiltered<K extends keyof FarmPlugin>(\n    hookName: K,\n    include: (plugin: FarmPlugin) => boolean,\n    ...args: any[]\n  ): Promise<boolean> {\n    if (hookName === \"shutdown\" && !this.runtimeShutdownHooksRunning) {\n      await this.closeRuntime(args[0]?.reason);\n      return false;\n    }\n\n    const plugins = this.getSortedPlugins().filter(include);\n\n    // Run selected hooks sequentially for deterministic execution and short-circuiting.\n    const sequentialHooks = new Set<keyof FarmPlugin>([\n      \"ready\",\n      \"shutdown\",\n      \"beforeRequest\",\n      \"afterResponse\",\n      \"beforeApiHandler\",\n      \"afterApiHandler\",\n      \"beforeRouteMatch\",\n      \"afterRouteMatch\",\n      \"beforeRender\",\n      \"afterRender\",\n    ]);\n\n    if (sequentialHooks.has(hookName)) {\n      const shutdownErrors: unknown[] = [];\n      for (const plugin of plugins) {\n        for (const hook of this.getPluginHooks(plugin, hookName)) {\n          // Check if response is already sent (only for beforeRequest)\n          if (hookName === \"beforeRequest\") {\n            const res = args[1];\n            if (res && (res.writableEnded || res[FARM_NODE_RESPONSE_END_PENDING])) {\n              return true;\n            }\n          }\n\n          const hookContext = this.getHookContext(plugin, hookName, args);\n          try {\n            await (hook as any).apply(plugin, [...args, hookContext]);\n          } catch (error) {\n            if (hookName !== \"shutdown\") throw error;\n            shutdownErrors.push(error);\n          }\n\n          // Check again after plugin execution (only for beforeRequest)\n          if (hookName === \"beforeRequest\") {\n            const res = args[1];\n            if (res && res.writableEnded) {\n              return true;\n            }\n          }\n        }\n      }\n      if (hookName === \"shutdown\" && shutdownErrors.length > 0) {\n        throw new FarmRuntimeShutdownError(\"Farm plugin shutdown hooks failed\", shutdownErrors);\n      }\n    } else {\n      // Run other hooks in parallel\n      const promises: Promise<any>[] = [];\n      for (const plugin of plugins) {\n        for (const hook of this.getPluginHooks(plugin, hookName)) {\n          const hookContext = this.getHookContext(plugin, hookName, args);\n          promises.push((hook as any).apply(plugin, [...args, hookContext]));\n        }\n      }\n      await Promise.all(promises);\n    }\n\n    if (hookName === \"init\") this.initialized = true;\n    if (hookName === \"ready\") this.runtimeReady = true;\n\n    return false;\n  }\n\n  updateContext(updates: Partial<FarmPluginContext>) {\n    this.context = {\n      ...this.context,\n      ...updates,\n      requestContext: this.context.requestContext,\n    };\n  }\n}\n\nexport function definePlugin<\n  TState = undefined,\n  TRequestContext extends object = Record<string, never>,\n  TClientState = unknown,\n  TClientPublic = undefined,\n  TIntegrationInstance = unknown,\n  const TRoutes extends PluginRoutes = PluginRoutes,\n>(\n  plugin: FarmPlugin<\n    TState,\n    TRequestContext,\n    TClientState,\n    TClientPublic,\n    TIntegrationInstance,\n    false,\n    TRoutes\n  >,\n): FarmPlugin<\n  TState,\n  TRequestContext,\n  TClientState,\n  TClientPublic,\n  TIntegrationInstance,\n  false,\n  TRoutes\n> {\n  return plugin;\n}\n\nexport namespace definePlugin {\n  /** Bind an integration instance type while preserving inference for plugin state and context. */\n  export function forIntegration<TIntegrationInstance>() {\n    return function defineBoundPlugin<\n      TState = undefined,\n      TRequestContext extends object = Record<string, never>,\n      TClientState = unknown,\n      TClientPublic = undefined,\n    >(\n      plugin: FarmPlugin<\n        TState,\n        TRequestContext,\n        TClientState,\n        TClientPublic,\n        TIntegrationInstance,\n        true\n      >,\n    ): FarmPlugin<\n      TState,\n      TRequestContext,\n      TClientState,\n      TClientPublic,\n      TIntegrationInstance,\n      true\n    > {\n      return plugin;\n    };\n  }\n}\nexport { farmPlugin } from \"./vite\";\n","import type { NitroConfig } from \"nitro/config\";\nimport type { ResolvedFarmConfig } from \"../config\";\nimport type { RouteManager } from \"../routing/route-manager\";\nimport type { APIRouteManager } from \"../api/route-manager\";\nimport type { ServerRenderer } from \"../server/renderer\";\nimport { createNitroAPIHandler } from \"./api-handler\";\nimport { createNitroSSRHandler } from \"./ssr-handler\";\nimport path from \"path\";\nimport { prepareFarmWorkflowsForNitro } from \"../workflows\";\nimport {\n  createFarmCronCloudflareConfig,\n  mergeScheduledTasks,\n  prepareFarmCronForNitro,\n} from \"../cron\";\nimport { routeRulesToNitroRouteRules } from \"../route-rules\";\nimport { resolveFarmAPIServerBasePath } from \"../api/server-path\";\n\n/**\n * Create Nitro configuration for Farm.js\n * Based on https://nitro.build/config\n */\nexport async function createNitroConfig(\n  config: ResolvedFarmConfig,\n  routeManager: RouteManager,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: ServerRenderer,\n  preset = \"node-server\",\n): Promise<NitroConfig> {\n  const root = config.root || process.cwd();\n  const apiBasePath = resolveFarmAPIServerBasePath(config.api);\n  const srcDir = config.srcDir || \"src\";\n  const distDir = \".farm\";\n  // Nitro build directory - where Nitro does its work (temporary)\n  // We use .nitro as a working directory, but ensure output goes to .farm/.output\n  const nitroBuildDir = path.join(root, distDir, \".nitro\");\n  // Final output directory - where the deployable output goes\n  // This MUST be .farm/.output (not .nitro/.output) for consistency\n  const outputDir = path.join(root, distDir, \".output\");\n  // Server directory for handlers (inside build dir, will be copied to output)\n  const serverDir = path.join(nitroBuildDir, \"server\");\n\n  // Ensure Nitro doesn't create its own .output inside .nitro\n  // By explicitly setting output.dir, Nitro will use our specified directory\n\n  // Create server directory structure for Nitro to discover routes\n  // According to Nitro docs: https://nitro.build/deploy/providers/vercel\n  // Routes should be in server/api/[...].ts and server/routes/[...].ts\n  const { mkdir, writeFile } = await import(\"fs/promises\");\n  await mkdir(serverDir, { recursive: true });\n  await mkdir(path.join(serverDir, \"api\"), { recursive: true });\n  await mkdir(path.join(serverDir, \"routes\"), { recursive: true });\n  const farmWorkflows = await prepareFarmWorkflowsForNitro({\n    ...config,\n    distDir,\n  });\n  const farmCron = await prepareFarmCronForNitro({\n    ...config,\n    distDir,\n  });\n  const scheduledTasks = mergeScheduledTasks(farmWorkflows.scheduledTasks, farmCron.scheduledTasks);\n  const cloudflareCronConfig = createFarmCronCloudflareConfig(farmCron.jobs);\n\n  // Create a runtime registry file to store route managers\n  // This will be populated at runtime through Nitro hooks\n  const registryFile = path.join(serverDir, \"farm-registry.ts\");\n\n  // Serialize route paths for SSR module loading\n  const routePaths: Record<string, string> = {};\n  for (const [pattern, entry] of routeManager.getRoutes()) {\n    const bundledPath = entry.modulePath\n      .replace(/.*\\/src\\/app\\//, \"\")\n      .replace(/\\.(tsx?|jsx?)$/, \".js\");\n    routePaths[pattern] = bundledPath;\n  }\n\n  // Load client manifest path for reference\n  const clientManifestPath = path.join(root, distDir, \"client\", \"farm-client-manifest.json\");\n\n  await writeFile(\n    registryFile,\n    `\n// Auto-generated by Farm.js\n// Runtime registry for route managers and renderers\nexport const farmRegistry: {\n  apiRouteManager?: any;\n  routeManager?: any;\n  serverRenderer?: any;\n  env?: any;\n  deploymentId?: string;\n  basePath?: string;\n  apiBasePath?: string;\n  clientManifest?: any;\n  routePaths?: Record<string, string>;\n} = {\n  env: ${JSON.stringify(config.env || { server: {}, public: {} }, null, 2)},\n  deploymentId: ${JSON.stringify(config.deploymentId)},\n  basePath: ${JSON.stringify(config.basePath)},\n  apiBasePath: ${JSON.stringify(apiBasePath)},\n  routePaths: ${JSON.stringify(routePaths, null, 2)},\n};\n`,\n    \"utf-8\",\n  );\n\n  // Create API route handler file\n  // For Vercel, Nitro expects routes in server/api/[...].ts format\n  // This catch-all will handle all /api/* requests\n  const apiHandlerFile = path.join(serverDir, \"api\", \"[...].ts\");\n  await mkdir(path.dirname(apiHandlerFile), { recursive: true });\n  await writeFile(\n    apiHandlerFile,\n    `\n// Auto-generated by Farm.js\n// This handler intercepts all /api/* requests\nimport { defineEventHandler, getHeaders, readRawBody, sendWebResponse, setResponseStatus, getRequestURL } from 'h3';\nimport type { H3Event } from 'h3';\nimport { farmRegistry } from '../farm-registry';\nimport { createFarmLegacyRequest } from '@farm.js/core/internal/production-runtime';\n\nexport default defineEventHandler(async (event: H3Event) => {\n  // Get URL using H3's abstraction (works in all environments)\n  const url = getRequestURL(event);\n  const urlPath = url.pathname;\n  const apiBasePath = farmRegistry.apiBasePath || '/api';\n  const isAPIPath = apiBasePath !== '/' &&\n    (urlPath === apiBasePath || urlPath.startsWith(apiBasePath + '/'));\n  \n  // Only handle API routes - for Vercel, Nitro routes /api/* to this handler\n  // According to https://nitro.build/deploy/providers/vercel\n  // This handler should process all /api/* routes\n  if (!isAPIPath) {\n    // Return undefined to let Nitro's routing system handle non-API routes\n    return undefined;\n  }\n  \n  // Ensure registry is populated (lazy initialization)\n  // In serverless environments, the registry needs to be initialized at runtime\n  if (!farmRegistry.apiRouteManager) {\n    // Try to initialize from global if available (set during build)\n    if (typeof globalThis !== 'undefined' && (globalThis as any).__FARM_REGISTRY__) {\n      Object.assign(farmRegistry, (globalThis as any).__FARM_REGISTRY__);\n    }\n    // If still not available, try the init function (if it exists)\n    if (!farmRegistry.apiRouteManager && (farmRegistry as any).__INIT__) {\n      (farmRegistry as any).__INIT__();\n    }\n  }\n  \n  const apiRouteManager = farmRegistry.apiRouteManager;\n  if (!apiRouteManager) {\n    console.error('API route manager not initialized. Registry keys:', Object.keys(farmRegistry));\n    setResponseStatus(event, 500);\n    return { error: 'API route manager not initialized. Please check server logs.' };\n  }\n  \n  const startTime = Date.now();\n  const method = event.method || 'GET';\n  const host = url.host || 'localhost';\n  \n  // Log API request (only in development)\n  if (process.env.NODE_ENV === 'development' || !process.env.NODE_ENV) {\n    try {\n      const pc = await import('picocolors');\n      const log = [\n        pc.default.dim('[') + pc.default.bold(pc.default.blue('FARM')) + pc.default.dim(']'),\n        pc.default.dim('[') + pc.default.bold(pc.default.white(method.padEnd(3))) + pc.default.dim(']'),\n        pc.default.cyan('[API]'),\n        pc.default.gray(\\`\\${url.protocol}//\\${host}\\${urlPath}\\`),\n      ].join(' ');\n      console.log(log);\n    } catch {\n      // picocolors not available, use simple log\n      console.log(\\`[FARM] [\\${method}] [API] \\${urlPath}\\`);\n    }\n  }\n  \n  try {\n    // Convert H3 event to Web Request using H3 abstractions\n    const protocol = url.protocol.replace(':', '') || 'http';\n    const host = url.host || 'localhost';\n    const fullUrl = url.toString();\n    \n    const headers = new Headers();\n    const h3Headers = getHeaders(event);\n    \n    for (const [key, value] of Object.entries(h3Headers)) {\n      if (value) {\n        headers.set(key, Array.isArray(value) ? value.join(', ') : String(value));\n      }\n    }\n    \n    const request = await createFarmLegacyRequest(event, fullUrl, headers, readRawBody);\n    \n    // Call better-call handler\n    const betterCallHandler = apiRouteManager.getHandler();\n    if (!betterCallHandler) {\n      setResponseStatus(event, 404);\n      return { error: 'API handler not found' };\n    }\n    \n    const response = await betterCallHandler(request);\n    \n    // Log API response (only in development)\n    if (process.env.NODE_ENV === 'development' || !process.env.NODE_ENV) {\n      const duration = Date.now() - startTime;\n      const status = response.status;\n      try {\n        const pc = await import('picocolors');\n        let statusColor = pc.default.green;\n        if (status >= 500) statusColor = pc.default.red;\n        else if (status >= 400) statusColor = pc.default.yellow;\n        else if (status >= 300) statusColor = pc.default.cyan;\n\n        const log = [\n          pc.default.dim('[') + pc.default.bold(pc.default.blue('FARM')) + pc.default.dim(']'),\n          status >= 400 ? pc.default.red('✗') : pc.default.green('✓'),\n          pc.default.cyan('[API]'),\n          pc.default.gray(urlPath),\n          pc.default.dim('-'),\n          statusColor(status.toString()),\n          pc.default.dim(\\`(\\${duration}ms)\\`),\n        ].join(' ');\n        console.log(log);\n      } catch {\n        // picocolors not available, use simple log\n        console.log(\\`[FARM] [\\${method}] [API] \\${urlPath} - \\${response.status} (\\${duration}ms)\\`);\n      }\n    }\n    \n    return sendWebResponse(response);\n  } catch (error: any) {\n    console.error('API handler error:', error);\n    setResponseStatus(event, 500);\n    return {\n      error: error.message || 'Internal Server Error',\n    };\n  }\n});\n`,\n    \"utf-8\",\n  );\n\n  // Create SSR catch-all route handler\n  // For Vercel, Nitro expects routes in server/routes/[...].ts format\n  const ssrHandlerFile = path.join(serverDir, \"routes\", \"[...].ts\");\n  await mkdir(path.dirname(ssrHandlerFile), { recursive: true });\n  await writeFile(\n    ssrHandlerFile,\n    `\n// Auto-generated by Farm.js\n// This handler handles all page routes (SSR)\nimport { defineEventHandler, setResponseStatus, getRequestURL, setHeader, getHeaders, readRawBody, sendWebResponse, setCookie } from 'h3';\nimport type { H3Event } from 'h3';\nimport { farmRegistry } from '../farm-registry';\nimport React from 'react';\nimport { renderToString } from 'react-dom/server';\nimport { searchParamsToObject } from '@farm.js/core/internal/production-runtime';\nimport { createFarmLegacyRequest, renderFarmLegacyErrorHtml, renderFarmLegacyHtml } from '@farm.js/core/internal/production-runtime';\n\nexport default defineEventHandler(async (event: H3Event) => {\n  try {\n    // Ensure registry is populated (lazy initialization)\n    // In serverless environments, the registry needs to be initialized at runtime\n    if (!farmRegistry.routeManager || !farmRegistry.serverRenderer) {\n      // Try to initialize from global if available (set during build)\n      if (typeof globalThis !== 'undefined' && (globalThis as any).__FARM_REGISTRY__) {\n        Object.assign(farmRegistry, (globalThis as any).__FARM_REGISTRY__);\n      }\n      // If still not available, try the init function (if it exists)\n      if ((!farmRegistry.routeManager || !farmRegistry.serverRenderer) && (farmRegistry as any).__INIT__) {\n        (farmRegistry as any).__INIT__();\n      }\n    }\n    \n    const routeManager = farmRegistry.routeManager;\n    const serverRenderer = farmRegistry.serverRenderer;\n    \n    if (!routeManager || !serverRenderer) {\n      console.error('Route manager or renderer not initialized. Registry keys:', Object.keys(farmRegistry));\n      setResponseStatus(event, 500);\n      setHeader(event, 'Content-Type', 'text/html; charset=utf-8');\n      return '<!DOCTYPE html><html><head><title>Error</title></head><body><h1>500 Internal Server Error</h1><p>Route manager or renderer not initialized. Please check server logs.</p></body></html>';\n    }\n    \n    // Get URL from H3 event\n    const url = getRequestURL(event);\n    const pathname = url.pathname;\n    const apiBasePath = farmRegistry.apiBasePath || '/api';\n    const isAPIPath = apiBasePath !== '/' &&\n      (pathname === apiBasePath || pathname.startsWith(apiBasePath + '/'));\n    const redirectMatch = routeManager.matchRedirect(pathname, url.search);\n    if (redirectMatch) {\n      setResponseStatus(event, redirectMatch.statusCode);\n      setHeader(event, 'Location', redirectMatch.destination);\n      return \\`Redirecting to \\${redirectMatch.destination}\\`;\n    }\n    const apiRouteManager = farmRegistry.apiRouteManager;\n\n    if (apiRouteManager?.matchRoute(pathname)) {\n      const handler = apiRouteManager.getHandler();\n      if (!handler) {\n        setResponseStatus(event, 404);\n        return { error: 'API handler not found' };\n      }\n\n      const headers = new Headers();\n      const h3Headers = getHeaders(event);\n      for (const [key, value] of Object.entries(h3Headers)) {\n        if (value) {\n          headers.set(key, Array.isArray(value) ? value.join(', ') : String(value));\n        }\n      }\n\n      const request = await createFarmLegacyRequest(event, url, headers, readRawBody);\n      const response = await handler(request);\n\n      return sendWebResponse(response);\n    }\n\n    // Skip API routes - let the API handler process them\n    if (isAPIPath) {\n      // Return undefined to let Nitro's API handler process\n      return undefined;\n    }\n    \n    // Skip static assets - let Nitro serve them\n    // Only skip if it's clearly a static file (has extension and not in root)\n    if (pathname.startsWith('/assets/') || (pathname.includes('.') && !isAPIPath)) {\n      // Check if it's a static file by extension\n      const staticExtensions = ['.js', '.css', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.woff', '.woff2', '.ttf', '.eot'];\n      const hasStaticExtension = staticExtensions.some(ext => pathname.toLowerCase().endsWith(ext));\n      if (hasStaticExtension) {\n        return; // Let Nitro's static file handler process\n      }\n    }\n    \n    // Try to use Node.js req/res if available (for node-server preset)\n    if (event.node && event.node.req && event.node.res) {\n      await serverRenderer.renderPage(event.node.req as any, event.node.res as any);\n      return undefined; // Response already sent\n    }\n\n    if (farmRegistry.deploymentId) {\n      setHeader(event, 'x-farm-deployment-id', farmRegistry.deploymentId);\n      setCookie(event, '__farm_deployment', farmRegistry.deploymentId, {\n        httpOnly: true,\n        sameSite: 'lax',\n        secure: url.protocol === 'https:',\n        path: farmRegistry.basePath || '/',\n      });\n    }\n    \n    // For serverless (Vercel), render to string and send HTML\n    try {\n      // Match route\n      const { route, params, layouts } = routeManager.matchRoute(pathname);\n      \n      if (!route) {\n        setResponseStatus(event, 404);\n        setHeader(event, 'Content-Type', 'text/html; charset=utf-8');\n        return '<!DOCTYPE html><html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1></body></html>';\n      }\n      \n      // Get search params\n      const searchParamsObject = searchParamsToObject(url.searchParams);\n      \n      // Load route module - in production, use bundled SSR output\n      // Get bundled path from registry or construct it\n      let routeModule;\n      const routePaths = farmRegistry.routePaths || {};\n      const bundledPath = routePaths[pathname] || route.modulePath\n        .replace(/.*\\\\/src\\\\/app\\\\//, '')\n        .replace(/\\\\.(tsx?|jsx?)$/, '.js');\n      \n      try {\n        // Try to load from bundled SSR output (copied to Nitro's server/farm directory)\n        // Nitro bundles everything, so we need to use the correct import path\n        routeModule = await import('./farm/' + bundledPath);\n      } catch (importError) {\n        // Fallback: try route manager's load method (for node-server preset)\n        try {\n          routeModule = await routeManager.loadRouteModule(route.modulePath);\n        } catch (loadError) {\n          // Last resort: try just the filename\n          const bundledName = bundledPath.split('/').pop() || 'page.js';\n          try {\n            routeModule = await import('./farm/' + bundledName);\n          } catch {\n            throw new Error(\\`Failed to load route module: \\${route.modulePath}. Tried: ./farm/\\${bundledPath}, ./farm/\\${bundledName}\\`);\n          }\n        }\n      }\n      \n      if (!routeModule.default) {\n        throw new Error(\\`Route module \\${route.modulePath} does not export a default component\\`);\n      }\n      \n      // Load layout modules\n      const layoutModules = await Promise.all(\n        layouts.map(async (layout) => {\n          const bundledPath = layout.modulePath\n            .replace(/.*\\\\/src\\\\/app\\\\//, '')\n            .replace(/\\\\.(tsx?|jsx?)$/, '.js');\n          \n          try {\n            // Try to load from bundled SSR output\n            return await import('./farm/' + bundledPath);\n          } catch {\n            // Fallback to route manager's load method\n            try {\n              return await routeManager.loadLayoutModule(layout.modulePath);\n            } catch {\n              // Last resort: try just the filename\n              const bundledName = bundledPath.split('/').pop() || 'layout.js';\n              try {\n                return await import('./farm/' + bundledName);\n              } catch {\n                // Return a dummy layout if all fails\n                return { default: ({ children }: any) => children };\n              }\n            }\n          }\n        })\n      );\n      \n      // Create page props\n      const rawPageProps = {\n        params,\n        searchParams: Promise.resolve(searchParamsObject),\n        path: pathname,\n      };\n      const pageProps = routeModule.__farmResolveRouteProps\n        ? await routeModule.__farmResolveRouteProps(rawPageProps)\n        : (() => {\n            const routeSchemas = routeModule.__farmRouteParsesProps\n              ? {}\n              : routeModule.__farmRouteSchemas || {};\n            const parsedParams = routeSchemas.params?.parse\n              ? routeSchemas.params.parse(params)\n              : params;\n            const parsedSearch = routeSchemas.search?.parse\n              ? routeSchemas.search.parse(searchParamsObject)\n              : searchParamsObject;\n            return {\n              ...rawPageProps,\n              params: parsedParams,\n              search: parsedSearch,\n              searchParams: Promise.resolve(parsedSearch),\n            };\n          })();\n      \n      // Create page element\n      const PageComponent = routeModule.default;\n      let pageElement;\n      if (typeof PageComponent === \"function\" && PageComponent.constructor.name === \"AsyncFunction\") {\n        pageElement = await PageComponent(pageProps);\n      } else {\n        pageElement = React.createElement(PageComponent, pageProps);\n      }\n      \n      // Wrap with layouts\n      for (let i = layoutModules.length - 1; i >= 0; i--) {\n        const layoutModule = layoutModules[i];\n        const LayoutComponent = layoutModule.default;\n        pageElement = React.createElement(LayoutComponent, {\n          children: pageElement,\n          params,\n        } as any);\n      }\n      \n      // Render to string\n      const html = renderToString(pageElement);\n      \n      // Get client script path from manifest\n      const clientManifest = farmRegistry.clientManifest || {};\n      // Find the client script for this route - check manifest structure\n      let clientScript = '/assets/page-wbYjx1yQ.js'; // Default fallback\n      if (clientManifest && typeof clientManifest === 'object') {\n        // Manifest structure: { \"assets/page-xxx.js\": { ... } }\n        const manifestEntry = Object.values(clientManifest).find((entry: any) => \n          entry && entry.name === 'page'\n        ) as any;\n        if (manifestEntry && manifestEntry.chunks && manifestEntry.chunks[0]) {\n          clientScript = '/' + manifestEntry.chunks[0];\n        } else if (Object.keys(clientManifest).length > 0) {\n          // Fallback to first asset in manifest\n          clientScript = '/' + Object.keys(clientManifest)[0];\n        }\n      }\n      \n      // Build full HTML\n      const fullHtml = renderFarmLegacyHtml({\n        deploymentId: farmRegistry.deploymentId || '',\n        pageProps,\n        pathname,\n        html,\n        clientScript,\n      });\n      \n      setHeader(event, 'Content-Type', 'text/html; charset=utf-8');\n      return fullHtml;\n      \n    } catch (renderError: any) {\n      console.error('SSR render error:', renderError);\n      setResponseStatus(event, 500);\n      setHeader(event, 'Content-Type', 'text/html; charset=utf-8');\n      return renderFarmLegacyErrorHtml();\n    }\n  } catch (error: any) {\n    console.error('SSR handler error:', error);\n    setResponseStatus(event, 500);\n    setHeader(event, 'Content-Type', 'text/html; charset=utf-8');\n    return renderFarmLegacyErrorHtml();\n  }\n});\n`,\n    \"utf-8\",\n  );\n\n  // Create Nitro config according to https://nitro.build/config\n  // Compatibility date is required in Nitro v3\n  const nitroConfig: NitroConfig = {\n    preset,\n    // rootDir must be the project root for Nitro to correctly resolve paths\n    rootDir: root,\n    // srcDir should point to where source files are (for scanning)\n    // But we're using scanDirs to point to our server directory\n    srcDir: root,\n    // buildDir is where Nitro builds (temporary working directory)\n    buildDir: nitroBuildDir,\n    // output.dir is where the final deployable output goes\n    // This ensures everything ends up in .farm/.output\n    compatibilityDate: \"2024-12-01\",\n    // Vercel-specific configuration\n    ...(preset === \"vercel\"\n      ? {\n          vercel: {\n            // Ensure proper function configuration\n            config: {},\n          },\n        }\n      : {}),\n    // Tell Nitro to scan the server directory we created\n    // This ensures our handlers are discovered by Nitro\n    scanDirs: [serverDir],\n    tasks: {\n      ...farmWorkflows.tasks,\n      ...farmCron.tasks,\n    },\n    scheduledTasks,\n    ...(preset === \"cloudflare-module\" && cloudflareCronConfig\n      ? {\n          cloudflare: cloudflareCronConfig,\n        }\n      : {}),\n    handlers: farmWorkflows.handlerPath\n      ? [\n          {\n            route: `${config.workflows.route}/**`,\n            handler: farmWorkflows.handlerPath,\n          },\n        ]\n      : [],\n    // Route rules for Vercel\n    routeRules: {\n      ...(apiBasePath === \"/\"\n        ? {}\n        : {\n            [`${apiBasePath}/**`]: {\n              cors: true,\n              headers: {\n                \"Access-Control-Allow-Origin\": \"*\",\n                \"Access-Control-Allow-Methods\": \"*\",\n                \"Access-Control-Allow-Headers\": \"*\",\n              },\n            },\n          }),\n      \"/**\": {\n        prerender: false,\n      },\n      ...routeRulesToNitroRouteRules(config.routeRules),\n    },\n\n    // // Exclude certain directories from scanning\n    // scanDirsExclude: [\n    //   '**/node_modules/**',\n    //   '**/.git/**',\n    //   '**/.output/**',\n    //   '**/.nitro/**',\n    // ],\n    output: {\n      // CRITICAL: All output MUST go to .farm/.output (NOT .nitro/.output)\n      // This ensures consistency and that deployment always uses .farm/.output\n      // By explicitly setting dir, serverDir, and publicDir, we prevent Nitro\n      // from creating its own .output directory inside .nitro\n      dir: outputDir, // .farm/.output\n      serverDir: path.join(outputDir, \"server\"), // .farm/.output/server\n      publicDir: path.join(outputDir, \"public\"), // .farm/.output/public\n    },\n    // Use Nitro hooks to populate the runtime registry\n    // This allows us to pass complex objects (route managers, renderers) at runtime\n    hooks: {\n      \"build:before\": async (nitro: any) => {\n        // Import and populate the registry at build time\n        const registryPath = path.join(serverDir, \"farm-registry.ts\");\n        const { farmRegistry } = await import(/* @vite-ignore */ registryPath);\n\n        // Store route paths (serializable)\n        const routePaths: Record<string, string> = {};\n        for (const [pattern, entry] of routeManager.getRoutes()) {\n          const bundledPath = entry.modulePath\n            .replace(/.*\\/src\\/app\\//, \"\")\n            .replace(/\\.(tsx?|jsx?)$/, \".js\");\n          routePaths[pattern] = bundledPath;\n        }\n        farmRegistry.routePaths = routePaths;\n\n        // Load and store client manifest for SSR\n        try {\n          const clientManifestPath = path.join(\n            root,\n            distDir,\n            \"client\",\n            \"farm-client-manifest.json\",\n          );\n          const { readFile } = await import(\"fs/promises\");\n          const manifestContent = await readFile(clientManifestPath, \"utf-8\");\n          farmRegistry.clientManifest = JSON.parse(manifestContent);\n        } catch (error) {\n          // Manifest not critical, continue without it\n          farmRegistry.clientManifest = {};\n        }\n\n        // CRITICAL: Store managers in a way that persists to runtime\n        // In serverless, we can't serialize complex objects, so we store them\n        // in a module-level variable that will be available at runtime\n        // The handlers will access them through the registry\n        // We use a closure to capture the managers\n        (farmRegistry as any).__INIT__ = () => {\n          farmRegistry.apiRouteManager = apiRouteManager;\n          farmRegistry.routeManager = routeManager;\n          farmRegistry.serverRenderer = serverRenderer;\n          farmRegistry.env = config.env || { server: {}, public: {} };\n          farmRegistry.deploymentId = config.deploymentId;\n          farmRegistry.basePath = config.basePath;\n        };\n\n        // Also store in global for runtime access (works in serverless)\n        // This ensures they're available even if module state is reset\n        if (typeof globalThis !== \"undefined\") {\n          (globalThis as any).__FARM_REGISTRY__ = {\n            apiRouteManager,\n            routeManager,\n            serverRenderer,\n            env: farmRegistry.env,\n            deploymentId: farmRegistry.deploymentId,\n            basePath: farmRegistry.basePath,\n            clientManifest: farmRegistry.clientManifest,\n            routePaths: farmRegistry.routePaths,\n          };\n        }\n      },\n    },\n    // API base URL (default is /api)\n    apiBaseURL: \"/api\",\n    // Include public directory and client build\n    publicAssets: [\n      {\n        baseURL: \"/\",\n        dir: path.join(root, \"public\"),\n      },\n      // Include client build assets\n      {\n        baseURL: \"/\",\n        dir: path.join(root, distDir, \"client\"),\n      },\n    ],\n    // Build configuration\n    minify: process.env.NODE_ENV === \"production\",\n    sourceMap: true,\n    // Bundle all dependencies to avoid workspace issues on Vercel\n    // This ensures all farm package code is bundled into the serverless function\n    // so it doesn't need to resolve workspace dependencies at runtime\n    // This is similar to how Next.js and Nuxt bundle their core packages\n    // bundle: true,\n    // External dependencies that should NOT be bundled (provided by runtime)\n    // We exclude React/ReactDOM to reduce bundle size (they're in node_modules)\n    externals: {\n      external: [\"react\", \"react-dom\"],\n      // Keep React external - it's in the serverless function's node_modules\n      // This reduces bundle size significantly\n    },\n    // Runtime config\n    runtimeConfig: {\n      public: {},\n    },\n    // Experimental features\n    experimental: {\n      tasks: farmWorkflows.workflows.length > 0 || farmCron.jobs.length > 0,\n      wasm: false, // Disable for now to avoid issues\n    },\n  };\n\n  return nitroConfig;\n}\n\n/**\n * Get Nitro preset from config\n */\nexport function getNitroPreset(preset?: string): string {\n  return preset || \"node-server\";\n}\n","export * from \"./types\";\nexport type { FarmAgentUserConfig, FarmAgentJsonLd } from \"./agent-config\";\nexport { defineRenderer, REACT_RENDERER } from \"./renderer\";\nexport type {\n  FarmRenderer,\n  FarmRendererCapabilities,\n  FarmRendererCapabilitiesInput,\n  FarmRendererStreamingCapabilities,\n} from \"./renderer\";\nexport * from \"./utils\";\nexport * from \"./storage\";\nexport * from \"./integrations\";\nexport * from \"./integration-orm\";\nexport * from \"./integration-api\";\nexport { createFarmApp } from \"./app\";\nexport { FarmProvider } from \"./provider\";\nexport { getCurrentRequest } from \"./server/request\";\nexport { definePlugin, FarmRuntimeShutdownError, PluginManager } from \"./plugin\";\nexport {\n  defineConfig,\n  defineFarmConfig,\n  resolveConfig,\n  loadConfig,\n  resolveDeployConfig,\n  resolveMigrationsConfig,\n  resolveDeployOutputPath,\n  normalizeDeployTarget,\n  getDeployTargetForPreset,\n  getPresetForDeployTarget,\n} from \"./config\";\nexport type { FarmLayerConfig } from \"./config\";\nexport type {\n  FarmPerformanceConfig,\n  FarmPreloadMode,\n  FarmPreloadUserConfig,\n  ResolvedFarmPerformanceConfig,\n  ResolvedFarmPreloadConfig,\n} from \"./preload\";\nexport type {\n  FarmCspConfig,\n  FarmCspDirectives,\n  FarmCspDirectiveValue,\n  FarmCspOptions,\n  FarmSecurityConfig,\n  ResolvedFarmCspConfig,\n  ResolvedFarmSecurityConfig,\n} from \"./security\";\nexport type { FarmIslandStrategy } from \"./island\";\nexport type { FarmLayerEntry, ResolvedFarmLayer } from \"./layers\";\nexport {\n  getFarmAppDirectories,\n  getFarmLayerAliases,\n  getFarmSourceRoots,\n  resolveFarmLayers,\n} from \"./layers\";\nexport { HMRManager } from \"./hmr\";\nexport * from \"./plugins\";\nexport * from \"./api\";\nexport { APITypeGenerator } from \"./type-generator\";\nexport * from \"./openapi\";\nexport * from \"./query\";\nexport * from \"./middleware\";\nexport * from \"./router\";\nexport * from \"./route-rules\";\nexport * from \"./route-runtime\";\nexport type { MetadataRoute, MetadataRouteContext } from \"./metadata-route\";\nexport {\n  createLayoutModuleFromProgrammaticLayout,\n  createRoute,\n  createProgrammaticRouteModuleId,\n  createRouteModuleFromProgrammaticPage,\n  defineRoutes,\n  getProgrammaticRouteManifest,\n  isProgrammaticRouteManifest,\n  isProgrammaticRoutesFileName,\n  layout,\n  page,\n  parseProgrammaticRouteModuleId,\n  parseProgrammaticRoutePath,\n  routesBuilder,\n  scanProgrammaticPagePaths,\n} from \"./routes\";\nexport type {\n  ProgrammaticApiRoute,\n  ProgrammaticApiRouteOptions,\n  ProgrammaticLayoutRoute,\n  ProgrammaticPageRoute,\n  ProgrammaticRouteAction,\n  ProgrammaticRouteActionContract,\n  ProgrammaticRouteActions,\n  ProgrammaticRouteDefaultAction,\n  ProgrammaticRouteWithActions,\n  ProgrammaticRedirectRoute,\n  ProgrammaticRouteComponentProps,\n  ProgrammaticRouteDataCacheContext,\n  ProgrammaticRouteDataCacheKeys,\n  ProgrammaticRouteDataContext,\n  ProgrammaticRouteDataHooks,\n  ProgrammaticRouteDataStaleTime,\n  ProgrammaticRouteErrorComponentProps,\n  ProgrammaticRouteGuard,\n  ProgrammaticRouteGuardContext,\n  ProgrammaticRoutePendingComponentProps,\n  ProgrammaticRouteBuilder,\n  ProgrammaticRouteContext,\n  ProgrammaticRouteDefinition,\n  ProgrammaticRouteFactory,\n  ProgrammaticRouteManifest,\n  ProgrammaticRouteMaybePromise,\n  ProgrammaticRouteMethod,\n  ProgrammaticRoutePrimitive,\n  ProgrammaticRouteRenderMode,\n  ProgrammaticRouteParamsFallback,\n  ProgrammaticRouteSchema,\n  ProgrammaticRouteSearchClientOptions,\n  ProgrammaticRouteSearchConfig,\n  ProgrammaticRouteSearchOptions,\n  ProgrammaticRouteSearchFallback,\n  ProgrammaticStaticPath,\n  ProgrammaticStaticPathParams,\n  ProgrammaticStaticPaths,\n  InferProgrammaticRouteData,\n  InferProgrammaticRouteSchema,\n  CreateRouteOptions,\n} from \"./routes\";\nexport * from \"./docs\";\nexport * from \"./markdown\";\nexport * from \"./app-markdown\";\nexport * from \"./observability\";\nexport * from \"./devtools-config\";\nexport type { FarmDevtoolsSnapshot, FarmDevtoolsDiagnostic, FarmDevtoolsRuntime } from \"./devtools\";\nexport * from \"./dev-indicators\";\nexport * from \"./workflows\";\nexport * from \"./cron\";\nexport * from \"./env\";\nexport * from \"./env-types\";\nexport * from \"./theme\";\nexport * from \"./environment\";\nexport * from \"./font\";\nexport * from \"./type-artifacts\";\nexport { createFarmImageTypeDeclarations, generateFarmImageTypes } from \"./image-types\";\nexport type { GenerateFarmImageTypesOptions } from \"./image-types\";\nexport * from \"./server-fn\";\nexport * from \"./server-fn-client\";\nexport * from \"./server-query\";\nexport * from \"./server-query-client\";\nexport * from \"./server-action-security\";\nexport * from \"./deployment\";\nexport type {\n  FarmImageConfig,\n  FarmImageFormat,\n  FarmImageLocalPattern,\n  FarmImageProvider,\n  FarmImageRemotePattern,\n  ResolvedFarmImageConfig,\n} from \"./image-config\";\nexport { generateRouteTypes } from \"./routing/generate-route-types\";\nexport type { GenerateRouteTypesOptions } from \"./routing/generate-route-types\";\nexport * from \"./build/index\";\nexport * from \"./client\";\nexport * from \"./ssg\";\nexport * from \"./cache\";\nexport type {\n  FarmAuthConfig,\n  FarmAuthDatabaseConfig,\n  FarmAuthEmailAndPasswordConfig,\n  FarmAuthSessionConfig,\n  FarmAuthUserConfig,\n  ResolvedFarmAuthConfig,\n} from \"./auth-config\";\nexport * from \"./deferred\";\nexport * from \"./after\";\nexport {\n  getFarmRedirectError,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n  notFound,\n  permanentRedirect,\n  redirect,\n  usePathname,\n  useSearchParams,\n} from \"./navigation\";\nexport type { FarmRedirectSignal, FarmRedirectStatus } from \"./navigation\";\nexport { cookies, headers } from \"./headers\";\nexport type { ReadonlyHeaders, ReadonlyRequestCookies, RequestCookie } from \"./headers\";\nexport type {\n  PluginRequestContext,\n  FarmPlugin,\n  FarmPluginContext,\n  FarmPluginIntegrationContext,\n  FarmPluginLifecycle,\n  FarmRequestPluginContext,\n  FarmRequestStore,\n  FarmPluginRuntimeKind,\n  FarmPluginRouteRuntimePayload,\n  FarmPluginSetupContext,\n  FarmPluginStateContext,\n  FarmPluginRuntimeBaseEvent,\n  FarmPluginRuntimeContextEvent,\n  FarmPluginRuntimeBeforeEvent,\n  FarmPluginRuntimeAfterEvent,\n  FarmPluginRuntimeErrorEvent,\n  FarmPluginRuntimeStartEvent,\n  FarmPluginRuntimeCloseEvent,\n  FarmPluginRuntimeHooks,\n  FarmPluginRuntimeRequestOptions,\n  FarmPluginRuntimeRequestHandler,\n  FarmPluginRuntimeSession,\n  FarmPluginDiscoveredRoute,\n  FarmPluginRouterHooks,\n  FarmPluginRenderHooks,\n  FarmPluginBuildHooks,\n  FarmPluginDevHooks,\n  FarmPluginClientConfig,\n  RouteDiscoveredPayload,\n  RoutesGeneratedPayload,\n  MiddlewareDiscoveredPayload,\n  APIRouteDiscoveredPayload,\n  RouteMatchPayload,\n  RouteMatchResultPayload,\n  RenderLifecyclePayload,\n  APIHandlerLifecyclePayload,\n  ErrorLifecyclePayload,\n  HMRUpdatePayload,\n  BundleLifecyclePayload,\n  BundleResultPayload,\n  NitroBuildLifecyclePayload,\n  ShutdownPayload,\n} from \"./plugin\";\nexport type { MiddlewareProps, PagePropsWithMiddleware, PageProps } from \"./types\";\nexport type {\n  FarmUserConfig,\n  ResolvedFarmConfig,\n  RedirectConfig,\n  HeaderConfig,\n  RewriteConfig,\n  ImageConfig,\n  I18nConfig,\n  FarmI18nCookieConfig,\n  FarmI18nDetectionSignal,\n  FarmI18nDirection,\n  FarmI18nRouting,\n  FarmI18nUserConfig,\n  ResolvedFarmI18nConfig,\n  FarmServerActionsConfig,\n  ResolvedFarmServerActionsConfig,\n  FarmServerConfig,\n  FarmServerDuration,\n  FarmServerHealthConfig,\n  ResolvedFarmServerConfig,\n  ResolvedFarmServerHealthConfig,\n  OpenAPIConfig,\n  MiddlewareConfig,\n  FarmDeployConfig,\n  ResolvedFarmDeployConfig,\n  FarmDeployTarget,\n  FarmMigrationCommand,\n  FarmMigrationsConfig,\n  FarmMigrationsUserConfig,\n  ResolvedFarmMigrationsConfig,\n  FarmWorkflowsUserConfig,\n  FarmWorkflowsResolvedConfig,\n  FarmDocsResolvedConfig,\n  FarmDocsUserConfig,\n  FarmMarkdownResolvedConfig,\n  FarmMarkdownUserConfig,\n} from \"./config\";\n\nexport type { ComponentType, ReactNode, ReactElement, FC, PropsWithChildren } from \"react\";\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 type { ViteDevServer, ModuleNode } from \"vite\";\nimport { toPosixPath } from \"./utils\";\n\nexport class HMRManager {\n  private server: ViteDevServer;\n\n  constructor(server: ViteDevServer) {\n    this.server = server;\n  }\n\n  /**\n   * Send HMR update to client\n   */\n  async send(payload: any) {\n    this.server.ws.send(payload);\n  }\n\n  /**\n   * Trigger full page reload\n   */\n  async reloadPage() {\n    this.server.ws.send({\n      type: \"full-reload\",\n      path: \"*\",\n    });\n  }\n\n  /**\n   * Handle file change and trigger HMR\n   */\n  async handleFileChange(file: string) {\n    const module = await this.server.moduleGraph.getModuleByUrl(file);\n    const normalizedFile = toPosixPath(file);\n\n    if (!module) {\n      return;\n    }\n\n    // Invalidate module\n    this.server.moduleGraph.invalidateModule(module);\n\n    // Get affected modules\n    const affectedModules = this.getAffectedModules(module);\n\n    if (affectedModules.size === 0) {\n      return;\n    }\n\n    if (\n      normalizedFile.includes(\"/app/\") &&\n      /\\/page\\.(?:tsx?|jsx?|vue|svelte)$/.test(normalizedFile)\n    ) {\n      await this.reloadPage();\n      return;\n    }\n\n    if (\n      normalizedFile.includes(\"/app/\") &&\n      /\\/layout\\.(?:tsx?|jsx?|vue|svelte)$/.test(normalizedFile)\n    ) {\n      await this.reloadPage();\n      return;\n    }\n    // Send update for other files\n    this.send({\n      type: \"update\",\n      updates: Array.from(affectedModules).map((m) => ({\n        type: m.type === \"css\" ? \"css-update\" : \"js-update\",\n        path: m.url,\n        acceptedPath: m.url,\n        timestamp: Date.now(),\n      })),\n    });\n  }\n\n  /**\n   * Get all affected modules in the dependency graph\n   */\n  private getAffectedModules(module: ModuleNode): Set<ModuleNode> {\n    const affected = new Set<ModuleNode>();\n    const seen = new Set<ModuleNode>();\n\n    const traverse = (mod: ModuleNode) => {\n      if (seen.has(mod)) return;\n      seen.add(mod);\n      affected.add(mod);\n\n      // A self-accepting module is the HMR boundary: it re-runs with the\n      // update, so nothing above it is affected.\n      if (mod.isSelfAccepting) return;\n\n      for (const importer of mod.importers) {\n        // An importer that accepts this dependency is likewise a boundary:\n        // it receives the update, but its own importers do not. Accepting is\n        // per-edge, so the importer stays traversable via other dependencies.\n        if (importer.acceptedHmrDeps?.has(mod)) {\n          affected.add(importer);\n          continue;\n        }\n        traverse(importer);\n      }\n    };\n\n    traverse(module);\n    return affected;\n  }\n\n  /**\n   * Handle custom HMR events from client\n   */\n  onClientMessage(event: string, callback: (data: any) => void) {\n    // Vite handles this via ws.on\n  }\n}\n\n/**\n * Create HMR client code for injection\n */\nexport function createHMRClientCode(): string {\n  return `\n// Farm.js HMR Client\nif (import.meta.hot) {\n  // Accept HMR updates for this module\n  import.meta.hot.accept((newModule) => {\n    if (newModule) {\n      // Module updated, trigger re-render\n      window.location.reload();\n    }\n  });\n\n  // Listen for custom Farm.js events\n  import.meta.hot.on('farm:route-update', (data) => {\n    console.log('Route updated:', data.path);\n    window.location.reload();\n  });\n\n  // Handle CSS updates\n  import.meta.hot.on('vite:beforeUpdate', () => {\n    console.log('[Farm.js] HMR update incoming...');\n  });\n\n  import.meta.hot.on('vite:afterUpdate', () => {\n    console.log('[Farm.js] HMR update applied ✓');\n  });\n\n  // Handle errors\n  import.meta.hot.on('vite:error', (err) => {\n    console.error('[Farm.js] HMR error:', err);\n  });\n}\n`;\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { RedirectConfig } from \"../config\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { isFarmRedirectStatus } from \"../navigation-errors\";\nimport { appendFarmRedirectQuery } from \"../redirect-query\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport {\n  compileConfigRoutePattern,\n  interpolateConfigRouteDestination,\n  localizeConfigRouteDestination,\n  resolveConfigRoutePathname,\n} from \"./route-pattern\";\n\nexport function createRedirectsPlugin(\n  redirects: RedirectConfig[],\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n    i18n,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    i18n?: ResolvedFarmI18nConfig;\n  } = {},\n): FarmPlugin {\n  for (const redirect of redirects) {\n    if (redirect.statusCode !== undefined && !isFarmRedirectStatus(redirect.statusCode)) {\n      throw new RangeError(\n        `Redirect \"${redirect.source}\" statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n  }\n  const compiledRedirects = redirects.map((redirect) => ({\n    redirect,\n    pattern: compileConfigRoutePattern(redirect.source),\n  }));\n\n  return {\n    name: \"farm:redirects\",\n    enforce: \"pre\",\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n      const url = resolveFarmRequestURL(req);\n      const routePath = resolveConfigRoutePathname(url.pathname, i18n);\n      const pathname = routePath.pathname;\n\n      for (const { redirect, pattern } of compiledRedirects) {\n        const match = pathname.match(pattern.regex);\n        if (match) {\n          const localizedDestination = localizeConfigRouteDestination(\n            interpolateConfigRouteDestination(redirect.destination, match, pattern.tokens),\n            routePath.locale,\n            i18n,\n          );\n          const destination = appendFarmRedirectQuery(localizedDestination, url.search);\n\n          const statusCode = redirect.statusCode ?? (redirect.permanent ? 308 : 307);\n\n          res.writeHead(statusCode, {\n            Location: destination,\n          });\n          res.end();\n          return;\n        }\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { HeaderConfig } from \"../config\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport { compileConfigRoutePattern, resolveConfigRoutePathname } from \"./route-pattern\";\n\nconst FARM_CONFIG_HEADERS_FINALIZER = Symbol.for(\"farm.configHeadersFinalizer\");\n\nfunction appendConfiguredLinkHeader(res: FarmResponse, value: string): void {\n  const current = res.getHeader(\"Link\");\n  if (current === undefined) {\n    res.setHeader(\"Link\", value);\n    return;\n  }\n\n  const currentValue = Array.isArray(current) ? current.join(\", \") : String(current);\n  if (currentValue !== value && !currentValue.endsWith(`, ${value}`)) {\n    res.setHeader(\"Link\", `${currentValue}, ${value}`);\n  }\n}\n\nfunction appendConfiguredSetCookieHeader(res: FarmResponse, value: string): void {\n  const current = res.getHeader(\"Set-Cookie\");\n  if (current === undefined) {\n    res.setHeader(\"Set-Cookie\", value);\n    return;\n  }\n\n  const values = (Array.isArray(current) ? current : [current]).map(String);\n  if (!values.includes(value)) {\n    res.setHeader(\"Set-Cookie\", [...values, value]);\n  }\n}\n\nfunction applyResponseHeaders(\n  res: FarmResponse,\n  matchedHeaders: readonly HeaderConfig[\"headers\"][],\n): void {\n  for (const headers of matchedHeaders) {\n    for (const header of headers) {\n      const key = header.key.toLowerCase();\n      if (key === \"link\") {\n        appendConfiguredLinkHeader(res, header.value);\n      } else if (key === \"set-cookie\") {\n        appendConfiguredSetCookieHeader(res, header.value);\n      } else {\n        res.setHeader(header.key, header.value);\n      }\n    }\n  }\n}\n\nfunction applyWriteHeadHeaders(res: FarmResponse, headers: unknown): void {\n  if (Array.isArray(headers)) {\n    let setCookieWritten = false;\n    for (let index = 0; index + 1 < headers.length; index += 2) {\n      const key = String(headers[index]);\n      const value = headers[index + 1] as string | number | readonly string[];\n      if (key.toLowerCase() === \"set-cookie\" && setCookieWritten) {\n        const current = res.getHeader(\"Set-Cookie\");\n        const values = (Array.isArray(current) ? current : [current]).filter(\n          (entry) => entry !== undefined,\n        );\n        res.setHeader(\"Set-Cookie\", [...values, ...(Array.isArray(value) ? value : [value])]);\n      } else {\n        res.setHeader(key, value);\n        if (key.toLowerCase() === \"set-cookie\") setCookieWritten = true;\n      }\n    }\n    return;\n  }\n\n  if (!headers || typeof headers !== \"object\") return;\n  for (const [key, value] of Object.entries(headers)) {\n    if (value !== undefined) res.setHeader(key, value);\n  }\n}\n\nexport function createHeadersPlugin(\n  headers: HeaderConfig[],\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n    i18n,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    i18n?: ResolvedFarmI18nConfig;\n  } = {},\n): FarmPlugin {\n  const compiledHeaders = headers.map((config) => ({\n    config,\n    pattern: compileConfigRoutePattern(config.source),\n  }));\n\n  return {\n    name: \"farm:headers\",\n    enforce: \"pre\",\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n      const url = resolveFarmRequestURL(req);\n      const pathname = resolveConfigRoutePathname(url.pathname, i18n).pathname;\n      const matchedHeaders = compiledHeaders\n        .filter(({ pattern }) => pattern.regex.test(pathname))\n        .map(({ config }) => config.headers);\n\n      applyResponseHeaders(res, matchedHeaders);\n\n      const responseWithFinalizer = res as FarmResponse & {\n        [FARM_CONFIG_HEADERS_FINALIZER]?: boolean;\n      };\n      if (matchedHeaders.length === 0 || responseWithFinalizer[FARM_CONFIG_HEADERS_FINALIZER]) {\n        return;\n      }\n\n      responseWithFinalizer[FARM_CONFIG_HEADERS_FINALIZER] = true;\n      const writeHead = res.writeHead;\n      res.writeHead = ((statusCode: number, ...args: unknown[]) => {\n        const statusMessage = typeof args[0] === \"string\" ? (args.shift() as string) : undefined;\n        applyWriteHeadHeaders(res, args[0]);\n        applyResponseHeaders(res, matchedHeaders);\n        return statusMessage === undefined\n          ? (writeHead as any).call(res, statusCode)\n          : (writeHead as any).call(res, statusCode, statusMessage);\n      }) as FarmResponse[\"writeHead\"];\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","export { createRedirectsPlugin } from \"./redirects\";\nexport { createHeadersPlugin } from \"./headers\";\nexport { createRewritesPlugin } from \"./rewrites\";\nexport { createEnvPlugin } from \"./env\";\nexport { createCompressionPlugin } from \"./compression\";\nexport { createLoggerPlugin } from \"./logger\";\nexport type { FarmPlugin } from \"../plugin\";\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\n\nexport function createEnvPlugin(\n  env: Record<string, string>,\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n  } = {},\n): FarmPlugin {\n  return {\n    name: \"farm:env\",\n\n    configResolved(config, context) {\n      for (const [key, value] of Object.entries(env)) {\n        process.env[key] = value;\n      }\n    },\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport { pipeline, Readable } from \"node:stream\";\nimport { constants, createBrotliCompress, createGzip } from \"node:zlib\";\n\ntype SupportedEncoding = \"br\" | \"gzip\";\n\nconst Q_VALUE = /^(?:0(?:\\.\\d{0,3})?|1(?:\\.0{0,3})?)$/;\n\nfunction parseEncodingQuality(header: string): Map<string, number> {\n  const qualities = new Map<string, number>();\n\n  for (const item of header.split(\",\")) {\n    const [rawEncoding, ...parameters] = item.trim().split(\";\");\n    const encoding = rawEncoding?.trim().toLowerCase();\n    if (!encoding) continue;\n\n    let quality = 1;\n    for (const parameter of parameters) {\n      const [rawName, rawValue] = parameter.split(\"=\", 2);\n      if (rawName?.trim().toLowerCase() !== \"q\") continue;\n      const value = rawValue?.trim() ?? \"\";\n      quality = Q_VALUE.test(value) ? Number(value) : 0;\n    }\n\n    qualities.set(encoding, Math.max(qualities.get(encoding) ?? 0, quality));\n  }\n\n  return qualities;\n}\n\nfunction selectEncoding(header: string): SupportedEncoding | undefined {\n  if (!header.trim()) return undefined;\n\n  const qualities = parseEncodingQuality(header);\n  const wildcard = qualities.get(\"*\") ?? 0;\n  const quality = (encoding: SupportedEncoding) => qualities.get(encoding) ?? wildcard;\n  const brotli = quality(\"br\");\n  const gzip = quality(\"gzip\");\n\n  if (brotli <= 0 && gzip <= 0) return undefined;\n  return brotli >= gzip ? \"br\" : \"gzip\";\n}\n\nfunction isCompressionEligible(request: Request, response: Response): boolean {\n  if (\n    (request.method !== \"HEAD\" && !response.body) ||\n    response.status === 204 ||\n    response.status === 205 ||\n    response.status === 304 ||\n    response.headers.has(\"content-encoding\") ||\n    response.headers.has(\"content-range\") ||\n    response.headers.get(\"cache-control\")?.toLowerCase().includes(\"no-transform\")\n  ) {\n    return false;\n  }\n\n  const mediaType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n  return mediaType !== \"text/event-stream\";\n}\n\nfunction appendVary(headers: Headers, value: string): void {\n  const current = headers.get(\"vary\");\n  const values = current\n    ? current\n        .split(\",\")\n        .map((item) => item.trim())\n        .filter(Boolean)\n    : [];\n  if (values.includes(\"*\")) return;\n  if (!values.some((item) => item.toLowerCase() === value.toLowerCase())) {\n    values.push(value);\n  }\n  headers.set(\"vary\", values.join(\", \"));\n}\n\nfunction compressResponse(response: Response, encoding: SupportedEncoding): Response {\n  const compressor =\n    encoding === \"br\" ? createBrotliCompress() : createGzip({ flush: constants.Z_SYNC_FLUSH });\n  const input = Readable.fromWeb(response.body as any);\n  const output = pipeline(input, compressor, () => {\n    // pipeline forwards source failures to the compressed body and destroys\n    // the source when the response consumer cancels it. The web stream owns\n    // observing the resulting destination error.\n  });\n  const headers = new Headers(response.headers);\n\n  headers.set(\"content-encoding\", encoding);\n  headers.delete(\"content-length\");\n  appendVary(headers, \"Accept-Encoding\");\n\n  const etag = headers.get(\"etag\");\n  if (etag && !etag.startsWith(\"W/\")) {\n    headers.set(\"etag\", `W/${etag}`);\n  }\n\n  return new Response(Readable.toWeb(output) as ReadableStream<Uint8Array>, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nfunction varyIdentityResponse(response: Response): Response {\n  const headers = new Headers(response.headers);\n  appendVary(headers, \"Accept-Encoding\");\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function createCompressionPlugin({\n  beforeRequest: overrideBeforeRequest,\n  afterResponse: overrideAfterResponse,\n}: {\n  beforeRequest?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n  afterResponse?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n} = {}): FarmPlugin {\n  return {\n    name: \"farm:compression\",\n    enforce: \"post\",\n\n    runtime: {\n      after({ request, response, isProd }) {\n        if (!isProd || !isCompressionEligible(request, response)) return;\n\n        if (request.method === \"HEAD\") return varyIdentityResponse(response);\n\n        const encoding = selectEncoding(request.headers.get(\"accept-encoding\") ?? \"\");\n        if (!encoding) return varyIdentityResponse(response);\n        return compressResponse(response, encoding);\n      },\n    },\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { FarmResponse } from \"../types\";\nimport type { FarmRequest } from \"../types\";\n\nexport function createLoggerPlugin({\n  beforeRequest,\n  afterResponse,\n}: {\n  beforeRequest?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n  afterResponse?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmPluginContext,\n  ) => void | Promise<void>;\n} = {}): FarmPlugin {\n  const plugin: FarmPlugin = {\n    name: \"farm:logger\",\n    enforce: \"post\",\n  };\n\n  if (beforeRequest) {\n    plugin.beforeRequest = async (req, res, context) => {\n      await beforeRequest(req, res, context);\n    };\n  }\n  if (afterResponse) {\n    plugin.afterResponse = async (req, res, context) => {\n      await afterResponse(req, res, context);\n    };\n  }\n\n  return plugin;\n}\n","export * from \"./endpoint\";\nexport * from \"./route-manager\";\nexport * from \"./client\";\nexport * from \"./config\";\nexport { resolveFarmAPIServerBasePath } from \"./server-path\";\nexport * from \"./transport\";\nexport * from \"./vite-plugin\";\nexport * from \"./route\";\n","import 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","/** 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","/// <reference lib=\"es2021.weakref\" />\nimport { createRouteDataCacheKey, type RouteDataCacheKey } from \"./cache\";\nimport { subscribeFarmCacheInvalidation } from \"./cache-invalidation\";\n\nexport type FarmClientCacheKey = RouteDataCacheKey;\n\nexport type FarmClientCacheStatus = \"idle\" | \"pending\" | \"success\" | \"error\";\n\nexport type FarmClientCacheEntry<TData = unknown> = {\n  data: TData;\n  updatedAt: number;\n  staleAt: number;\n  gcAt?: number;\n  invalidatedAt?: number;\n  status?: FarmClientCacheStatus;\n  error?: Error | null;\n  fetching?: boolean;\n  /** Marks an entry the persistence layer may write to its adapter. */\n  persist?: boolean;\n};\n\n/** @internal Observation seam for the client cache persistence engine. */\nexport type FarmClientCachePersistenceSink = {\n  onSet(key: string, entry: FarmClientCacheEntry): void;\n  onDelete(key: string): void;\n  onClear(): void;\n};\n\ntype FarmClientCacheListener = (event?: \"invalidate\") => void;\n\nconst invalidationTrackers = new WeakMap<FarmClientDataCache, Set<Set<string>>>();\n\n/** Internal request-lifetime tracking, including keys learned only from a response. */\nexport function trackFarmClientCacheInvalidations(cache: FarmClientDataCache) {\n  let trackers = invalidationTrackers.get(cache);\n  if (!trackers) {\n    trackers = new Set();\n    invalidationTrackers.set(cache, trackers);\n  }\n  const keys = new Set<string>();\n  trackers.add(keys);\n  return {\n    has(key: string) {\n      const resolved = cache.resolveKey(key);\n      for (const invalidated of keys) {\n        if (cache.resolveKey(invalidated) === resolved) return true;\n      }\n      return false;\n    },\n    dispose() {\n      if (!trackers.delete(keys)) return;\n      keys.clear();\n      if (trackers.size === 0) invalidationTrackers.delete(cache);\n    },\n  };\n}\n\nconst cacheFinalizer =\n  typeof FinalizationRegistry === \"function\"\n    ? new FinalizationRegistry<() => void>((unsubscribe) => unsubscribe())\n    : undefined;\n\n// This closure must only capture a weak reference, never the cache itself.\nfunction subscribeWeakCache(reference: WeakRef<FarmClientDataCache>): () => void {\n  const unsubscribe = subscribeFarmCacheInvalidation((key) => {\n    const cache = reference.deref();\n    if (cache) cache.invalidate(key);\n    else dispose();\n  });\n  function dispose() {\n    unsubscribe();\n    cacheFinalizer?.unregister(reference);\n  }\n  return dispose;\n}\n\nconst DEFAULT_GC_SWEEP_INTERVAL_MS = 30_000;\n\nexport class FarmClientDataCache {\n  private entries = new Map<string, FarmClientCacheEntry>();\n  private aliases = new Map<string, string>();\n  private invalidatedAt = new Map<string, number>();\n  private listeners = new Map<string, Set<FarmClientCacheListener>>();\n  private inflight = new Map<string, Promise<unknown>>();\n  private unsubscribeInvalidation: (() => void) | undefined;\n  private gcTimer: ReturnType<typeof setTimeout> | undefined;\n  private readonly gcSweepIntervalMs: number | false;\n  private persistence: FarmClientCachePersistenceSink | undefined;\n\n  constructor(\n    options: { subscribeToInvalidation?: boolean; gcSweepIntervalMs?: number | false } = {},\n  ) {\n    this.gcSweepIntervalMs = options.gcSweepIntervalMs ?? DEFAULT_GC_SWEEP_INTERVAL_MS;\n    if (options.subscribeToInvalidation !== false) {\n      if (typeof WeakRef === \"function\") {\n        const reference = new WeakRef(this);\n        const unsubscribe = subscribeWeakCache(reference);\n        cacheFinalizer?.register(this, unsubscribe, reference);\n        this.unsubscribeInvalidation = unsubscribe;\n      } else {\n        // Keep invalidation working on older runtimes without weak references.\n        this.unsubscribeInvalidation = subscribeFarmCacheInvalidation((key) =>\n          this.invalidate(key),\n        );\n      }\n    }\n  }\n\n  get size(): number {\n    return this.entries.size;\n  }\n\n  /** @internal Attach or detach the persistence engine's observation sink. */\n  attachPersistence(sink: FarmClientCachePersistenceSink | undefined): void {\n    this.persistence = sink;\n  }\n\n  resolveKey(key: string): string {\n    let resolved = key;\n    const seen = new Set<string>();\n\n    while (this.aliases.has(resolved) && !seen.has(resolved)) {\n      seen.add(resolved);\n      resolved = this.aliases.get(resolved)!;\n    }\n\n    return resolved;\n  }\n\n  get<TData = unknown>(key: string, now = Date.now()): FarmClientCacheEntry<TData> | undefined {\n    const resolved = this.resolveKey(key);\n    const entry = this.entries.get(resolved) as FarmClientCacheEntry<TData> | undefined;\n    if (!entry) return undefined;\n\n    if (entry.gcAt !== undefined && now >= entry.gcAt) {\n      this.entries.delete(resolved);\n      this.persistence?.onDelete(resolved);\n      this.emit(resolved);\n      return undefined;\n    }\n\n    return entry;\n  }\n\n  set<TData>(key: string, entry: FarmClientCacheEntry<TData>): this {\n    const resolved = this.resolveKey(key);\n    const invalidatedAt = this.invalidatedAt.get(resolved);\n    const nextEntry =\n      invalidatedAt !== undefined && invalidatedAt > entry.updatedAt\n        ? { ...entry, staleAt: 0, invalidatedAt }\n        : { ...entry, invalidatedAt: undefined };\n\n    if (invalidatedAt === undefined || entry.updatedAt >= invalidatedAt) {\n      this.invalidatedAt.delete(resolved);\n    }\n\n    this.entries.set(resolved, nextEntry);\n    if (nextEntry.gcAt !== undefined) this.scheduleGcSweep();\n    this.persistence?.onSet(resolved, nextEntry);\n    this.emit(resolved);\n    return this;\n  }\n\n  delete(key: string): boolean {\n    const resolved = this.resolveKey(key);\n    const deleted = this.entries.delete(resolved);\n    this.inflight.delete(resolved);\n    if (deleted) this.persistence?.onDelete(resolved);\n    this.emit(resolved);\n    return deleted;\n  }\n\n  clear(): void {\n    const keys = new Set([...this.entries.keys(), ...this.listeners.keys()]);\n    this.entries.clear();\n    this.aliases.clear();\n    this.invalidatedAt.clear();\n    this.inflight.clear();\n    this.persistence?.onClear();\n    for (const key of keys) this.emit(key);\n  }\n\n  dispose(): void {\n    this.unsubscribeInvalidation?.();\n    this.unsubscribeInvalidation = undefined;\n    if (this.gcTimer !== undefined) {\n      clearTimeout(this.gcTimer);\n      this.gcTimer = undefined;\n    }\n    this.clear();\n  }\n\n  isStale(key: string, now = Date.now()): boolean {\n    const entry = this.get(key, now);\n    return !entry || entry.invalidatedAt !== undefined || now >= entry.staleAt;\n  }\n\n  invalidate(key: string, now = Date.now()): void {\n    const resolved = this.resolveKey(key);\n    for (const keys of invalidationTrackers.get(this) ?? []) keys.add(resolved);\n    this.invalidatedAt.set(resolved, now);\n\n    const entry = this.entries.get(resolved);\n    if (entry) {\n      this.entries.set(resolved, {\n        ...entry,\n        staleAt: 0,\n        invalidatedAt: now,\n      });\n    }\n\n    this.emit(resolved, \"invalidate\");\n  }\n\n  alias(alias: string, key: string): void {\n    const resolved = this.resolveKey(key);\n    if (alias === resolved) return;\n\n    const aliasEntry = this.entries.get(alias);\n    const aliasInvalidatedAt = this.invalidatedAt.get(alias) ?? aliasEntry?.invalidatedAt;\n    const resolvedInvalidatedAt = this.invalidatedAt.get(resolved);\n    if (aliasEntry && !this.entries.has(resolved)) {\n      this.entries.set(resolved, aliasEntry);\n      this.persistence?.onSet(resolved, aliasEntry);\n    }\n\n    if (this.entries.delete(alias)) this.persistence?.onDelete(alias);\n    this.invalidatedAt.delete(alias);\n    const invalidatedAt = [aliasInvalidatedAt, resolvedInvalidatedAt].reduce<number | undefined>(\n      (latest, value) =>\n        value === undefined ? latest : latest === undefined ? value : Math.max(latest, value),\n      undefined,\n    );\n    const resolvedEntry = this.entries.get(resolved);\n    if (\n      invalidatedAt !== undefined &&\n      (!resolvedEntry || invalidatedAt > resolvedEntry.updatedAt)\n    ) {\n      this.invalidatedAt.set(resolved, invalidatedAt);\n      if (resolvedEntry) {\n        this.entries.set(resolved, {\n          ...resolvedEntry,\n          staleAt: 0,\n          invalidatedAt,\n        });\n      }\n    } else if (invalidatedAt !== undefined) {\n      this.invalidatedAt.delete(resolved);\n      if (resolvedEntry?.invalidatedAt !== undefined) {\n        this.entries.set(resolved, { ...resolvedEntry, invalidatedAt: undefined });\n      }\n    }\n\n    const aliasInflight = this.inflight.get(alias);\n    if (aliasInflight && !this.inflight.has(resolved)) {\n      this.inflight.set(resolved, aliasInflight);\n    }\n    this.inflight.delete(alias);\n    this.aliases.set(alias, resolved);\n    this.emit(alias);\n    this.emit(resolved, this.invalidatedAt.has(resolved) ? \"invalidate\" : undefined);\n  }\n\n  subscribe(key: string, listener: FarmClientCacheListener): () => void {\n    let listeners = this.listeners.get(key);\n    if (!listeners) {\n      listeners = new Set();\n      this.listeners.set(key, listeners);\n    }\n\n    listeners.add(listener);\n    return () => {\n      listeners!.delete(listener);\n      // Only drop the map entry if it still holds this exact set. A repeated or\n      // stale unsubscribe (called after the key was drained and resubscribed)\n      // must not evict a newer subscriber's live listener set.\n      if (listeners!.size === 0 && this.listeners.get(key) === listeners) {\n        this.listeners.delete(key);\n      }\n    };\n  }\n\n  getInflight<TData>(key: string): Promise<TData> | undefined {\n    return this.inflight.get(this.resolveKey(key)) as Promise<TData> | undefined;\n  }\n\n  setInflight<TData>(key: string, promise: Promise<TData>): void {\n    this.inflight.set(this.resolveKey(key), promise);\n  }\n\n  deleteInflight(key: string): void {\n    this.inflight.delete(this.resolveKey(key));\n  }\n\n  private scheduleGcSweep(): void {\n    if (this.gcSweepIntervalMs === false || this.gcTimer !== undefined) return;\n    const timer = setTimeout(() => {\n      this.gcTimer = undefined;\n      this.sweepExpiredEntries();\n    }, this.gcSweepIntervalMs);\n    // Cache cleanup must never keep a Node.js process (SSR, tests) alive.\n    (timer as unknown as { unref?: () => void }).unref?.();\n    this.gcTimer = timer;\n  }\n\n  private sweepExpiredEntries(now = Date.now()): void {\n    const watched = new Set<string>();\n    for (const key of this.listeners.keys()) watched.add(this.resolveKey(key));\n\n    let remaining = false;\n    const swept = new Set<string>();\n    for (const [key, entry] of this.entries) {\n      if (entry.gcAt === undefined) continue;\n      if (now < entry.gcAt || entry.fetching || this.inflight.has(key) || watched.has(key)) {\n        remaining = true;\n        continue;\n      }\n      // Only unwatched entries are swept, so eviction is unobservable: a read\n      // of this key would already evict it lazily before returning data.\n      this.entries.delete(key);\n      this.persistence?.onDelete(key);\n      swept.add(key);\n    }\n\n    if (swept.size > 0) this.sweepEntryMetadata(swept);\n    if (remaining) this.scheduleGcSweep();\n  }\n\n  /**\n   * Entry eviction alone leaves the per-key metadata behind. `invalidatedAt`\n   * marks and provisional aliases are created per query invocation, so with\n   * dynamic keys they accumulate for the lifetime of the page even though the\n   * entries they describe are long gone.\n   */\n  private sweepEntryMetadata(swept: Set<string>): void {\n    for (const key of swept) this.invalidatedAt.delete(key);\n\n    for (const [alias, target] of this.aliases) {\n      // Keep any alias that is still addressable: one that has its own entry,\n      // that something is subscribed to, or whose target is still live.\n      if (this.entries.has(alias) || this.listeners.has(alias)) continue;\n      const resolved = this.resolveKey(target);\n      if (!swept.has(resolved)) continue;\n      if (this.entries.has(resolved) || this.listeners.has(resolved)) continue;\n      this.aliases.delete(alias);\n      this.invalidatedAt.delete(alias);\n    }\n  }\n\n  private emit(key: string, event?: \"invalidate\"): void {\n    this.notifyListeners(key, event);\n    for (const [alias, target] of this.aliases) {\n      if (this.resolveKey(target) === key) {\n        this.notifyListeners(alias, event);\n      }\n    }\n  }\n\n  private notifyListeners(key: string, event?: \"invalidate\"): void {\n    for (const listener of this.listeners.get(key) ?? []) {\n      // One subscriber must not be able to break the others, or to make an\n      // ordinary cache write or invalidation throw in its caller. This matches\n      // the isolation the global invalidation bus already provides.\n      try {\n        listener(event);\n      } catch (error) {\n        const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);\n        console.warn(`[farm:client-cache] cache listener failed: ${detail}`);\n      }\n    }\n  }\n}\n\nconst FARM_CLIENT_DATA_CACHE = Symbol.for(\"farm.clientDataCache\");\nconst clientCacheGlobal = globalThis as typeof globalThis & {\n  [FARM_CLIENT_DATA_CACHE]?: FarmClientDataCache;\n};\nconst sharedFarmClientDataCache = (clientCacheGlobal[FARM_CLIENT_DATA_CACHE] ??=\n  new FarmClientDataCache());\n\nexport function getFarmClientDataCache(): FarmClientDataCache {\n  return sharedFarmClientDataCache;\n}\n\nexport function normalizeFarmClientCacheKey(key: FarmClientCacheKey): string {\n  return typeof key === \"string\" ? key : createRouteDataCacheKey(key);\n}\n","import {\n  integrationsClient,\n  integrationsServer,\n  type IntegrationClientOptions,\n  type IntegrationClientRoot,\n  type IntegrationServerClientOptions,\n  type IntegrationServerClientRoot,\n} from \"../integration-client\";\nimport {\n  FarmClientDataCache,\n  getFarmClientDataCache,\n  normalizeFarmClientCacheKey,\n  type FarmClientCacheEntry,\n  type FarmClientCacheKey,\n} from \"../client-cache\";\nimport {\n  applyFarmCacheInvalidations,\n  decodeFarmCacheInvalidations,\n  FARM_CACHE_INVALIDATION_HEADER,\n} from \"../cache-invalidation\";\nimport type { DefinedCacheKey, InferCacheKeyData, RouteDataCacheKey } from \"../cache\";\nimport { getFarmAPIBaseURL, resolveFarmAPIRequestURL } from \"./config\";\nimport { ClientRouteManifest, type APIRouteManifest, type BoundRouteParams } from \"./client-routes\";\nimport type { RoutePathParams } from \"./route\";\nimport { _resolveCurrentRequest } from \"../server/request-bridge\";\nimport { resolveClientHeaders, type ClientHeaders } from \"../client-headers\";\nimport { createClientCancellation } from \"../client-cancellation\";\nimport { notifyClientObserver, type ClientLifecycleHooks } from \"../client-observers\";\nimport { resolveAPIRequestRuntime, type APIRequestRuntime } from \"./server-client-bridge\";\nexport type { APIRouteManifest } from \"./client-routes\";\nimport {\n  isFarmAPIStream,\n  isJSONStreamResponse,\n  readJSONStream,\n  type FarmAPIStream,\n} from \"./transport\";\n\nexport const FARM_API_ROUTE_REF_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-ref\") as any;\nexport const FARM_API_ROUTE_META_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-meta\") as any;\n\nexport type APIRouteRefMetadata = {\n  path: string;\n  method: string;\n  baseURL: string;\n  sameOrigin: boolean;\n};\n\nexport type APIClientOptions = ClientLifecycleHooks & {\n  /** Generated path/method metadata required for dynamic shorthand and $params scopes. */\n  routes?: APIRouteManifest;\n  baseURL?: string;\n  headers?: ClientHeaders;\n  credentials?: RequestCredentials;\n  /** Whole-call deadline in milliseconds. 0 (default) disables it. */\n  timeoutMs?: number;\n  /** HTTP transport only; local server dispatch does not use it. */\n  fetch?: typeof globalThis.fetch;\n  cacheDefaults?: CacheOptions;\n  integrations?: IntegrationClientOptions;\n};\n\nexport type APIClientWithoutIntegrationsOptions = Omit<APIClientOptions, \"integrations\"> & {\n  integrations: false;\n};\n\nexport type ServerAPIClientOptions = {\n  integrations?: Omit<IntegrationServerClientOptions, \"isServer\">;\n};\n\nexport type ServerAPIClientWithoutIntegrationsOptions = Omit<\n  ServerAPIClientOptions,\n  \"integrations\"\n> & {\n  integrations: false;\n};\n\nexport type StatusPhase = \"idle\" | \"pending\" | \"success\" | \"error\" | \"revalidating\" | \"invalidated\";\n\nexport type StatusEvent<TData = unknown, TError = unknown> = {\n  phase: StatusPhase;\n  requestId: string;\n  method: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n  key: string;\n  input?: unknown;\n  data?: TData;\n  error?: TError;\n  isBackground?: boolean;\n  timestamp: number;\n};\n\nexport type CacheKey<TData = unknown> = string & {\n  readonly __farmCacheData?: TData;\n};\n\nexport type APIResult<TData = unknown, TError = Error> = {\n  data: TData | undefined;\n  error: TError | null;\n  key: CacheKey<TData>;\n};\n\nexport class APIClientError<\n  TCode extends string = string,\n  TData = unknown,\n  TStatus extends number = number,\n> extends Error {\n  readonly code: TCode;\n  readonly data: TData;\n  readonly status: TStatus;\n  readonly response?: Response;\n\n  constructor(\n    code: TCode,\n    data: TData,\n    options: {\n      status: TStatus;\n      message: string;\n      response?: Response;\n    },\n  ) {\n    super(options.message);\n    this.name = \"APIClientError\";\n    this.code = code;\n    this.data = data;\n    this.status = options.status;\n    this.response = options.response;\n  }\n}\n\nexport type APIClientSystemError =\n  | APIClientError<\"http_error\", unknown, number>\n  | APIClientError<\"aborted\" | \"timeout\", unknown, 0>\n  | APIClientError<\"network_error\", unknown, 0>;\n\nexport type RequestEvent = {\n  requestId: string;\n  method: StatusEvent[\"method\"];\n  key: string;\n  path: string;\n  input?: unknown;\n  attempt: number;\n  timestamp: number;\n};\n\nexport type ResponseEvent<TData = unknown, TError = Error> = {\n  requestId: string;\n  method: StatusEvent[\"method\"];\n  key: string;\n  path: string;\n  input?: unknown;\n  attempt: number;\n  timestamp: number;\n  response?: Response;\n  data?: TData;\n  error?: TError;\n  ok?: boolean;\n  status?: number;\n};\n\nexport type CachePolicy = \"cache-first\" | \"network-only\" | \"stale-while-revalidate\";\nexport type CacheScope = \"client\" | \"shared\";\n\nexport type CacheOptions = {\n  key?: FarmClientCacheKey;\n  policy?: CachePolicy;\n  /** Select client-local or public shared storage. Identity-carrying requests always stay local. */\n  scope?: CacheScope;\n  staleTime?: number;\n  gcTime?: number;\n  dedupeMs?: number;\n  /** Allow the configured client cache persistence adapter to store this read. */\n  persist?: boolean;\n};\n\nexport type RetryOptions = {\n  count?: number;\n  delay?: number | ((attempt: number) => number);\n};\n\nexport type InvalidateTarget =\n  | FarmClientCacheKey\n  | {\n      key: FarmClientCacheKey;\n    }\n  | {\n      path: string;\n      method?: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n      input?: unknown;\n    }\n  | [CallableRouteRef<any>, unknown?];\n\nexport type InvalidateOptions =\n  | InvalidateTarget[]\n  | {\n      targets: InvalidateTarget[];\n      refetch?: boolean;\n    };\n\nexport type OptimisticUpdate =\n  | [CallableRouteRef<any>, unknown, (prev: any) => any]\n  | [CacheKey<any> | DefinedCacheKey<any> | string, (prev: any) => any];\n\nexport type OptimisticOptions<TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]> = {\n  update: TUpdates & NormalizeOptimisticUpdates<TUpdates>;\n  rollbackOnError?: boolean;\n};\n\nexport type ClientOptions<\n  TData = unknown,\n  TError = unknown,\n  TUpdates extends readonly unknown[] = readonly OptimisticUpdate[],\n> = {\n  key?: CacheKey<TData> | FarmClientCacheKey;\n  signal?: AbortSignal;\n  /** Override the instance deadline; 0 disables it for this call. */\n  timeoutMs?: number;\n  cache?: CacheOptions;\n  retry?: RetryOptions;\n  invalidate?: InvalidateOptions;\n  optimistic?: OptimisticOptions<TUpdates>;\n  onRequest?: (event: RequestEvent) => void;\n  onResponse?: (\n    data: TData | undefined,\n    error: TError | null,\n    event: ResponseEvent<TData, TError>,\n  ) => void;\n  onSuccess?: (data: TData) => void;\n  onError?: (err: TError) => void;\n  onSettled?: (data?: TData, err?: TError | null) => void;\n  onStatus?: (event: StatusEvent<TData, TError>) => void;\n};\n\ntype AnyRouteRef = (...args: any[]) => any;\ntype RouteRef<TData = any, TInput = any> = {\n  readonly __farmRouteInput: TInput;\n  readonly __farmRouteData: TData;\n};\ntype CallableRouteRef<TData = any, TInput = any> = AnyRouteRef & RouteRef<TData, TInput>;\n\ntype InferRouteInput<TRoute> = TRoute extends { readonly __farmRouteInput: infer TInput }\n  ? TInput\n  : never;\ntype InferRouteData<TRoute> = TRoute extends { readonly __farmRouteData: infer TData }\n  ? TData\n  : never;\n\ntype NormalizeOptimisticUpdate<TUpdate> = TUpdate extends readonly [\n  infer TRoute,\n  unknown,\n  (prev: any) => any,\n]\n  ? TRoute extends RouteRef<any, any>\n    ? [\n        TRoute,\n        InferRouteInput<TRoute> | undefined,\n        (prev: InferRouteData<TRoute> | undefined) => InferRouteData<TRoute>,\n      ]\n    : never\n  : TUpdate extends readonly [infer TKey, (prev: any) => any]\n    ? TKey extends DefinedCacheKey<any, RouteDataCacheKey>\n      ? [TKey, (prev: InferCacheKeyData<TKey> | undefined) => InferCacheKeyData<TKey>]\n      : TKey extends CacheKey<infer TData>\n        ? [TKey, (prev: TData | undefined) => TData]\n        : TKey extends string\n          ? [TKey, (prev: unknown) => unknown]\n          : never\n    : never;\n\ntype NormalizeOptimisticUpdates<TUpdates extends readonly unknown[]> = {\n  [K in keyof TUpdates]: NormalizeOptimisticUpdate<TUpdates[K]>;\n};\n\ntype TypedEndpointLike = {\n  __types: {\n    body: any;\n    query: any;\n    response: any;\n    errors?: any;\n  };\n};\n\ntype Simplify<T> = {\n  [K in keyof T]: T[K];\n} & {};\n\ntype IsNever<T> = [T] extends [never] ? true : false;\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype RequiredKeys<T> = T extends object\n  ? {\n      [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n    }[keyof T]\n  : never;\n\ntype BodyInputProp<TValue> =\n  IsNever<TValue> extends true\n    ? {}\n    : IsAny<TValue> extends true\n      ? { body?: TValue }\n      : undefined extends TValue\n        ? { body?: TValue }\n        : { body: TValue };\n\ntype QueryInputProp<TValue> =\n  IsNever<TValue> extends true\n    ? {}\n    : IsAny<TValue> extends true\n      ? { query?: TValue }\n      : undefined extends TValue\n        ? { query?: TValue }\n        : RequiredKeys<TValue> extends never\n          ? { query?: TValue }\n          : { query: TValue };\n\ntype HasRequiredKeys<T> = RequiredKeys<T> extends never ? false : true;\n\n// Type utilities to extract endpoint input/output types from TypedEndpoint\ntype InferEndpointBody<T> = T extends {\n  __types: {\n    inputBody: infer TInputBody;\n  };\n}\n  ? TInputBody\n  : T extends {\n        __types: {\n          body: infer TBody;\n        };\n      }\n    ? TBody\n    : never;\n\ntype InferEndpointInput<T> = T extends {\n  __types: {\n    query: infer TQuery;\n  };\n}\n  ? Simplify<\n      BodyInputProp<InferEndpointBody<T>> &\n        QueryInputProp<T extends { __types: { inputQuery: infer I } } ? I : TQuery> &\n        (T extends { __routeParams: infer P }\n          ? keyof P extends never\n            ? { params?: never }\n            : { params: P }\n          : {}) &\n        (T extends { __types: { inputHeaders: infer H } }\n          ? IsNever<H> extends true\n            ? {}\n            : RequiredKeys<H> extends never\n              ? { headers?: H }\n              : { headers: H }\n          : {})\n    >\n  : T extends { __routeParams: infer P }\n    ? keyof P extends never\n      ? { params?: never }\n      : { params: P }\n    : {};\n\ntype InferEndpointOutput<T> = T extends {\n  __types: {\n    response: infer R;\n  };\n}\n  ? R extends { readonly __farmStreamItem: infer TItem }\n    ? FarmAPIStream<TItem>\n    : R\n  : any;\n\ntype InferEndpointError<T> = T extends {\n  __types: {\n    errors: infer TErrors;\n  };\n}\n  ? keyof TErrors extends never\n    ? Error\n    :\n        | {\n            [TCode in keyof TErrors]: TErrors[TCode] extends {\n              data: infer TData;\n              status: infer TStatus extends number;\n            }\n              ? APIClientError<TCode & string, TData, TStatus>\n              : never;\n          }[keyof TErrors]\n        | APIClientSystemError\n  : Error;\n\n// Type for a single endpoint method\ntype EndpointCall<T = any> = <TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]>(\n  ...args: HasRequiredKeys<InferEndpointInput<T>> extends true\n    ? [\n        options: InferEndpointInput<T>,\n        clientOptions?: ClientOptions<InferEndpointOutput<T>, InferEndpointError<T>, TUpdates>,\n      ]\n    : [\n        options?: InferEndpointInput<T>,\n        clientOptions?: ClientOptions<InferEndpointOutput<T>, InferEndpointError<T>, TUpdates>,\n      ]\n) => Promise<APIResult<InferEndpointOutput<T>, InferEndpointError<T>>>;\ntype EndpointMethod<T = any> = EndpointCall<T> &\n  RouteRef<InferEndpointOutput<T>, InferEndpointInput<T>>;\n\ntype DynamicKeys<T> = Extract<keyof T, `[${string}]`>;\ntype MethodKeys = \"get\" | \"head\" | \"query\" | \"post\" | \"put\" | \"patch\" | \"delete\" | \"options\";\ntype OwnMethodKeys<T> = {\n  [K in Extract<keyof T, MethodKeys>]: T[K] extends TypedEndpointLike | ((...args: any[]) => any)\n    ? K\n    : never;\n}[Extract<keyof T, MethodKeys>];\ntype WithRouteParams<T, P> = T & { __routeParams: P };\ntype UnionToIntersection<U> = (U extends unknown ? (v: U) => void : never) extends (\n  v: infer I,\n) => void\n  ? I\n  : never;\ntype ChildMethods<T> = { [K in DynamicKeys<T>]: OwnMethodKeys<T[K]> }[DynamicKeys<T>];\ntype MethodEndpoints<T, M extends PropertyKey, P> =\n  | (M extends OwnMethodKeys<T> ? WithRouteParams<T[M], P> : never)\n  | {\n      [K in DynamicKeys<T>]: M extends keyof T[K]\n        ? WithRouteParams<T[K][M], P & RoutePathParams<K>>\n        : never;\n    }[DynamicKeys<T>];\ntype DistributedCall<T> = T extends unknown ? EndpointCall<T> : never;\ntype ScopedMethod<T> = UnionToIntersection<DistributedCall<T>> &\n  EndpointCall<T> &\n  RouteRef<InferEndpointOutput<T>, InferEndpointInput<T>>;\n\n// Keep bracket access for compatibility; explicit binding preserves intermediate segments.\ntype RouterToClient<T, P = {}> = {\n  [K in Exclude<keyof T, OwnMethodKeys<T>>]: T[K] extends TypedEndpointLike\n    ? EndpointMethod<WithRouteParams<T[K], P>>\n    : T[K] extends Record<string, any>\n      ? RouterToClient<T[K], P & (K extends string ? RoutePathParams<K> : {})>\n      : EndpointMethod<WithRouteParams<T[K], P>>;\n} & {\n  [M in OwnMethodKeys<T> | ChildMethods<T>]: M extends ChildMethods<T>\n    ? ScopedMethod<MethodEndpoints<T, M, P>>\n    : M extends keyof T\n      ? EndpointMethod<WithRouteParams<T[M], P>>\n      : never;\n} & ([DynamicKeys<T>] extends [never]\n    ? {}\n    : {\n        $params: UnionToIntersection<\n          {\n            [K in DynamicKeys<T>]: (params: RoutePathParams<K>) => RouterToClient<T[K], P>;\n          }[DynamicKeys<T>]\n        >;\n      });\n\nexport type RouteAPIClient<TRouter extends Record<string, any>> = RouterToClient<TRouter>;\n\nexport type APIClient<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n> = RouteAPIClient<TRouter> & IntegrationClientRoot<TIntegrations>;\n\nexport type ServerAPIClient<\n  TEndpoints extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n> = TEndpoints & IntegrationServerClientRoot<TIntegrations>;\n\nexport type ApiClients<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n> = {\n  api: RouteAPIClient<TRouter> & IntegrationServerClientRoot<TIntegrations>;\n  apiClient: APIClient<TRouter, TIntegrations>;\n};\n\n/**\n * Define one shared pair of typed callers. Import only generated route metadata\n * here, not endpoint modules. `api` dispatches locally during a Farm request;\n * `apiClient` uses HTTP. Both return the same app-route APIResult shape.\n */\nexport function createApiClients<TRouter extends Record<string, any>>(\n  options: APIClientWithoutIntegrationsOptions,\n): { api: RouteAPIClient<TRouter>; apiClient: RouteAPIClient<TRouter> };\nexport function createApiClients<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(options?: APIClientOptions): ApiClients<TRouter, TIntegrations>;\nexport function createApiClients<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n): ApiClients<TRouter, TIntegrations> {\n  // A module-level pair is safe across requests. No cache, credentials, or\n  // dispatcher from one request is retained by another request's caller.\n  const localScopes = new WeakMap<APIRequestRuntime, WeakMap<Request, { request: APICall }>>();\n  const routeMeta = new WeakMap<AnyRouteRef, RouteMeta>();\n  const api = createNestedProxy(\n    [],\n    async (path: string, method: string, input: any, clientOptions?: ClientOptions<any, any>) => {\n      if (typeof window !== \"undefined\") {\n        throw new Error(\n          \"api is server-only. Use apiClient from createApiClients() in the browser.\",\n        );\n      }\n      const currentRequest = _resolveCurrentRequest();\n      const runtime = resolveAPIRequestRuntime();\n      if (!currentRequest || !runtime) {\n        throw new Error(\n          \"api requires an active Farm server request. Call it from a server page, query, action, or API handler; use apiClient with an absolute baseURL for standalone HTTP calls.\",\n        );\n      }\n      let localClients = localScopes.get(runtime);\n      if (!localClients) {\n        localClients = new WeakMap();\n        localScopes.set(runtime, localClients);\n      }\n      let local = localClients.get(currentRequest);\n      if (!local) {\n        const origin = new URL(currentRequest.url).origin;\n        const headers = new Headers();\n        // Only identity/content negotiation headers are inherited. In\n        // particular, never copy the outer request's body or hop-by-hop fields.\n        for (const name of [\"cookie\", \"authorization\", \"accept-language\"]) {\n          const value = currentRequest.headers.get(name);\n          if (value !== null) headers.set(name, value);\n        }\n        local = createAPIClientRuntime(\n          {\n            ...options,\n            integrations: false,\n            baseURL: new URL(runtime.basePath, origin).toString(),\n          },\n          {\n            headers,\n            signal: currentRequest.signal,\n            cache: new FarmClientDataCache({ subscribeToInvalidation: false }),\n            routeMeta,\n            fetch: (url, init) => {\n              if (new URL(url).origin !== origin) {\n                throw new Error(\n                  \"api can only dispatch to this Farm app. Use apiClient for HTTP calls.\",\n                );\n              }\n              currentRequest.signal.throwIfAborted();\n              return runtime.dispatch(new Request(url, init));\n            },\n          },\n        );\n        localClients.set(currentRequest, local);\n      }\n      return local.request(path, method, input, clientOptions);\n    },\n    routeMeta,\n    \"/api\",\n    true,\n    options.integrations === false\n      ? undefined\n      : {\n          integrations: integrationsServer<TIntegrations>({\n            baseURL: options.baseURL,\n            headers: options.headers,\n            credentials: options.credentials,\n            timeoutMs: options.timeoutMs,\n            fetch: options.fetch,\n            onRequest: options.onRequest,\n            onResponse: options.onResponse,\n            onError: options.onError,\n            ...options.integrations,\n          }),\n        },\n    options.routes ? new ClientRouteManifest(options.routes) : undefined,\n  );\n  return {\n    api: api as ApiClients<TRouter, TIntegrations>[\"api\"],\n    apiClient: createAPIClient<TRouter, TIntegrations>(options as APIClientOptions),\n  };\n}\n\n/**\n * Create a typed RPC client for Farm.js API routes\n *\n * Returns a nested proxy that supports:\n * - api.hello.get({ query: { name: 'World' } })\n * - api['auth/login'].post({ body: { email: '...', password: '...' } })\n * - api.users.get({ query: { limit: '10' } })\n * - api.integrations.billing.checkout({ body: { priceId: 'price_...' } })\n *\n * @example\n * ```typescript\n * import { createAPIClient } from 'farm/client';\n * import type { APIRouter } from '@/api';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createAPIClient<APIRouter, AppIntegrations>();\n *\n * // Use it (nested property access)\n * const result = await api.hello.get({ query: { name: 'World' } });\n * if (result.error) console.error(result.error);\n * else console.log(result.data);\n *\n * // Or with string keys for nested paths\n * const result = await api['auth/login'].post({\n *   body: { email: 'test@example.com', password: 'pass123' }\n * });\n *\n * // Integration APIs live under a reserved namespace.\n * const checkout = await api.integrations.billing.checkout({\n *   body: { priceId: 'price_123' }\n * });\n * ```\n */\nexport function createAPIClient<TRouter extends Record<string, any>>(\n  options: APIClientWithoutIntegrationsOptions,\n): RouteAPIClient<TRouter>;\nexport function createAPIClient<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(options?: APIClientOptions): APIClient<TRouter, TIntegrations>;\nexport function createAPIClient<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n): RouteAPIClient<TRouter> | APIClient<TRouter, TIntegrations> {\n  return createAPIClientRuntime<TRouter, TIntegrations>(options).client;\n}\n\ntype APICall = (\n  path: string,\n  method: string,\n  input?: any,\n  options?: ClientOptions<any, any>,\n) => Promise<APIResult<any, Error>>;\n\nfunction createAPIClientRuntime<\n  TRouter extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  options: APIClientOptions | APIClientWithoutIntegrationsOptions = {},\n  transport?: {\n    headers?: HeadersInit;\n    signal?: AbortSignal;\n    fetch(url: string, init: RequestInit): Promise<Response>;\n    cache: FarmClientDataCache;\n    routeMeta: WeakMap<AnyRouteRef, RouteMeta>;\n  },\n): { client: APIClient<TRouter, TIntegrations>; request: APICall } {\n  options ??= {};\n  const baseURL = options.baseURL || getFarmAPIBaseURL();\n  const httpFetch = options.fetch;\n  const integrationOptions =\n    options.integrations === false\n      ? false\n      : {\n          baseURL: options.baseURL,\n          headers: options.headers,\n          credentials: options.credentials,\n          timeoutMs: options.timeoutMs,\n          fetch: httpFetch,\n          onRequest: options.onRequest,\n          onResponse: options.onResponse,\n          onError: options.onError,\n          ...(typeof options.integrations === \"object\" ? options.integrations : {}),\n        };\n  const rootAliases =\n    integrationOptions === false\n      ? undefined\n      : {\n          integrations: integrationsClient<TIntegrations>(integrationOptions),\n        };\n\n  const sharedCacheState = transport?.cache ?? getFarmClientDataCache();\n  const localCaches = transport ? new Set([sharedCacheState]) : undefined;\n  const sharedInflightState = new Map<string, InflightEntry>();\n  let scopedRequestState: ScopedRequestState | undefined;\n  const routeMeta = transport?.routeMeta ?? new WeakMap<AnyRouteRef, RouteMeta>();\n  let requestCounter = 0;\n\n  // Create a simple fetch-based client (browser compatible)\n  const fetchClient = async (\n    path: string,\n    requestOptions: any,\n    defaultHeaders: Headers,\n    cancellation: ReturnType<typeof createClientCancellation>,\n  ) => {\n    const url = resolveFarmAPIRequestURL(path, baseURL);\n    const method = String(requestOptions.method || \"GET\").toUpperCase();\n\n    // Handle query parameters\n    if (requestOptions.query) {\n      Object.entries(requestOptions.query).forEach(([key, value]) => {\n        if (value === undefined || value === null) return;\n        url.searchParams.delete(key);\n        const values = Array.isArray(value) ? value : [value];\n        for (const item of values) {\n          if (item !== undefined && item !== null) url.searchParams.append(key, String(item));\n        }\n      });\n    }\n\n    // Prepare fetch options\n    const headers = new Headers(defaultHeaders);\n    new Headers(requestOptions.headers).forEach((value, key) => headers.set(key, value));\n    const fetchOptions: RequestInit = {\n      method,\n      headers,\n      credentials: options.credentials,\n      signal: cancellation.signal,\n    };\n    if (method === \"QUERY\" && !headers.has(\"content-type\")) {\n      headers.set(\"content-type\", \"application/json\");\n    }\n\n    // Handle body\n    if (requestOptions.body !== undefined) {\n      if (isFormData(requestOptions.body)) {\n        headers.delete(\"content-type\");\n        fetchOptions.body = requestOptions.body;\n      } else {\n        if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n        fetchOptions.body = JSON.stringify(requestOptions.body);\n      }\n    }\n\n    cancellation.check();\n    const response = await (transport?.fetch ?? httpFetch ?? fetch)(url.toString(), fetchOptions);\n    cancellation.check();\n    const invalidations = decodeFarmCacheInvalidations(\n      response.headers?.get?.(FARM_CACHE_INVALIDATION_HEADER),\n    );\n    if (transport) {\n      for (const cache of localCaches!) {\n        for (const key of invalidations) cache.invalidate(key);\n      }\n    } else {\n      applyFarmCacheInvalidations(invalidations);\n    }\n    let data: unknown;\n    try {\n      data = await readAPIResponseData(response, method);\n      cancellation.check();\n    } catch (decodeError) {\n      if (!(decodeError instanceof APIResponseDecodeError)) throw decodeError;\n      if (response.ok) throw decodeError.cause;\n      return { response, data: undefined, decodeError: decodeError.cause };\n    }\n\n    return { response, data };\n  };\n\n  const request = async (\n    path: string,\n    method: string,\n    input: any = {},\n    clientOptions?: ClientOptions<any, any>,\n  ): Promise<APIResult<any, Error>> => {\n    const cancellation = createClientCancellation(\n      clientOptions?.signal,\n      clientOptions?.timeoutMs ?? options.timeoutMs,\n      transport?.signal,\n    );\n    const normalizeCallError = (error: unknown): Error => {\n      if (!cancellation.signal?.aborted) return normalizeError(error);\n      const normalized = new APIClientError(\n        cancellation.timedOut ? \"timeout\" : \"aborted\",\n        undefined,\n        {\n          status: 0,\n          message: cancellation.timedOut ? \"Client request timed out\" : \"Client request aborted\",\n        },\n      );\n      (normalized as Error & { cause?: unknown }).cause = cancellation.signal.reason;\n      return normalized;\n    };\n    try {\n      const methodUpper = method.toUpperCase() as StatusEvent[\"method\"];\n      const requestId = `${Date.now()}-${++requestCounter}`;\n      const defaultHeaders = new Headers(transport?.headers);\n      let requestContextError: Error | undefined;\n      try {\n        cancellation.check();\n        const resolved = resolveClientHeaders(options.headers);\n        const headers =\n          resolved instanceof Headers ? resolved : await cancellation.run(() => resolved);\n        cancellation.check();\n        headers.forEach((value, name) => defaultHeaders.set(name, value));\n      } catch (error) {\n        requestContextError = normalizeCallError(error);\n      }\n      const cacheOptions = clientOptions?.cache\n        ? {\n            ...options.cacheDefaults,\n            ...clientOptions.cache,\n          }\n        : undefined;\n      const configuredCacheKey = clientOptions?.key ?? cacheOptions?.key;\n      const cacheKey = normalizeFarmClientCacheKey(\n        configuredCacheKey ?? buildCacheKey(methodUpper, path, input, baseURL, defaultHeaders),\n      ) as CacheKey<any>;\n      const now = Date.now();\n\n      const emitStatus = (phase: StatusPhase, payload?: Partial<StatusEvent>) => {\n        clientOptions?.onStatus?.({\n          phase,\n          requestId,\n          method: methodUpper,\n          key: cacheKey,\n          input,\n          timestamp: Date.now(),\n          ...payload,\n        });\n      };\n\n      const policy = cacheOptions?.policy ?? (cacheOptions ? \"cache-first\" : \"network-only\");\n      const staleTime = cacheOptions?.staleTime ?? 0;\n      const hasReliableDefaultCacheKey =\n        methodUpper !== \"QUERY\" || !isFormData(input?.body) || configuredCacheKey !== undefined;\n      const isCacheEnabled =\n        Boolean(cacheOptions) &&\n        (methodUpper === \"GET\" || methodUpper === \"QUERY\") &&\n        hasReliableDefaultCacheKey;\n      const needsCacheState =\n        isCacheEnabled ||\n        Boolean(clientOptions?.optimistic?.update?.length) ||\n        Boolean(clientOptions?.invalidate);\n      let requestCacheContext = requestContextError ? `invalid:${requestId}` : undefined;\n      if (needsCacheState && !requestContextError) {\n        try {\n          requestCacheContext = getRequestCacheContext(\n            { headers: defaultHeaders, credentials: options.credentials },\n            input,\n            // Custom transports can inject an identity outside visible headers.\n            // Never share their cached data with other client instances.\n            httpFetch ? \"client\" : cacheOptions?.scope,\n          );\n        } catch (error) {\n          requestCacheContext = `invalid:${requestId}`;\n          requestContextError = normalizeError(error);\n        }\n      }\n\n      let cacheState = sharedCacheState;\n      let inflightState = sharedInflightState;\n      let requestScopedState: ScopedRequestState | undefined;\n      if (requestCacheContext !== undefined) {\n        if (scopedRequestState && scopedRequestState.context !== requestCacheContext) {\n          scopedRequestState.retired = true;\n          if (scopedRequestState.inflight.size === 0) scopedRequestState.cache.dispose();\n          scopedRequestState = undefined;\n        }\n        scopedRequestState ??= {\n          context: requestCacheContext,\n          cache: new FarmClientDataCache({ subscribeToInvalidation: !transport }),\n          inflight: new Map(),\n          retired: false,\n        };\n        requestScopedState = scopedRequestState;\n        cacheState = requestScopedState.cache;\n        localCaches?.add(cacheState);\n        inflightState = requestScopedState.inflight;\n      }\n      const optimisticState = getOptimisticState(cacheState);\n\n      const entry = getValidCacheEntry(cacheState, cacheKey, now);\n      const isStale = entry ? isEntryStale(entry, now) : true;\n\n      const applyOptimisticUpdates = () => {\n        if (!clientOptions?.optimistic?.update?.length) return [] as OptimisticSnapshot[];\n\n        const snapshots = new Map<string, OptimisticSnapshot>();\n        for (const update of clientOptions.optimistic.update) {\n          const [target, targetInput, updater] =\n            update.length === 2\n              ? [update[0], undefined, update[1]]\n              : [update[0], update[1], update[2]];\n          const targetKey = resolveTargetKey(\n            routeMeta,\n            target,\n            targetInput,\n            baseURL,\n            defaultHeaders,\n            transport ? baseURL : undefined,\n          );\n          if (!targetKey) continue;\n\n          const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n          const currentEntry = cacheState.get(targetKey);\n          let stack = optimisticState.get(targetKey);\n          if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {\n            stack = undefined;\n          }\n          if (!stack) {\n            stack = {\n              entry: targetEntry ? { ...targetEntry } : undefined,\n              layers: [],\n              renderedEntry: currentEntry,\n            };\n            optimisticState.set(targetKey, stack);\n          }\n\n          let snapshot = snapshots.get(targetKey);\n          if (!snapshot) {\n            const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;\n            const layer: OptimisticLayer = {\n              updaters: [],\n              updatedAt: now,\n              staleAt:\n                targetEntry?.staleAt ??\n                now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),\n              gcAt:\n                targetEntry?.gcAt ??\n                getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime),\n            };\n            stack.layers.push(layer);\n            snapshot = {\n              key: targetKey,\n              stack,\n              layer,\n            };\n            snapshots.set(targetKey, snapshot);\n            snapshot.layer.updaters.push(updater);\n            const nextEntry = applyOptimisticLayer(previousEntry, {\n              ...snapshot.layer,\n              updaters: [updater],\n            });\n            storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n            continue;\n          }\n          snapshot.layer.updaters.push(updater);\n          const nextEntry = applyOptimisticLayer(stack.renderedEntry, {\n            ...snapshot.layer,\n            updaters: [updater],\n          });\n          storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n        }\n\n        return Array.from(snapshots.values());\n      };\n\n      const rollbackOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n        if (!clientOptions?.optimistic?.rollbackOnError) return;\n        settleOptimisticUpdates(cacheState, optimisticState, snapshots, \"rollback\");\n      };\n\n      const invalidateUncommittedOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n        if (clientOptions?.optimistic?.rollbackOnError) return;\n        for (const key of settleOptimisticUpdates(\n          cacheState,\n          optimisticState,\n          snapshots,\n          \"invalidate\",\n        )) {\n          emitStatus(\"invalidated\", { key });\n        }\n      };\n\n      const executeNetwork = async (opts?: { isBackground?: boolean; callCallbacks?: boolean }) => {\n        const release = cancellation.hold();\n        let unsubscribeInvalidation: (() => void) | undefined;\n        let readOwners: Map<string, object> | undefined;\n        let readOwner: object | undefined;\n        const resolvedCacheKey = cacheState.resolveKey(cacheKey);\n        try {\n          const dedupeMs = cacheOptions?.dedupeMs ?? 0;\n          const inflight = inflightState.get(cacheKey);\n          const allowDedupe =\n            isCacheEnabled && dedupeMs > 0 && !cancellation.signal && !requestContextError;\n\n          if (\n            allowDedupe &&\n            inflight &&\n            !inflight.cancellable &&\n            now - inflight.startedAt < dedupeMs\n          ) {\n            emitStatus(\"pending\", { isBackground: opts?.isBackground, data: entry?.data });\n            const result = await inflight.promise;\n\n            if (result.error) {\n              emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n              notifyClientObserver(options.onError, [result.error]);\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onError?.(result.error);\n              }\n            } else {\n              emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onSuccess?.(result.data as any);\n              }\n            }\n\n            return result;\n          }\n\n          // Observe ordering, not wall-clock timestamps: invalidation can happen in the\n          // same millisecond, or be cleared by another client's newer cache write.\n          let invalidatedDuringRequest = false;\n          if (isCacheEnabled) {\n            // Transport deduplication is caller-local, but cache ownership must\n            // span every caller writing to the same cache instance.\n            readOwners = getCacheReadOwners(cacheState);\n            readOwner = {};\n            readOwners.set(resolvedCacheKey, readOwner);\n            unsubscribeInvalidation = cacheState.subscribe(cacheKey, (event) => {\n              if (event === \"invalidate\") invalidatedDuringRequest = true;\n            });\n          }\n          emitStatus(opts?.isBackground ? \"revalidating\" : \"pending\", {\n            isBackground: opts?.isBackground,\n          });\n\n          const promise = (async () => {\n            const maxRetries = Math.max(0, clientOptions?.retry?.count ?? 0);\n            let attempt = 0;\n\n            // eslint-disable-next-line no-constant-condition\n            while (true) {\n              if (options.onRequest || clientOptions?.onRequest) {\n                const requestEvent: RequestEvent = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                };\n                notifyClientObserver(options.onRequest, [requestEvent]);\n                clientOptions?.onRequest?.(requestEvent);\n              }\n\n              try {\n                if (requestContextError) throw requestContextError;\n                const { response, data, decodeError } = await cancellation.run(() =>\n                  fetchClient(\n                    path,\n                    {\n                      ...input,\n                      method: methodUpper,\n                    },\n                    defaultHeaders,\n                    cancellation,\n                  ),\n                );\n\n                const error = response.ok ? null : createResponseError(response, data, decodeError);\n\n                const responseEvent: ResponseEvent<any, Error> = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                  response,\n                  data: response.ok ? data : undefined,\n                  error: error ?? undefined,\n                  ok: response.ok,\n                  status: response.status,\n                };\n\n                notifyClientObserver(options.onResponse, [\n                  response.ok ? data : undefined,\n                  error,\n                  responseEvent,\n                ]);\n                notifyResponseObserver(\n                  clientOptions?.onResponse,\n                  response.ok ? data : undefined,\n                  error,\n                  responseEvent,\n                );\n\n                if (!error) {\n                  return { data, error: null, key: cacheKey } as APIResult<any, Error>;\n                }\n\n                if (attempt >= maxRetries) {\n                  return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n                }\n              } catch (err: any) {\n                const error = normalizeCallError(err);\n                const responseEvent: ResponseEvent<any, Error> = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                  error,\n                  ok: false,\n                };\n\n                notifyClientObserver(options.onResponse, [undefined, error, responseEvent]);\n                notifyResponseObserver(clientOptions?.onResponse, undefined, error, responseEvent);\n\n                if (attempt >= maxRetries || requestContextError || cancellation.signal?.aborted) {\n                  return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n                }\n              }\n\n              attempt += 1;\n              const delay =\n                typeof clientOptions?.retry?.delay === \"function\"\n                  ? clientOptions.retry.delay(attempt)\n                  : (clientOptions?.retry?.delay ?? 0);\n\n              if (delay > 0) {\n                try {\n                  await cancellation.delay(delay);\n                } catch (error) {\n                  return { data: undefined, error: normalizeCallError(error), key: cacheKey };\n                }\n              }\n            }\n          })();\n\n          const inflightEntry = {\n            promise,\n            startedAt: now,\n            cancellable: !!cancellation.signal || !!requestContextError,\n          };\n          inflightState.set(cacheKey, inflightEntry);\n\n          try {\n            const result = await promise;\n\n            if (\n              inflightState.get(cacheKey) === inflightEntry &&\n              readOwners?.get(resolvedCacheKey) === readOwner &&\n              !invalidatedDuringRequest &&\n              !result.error &&\n              isCacheEnabled &&\n              !isFarmAPIStream(result.data)\n            ) {\n              const updatedAt = Date.now();\n              const cached: CacheEntry = {\n                data: result.data,\n                updatedAt,\n                staleAt: updatedAt + staleTime,\n                gcAt: getGcAt(updatedAt, cacheOptions?.gcTime),\n                invalidatedAt: undefined,\n                persist: cacheOptions?.persist === true ? true : undefined,\n                [API_CACHE_REFETCH]: createCacheRefetch(\n                  request,\n                  path,\n                  method,\n                  input,\n                  cacheKey,\n                  cacheOptions!,\n                  clientOptions,\n                  options.onError,\n                ),\n              };\n              cacheState.set(cacheKey, cached);\n            }\n\n            if (result.error) {\n              emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n              notifyClientObserver(options.onError, [result.error]);\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onError?.(result.error);\n              }\n            } else {\n              emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n              if (opts?.callCallbacks !== false) {\n                clientOptions?.onSuccess?.(result.data as any);\n              }\n            }\n\n            return result;\n          } finally {\n            if (inflightState.get(cacheKey) === inflightEntry) {\n              inflightState.delete(cacheKey);\n            }\n            if (requestContextError && requestScopedState) {\n              requestScopedState.retired = true;\n              if (scopedRequestState === requestScopedState) scopedRequestState = undefined;\n            }\n            if (requestScopedState?.retired && requestScopedState.inflight.size === 0) {\n              requestScopedState.cache.dispose();\n            }\n          }\n        } finally {\n          if (readOwner && readOwners?.get(resolvedCacheKey) === readOwner) {\n            readOwners.delete(resolvedCacheKey);\n          }\n          unsubscribeInvalidation?.();\n          release();\n        }\n      };\n\n      const invalidateTargets = async () => {\n        if (!clientOptions?.invalidate) return;\n\n        const invalidateOptions = Array.isArray(clientOptions.invalidate)\n          ? { targets: clientOptions.invalidate, refetch: false }\n          : {\n              targets: clientOptions.invalidate.targets,\n              refetch: clientOptions.invalidate.refetch ?? false,\n            };\n\n        const refetches = new Set<() => void>();\n        for (const target of invalidateOptions.targets) {\n          const targetKey = resolveTargetKey(\n            routeMeta,\n            target,\n            undefined,\n            baseURL,\n            defaultHeaders,\n            transport ? baseURL : undefined,\n          );\n          if (!targetKey) continue;\n\n          const existing = cacheState.get(targetKey);\n          const invalidatedAt = Date.now();\n          // The first read may still be in flight with no stored entry yet.\n          // Notify its invalidation listener before it can cache an old result.\n          cacheState.invalidate(targetKey, invalidatedAt);\n          if (existing) {\n            const stack = optimisticState.get(targetKey);\n            if (stack?.renderedEntry === existing) {\n              stack.invalidatedAt = invalidatedAt;\n              stack.renderedEntry = cacheState.get(targetKey);\n            }\n          }\n\n          emitStatus(\"invalidated\", { key: targetKey });\n\n          const refetch = (existing as CacheEntry | undefined)?.[API_CACHE_REFETCH];\n          if (invalidateOptions.refetch && refetch) {\n            refetches.add(refetch);\n          }\n        }\n        // Invalidate every alias before starting work; never replay this mutation.\n        for (const refetch of refetches) refetch();\n      };\n\n      const optimisticSnapshots = requestContextError ? [] : applyOptimisticUpdates();\n\n      if (isCacheEnabled && !requestContextError && !cancellation.signal?.aborted) {\n        if (entry && !isStale && policy !== \"network-only\") {\n          emitStatus(\"success\", { data: entry.data });\n          clientOptions?.onSuccess?.(entry.data);\n          clientOptions?.onSettled?.(entry.data, null);\n          return { data: entry.data, error: null, key: cacheKey };\n        }\n\n        if (entry && isStale && policy === \"stale-while-revalidate\") {\n          emitStatus(\"success\", { data: entry.data });\n          clientOptions?.onSuccess?.(entry.data);\n          clientOptions?.onSettled?.(entry.data, null);\n\n          void executeNetwork({ isBackground: true, callCallbacks: false });\n          return { data: entry.data, error: null, key: cacheKey };\n        }\n      }\n\n      const result = await executeNetwork();\n      if (result.error) {\n        if (cancellation.signal?.aborted) {\n          settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, \"rollback\");\n        } else {\n          rollbackOptimisticUpdates(optimisticSnapshots);\n          invalidateUncommittedOptimisticUpdates(optimisticSnapshots);\n        }\n      } else {\n        settleOptimisticUpdates(cacheState, optimisticState, optimisticSnapshots, \"commit\");\n        await invalidateTargets();\n      }\n      clientOptions?.onSettled?.(result.data, result.error);\n      return result;\n    } finally {\n      cancellation.dispose();\n    }\n  };\n\n  // Return nested proxy (starts with empty path, user adds to it)\n  const client = createNestedProxy(\n    [],\n    request,\n    routeMeta,\n    baseURL,\n    isSameOriginAPIBaseURL(baseURL),\n    rootAliases,\n    options.routes ? new ClientRouteManifest(options.routes) : undefined,\n  ) as APIClient<TRouter, TIntegrations>;\n  return { client, request };\n}\n\nasync function readAPIResponseData(response: Response, method: string): Promise<unknown> {\n  if (\n    method === \"HEAD\" ||\n    response.status === 204 ||\n    response.status === 205 ||\n    response.status === 304\n  ) {\n    return undefined;\n  }\n\n  // Keep lightweight fetch-compatible adapters working when they expose the\n  // traditional json() contract without a complete Web Response implementation.\n  if (!response.headers?.get && typeof response.json === \"function\") {\n    return readResponseJSON(response);\n  }\n\n  if (response.body === null) return undefined;\n\n  if (isJSONStreamResponse(response)) {\n    return readJSONStream(response);\n  }\n\n  const contentType = response.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n  if (typeof response.arrayBuffer === \"function\") {\n    const data = await response.arrayBuffer();\n    if (data.byteLength === 0) return undefined;\n\n    if (!contentType || contentType === \"application/json\" || contentType.endsWith(\"+json\")) {\n      return parseResponseJSON(new TextDecoder().decode(data));\n    }\n\n    if (\n      contentType.startsWith(\"text/\") ||\n      contentType === \"application/xml\" ||\n      contentType === \"application/xhtml+xml\" ||\n      contentType === \"application/graphql\"\n    ) {\n      return new TextDecoder().decode(data);\n    }\n\n    return data;\n  }\n\n  if (\n    (!contentType || contentType === \"application/json\" || contentType.endsWith(\"+json\")) &&\n    typeof response.json === \"function\"\n  ) {\n    return readResponseJSON(response);\n  }\n\n  if (\n    (contentType?.startsWith(\"text/\") ||\n      contentType === \"application/xml\" ||\n      contentType === \"application/xhtml+xml\" ||\n      contentType === \"application/graphql\") &&\n    typeof response.text === \"function\"\n  ) {\n    return response.text();\n  }\n\n  // Some fetch-compatible adapters expose headers but still only implement\n  // the traditional json() reader.\n  if (typeof response.json === \"function\") {\n    return readResponseJSON(response);\n  }\n\n  return undefined;\n}\n\nclass APIResponseDecodeError extends Error {\n  readonly cause: unknown;\n\n  constructor(cause: unknown) {\n    super(cause instanceof Error ? cause.message : \"Failed to decode JSON response\");\n    this.name = \"APIResponseDecodeError\";\n    this.cause = cause;\n  }\n}\n\nfunction parseResponseJSON(value: string): unknown {\n  try {\n    return JSON.parse(value);\n  } catch (error) {\n    throw new APIResponseDecodeError(error);\n  }\n}\n\nasync function readResponseJSON(response: Pick<Response, \"json\">): Promise<unknown> {\n  try {\n    return await response.json();\n  } catch (error) {\n    if (error instanceof SyntaxError) throw new APIResponseDecodeError(error);\n    throw error;\n  }\n}\n\n/**\n * Create a nested proxy that builds up the path\n *\n * Flow:\n * 1. api.hello       -> Proxy(['hello'])\n * 2. api.hello.get   -> Proxy(['hello', 'get'])\n * 3. api.hello.get({ query: {...} })\n *    -> fetch('/api/hello', { method: 'GET', ... })\n *\n * For routes with single method:\n * 1. api.hello       -> Proxy(['hello'])\n * 2. api.hello({ query: {...} })\n *    -> fetch('/api/hello', ...)\n */\nfunction createNestedProxy(\n  path: string[],\n  client: any,\n  routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n  baseURL: string,\n  sameOrigin: boolean,\n  rootAliases?: Record<string, unknown>,\n  manifest?: ClientRouteManifest,\n  bound: BoundRouteParams = {},\n): any {\n  const target = () => {};\n  const proxy = new Proxy(target, {\n    // When accessing a property (api.hello)\n    get(_target, prop: string | symbol) {\n      if (prop === \"$params\") {\n        return (params: unknown) => {\n          if (!manifest)\n            throw new TypeError(\n              \"$params requires createAPIClient({ routes: apiRoutes }) from the generated API manifest.\",\n            );\n          const scope = manifest.bind(buildProxyRoutePath(path), params);\n          return createNestedProxy(\n            [...path, scope.segment],\n            client,\n            routeMeta,\n            baseURL,\n            sameOrigin,\n            rootAliases,\n            manifest,\n            Object.freeze({ ...bound, ...scope.params }),\n          );\n        };\n      }\n      if (prop === FARM_API_ROUTE_REF_SYMBOL) {\n        return path.length > 0;\n      }\n      if (prop === FARM_API_ROUTE_META_SYMBOL) {\n        let metadata;\n        try {\n          metadata = resolveRouteMeta({ path, baseURL, manifest, bound });\n        } catch {\n          return null;\n        } // An unbound/overloaded route has no single URL yet.\n        const requestURL = resolveFarmAPIRequestURL(metadata.routePath, baseURL);\n        return Object.freeze({\n          path: `${requestURL.pathname}${requestURL.search}${requestURL.hash}`,\n          method: metadata.method,\n          baseURL: requestURL.origin,\n          sameOrigin,\n        });\n      }\n\n      if (path.length === 0 && typeof prop === \"string\" && rootAliases && prop in rootAliases) {\n        return rootAliases[prop];\n      }\n\n      if (typeof prop !== \"string\") {\n        return Reflect.get(_target, prop);\n      }\n\n      // Add prop to path and return new proxy\n      return createNestedProxy(\n        [...path, prop],\n        client,\n        routeMeta,\n        baseURL,\n        sameOrigin,\n        rootAliases,\n        manifest,\n        bound,\n      );\n    },\n\n    // When calling as a function\n    apply(_target, _thisArg, args) {\n      // Check if the last part is an HTTP method\n      const lastPart = path[path.length - 1];\n      const httpMethods = [\"get\", \"head\", \"query\", \"post\", \"put\", \"delete\", \"patch\", \"options\"];\n\n      if (httpMethods.includes(lastPart)) {\n        // Method is explicitly called: api.users.get() or api['auth/login'].post()\n        // Remove the method from path and use it as the HTTP method\n        const routePath = buildProxyRoutePath(path.slice(0, -1));\n        const method = lastPart.toUpperCase();\n\n        // Extract options from arguments\n        const [options, clientOptions] = args;\n\n        // Call fetch client with explicit method\n        const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;\n        if (!manifest && options?.params)\n          throw new TypeError(\"Dynamic params require the generated routes manifest.\");\n        return client(resolved, method, options, clientOptions);\n      } else {\n        // Direct call without method: api.hello()\n        // Use the full path and let the server determine the method (usually GET)\n        const routePath = buildProxyRoutePath(path);\n\n        // Extract options from arguments\n        const [options, clientOptions] = args;\n\n        // Call fetch client (default method will be GET)\n        const method = options?.method || \"GET\";\n        const resolved = manifest ? manifest.resolve(routePath, method, bound, options) : routePath;\n        return client(resolved, method, options, clientOptions);\n      }\n    },\n  });\n\n  routeMeta.set(proxy, { path: [...path], baseURL, manifest, bound });\n  return proxy;\n}\n\nfunction buildProxyRoutePath(path: string[]): string {\n  return \"/api/\" + path.join(\"/\").replace(/^\\/+/, \"\");\n}\n\nexport function isAPIRouteRef(value: unknown): value is CallableRouteRef {\n  return (\n    typeof value === \"function\" &&\n    (value as { [FARM_API_ROUTE_REF_SYMBOL]?: unknown })[FARM_API_ROUTE_REF_SYMBOL] === true\n  );\n}\n\nexport function getAPIRouteRefMetadata(value: unknown): APIRouteRefMetadata | null {\n  if (!isAPIRouteRef(value)) return null;\n  const metadata = (value as { [FARM_API_ROUTE_META_SYMBOL]?: unknown })[\n    FARM_API_ROUTE_META_SYMBOL\n  ];\n  if (!metadata || typeof metadata !== \"object\") return null;\n\n  const candidate = metadata as Partial<APIRouteRefMetadata>;\n  if (\n    typeof candidate.path !== \"string\" ||\n    typeof candidate.method !== \"string\" ||\n    typeof candidate.baseURL !== \"string\" ||\n    typeof candidate.sameOrigin !== \"boolean\"\n  ) {\n    return null;\n  }\n\n  return {\n    path: candidate.path,\n    method: candidate.method,\n    baseURL: candidate.baseURL,\n    sameOrigin: candidate.sameOrigin,\n  };\n}\n\n/**\n * Server-side API client that calls endpoints directly as functions\n * No HTTP overhead for app endpoints, and registered integration routes can be exposed at\n * api.integrations.* where Farm can dispatch them directly to the integration handler.\n *\n * @example\n * ```typescript\n * import { createServerAPIClient } from 'farm/client';\n * import type { AppIntegrations } from '@/lib/integrations';\n *\n * export const api = createServerAPIClient<{}, AppIntegrations>({});\n *\n * const result = await api.integrations.billing.status();\n * ```\n */\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n  endpoints: TEndpoints,\n): TEndpoints;\nexport function createServerAPIClient<TEndpoints extends Record<string, any>>(\n  endpoints: TEndpoints,\n  options: ServerAPIClientWithoutIntegrationsOptions,\n): TEndpoints;\nexport function createServerAPIClient<\n  TEndpoints extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  endpoints: TEndpoints,\n  options?: ServerAPIClientOptions,\n): ServerAPIClient<TEndpoints, TIntegrations>;\nexport function createServerAPIClient<\n  TEndpoints extends Record<string, any>,\n  TIntegrations extends Record<string, any> = {},\n>(\n  endpoints: TEndpoints,\n  options: ServerAPIClientOptions | ServerAPIClientWithoutIntegrationsOptions = {},\n): TEndpoints | ServerAPIClient<TEndpoints, TIntegrations> {\n  if (\n    options.integrations === false ||\n    Object.prototype.hasOwnProperty.call(endpoints, \"integrations\")\n  ) {\n    return endpoints;\n  }\n\n  Object.defineProperty(endpoints, \"integrations\", {\n    get() {\n      return integrationsServer<TIntegrations>(\n        typeof options.integrations === \"object\" ? options.integrations : {},\n      );\n    },\n    enumerable: false,\n    configurable: true,\n  });\n\n  return endpoints as ServerAPIClient<TEndpoints, TIntegrations>;\n}\n\nconst API_CACHE_REFETCH = Symbol.for(\"farm.api.cache-refetch\");\ntype CacheEntry = FarmClientCacheEntry<any> & {\n  [API_CACHE_REFETCH]?: () => void;\n};\n\n// Keep the read recipe on its cache entry, so deletion/GC also releases it.\n// This separate closure must not retain the original request's entry or signal.\nfunction createCacheRefetch(\n  request: APICall,\n  path: string,\n  method: string,\n  input: unknown,\n  key: string,\n  cache: CacheOptions,\n  options: ClientOptions<any, any> | undefined,\n  onError: APIClientOptions[\"onError\"],\n): () => void {\n  const readOptions: ClientOptions<any, any> = {\n    cache: { ...cache, key, policy: \"network-only\", dedupeMs: 0 },\n    retry: options?.retry,\n    timeoutMs: options?.timeoutMs,\n  };\n  return () => {\n    // A new call resolves current defaults and owns a fresh deadline. Do not\n    // retain prior signals, mutation options, or per-call completion callbacks.\n    void request(path, method, input, readOptions).catch((error) => {\n      notifyClientObserver(onError, [normalizeError(error)]);\n    });\n  };\n}\n\ntype InflightEntry = {\n  cancellable?: boolean;\n  promise: Promise<APIResult<any, Error>>;\n  startedAt: number;\n};\n\ntype ScopedRequestState = {\n  context: string;\n  cache: FarmClientDataCache;\n  inflight: Map<string, InflightEntry>;\n  retired: boolean;\n};\n\ntype RouteMeta = {\n  path: string[];\n  baseURL: string;\n  manifest?: ClientRouteManifest;\n  bound?: BoundRouteParams;\n};\n\ntype OptimisticSnapshot = {\n  key: string;\n  stack: OptimisticStack;\n  layer: OptimisticLayer;\n};\n\ntype OptimisticStack = {\n  entry?: CacheEntry;\n  layers: OptimisticLayer[];\n  renderedEntry?: CacheEntry;\n  invalidatedAt?: number;\n};\n\ntype OptimisticLayer = {\n  updaters: Array<(prev: any) => any>;\n  updatedAt: number;\n  staleAt: number;\n  gcAt?: number;\n  committed?: boolean;\n};\n\nconst optimisticStates = new WeakMap<FarmClientDataCache, Map<string, OptimisticStack>>();\nconst cacheReadOwners = new WeakMap<FarmClientDataCache, Map<string, object>>();\n\nfunction getCacheReadOwners(cache: FarmClientDataCache): Map<string, object> {\n  let owners = cacheReadOwners.get(cache);\n  if (!owners) {\n    owners = new Map();\n    cacheReadOwners.set(cache, owners);\n  }\n  return owners;\n}\n\nfunction getOptimisticState(cache: FarmClientDataCache): Map<string, OptimisticStack> {\n  let state = optimisticStates.get(cache);\n  if (!state) {\n    state = new Map();\n    optimisticStates.set(cache, state);\n  }\n  return state;\n}\n\nfunction applyOptimisticLayer(entry: CacheEntry | undefined, layer: OptimisticLayer): CacheEntry {\n  let data = entry?.data;\n  for (const updater of layer.updaters) data = updater(data);\n\n  return {\n    data,\n    updatedAt: layer.updatedAt,\n    staleAt: entry?.staleAt ?? layer.staleAt,\n    gcAt: entry?.gcAt ?? layer.gcAt,\n    invalidatedAt: entry?.invalidatedAt,\n    [API_CACHE_REFETCH]: entry?.[API_CACHE_REFETCH],\n  };\n}\n\nfunction storeOptimisticEntry(\n  cacheState: FarmClientDataCache,\n  key: string,\n  stack: OptimisticStack,\n  entry: CacheEntry | undefined,\n): void {\n  if (!entry) {\n    cacheState.delete(key);\n    stack.renderedEntry = undefined;\n    return;\n  }\n\n  cacheState.set(key, entry);\n  if (stack.invalidatedAt !== undefined) {\n    cacheState.invalidate(key, stack.invalidatedAt);\n  }\n  stack.renderedEntry = cacheState.get(key);\n}\n\nfunction reconcileOptimisticInvalidation(\n  cacheState: FarmClientDataCache,\n  key: string,\n  stack: OptimisticStack,\n): boolean {\n  const current = cacheState.get(key);\n  const rendered = stack.renderedEntry;\n  if (current === rendered) return true;\n  if (\n    !current ||\n    !rendered ||\n    current.data !== rendered.data ||\n    current.updatedAt !== rendered.updatedAt ||\n    current.gcAt !== rendered.gcAt ||\n    current.status !== rendered.status ||\n    current.error !== rendered.error ||\n    current.fetching !== rendered.fetching ||\n    current.staleAt !== 0 ||\n    current.invalidatedAt === undefined\n  ) {\n    return false;\n  }\n\n  stack.invalidatedAt = current.invalidatedAt;\n  stack.renderedEntry = current;\n  return true;\n}\n\nfunction renderOptimisticStack(\n  cacheState: FarmClientDataCache,\n  key: string,\n  stack: OptimisticStack,\n): void {\n  let entry = stack.entry ? { ...stack.entry } : undefined;\n  for (const layer of stack.layers) entry = applyOptimisticLayer(entry, layer);\n  storeOptimisticEntry(cacheState, key, stack, entry);\n}\n\nfunction settleOptimisticUpdates(\n  cacheState: FarmClientDataCache,\n  optimisticState: Map<string, OptimisticStack>,\n  snapshots: OptimisticSnapshot[],\n  outcome: \"commit\" | \"rollback\" | \"invalidate\",\n): string[] {\n  const settledKeys: string[] = [];\n  for (const snapshot of snapshots) {\n    const stack = optimisticState.get(snapshot.key);\n    if (stack !== snapshot.stack) continue;\n    if (!reconcileOptimisticInvalidation(cacheState, snapshot.key, stack)) {\n      optimisticState.delete(snapshot.key);\n      continue;\n    }\n\n    if (outcome === \"rollback\") {\n      stack.layers = stack.layers.filter((layer) => layer !== snapshot.layer);\n    } else {\n      snapshot.layer.committed = true;\n      if (outcome === \"invalidate\") stack.invalidatedAt = Date.now();\n    }\n\n    while (stack.layers[0]?.committed) {\n      stack.entry = applyOptimisticLayer(stack.entry, stack.layers.shift()!);\n    }\n\n    renderOptimisticStack(cacheState, snapshot.key, stack);\n    if (stack.layers.length === 0) optimisticState.delete(snapshot.key);\n    settledKeys.push(snapshot.key);\n  }\n  return settledKeys;\n}\n\n/**\n * @internal Apply key-targeted optimistic updates to the shared client cache\n * for a server-function mutation. Route-reference update tuples need an API\n * caller's route metadata and are skipped here; use structured cache keys.\n */\nexport function applyServerFnOptimisticUpdates(\n  updates: readonly OptimisticUpdate[],\n  now = Date.now(),\n): OptimisticSnapshot[] {\n  const cacheState = getFarmClientDataCache();\n  const optimisticState = getOptimisticState(cacheState);\n  const snapshots = new Map<string, OptimisticSnapshot>();\n\n  for (const update of updates) {\n    if (update.length !== 2) continue;\n    const [target, updater] = update;\n    if (typeof updater !== \"function\") continue;\n    const targetKey =\n      typeof target === \"string\" || Array.isArray(target)\n        ? normalizeFarmClientCacheKey(target as FarmClientCacheKey)\n        : null;\n    if (!targetKey) continue;\n\n    const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n    const currentEntry = cacheState.get(targetKey);\n    let stack = optimisticState.get(targetKey);\n    if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {\n      stack = undefined;\n    }\n    if (!stack) {\n      stack = {\n        entry: targetEntry ? { ...targetEntry } : undefined,\n        layers: [],\n        renderedEntry: currentEntry,\n      };\n      optimisticState.set(targetKey, stack);\n    }\n\n    let snapshot = snapshots.get(targetKey);\n    if (!snapshot) {\n      const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;\n      const layer: OptimisticLayer = {\n        updaters: [],\n        updatedAt: now,\n        // A server function has no cache policy of its own; preserve the\n        // target read's freshness metadata when it exists.\n        staleAt: targetEntry?.staleAt ?? now,\n        gcAt: targetEntry?.gcAt,\n      };\n      stack.layers.push(layer);\n      snapshot = { key: targetKey, stack, layer };\n      snapshots.set(targetKey, snapshot);\n      snapshot.layer.updaters.push(updater);\n      const nextEntry = applyOptimisticLayer(previousEntry, {\n        ...snapshot.layer,\n        updaters: [updater],\n      });\n      storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n      continue;\n    }\n    snapshot.layer.updaters.push(updater);\n    const nextEntry = applyOptimisticLayer(stack.renderedEntry, {\n      ...snapshot.layer,\n      updaters: [updater],\n    });\n    storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n  }\n\n  return Array.from(snapshots.values());\n}\n\n/**\n * @internal Settle a server-function mutation's optimistic snapshots with the\n * API client's semantics: commit on success, rollback on failure with\n * `rollbackOnError`, and mark-stale on failure without it.\n */\nexport function settleServerFnOptimisticUpdates(\n  snapshots: OptimisticSnapshot[],\n  outcome: \"commit\" | \"rollback\" | \"invalidate\",\n): void {\n  if (snapshots.length === 0) return;\n  const cacheState = getFarmClientDataCache();\n  settleOptimisticUpdates(cacheState, getOptimisticState(cacheState), snapshots, outcome);\n}\n\n/**\n * @internal Resolve a server-function mutation's invalidate targets to cache\n * keys. Route-reference and path targets need an API caller's identity and are\n * skipped; use structured cache keys. Keys are applied through the shared\n * invalidation bus, matching server-declared `invalidates`.\n */\nexport function resolveServerFnInvalidateTargets(invalidate: InvalidateOptions): string[] {\n  const targets = Array.isArray(invalidate) ? invalidate : invalidate.targets;\n  const keys: string[] = [];\n  for (const target of targets) {\n    if (typeof target === \"string\" || Array.isArray(target)) {\n      if (Array.isArray(target) && typeof target[0] === \"function\") continue;\n      keys.push(normalizeFarmClientCacheKey(target as FarmClientCacheKey));\n    } else if (target && typeof target === \"object\" && \"key\" in target) {\n      keys.push(normalizeFarmClientCacheKey(target.key));\n    }\n  }\n  return keys;\n}\n\nfunction buildCacheKey(\n  method: string,\n  path: string,\n  input: any,\n  baseURL: string,\n  defaultHeaders?: HeadersInit,\n): string {\n  const keyInput =\n    input && typeof input === \"object\"\n      ? {\n          query: input.query,\n          body: input.body,\n          ...(method === \"QUERY\"\n            ? {\n                contentType:\n                  getHeader(input.headers, \"content-type\") ??\n                  getHeader(defaultHeaders, \"content-type\") ??\n                  \"application/json\",\n                contentEncoding:\n                  getHeader(input.headers, \"content-encoding\") ??\n                  getHeader(defaultHeaders, \"content-encoding\"),\n              }\n            : {}),\n        }\n      : input;\n  const url = resolveFarmAPIRequestURL(path, baseURL);\n  return `${method}:${url.origin}${url.pathname}:${stableStringify(keyInput ?? {})}`;\n}\n\nfunction isSameOriginAPIBaseURL(baseURL: string): boolean {\n  if (typeof window === \"undefined\") return baseURL.startsWith(\"/\");\n  return resolveFarmAPIRequestURL(\"/api\", baseURL).origin === window.location.origin;\n}\n\nfunction stableStringify(value: any): string {\n  if (value === null || value === undefined) return String(value);\n  if (value instanceof Date) return value.toISOString();\n  if (typeof value !== \"object\") return JSON.stringify(value);\n  if (Array.isArray(value)) {\n    return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n  }\n\n  const keys = Object.keys(value).sort();\n  const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);\n  return `{${entries.join(\",\")}}`;\n}\n\nfunction getHeader(headers: unknown, name: string): string | undefined {\n  if (!headers || typeof headers !== \"object\") return undefined;\n\n  if (typeof Headers !== \"undefined\" && headers instanceof Headers) {\n    return headers.get(name) ?? undefined;\n  }\n\n  const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);\n  return entry?.[1] === undefined ? undefined : String(entry[1]);\n}\n\nfunction getRequestCacheContext(\n  options: { headers?: HeadersInit; credentials?: RequestCredentials },\n  input: unknown,\n  scope: CacheScope | undefined,\n): string | undefined {\n  const credentials = options.credentials ?? \"same-origin\";\n  const headers = new Headers(options.headers);\n  const requestHeaders =\n    input && typeof input === \"object\" && \"headers\" in input ? input.headers : undefined;\n\n  if (requestHeaders) {\n    new Headers(requestHeaders as HeadersInit).forEach((value, key) => headers.set(key, value));\n  }\n\n  const carriesBrowserIdentity = credentials !== \"omit\" || [...headers].length > 0;\n  if (scope !== \"client\" && !carriesBrowserIdentity) return undefined;\n\n  return stableStringify({\n    credentials,\n    headers: [...headers].sort(([left], [right]) => left.localeCompare(right)),\n  });\n}\n\nfunction getGcAt(now: number, gcTime?: number): number | undefined {\n  if (gcTime === undefined) return undefined;\n  if (!Number.isFinite(gcTime) || gcTime <= 0) return now;\n  return now + gcTime;\n}\n\nfunction getValidCacheEntry(\n  cacheState: FarmClientDataCache,\n  key: string,\n  now: number,\n): CacheEntry | undefined {\n  const entry = cacheState.get(key);\n  if (!entry) return undefined;\n\n  if (entry.gcAt !== undefined && now >= entry.gcAt) {\n    cacheState.delete(key);\n    return undefined;\n  }\n\n  return entry;\n}\n\nfunction isEntryStale(entry: CacheEntry, now: number): boolean {\n  if (entry.invalidatedAt !== undefined) return true;\n  return now >= entry.staleAt;\n}\n\nfunction resolveTargetKey(\n  routeMeta: WeakMap<AnyRouteRef, RouteMeta>,\n  target: InvalidateTarget | AnyRouteRef,\n  input?: unknown,\n  baseURL = \"http://localhost:3000\",\n  defaultHeaders?: HeadersInit,\n  localBaseURL?: string,\n): string | null {\n  if (!target) return null;\n\n  if (typeof target === \"string\") return target;\n\n  if (typeof target === \"function\") {\n    const meta = routeMeta.get(target);\n    if (!meta) return null;\n\n    const { method, routePath } = resolveRouteMeta(meta, input);\n    return buildCacheKey(\n      method,\n      routePath,\n      input ?? {},\n      localBaseURL ?? meta.baseURL,\n      defaultHeaders,\n    );\n  }\n\n  if (Array.isArray(target)) {\n    const [route, routeInput] = target;\n    if (typeof route === \"function\") {\n      return resolveTargetKey(routeMeta, route, routeInput, baseURL, defaultHeaders, localBaseURL);\n    }\n    return normalizeFarmClientCacheKey(target);\n  }\n\n  if (\"key\" in target) return normalizeFarmClientCacheKey(target.key);\n\n  if (\"path\" in target) {\n    const method = target.method ?? \"GET\";\n    return buildCacheKey(method, target.path, target.input ?? {}, baseURL, defaultHeaders);\n  }\n\n  return null;\n}\n\nfunction resolveRouteMeta(meta: RouteMeta, input?: any): { routePath: string; method: string } {\n  const httpMethods = [\"get\", \"head\", \"query\", \"post\", \"put\", \"delete\", \"patch\", \"options\"];\n  const lastPart = meta.path[meta.path.length - 1];\n  if (lastPart && httpMethods.includes(lastPart)) {\n    return {\n      routePath: meta.manifest\n        ? meta.manifest.resolve(\n            buildProxyRoutePath(meta.path.slice(0, -1)),\n            lastPart.toUpperCase(),\n            meta.bound ?? {},\n            input,\n          )\n        : buildProxyRoutePath(meta.path.slice(0, -1)),\n      method: lastPart.toUpperCase(),\n    };\n  }\n\n  return {\n    routePath: meta.manifest\n      ? meta.manifest.resolve(buildProxyRoutePath(meta.path), \"GET\", meta.bound ?? {}, input)\n      : buildProxyRoutePath(meta.path),\n    method: \"GET\",\n  };\n}\n\nfunction normalizeError(error: unknown): Error {\n  if (error instanceof APIClientError) return error;\n\n  const normalized = new APIClientError(\"network_error\", undefined, {\n    status: 0,\n    message:\n      error instanceof Error\n        ? error.message\n        : typeof error === \"string\"\n          ? error\n          : \"Network request failed\",\n  });\n  (normalized as Error & { cause?: unknown }).cause = error;\n  return normalized;\n}\n\nfunction notifyResponseObserver(\n  observer: ClientOptions<any, any>[\"onResponse\"],\n  data: unknown,\n  error: unknown,\n  event: ResponseEvent<any, any>,\n): void {\n  notifyClientObserver(observer, [data, error, event], \"API client onResponse\");\n}\n\nfunction isFormData(value: unknown): value is FormData {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    ((typeof FormData !== \"undefined\" && value instanceof FormData) ||\n      (Object.prototype.toString.call(value) === \"[object FormData]\" &&\n        typeof (value as { entries?: unknown }).entries === \"function\"))\n  );\n}\n\nfunction createResponseError(response: Response, data: any, cause?: unknown): Error {\n  const expected = readEndpointErrorEnvelope(data);\n  if (expected) {\n    return new APIClientError(expected.code, expected.data, {\n      status: response.status,\n      message: expected.message,\n      response,\n    });\n  }\n\n  const error = new APIClientError(\"http_error\", data, {\n    status: response.status,\n    message: `HTTP ${response.status}: ${response.statusText}`,\n    response,\n  });\n  if (cause !== undefined) (error as Error & { cause?: unknown }).cause = cause;\n  return error;\n}\n\nfunction readEndpointErrorEnvelope(data: unknown): {\n  code: string;\n  message: string;\n  data: unknown;\n} | null {\n  if (!data || typeof data !== \"object\") return null;\n  const error = (data as { error?: unknown }).error;\n  if (!error || typeof error !== \"object\") return null;\n\n  const code = (error as { code?: unknown }).code;\n  const message = (error as { message?: unknown }).message;\n  if (typeof code !== \"string\" || typeof message !== \"string\") return null;\n\n  return {\n    code,\n    message,\n    data: (error as { data?: unknown }).data,\n  };\n}\n","import { matchAPIRoute, parseDynamicSegment } from \"./route-pattern\";\n\nexport type APIRouteManifest = readonly {\n  readonly path: string;\n  readonly methods: readonly string[];\n}[];\nexport type BoundRouteParams = Readonly<Record<string, string | readonly string[]>>;\n\n/** A schema-free lookup shared by every immutable scope of one API client. */\nexport class ClientRouteManifest {\n  readonly routes: Map<string, APIRouteManifest[number]>;\n  constructor(routes: APIRouteManifest) {\n    this.routes = new Map(\n      routes.map((route) => [\n        route.path.replace(/\\/$/, \"\"),\n        {\n          path: route.path.replace(/\\/$/, \"\"),\n          methods: [...route.methods],\n        },\n      ]),\n    );\n  }\n\n  bind(path: string, input: unknown): { segment: string; params: BoundRouteParams } {\n    const params = readParams(input);\n    const prefix = `${path.replace(/\\/$/, \"\")}/`;\n    const candidates = new Set(\n      [...this.routes.keys()]\n        .filter((route) => route.startsWith(prefix))\n        .map((route) => route.slice(prefix.length).split(\"/\")[0])\n        .filter((segment) => {\n          const dynamic = parseDynamicSegment(segment);\n          return (\n            dynamic &&\n            Object.keys(params).every((key) => key === dynamic.name) &&\n            (Object.prototype.hasOwnProperty.call(params, dynamic.name) || dynamic.optional)\n          );\n        }),\n    );\n    if (candidates.size !== 1)\n      throw new TypeError(\n        `Cannot bind route params at ${path}: supply exactly the next dynamic segment's parameter.`,\n      );\n    const segment = [...candidates][0]!;\n    const dynamic = parseDynamicSegment(segment)!;\n    encodeParameter(dynamic, params[dynamic.name]);\n    return {\n      segment,\n      params: Object.freeze(\n        Object.fromEntries(\n          Object.entries(params).map(([key, value]) => [\n            key,\n            Array.isArray(value) ? Object.freeze([...value]) : value,\n          ]),\n        ),\n      ),\n    };\n  }\n\n  resolve(\n    path: string,\n    method: string,\n    bound: BoundRouteParams,\n    input?: { params?: unknown },\n  ): string {\n    const normalized = path.replace(/\\/$/, \"\");\n    const supplied = readParams(input?.params);\n    const candidates = [...this.routes.values()].filter((route) => {\n      if (route.path === normalized) return true;\n      if (!route.path.startsWith(`${normalized}/`)) return false;\n      const tail = route.path.slice(normalized.length + 1);\n      return (\n        !tail.includes(\"/\") && Boolean(parseDynamicSegment(tail)) && input?.params !== undefined\n      );\n    });\n    const selected = candidates.filter((route) => {\n      const unbound = route.path\n        .split(\"/\")\n        .map(parseDynamicSegment)\n        .filter((part) => part && !Object.prototype.hasOwnProperty.call(bound, part.name));\n      return (\n        Object.keys(supplied).every((key) => unbound.some((part) => part!.name === key)) &&\n        unbound.every(\n          (part) => part!.optional || Object.prototype.hasOwnProperty.call(supplied, part!.name),\n        )\n      );\n    });\n    if (selected.length !== 1)\n      throw new TypeError(\n        `Cannot resolve ${method} ${normalized}: missing, unexpected, or ambiguous route params.`,\n      );\n    const route = selected[0]!;\n    if (!route.methods.includes(method) && !(method === \"HEAD\" && route.methods.includes(\"GET\"))) {\n      throw new TypeError(`${method} is not registered for ${route.path}.`);\n    }\n    const params = { ...bound, ...supplied };\n    const resolved = route.path\n      .split(\"/\")\n      .map((segment) => {\n        const dynamic = parseDynamicSegment(segment);\n        return dynamic ? encodeParameter(dynamic, params[dynamic.name]) : segment;\n      })\n      .filter(Boolean)\n      .join(\"/\");\n    const pathname = `/${resolved}`;\n    const winner = matchAPIRoute(this.routes, pathname);\n    if (winner?.route.path !== route.path) {\n      throw new TypeError(\n        `Route ${route.path} resolves to ${pathname}, which is shadowed by ${winner?.route.path ?? \"another route\"}.`,\n      );\n    }\n    return pathname;\n  }\n}\n\nfunction readParams(input: unknown): Record<string, string | readonly string[]> {\n  if (input === undefined) return {};\n  if (\n    !input ||\n    typeof input !== \"object\" ||\n    Array.isArray(input) ||\n    ![Object.prototype, null].includes(Object.getPrototypeOf(input))\n  ) {\n    throw new TypeError(\"Route params must be a plain object.\");\n  }\n  for (const key of Object.keys(input)) {\n    if ([\"__proto__\", \"constructor\", \"prototype\"].includes(key))\n      throw new TypeError(`Unsafe route parameter ${key}.`);\n  }\n  return input as Record<string, string | readonly string[]>;\n}\n\nfunction encodeParameter(\n  parameter: { name: string; catchAll: boolean; optional: boolean },\n  value: unknown,\n): string {\n  if (parameter.optional && value === undefined) return \"\";\n  const parts = parameter.catchAll ? value : [value];\n  if (!Array.isArray(parts) || (!parts.length && !parameter.optional)) {\n    throw new TypeError(\n      `Route parameter ${parameter.name} must be ${parameter.catchAll ? \"a non-empty array of strings\" : \"a string\"}.`,\n    );\n  }\n  return Array.from(parts, (part) => {\n    if (\n      typeof part !== \"string\" ||\n      !part ||\n      part === \".\" ||\n      part === \"..\" ||\n      Array.from(part).some(\n        (character) =>\n          character.charCodeAt(0) <= 31 ||\n          (character.charCodeAt(0) >= 127 && character.charCodeAt(0) <= 159),\n      )\n    ) {\n      throw new TypeError(`Invalid value for route parameter ${parameter.name}.`);\n    }\n    return encodeURIComponent(part);\n  }).join(\"/\");\n}\n","/**\n * Farm.js API Routes Vite Plugin\n *\n * Standalone API route support that works with any Vite setup.\n * Discovers and handles route.ts files in the api directory.\n * Also supports root routes.ts for custom route definitions.\n *\n * @example\n * ```ts\n * import { farmApiPlugin } from '@farm.js/core'\n *\n * export default defineConfig({\n *   plugins: [farmApiPlugin({ srcDir: 'src' })],\n * })\n * ```\n */\n\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport {\n  APIRouteConflictError,\n  API_ROUTE_METHODS,\n  getAllowedAPIRouteMethods,\n  invokeAPIRouteEndpoint,\n  resolveAPIRouteEndpoint,\n} from \"./route-manager\";\nimport { matchAPIRouteAtBasePath } from \"./runtime\";\nimport { sendWebResponse } from \"../server/response\";\nimport { isFarmAPIRouteFileName } from \"./route-files\";\nimport { _withAfterNodeMiddleware } from \"../after\";\nimport { _runWithAPIRequestRuntime } from \"./server-context\";\nimport { isProgrammaticRoutesFileName } from \"../routes-shared\";\nimport { findProgrammaticRouteFilesInDir } from \"../routes.server\";\nimport { toPosixPath, toViteModuleId } from \"../utils\";\nimport {\n  createFarmRequestBodyErrorResponse,\n  readNodeRequestBody,\n  resolveFarmServerConfig,\n} from \"../server-http\";\nimport { createCliColors } from \"../cli-colors\";\nimport {\n  AmbiguousRouteError,\n  assertUniqueRouteParameters,\n  getRoutePatternShape,\n} from \"../routing/specificity\";\n\nexport interface FarmApiPluginOptions {\n  /** Source directory containing the api folder (default: 'src') */\n  srcDir?: string;\n  /** Enable debug logging */\n  debug?: boolean;\n  /** Maximum request body size, for example `\"10mb\"`. */\n  bodySizeLimit?: number | string;\n  /** Same-origin path where canonical `/api` routes are served. @default \"/api\" */\n  basePath?: string;\n}\n\nexport interface ApiRoute {\n  path: string;\n  filePath: string;\n  methods: string[];\n  endpoints: Record<string, any>;\n}\n\n/**\n * Farm.js API Routes Vite Plugin\n */\nexport function farmApiPlugin(options: FarmApiPluginOptions = {}): Plugin {\n  const srcDir = options.srcDir ?? \"src\";\n  const debug = options.debug ?? false;\n  const bodySizeLimit = resolveFarmServerConfig({\n    bodySizeLimit: options.bodySizeLimit,\n  }).bodySizeLimit;\n  const basePath = options.basePath;\n\n  // API routes cache\n  let apiRoutesCache: Map<string, ApiRoute> = new Map();\n  let apiRouterHandler: ((req: Request) => Promise<Response>) | null = null;\n  let discoveryComplete = false;\n  let discoveryPromise: Promise<void> | null = null;\n  let discoveryError: unknown;\n  let recoverFailedDiscovery: (() => Promise<boolean>) | undefined;\n  const endpointSources = new Map<string, Map<string, string>>();\n  const routeShapes = new Map<string, { routePath: string; filePath: string }>();\n\n  const log = (_message: string) => {};\n  const logResponse = (method: string, urlPath: string, status: number, duration: number) => {\n    const pc = createCliColors();\n    let statusColor = pc.green;\n    if (status >= 500) statusColor = pc.red;\n    else if (status >= 400) statusColor = pc.yellow;\n    else if (status >= 300) statusColor = pc.cyan;\n\n    const logMsg = [\n      pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.cyan(\"API\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n      pc.gray(urlPath),\n      pc.dim(\"-\"),\n      statusColor(status.toString()),\n      pc.dim(`(${duration}ms)`),\n    ].join(\" \");\n    console.log(logMsg);\n  };\n\n  const registerRouteShape = (routePath: string, filePath: string): void => {\n    assertUniqueRouteParameters(routePath, \"api\");\n    const shape = getRoutePatternShape(routePath, \"api\");\n    const existing = routeShapes.get(shape);\n    if (existing && existing.routePath !== routePath) {\n      throw new AmbiguousRouteError(\n        `Ambiguous API routes \"${existing.routePath}\" and \"${routePath}\" match the same URLs. Found ${existing.filePath} and ${filePath}. Keep only one route for this URL shape.`,\n      );\n    }\n    routeShapes.set(shape, { routePath, filePath });\n  };\n\n  const addEndpoint = (\n    routePath: string,\n    filePath: string,\n    method: string,\n    endpoint: any,\n  ): void => {\n    registerRouteShape(routePath, filePath);\n    const normalizedMethod = method.toUpperCase();\n    const existing = apiRoutesCache.get(routePath);\n    const existingFile = endpointSources.get(routePath)?.get(normalizedMethod);\n\n    if (existingFile) {\n      throw new APIRouteConflictError(routePath, normalizedMethod, existingFile, filePath);\n    }\n\n    if (existing) {\n      if (!existing.methods.includes(normalizedMethod)) {\n        existing.methods.push(normalizedMethod);\n      }\n      existing.endpoints[normalizedMethod] = endpoint;\n      const sources = endpointSources.get(routePath) ?? new Map();\n      sources.set(normalizedMethod, filePath);\n      endpointSources.set(routePath, sources);\n      return;\n    }\n\n    apiRoutesCache.set(routePath, {\n      path: routePath,\n      filePath,\n      methods: [normalizedMethod],\n      endpoints: { [normalizedMethod]: endpoint },\n    });\n    endpointSources.set(routePath, new Map([[normalizedMethod, filePath]]));\n  };\n\n  const removeEndpointsFromFile = (filePath: string): void => {\n    for (const [routePath, sources] of endpointSources) {\n      const route = apiRoutesCache.get(routePath);\n      if (!route) continue;\n\n      for (const [method, sourceFile] of sources) {\n        if (sourceFile !== filePath) continue;\n        sources.delete(method);\n        route.methods = route.methods.filter((candidate) => candidate !== method);\n        delete route.endpoints[method];\n      }\n\n      if (route.methods.length === 0) {\n        apiRoutesCache.delete(routePath);\n        endpointSources.delete(routePath);\n        routeShapes.delete(getRoutePatternShape(routePath, \"api\"));\n      } else {\n        const currentSource = sources.values().next().value;\n        if (route.filePath === filePath && currentSource) {\n          route.filePath = currentSource;\n        }\n        routeShapes.set(getRoutePatternShape(routePath, \"api\"), {\n          routePath,\n          filePath: currentSource ?? route.filePath,\n        });\n      }\n    }\n  };\n\n  const snapshotRouteState = () => ({\n    routes: new Map(\n      [...apiRoutesCache].map(([routePath, route]) => [\n        routePath,\n        {\n          ...route,\n          methods: [...route.methods],\n          endpoints: { ...route.endpoints },\n        },\n      ]),\n    ),\n    sources: new Map(\n      [...endpointSources].map(([routePath, sources]) => [routePath, new Map(sources)]),\n    ),\n    shapes: new Map(routeShapes),\n  });\n\n  const restoreRouteState = (snapshot: ReturnType<typeof snapshotRouteState>): void => {\n    apiRoutesCache = snapshot.routes;\n    endpointSources.clear();\n    for (const [routePath, sources] of snapshot.sources) {\n      endpointSources.set(routePath, sources);\n    }\n    routeShapes.clear();\n    for (const [shape, route] of snapshot.shapes) {\n      routeShapes.set(shape, route);\n    }\n  };\n\n  // Create API router handler\n  const createRouter = async (): Promise<void> => {\n    const totalEndpoints = Array.from(apiRoutesCache.values()).reduce(\n      (sum, route) => sum + route.methods.length,\n      0,\n    );\n\n    apiRouterHandler = null;\n\n    if (totalEndpoints > 0) {\n      apiRouterHandler = async (request: Request): Promise<Response> => {\n        const url = new URL(request.url);\n        const method = request.method.toUpperCase();\n        const pathname = url.pathname;\n\n        const match = matchAPIRouteAtBasePath(apiRoutesCache, pathname, basePath);\n        if (!match) {\n          return new Response(JSON.stringify({ error: \"Not Found\" }), {\n            status: 404,\n            headers: { \"Content-Type\": \"application/json\" },\n          });\n        }\n\n        const { route, params } = match;\n        const endpoint = resolveAPIRouteEndpoint(route, method);\n        if (!endpoint) {\n          return new Response(JSON.stringify({ error: \"Method Not Allowed\" }), {\n            status: 405,\n            headers: {\n              Allow: getAllowedAPIRouteMethods(route).join(\", \"),\n              \"Content-Type\": \"application/json\",\n            },\n          });\n        }\n\n        try {\n          return await invokeAPIRouteEndpoint(endpoint, request, params, bodySizeLimit);\n        } catch (error: any) {\n          return new Response(JSON.stringify({ error: error.message || \"Internal Server Error\" }), {\n            status: 500,\n            headers: { \"Content-Type\": \"application/json\" },\n          });\n        }\n      };\n\n      log(`API router created with ${totalEndpoints} endpoints`);\n    }\n  };\n\n  return {\n    name: \"@farm.js/core:api\",\n    enforce: \"pre\",\n\n    configureServer(server: ViteDevServer) {\n      // Discover API routes in /api directory\n      const discoverFileRoutes = async (apiDir: string): Promise<void> => {\n        const fs = await import(\"fs\");\n        const path = await import(\"path\");\n\n        if (!fs.existsSync(apiDir)) {\n          log(\"No api directory found\");\n          return;\n        }\n\n        const findRouteFiles = (dir: string): string[] => {\n          const files: string[] = [];\n          if (!fs.existsSync(dir)) return files;\n          const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n          for (const entry of entries) {\n            const fullPath = path.join(dir, entry.name);\n            if (entry.isDirectory()) {\n              files.push(...findRouteFiles(fullPath));\n            } else if (isFarmAPIRouteFileName(entry.name)) {\n              files.push(fullPath);\n            }\n          }\n          return files;\n        };\n\n        const routeFiles = findRouteFiles(apiDir);\n        apiRoutesCache.clear();\n        endpointSources.clear();\n        routeShapes.clear();\n\n        for (const filePath of routeFiles) {\n          try {\n            const relativePath = path.relative(apiDir, path.dirname(filePath));\n            const routePath =\n              \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n\n            const routeModule = await server.ssrLoadModule(filePath);\n            const endpoints: Record<string, any> = {};\n            const availableMethods: string[] = [];\n\n            for (const method of API_ROUTE_METHODS) {\n              if (routeModule[method]) {\n                availableMethods.push(method);\n                endpoints[method] = routeModule[method];\n              }\n            }\n\n            if (availableMethods.length > 0) {\n              for (const method of availableMethods) {\n                addEndpoint(routePath, filePath, method, endpoints[method]);\n              }\n              log(`API route discovered: ${availableMethods.join(\", \")} ${routePath}`);\n            }\n          } catch (e: any) {\n            if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n            log(`API route load failed at ${filePath}: ${e.message}`);\n          }\n        }\n      };\n\n      // Discover routes from root routes.ts file\n      const discoverRootRoutes = async (): Promise<void> => {\n        const fs = await import(\"fs\");\n        const path = await import(\"path\");\n\n        const routesFiles = [\n          path.join(server.config.root, srcDir, \"routes.ts\"),\n          path.join(server.config.root, srcDir, \"routes.tsx\"),\n          path.join(server.config.root, srcDir, \"routes.js\"),\n        ];\n\n        for (const routesFile of routesFiles) {\n          if (fs.existsSync(routesFile)) {\n            try {\n              const routesModule = await server.ssrLoadModule(routesFile);\n\n              for (const [exportName, exportValue] of Object.entries(routesModule)) {\n                const endpoint = exportValue as any;\n\n                if (endpoint && endpoint.__path) {\n                  const routePath = endpoint.__path;\n                  const method = String(endpoint.__method || \"GET\").toUpperCase();\n\n                  addEndpoint(routePath, routesFile, method, endpoint);\n                  log(`Root route discovered: ${method} ${routePath}`);\n                }\n              }\n            } catch (e: any) {\n              if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n              log(`Root routes.ts load failed: ${e.message}`);\n            }\n            break;\n          }\n        }\n      };\n\n      const discoverProgrammaticRoutes = async (): Promise<void> => {\n        const path = await import(\"path\");\n        const srcRoot = path.join(server.config.root, srcDir);\n        const routeFiles = findProgrammaticRouteFilesInDir(srcRoot);\n        if (routeFiles.length === 0) return;\n        const { getProgrammaticRouteManifest } = await import(\"../routes\");\n\n        for (const routeFile of routeFiles) {\n          try {\n            const routesModule = await server.ssrLoadModule(\n              toViteModuleId(routeFile, server.config.root),\n            );\n            const manifest = getProgrammaticRouteManifest(routesModule);\n            if (!manifest) continue;\n\n            for (const definition of manifest.routes) {\n              if (definition.kind !== \"api\") continue;\n\n              for (const [method, endpoint] of Object.entries(definition.methods)) {\n                if (endpoint) {\n                  addEndpoint(definition.path, routeFile, method, endpoint);\n                  log(`Programmatic route discovered: ${method} ${definition.path}`);\n                }\n              }\n            }\n          } catch (e: any) {\n            if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n            log(`Programmatic routes file load failed at ${routeFile}: ${e.message}`);\n          }\n        }\n      };\n\n      // Initialize discovery\n      const initializeDiscovery = async () => {\n        const path = await import(\"path\");\n        const apiDir = path.join(server.config.root, srcDir, \"api\");\n        log(`Discovering API routes in: ${apiDir}`);\n\n        await discoverFileRoutes(apiDir);\n        await discoverRootRoutes();\n        await discoverProgrammaticRoutes();\n        await createRouter();\n\n        discoveryComplete = true;\n        log(`API discovery complete: ${apiRoutesCache.size} routes found`);\n      };\n\n      discoveryPromise = initializeDiscovery().catch((e) => {\n        discoveryError = e;\n        console.error(\"[FARM] API discovery error:\", e);\n      });\n\n      const waitForDiscovery = async () => {\n        await discoveryPromise;\n        if (discoveryError) throw discoveryError;\n      };\n\n      recoverFailedDiscovery = async (): Promise<boolean> => {\n        if (!discoveryError) return false;\n\n        const previousState = snapshotRouteState();\n        try {\n          await initializeDiscovery();\n          discoveryError = undefined;\n          discoveryPromise = Promise.resolve();\n        } catch (error) {\n          restoreRouteState(previousState);\n          discoveryError = error;\n          discoveryComplete = false;\n          discoveryPromise = Promise.resolve();\n          throw error;\n        }\n\n        return true;\n      };\n\n      // Expose API router for other plugins\n      (server as any).__farmApi__ = {\n        getHandler: () => apiRouterHandler,\n        getRoutes: () => apiRoutesCache,\n        isReady: () => discoveryComplete,\n        waitForDiscovery,\n      };\n\n      // Add middleware to handle API requests\n      return () => {\n        const apiMiddleware = _withAfterNodeMiddleware(async (req, res, next) => {\n          const url = req.url || \"/\";\n          const pathname = url.split(\"?\")[0];\n          const method = req.method || \"GET\";\n\n          if (discoveryPromise) await waitForDiscovery();\n\n          if (!matchAPIRouteAtBasePath(apiRoutesCache, pathname, basePath)) {\n            return next();\n          }\n\n          if (!apiRouterHandler) {\n            return next();\n          }\n\n          const startTime = Date.now();\n\n          try {\n            // Execute middleware if available\n            const farmMiddleware = (server as any).__farmMiddleware__;\n            if (farmMiddleware) {\n              await farmMiddleware.waitForDiscovery?.();\n              const middlewareData = new Map<string, any>();\n              const handled = await farmMiddleware.execute(req, res, pathname, middlewareData);\n              if (handled) {\n                const duration = Date.now() - startTime;\n                logResponse(method, pathname, res.statusCode || 200, duration);\n                return;\n              }\n            }\n\n            // ctx.rewrite() mutates req.url; dispatch from the current\n            // value so dev matches production, where the rewritten request\n            // reaches the API router.\n            const currentUrl = req.url || url;\n            const currentPathname = currentUrl.split(\"?\")[0];\n            if (\n              currentPathname !== pathname &&\n              !matchAPIRouteAtBasePath(apiRoutesCache, currentPathname, basePath)\n            ) {\n              // Rewritten off the API surface; let the page pipeline serve it.\n              return next();\n            }\n\n            // Convert Node request to Web Request\n            const fullUrl = `http://${req.headers.host || \"localhost:3000\"}${currentUrl}`;\n            const headers = new Headers();\n            for (const [key, value] of Object.entries(req.headers)) {\n              if (value) {\n                headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n              }\n            }\n\n            let body: Buffer | undefined;\n            if (method !== \"GET\" && method !== \"HEAD\") {\n              body = await readNodeRequestBody(req as any, bodySizeLimit);\n            }\n\n            const request = new Request(fullUrl, {\n              method,\n              headers,\n              body: body\n                ? (body.buffer.slice(\n                    body.byteOffset,\n                    body.byteOffset + body.byteLength,\n                  ) as ArrayBuffer)\n                : undefined,\n            });\n\n            const response = await apiRouterHandler(request);\n\n            const duration = Date.now() - startTime;\n            logResponse(method, currentPathname, response.status, duration);\n\n            await sendWebResponse(res, response);\n          } catch (error: any) {\n            const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n            if (bodyErrorResponse) {\n              await sendWebResponse(res, bodyErrorResponse);\n              return;\n            }\n            const duration = Date.now() - startTime;\n            logResponse(method, pathname, 500, duration);\n            console.error(\"[FARM] API error:\", error);\n            res.statusCode = 500;\n            res.setHeader(\"Content-Type\", \"application/json\");\n            res.end(JSON.stringify({ error: \"Internal server error\" }));\n          }\n        });\n        server.middlewares.use((req, res, next) =>\n          _runWithAPIRequestRuntime(\n            {\n              basePath: basePath ?? \"/api\",\n              dispatch: async (request) =>\n                apiRouterHandler\n                  ? apiRouterHandler(request)\n                  : Response.json({ error: \"Not Found\" }, { status: 404 }),\n            },\n            () => apiMiddleware(req, res, next),\n          ),\n        );\n      };\n    },\n\n    async handleHotUpdate({ file, server, modules }) {\n      const normalizedFile = toPosixPath(file);\n      const fileName = normalizedFile.split(\"/\").pop() || \"\";\n\n      // Handle root routes.ts updates\n      if (\n        fileName === \"routes.ts\" ||\n        fileName === \"routes.tsx\" ||\n        fileName === \"routes.js\" ||\n        isProgrammaticRoutesFileName(fileName)\n      ) {\n        log(`Root routes file updated: ${fileName}`);\n\n        for (const mod of modules) {\n          server.moduleGraph.invalidateModule(mod);\n        }\n\n        if (await recoverFailedDiscovery?.()) return [];\n\n        const previousState = snapshotRouteState();\n\n        try {\n          const routesModule = await server.ssrLoadModule(file);\n          removeEndpointsFromFile(file);\n\n          for (const [exportName, exportValue] of Object.entries(routesModule)) {\n            const endpoint = exportValue as any;\n\n            if (endpoint && endpoint.__path) {\n              const routePath = endpoint.__path;\n              const method = String(endpoint.__method || \"GET\").toUpperCase();\n\n              addEndpoint(routePath, file, method, endpoint);\n              log(`Root route reloaded: ${method} ${routePath}`);\n            }\n          }\n\n          const { getProgrammaticRouteManifest } = await import(\"../routes\");\n          const manifest = getProgrammaticRouteManifest(routesModule);\n          if (manifest) {\n            for (const definition of manifest.routes) {\n              if (definition.kind !== \"api\") continue;\n\n              for (const [method, endpoint] of Object.entries(definition.methods)) {\n                if (endpoint) {\n                  addEndpoint(definition.path, file, method, endpoint);\n                  log(`Programmatic route reloaded: ${method} ${definition.path}`);\n                }\n              }\n            }\n          }\n\n          await createRouter();\n          log(`API router recreated`);\n        } catch (e: any) {\n          restoreRouteState(previousState);\n          if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n          log(`Root routes.ts HMR failed: ${e.message}`);\n        }\n\n        return [];\n      }\n\n      // Handle file-based route updates\n      if (normalizedFile.includes(\"/api/\") && fileName.startsWith(\"route.\")) {\n        const shortPath = normalizedFile.split(\"/api/\")[1] || normalizedFile;\n        log(`API route updated: ${shortPath}`);\n\n        for (const mod of modules) {\n          server.moduleGraph.invalidateModule(mod);\n        }\n\n        if (await recoverFailedDiscovery?.()) return [];\n\n        const previousState = snapshotRouteState();\n        try {\n          const path = await import(\"path\");\n          const apiDir = path.join(server.config.root, srcDir, \"api\");\n          const relativePath = path.relative(apiDir, path.dirname(file));\n          const routePath =\n            \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n          const fs = await import(\"fs\");\n          if (!fs.existsSync(file)) {\n            removeEndpointsFromFile(file);\n            await createRouter();\n            log(`API route file removed: ${routePath}`);\n            return [];\n          }\n          const routeModule = await server.ssrLoadModule(file);\n\n          removeEndpointsFromFile(file);\n          const availableMethods: string[] = [];\n          for (const method of API_ROUTE_METHODS) {\n            if (!routeModule[method]) continue;\n            availableMethods.push(method);\n            addEndpoint(routePath, file, method, routeModule[method]);\n          }\n\n          await createRouter();\n          log(`API route reloaded: ${availableMethods.join(\", \")} ${routePath}`);\n          log(`API router recreated`);\n        } catch (e: any) {\n          restoreRouteState(previousState);\n          if (e instanceof APIRouteConflictError || e instanceof AmbiguousRouteError) throw e;\n          log(`API route HMR failed: ${e.message}`);\n        }\n\n        return [];\n      }\n    },\n  };\n}\n","export { OpenAPIGenerator } from \"./generator\";\nexport { OpenAPIManager } from \"./manager\";\nexport { ScalarAPIDocumentation } from \"./scalar-component\";\nexport { DocsRoute } from \"./docs-route\";\nexport type { OpenAPISpec } from \"./generator\";\n","import React from \"react\";\n\ninterface ScalarAPIDocumentationProps {\n  spec: any;\n  config?: {\n    theme?: \"default\" | \"purple\" | \"blue\" | \"green\" | \"red\" | \"yellow\";\n    layout?: \"modern\" | \"classic\";\n    showSidebar?: boolean;\n    hideDownloadButton?: boolean;\n    hideTryItPanel?: boolean;\n  };\n}\n\nexport function ScalarAPIDocumentation({ spec, config = {} }: ScalarAPIDocumentationProps) {\n  const [isLoaded, setIsLoaded] = React.useState(false);\n\n  React.useEffect(() => {\n    // Dynamically import Scalar components\n    const loadScalar = async () => {\n      try {\n        // Load Scalar CSS\n        const cssLink = document.createElement(\"link\");\n        cssLink.rel = \"stylesheet\";\n        cssLink.href = \"https://cdn.jsdelivr.net/npm/@scalar/api-reference@latest/dist/style.css\";\n        document.head.appendChild(cssLink);\n\n        // Load Scalar JS\n        const script = document.createElement(\"script\");\n        script.src =\n          \"https://cdn.jsdelivr.net/npm/@scalar/api-reference@latest/dist/browser/standalone.js\";\n        script.onload = () => setIsLoaded(true);\n        document.head.appendChild(script);\n      } catch (error) {\n        console.error(\"Failed to load Scalar:\", error);\n      }\n    };\n\n    loadScalar();\n  }, []);\n\n  React.useEffect(() => {\n    if (isLoaded && window.ScalarApiReference) {\n      // Initialize Scalar\n      const container = document.getElementById(\"scalar-api-reference\");\n      if (container) {\n        window.ScalarApiReference({\n          spec,\n          theme: config.theme || \"default\",\n          layout: config.layout || \"modern\",\n          showSidebar: config.showSidebar !== false,\n          hideDownloadButton: config.hideDownloadButton || false,\n          hideTryItPanel: config.hideTryItPanel || false,\n        });\n      }\n    }\n  }, [isLoaded, spec, config]);\n\n  return (\n    <div className=\"scalar-container\">\n      <div id=\"scalar-api-reference\" style={{ height: \"100vh\", width: \"100%\" }} />\n    </div>\n  );\n}\n\n// Extend window type for Scalar\ndeclare global {\n  interface Window {\n    ScalarApiReference: (config: any) => void;\n  }\n}\n","import React from \"react\";\nimport { ScalarAPIDocumentation } from \"./scalar-component\";\n\ninterface DocsRouteProps {\n  spec: any;\n  config?: any;\n}\n\nexport function DocsRoute({ spec, config }: DocsRouteProps) {\n  return (\n    <html lang=\"en\">\n      <head>\n        <meta charSet=\"utf-8\" />\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n        <link rel=\"icon\" href=\"data:,\" />\n        <title>{config?.title || \"API Documentation\"}</title>\n        <style>{`\n          body {\n            margin: 0;\n            padding: 0;\n            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;\n          }\n          .scalar-container {\n            height: 100vh;\n            width: 100%;\n          }\n        `}</style>\n      </head>\n      <body>\n        <ScalarAPIDocumentation spec={spec} config={config} />\n      </body>\n    </html>\n  );\n}\n","/**\n * Farm.js Query State Parsers\n *\n * Shared parsers that can be used in both client and server contexts\n */\n\nexport interface Parser<T> {\n  parse: (value: string) => T | null;\n  serialize: (value: T) => string;\n  withDefault?: (defaultValue: T) => Parser<T>;\n}\n\nconst INTEGER_PATTERN = /^[+-]?\\d+$/;\nconst FLOAT_PATTERN = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?$/;\nconst ISO_DATE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst ISO_DATE_TIME_PATTERN =\n  /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction parseInteger(value: string): number | null {\n  if (!INTEGER_PATTERN.test(value)) return null;\n  const parsed = Number(value);\n  return Number.isSafeInteger(parsed) ? parsed : null;\n}\n\nfunction parseFloatValue(value: string): number | null {\n  if (!FLOAT_PATTERN.test(value)) return null;\n  const parsed = Number(value);\n  return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction isValidCalendarDate(year: number, month: number, day: number): boolean {\n  if (month < 1 || month > 12 || day < 1) return false;\n  const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n  const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n  return day <= daysInMonth[month - 1];\n}\n\nfunction parseIsoDate(value: string): Date | null {\n  const match = value.match(ISO_DATE_PATTERN);\n  if (!match) return null;\n\n  const year = Number(match[1]);\n  const month = Number(match[2]);\n  const day = Number(match[3]);\n  if (!isValidCalendarDate(year, month, day)) return null;\n\n  const date = new Date(0);\n  date.setUTCHours(0, 0, 0, 0);\n  date.setUTCFullYear(year, month - 1, day);\n  return date;\n}\n\nfunction parseIsoDateTime(value: string): Date | null {\n  const match = value.match(ISO_DATE_TIME_PATTERN);\n  if (!match) return null;\n\n  const year = Number(match[1]);\n  const month = Number(match[2]);\n  const day = Number(match[3]);\n  const hour = Number(match[4]);\n  const minute = Number(match[5]);\n  const second = Number(match[6]);\n  const timezone = match[7];\n  if (!isValidCalendarDate(year, month, day) || hour > 23 || minute > 59 || second > 59) {\n    return null;\n  }\n\n  if (timezone !== \"Z\") {\n    const [offsetHour, offsetMinute] = timezone.slice(1).split(\":\").map(Number);\n    if (offsetHour > 23 || offsetMinute > 59) return null;\n  }\n\n  const date = new Date(value);\n  return Number.isFinite(date.getTime()) ? date : null;\n}\n\n// String parser\nexport const asString: Parser<string> = {\n  parse: (value: string) => (value && value.trim()) || null,\n  serialize: (value: string) => value,\n  withDefault: (defaultValue: string) => ({\n    parse: (value: string) => (value && value.trim()) || defaultValue,\n    serialize: (value: string) => value || defaultValue,\n  }),\n};\n\n// Integer parser\nexport const asInteger: Parser<number> = {\n  parse: parseInteger,\n  serialize: (value: number) => value.toString(),\n  withDefault: (defaultValue: number) => ({\n    parse: (value: string) => parseInteger(value) ?? defaultValue,\n    serialize: (value: number) => value.toString(),\n  }),\n};\n\n// Float parser\nexport const asFloat: Parser<number> = {\n  parse: parseFloatValue,\n  serialize: (value: number) => value.toString(),\n  withDefault: (defaultValue: number) => ({\n    parse: (value: string) => parseFloatValue(value) ?? defaultValue,\n    serialize: (value: number) => value.toString(),\n  }),\n};\n\n// Boolean parser\nexport const asBoolean: Parser<boolean> = {\n  parse: (value: string) => {\n    if (value === \"true\") return true;\n    if (value === \"false\") return false;\n    return null;\n  },\n  serialize: (value: boolean) => value.toString(),\n  withDefault: (defaultValue: boolean) => ({\n    parse: (value: string) => {\n      if (value === \"true\") return true;\n      if (value === \"false\") return false;\n      return defaultValue;\n    },\n    serialize: (value: boolean) => value.toString(),\n  }),\n};\n\n// Array parser\nconst STRUCTURED_ARRAY_PREFIX = \"~farm-array:v1:\";\nexport interface ArrayParserOptions {\n  /** Preserve comma URLs by default; opt in when item delimiters must round-trip. */\n  format?: \"comma\" | \"structured\";\n}\n\nfunction parseArrayItems(value: string, structured: boolean): string[] {\n  if (structured && value.startsWith(STRUCTURED_ARRAY_PREFIX)) {\n    try {\n      const parsed = JSON.parse(value.slice(STRUCTURED_ARRAY_PREFIX.length));\n      if (Array.isArray(parsed) && parsed.every((item) => typeof item === \"string\")) {\n        return parsed;\n      }\n    } catch {\n      // Keep accepting legacy values that happen to begin with the prefix.\n    }\n  }\n\n  return value\n    .split(\",\")\n    .filter(Boolean)\n    .map((item) => item.trim());\n}\n\nfunction serializeArrayItems(values: string[], structured: boolean): string {\n  if (!structured) return values.join(\",\");\n\n  const needsStructuredEncoding = values.some(\n    (value, index) =>\n      value === \"\" ||\n      value.trim() !== value ||\n      value.includes(\",\") ||\n      (index === 0 && value.startsWith(STRUCTURED_ARRAY_PREFIX)),\n  );\n  return needsStructuredEncoding\n    ? `${STRUCTURED_ARRAY_PREFIX}${JSON.stringify(values)}`\n    : values.join(\",\");\n}\n\nexport function asArrayOf<T>(itemParser: Parser<T>, options: ArrayParserOptions = {}): Parser<T[]> {\n  const structured = options.format === \"structured\";\n  const parse = (value: string): T[] | null => {\n    if (!value) return null;\n    return parseArrayItems(value, structured)\n      .map((item) => itemParser.parse(item))\n      .filter((item) => item !== null) as T[];\n  };\n  const serialize = (value: T[]) =>\n    serializeArrayItems(\n      value.map((item) => itemParser.serialize(item)),\n      structured,\n    );\n\n  return {\n    parse,\n    serialize,\n    withDefault: (defaultValue: T[]) => ({\n      parse: (value: string) => parse(value) ?? defaultValue,\n      serialize,\n    }),\n  };\n}\n\n// JSON parser\nexport function asJson<T>(): Parser<T> {\n  return {\n    parse: (value: string) => {\n      try {\n        return JSON.parse(value);\n      } catch {\n        return null;\n      }\n    },\n    serialize: (value: T) => JSON.stringify(value),\n    withDefault: (defaultValue: T) => ({\n      parse: (value: string) => {\n        try {\n          return JSON.parse(value);\n        } catch {\n          return defaultValue;\n        }\n      },\n      serialize: (value: T) => JSON.stringify(value),\n    }),\n  };\n}\n\n// ISO Date parser\nexport const asIsoDate: Parser<Date> = {\n  parse: parseIsoDate,\n  serialize: (value: Date) => value.toISOString().slice(0, 10),\n  withDefault: (defaultValue: Date) => ({\n    parse: (value: string) => parseIsoDate(value) ?? defaultValue,\n    serialize: (value: Date) => value.toISOString().slice(0, 10),\n  }),\n};\n\n// ISO DateTime parser\nexport const asIsoDateTime: Parser<Date> = {\n  parse: parseIsoDateTime,\n  serialize: (value: Date) => value.toISOString(),\n  withDefault: (defaultValue: Date) => ({\n    parse: (value: string) => parseIsoDateTime(value) ?? defaultValue,\n    serialize: (value: Date) => value.toISOString(),\n  }),\n};\n\n// Custom parser creator\nexport function createParser<T>(config: {\n  parse: (value: string) => T | null;\n  serialize: (value: T) => string;\n}): Parser<T> {\n  return {\n    parse: config.parse,\n    serialize: config.serialize,\n    withDefault: (defaultValue: T) => ({\n      parse: (value: string) => config.parse(value) ?? defaultValue,\n      serialize: config.serialize,\n    }),\n  };\n}\n\n// Type inference helper\nexport type inferParserType<T> = T extends Parser<infer U> ? U : never;\n","import type { Parser } from \"./parsers\";\n\nexport type RouteParamsInput =\n  | Record<string, string | undefined>\n  | URLSearchParams\n  | Promise<Record<string, string | undefined> | URLSearchParams>;\n\nfunction normalizeParams(input: Record<string, string | undefined> | URLSearchParams) {\n  if (input instanceof URLSearchParams) {\n    const params: Record<string, string | undefined> = {};\n    input.forEach((value, key) => {\n      params[key] = value;\n    });\n    return params;\n  }\n  return input;\n}\n\nexport async function loadRouteParams<T extends Record<string, Parser<any>>>(\n  input: RouteParamsInput,\n  parsers: T,\n  options: { strict?: boolean } = {},\n): Promise<{ [K in keyof T]: ReturnType<T[K][\"parse\"]> }> {\n  const resolved = await Promise.resolve(input);\n  const params = normalizeParams(resolved);\n  const result = {} as { [K in keyof T]: ReturnType<T[K][\"parse\"]> };\n\n  for (const [key, parser] of Object.entries(parsers)) {\n    const raw = params[key] ?? \"\";\n    const parsed = parser.parse(raw);\n    if (parsed === null && options.strict) {\n      throw new Error(`Failed to parse route param \"${key}\" with value \"${raw}\"`);\n    }\n    result[key as keyof T] = parsed as ReturnType<T[typeof key][\"parse\"]>;\n  }\n\n  return result;\n}\n\nexport function parseRouteParams<T extends Record<string, Parser<any>>>(\n  input: Record<string, string | undefined> | URLSearchParams,\n  parsers: T,\n  options: { strict?: boolean } = {},\n): { [K in keyof T]: ReturnType<T[K][\"parse\"]> } {\n  const params = normalizeParams(input);\n  const result = {} as { [K in keyof T]: ReturnType<T[K][\"parse\"]> };\n\n  for (const [key, parser] of Object.entries(parsers)) {\n    const raw = params[key] ?? \"\";\n    const parsed = parser.parse(raw);\n    if (parsed === null && options.strict) {\n      throw new Error(`Failed to parse route param \"${key}\" with value \"${raw}\"`);\n    }\n    result[key as keyof T] = parsed as ReturnType<T[typeof key][\"parse\"]>;\n  }\n\n  return result;\n}\n","/**\n * Middleware Chain Builder\n */\n\nimport type {\n  MiddlewareChain,\n  MiddlewareFunction,\n  MiddlewareContext,\n  MiddlewareConfig,\n  RateLimitConfig,\n  RateLimitStorage,\n  RateLimitStatus,\n  RateLimitIncrementResult,\n  MemoryRateLimitStorageOptions,\n  MiddlewareResult,\n} from \"./types\";\n\nconst DEFAULT_MEMORY_RATE_LIMIT_ENTRIES = 100_000;\n\nexport class UnsupportedRateLimitStorageError extends TypeError {\n  constructor() {\n    super(\n      \"RateLimitStorage must implement atomic increment(key, windowMs). Legacy get/set adapters can lose increments under concurrency. Use memoryRateLimitStorage() for one process or redisRateLimitStorage() from @farm.js/cache-redis for production.\",\n    );\n    this.name = \"UnsupportedRateLimitStorageError\";\n  }\n}\n\n/** Create an atomic, process-local fixed-window rate-limit store. */\nexport function memoryRateLimitStorage(\n  options: MemoryRateLimitStorageOptions = {},\n): RateLimitStorage {\n  const maxEntries = options.maxEntries ?? DEFAULT_MEMORY_RATE_LIMIT_ENTRIES;\n  if (!Number.isSafeInteger(maxEntries) || maxEntries <= 0) {\n    throw new TypeError(\"memoryRateLimitStorage maxEntries must be a positive safe integer.\");\n  }\n\n  const records = new Map<string, RateLimitIncrementResult>();\n\n  function read(key: string, now: number): RateLimitIncrementResult | null {\n    const record = records.get(key);\n    if (!record) return null;\n    if (record.resetAt <= now) {\n      records.delete(key);\n      return null;\n    }\n    return record;\n  }\n\n  function pruneExpired(now: number): void {\n    for (const [key, record] of records) {\n      if (record.resetAt <= now) records.delete(key);\n    }\n  }\n\n  return {\n    increment(key, windowMs) {\n      if (!Number.isSafeInteger(windowMs) || windowMs <= 0) {\n        throw new TypeError(\"Rate-limit windowMs must be a positive safe integer.\");\n      }\n      const now = Date.now();\n      const current = read(key, now);\n      if (current) {\n        const next = { count: current.count + 1, resetAt: current.resetAt };\n        records.set(key, next);\n        return next;\n      }\n\n      if (records.size >= maxEntries) pruneExpired(now);\n      if (records.size >= maxEntries) {\n        throw new Error(\n          `Process-local rate-limit storage reached its ${maxEntries} active-key capacity. Configure a shared production adapter or increase maxEntries.`,\n        );\n      }\n\n      const next = { count: 1, resetAt: now + windowMs };\n      records.set(key, next);\n      return next;\n    },\n    get(key) {\n      const record = read(key, Date.now());\n      return record ? { ...record } : null;\n    },\n  };\n}\n\nconst defaultRateLimitStorage = memoryRateLimitStorage();\n\nfunction parseTimeWindow(window: string): number {\n  const match = window.match(/^(\\d+)(ms|s|m|h|d)$/);\n  if (!match) throw new Error(`Invalid time window: ${window}`);\n\n  const [, amount, unit] = match;\n  const value = Number.parseInt(amount, 10);\n\n  const multipliers: Record<string, number> = {\n    ms: 1,\n    s: 1000,\n    m: 60 * 1000,\n    h: 60 * 60 * 1000,\n    d: 24 * 60 * 60 * 1000,\n  };\n\n  const windowMs = value * multipliers[unit];\n  if (!Number.isSafeInteger(windowMs) || windowMs <= 0) {\n    throw new Error(`Invalid time window: ${window}`);\n  }\n  return windowMs;\n}\n\nfunction createRateLimitMiddleware(config: RateLimitConfig): MiddlewareFunction {\n  if (!Number.isSafeInteger(config.requests) || config.requests <= 0) {\n    throw new TypeError(\"Rate limit requests must be a positive safe integer.\");\n  }\n  const windowMs = parseTimeWindow(config.window);\n  const storage = config.storage || defaultRateLimitStorage;\n  assertAtomicRateLimitStorage(storage);\n\n  return async (ctx: MiddlewareContext, next) => {\n    const key = config.keyGenerator\n      ? config.keyGenerator(ctx)\n      : `${ctx.request.socket.remoteAddress}:${ctx.pathname}`;\n\n    const current = await storage.increment(key, windowMs);\n    assertRateLimitIncrementResult(current);\n    const now = Date.now();\n    const resetIn = Math.max(1, Math.ceil((current.resetAt - now) / 1000));\n    const remaining = Math.max(0, config.requests - current.count);\n    setRateLimitHeaders(ctx, config.requests, remaining, resetIn, Math.ceil(windowMs / 1000));\n\n    if (current.count > config.requests) {\n      setMiddlewareResponseHeader(ctx, \"Retry-After\", String(resetIn));\n      if (config.onLimit) {\n        const result = await config.onLimit(ctx);\n        if (result) return result;\n      }\n\n      ctx.json(\n        {\n          error: \"Rate limit exceeded\",\n          retryAfter: resetIn,\n        },\n        429,\n      );\n      return;\n    }\n\n    return next();\n  };\n}\n\nfunction assertAtomicRateLimitStorage(storage: RateLimitStorage): void {\n  if (!storage || typeof storage.increment !== \"function\") {\n    throw new UnsupportedRateLimitStorageError();\n  }\n}\n\nfunction assertRateLimitIncrementResult(\n  result: RateLimitIncrementResult,\n): asserts result is RateLimitIncrementResult {\n  if (\n    !result ||\n    !Number.isSafeInteger(result.count) ||\n    result.count <= 0 ||\n    !Number.isFinite(result.resetAt) ||\n    result.resetAt <= 0\n  ) {\n    throw new TypeError(\n      \"RateLimitStorage.increment() must return a positive integer count and a resetAt timestamp.\",\n    );\n  }\n}\n\nfunction setRateLimitHeaders(\n  ctx: MiddlewareContext,\n  limit: number,\n  remaining: number,\n  resetIn: number,\n  windowSeconds: number,\n): void {\n  setMiddlewareResponseHeader(ctx, \"RateLimit-Policy\", `\"farm\";q=${limit};w=${windowSeconds}`);\n  setMiddlewareResponseHeader(ctx, \"RateLimit\", `\"farm\";r=${remaining};t=${resetIn}`);\n}\n\nfunction setMiddlewareResponseHeader(ctx: MiddlewareContext, name: string, value: string): void {\n  ctx.headers.set(name, value);\n  if (!ctx.response.headersSent && !ctx.response.writableEnded) {\n    ctx.response.setHeader(name, value);\n  }\n}\n\nfunction matchPattern(pattern: string | RegExp, pathname: string): boolean {\n  if (pattern instanceof RegExp) {\n    return pattern.test(pathname);\n  }\n\n  // Protect glob stars, escape every regex metacharacter, then restore the\n  // globs — otherwise \"/promo.html\" also matches \"/promoXhtml\" and a pattern\n  // containing \"(\" throws at request time.\n  const regexPattern = pattern\n    .replace(/\\*\\*/g, \"__DOUBLE_STAR__\")\n    .replace(/\\*/g, \"__SINGLE_STAR__\")\n    .replace(/[.+?^${}()|[\\]\\\\/]/g, \"\\\\$&\")\n    .replace(/__DOUBLE_STAR__/g, \".*\")\n    .replace(/__SINGLE_STAR__/g, \"[^/]+\");\n\n  const regex = new RegExp(`^${regexPattern}$`);\n  return regex.test(pathname);\n}\n\nclass MiddlewareChainImpl implements MiddlewareChain {\n  private handlers: MiddlewareFunction[] = [];\n  public config?: MiddlewareConfig;\n  private basePath: string;\n\n  constructor(basePath = \"/\") {\n    this.basePath =\n      basePath === \"/\" ? \"/\" : basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n  }\n\n  /**\n   * Set the base path for this middleware chain (called by manager when loading)\n   */\n  setBasePath(path: string): void {\n    this.basePath = path === \"/\" ? \"/\" : path.endsWith(\"/\") ? path.slice(0, -1) : path;\n  }\n\n  use(fn: MiddlewareFunction): MiddlewareChain {\n    this.handlers.push(fn);\n    return this;\n  }\n\n  /**\n   * Normalize a path pattern - auto-scope to middleware route\n   * If middleware is in /contact, then \"/api\" becomes \"/contact/api\"\n   */\n  private normalizePattern(pattern: string): string {\n    // If we're at root middleware, use pattern as-is\n    if (this.basePath === \"/\") {\n      // Ensure it starts with /\n      return pattern.startsWith(\"/\") ? pattern : `/${pattern}`;\n    }\n\n    // For route-specific middleware, always scope the pattern\n    // Remove leading / from pattern if present, then join with basePath\n    const cleanPattern = pattern.startsWith(\"/\") ? pattern.slice(1) : pattern;\n    return `${this.basePath}/${cleanPattern}`;\n  }\n\n  /**\n   * Conditionally run middleware based on a condition.\n   * Only supports boolean values or functions that evaluate to boolean.\n   * Route-based string matching has been removed - use function conditions instead.\n   *\n   * @example\n   * .when(true, (ctx, next) => { ... })  // Always run\n   * .when((ctx) => ctx.data.get('flag'), (ctx, next) => { ... })  // Conditional\n   * .when((ctx) => ctx.pathname === '/contact', (ctx, next) => { ... })  // Path-based condition\n   */\n  when(\n    condition: boolean | ((ctx: MiddlewareContext) => boolean),\n    fn: MiddlewareFunction | ((chain: MiddlewareChain) => void),\n  ): MiddlewareChain {\n    const conditionalMiddleware: MiddlewareFunction = async (ctx, next) => {\n      // Evaluate condition - boolean or function\n      const shouldRun = typeof condition === \"function\" ? condition(ctx) : condition;\n\n      if (!shouldRun) {\n        return next();\n      }\n\n      if (typeof fn === \"function\" && fn.length === 2) {\n        return (fn as MiddlewareFunction)(ctx, next);\n      } else {\n        const subChain = middleware(this.basePath);\n        (fn as (chain: MiddlewareChain) => void)(subChain);\n        const { handlers } = subChain.build();\n\n        let index = 0;\n        let returnedResponse: Response | undefined;\n        const executeNext = async (): Promise<MiddlewareResult> => {\n          if (index < handlers.length) {\n            const handler = handlers[index++];\n            const result = await handler(ctx, executeNext);\n            if (result instanceof Response) {\n              returnedResponse = result;\n              return result;\n            }\n          } else {\n            const result = await next();\n            if (result instanceof Response) {\n              returnedResponse = result;\n              return result;\n            }\n          }\n          return returnedResponse;\n        };\n\n        return executeNext();\n      }\n    };\n    this.handlers.push(conditionalMiddleware);\n    return this;\n  }\n\n  rateLimit(config: RateLimitConfig): MiddlewareChain {\n    this.handlers.push(createRateLimitMiddleware(config));\n    return this;\n  }\n\n  redirect(source: string, destination: string, permanent = false): MiddlewareChain {\n    const redirectMiddleware: MiddlewareFunction = async (ctx, next) => {\n      // Auto-scope source pattern to the middleware route\n      const normalizedSource = this.normalizePattern(source);\n      if (matchPattern(normalizedSource, ctx.pathname)) {\n        ctx.redirect(destination, permanent ? 308 : 307);\n        return;\n      }\n      return next();\n    };\n\n    this.handlers.push(redirectMiddleware);\n    return this;\n  }\n\n  /**\n   * Rewrite the current middleware route to a new destination.\n   * Since each middleware file is route-specific, the source is automatically\n   * the middleware's route, so you only need to specify the destination.\n   *\n   * @param destination - The destination path to rewrite to\n   * @param condition - Optional boolean or function that evaluates to boolean.\n   *                    If provided and evaluates to false, rewrite is skipped.\n   *                    If not provided, rewrite always happens.\n   *\n   * @example\n   * // In /contact/middleware.ts\n   * .rewrite('/about')  // Always rewrites /contact to /about\n   * .rewrite('/about', true)  // Always rewrites\n   * .rewrite('/about', false)  // Never rewrites\n   * .rewrite('/about', (ctx) => ctx.data.get('shouldRewrite'))  // Conditional rewrite\n   */\n  rewrite(\n    destination: string,\n    condition?: boolean | ((ctx: MiddlewareContext) => boolean),\n  ): MiddlewareChain {\n    const rewriteMiddleware: MiddlewareFunction = async (ctx, next) => {\n      // Check condition if provided\n      if (condition !== undefined) {\n        const shouldRewrite = typeof condition === \"function\" ? condition(ctx) : condition;\n        if (!shouldRewrite) {\n          return next();\n        }\n      }\n\n      // If this middleware is route-specific (not root)\n      if (this.basePath !== \"/\") {\n        // Rewrite when the pathname exactly matches this middleware's route\n        // This rewrites the entire route (e.g., /contact -> /about)\n        if (ctx.pathname === this.basePath) {\n          ctx.rewrite(destination);\n        }\n        // Also handle sub-routes: rewrite /contact/something to /destination/something\n        else if (ctx.pathname.startsWith(this.basePath + \"/\")) {\n          const subPath = ctx.pathname.slice(this.basePath.length);\n          const newPath = destination + subPath;\n          ctx.rewrite(newPath);\n        }\n      } else {\n        // For root middleware, this is less common\n        // Only rewrite if pathname matches exactly (edge case)\n        ctx.rewrite(destination);\n      }\n      return next();\n    };\n\n    this.handlers.push(rewriteMiddleware);\n    return this;\n  }\n\n  build() {\n    return {\n      handlers: this.handlers,\n      config: this.config,\n    };\n  }\n}\n\n/**\n * Get rate limit status for a key\n * @example\n * const status = await getRateLimitStatus('user:123', 100, storage);\n */\nexport async function getRateLimitStatus(\n  key: string,\n  limit: number,\n  storage: RateLimitStorage = defaultRateLimitStorage,\n): Promise<RateLimitStatus> {\n  if (!Number.isSafeInteger(limit) || limit <= 0) {\n    throw new TypeError(\"Rate limit must be a positive safe integer.\");\n  }\n  assertAtomicRateLimitStorage(storage);\n  if (typeof storage.get !== \"function\") {\n    throw new TypeError(\n      \"getRateLimitStatus() requires a RateLimitStorage adapter that implements get(key).\",\n    );\n  }\n  const record = await storage.get(key);\n\n  if (!record) {\n    return {\n      requests: 0,\n      limit,\n      remaining: limit,\n      resetIn: null,\n      resetAt: null,\n      isLimited: false,\n    };\n  }\n  assertRateLimitIncrementResult(record);\n\n  const now = Date.now();\n\n  if (record.resetAt && now > record.resetAt) {\n    return {\n      requests: 0,\n      limit,\n      remaining: limit,\n      resetIn: null,\n      resetAt: null,\n      isLimited: false,\n    };\n  }\n\n  const requests = record.count || 0;\n  const remaining = Math.max(0, limit - requests);\n  const isLimited = requests >= limit;\n\n  let resetIn: number | null = null;\n  let resetAt: Date | null = null;\n\n  if (record.resetAt) {\n    const remainingMs = record.resetAt - now;\n    resetIn = remainingMs > 0 ? Math.ceil(remainingMs / 1000) : null;\n    resetAt = new Date(record.resetAt);\n  }\n\n  return {\n    requests,\n    limit,\n    remaining,\n    resetIn,\n    resetAt,\n    isLimited,\n  };\n}\n\nexport function middleware(basePath = \"/\"): MiddlewareChain {\n  return new MiddlewareChainImpl(basePath);\n}\n","/**\n * Farm.js Middleware System\n *\n * Export public API\n */\n\nexport {\n  middleware,\n  getRateLimitStatus,\n  memoryRateLimitStorage,\n  UnsupportedRateLimitStorageError,\n} from \"./chain\";\nexport { createContext } from \"./context\";\nexport { MiddlewareManager } from \"./manager\";\nexport {\n  getMiddlewareContext,\n  getMiddlewareData,\n  getMiddlewareValue,\n  _runWithMiddlewareContext,\n  _runWithMiddlewareData,\n} from \"./server\";\nexport { unwrapMiddleware, getFromMiddleware, hasMiddlewareData } from \"./helpers\";\nexport {\n  createProductionMiddlewareRunner,\n  applyProductionMiddlewareHeaders,\n} from \"./production-runtime\";\nexport * from \"./vite-plugin\";\n\nexport type {\n  MiddlewareContext,\n  MiddlewareFunction,\n  RequestMiddleware,\n  RequestMiddlewareContext,\n  MiddlewareStore,\n  ReadonlyMiddlewareStore,\n  MiddlewareChain,\n  MiddlewareConfig,\n  CookieJar,\n  CookieOptions,\n  RateLimitConfig,\n  RateLimitIncrementResult,\n  RateLimitStorage,\n  RateLimitStatus,\n  MemoryRateLimitStorageOptions,\n  NextFunction,\n  MiddlewareResult,\n  FarmMiddlewareConfig,\n} from \"./types\";\n","/**\n * Middleware helper utilities for pages\n */\n\nimport type { MiddlewareProps } from \"../types\";\n\n/**\n * Unwrap middleware data from PageProps\n *\n * @example\n * ```tsx\n * export default async function Page(props: PageProps) {\n *   const { user, stats } = await unwrapMiddleware(props.middleware, {\n *     user: null,\n *     stats: { views: 0, clicks: 0 }\n *   });\n *\n *   return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function unwrapMiddleware<T extends Record<string, any>>(\n  middleware: MiddlewareProps | undefined,\n  defaults?: Partial<T>,\n): Partial<T> {\n  if (!middleware) {\n    return (defaults || {}) as Partial<T>;\n  }\n\n  const result: any = { ...defaults };\n\n  for (const [key, value] of middleware.data) {\n    result[key] = value;\n  }\n\n  return result as Partial<T>;\n}\n\n/**\n * Get a single value from middleware with a default\n *\n * @example\n * ```tsx\n * export default async function Page(props: PageProps) {\n *   const user = await getMiddlewareValue(props.middleware, 'user', null);\n *   return <div>Welcome {user?.name || 'Guest'}</div>;\n * }\n * ```\n */\nexport function getFromMiddleware<T = any>(\n  middleware: MiddlewareProps | undefined,\n  key: string,\n  defaultValue?: T,\n): T | undefined {\n  if (!middleware) {\n    return defaultValue;\n  }\n\n  const value = middleware.data.get(key);\n  return value !== undefined ? value : defaultValue;\n}\n\n/**\n * Check if middleware data exists\n */\nexport function hasMiddlewareData(middleware: MiddlewareProps | undefined): boolean {\n  if (!middleware) return false;\n  return middleware.data.size > 0;\n}\n","import type {\n  CookieJar,\n  CookieOptions,\n  FarmMiddlewareConfig,\n  MiddlewareConfig,\n  MiddlewareContext,\n  MiddlewareFunction,\n  MiddlewareMatcher,\n  MiddlewareModule,\n  MiddlewareResult,\n} from \"./types\";\nimport { emitFarmEvent } from \"../observability\";\nimport { decodeRouteSegment } from \"../utils/decode\";\nimport { normalizeMiddlewareModule } from \"./module\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport type { ResolvedFarmServerConfig } from \"../server-http\";\nimport { parseMiddlewareCookieHeader } from \"./cookie-header\";\n\nexport interface ProductionMiddlewareModuleEntry {\n  path: string;\n  filePath?: string;\n  module: MiddlewareModule | Record<string, any>;\n}\n\nexport interface ProductionMiddlewareRunnerOptions {\n  config?: FarmMiddlewareConfig | null;\n  modules?: ProductionMiddlewareModuleEntry[];\n  i18n?: ResolvedFarmI18nConfig;\n  server?: Pick<ResolvedFarmServerConfig, \"trustProxy\">;\n}\n\nexport interface ProductionMiddlewareResult {\n  request: Request;\n  response: Response | null;\n  data: Map<string, any>;\n  context: Map<string, any>;\n  headers: Headers;\n  handled: boolean;\n}\n\ninterface ProductionMiddlewareEntry {\n  path: string;\n  filePath: string;\n  handlers: MiddlewareFunction[];\n  config?: MiddlewareConfig;\n  source: \"config\" | \"file\";\n}\n\ninterface WebMiddlewareContextState {\n  ctx: MiddlewareContext;\n  headers: WebResponseHeaderMap;\n  getRequest(): Request;\n  getResponse(): Response | null;\n}\n\nconst FARM_SET_COOKIE_HEADERS = Symbol(\"farm.setCookieHeaders\");\n\ntype InternalMiddlewareParent = MiddlewareContext[\"parent\"] & {\n  [FARM_SET_COOKIE_HEADERS]?: string[];\n};\n\nclass WebResponseHeaderMap extends Map<string, string> {\n  private setCookies: string[] = [];\n\n  override set(key: string, value: string): this {\n    if (key.toLowerCase() === \"set-cookie\") {\n      this.setCookies = [value];\n      super.set(\"Set-Cookie\", value);\n      return this;\n    }\n    return super.set(key, value);\n  }\n\n  override delete(key: string): boolean {\n    if (key.toLowerCase() === \"set-cookie\") {\n      this.setCookies = [];\n      return super.delete(\"Set-Cookie\") || super.delete(\"set-cookie\");\n    }\n    return super.delete(key);\n  }\n\n  override clear(): void {\n    this.setCookies = [];\n    super.clear();\n  }\n\n  appendSetCookie(value: string): void {\n    this.setCookies.push(value);\n    super.set(\"Set-Cookie\", value);\n  }\n\n  replaceSetCookies(values: readonly string[]): void {\n    this.setCookies = [...values];\n    super.delete(\"Set-Cookie\");\n    super.delete(\"set-cookie\");\n    if (this.setCookies.length > 0) {\n      super.set(\"Set-Cookie\", this.setCookies[this.setCookies.length - 1]);\n    }\n  }\n\n  getSetCookies(): readonly string[] {\n    return this.setCookies;\n  }\n}\n\nfunction serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n  let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n  if (options.maxAge != null) cookie += `; Max-Age=${options.maxAge}`;\n  if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;\n  cookie += `; Path=${options.path || \"/\"}`;\n  if (options.domain) cookie += `; Domain=${options.domain}`;\n  if (options.secure) cookie += \"; Secure\";\n  if (options.httpOnly) cookie += \"; HttpOnly\";\n  if (options.sameSite) {\n    cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase()}${options.sameSite.slice(1)}`;\n  }\n\n  return cookie;\n}\n\nclass WebCookieJar implements CookieJar {\n  private cookies: Record<string, string>;\n\n  constructor(\n    request: Request,\n    private headers: WebResponseHeaderMap,\n  ) {\n    this.cookies = parseMiddlewareCookieHeader(request.headers.get(\"cookie\"));\n  }\n\n  get(name: string): string | undefined {\n    return this.cookies[name];\n  }\n\n  set(name: string, value: string, options: CookieOptions = {}): void {\n    this.cookies[name] = value;\n    const cookieString = serializeCookie(name, value, options);\n    this.headers.appendSetCookie(cookieString);\n  }\n\n  delete(name: string): void {\n    delete this.cookies[name];\n    const cookieString = serializeCookie(name, \"\", {\n      maxAge: 0,\n      expires: new Date(0),\n    });\n    this.headers.appendSetCookie(cookieString);\n  }\n\n  getAll(): Record<string, string> {\n    return { ...this.cookies };\n  }\n}\n\nfunction mapToHeaders(map: WebResponseHeaderMap): Headers {\n  const headers = new Headers();\n  for (const [key, value] of map) {\n    if (key.toLowerCase() === \"set-cookie\") continue;\n    headers.set(key, value);\n  }\n  for (const cookie of map.getSetCookies()) {\n    headers.append(\"Set-Cookie\", cookie);\n  }\n  return headers;\n}\n\nfunction headersToRecord(headers: Map<string, string>): Record<string, string> {\n  return Object.fromEntries(headers);\n}\n\nfunction isMiddlewareResponse(value: unknown): value is Response {\n  return value instanceof Response;\n}\n\nfunction createResponseShim(headers: WebResponseHeaderMap): Record<string, any> {\n  return {\n    headersSent: false,\n    writableEnded: false,\n    setHeader(name: string, value: string | string[]) {\n      if (name.toLowerCase() === \"set-cookie\") {\n        headers.replaceSetCookies(Array.isArray(value) ? value.map(String) : [String(value)]);\n      } else {\n        headers.set(name, Array.isArray(value) ? value.join(\", \") : String(value));\n      }\n    },\n    getHeader(name: string) {\n      return headers.get(name);\n    },\n    writeHead(status: number, responseHeaders?: Record<string, string>) {\n      this.statusCode = status;\n      if (responseHeaders) {\n        for (const [key, value] of Object.entries(responseHeaders)) {\n          headers.set(key, value);\n        }\n      }\n      this.headersSent = true;\n    },\n    end() {\n      this.writableEnded = true;\n    },\n  };\n}\n\nfunction withNodeRequestShape(request: Request, trustProxy: boolean): Request {\n  const requestWithShape = request as Request & {\n    socket?: { remoteAddress?: string };\n  };\n\n  if (!requestWithShape.socket) {\n    const forwardedFor = trustProxy\n      ? request.headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim()\n      : undefined;\n    try {\n      requestWithShape.socket = {\n        remoteAddress: forwardedFor || \"127.0.0.1\",\n      };\n    } catch {\n      // Some Request implementations may not be extensible.\n    }\n  }\n\n  return requestWithShape;\n}\n\nfunction createHandledResponse(\n  body: BodyInit | null,\n  init: ResponseInit,\n  headers: WebResponseHeaderMap,\n): Response {\n  const responseHeaders = new Headers(init.headers);\n  for (const [key, value] of headers) {\n    if (key.toLowerCase() === \"set-cookie\") continue;\n    responseHeaders.set(key, value);\n  }\n  for (const cookie of headers.getSetCookies()) {\n    responseHeaders.append(\"Set-Cookie\", cookie);\n  }\n  return new Response(body, { ...init, headers: responseHeaders });\n}\n\nfunction createWebMiddlewareContext(\n  request: Request,\n  parent?: MiddlewareContext[\"parent\"],\n  trustProxy = false,\n): WebMiddlewareContextState {\n  let currentRequest = withNodeRequestShape(request, trustProxy);\n  let handledResponse: Response | null = null;\n  const url = new URL(currentRequest.url);\n  const data = parent?.data ? new Map(parent.data) : new Map<string, any>();\n  const locals = parent?.locals ? new Map(parent.locals) : new Map<string, any>();\n  const headers = new WebResponseHeaderMap();\n\n  if (parent?.headers) {\n    for (const [key, value] of Object.entries(parent.headers)) {\n      if (key.toLowerCase() === \"set-cookie\") continue;\n      headers.set(key, value);\n    }\n  }\n  const parentCookies = (parent as InternalMiddlewareParent | undefined)?.[FARM_SET_COOKIE_HEADERS];\n  if (parentCookies) headers.replaceSetCookies(parentCookies);\n\n  const ctx = {\n    request: currentRequest as any,\n    response: createResponseShim(headers) as any,\n    url,\n    pathname: url.pathname,\n    searchParams: url.searchParams,\n    method: currentRequest.method || \"GET\",\n    params: {},\n    route: url.pathname,\n    parent,\n    vite: {\n      isDev: false,\n      hmr: false,\n    },\n    data,\n    locals,\n    headers,\n    cookies: new WebCookieJar(currentRequest, headers),\n    _handled: false as boolean,\n    _redirectUrl: undefined as string | undefined,\n    _rewriteUrl: undefined as string | undefined,\n\n    redirect(redirectUrl: string, status = 307): void {\n      ctx._redirectUrl = redirectUrl;\n      ctx._handled = true;\n      handledResponse = createHandledResponse(\n        `Redirecting to ${redirectUrl}`,\n        {\n          status,\n          headers: {\n            Location: redirectUrl,\n            \"Content-Type\": \"text/plain\",\n          },\n        },\n        headers,\n      );\n    },\n\n    rewrite(rewriteUrl: string): void {\n      ctx._rewriteUrl = rewriteUrl;\n      const nextUrl = new URL(rewriteUrl, currentRequest.url);\n      currentRequest = withNodeRequestShape(new Request(nextUrl, currentRequest), trustProxy);\n      ctx.request = currentRequest as any;\n      ctx.url = nextUrl;\n      ctx.pathname = nextUrl.pathname;\n      ctx.searchParams = nextUrl.searchParams;\n      ctx.route = nextUrl.pathname;\n    },\n\n    json(jsonData: any, status = 200): void {\n      ctx._handled = true;\n      handledResponse = createHandledResponse(\n        JSON.stringify(jsonData),\n        {\n          status,\n          headers: {\n            \"Content-Type\": \"application/json\",\n          },\n        },\n        headers,\n      );\n    },\n\n    text(content: string, status = 200): void {\n      ctx._handled = true;\n      handledResponse = createHandledResponse(\n        content,\n        {\n          status,\n          headers: {\n            \"Content-Type\": \"text/plain\",\n          },\n        },\n        headers,\n      );\n    },\n\n    html(content: string, status = 200): void {\n      ctx._handled = true;\n      handledResponse = createHandledResponse(\n        content,\n        {\n          status,\n          headers: {\n            \"Content-Type\": \"text/html\",\n          },\n        },\n        headers,\n      );\n    },\n  } satisfies MiddlewareContext;\n\n  return {\n    ctx,\n    headers,\n    getRequest: () => currentRequest,\n    getResponse: () => handledResponse,\n  };\n}\n\nfunction toMatcherList(matcher: MiddlewareConfig[\"matcher\"]): MiddlewareMatcher[] {\n  if (!matcher) return [];\n  return Array.isArray(matcher) ? matcher : [matcher];\n}\n\nfunction escapeRegex(value: string): string {\n  return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n}\n\nfunction parseColonParam(segment: string): { name: string; modifier?: string } {\n  const raw = segment.slice(1);\n  const last = raw[raw.length - 1];\n  const modifier = last === \"*\" || last === \"+\" || last === \"?\" ? last : undefined;\n  return {\n    name: modifier ? raw.slice(0, -1) : raw,\n    modifier,\n  };\n}\n\nfunction compilePathPattern(pattern: string): { regex: RegExp; params: string[] } {\n  const params: string[] = [];\n  const segments = pattern.split(\"/\").filter(Boolean);\n\n  if (segments.length === 0) {\n    return { regex: /^\\/$/, params };\n  }\n\n  const parts = segments.map((segment) => {\n    if (segment === \"**\") {\n      return \"(?:/.*)?\";\n    }\n\n    if (segment === \"*\") {\n      return \"/[^/]+\";\n    }\n\n    if (segment.startsWith(\":\")) {\n      const { name, modifier } = parseColonParam(segment);\n      params.push(name);\n\n      if (modifier === \"*\") {\n        return \"(?:/(.*))?\";\n      }\n      if (modifier === \"+\") {\n        return \"/(.+)\";\n      }\n      return \"/([^/]+)\";\n    }\n\n    if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n      params.push(segment.slice(4, -1));\n      return \"(?:/(.*))?\";\n    }\n\n    if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n      params.push(segment.slice(1, -1));\n      return \"/([^/]+)\";\n    }\n\n    return `/${escapeRegex(segment).replace(/\\\\\\*/g, \"[^/]*\")}`;\n  });\n\n  return {\n    regex: new RegExp(`^${parts.join(\"\")}$`),\n    params,\n  };\n}\n\nfunction matchPattern(\n  pattern: string | RegExp,\n  pathname: string,\n): { matched: boolean; params?: Record<string, string> } {\n  if (pattern instanceof RegExp) {\n    pattern.lastIndex = 0;\n    const match = pattern.exec(pathname);\n    return {\n      matched: !!match,\n      params: match?.groups ? { ...match.groups } : undefined,\n    };\n  }\n\n  if (pattern === \"*\" || pattern === \"/(.*)\") {\n    return { matched: true };\n  }\n\n  if (pattern.endsWith(\"(.*)\")) {\n    const prefix = pattern.slice(0, -4);\n    return { matched: pathname === prefix || pathname.startsWith(`${prefix}/`) };\n  }\n\n  const { regex, params } = compilePathPattern(pattern);\n  const match = regex.exec(pathname);\n  if (!match) {\n    return { matched: false };\n  }\n\n  const values: Record<string, string> = {};\n  params.forEach((param, index) => {\n    values[param] = decodeRouteSegment(match[index + 1] || \"\");\n  });\n\n  return {\n    matched: true,\n    params: Object.keys(values).length > 0 ? values : undefined,\n  };\n}\n\nfunction matchesConfig(\n  pathname: string,\n  config: MiddlewareConfig,\n  ctx: MiddlewareContext,\n): { matched: boolean; params?: Record<string, string> } {\n  if (config.exclude) {\n    for (const pattern of config.exclude) {\n      if (matchPattern(pattern, pathname).matched) {\n        return { matched: false };\n      }\n    }\n  }\n\n  if (config.matcher) {\n    for (const matcher of toMatcherList(config.matcher)) {\n      if (typeof matcher === \"string\" || matcher instanceof RegExp) {\n        const result = matchPattern(matcher, pathname);\n        if (result.matched) {\n          return result;\n        }\n      } else if (typeof matcher === \"function\" && matcher(ctx)) {\n        return { matched: true };\n      }\n    }\n    return { matched: false };\n  }\n\n  return { matched: true };\n}\n\nfunction matchRoutePath(\n  pathname: string,\n  middlewarePath: string,\n): { matched: boolean; params?: Record<string, string> } {\n  if (middlewarePath === \"/\") return { matched: true };\n\n  const exactMatch = matchPattern(middlewarePath, pathname);\n  if (exactMatch.matched) {\n    return exactMatch;\n  }\n\n  const nestedMatch = matchPattern(`${middlewarePath}/:__farmRest*`, pathname);\n  if (!nestedMatch.matched) {\n    return { matched: false };\n  }\n\n  const params = { ...nestedMatch.params };\n  delete params.__farmRest;\n  return {\n    matched: true,\n    params: Object.keys(params).length > 0 ? params : undefined,\n  };\n}\n\nfunction getConfigHandlers(\n  entry: MiddlewareConfig & {\n    handler?: MiddlewareFunction;\n    handlers?: MiddlewareFunction[];\n  },\n): MiddlewareFunction[] {\n  const handlers: MiddlewareFunction[] = [];\n  if (\"handler\" in entry && typeof entry.handler === \"function\") {\n    handlers.push(entry.handler);\n  }\n  if (\"handlers\" in entry && Array.isArray(entry.handlers)) {\n    handlers.push(...entry.handlers.filter((handler) => typeof handler === \"function\"));\n  }\n  return handlers;\n}\n\nfunction toMiddlewareConfig(\n  entry: MiddlewareConfig & {\n    handler?: MiddlewareFunction;\n    handlers?: MiddlewareFunction[];\n  },\n): MiddlewareConfig {\n  const { matcher, exclude, runtime } = entry;\n  return { matcher, exclude, runtime };\n}\n\nfunction normalizeConfigMiddleware(config?: FarmMiddlewareConfig | null): {\n  entries: ProductionMiddlewareEntry[];\n  globalConfig?: MiddlewareConfig;\n} {\n  const entries: ProductionMiddlewareEntry[] = [];\n  let globalConfig: MiddlewareConfig | undefined;\n\n  if (!config) {\n    return { entries, globalConfig };\n  }\n\n  const configEntries = Array.isArray(config) ? config : [config];\n  for (const [index, entry] of configEntries.entries()) {\n    const handlers = getConfigHandlers(entry);\n    const middlewareConfig = toMiddlewareConfig(entry);\n\n    if (handlers.length === 0) {\n      globalConfig = middlewareConfig;\n      continue;\n    }\n\n    entries.push({\n      path: \"/\",\n      filePath: `farm.config.ts#middleware-${index}`,\n      handlers,\n      config: middlewareConfig,\n      source: \"config\",\n    });\n  }\n\n  return { entries, globalConfig };\n}\n\nfunction normalizeFileMiddleware(\n  modules: ProductionMiddlewareModuleEntry[] = [],\n): ProductionMiddlewareEntry[] {\n  const entries: ProductionMiddlewareEntry[] = [];\n\n  for (const moduleEntry of modules) {\n    const normalized = normalizeMiddlewareModule(moduleEntry.module, moduleEntry.path);\n    if (!normalized) {\n      continue;\n    }\n\n    entries.push({\n      path: moduleEntry.path,\n      filePath: moduleEntry.filePath || moduleEntry.path,\n      handlers: normalized.handlers,\n      config: normalized.config,\n      source: \"file\",\n    });\n  }\n\n  return entries;\n}\n\nasync function executeHandlers(\n  handlers: MiddlewareFunction[],\n  ctx: MiddlewareContext,\n): Promise<Response | undefined> {\n  let handlerIndex = 0;\n  let returnedResponse: Response | undefined;\n  const executeNext = async (): Promise<MiddlewareResult> => {\n    if (handlerIndex < handlers.length) {\n      const handler = handlers[handlerIndex++];\n      const result = await handler(ctx, executeNext);\n      if (isMiddlewareResponse(result)) {\n        returnedResponse = result;\n        return result;\n      }\n    }\n    return returnedResponse;\n  };\n\n  const result = await executeNext();\n  return isMiddlewareResponse(result) ? result : returnedResponse;\n}\n\nfunction emptyResult(request: Request): ProductionMiddlewareResult {\n  return {\n    request,\n    response: null,\n    data: new Map(),\n    context: new Map(),\n    headers: new Headers(),\n    handled: false,\n  };\n}\n\nexport function createProductionMiddlewareRunner(options: ProductionMiddlewareRunnerOptions = {}) {\n  const configMiddleware = normalizeConfigMiddleware(options.config);\n  const fileMiddleware = normalizeFileMiddleware(options.modules);\n  const entries = [...configMiddleware.entries, ...fileMiddleware];\n  const globalConfig = configMiddleware.globalConfig;\n\n  return async function runProductionMiddleware(\n    request: Request,\n  ): Promise<ProductionMiddlewareResult> {\n    if (!globalConfig && entries.length === 0) {\n      return emptyResult(request);\n    }\n\n    let contextState = createWebMiddlewareContext(\n      request,\n      undefined,\n      options.server?.trustProxy === true,\n    );\n    let ctx = contextState.ctx;\n    let currentRequest = contextState.getRequest();\n    const initialPathname = options.i18n?.enabled\n      ? stripFarmLocaleFromPathname(ctx.pathname, options.i18n)\n      : ctx.pathname;\n    let parentData: MiddlewareContext[\"parent\"] | undefined;\n\n    if (globalConfig) {\n      const globalMatch = matchesConfig(initialPathname, globalConfig, ctx);\n      if (!globalMatch.matched) {\n        return emptyResult(request);\n      }\n      if (globalMatch.params) {\n        ctx.params = { ...ctx.params, ...globalMatch.params };\n      }\n    }\n\n    const applicable = entries\n      .map((entry) => ({\n        entry,\n        routeMatch:\n          entry.source === \"config\"\n            ? { matched: true }\n            : matchRoutePath(initialPathname, entry.path),\n      }))\n      .filter((candidate) => candidate.routeMatch.matched);\n\n    if (applicable.length === 0) {\n      return {\n        request: currentRequest,\n        response: null,\n        data: new Map(ctx.data),\n        context: new Map(ctx.locals),\n        headers: mapToHeaders(contextState.headers),\n        handled: false,\n      };\n    }\n\n    for (const candidate of applicable) {\n      const { entry, routeMatch } = candidate;\n      const configMatch = entry.config\n        ? matchesConfig(initialPathname, entry.config, ctx)\n        : { matched: true };\n      if (!configMatch.matched) {\n        continue;\n      }\n\n      if (parentData) {\n        contextState = createWebMiddlewareContext(\n          currentRequest,\n          parentData,\n          options.server?.trustProxy === true,\n        );\n        ctx = contextState.ctx;\n      }\n\n      if (routeMatch.params) {\n        ctx.params = { ...ctx.params, ...routeMatch.params };\n      }\n      if (configMatch.params) {\n        ctx.params = { ...ctx.params, ...configMatch.params };\n      }\n\n      const middlewareStartTime = Date.now();\n      const middlewareEvent = {\n        route: entry.path,\n        pathname: initialPathname,\n        name: entry.filePath,\n      };\n      emitFarmEvent({ type: \"middleware.start\", ...middlewareEvent });\n\n      try {\n        const returnedResponse = await executeHandlers(entry.handlers, ctx);\n        currentRequest = contextState.getRequest();\n\n        if (returnedResponse) {\n          const response = applyProductionMiddlewareHeaders(\n            returnedResponse,\n            mapToHeaders(contextState.headers),\n          );\n          emitFarmEvent({\n            type: \"middleware.shortCircuit\",\n            ...middlewareEvent,\n            status: response.status,\n          });\n          return {\n            request: currentRequest,\n            response,\n            data: new Map(ctx.data),\n            context: new Map(ctx.locals),\n            headers: mapToHeaders(contextState.headers),\n            handled: true,\n          };\n        }\n\n        if (ctx._handled) {\n          const response = contextState.getResponse() || new Response(null);\n          emitFarmEvent({\n            type: \"middleware.shortCircuit\",\n            ...middlewareEvent,\n            status: response.status,\n          });\n          return {\n            request: currentRequest,\n            response,\n            data: new Map(ctx.data),\n            context: new Map(ctx.locals),\n            headers: mapToHeaders(contextState.headers),\n            handled: true,\n          };\n        }\n\n        emitFarmEvent({\n          type: \"middleware.complete\",\n          ...middlewareEvent,\n          durationMs: Date.now() - middlewareStartTime,\n        });\n      } catch (error) {\n        emitFarmEvent({\n          type: \"middleware.error\",\n          ...middlewareEvent,\n          error,\n        });\n        throw error;\n      }\n\n      parentData = {\n        data: new Map(ctx.data),\n        locals: new Map(ctx.locals),\n        headers: headersToRecord(contextState.headers),\n        [FARM_SET_COOKIE_HEADERS]: [...contextState.headers.getSetCookies()],\n      } as InternalMiddlewareParent;\n    }\n\n    return {\n      request: currentRequest,\n      response: null,\n      data: new Map(ctx.data),\n      context: new Map(ctx.locals),\n      headers: mapToHeaders(contextState.headers),\n      handled: false,\n    };\n  };\n}\n\nexport function applyProductionMiddlewareHeaders(\n  response: Response,\n  middlewareHeaders?: Headers | null,\n): Response {\n  if (!middlewareHeaders || Array.from(middlewareHeaders.keys()).length === 0) {\n    return response;\n  }\n\n  const headers = new Headers(response.headers);\n  const getSetCookie = (middlewareHeaders as Headers & { getSetCookie?: () => string[] })\n    .getSetCookie;\n  const setCookies = getSetCookie\n    ? getSetCookie.call(middlewareHeaders)\n    : middlewareHeaders.get(\"set-cookie\")\n      ? [middlewareHeaders.get(\"set-cookie\")!]\n      : [];\n  for (const [key, value] of middlewareHeaders) {\n    if (key.toLowerCase() === \"set-cookie\") continue;\n    // A returned Response's headers are authoritative and preserved (matching\n    // the dev runtime, where the Response is applied after ctx.headers). ctx\n    // headers only add keys the Response did not already set.\n    if (headers.has(key)) continue;\n    headers.set(key, value);\n  }\n  for (const cookie of setCookies) {\n    headers.append(\"Set-Cookie\", cookie);\n  }\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n","/**\n * Standalone Vite middleware support used by Farm's RSC and API plugins.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport { MiddlewareManager } from \"./manager\";\n\nexport interface FarmMiddlewarePluginOptions {\n  /** Source directory (default: `src`). */\n  srcDir?: string;\n  /** Enable debug logging. */\n  debug?: boolean;\n}\n\nfunction getMiddlewareAppDirectory(root: string, srcDir: string): string {\n  const sourceDirectory = path.join(root, srcDir);\n  const appDirectory = path.join(sourceDirectory, \"app\");\n  return fs.existsSync(appDirectory) ? appDirectory : sourceDirectory;\n}\n\nexport function farmMiddlewarePlugin(options: FarmMiddlewarePluginOptions = {}): Plugin {\n  const srcDir = options.srcDir ?? \"src\";\n  let manager: MiddlewareManager | null = null;\n  let discoveryComplete = false;\n  let discoveryPromise: Promise<void> | null = null;\n\n  const discover = async (server: ViteDevServer): Promise<void> => {\n    manager = new MiddlewareManager(getMiddlewareAppDirectory(server.config.root, srcDir), server);\n    await manager.discover();\n    discoveryComplete = true;\n  };\n\n  return {\n    name: \"@farm.js/core:middleware\",\n    enforce: \"pre\",\n\n    configureServer(server) {\n      discoveryPromise = discover(server);\n      void discoveryPromise.catch((error) => {\n        console.error(\"[FARM] Middleware discovery error:\", error);\n      });\n\n      const execute = async (\n        req: IncomingMessage,\n        res: ServerResponse,\n        _pathname?: string,\n        sharedData?: Map<string, any>,\n      ): Promise<boolean> => {\n        if (discoveryPromise) {\n          await discoveryPromise;\n        }\n\n        if (!manager) {\n          return false;\n        }\n\n        const handled = await manager.execute(req, res);\n        const middlewareData = (req as any).__FARM_MIDDLEWARE_DATA__;\n        if (sharedData && middlewareData instanceof Map) {\n          for (const [key, value] of middlewareData) {\n            sharedData.set(key, value);\n          }\n        }\n        return handled;\n      };\n\n      (server as any).__farmMiddleware__ = {\n        execute,\n        getMiddlewares: () => manager?.getMiddlewares() ?? [],\n        isReady: () => discoveryComplete,\n        waitForDiscovery: () => discoveryPromise,\n      };\n    },\n\n    async handleHotUpdate({ file, server, modules }) {\n      if (!/^middleware\\.[tj]sx?$/.test(path.basename(file))) {\n        return;\n      }\n\n      for (const module of modules) {\n        server.moduleGraph.invalidateModule(module);\n      }\n\n      await manager?.reload();\n      server.ws.send({ type: \"full-reload\", path: \"*\" });\n      return [];\n    },\n  };\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 = normalizePathname(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 splitPathname(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 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 { resolveFarmThemeConfig } from \"./config\";\nexport type {\n  FarmResolvedTheme,\n  FarmThemeConfig,\n  FarmThemePreference,\n  FarmThemeSnapshot,\n  ResolvedFarmThemeConfig,\n} from \"./types\";\n","type AnyEnvironmentFunction = (...args: never[]) => unknown;\n\nexport type FarmEnvironment = \"server\" | \"client\";\n\nexport interface FarmIsomorphicFnOptions<TArgs extends unknown[], TServerResult, TClientResult> {\n  server: (...args: TArgs) => TServerResult;\n  client: (...args: TArgs) => TClientResult;\n}\n\nexport class FarmEnvironmentError extends Error {\n  readonly code = \"FARM_ENVIRONMENT_MISMATCH\";\n\n  constructor(\n    readonly api: \"createServerOnlyFn\" | \"createClientOnlyFn\",\n    readonly expected: FarmEnvironment,\n    readonly actual: FarmEnvironment,\n  ) {\n    super(`${api}() can only be called on the ${expected}. It was called on the ${actual}.`);\n    this.name = \"FarmEnvironmentError\";\n  }\n}\n\nexport function createServerOnlyFn<TFunction extends AnyEnvironmentFunction>(\n  implementation: TFunction,\n): TFunction;\nexport function createServerOnlyFn(\n  implementation: AnyEnvironmentFunction | undefined,\n  compiledActualEnvironment?: FarmEnvironment,\n): AnyEnvironmentFunction {\n  if (compiledActualEnvironment) {\n    return createMismatchFunction(\"createServerOnlyFn\", \"server\", compiledActualEnvironment);\n  }\n  if (getRuntimeEnvironment() !== \"server\") {\n    return createMismatchFunction(\"createServerOnlyFn\", \"server\");\n  }\n\n  assertFunction(implementation, \"createServerOnlyFn\");\n  return implementation;\n}\n\nexport function createClientOnlyFn<TFunction extends AnyEnvironmentFunction>(\n  implementation: TFunction,\n): TFunction;\nexport function createClientOnlyFn(\n  implementation: AnyEnvironmentFunction | undefined,\n  compiledActualEnvironment?: FarmEnvironment,\n): AnyEnvironmentFunction {\n  if (compiledActualEnvironment) {\n    return createMismatchFunction(\"createClientOnlyFn\", \"client\", compiledActualEnvironment);\n  }\n  if (getRuntimeEnvironment() !== \"client\") {\n    return createMismatchFunction(\"createClientOnlyFn\", \"client\");\n  }\n\n  assertFunction(implementation, \"createClientOnlyFn\");\n  return implementation;\n}\n\nexport function createIsomorphicFn<TArgs extends unknown[], TServerResult, TClientResult>(\n  options: FarmIsomorphicFnOptions<TArgs, TServerResult, TClientResult>,\n): (...args: TArgs) => TServerResult | TClientResult {\n  if (!options || typeof options !== \"object\") {\n    throw new TypeError(\"createIsomorphicFn requires server and client functions\");\n  }\n\n  assertFunction(options.server, \"createIsomorphicFn server\");\n  assertFunction(options.client, \"createIsomorphicFn client\");\n\n  return getRuntimeEnvironment() === \"server\" ? options.server : options.client;\n}\n\nfunction getRuntimeEnvironment(): FarmEnvironment {\n  return typeof window === \"undefined\" ? \"server\" : \"client\";\n}\n\nfunction createMismatchFunction(\n  api: \"createServerOnlyFn\" | \"createClientOnlyFn\",\n  expected: FarmEnvironment,\n  actual: FarmEnvironment = expected === \"server\" ? \"client\" : \"server\",\n) {\n  return function farmEnvironmentBoundary(): never {\n    throw new FarmEnvironmentError(api, expected, actual);\n  };\n}\n\nfunction assertFunction(value: unknown, label: string): asserts value is AnyEnvironmentFunction {\n  if (typeof value !== \"function\") {\n    throw new TypeError(`${label} must be a function`);\n  }\n}\n","import { getServerActionExecutionContext, getServerActionSignal } from \"./server-action-security\";\nimport { _resolveCurrentRequest } from \"./server/request-bridge\";\nimport { applyFarmCacheInvalidationTargets, type FarmCacheInvalidationTarget } from \"./cache\";\nimport { ServerActionError, ServerFnFailure } from \"./server-fn-error\";\n\nexport {\n  FARM_SERVER_FN_FAILURE_SYMBOL,\n  ServerActionError,\n  ServerFnFailure,\n  createServerFnTransportError,\n  isServerFnFailure,\n} from \"./server-fn-error\";\nexport type { SerializedServerFnFailure } from \"./server-fn-error\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n// Generic schema type that works with Zod v3/v4 and similar validator APIs.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ServerFnSchema = {\n  _input?: any;\n  _output?: any;\n  parse?: (data: unknown) => any;\n  parseAsync?: (data: unknown) => Promise<any>;\n  safeParse?: (data: unknown) => any;\n  safeParseAsync?: (data: unknown) => Promise<any>;\n};\n\nexport type InferServerFnSchemaInput<T> = T extends { _input: infer I } ? I : unknown;\nexport type InferServerFnSchemaOutput<T> = T extends { _output: infer O }\n  ? O\n  : T extends { parse: (data: unknown) => infer R }\n    ? R\n    : unknown;\n\nexport type ServerFnErrorSchema = ServerFnSchema &\n  ({ parse: (data: unknown) => unknown } | { safeParse: (data: unknown) => unknown });\n\nexport type ServerFnErrorDefinition<\n  TSchema extends ServerFnErrorSchema = ServerFnErrorSchema,\n  TStatus extends number = number,\n> = {\n  status: TStatus;\n  /** Schema for the public error payload exposed to callers. */\n  data: TSchema;\n  /** Public message safe to expose to callers. */\n  message?: string;\n};\n\nexport type ServerFnErrorDefinitions = Record<\n  string,\n  ServerFnErrorDefinition<ServerFnErrorSchema, number>\n>;\n\nexport type ServerFnDeclaredError<TErrors extends ServerFnErrorDefinitions> = {\n  [TCode in keyof TErrors]: ServerFnFailure<\n    TCode & string,\n    InferServerFnSchemaOutput<TErrors[TCode][\"data\"]>,\n    TErrors[TCode][\"status\"]\n  >;\n}[keyof TErrors];\n\nexport type ServerFnError<TErrors extends ServerFnErrorDefinitions> = keyof TErrors extends never\n  ? Error\n  : ServerActionError | ServerFnDeclaredError<TErrors>;\n\nexport type ServerFnErrorHandler<TErrors extends ServerFnErrorDefinitions> = <\n  TCode extends keyof TErrors & string,\n>(\n  code: TCode,\n  data: InferServerFnSchemaInput<TErrors[TCode][\"data\"]>,\n) => never;\n\nexport type ServerFnFormInput = FormData;\n\ntype Simplify<T> = { [TKey in keyof T]: T[TKey] } & {};\ntype AssignContext<TCurrent extends object, TNext extends object> = Simplify<\n  Omit<TCurrent, keyof TNext> & TNext\n>;\ntype MiddlewareContext<TMiddleware> =\n  TMiddleware extends ServerFnMiddleware<infer TContext> ? TContext : {};\n\nexport type ServerFnMiddlewareContext<\n  TMiddlewares extends readonly AnyServerFnMiddleware[],\n  TContext extends object = {},\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n  ? TMiddleware extends AnyServerFnMiddleware\n    ? TRest extends readonly AnyServerFnMiddleware[]\n      ? ServerFnMiddlewareContext<TRest, AssignContext<TContext, MiddlewareContext<TMiddleware>>>\n      : TContext\n    : TContext\n  : number extends TMiddlewares[\"length\"]\n    ? Simplify<TContext & MiddlewareContext<TMiddlewares[number]>>\n    : Simplify<TContext>;\n\ndeclare const SERVER_FN_MIDDLEWARE_CONTEXT: unique symbol;\n\nexport type ServerFnMiddlewareContinuation<TContext extends object = {}> = {\n  readonly [SERVER_FN_MIDDLEWARE_CONTEXT]: TContext;\n};\n\nexport type ServerFnMiddlewareNext = <TContext extends object = {}>(options?: {\n  context?: TContext;\n}) => Promise<ServerFnMiddlewareContinuation<TContext>>;\n\nexport type ServerFnContext<TInput, TContext extends object = {}> = {\n  input: TInput;\n  rawInput: unknown;\n  formData?: FormData;\n  /** The action request when invoked across the network. Undefined for direct server calls. */\n  request?: Request;\n  /** Aborts when the underlying action request is cancelled. */\n  signal: AbortSignal;\n  /** Context produced by this server function's middleware chain. */\n  context: Readonly<TContext>;\n};\n\nexport type ServerFnHandlerContext<\n  TInput,\n  TContext extends object = {},\n  TErrors extends ServerFnErrorDefinitions = {},\n> = ServerFnContext<TInput, TContext> & {\n  /** Return a declared, validated error from this server function. */\n  error: ServerFnErrorHandler<TErrors>;\n};\n\nexport type ServerFnHandler<\n  TInput,\n  TResult,\n  TContext extends object = {},\n  TErrors extends ServerFnErrorDefinitions = {},\n> = (ctx: ServerFnHandlerContext<TInput, TContext, TErrors>) => MaybePromise<TResult>;\n\nexport type ServerFnInvalidationContext<\n  TInput,\n  TResult,\n  TContext extends object = {},\n> = ServerFnContext<TInput, TContext> & {\n  /** Parsed value returned by the successful server function. */\n  result: TResult;\n};\n\nexport type ServerFnInvalidations<TInput, TResult, TContext extends object = {}> =\n  | readonly FarmCacheInvalidationTarget[]\n  | ((\n      context: ServerFnInvalidationContext<TInput, TResult, TContext>,\n    ) => readonly FarmCacheInvalidationTarget[] | Promise<readonly FarmCacheInvalidationTarget[]>);\n\nexport type ServerFnMiddlewareHandlerContext<TContext extends object = {}> = ServerFnContext<\n  unknown,\n  TContext\n> & {\n  next: ServerFnMiddlewareNext;\n};\n\nexport type ServerFnMiddlewareHandler<\n  TContext extends object = {},\n  TProvidedContext extends object = {},\n> = (\n  ctx: ServerFnMiddlewareHandlerContext<TContext>,\n) => MaybePromise<ServerFnMiddlewareContinuation<TProvidedContext>>;\n\nexport type ServerFnMiddleware<TContext extends object = {}> = {\n  readonly __farmServerFnMiddleware: true;\n  readonly __farmServerFnMiddlewareContext?: TContext;\n  readonly middleware: readonly AnyServerFnMiddleware[];\n  readonly handler: ServerFnMiddlewareHandler<any, any>;\n};\n\nexport type AnyServerFnMiddleware = ServerFnMiddleware<any>;\n\nexport type ServerFnMiddlewareOptions<\n  TMiddlewares extends readonly AnyServerFnMiddleware[],\n  TProvidedContext extends object,\n> = {\n  middleware?: TMiddlewares;\n  handler: ServerFnMiddlewareHandler<ServerFnMiddlewareContext<TMiddlewares>, TProvidedContext>;\n};\n\nexport type ServerFnOptions<\n  TSchema extends ServerFnSchema | undefined,\n  TResult,\n  TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n  TErrors extends ServerFnErrorDefinitions = {},\n> = {\n  input?: TSchema;\n  output?: undefined;\n  middleware?: TMiddlewares;\n  errors?: TErrors;\n  invalidates?: ServerFnInvalidations<\n    TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n    Awaited<TResult>,\n    ServerFnMiddlewareContext<TMiddlewares>\n  >;\n  handler: ServerFnHandler<\n    TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n    TResult,\n    ServerFnMiddlewareContext<TMiddlewares>,\n    TErrors\n  >;\n};\n\nexport type ServerFnOutputOptions<\n  TInputSchema extends ServerFnSchema | undefined,\n  TOutputSchema extends ServerFnSchema,\n  TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n  TErrors extends ServerFnErrorDefinitions = {},\n> = {\n  input?: TInputSchema;\n  output: TOutputSchema;\n  middleware?: TMiddlewares;\n  errors?: TErrors;\n  invalidates?: ServerFnInvalidations<\n    TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n    Awaited<InferServerFnSchemaOutput<TOutputSchema>>,\n    ServerFnMiddlewareContext<TMiddlewares>\n  >;\n  handler: ServerFnHandler<\n    TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n    unknown,\n    ServerFnMiddlewareContext<TMiddlewares>,\n    TErrors\n  >;\n};\n\nexport type ServerFn<TInput, TResult, TError extends Error = Error> = ([unknown] extends [TInput]\n  ? (input?: TInput | FormData) => Promise<TResult>\n  : (input: TInput | FormData) => Promise<TResult>) & {\n  readonly __farmServerFn: true;\n  readonly __farmServerFnInput?: unknown;\n  readonly __farmServerFnOutput?: unknown;\n  readonly __farmServerFnError: TError;\n};\n\nexport type InferServerFnError<TServerFn> =\n  TServerFn extends ServerFn<any, any, infer TError> ? TError : Error;\n\nexport const FARM_SERVER_FN_SYMBOL = Symbol.for(\"farm.server-fn\");\n\nconst UNSAFE_FORM_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function createServerMiddleware<\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n  TProvidedContext extends object = {},\n>(\n  options: ServerFnMiddlewareOptions<TMiddlewares, TProvidedContext>,\n): ServerFnMiddleware<AssignContext<ServerFnMiddlewareContext<TMiddlewares>, TProvidedContext>>;\nexport function createServerMiddleware(options: {\n  middleware?: readonly AnyServerFnMiddleware[];\n  handler: ServerFnMiddlewareHandler<any, any>;\n}): ServerFnMiddleware<any> {\n  if (!options || typeof options.handler !== \"function\") {\n    throw new TypeError(\"createServerMiddleware requires a handler function\");\n  }\n\n  const middleware = Object.freeze([...(options.middleware ?? [])]);\n  for (const entry of middleware) {\n    assertServerFnMiddleware(entry);\n  }\n\n  return Object.freeze({\n    __farmServerFnMiddleware: true as const,\n    middleware,\n    handler: options.handler,\n  });\n}\n\nexport function createServerFn<\n  TInputSchema extends ServerFnSchema,\n  TOutputSchema extends ServerFnSchema,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n  const TErrors extends ServerFnErrorDefinitions = {},\n>(\n  options: ServerFnOutputOptions<TInputSchema, TOutputSchema, TMiddlewares, TErrors>,\n): ServerFn<\n  InferServerFnSchemaInput<TInputSchema>,\n  Awaited<InferServerFnSchemaOutput<TOutputSchema>>,\n  ServerFnError<TErrors>\n>;\nexport function createServerFn<\n  TOutputSchema extends ServerFnSchema,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n  const TErrors extends ServerFnErrorDefinitions = {},\n>(\n  options: ServerFnOutputOptions<undefined, TOutputSchema, TMiddlewares, TErrors>,\n): ServerFn<unknown, Awaited<InferServerFnSchemaOutput<TOutputSchema>>, ServerFnError<TErrors>>;\nexport function createServerFn<\n  TSchema extends ServerFnSchema,\n  TResult,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n  const TErrors extends ServerFnErrorDefinitions = {},\n>(\n  options: ServerFnOptions<TSchema, TResult, TMiddlewares, TErrors>,\n): ServerFn<InferServerFnSchemaInput<TSchema>, Awaited<TResult>, ServerFnError<TErrors>>;\nexport function createServerFn<\n  TResult,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n  const TErrors extends ServerFnErrorDefinitions = {},\n>(\n  options: ServerFnOptions<undefined, TResult, TMiddlewares, TErrors>,\n): ServerFn<unknown, Awaited<TResult>, ServerFnError<TErrors>>;\nexport function createServerFn(options: {\n  input?: ServerFnSchema;\n  output?: ServerFnSchema;\n  middleware?: readonly AnyServerFnMiddleware[];\n  errors?: ServerFnErrorDefinitions;\n  invalidates?: ServerFnInvalidations<any, any, any>;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  handler: ServerFnHandler<any, any, any, any>;\n}) {\n  if (!options || typeof options.handler !== \"function\") {\n    throw new TypeError(\"createServerFn requires a handler function\");\n  }\n\n  const middleware = resolveServerFnMiddleware(options.middleware);\n  const errors = normalizeServerFnErrors(options.errors);\n  const error = createServerFnErrorHandler(errors);\n  const serverFn = async (value: unknown) => {\n    const formData = isFormData(value) ? value : undefined;\n    const rawInput = formData ? formDataToObject(formData) : value;\n    const input = await _parseServerFnSchema(options.input, rawInput, \"input\");\n    const executionContext = getServerActionExecutionContext();\n    const request = executionContext?.request ?? _resolveCurrentRequest();\n    const signal = executionContext?.signal ?? request?.signal ?? getServerActionSignal();\n    const handlerContext = {\n      input,\n      rawInput,\n      formData,\n      request,\n      signal,\n    };\n    let resolvedContext: Readonly<object> = Object.freeze(Object.create(null));\n    const result = await runServerFnMiddleware(middleware, handlerContext, async (context) => {\n      resolvedContext = context.context;\n      return options.handler({ ...context, error });\n    });\n    const parsedResult = await _parseServerFnSchema(options.output, result, \"output\");\n\n    if (options.invalidates) {\n      const declaration =\n        typeof options.invalidates === \"function\"\n          ? await options.invalidates({\n              ...handlerContext,\n              context: resolvedContext,\n              result: parsedResult,\n            })\n          : options.invalidates;\n      await applyFarmCacheInvalidationTargets(declaration);\n    }\n\n    return parsedResult;\n  };\n\n  Object.defineProperties(serverFn, {\n    [FARM_SERVER_FN_SYMBOL]: {\n      value: true,\n      enumerable: false,\n    },\n    __farmServerFn: {\n      value: true,\n      enumerable: false,\n    },\n    __farmServerFnInput: {\n      value: options.input,\n      enumerable: false,\n    },\n    __farmServerFnOutput: {\n      value: options.output,\n      enumerable: false,\n    },\n    __farmServerFnError: {\n      value: undefined,\n      enumerable: false,\n    },\n    __farmServerFnMiddleware: {\n      value: middleware,\n      enumerable: false,\n    },\n    __farmServerFnInvalidates: {\n      value: options.invalidates,\n      enumerable: false,\n    },\n  });\n\n  return serverFn as ServerFn<unknown, unknown, Error>;\n}\n\ntype ServerFnBaseContext = Omit<ServerFnContext<unknown, {}>, \"context\">;\n\nasync function runServerFnMiddleware(\n  middleware: readonly AnyServerFnMiddleware[],\n  handlerContext: ServerFnBaseContext,\n  handler: (context: ServerFnContext<any, any>) => MaybePromise<unknown>,\n) {\n  const dispatch = async (index: number, context: Readonly<object>): Promise<unknown> => {\n    const current = middleware[index];\n    if (!current) {\n      return handler({ ...handlerContext, context });\n    }\n\n    let nextCalled = false;\n    const result = await current.handler({\n      ...handlerContext,\n      context,\n      next: async (nextOptions) => {\n        if (nextCalled) {\n          throw new Error(\"Server function middleware next() can only be called once\");\n        }\n        nextCalled = true;\n\n        return dispatch(index + 1, mergeServerFnContext(context, nextOptions?.context)) as Promise<\n          ServerFnMiddlewareContinuation<any>\n        >;\n      },\n    });\n\n    if (!nextCalled) {\n      throw new Error(\"Server function middleware must call next()\");\n    }\n\n    return result;\n  };\n\n  return dispatch(0, Object.freeze(Object.create(null)));\n}\n\nfunction normalizeServerFnErrors(\n  definitions: ServerFnErrorDefinitions | undefined,\n): Readonly<ServerFnErrorDefinitions> {\n  if (definitions === undefined) return Object.freeze({});\n  if (!isPlainServerFnObject(definitions)) {\n    throw new TypeError(\"createServerFn errors must be an object\");\n  }\n\n  const normalized: ServerFnErrorDefinitions = Object.create(null);\n  for (const [code, definition] of Object.entries(definitions)) {\n    if (!code.trim()) {\n      throw new TypeError(\"Server function error codes cannot be empty\");\n    }\n    if (!definition || typeof definition !== \"object\") {\n      throw new TypeError(`Server function error \"${code}\" must be an object`);\n    }\n    if (\n      !Number.isInteger(definition.status) ||\n      definition.status < 400 ||\n      definition.status > 599\n    ) {\n      throw new TypeError(\n        `Server function error \"${code}\" status must be an integer between 400 and 599`,\n      );\n    }\n    if (\n      !definition.data ||\n      (typeof definition.data.parse !== \"function\" &&\n        typeof definition.data.safeParse !== \"function\")\n    ) {\n      throw new TypeError(\n        `Server function error \"${code}\" data must provide synchronous parse() or safeParse()`,\n      );\n    }\n    if (definition.message !== undefined && typeof definition.message !== \"string\") {\n      throw new TypeError(`Server function error \"${code}\" message must be a string`);\n    }\n\n    normalized[code] = Object.freeze({ ...definition });\n  }\n\n  return Object.freeze(normalized);\n}\n\nfunction createServerFnErrorHandler(\n  definitions: Readonly<ServerFnErrorDefinitions>,\n): ServerFnErrorHandler<ServerFnErrorDefinitions> {\n  return ((code: string, data: unknown): never => {\n    const definition = definitions[code];\n    if (!definition) {\n      throw new TypeError(`Server function error \"${code}\" is not declared`);\n    }\n\n    const parsed = parseServerFnFailureData(code, definition.data, data);\n    throw new ServerFnFailure(code, parsed, {\n      status: definition.status,\n      message: definition.message ?? \"Server function failed\",\n    });\n  }) as ServerFnErrorHandler<ServerFnErrorDefinitions>;\n}\n\nfunction parseServerFnFailureData(code: string, schema: ServerFnSchema, value: unknown) {\n  if (typeof schema.safeParse === \"function\") {\n    const result = schema.safeParse(value);\n    if (isPromiseLike(result)) {\n      throw new TypeError(`Server function error \"${code}\" data schema must parse synchronously`);\n    }\n    return unwrapSafeParseResult(result);\n  }\n\n  const result = schema.parse!(value);\n  if (isPromiseLike(result)) {\n    throw new TypeError(`Server function error \"${code}\" data schema must parse synchronously`);\n  }\n  return result;\n}\n\nfunction isPlainServerFnObject(value: unknown): value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n  return Boolean(\n    value &&\n    (typeof value === \"object\" || typeof value === \"function\") &&\n    \"then\" in value &&\n    typeof (value as PromiseLike<unknown>).then === \"function\",\n  );\n}\n\nfunction resolveServerFnMiddleware(\n  middleware: readonly AnyServerFnMiddleware[] | undefined,\n): readonly AnyServerFnMiddleware[] {\n  const resolved: AnyServerFnMiddleware[] = [];\n  const seen = new Set<AnyServerFnMiddleware>();\n  const visiting = new Set<AnyServerFnMiddleware>();\n\n  const visit = (entry: AnyServerFnMiddleware) => {\n    assertServerFnMiddleware(entry);\n    if (seen.has(entry)) return;\n    if (visiting.has(entry)) {\n      throw new Error(\"Server function middleware dependencies cannot contain a cycle\");\n    }\n\n    visiting.add(entry);\n    for (const dependency of entry.middleware) {\n      visit(dependency);\n    }\n    visiting.delete(entry);\n    seen.add(entry);\n    resolved.push(entry);\n  };\n\n  for (const entry of middleware ?? []) {\n    visit(entry);\n  }\n\n  return Object.freeze(resolved);\n}\n\nfunction assertServerFnMiddleware(value: unknown): asserts value is AnyServerFnMiddleware {\n  if (\n    !value ||\n    typeof value !== \"object\" ||\n    (value as { __farmServerFnMiddleware?: unknown }).__farmServerFnMiddleware !== true ||\n    typeof (value as { handler?: unknown }).handler !== \"function\" ||\n    !Array.isArray((value as { middleware?: unknown }).middleware)\n  ) {\n    throw new TypeError(\"createServerFn middleware must be created with createServerMiddleware\");\n  }\n}\n\nfunction mergeServerFnContext(current: Readonly<object>, added: object | undefined) {\n  if (\n    added !== undefined &&\n    (added === null || typeof added !== \"object\" || Array.isArray(added))\n  ) {\n    throw new TypeError(\"Server function middleware context must be an object\");\n  }\n\n  return Object.freeze(Object.assign(Object.create(null), current, added));\n}\n\nexport async function _parseServerFnSchema(\n  schema: ServerFnSchema | undefined,\n  value: unknown,\n  contract: \"input\" | \"output\",\n  owner = \"createServerFn\",\n) {\n  if (!schema) return value;\n\n  if (typeof schema.safeParseAsync === \"function\") {\n    const result = await schema.safeParseAsync(value);\n    return unwrapSafeParseResult(result);\n  }\n\n  if (typeof schema.safeParse === \"function\") {\n    const result = schema.safeParse(value);\n    return unwrapSafeParseResult(await result);\n  }\n\n  if (typeof schema.parseAsync === \"function\") {\n    return schema.parseAsync(value);\n  }\n\n  if (typeof schema.parse === \"function\") {\n    return schema.parse(value);\n  }\n\n  throw new TypeError(`${owner} ${contract} must provide parse, parseAsync, or safeParse`);\n}\n\nfunction unwrapSafeParseResult(result: unknown) {\n  if (\n    result &&\n    typeof result === \"object\" &&\n    \"success\" in result &&\n    (result as { success: boolean }).success === false\n  ) {\n    throw (result as { error?: unknown }).error;\n  }\n\n  if (\n    result &&\n    typeof result === \"object\" &&\n    \"success\" in result &&\n    (result as { success: boolean }).success === true\n  ) {\n    return (result as unknown as { data: unknown }).data;\n  }\n\n  return result;\n}\n\nfunction formDataToObject(formData: FormData) {\n  const output: Record<string, FormDataEntryValue | FormDataEntryValue[]> = Object.create(null);\n\n  for (const [key, value] of formData.entries()) {\n    if (!isSafeFormKey(key)) continue;\n\n    const existing = output[key];\n    if (existing === undefined) {\n      output[key] = value;\n    } else if (Array.isArray(existing)) {\n      existing.push(value);\n    } else {\n      output[key] = [existing, value];\n    }\n  }\n\n  return output;\n}\n\nfunction isSafeFormKey(key: string) {\n  return !key.startsWith(\"$ACTION_\") && !UNSAFE_FORM_KEYS.has(key);\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 {\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","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","import {\n  createFarmCacheKey,\n  createRouteDataCacheKey,\n  createRouteDataCacheTag,\n  getFarmDataCache,\n  type RouteDataCacheKey,\n} from \"./cache\";\nimport { getServerActionExecutionContext } from \"./server-action-security\";\nimport {\n  createServerFn,\n  type AnyServerFnMiddleware,\n  type InferServerFnSchemaInput,\n  type InferServerFnSchemaOutput,\n  type ServerFn,\n  type ServerFnContext,\n  type ServerFnHandler,\n  type ServerFnHandlerContext,\n  type ServerFnMiddlewareContext,\n  type ServerFnSchema,\n  _parseServerFnSchema,\n} from \"./server-fn\";\nimport { createFarmServerQueryResult, type FarmServerQueryResult } from \"./server-query-protocol\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type ServerQueryStaleTime = number | false | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport type ServerQueryKey<TInput, TContext extends object = {}> = (\n  context: ServerFnContext<TInput, TContext>,\n) => MaybePromise<RouteDataCacheKey>;\n\nexport type ServerQueryOptions<\n  TSchema extends ServerFnSchema | undefined,\n  TResult,\n  TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n> = {\n  input?: TSchema;\n  output?: undefined;\n  middleware?: TMiddlewares;\n  key: ServerQueryKey<\n    TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n    ServerFnMiddlewareContext<TMiddlewares>\n  >;\n  /** Milliseconds, a duration string such as \"30s\", or false for no expiry. */\n  staleTime?: ServerQueryStaleTime;\n  /** Allow the configured client cache persistence adapter to store results on the device. */\n  persist?: boolean;\n  handler: ServerFnHandler<\n    TSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TSchema> : unknown,\n    TResult,\n    ServerFnMiddlewareContext<TMiddlewares>\n  >;\n};\n\nexport type ServerQueryOutputOptions<\n  TInputSchema extends ServerFnSchema | undefined,\n  TOutputSchema extends ServerFnSchema,\n  TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n> = {\n  input?: TInputSchema;\n  output: TOutputSchema;\n  middleware?: TMiddlewares;\n  key: ServerQueryKey<\n    TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n    ServerFnMiddlewareContext<TMiddlewares>\n  >;\n  /** Milliseconds, a duration string such as \"30s\", or false for no expiry. */\n  staleTime?: ServerQueryStaleTime;\n  /** Allow the configured client cache persistence adapter to store results on the device. */\n  persist?: boolean;\n  handler: ServerFnHandler<\n    TInputSchema extends ServerFnSchema ? InferServerFnSchemaOutput<TInputSchema> : unknown,\n    unknown,\n    ServerFnMiddlewareContext<TMiddlewares>\n  >;\n};\n\nexport type ServerQuery<TInput, TResult> = ([unknown] extends [TInput]\n  ? (input?: TInput) => Promise<TResult>\n  : (input: TInput) => Promise<TResult>) & {\n  readonly __farmServerQuery: true;\n  readonly __farmServerQueryInput?: unknown;\n  readonly __farmServerQueryOutput?: unknown;\n};\n\nexport const FARM_SERVER_QUERY_SYMBOL = Symbol.for(\"farm.server-query\");\n\ntype AnyServerQueryOptions = {\n  input?: ServerFnSchema;\n  output?: ServerFnSchema;\n  middleware?: readonly AnyServerFnMiddleware[];\n  key: ServerQueryKey<any, any>;\n  staleTime?: ServerQueryStaleTime;\n  persist?: boolean;\n  handler: ServerFnHandler<any, any, any>;\n};\n\nconst requestInflight = new WeakMap<Request, Map<string, Promise<unknown>>>();\nconst detachedInflight = new Map<string, Promise<unknown>>();\n\nexport function createServerQuery<\n  TInputSchema extends ServerFnSchema,\n  TOutputSchema extends ServerFnSchema,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n  options: ServerQueryOutputOptions<TInputSchema, TOutputSchema, TMiddlewares>,\n): ServerQuery<\n  InferServerFnSchemaInput<TInputSchema>,\n  Awaited<InferServerFnSchemaOutput<TOutputSchema>>\n>;\nexport function createServerQuery<\n  TOutputSchema extends ServerFnSchema,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n  options: ServerQueryOutputOptions<undefined, TOutputSchema, TMiddlewares>,\n): ServerQuery<unknown, Awaited<InferServerFnSchemaOutput<TOutputSchema>>>;\nexport function createServerQuery<\n  TSchema extends ServerFnSchema,\n  TResult,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n  options: ServerQueryOptions<TSchema, TResult, TMiddlewares>,\n): ServerQuery<InferServerFnSchemaInput<TSchema>, Awaited<TResult>>;\nexport function createServerQuery<\n  TResult,\n  const TMiddlewares extends readonly AnyServerFnMiddleware[] = readonly [],\n>(\n  options: ServerQueryOptions<undefined, TResult, TMiddlewares>,\n): ServerQuery<unknown, Awaited<TResult>>;\nexport function createServerQuery(options: AnyServerQueryOptions): ServerQuery<unknown, unknown> {\n  if (!options || typeof options.handler !== \"function\") {\n    throw new TypeError(\"createServerQuery requires a handler function\");\n  }\n  if (typeof options.key !== \"function\") {\n    throw new TypeError(\"createServerQuery requires a key function\");\n  }\n\n  const staleTime = normalizeServerQueryStaleTime(options.staleTime);\n  const execute = (\n    createServerFn as (options: any) => ServerFn<unknown, FarmServerQueryResult<any>>\n  )({\n    input: options.input,\n    middleware: options.middleware,\n    handler: async (context: ServerFnHandlerContext<any, any>) => {\n      const routeKey = await options.key(context);\n      assertServerQueryKey(routeKey);\n\n      const clientKey = createRouteDataCacheKey(routeKey);\n      const cacheKey = createFarmCacheKey([\"route-data\", routeKey]);\n      const producer = async () => {\n        const value = await options.handler(context);\n        return _parseServerFnSchema(options.output, value, \"output\", \"createServerQuery\");\n      };\n\n      let data: unknown;\n      let updatedAt: number;\n\n      if (staleTime === 0) {\n        data = await dedupeServerQueryRequest(cacheKey, context.request, producer);\n        updatedAt = Date.now();\n      } else {\n        const cache = getFarmDataCache();\n        data = await cache.getOrSet(cacheKey, producer, {\n          tags: [createRouteDataCacheTag(routeKey)],\n          revalidate: staleTime === false ? false : staleTime / 1000,\n        });\n        updatedAt =\n          (await cache.getEntryAsync(cacheKey, { allowStale: true }))?.createdAt ?? Date.now();\n      }\n\n      return createFarmServerQueryResult(data, {\n        key: clientKey,\n        staleTime,\n        updatedAt,\n        ...(options.persist === true ? { persist: true } : {}),\n      });\n    },\n  });\n\n  const query = async (input?: unknown) => {\n    const result = await execute(input);\n    return getServerActionExecutionContext() ? result : result.data;\n  };\n\n  Object.defineProperties(query, {\n    [FARM_SERVER_QUERY_SYMBOL]: {\n      value: true,\n      enumerable: false,\n    },\n    __farmServerQuery: {\n      value: true,\n      enumerable: false,\n    },\n    __farmServerQueryInput: {\n      value: options.input,\n      enumerable: false,\n    },\n    __farmServerQueryOutput: {\n      value: options.output,\n      enumerable: false,\n    },\n  });\n\n  return query as ServerQuery<unknown, unknown>;\n}\n\nasync function dedupeServerQueryRequest<TData>(\n  key: string,\n  request: Request | undefined,\n  producer: () => Promise<TData>,\n): Promise<TData> {\n  let inflight: Map<string, Promise<unknown>>;\n  if (request) {\n    inflight = requestInflight.get(request) ?? new Map();\n    requestInflight.set(request, inflight);\n  } else {\n    inflight = detachedInflight;\n  }\n\n  const existing = inflight.get(key) as Promise<TData> | undefined;\n  if (existing) return existing;\n\n  const promise = Promise.resolve().then(producer);\n  inflight.set(key, promise);\n\n  try {\n    return await promise;\n  } finally {\n    inflight.delete(key);\n  }\n}\n\nfunction normalizeServerQueryStaleTime(value: ServerQueryStaleTime | undefined): number | false {\n  if (value === false) return false;\n  if (value === undefined) return 0;\n\n  if (typeof value === \"number\") {\n    if (!Number.isFinite(value) || value < 0) {\n      throw new TypeError(\"createServerQuery staleTime must be a non-negative duration\");\n    }\n    return value;\n  }\n\n  const match = value.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)$/);\n  if (!match) {\n    throw new TypeError('createServerQuery staleTime must look like \"250ms\", \"30s\", \"5m\", or \"1h\"');\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2];\n  const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1000 : unit === \"m\" ? 60_000 : 3_600_000;\n  return amount * multiplier;\n}\n\nfunction assertServerQueryKey(key: unknown): asserts key is RouteDataCacheKey {\n  if (typeof key === \"string\") {\n    if (key.trim().length > 0) return;\n  } else if (Array.isArray(key)) {\n    return;\n  }\n\n  throw new TypeError(\"createServerQuery key must return a non-empty string or an array\");\n}\n","export const FARM_SERVER_QUERY_RESULT_VERSION = 1 as const;\n\nexport type FarmServerQueryResult<TData> = {\n  __farmServerQuery: {\n    version: typeof FARM_SERVER_QUERY_RESULT_VERSION;\n    key: string;\n    staleTime: number | false;\n    updatedAt: number;\n    /** Declared by the query; allows the client persistence adapter to store the entry. */\n    persist?: boolean;\n  };\n  data: TData;\n};\n\nexport function createFarmServerQueryResult<TData>(\n  data: TData,\n  metadata: Omit<FarmServerQueryResult<TData>[\"__farmServerQuery\"], \"version\">,\n): FarmServerQueryResult<TData> {\n  return {\n    __farmServerQuery: {\n      version: FARM_SERVER_QUERY_RESULT_VERSION,\n      ...metadata,\n    },\n    data,\n  };\n}\n\nexport function isFarmServerQueryResult(value: unknown): value is FarmServerQueryResult<unknown> {\n  if (!value || typeof value !== \"object\") return false;\n\n  const metadata = (value as Partial<FarmServerQueryResult<unknown>>).__farmServerQuery;\n  return (\n    metadata?.version === FARM_SERVER_QUERY_RESULT_VERSION &&\n    typeof metadata.key === \"string\" &&\n    (metadata.staleTime === false || typeof metadata.staleTime === \"number\") &&\n    typeof metadata.updatedAt === \"number\" &&\n    \"data\" in value\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 type { ResolvedFarmConfig } from \"../config\";\nimport {\n  getDefaultDeployOutputDir,\n  getDeployTargetForPreset,\n  resolveDeployOutputPath,\n} from \"../config\";\nimport type { ViteDevServer } from \"vite\";\nimport path from \"path\";\nimport { existsSync } from \"node:fs\";\nimport { logger } from \"../utils\";\nimport { createFarmApp } from \"../app\";\nimport { APIRouteManager } from \"../api/route-manager\";\nimport { resolveFarmAPIServerBasePath } from \"../api/server-path\";\nimport { getFarmAppDirectories } from \"../layers\";\nimport { buildUniversal } from \"../nitro/universal-build\";\nimport { getFarmDocsRouteTypeEntries } from \"../docs\";\nimport { generateFarmTypeArtifacts } from \"../type-artifacts\";\nimport { PluginManager } from \"../plugin\";\nimport { farmEnvironmentFunctionsPlugin } from \"../environment-vite\";\nimport { farmFontImportsPlugin } from \"../font-vite\";\nimport { createFarmSourceAlias, mergeFarmViteConfig } from \"../server/vite-config\";\nimport { getFarmRendererComponentExtensions, loadFarmRendererVitePlugins } from \"../renderer\";\nimport {\n  canUseRolldownForRouteDiscovery,\n  loadFarmProductionVite,\n  type FarmProductionViteRuntime,\n} from \"./production-vite\";\nimport { withProductionNodeEnv } from \"./production-node-env\";\n\ninterface BuildOptions {\n  preset?: string;\n  root?: string;\n  universal?: boolean; // Use universal build pattern (TanStack Start style)\n  /** @internal Production Vite preload started by the CLI. */\n  productionVite?: FarmProductionViteRuntime | Promise<FarmProductionViteRuntime>;\n}\n\ninterface BuildTargetBaseline {\n  preset: string;\n  distDir: string;\n  outputDir: string;\n  outputWasDerived: boolean;\n}\n\n/**\n * Build Farm.js application for production\n */\nexport async function build(config: ResolvedFarmConfig, options: BuildOptions = {}) {\n  return withProductionNodeEnv(() => buildWithProductionNodeEnv(config, options));\n}\n\n/** Every build path derived from config, recomputed once plugins have transformed it. */\nfunction createBuildTargetBaseline(config: ResolvedFarmConfig): BuildTargetBaseline {\n  const preset = config.preset || \"node-server\";\n  const distDir = config.distDir || \".farm\";\n  const outputDir = config.deploy.outputDir;\n  return {\n    preset,\n    distDir,\n    outputDir,\n    outputWasDerived:\n      outputDir === getDefaultDeployOutputDir(config.deploy.target, preset, distDir),\n  };\n}\n\nfunction resolveBuildTargets(\n  config: ResolvedFarmConfig,\n  options: BuildOptions,\n  baseline: BuildTargetBaseline,\n) {\n  const root = options.root || config.root || process.cwd();\n  const preset = options.preset || config.preset || \"node-server\";\n  const distDir = config.distDir || \".farm\";\n  const outputWasReplaced = config.deploy.outputDir !== baseline.outputDir;\n  const shouldRefreshDerivedOutput =\n    baseline.outputWasDerived &&\n    !outputWasReplaced &&\n    (preset !== baseline.preset || distDir !== baseline.distDir);\n  const deployTarget =\n    preset === config.deploy.preset ? config.deploy.target : getDeployTargetForPreset(preset);\n  const outputDir = shouldRefreshDerivedOutput\n    ? getDefaultDeployOutputDir(deployTarget, preset, distDir)\n    : config.deploy.outputDir;\n\n  return {\n    root,\n    preset,\n    srcDir: config.srcDir || \"src\",\n    distDir,\n    deployTarget,\n    outputDir,\n    deployOutputDir: resolveDeployOutputPath(root, outputDir),\n  };\n}\n\nasync function buildWithProductionNodeEnv(inputConfig: ResolvedFarmConfig, options: BuildOptions) {\n  let config = inputConfig;\n  const targetBaseline = createBuildTargetBaseline(config);\n  let targets: ReturnType<typeof resolveBuildTargets> | undefined;\n  const productionViteResultPromise =\n    options.universal === false\n      ? undefined\n      : Promise.allSettled([Promise.resolve(options.productionVite ?? loadFarmProductionVite())]);\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n  let projectModuleServer: ViteDevServer | undefined;\n\n  try {\n    await pluginManager.runHookParallel(\"init\");\n\n    // Settle plugin config before deriving the paths and deployment plan used\n    // by the production pipeline. Otherwise the build can report the returned\n    // config while still writing to the original locations.\n    config = await pluginManager.runHookSerial(\"config\", config);\n    if (options.universal === false && config.plugins.some((plugin) => plugin.routes)) {\n      throw new Error(\n        \"Plugin API routes require the default universal production build. Remove universal: false.\",\n      );\n    }\n    targets = resolveBuildTargets(config, options, targetBaseline);\n    config = {\n      ...config,\n      preset: targets.preset,\n      deploy: {\n        ...config.deploy,\n        target: targets.deployTarget,\n        preset: targets.preset,\n        outputDir: targets.outputDir,\n      },\n    };\n    pluginManager.updateContext({ config });\n    const { root, preset, srcDir, distDir, deployOutputDir } = targets;\n\n    logger.info(`🚜 Building Farm.js application with preset: ${preset}...`);\n\n    await pluginManager.setupPlugins();\n    await pluginManager.runHookParallel(\"beforeBundle\", {\n      root,\n      preset,\n      universal: options.universal !== false,\n      distDir,\n      outputDir: deployOutputDir,\n    });\n\n    // Step 1: Initialize Farm app to get route managers\n    logger.info(\"🔍 Discovering routes and API endpoints...\");\n    const productionViteResult = productionViteResultPromise\n      ? (await productionViteResultPromise)[0]\n      : undefined;\n    if (productionViteResult?.status === \"rejected\") throw productionViteResult.reason;\n    const productionVite = productionViteResult?.value;\n    const useProductionViteForDiscovery =\n      productionVite && canUseRolldownForRouteDiscovery(config.vite);\n    if (productionVite?.builder === \"rolldown\" && !useProductionViteForDiscovery) {\n      logger.info(\"🔌 Using Vite Rollup for route discovery with custom Vite configuration\");\n    }\n    const createViteServer = useProductionViteForDiscovery\n      ? productionVite.createServer\n      : (await import(\"vite\")).createServer;\n    projectModuleServer = await createProjectModuleServer(createViteServer, config, root);\n    const farmApp = createFarmApp(config, projectModuleServer);\n    await farmApp.initialize();\n\n    const routeManager = farmApp.getRouteManager();\n    const serverRenderer = farmApp.getServerRenderer();\n\n    const typeArtifacts = generateFarmTypeArtifacts({\n      root,\n      srcDir,\n      layers: config.layers,\n      plugins: config.plugins,\n      extraRoutes: [\n        ...(config.openapi?.enabled && config.openapi.route ? [config.openapi.route] : []),\n        ...getFarmDocsRouteTypeEntries(config.docs),\n      ],\n      suppressLintOnLink: config.suppressLintOnLink,\n      componentExtensions: config.renderer.componentExtensions,\n      i18nConfig: config.i18n,\n    }).catch((error: unknown) => {\n      // Non-fatal; type generation is for DX only. But say so: a silently\n      // skipped run leaves src/farm.d.ts describing routes that no longer\n      // exist, which reads as the framework having gone stale.\n      const message = error instanceof Error ? error.message : String(error);\n      logger.warn(`Route type generation failed (farm.d.ts may be stale): ${message}`);\n    });\n\n    // Type artifacts and API discovery scan independent inputs, so keep them\n    // off the critical path by running both after app initialization.\n    const apiRouteManager = new APIRouteManager(\n      getFarmAppDirectories(config),\n      projectModuleServer,\n      {\n        throwOnLoadError: true,\n        plugins: config.plugins,\n        i18n: farmApp.getI18nRuntime(),\n        bodySizeLimit: config.server.bodySizeLimit,\n        basePath: resolveFarmAPIServerBasePath(config.api),\n      },\n    );\n    const [, apiDiscovery] = await Promise.allSettled([\n      typeArtifacts,\n      apiRouteManager.discoverRoutes(),\n    ]);\n    if (apiDiscovery.status === \"rejected\") throw apiDiscovery.reason;\n\n    // Use universal build pattern if enabled\n    if (options.universal !== false) {\n      // Default to universal build (new pattern)\n      await buildUniversal(config, routeManager, apiRouteManager, serverRenderer, {\n        preset,\n        root,\n        pluginManager,\n        productionVite,\n      });\n    } else {\n      const { build: legacyViteBuild } = await import(\"vite\");\n      // Legacy build pattern (for backward compatibility)\n      // Step 1: Build client bundle with Vite\n      logger.info(\"📦 Building client bundle...\");\n      await buildClient(legacyViteBuild, config, root, srcDir, path.join(root, distDir, \"client\"));\n\n      // Step 2: Build SSR bundle with Vite\n      logger.info(\"📦 Building SSR bundle...\");\n      await buildSSR(legacyViteBuild, config, root, srcDir, path.join(root, distDir, \"server\"));\n\n      // Step 3: Build with Nitro\n      logger.info(`🚀 Building server with Nitro (preset: ${preset})...`);\n      await buildNitro(\n        config,\n        routeManager,\n        apiRouteManager,\n        serverRenderer,\n        preset,\n        root,\n        distDir,\n        pluginManager,\n      );\n    }\n\n    await pluginManager.runHookParallel(\"buildEnd\");\n    await pluginManager.runHookParallel(\"afterBundle\", {\n      root,\n      preset,\n      universal: options.universal !== false,\n      distDir,\n      outputDir: deployOutputDir,\n      success: true,\n    });\n\n    // The one completion summary for the whole pipeline: inner stages and the\n    // CLI stay quiet so success is reported exactly once, and the line that\n    // names the output directory also names the preset that chose it.\n    logger.success(`✅ Build completed successfully! (preset: ${preset})`);\n    logger.info(`📁 Output directory: ${deployOutputDir}`);\n  } catch (error) {\n    const { root, preset, distDir, deployOutputDir } =\n      targets ?? resolveBuildTargets(config, options, targetBaseline);\n    await pluginManager.runHookParallel(\"onError\", {\n      phase: \"build\",\n      error,\n      meta: {\n        root,\n        preset,\n      },\n    });\n    await pluginManager.runHookParallel(\"afterBundle\", {\n      root,\n      preset,\n      universal: options.universal !== false,\n      distDir,\n      outputDir: deployOutputDir,\n      success: false,\n    });\n    logger.error(`❌ Build failed: ${error}`);\n    throw error;\n  } finally {\n    await projectModuleServer?.close();\n  }\n}\n\nasync function createProjectModuleServer(\n  createViteServer: FarmProductionViteRuntime[\"createServer\"],\n  config: ResolvedFarmConfig,\n  root: string,\n): Promise<ViteDevServer> {\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, root, {\n    ssr: true,\n  });\n  const viteConfig = mergeFarmViteConfig(\n    {\n      root,\n      appType: \"custom\",\n      mode: \"production\",\n      css: {\n        postcss: {\n          plugins: [],\n        },\n      },\n      plugins: [\n        ...(rendererVitePlugins as any[]),\n        farmFontImportsPlugin({\n          root,\n          basePath: config.basePath,\n          publicDir: config.publicDir,\n        }),\n        farmEnvironmentFunctionsPlugin(),\n      ],\n      server: {\n        middlewareMode: true,\n        hmr: false,\n      },\n      resolve: {\n        alias: createFarmSourceAlias(root, config.srcDir),\n        dedupe: [...(config.renderer.dedupe || [])],\n      },\n      optimizeDeps: {\n        noDiscovery: true,\n      },\n      logLevel: \"silent\",\n    },\n    config.vite,\n  );\n\n  return createViteServer({\n    ...viteConfig,\n    root,\n    configFile: false,\n    appType: \"custom\",\n    mode: \"production\",\n    esbuild: {\n      ...(typeof viteConfig.esbuild === \"object\" ? viteConfig.esbuild : {}),\n      jsxDev: false,\n    },\n    server: {\n      ...viteConfig.server,\n      middlewareMode: true,\n      hmr: false,\n      // This server only loads modules for a single build. HMR alone does not\n      // disable filesystem watching, which can race with generated output.\n      watch: null,\n    },\n    optimizeDeps: {\n      ...viteConfig.optimizeDeps,\n      noDiscovery: true,\n    },\n  });\n}\n\n/**\n * Build client bundle\n */\nasync function buildClient(\n  viteBuild: (typeof import(\"vite\"))[\"build\"],\n  config: ResolvedFarmConfig,\n  root: string,\n  srcDir: string,\n  outputDir: string,\n) {\n  const { farmI18nClientBridgePlugin, farmPlugin } = await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n\n  await viteBuild({\n    root,\n    build: {\n      outDir: outputDir,\n      emptyOutDir: true,\n      rollupOptions: {\n        input: resolveLegacyPageEntry(config, root, srcDir),\n      },\n    },\n    plugins: [\n      farmI18nClientBridgePlugin(),\n      farmPlugin(config, pluginManager),\n      farmEnvironmentFunctionsPlugin(),\n    ],\n    mode: \"production\",\n  });\n}\n\n/**\n * Build SSR bundle\n */\nasync function buildSSR(\n  viteBuild: (typeof import(\"vite\"))[\"build\"],\n  config: ResolvedFarmConfig,\n  root: string,\n  srcDir: string,\n  outputDir: string,\n) {\n  const { farmI18nClientBridgePlugin, farmPlugin } = await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n\n  const ssrEntry = resolveLegacyPageEntry(config, root, srcDir);\n\n  await viteBuild({\n    root,\n    build: {\n      ssr: true,\n      outDir: outputDir,\n      emptyOutDir: true,\n      rollupOptions: {\n        input: ssrEntry,\n      },\n    },\n    define: {\n      __FARM_API_BASE_URL__: JSON.stringify(config.api.baseURL),\n      __FARM_ENV__: JSON.stringify(config.env || { server: {}, public: {} }),\n      __FARM_PUBLIC_ENV__: JSON.stringify(config.env?.public || {}),\n    },\n    plugins: [\n      farmI18nClientBridgePlugin(),\n      farmPlugin(config, pluginManager),\n      farmEnvironmentFunctionsPlugin(),\n    ],\n    mode: \"production\",\n  });\n}\n\nfunction resolveLegacyPageEntry(config: ResolvedFarmConfig, root: string, srcDir: string): string {\n  const appDir = path.join(root, srcDir, \"app\");\n  for (const extension of getFarmRendererComponentExtensions(config.renderer)) {\n    const candidate = path.join(appDir, `page${extension}`);\n    if (existsSync(candidate)) return candidate;\n  }\n  return path.join(appDir, \"page.tsx\");\n}\n\n/**\n * Build with Nitro\n */\nasync function buildNitro(\n  config: ResolvedFarmConfig,\n  routeManager: any,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: any,\n  preset: string,\n  root: string,\n  distDir: string,\n  pluginManager?: PluginManager,\n) {\n  const [{ createNitroConfig }, { createNitro, build: nitroBuild }] = await Promise.all([\n    import(\"../nitro\"),\n    import(\"nitro\"),\n  ]);\n  let nitroConfig = await createNitroConfig(\n    config,\n    routeManager,\n    apiRouteManager,\n    serverRenderer,\n    preset,\n  );\n\n  if (pluginManager) {\n    nitroConfig = await pluginManager.runHookSerial(\"beforeNitroBuild\", nitroConfig);\n  }\n\n  // Directory structure:\n  // .farm/\n  //   ├── client/          - Client-side build output (Vite)\n  //   ├── server/          - SSR build output (Vite)\n  //   ├── .nitro/          - Nitro's build directory (temporary, where it does its work)\n  //   │   └── server/      - Handlers and source files for Nitro\n  //   └── .output/         - Final deployable output (this is what gets deployed)\n  //       ├── server/      - Serverless function bundles\n  //       ├── public/      - Static assets\n  //       └── config.json  - Vercel routing config\n  //\n  // IMPORTANT: Nitro is configured to output to .farm/.output (NOT .nitro/.output)\n  // This is ensured by explicitly setting output.dir in the Nitro config\n  //\n  // Build flow:\n  // 1. Vite builds client → .farm/client\n  // 2. Vite builds SSR → .farm/server\n  // 3. Copy client assets → .farm/.output/public\n  // 4. Copy SSR bundles → .farm/.nitro/server/farm\n  // 5. Nitro builds from .farm/.nitro → outputs to .farm/.output (via output.dir config)\n  // 6. Deploy from .farm/.output\n\n  // Ensure output directory exists before building\n  const outputDir = resolveDeployOutputPath(root, config.deploy.outputDir);\n  const serverOutputDir = path.join(outputDir, \"server\");\n  const publicOutputDir = path.join(outputDir, \"public\");\n  const { mkdir, cp } = await import(\"fs/promises\");\n  await mkdir(serverOutputDir, { recursive: true });\n  await mkdir(publicOutputDir, { recursive: true });\n\n  // Copy client assets to public directory for Nitro to serve\n  // This ensures Vercel can serve static files from the public directory\n  const clientDir = path.join(root, distDir, \"client\");\n  try {\n    // Ensure public directory exists\n    await mkdir(publicOutputDir, { recursive: true });\n\n    // Copy all client assets including manifest\n    await cp(clientDir, publicOutputDir, { recursive: true });\n    logger.info(\"📦 Copied client assets to public directory\");\n\n    // Verify important files are present\n    const manifestPath = path.join(publicOutputDir, \"farm-client-manifest.json\");\n    const assetsDir = path.join(publicOutputDir, \"assets\");\n    const manifestExists = await import(\"fs/promises\").then((fs) =>\n      fs\n        .access(manifestPath)\n        .then(() => true)\n        .catch(() => false),\n    );\n    const assetsExist = await import(\"fs/promises\").then((fs) =>\n      fs\n        .access(assetsDir)\n        .then(() => true)\n        .catch(() => false),\n    );\n\n    if (manifestExists && assetsExist) {\n      logger.info(\"✅ Verified client assets are present\");\n    } else {\n      logger.warn(\"⚠️  Some client assets may be missing\");\n    }\n  } catch (error) {\n    logger.error(`❌ Failed to copy client assets: ${error}`);\n    throw error;\n  }\n\n  // Copy SSR bundles to Nitro server directory so they're included in the build\n  // These go into .farm/.nitro/server/farm (build directory)\n  // Nitro will then bundle them and output to .farm/.output/server\n  const serverDir = path.join(root, distDir, \"server\");\n  const nitroServerDir = path.join(root, distDir, \".nitro\", \"server\", \"farm\");\n  try {\n    await mkdir(nitroServerDir, { recursive: true });\n    await cp(serverDir, nitroServerDir, { recursive: true });\n    logger.info(\"📦 Copied SSR bundles to Nitro server directory\");\n  } catch (error) {\n    logger.warn(`Could not copy SSR bundles: ${error}`);\n  }\n\n  // Create Nitro instance - this handles preset loading and config preparation\n  // The createNitro function loads the preset and normalizes the config\n  const nitro = await createNitro(nitroConfig);\n\n  // Populate the runtime registry before building\n  // This ensures route managers are available at runtime\n  // Note: The registry will be populated again in the build:before hook\n  // but we also populate it here to ensure it's available\n  // Registry file is in .farm/.nitro/server (build directory)\n  // But will be bundled and available in .farm/.output/server (output directory)\n  const registryPath = path.join(root, distDir, \".nitro\", \"server\", \"farm-registry.ts\");\n  try {\n    const { farmRegistry } = await import(/* @vite-ignore */ registryPath);\n    farmRegistry.apiRouteManager = apiRouteManager;\n    farmRegistry.routeManager = routeManager;\n    farmRegistry.serverRenderer = serverRenderer;\n    farmRegistry.env = config.env || { server: {}, public: {} };\n\n    // Store route paths for SSR module loading\n    const routePaths: Record<string, string> = {};\n    for (const [pattern, entry] of routeManager.getRoutes()) {\n      const bundledPath = entry.modulePath\n        .replace(/.*\\/src\\/app\\//, \"\")\n        .replace(/\\.(tsx?|jsx?)$/, \".js\");\n      routePaths[pattern] = bundledPath;\n    }\n    farmRegistry.routePaths = routePaths;\n\n    // Load client manifest\n    try {\n      const clientManifestPath = path.join(root, distDir, \"client\", \"farm-client-manifest.json\");\n      const { readFile } = await import(\"fs/promises\");\n      const manifestContent = await readFile(clientManifestPath, \"utf-8\");\n      farmRegistry.clientManifest = JSON.parse(manifestContent);\n    } catch {\n      farmRegistry.clientManifest = {};\n    }\n  } catch (error) {\n    logger.warn(`Could not populate registry: ${error}`);\n  }\n\n  // Build Nitro with the prepared instance\n  await nitroBuild(nitro);\n\n  if (pluginManager) {\n    await pluginManager.runHookParallel(\"afterNitroBuild\", {\n      root,\n      preset,\n      distDir,\n      outputDir: resolveDeployOutputPath(root, config.deploy.outputDir),\n    });\n  }\n}\n","import type { RedirectConfig, ResolvedFarmConfig, RewriteConfig } from \"../config\";\nimport { hasCustomFarmRouteContext, resolveDeployOutputPath } from \"../config\";\nimport {\n  FARM_CLIENT_CSS_HREF_PLACEHOLDER,\n  FARM_CLIENT_JS_SRC_PLACEHOLDER,\n  findFingerprintedClientEntry,\n  resolveHashedClientCssHref,\n  resolveHashedClientJsSrc,\n} from \"./client-css-href\";\nimport type { RouteManager } from \"../routing/route-manager\";\nimport type { APIRouteManager } from \"../api/route-manager\";\nimport { resolveFarmAPIServerBasePath } from \"../api/server-path\";\nimport type { ServerRenderer } from \"../server/renderer\";\nimport type { FarmPlugin, PluginManager } from \"../plugin\";\nimport {\n  generateFarmClientPluginEntryCode,\n  type FarmClientPluginEntryCode,\n} from \"../client-plugin-build\";\nimport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n  type ClientCachePersistenceEntryCode,\n} from \"../client-cache-persistence-build\";\nimport type { Rollup } from \"vite\";\nimport os from \"os\";\nimport path from \"path\";\nimport { constants as fsConstants, existsSync, readFileSync } from \"fs\";\nimport { fileURLToPath } from \"url\";\nimport { builtinModules, createRequire } from \"module\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { logger, toPosixPath, toViteModuleId } from \"../utils\";\nimport {\n  enforceFarmIsolatedHydrationRouteBudget,\n  getClientModuleHydrationPlan,\n  getClientModuleMetadata,\n  resolveFarmIsolatedClientHydrationMode,\n  type ClientModuleHydrationPlan,\n  type IsolatedClientBoundaryReference,\n} from \"../utils/client-component\";\nimport type { FarmIsolatedClientHydrationMode } from \"../types\";\nimport { isFarmMarkdownPageFile } from \"../app-markdown\";\nimport type { ProgrammaticRedirectRoute } from \"../routes\";\nimport type { NitroConfig } from \"nitro/config\";\nimport {\n  applyFarmWorkflowVercelCrons,\n  prepareFarmWorkflowsForNitro,\n  type PreparedFarmWorkflows,\n} from \"../workflows\";\nimport {\n  applyFarmCronVercelCrons,\n  createFarmCronCloudflareConfig,\n  mergeScheduledTasks,\n  prepareFarmCronForNitro,\n} from \"../cron\";\nimport { routeRulesToNitroRouteRules } from \"../route-rules\";\nimport { getFarmAppDirectories } from \"../layers\";\nimport { farmEnvironmentFunctionsPlugin } from \"../environment-vite\";\nimport {\n  createFarmDocsLastModifiedManifest,\n  FARM_DOCS_LAST_MODIFIED_MANIFEST,\n} from \"../docs/last-modified\";\nimport {\n  generateFarmDocsSearchClientRuntime,\n  isFarmDocsSearchEnabled,\n  resolveFarmDocsSearchClientModule,\n} from \"../docs/search-client\";\nimport { resolveFarmDocsFontAssets, toFarmDocsPublicFontAssets } from \"../docs/fonts\";\nimport {\n  createFarmRouteRuntimeManifest,\n  validateFarmRouteRuntimeDeployment,\n  writeFarmRouteRuntimeManifest,\n} from \"../route-runtime-manifest\";\nimport type { FarmRouteRuntimeManifest, FarmRouteRuntimeManifestEntry } from \"../route-runtime\";\nimport { createFarmVercelRouteRuntimeFunctions } from \"./vercel-route-runtime\";\nimport { buildFarmVercelRoutes } from \"./vercel-assets\";\nimport { createFarmNodeServerEntry } from \"./node-server-entry\";\nimport { resolveFarmNotFoundComponentPath } from \"../not-found\";\nimport { readFarmI18nCatalogs } from \"../i18n/catalog\";\nimport type { FarmI18nCatalogs } from \"../i18n/types\";\nimport { getFarmIntegrationPluginServerRuntime, getIntegrationProviders } from \"../integrations\";\nimport {\n  generateFarmIntegrationProviderClientCode,\n  generateFarmIntegrationProviderServerModules,\n} from \"../integration-provider-build\";\nimport type { TransformOptions } from \"esbuild\";\nimport { loadFarmProductionVite, type FarmProductionViteRuntime } from \"../build/production-vite\";\nimport { adaptTailwindVitePlugin } from \"../build/vite-plugin-compat\";\nimport { mergeFarmFontCss } from \"../font-vite\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport { createFarmSourceAlias } from \"../server/vite-config\";\nimport { DEFAULT_NOT_FOUND_STYLES } from \"../components/not-found-styles\";\nimport { createFarmThemeCssPlugin } from \"../theme/vite\";\nimport { resolveFarmInstrumentationFile } from \"../instrumentation\";\nimport { isReactRenderer, loadFarmRendererVitePlugins, REACT_RENDERER } from \"../renderer\";\nimport { appendMiddlewareRoutePath } from \"../middleware/path\";\nimport type { FarmRenderer } from \"../renderer\";\n\n// Type alias for OutputBundle\ntype OutputBundle = Rollup.OutputBundle;\ntype NitroEsbuildOptions = NonNullable<NonNullable<NitroConfig[\"esbuild\"]>[\"options\"]>;\ntype FarmNitroRuntime = typeof import(\"nitro\");\ntype UniversalPageRoute = {\n  pattern: string;\n  modulePath: string;\n  source?: string;\n  markdownSourcePath?: string;\n};\ntype UniversalBoundaryRoute = {\n  pattern: string;\n  modulePath: string;\n};\ntype UniversalRouteSlot = {\n  name: string;\n  ownerPattern: string;\n  pattern: string;\n  modulePath: string;\n  containerId: string;\n  interception: boolean;\n  fallback: boolean;\n};\ntype UniversalConfiguredHeaderRoute = {\n  source: string;\n  headers: Array<{ key: string; value: string }>;\n};\ntype UniversalMetadataImageRoute = {\n  pattern: string;\n  kind: \"opengraph\" | \"twitter\";\n  fileName: \"opengraph-image\" | \"twitter-image\";\n  sourceType: \"module\" | \"static\";\n  modulePath?: string;\n  staticInfo?: {\n    contentType: string;\n    width: number;\n    height: number;\n    alt?: string;\n    hash: string;\n    byteLength: number;\n  };\n  data?: string;\n};\ntype UniversalApplicationMetadataRoute = {\n  pattern: string;\n  kind: \"sitemap\" | \"robots\" | \"manifest\";\n  outputName: \"sitemap.xml\" | \"robots.txt\" | \"manifest.webmanifest\";\n  modulePath: string;\n};\ntype UniversalMiddlewareRoute = {\n  path: string;\n  filePath: string;\n};\n\nfunction preloadFarmNitroRuntime(): Promise<PromiseSettledResult<FarmNitroRuntime>> {\n  return import(\"nitro\").then(\n    (value) => ({ status: \"fulfilled\", value }),\n    (reason) => ({ status: \"rejected\", reason }),\n  );\n}\n\n// Get __dirname equivalent for ESM\nconst _filename = typeof import.meta.url !== \"undefined\" ? fileURLToPath(import.meta.url) : \"\";\nconst _dirname = path.dirname(_filename);\nconst NODE_BUILTIN_MODULES = new Set([\n  ...builtinModules,\n  ...builtinModules.map((moduleName) => `node:${moduleName}`),\n]);\nconst NITRO_EXTERNAL_MODULES = new Set([\n  \"react\",\n  \"react-dom\",\n  \"react-dom/server\",\n  \"@prisma/client\",\n  \"@prisma/client/default\",\n  \"@prisma/client/default.js\",\n  \".prisma/client\",\n  \".prisma/client/default\",\n  \"better-sqlite3\",\n  \"fsevents\",\n  \"esbuild\",\n  \"lightningcss\",\n  \"rollup\",\n  \"vite\",\n  \"vite-rolldown\",\n  \"nitro\",\n  \"nitropack\",\n  \"sharp\",\n]);\nconst FARM_SSR_PACKAGE_IMPORT = \"#farm-ssr-entry\";\nconst FARM_SSR_OUTPUT_DIR = \"farm-ssr\";\nconst FARM_CLIENT_BUILD_TARGET = [\"es2020\", \"edge88\", \"firefox78\", \"chrome87\", \"safari14\"];\n\nfunction resolveNitroRuntimeDependency(root: string, specifier: string): string {\n  return createRequire(resolveNitroPackageEntry(root)).resolve(specifier).split(path.sep).join(\"/\");\n}\n\n/**\n * Rollup fallback resolver for the temporary prerender server. Bare ids that\n * the regular pipeline cannot resolve (Nitro virtual modules import Nitro's\n * runtime dependencies without a real importer) are retried from Nitro's own\n * package location, where pnpm's strict layout can supply them.\n */\nexport function createPrerenderRuntimeResolverPlugin(\n  root: string,\n  resolveNitroEntry: (projectRoot: string) => string = resolveNitroPackageEntry,\n): Rollup.Plugin {\n  let nitroEntry: string | null | undefined;\n\n  return {\n    name: \"farm-prerender-runtime-resolver\",\n    async resolveId(id, _importer, options) {\n      if (options.custom?.farmPrerenderRuntimeResolve) return null;\n      if (\n        id.startsWith(\"\\0\") ||\n        id.startsWith(\".\") ||\n        id.startsWith(\"#\") ||\n        id.startsWith(\"virtual:\") ||\n        path.isAbsolute(id) ||\n        NODE_BUILTIN_MODULES.has(id)\n      ) {\n        return null;\n      }\n\n      if (nitroEntry === undefined) {\n        try {\n          nitroEntry = resolveNitroEntry(root);\n        } catch {\n          nitroEntry = null;\n        }\n      }\n      if (!nitroEntry) return null;\n\n      return this.resolve(id, nitroEntry, {\n        ...options,\n        skipSelf: true,\n        custom: { ...options.custom, farmPrerenderRuntimeResolve: true },\n      });\n    },\n  };\n}\n\nfunction resolveNitroPackageEntry(root: string): string {\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  let runtimeRequire = projectRequire;\n  try {\n    runtimeRequire = createRequire(projectRequire.resolve(\"@farm.js/core\"));\n  } catch {\n    // Source-only framework builds can resolve Nitro directly from the project.\n  }\n  return runtimeRequire.resolve(\"nitro\");\n}\n\nfunction cloneConfigValue<T>(value: T, seen = new WeakMap<object, unknown>()): T {\n  if (value === null || typeof value !== \"object\") return value;\n  if (seen.has(value)) return seen.get(value) as T;\n  if (value instanceof RegExp) return new RegExp(value.source, value.flags) as T;\n  if (value instanceof Date) return new Date(value) as T;\n\n  if (Array.isArray(value)) {\n    const clone: unknown[] = [];\n    seen.set(value, clone);\n    for (const entry of value) clone.push(cloneConfigValue(entry, seen));\n    return clone as T;\n  }\n\n  const clone: Record<PropertyKey, unknown> = {};\n  seen.set(value, clone);\n  for (const key of Reflect.ownKeys(value)) {\n    clone[key] = cloneConfigValue((value as Record<PropertyKey, unknown>)[key], seen);\n  }\n  return clone as T;\n}\n\nfunction snapshotSSRRebundleOptions(config: NitroConfig) {\n  return cloneConfigValue({\n    alias: config.alias,\n    commonJS: config.commonJS,\n    entry: config.entry,\n    externals: config.externals,\n    exportConditions: config.exportConditions,\n    imports: config.imports,\n    inlineDynamicImports: config.inlineDynamicImports,\n    moduleSideEffects: config.moduleSideEffects,\n    noExternals: config.noExternals,\n    node: config.node,\n    nodeModulesDirs: config.nodeModulesDirs,\n    plugins: config.plugins,\n    replace: config.replace,\n    serverEntry: config.serverEntry,\n    typescript: config.typescript,\n    unenv: config.unenv,\n    virtual: config.virtual,\n    wasm: config.experimental?.wasm,\n    bundleRuntimeDependencies: config.experimental?.bundleRuntimeDependencies,\n  });\n}\n\nasync function canUseRolldownBuilder(): Promise<boolean> {\n  const [major = 0, minor = 0] = process.versions.node.split(\".\").map(Number);\n  const isSupportedNode = major > 22 || (major === 22 && minor >= 12);\n  if (!isSupportedNode) {\n    return false;\n  }\n\n  try {\n    await import(\"rolldown\");\n    return true;\n  } catch {\n    // Rolldown is optional so --no-optional installs retain Rollup.\n    return false;\n  }\n}\n\nfunction isCloudflareImagePreset(preset: string): boolean {\n  return preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\";\n}\n\nfunction shouldUseExternalMetadataImageRuntime(\n  preset: string,\n  hasGeneratedMetadataImages: boolean,\n): boolean {\n  return hasGeneratedMetadataImages && preset !== \"vercel-edge\" && !isCloudflareImagePreset(preset);\n}\n\nfunction resolveImageRuntime(\n  config: ResolvedFarmConfig,\n  preset: string,\n): \"none\" | \"node\" | \"cloudflare\" {\n  if (config.images.provider === \"none\") return \"none\";\n  const cloudflarePreset = isCloudflareImagePreset(preset);\n  if (config.images.provider === \"node\" && cloudflarePreset) {\n    throw new Error('images.provider \"node\" cannot run in a Cloudflare deployment');\n  }\n  if (config.images.provider === \"cloudflare\" && !cloudflarePreset) {\n    throw new Error('images.provider \"cloudflare\" requires a Cloudflare deployment preset');\n  }\n  return config.images.provider === \"cloudflare\" ||\n    (config.images.provider === \"auto\" && cloudflarePreset)\n    ? \"cloudflare\"\n    : \"node\";\n}\n\nfunction isNitroRollupExternal(id: string): boolean {\n  const normalizedId = id.replace(/\\\\/g, \"/\");\n\n  return (\n    NODE_BUILTIN_MODULES.has(id) ||\n    NITRO_EXTERNAL_MODULES.has(id) ||\n    normalizedId.startsWith(\".prisma/\") ||\n    normalizedId.includes(\"/node_modules/@prisma/client/\") ||\n    normalizedId.includes(\"/node_modules/.prisma/client/\")\n  );\n}\n\nconst FARM_METADATA_IMAGE_WASM_PREFIX = \"\\0farm-metadata-image-wasm:\";\n\nfunction createMetadataImageWasmPlugin(): Rollup.Plugin {\n  return {\n    name: \"farm-metadata-image-wasm\",\n    resolveId(source, importer) {\n      if (\n        !source.endsWith(\".wasm?module\") ||\n        !importer?.replace(/\\\\/g, \"/\").includes(\"/@vercel/og/\")\n      ) {\n        return null;\n      }\n\n      const requestPath = source.slice(0, -\"?module\".length);\n      const resolvedPath = path.isAbsolute(requestPath)\n        ? requestPath\n        : path.resolve(path.dirname(importer.split(\"?\", 1)[0]), requestPath);\n      return `${FARM_METADATA_IMAGE_WASM_PREFIX}${resolvedPath}`;\n    },\n    load(id) {\n      if (!id.startsWith(FARM_METADATA_IMAGE_WASM_PREFIX)) return null;\n      const wasmPath = id.slice(FARM_METADATA_IMAGE_WASM_PREFIX.length);\n      const encoded = readFileSync(wasmPath).toString(\"base64\");\n      return `\nconst encoded = ${JSON.stringify(encoded)};\nconst bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));\nexport default new WebAssembly.Module(bytes);\n`;\n    },\n  };\n}\n\nfunction collectSSRExternalPackages(ssrBundle: OutputBundle): Set<string> {\n  const emittedFiles = new Set(\n    Object.keys(ssrBundle).map((fileName) => fileName.replace(/^\\.\\//, \"\")),\n  );\n  const externalPackages = new Set<string>();\n\n  for (const [fileName, output] of Object.entries(ssrBundle)) {\n    if (output.type !== \"chunk\") continue;\n\n    for (const importId of [...output.imports, ...output.dynamicImports]) {\n      const normalizedImportId = importId.replace(/\\\\/g, \"/\");\n      const normalizedId = normalizedImportId.replace(/^\\.\\//, \"\");\n      const resolvedRelativeId =\n        normalizedImportId.startsWith(\"./\") || normalizedImportId.startsWith(\"../\")\n          ? path.posix.normalize(path.posix.join(path.posix.dirname(fileName), normalizedImportId))\n          : null;\n      if (\n        emittedFiles.has(normalizedId) ||\n        (resolvedRelativeId !== null && emittedFiles.has(resolvedRelativeId)) ||\n        NODE_BUILTIN_MODULES.has(importId) ||\n        importId.startsWith(\"node:\")\n      ) {\n        continue;\n      }\n\n      if (\n        path.isAbsolute(importId) ||\n        /^[A-Za-z]:[\\\\/]/.test(importId) ||\n        importId.startsWith(\"#\") ||\n        importId.startsWith(\"\\0\")\n      ) {\n        externalPackages.add(importId);\n        continue;\n      }\n\n      const segments = importId.split(\"/\");\n      const packageName = importId.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\n      if (packageName) externalPackages.add(packageName);\n    }\n  }\n\n  return externalPackages;\n}\n\nfunction createExternalSSRBundlePlugin(\n  nitroEntryPath: string,\n  ssrOutputDir: string,\n  ssrEntryFile: string,\n): Rollup.Plugin {\n  const resolvedNitroEntry = path.resolve(nitroEntryPath);\n  const resolvedSSREntry = path.resolve(ssrOutputDir, ssrEntryFile);\n\n  return {\n    name: \"farm-externalize-prebuilt-ssr\",\n    resolveId(source, importer) {\n      if (!importer || path.resolve(importer) !== resolvedNitroEntry) {\n        return null;\n      }\n\n      const resolvedImport = path.resolve(path.dirname(importer), source);\n      if (resolvedImport !== resolvedSSREntry) return null;\n\n      // A package import remains valid even when Nitro moves its adapter into a\n      // nested chunk. A relative external import would be resolved from that\n      // adapter chunk and can point at the wrong location.\n      return { id: FARM_SSR_PACKAGE_IMPORT, external: true };\n    },\n  };\n}\n\nfunction hasRollupPlugins(plugins: unknown): boolean {\n  if (Array.isArray(plugins)) {\n    return plugins.some((plugin) => hasRollupPlugins(plugin));\n  }\n  return Boolean(plugins);\n}\n\nexport function hasFarmRuntimeConfigModule(\n  config: Pick<ResolvedFarmConfig, \"layers\">,\n  configModulePath: string | null,\n): boolean {\n  return Boolean(configModulePath || (config.layers || []).some((layer) => layer.configFile));\n}\n\nfunction createEsbuildTransformOptions(\n  configuredEsbuildOptions: NitroEsbuildOptions,\n  minify: boolean,\n  defaultTarget: string,\n): TransformOptions {\n  const {\n    include: _include,\n    exclude: _exclude,\n    sourceMap: _sourceMap,\n    loaders: _loaders,\n    ...configuredTransformOptions\n  } = configuredEsbuildOptions;\n  const configuredTarget = Array.isArray(configuredTransformOptions.target)\n    ? configuredTransformOptions.target.filter(\n        (target): target is string => typeof target === \"string\",\n      )\n    : configuredTransformOptions.target;\n  const transformTarget =\n    Array.isArray(configuredTarget) && configuredTarget.length === 0\n      ? defaultTarget\n      : (configuredTarget ?? defaultTarget);\n  const transformSupported = configuredTransformOptions.supported\n    ? Object.fromEntries(\n        Object.entries(configuredTransformOptions.supported).filter(\n          (entry): entry is [string, boolean] => typeof entry[1] === \"boolean\",\n        ),\n      )\n    : undefined;\n\n  return {\n    ...(configuredTransformOptions as TransformOptions),\n    format: \"esm\",\n    target: transformTarget,\n    loader: \"js\",\n    sourcemap: false,\n    minify,\n    keepNames: configuredTransformOptions.keepNames ?? true,\n    legalComments: configuredTransformOptions.legalComments ?? \"none\",\n    supported: transformSupported,\n  };\n}\n\nfunction createEsbuildChunkMinifyPlugin(\n  configuredEsbuildOptions: NitroEsbuildOptions,\n): Rollup.Plugin {\n  const configuredTransformOptions = createEsbuildTransformOptions(\n    configuredEsbuildOptions,\n    true,\n    \"esnext\",\n  );\n  // Nitro already applies the configured esbuild transform to every module.\n  // Keep this final chunk pass limited to minification controls so options such\n  // as banner, footer, define, drop, and property mangling are not applied twice.\n  const transformOptions: TransformOptions = {\n    format: \"esm\",\n    target: configuredTransformOptions.target,\n    loader: \"js\",\n    sourcemap: false,\n    minify: true,\n    keepNames: configuredTransformOptions.keepNames,\n    legalComments: configuredTransformOptions.legalComments,\n    charset: configuredTransformOptions.charset,\n  };\n\n  return {\n    name: \"farm-esbuild-minify\",\n    async renderChunk(code, chunk) {\n      const { transform } = await import(\"esbuild\");\n      const result = await transform(code, {\n        ...transformOptions,\n        sourcefile: chunk.fileName,\n      });\n      if (!result.code) return null;\n      return {\n        code: result.code,\n        map: result.map || null,\n      };\n    },\n  };\n}\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction resolveBuildDocsContentDir(config: ResolvedFarmConfig, root: string): string | null {\n  if (!config.docs?.enabled) return null;\n\n  const configuredContentDir = config.docs.contentDir || config.docs.config.contentDir;\n  if (typeof configuredContentDir === \"string\" && configuredContentDir.trim()) {\n    const contentDir = path.isAbsolute(configuredContentDir)\n      ? configuredContentDir\n      : path.join(root, configuredContentDir);\n    return existsSync(contentDir) ? contentDir : null;\n  }\n\n  const entryDir = config.docs.config.entry || trimSlashes(config.docs.entry) || \"docs\";\n  const appDocsDir = path.join(root, config.srcDir || \"src\", \"app\", entryDir);\n  if (existsSync(appDocsDir)) return appDocsDir;\n\n  const rootDocsDir = path.join(root, entryDir);\n  return existsSync(rootDocsDir) ? rootDocsDir : null;\n}\n\nfunction hasProjectPostcssConfig(root: string): boolean {\n  const candidates = [\n    \"postcss.config.js\",\n    \"postcss.config.cjs\",\n    \"postcss.config.mjs\",\n    \"postcss.config.ts\",\n    \"postcss.config.json\",\n    \".postcssrc\",\n    \".postcssrc.json\",\n    \".postcssrc.js\",\n    \".postcssrc.cjs\",\n    \".postcssrc.mjs\",\n    \".postcssrc.ts\",\n  ];\n\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  return candidates.some((file) => {\n    try {\n      projectRequire.resolve(`./${file}`);\n      return true;\n    } catch {\n      return false;\n    }\n  });\n}\n\nasync function findFarmConfigPath(root: string): Promise<string | null> {\n  const fs = await import(\"fs/promises\");\n  const candidates = [\n    \"farm.config.ts\",\n    \"farm.config.mts\",\n    \"farm.config.js\",\n    \"farm.config.mjs\",\n    \"config.ts\",\n    \"config.mts\",\n    \"config.js\",\n    \"config.mjs\",\n  ];\n\n  for (const candidate of candidates) {\n    const resolvedPath = path.join(root, candidate);\n    try {\n      await fs.access(resolvedPath);\n      return resolvedPath;\n    } catch {\n      // Continue checking the next supported config path.\n    }\n  }\n\n  return null;\n}\n\nfunction hasFarmMiddlewareConfig(config: ResolvedFarmConfig[\"middleware\"]): boolean {\n  if (!config) return false;\n  if (Array.isArray(config)) return config.length > 0;\n\n  const configRecord = config as Record<string, unknown>;\n  return Boolean(\n    configRecord.matcher ||\n    configRecord.exclude ||\n    configRecord.runtime ||\n    configRecord.handler ||\n    (Array.isArray(configRecord.handlers) && configRecord.handlers.length > 0),\n  );\n}\n\nfunction hasFarmServerRuntimePlugins(config: ResolvedFarmConfig): boolean {\n  return (config.plugins || []).some((plugin) => {\n    if (getFarmIntegrationPluginServerRuntime(plugin) === false) return false;\n\n    return Boolean(\n      plugin.setup ||\n      plugin.init ||\n      plugin.ready ||\n      plugin.shutdown ||\n      plugin.runtime ||\n      plugin.router ||\n      plugin.render ||\n      plugin.beforeRouteMatch ||\n      plugin.afterRouteMatch ||\n      plugin.beforeRender ||\n      plugin.afterRender ||\n      plugin.onError ||\n      plugin.transformHTML,\n    );\n  });\n}\n\nexport async function discoverMiddlewareRoutes(\n  appDir: string | readonly string[],\n): Promise<UniversalMiddlewareRoute[]> {\n  const fs = await import(\"fs/promises\");\n  const appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n  const routes = new Map<string, UniversalMiddlewareRoute>();\n\n  async function walk(\n    dir: string,\n    routePath: string,\n    discovered: UniversalMiddlewareRoute[],\n  ): Promise<void> {\n    let entries: import(\"fs\").Dirent[];\n    try {\n      entries = await fs.readdir(dir, { withFileTypes: true });\n    } catch {\n      return;\n    }\n\n    const middlewareFile = entries.find(\n      (entry) => entry.isFile() && /^middleware\\.(tsx?|jsx?)$/.test(entry.name),\n    );\n\n    if (middlewareFile) {\n      discovered.push({\n        path: routePath,\n        filePath: path.join(dir, middlewareFile.name),\n      });\n    }\n\n    for (const entry of entries) {\n      if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name.startsWith(\"_\")) {\n        continue;\n      }\n\n      const childRoutePath = appendMiddlewareRoutePath(routePath, entry.name);\n      await walk(path.join(dir, entry.name), childRoutePath, discovered);\n    }\n  }\n\n  for (const sourceAppDir of appDirs) {\n    const discovered: UniversalMiddlewareRoute[] = [];\n    await walk(sourceAppDir, \"/\", discovered);\n    for (const route of discovered) {\n      routes.set(route.path, route);\n    }\n  }\n\n  return Array.from(routes.values()).sort((a, b) => {\n    const depthA = a.path.split(\"/\").filter(Boolean).length;\n    const depthB = b.path.split(\"/\").filter(Boolean).length;\n    return depthA - depthB || a.path.localeCompare(b.path);\n  });\n}\n\n/**\n * Universal build using TanStack Start pattern\n * - Builds SSR bundle in memory\n * - Uses virtual bundle plugin to expose to Nitro\n * - Creates virtual entry wrapping Web Standard handler\n */\nexport async function buildUniversal(\n  config: ResolvedFarmConfig,\n  routeManager: RouteManager,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: ServerRenderer,\n  options: {\n    preset?: string;\n    root?: string;\n    pluginManager?: PluginManager;\n    routeRuntimeManifest?: FarmRouteRuntimeManifest;\n    productionVite?: FarmProductionViteRuntime | Promise<FarmProductionViteRuntime>;\n  } = {},\n): Promise<void> {\n  const root = options.root || config.root || process.cwd();\n  const preset = options.preset || config.preset || \"node-server\";\n  const srcDir = config.srcDir || \"src\";\n  const distDir = config.distDir || \".farm\";\n  const deployOutputDir = resolveDeployOutputPath(root, config.deploy.outputDir);\n  const lifecyclePluginManager = options.pluginManager;\n  // Attach all-settled handlers immediately so an earlier discovery failure\n  // cannot leave a rejected preload unobserved.\n  const productionViteResultPromise = Promise.allSettled([\n    Promise.resolve(options.productionVite ?? loadFarmProductionVite()),\n  ]);\n  // Nitro is guaranteed to be needed for every universal production build.\n  // Start resolving it while route metadata and the client/SSR bundles are\n  // prepared, then consume the settled result at the adapter stage.\n  const nitroRuntimeResultPromise = preloadFarmNitroRuntime();\n\n  logger.info(`🚜 Building Farm.js application (universal) with preset: ${preset}...`);\n\n  try {\n    const routeRuntimeManifestPromise = options.routeRuntimeManifest\n      ? Promise.resolve(options.routeRuntimeManifest)\n      : createFarmRouteRuntimeManifest({\n          config,\n          routeManager,\n          apiRouteManager,\n          root,\n        });\n    const routeRuntimeManifestResultPromise = Promise.allSettled([routeRuntimeManifestPromise]);\n\n    // Get page routes first (needed for both client and SSR builds)\n    const pageRoutes: UniversalPageRoute[] = [];\n    for (const [pattern, entry] of routeManager.getRoutes()) {\n      const markdownSourcePath =\n        entry.markdownSourcePath ||\n        (isFarmMarkdownPageFile(entry.modulePath) ? entry.modulePath : undefined);\n      pageRoutes.push({\n        pattern,\n        modulePath: entry.modulePath,\n        ...(markdownSourcePath\n          ? {\n              source: readFileSync(markdownSourcePath, \"utf8\"),\n              markdownSourcePath,\n            }\n          : {}),\n      });\n    }\n    const routeSlots: UniversalRouteSlot[] = Array.from(\n      routeManager.getRouteSlots().values(),\n      (entry) => ({\n        name: entry.name,\n        ownerPattern: entry.ownerPattern,\n        pattern: entry.pattern,\n        modulePath: entry.modulePath,\n        containerId: entry.containerId,\n        interception: entry.interception,\n        fallback: entry.fallback,\n      }),\n    );\n    logger.info(`📋 Found ${pageRoutes.length} page routes`);\n\n    // Discover layout files early (needed for client CSS scanning)\n    const fs = await import(\"fs/promises\");\n    const layoutRoutes: Array<{ pattern: string; modulePath: string }> = [];\n    const appDir = path.join(root, srcDir, \"app\");\n\n    async function findLayoutsForClient(dir: string, routePrefix: string = \"/\"): Promise<void> {\n      try {\n        const entries = await fs.readdir(dir, { withFileTypes: true });\n        for (const entry of entries) {\n          if (entry.isFile() && entry.name.match(/^layout\\.(tsx?|jsx?|vue|svelte)$/)) {\n            layoutRoutes.push({\n              pattern: routePrefix,\n              modulePath: path.join(dir, entry.name),\n            });\n          } else if (\n            entry.isDirectory() &&\n            !entry.name.startsWith(\".\") &&\n            !entry.name.startsWith(\"_\")\n          ) {\n            const childPrefix =\n              routePrefix === \"/\" ? `/${entry.name}` : `${routePrefix}/${entry.name}`;\n            await findLayoutsForClient(path.join(dir, entry.name), childPrefix);\n          }\n        }\n      } catch {\n        // Directory doesn't exist or can't be read\n      }\n    }\n    await findLayoutsForClient(appDir);\n    const seenLayoutPatterns = new Set(layoutRoutes.map((layout) => layout.pattern));\n    for (const [pattern, entry] of routeManager.getLayouts()) {\n      if (seenLayoutPatterns.has(pattern)) continue;\n      seenLayoutPatterns.add(pattern);\n      layoutRoutes.push({ pattern, modulePath: entry.modulePath });\n    }\n    logger.info(`📋 Found ${pageRoutes.length} page routes and ${layoutRoutes.length} layouts`);\n\n    const isolatedClientBoundaryModules = routeManager.getIsolatedClientBoundaryModules(root);\n    const hydrationPlanCache = new Map<string, ClientModuleHydrationPlan>();\n\n    const clientOutputDir = path.join(root, distDir, \"client\");\n    const [productionViteResult] = await productionViteResultPromise;\n    if (productionViteResult.status === \"rejected\") {\n      // Route evaluation may still be using the project module server. Drain it\n      // before the outer build cleanup closes that server.\n      await routeRuntimeManifestResultPromise;\n      throw productionViteResult.reason;\n    }\n    const productionVite = productionViteResult.value;\n    if (productionVite.builder === \"rolldown\") {\n      logger.info(\"⚡ Building application bundles with Vite Rolldown\");\n    }\n\n    const buildClientBundle = () =>\n      buildClient(\n        productionVite,\n        config,\n        root,\n        srcDir,\n        clientOutputDir,\n        pageRoutes,\n        layoutRoutes,\n        routeSlots,\n        isolatedClientBoundaryModules,\n        hydrationPlanCache,\n      );\n    const buildSSRBundle = () =>\n      buildSSRInMemory(\n        productionVite,\n        config,\n        root,\n        routeManager,\n        apiRouteManager,\n        serverRenderer,\n        preset,\n        pageRoutes,\n        layoutRoutes,\n        routeSlots,\n        isolatedClientBoundaryModules,\n        hydrationPlanCache,\n      );\n\n    // Route metadata and the client/SSR graphs read independent inputs. Drain\n    // every task before propagating a deterministic first failure so a rejected\n    // sibling cannot keep mutating build output in the background. Renderer\n    // compiler plugins with process-global caches can request serial graphs.\n    let clientBuildResult: PromiseSettledResult<Awaited<ReturnType<typeof buildClientBundle>>>;\n    let ssrBuildResult: PromiseSettledResult<Awaited<ReturnType<typeof buildSSRBundle>>>;\n    if (config.renderer.buildConcurrency === \"serial\") {\n      logger.info(`📦 Building client and SSR bundles serially for ${config.renderer.name}...`);\n      [clientBuildResult] = await Promise.allSettled([buildClientBundle()]);\n      [ssrBuildResult] = await Promise.allSettled([buildSSRBundle()]);\n    } else {\n      logger.info(\"📦 Building client and SSR bundles in parallel...\");\n      [clientBuildResult, ssrBuildResult] = await Promise.allSettled([\n        buildClientBundle(),\n        buildSSRBundle(),\n      ]);\n    }\n    const [routeRuntimeManifestResult] = await routeRuntimeManifestResultPromise;\n    if (routeRuntimeManifestResult.status === \"rejected\") {\n      throw routeRuntimeManifestResult.reason;\n    }\n    if (ssrBuildResult.status === \"rejected\") throw ssrBuildResult.reason;\n    if (clientBuildResult.status === \"rejected\") {\n      if (\n        productionVite.builder !== \"rolldown\" ||\n        !(clientBuildResult.reason instanceof IncompleteClientBuildOutputError)\n      ) {\n        throw clientBuildResult.reason;\n      }\n\n      // Rolldown can very rarely complete a parallel client build without\n      // traversing its entry graph. Preserve the fast parallel path, then\n      // recover only that invalid result once the SSR graph is fully drained.\n      logger.warn(\"Client bundle was incomplete; retrying after the SSR build...\");\n      await buildClient(\n        productionVite,\n        config,\n        root,\n        srcDir,\n        clientOutputDir,\n        pageRoutes,\n        layoutRoutes,\n        routeSlots,\n        isolatedClientBoundaryModules,\n        hydrationPlanCache,\n      );\n    }\n\n    const ssrResult = ssrBuildResult.value;\n    const routeRuntimeManifest = routeRuntimeManifestResult.value;\n\n    const runtimeValidation = validateFarmRouteRuntimeDeployment(routeRuntimeManifest, preset);\n    for (const warning of runtimeValidation.warnings) {\n      logger.warn(warning);\n    }\n\n    const { bundle: ssrBundle, entryFile: ssrEntryFile, configuredHeaderRoutes } = ssrResult;\n    await writeSSRAssetsToClient(ssrBundle, clientOutputDir);\n    if (config.docs.enabled) {\n      await copyFarmDocsFontAssetsToClient(root, clientOutputDir);\n    }\n\n    // Step 3: Build with Nitro using virtual bundle\n    logger.info(`🚀 Building server with Nitro (preset: ${preset})...`);\n    await buildNitroUniversal(\n      config,\n      routeManager,\n      apiRouteManager,\n      serverRenderer,\n      preset,\n      root,\n      distDir,\n      ssrBundle,\n      ssrEntryFile,\n      clientOutputDir,\n      routeRuntimeManifest,\n      configuredHeaderRoutes,\n      nitroRuntimeResultPromise,\n      lifecyclePluginManager,\n    );\n\n    const runtimeManifestPath = await writeFarmRouteRuntimeManifest(\n      path.join(root, distDir),\n      routeRuntimeManifest,\n    );\n    logger.info(`📋 Route runtime manifest: ${path.relative(root, runtimeManifestPath)}`);\n    // The completion summary is printed once, by the build orchestrator.\n  } catch (error) {\n    if (lifecyclePluginManager) {\n      await lifecyclePluginManager.runHookParallel(\"onError\", {\n        phase: \"buildUniversal\",\n        error,\n        meta: {\n          root,\n          preset,\n        },\n      });\n    }\n    logger.error(`❌ Build failed: ${error}`);\n    throw error;\n  }\n}\n\nasync function writeSSRAssetsToClient(bundle: OutputBundle, outputDir: string): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  for (const [fileName, output] of Object.entries(bundle)) {\n    if (output.type !== \"asset\") continue;\n    if (fileName === \"farm-fonts.css\") {\n      await mergeBuiltFontCss(outputDir, output.source);\n      continue;\n    }\n    const filePath = path.join(outputDir, fileName);\n    await fs.mkdir(path.dirname(filePath), { recursive: true });\n    await fs.writeFile(filePath, output.source);\n  }\n}\n\nasync function copyFarmDocsFontAssetsToClient(root: string, outputDir: string): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  await Promise.all(\n    resolveFarmDocsFontAssets(root).map(async ({ sourcePath, url }) => {\n      const targetPath = path.join(outputDir, url.replace(/^\\/+/, \"\"));\n      await fs.mkdir(path.dirname(targetPath), { recursive: true });\n      await fs.copyFile(sourcePath, targetPath);\n    }),\n  );\n}\n\nasync function mergeBuiltFontCss(\n  outputDir: string,\n  fontCssSource?: string | Uint8Array,\n): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const fontCssPath = path.join(outputDir, \"farm-fonts.css\");\n  let fontCss = fontCssSource;\n  if (fontCss === undefined) {\n    try {\n      fontCss = await fs.readFile(fontCssPath);\n    } catch {\n      return;\n    }\n  }\n\n  const clientCssPath = path.join(outputDir, \"farm-client.css\");\n  let clientCss = \"\";\n  try {\n    clientCss = await fs.readFile(clientCssPath, \"utf8\");\n  } catch {\n    // A font-only app may not have produced a stylesheet yet.\n  }\n  const normalizedFontCss =\n    typeof fontCss === \"string\" ? fontCss : Buffer.from(fontCss).toString(\"utf8\");\n  await fs.writeFile(fontCssPath, normalizedFontCss);\n  await fs.writeFile(clientCssPath, mergeFarmFontCss(clientCss, normalizedFontCss));\n}\n\nclass IncompleteClientBuildOutputError extends Error {\n  constructor(detail: string) {\n    super(`Farm client build produced incomplete output: ${detail}`);\n    this.name = \"IncompleteClientBuildOutputError\";\n  }\n}\n\nasync function validateClientBuildOutput(\n  root: string,\n  srcDir: string,\n  outputDir: string,\n): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const fingerprinted = await findFingerprintedClientEntry(outputDir);\n  const clientEntryPath = path.join(outputDir, fingerprinted ?? \"farm-client.js\");\n  let clientEntrySize = 0;\n\n  try {\n    const clientEntry = await fs.stat(clientEntryPath);\n    if (clientEntry.isFile()) clientEntrySize = clientEntry.size;\n  } catch {\n    // Report the missing entry through the shared incomplete-output diagnostic.\n  }\n\n  if (clientEntrySize === 0) {\n    throw new IncompleteClientBuildOutputError(\"farm-client.js is missing or empty\");\n  }\n\n  const clientCssPath = path.join(outputDir, \"farm-client.css\");\n  const globalsCssPath = path.join(root, srcDir, \"app\", \"globals.css\");\n  let expectsCss = false;\n  try {\n    const globalsCss = await fs.readFile(globalsCssPath, \"utf8\");\n    expectsCss = globalsCss.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\").trim().length > 0;\n  } catch {\n    // Vite reports a missing imported stylesheet before output validation.\n  }\n\n  try {\n    const clientCss = await fs.stat(clientCssPath);\n    if (expectsCss && (!clientCss.isFile() || clientCss.size === 0)) {\n      throw new IncompleteClientBuildOutputError(\"farm-client.css is empty\");\n    }\n  } catch (error) {\n    if (error instanceof IncompleteClientBuildOutputError) throw error;\n    if (expectsCss) {\n      throw new IncompleteClientBuildOutputError(\"farm-client.css is missing\");\n    }\n\n    // Farm's HTML always references this stable path. Keep intentionally\n    // style-free applications from receiving an unnecessary 404.\n    await fs.writeFile(clientCssPath, \"\");\n  }\n}\n\n/**\n * Build client bundle (to disk) with hydration for \"use client\" components\n */\nfunction getCachedClientModuleHydrationPlan(\n  modulePath: string,\n  root: string,\n  mode: FarmIsolatedClientHydrationMode,\n  cache: Map<string, ClientModuleHydrationPlan>,\n): ClientModuleHydrationPlan {\n  const key = `${path.resolve(root)}\\0${mode}\\0${path.resolve(modulePath)}`;\n  let plan = cache.get(key);\n  if (!plan) {\n    plan = getClientModuleHydrationPlan(modulePath, root, mode);\n    cache.set(key, plan);\n  }\n  return { ...plan, isolatedBoundaries: [...plan.isolatedBoundaries] };\n}\n\nasync function buildClient(\n  productionVite: FarmProductionViteRuntime,\n  config: ResolvedFarmConfig,\n  root: string,\n  srcDir: string,\n  outputDir: string,\n  pageRoutes: UniversalPageRoute[],\n  layoutRoutes: Array<{ pattern: string; modulePath: string }> = [],\n  routeSlots: UniversalRouteSlot[] = [],\n  isolatedClientBoundaryModules: ReadonlySet<string> = new Set(),\n  hydrationPlanCache: Map<string, ClientModuleHydrationPlan> = new Map(),\n) {\n  const viteBuild = productionVite.build;\n  const { farmPlugin } = await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n  const fs = await import(\"fs/promises\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n\n  // Detect which pages should hydrate on the client.\n  const clientPages: Array<{\n    pattern: string;\n    modulePath: string;\n    relativePath: string;\n    pageShouldHydrate: boolean;\n    islandStrategy: FarmIslandStrategy;\n    hasIsolatedClientBoundaries: boolean;\n    isolatedBoundaries: IsolatedClientBoundaryReference[];\n  }> = [];\n\n  const integrationProviders = getIntegrationProviders(config.integrations).filter(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  const unsupportedIntegrationProvider = integrationProviders.find(\n    (provider) => provider.supportsIsolatedHydration !== true,\n  );\n  if (\n    config.experimental?.isolatedClientHydration === \"enabled\" &&\n    config.experimental?.serverComponents !== true &&\n    unsupportedIntegrationProvider\n  ) {\n    logger.warn(\n      `[Farm.js] isolated hydration kept route-wide because integration provider \"${unsupportedIntegrationProvider.name}\" does not declare supportsIsolatedHydration: true.`,\n    );\n  }\n  const isolatedMode = resolveFarmIsolatedClientHydrationMode(\n    config.experimental?.isolatedClientHydration,\n    {\n      serverComponents: config.experimental?.serverComponents === true,\n      hasUnsupportedIntegrationProvider: Boolean(unsupportedIntegrationProvider),\n    },\n  );\n\n  const clientLayouts = layoutRoutes.map((layout) => {\n    try {\n      const metadata = getCachedClientModuleHydrationPlan(\n        layout.modulePath,\n        root,\n        isolatedMode,\n        hydrationPlanCache,\n      );\n      return {\n        ...layout,\n        shouldHydrate: metadata.shouldHydrate,\n        islandStrategy: metadata.islandStrategy,\n        legacyShouldHydrate: metadata.legacyShouldHydrate,\n        legacyIslandStrategy: metadata.legacyIslandStrategy,\n        mode: metadata.mode,\n        estimatedIsolatedRootCount: metadata.estimatedIsolatedRootCount,\n        hasIsolatedClientBoundaries: metadata.hasIsolatedClientBoundaries,\n        isolatedHydrationEligible: metadata.isolatedHydrationEligible,\n        isolatedBoundaries: metadata.isolatedBoundaries,\n      };\n    } catch (error) {\n      logger.warn(`⚠️  Could not inspect layout file ${layout.modulePath}: ${error}`);\n      return {\n        ...layout,\n        shouldHydrate: false,\n        islandStrategy: null,\n        legacyShouldHydrate: false,\n        legacyIslandStrategy: null,\n        mode: isolatedMode,\n        estimatedIsolatedRootCount: 0,\n        hasIsolatedClientBoundaries: false,\n        isolatedHydrationEligible: false,\n        isolatedBoundaries: [],\n      };\n    }\n  });\n\n  const layoutAppliesToRoute = (layoutPattern: string, routePattern: string) =>\n    layoutPattern === \"/\" ||\n    routePattern === layoutPattern ||\n    routePattern.startsWith(`${layoutPattern}/`);\n\n  const adapterOwnsDocsRuntime = Boolean(\n    isReactRenderer(config.renderer) &&\n    config.docs?.enabled &&\n    config.docs.adapter?.server &&\n    config.docs.adapter.react,\n  );\n  const adapterDocsEntry = config.docs?.enabled\n    ? `/${config.docs.entry || \"docs\"}`.replace(/\\/+/g, \"/\").replace(/\\/$/, \"\") || \"/\"\n    : null;\n  const isAdapterDocsRoute = (routePattern: string) =>\n    Boolean(\n      adapterOwnsDocsRuntime &&\n      adapterDocsEntry &&\n      (adapterDocsEntry === \"/\" ||\n        routePattern === adapterDocsEntry ||\n        routePattern.startsWith(`${adapterDocsEntry}/`)),\n    );\n\n  const routePlans = pageRoutes.map((route) => ({\n    route,\n    metadata: isFarmMarkdownPageFile(route.modulePath)\n      ? {\n          isClientComponent: false,\n          shouldHydrate: false,\n          islandStrategy: null,\n          legacyShouldHydrate: false,\n          legacyIslandStrategy: null,\n          mode: isolatedMode,\n          estimatedIsolatedRootCount: 0,\n          hasIsolatedClientBoundaries: false,\n          isolatedBoundaries: [] as IsolatedClientBoundaryReference[],\n          suppressedAsyncHydration: undefined,\n        }\n      : getCachedClientModuleHydrationPlan(\n          route.modulePath,\n          root,\n          isolatedMode,\n          hydrationPlanCache,\n        ),\n  }));\n\n  enforceFarmIsolatedHydrationRouteBudget(\n    clientLayouts.map((layout) => ({\n      pattern: layout.pattern,\n      depth: layout.pattern.split(\"/\").filter(Boolean).length,\n      metadata: layout,\n    })),\n    routePlans.map(({ route, metadata }) => ({\n      pattern: route.pattern,\n      depth: route.pattern.split(\"/\").filter(Boolean).length,\n      metadata,\n    })),\n    layoutAppliesToRoute,\n  );\n\n  if (isolatedMode === \"analyze\") {\n    for (const { entry, metadata } of [\n      ...clientLayouts.map((layout) => ({ entry: layout, metadata: layout })),\n      ...routePlans.map(({ route, metadata }) => ({ entry: route, metadata })),\n    ]) {\n      if (!(\"isolatedHydrationEligible\" in metadata) || !metadata.isolatedHydrationEligible) {\n        continue;\n      }\n      logger.info(\n        `📊 Isolated hydration analysis: ${entry.modulePath} can exclude its server owner and hydrate ${metadata.isolatedBoundaries.length} client ${metadata.isolatedBoundaries.length === 1 ? \"boundary\" : \"boundaries\"}.`,\n      );\n    }\n  }\n\n  for (const { route, metadata } of routePlans) {\n    // The adapter imports and hydrates its compiled MDX modules itself. Keeping\n    // the same files in Farm's generic route table duplicates the docs runtime\n    // and can pull server-only Markdown dependencies into the browser bundle.\n    if (isAdapterDocsRoute(route.pattern)) continue;\n\n    try {\n      const applicableClientLayouts = clientLayouts.filter(\n        (layout) =>\n          (layout.shouldHydrate || layout.hasIsolatedClientBoundaries) &&\n          layoutAppliesToRoute(layout.pattern, route.pattern),\n      );\n      if (metadata.suppressedAsyncHydration) {\n        logger.warn(\n          `⚠️  ${route.pattern} is an async server component that imports client components; ` +\n            `React cannot hydrate async components, so the route stays server-rendered ` +\n            `and its client imports are not interactive.`,\n        );\n      }\n      if (\n        metadata.shouldHydrate ||\n        metadata.hasIsolatedClientBoundaries ||\n        applicableClientLayouts.length > 0\n      ) {\n        const relativePath = route.modulePath.replace(root, \"\").replace(/^\\//, \"\");\n        const hydrationStrategies = [\n          ...(metadata.islandStrategy ? [metadata.islandStrategy] : []),\n          ...applicableClientLayouts.flatMap((layout) =>\n            layout.islandStrategy ? [layout.islandStrategy] : [],\n          ),\n        ];\n        const islandStrategy = hydrationStrategies.every(\n          (strategy) => strategy === hydrationStrategies[0],\n        )\n          ? (hydrationStrategies[0] ?? \"load\")\n          : \"load\";\n        clientPages.push({\n          ...route,\n          relativePath,\n          pageShouldHydrate: metadata.shouldHydrate,\n          islandStrategy,\n          hasIsolatedClientBoundaries:\n            metadata.hasIsolatedClientBoundaries ||\n            applicableClientLayouts.some((layout) => layout.hasIsolatedClientBoundaries),\n          isolatedBoundaries: [\n            ...(metadata.hasIsolatedClientBoundaries ? metadata.isolatedBoundaries : []),\n            ...applicableClientLayouts\n              .filter((layout) => layout.hasIsolatedClientBoundaries)\n              .flatMap((layout) => layout.isolatedBoundaries),\n          ],\n        });\n        logger.info(`📱 Found hydratable route: ${route.pattern} -> ${route.modulePath}`);\n      }\n    } catch (error) {\n      logger.warn(`⚠️  Could not inspect route file ${route.modulePath}: ${error}`);\n    }\n  }\n\n  if (config.docs?.enabled && !adapterOwnsDocsRuntime) {\n    const docsEntry =\n      `/${config.docs.entry || \"docs\"}`.replace(/\\/+/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n    const applicableClientLayouts = clientLayouts.filter(\n      (layout) => layout.shouldHydrate && layoutAppliesToRoute(layout.pattern, docsEntry),\n    );\n    if (applicableClientLayouts.length > 0) {\n      const hydrationStrategies = applicableClientLayouts.flatMap((layout) =>\n        layout.islandStrategy ? [layout.islandStrategy] : [],\n      );\n      const islandStrategy = hydrationStrategies.every(\n        (strategy) => strategy === hydrationStrategies[0],\n      )\n        ? (hydrationStrategies[0] ?? \"load\")\n        : \"load\";\n      const docsPatterns =\n        docsEntry === \"/\" ? [\"/\", \"/[...slug]\"] : [docsEntry, `${docsEntry}/[...slug]`];\n      const docsClientRoutes = docsPatterns.map((pattern) => ({\n        pattern,\n        modulePath: \"\",\n        relativePath: \"\",\n        pageShouldHydrate: false,\n        islandStrategy,\n        hasIsolatedClientBoundaries: false,\n        isolatedBoundaries: [] as IsolatedClientBoundaryReference[],\n      }));\n\n      // Docs requests take precedence over app page routes on the server, so\n      // their synthetic layout-only entries must take precedence in the client\n      // route table as well.\n      clientPages.unshift(...docsClientRoutes);\n    }\n  }\n\n  const clientRouteSlots = routeSlots.filter((slot) => {\n    try {\n      return getClientModuleMetadata(slot.modulePath, root).shouldHydrate;\n    } catch (error) {\n      logger.warn(`⚠️  Could not inspect route slot ${slot.modulePath}: ${error}`);\n      return false;\n    }\n  });\n\n  logger.info(\n    `📱 Total hydratable routes detected: ${clientPages.length} pages, ${clientLayouts.filter((layout) => layout.shouldHydrate).length} layouts, and ${clientRouteSlots.length} slots`,\n  );\n\n  // Generate client hydration entry code\n  // Keep generated entries under the project so bare imports resolve through the\n  // application's node_modules, including isolated production-build fixtures.\n  const clientEntryRoot = path.join(root, \".farm\", \"tmp\");\n  await fs.mkdir(clientEntryRoot, { recursive: true });\n  const clientEntryDir = await fs.mkdtemp(path.join(clientEntryRoot, \"client-entry-\"));\n  const clientEntryPath = path.join(clientEntryDir, \"farm-client-entry.tsx\");\n  const clientHydrationCode = generateClientHydrationEntry(\n    clientPages,\n    clientLayouts,\n    clientRouteSlots,\n    root,\n    srcDir,\n    adapterOwnsDocsRuntime ? false : isFarmDocsSearchEnabled(config.docs),\n    adapterOwnsDocsRuntime ? undefined : resolveFarmDocsSearchClientModule(root),\n    config.docs?.enabled ? config.docs.entry : undefined,\n    adapterOwnsDocsRuntime ? config.docs.adapter?.react : undefined,\n    config.i18n,\n    config.plugins,\n    config.renderer,\n    config.publicRuntimeConfig,\n    config.trailingSlash,\n    getIntegrationProviders(config.integrations),\n    config.basePath,\n    generateClientCachePersistenceCode(resolveFarmClientCacheAdapterEntry(root, config.cache)),\n  );\n\n  // Write the client entry to a temporary file\n  await fs.writeFile(clientEntryPath, clientHydrationCode);\n\n  // Tailwind support:\n  // - If project has explicit PostCSS config, respect it.\n  // - Otherwise enable built-in @tailwindcss/vite (out of the box).\n  const hasScopedPostcssConfig = hasProjectPostcssConfig(root);\n  let postcssSearchPath: string | undefined;\n  let tailwindVitePlugin: any = undefined;\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, root, {\n    ssr: false,\n  });\n  if (hasScopedPostcssConfig) {\n    logger.info(\"📦 Using project PostCSS/Tailwind configuration\");\n  } else {\n    const postcssConfigPath = path.join(clientEntryDir, \"postcss.config.cjs\");\n    await fs.writeFile(postcssConfigPath, \"module.exports = { plugins: [] };\\n\");\n    postcssSearchPath = clientEntryDir;\n    try {\n      const tailwindVite = (await import(\"@tailwindcss/vite\")).default;\n      tailwindVitePlugin = adaptTailwindVitePlugin(tailwindVite(), productionVite.builder);\n      logger.info(\"📦 Enabled built-in Tailwind support (@tailwindcss/vite)\");\n    } catch (error) {\n      logger.warn(\n        `Tailwind plugin auto-enable failed; continuing without it: ${(error as Error).message}`,\n      );\n    }\n  }\n\n  try {\n    await viteBuild({\n      root,\n      // Vite otherwise falls back to <root>/public, silently dropping every\n      // asset in a custom config.publicDir from the production client output.\n      publicDir: config.publicDir,\n      esbuild: {\n        jsxDev: false,\n      },\n      build: {\n        // Preserve Farm's Vite 5 browser baseline when the production builder\n        // uses Vite 8, whose default target only covers newer browsers.\n        target: FARM_CLIENT_BUILD_TARGET,\n        outDir: outputDir,\n        emptyOutDir: true,\n        assetsInlineLimit: 0,\n        cssCodeSplit: false, // Bundle all CSS into one file\n        rollupOptions: {\n          input: {\n            \"farm-client\": clientEntryPath,\n          },\n          output: {\n            entryFileNames: \"[name]-h[hash].js\",\n            chunkFileNames: \"chunks/[name]-h[hash].js\",\n            hashCharacters: \"hex\",\n            // Use predictable name for CSS so we can reference it in SSR HTML\n            assetFileNames: (assetInfo) => {\n              if (assetInfo.name?.endsWith(\".css\")) {\n                return \"farm-client.css\";\n              }\n              return \"assets/[name]-h[hash][extname]\";\n            },\n          },\n          // Externalize Node.js built-ins and server-side modules for client build\n          external: (id) => {\n            // Externalize Node.js built-ins\n            if (\n              id.startsWith(\"node:\") ||\n              [\n                \"path\",\n                \"url\",\n                \"fs\",\n                \"fs/promises\",\n                \"os\",\n                \"crypto\",\n                \"http\",\n                \"https\",\n                \"net\",\n                \"stream\",\n                \"util\",\n                \"events\",\n                \"child_process\",\n                \"module\",\n                \"tty\",\n                \"dns\",\n              ].includes(id)\n            ) {\n              return true;\n            }\n            // Externalize native modules that can't be bundled for browser\n            if (id === \"fsevents\" || id.includes(\"fsevents\") || id.endsWith(\".node\")) {\n              return true;\n            }\n            return false;\n          },\n        },\n      },\n      plugins: [\n        createFarmThemeCssPlugin(config.theme, config.basePath),\n        ...(tailwindVitePlugin ? [tailwindVitePlugin] : []),\n        ...(rendererVitePlugins as any[]),\n        ...(config.vite.plugins || []),\n        // Plugin to redirect @farm.js/core imports to client-only exports\n        {\n          name: \"farm-client-only-imports\",\n          enforce: \"pre\" as const,\n          resolveId(id) {\n            // Redirect @farm.js/core to just export client-safe parts\n            // Don't redirect @farm.js/core/client - that's already client-safe\n            if (id === \"@farm.js/core\") {\n              return { id: \"\\0farm-client-exports\", external: false };\n            }\n            if (id === \"@farm.js/core/i18n/server\") {\n              return { id: \"\\0farm-i18n-client-bridge\", external: false };\n            }\n            // Block server-only imports completely\n            if (\n              id === \"@farm.js/core/server\" ||\n              id === \"@farm.js/core/api\" ||\n              id === \"@farm.js/core/middleware\" ||\n              id === \"@farm.js/core/headers\" ||\n              id === \"@farm.js/core/config\" ||\n              id.includes(\"@farm.js/core/middleware\") ||\n              id.includes(\"@farm.js/core/query/server\")\n            ) {\n              return { id: \"\\0empty-module\", external: false };\n            }\n            // Block API route imports (they come from type-only imports in api.generated.ts)\n            if (id.includes(\"/api/\") && id.includes(\"/route\")) {\n              return { id: \"\\0empty-api-route\", external: false };\n            }\n            // Block problematic node modules\n            if (\n              id === \"fsevents\" ||\n              id.includes(\"fsevents\") ||\n              id.endsWith(\".node\") ||\n              id === \"nitro\" ||\n              id === \"vite\" ||\n              id === \"vite-rolldown\" ||\n              id === \"esbuild\" ||\n              id === \"rollup\" ||\n              id.startsWith(\"nitro/\") ||\n              id.includes(\"node-pre-gyp\") ||\n              id.includes(\"nf3\")\n            ) {\n              return { id: \"\\0empty-module\", external: false };\n            }\n            return null;\n          },\n          load(id) {\n            if (id === \"\\0empty-module\") {\n              return \"const emptyMiddlewareStore = new Map(); export default {}; export const getMiddlewareContext = () => emptyMiddlewareStore; export const getMiddlewareData = () => emptyMiddlewareStore; export const getMiddlewareValue = () => undefined; export const middleware = () => ({});\";\n            }\n            if (id === \"\\0empty-api-route\") {\n              // Stub for API routes - only used in type context, provide empty exports\n              return \"export const GET = () => {}; export const HEAD = () => {}; export const QUERY = () => {}; export const POST = () => {}; export const PUT = () => {}; export const DELETE = () => {}; export const PATCH = () => {}; export const OPTIONS = () => {}; export default {};\";\n            }\n            if (id === \"\\0farm-i18n-client-bridge\") {\n              return 'export { createTranslator, format, getLocale, getLocaleSource, t } from \"@farm.js/core/i18n/client\";';\n            }\n            if (id === \"\\0farm-client-exports\") {\n              // Only export client-safe parts (no type exports - they're erased at compile time)\n              return [\n                \"// Farm.js Client Exports - Safe for browser bundling\",\n                'export { Link } from \"@farm.js/core/client\";',\n                'export { useRouter } from \"@farm.js/core/client\";',\n                'export { usePathname, useSearchParams } from \"@farm.js/core/navigation\";',\n                'export { createAPIClient } from \"@farm.js/core/client\";',\n                'export { localFont, remoteFont } from \"@farm.js/core/font\";',\n              ].join(\"\\n\");\n            }\n            return null;\n          },\n        },\n        farmPlugin({ ...config, isolatedClientBoundaryModules }, pluginManager),\n        farmEnvironmentFunctionsPlugin(),\n      ],\n      mode: \"production\",\n      css: postcssSearchPath\n        ? {\n            postcss: postcssSearchPath,\n          }\n        : undefined,\n      // Ensure React is bundled for client\n      resolve: {\n        alias: createFarmSourceAlias(root, config.srcDir),\n        dedupe: [...(config.renderer.dedupe || [])],\n      },\n      // Optimize dependencies - exclude server-side code from client bundle\n      optimizeDeps: {\n        exclude: [\n          \"@farm.js/core/server\",\n          \"@farm.js/core/api\",\n          \"@farm.js/core/middleware\",\n          \"@farm.js/core/headers\",\n        ],\n      },\n    });\n    await mergeBuiltFontCss(outputDir);\n    await validateClientBuildOutput(root, srcDir, outputDir);\n  } finally {\n    // Clean up temporary entry file\n    try {\n      await fs.rm(clientEntryDir, { recursive: true, force: true });\n    } catch {\n      // Ignore cleanup errors\n    }\n  }\n}\n\n/**\n * Generate client hydration entry that imports and hydrates client components\n */\nexport function generateUniversalRouterStateRuntime(): string {\n  return `\nconst FARM_PAGE_STATE_KEY = \"__farmPageState\";\nconst FARM_HISTORY_INDEX_KEY = \"__farmHistoryIndex\";\nconst IDLE_NAVIGATION_STATE = {\n  state: \"idle\",\n  pending: false,\n  from: null,\n  to: null,\n  action: null,\n  startedAt: null,\n};\n\nfunction createNavigationLocation(url) {\n  return {\n    href: url.href,\n    pathname: url.pathname,\n    search: url.search,\n    hash: url.hash,\n  };\n}\n\nfunction scrollElementStorageKey(pathname, key) {\n  return \"farm-scroll-\" + pathname + \":\" + key;\n}\n\nfunction createHistoryState(path, pageState, currentState) {\n  const base = currentState && typeof currentState === \"object\" ? { ...currentState } : {};\n  return {\n    ...base,\n    path,\n    [FARM_PAGE_STATE_KEY]: pageState,\n  };\n}\n\nasync function fetchFarmNavigationDocument(url, headers, recover = true, signal) {\n  const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n  const response = await fetch(url, {\n    headers: createFarmDeploymentRequestHeaders(deploymentId, headers),\n    signal,\n  });\n  if (isFarmDeploymentMismatchResponse(response, deploymentId)) {\n    const error = createFarmDeploymentMismatchError(response, deploymentId || \"unknown\");\n    window.dispatchEvent(new CustomEvent(\"farm:deployment-mismatch\", { detail: error }));\n    if (recover) window.location.assign(url);\n    throw error;\n  }\n  return response;\n}\n\nfunction clearFarmPrefetchCacheOnDeploymentMismatch(router, error) {\n  if (error?.name === \"FarmDeploymentMismatchError\") {\n    router.prefetchCache.clear();\n  }\n}\n\nfunction readHistoryIndex(state) {\n  if (!state || typeof state !== \"object\") return null;\n  const value = state[FARM_HISTORY_INDEX_KEY];\n  return Number.isSafeInteger(value) ? value : null;\n}\n\nfunction hasAbsoluteNavigationHref(href) {\n  return /^[a-zA-Z][a-zA-Z\\\\d+.-]*:/.test(href) || href.startsWith(\"//\");\n}\n`.trim();\n}\n\n/**\n * Path matcher emitted into the production runtime. Extracted so tests can\n * assert the emitted source decodes segments through the guarded helper;\n * a bare decodeURIComponent here throws URIError on malformed\n * percent-encoding out of route matching in deployed apps (#502).\n */\nexport function generateRuntimePathMatcherSource(): string {\n  return `\nfunction normalizeRuntimePath(pathname) {\n  if (!pathname || pathname === \"/\") return \"/\";\n  return pathname.endsWith(\"/\") ? pathname.replace(/\\\\/+$/, \"\") : pathname;\n}\n\nfunction splitRuntimePath(pathname) {\n  return normalizeRuntimePath(pathname).split(\"/\").filter(Boolean);\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    // Request paths are not guaranteed to be validly percent-encoded; a\n    // malformed segment must not throw out of route matching.\n    return segment;\n  }\n}\n\nconst farmCatchAllParamSegments = Symbol(\"farm.catch-all-param-segments\");\n\nfunction matchRuntimePathPattern(pattern, pathname) {\n  const patternSegments = splitRuntimePath(pattern);\n  const pathnameSegments = splitRuntimePath(pathname);\n  const params = {};\n  const catchAllParamSegments = {};\n  Object.defineProperty(params, farmCatchAllParamSegments, {\n    value: catchAllParamSegments,\n  });\n  let pathIndex = 0;\n\n  for (const segment of patternSegments) {\n    const optionalCatchAll = segment.match(/^\\\\[\\\\[\\\\.\\\\.\\\\.(.+)\\\\]\\\\]$/);\n    const catchAll = segment.match(/^\\\\[\\\\.\\\\.\\\\.(.+)\\\\]$/);\n    const dynamic = segment.match(/^\\\\[(.+)\\\\]$/);\n    const namedCatchAll = segment.match(/^:([^/]+)\\\\*$/);\n    const namedDynamic = segment.match(/^:([^/]+)$/);\n    const starCatchAll = segment.match(/^\\\\*([^?]+)(\\\\?)?$/);\n    const wildcard = segment === \"*\";\n\n    if (optionalCatchAll || catchAll || namedCatchAll || starCatchAll || wildcard) {\n      const name = wildcard\n        ? \"wildcard\"\n        : (optionalCatchAll || catchAll || namedCatchAll || starCatchAll)[1];\n      const remainingSegments = pathnameSegments.slice(pathIndex).map(decodeRouteSegment);\n      const remaining = remainingSegments.join(\"/\");\n      if (!remaining && (catchAll || (starCatchAll && !starCatchAll[2]))) return null;\n      params[name] = remaining;\n      catchAllParamSegments[name] = remainingSegments;\n      pathIndex = pathnameSegments.length;\n      continue;\n    }\n\n    const pathnameSegment = pathnameSegments[pathIndex];\n    if (pathnameSegment === undefined) return null;\n\n    if (dynamic || namedDynamic) {\n      params[(dynamic || namedDynamic)[1]] = decodeRouteSegment(pathnameSegment);\n      pathIndex++;\n      continue;\n    }\n\n    if (segment !== decodeRouteSegment(pathnameSegment)) return null;\n    pathIndex++;\n  }\n\n  return pathIndex === pathnameSegments.length ? params : null;\n}\n`.trim();\n}\n\nexport function generateRedirectInterpolationSource(): string {\n  // Interpolates redirect/rewrite destinations from the params produced by\n  // matchRuntimePathPattern. Must stay in parity with the development path in\n  // packages/farm/src/plugins/route-pattern.ts: named captures (:name, [name],\n  // catch-alls), a positional * for the wildcard param, and numbered captures\n  // ($1-based, in pattern order). Depends on farmCatchAllParamSegments from\n  // generateRuntimePathMatcherSource(), so emit that source alongside this one.\n  return `\nfunction encodeRuntimePathSegment(value) {\n  return encodeURIComponent(String(value)).replace(\n    /[!'()*]/g,\n    function(character) {\n      return \"%\" + character.charCodeAt(0).toString(16).toUpperCase();\n    },\n  );\n}\n\nfunction interpolateRedirectDestination(destination, params) {\n  let result = destination;\n  const catchAllParamSegments = params[farmCatchAllParamSegments] || {};\n  const orderedCaptures = [];\n  for (const [key, value] of Object.entries(params)) {\n    const segments = catchAllParamSegments[key];\n    const encodedValue = Array.isArray(segments)\n      ? segments.map(encodeRuntimePathSegment).join(\"/\")\n      : encodeRuntimePathSegment(value);\n    orderedCaptures.push(encodedValue);\n    result = result.split(\"[[...\" + key + \"]]\").join(encodedValue);\n    result = result.split(\"[...\" + key + \"]\").join(encodedValue);\n    result = result.split(\"[\" + key + \"]\").join(encodedValue);\n    result = result.split(\":\" + key + \"*\").join(encodedValue);\n    result = result.split(\":\" + key).join(encodedValue);\n    if (key === \"wildcard\") result = result.split(\"*\").join(encodedValue);\n  }\n  // Numbered captures resolve after the named substitutions. Encoded values\n  // never contain \"$\", so this cannot rewrite an already-injected value. An\n  // out-of-range index resolves to \"\", matching the development path.\n  result = result.replace(/\\\\$(\\\\d+)/g, function(_whole, group) {\n    const captured = orderedCaptures[Number(group) - 1];\n    return captured === undefined ? \"\" : captured;\n  });\n  return result;\n}\n`.trim();\n}\n\nexport function generateUniversalRouterStateProperties(): string {\n  return `\n  blockers: new Set(),\n  unloadBlockers: new Map(),\n  navigationListeners: new Set(),\n  navigationState: IDLE_NAVIGATION_STATE,\n  navigationSequence: 0,\n  activeNavigation: null,\n  observers: new Map(),\n  scrollElements: new Map(),\n  currentPath: window.location.pathname + window.location.search,\n  currentHistoryIndex: null,\n  currentHistoryState: null,\n\n  initializeHistory: function() {\n    const existingIndex = readHistoryIndex(window.history.state);\n    if (existingIndex != null) {\n      this.currentHistoryIndex = existingIndex;\n      this.currentHistoryState = window.history.state;\n      return;\n    }\n    try {\n      const initialState = {\n        ...(window.history.state && typeof window.history.state === \"object\"\n          ? window.history.state\n          : {}),\n        [FARM_HISTORY_INDEX_KEY]: 0,\n      };\n      window.history.replaceState(initialState, \"\", window.location.href);\n      this.currentHistoryIndex = 0;\n      this.currentHistoryState = initialState;\n    } catch {\n      this.currentHistoryIndex = null;\n      this.currentHistoryState = null;\n    }\n  },\n\n  getNavigationState: function() {\n    return this.navigationState;\n  },\n\n  subscribeNavigation: function(listener) {\n    this.navigationListeners.add(listener);\n    listener(this.navigationState);\n    return () => this.navigationListeners.delete(listener);\n  },\n\n  addBlocker: function(blocker, shouldBlockUnload) {\n    this.blockers.add(blocker);\n    this.unloadBlockers.set(blocker, shouldBlockUnload || (() => {\n      const result = blocker({ from: this.currentPath, to: this.currentPath, action: \"replace\" });\n      if (result && typeof result.then === \"function\") {\n        result.catch(() => undefined);\n        return true;\n      }\n      return result === true;\n    }));\n    return () => {\n      this.blockers.delete(blocker);\n      this.unloadBlockers.delete(blocker);\n    };\n  },\n\n  shouldBlockNavigation: async function(context) {\n    for (const blocker of this.blockers) {\n      if (await blocker(context)) return true;\n    }\n    return false;\n  },\n\n  shouldBlockUnload: function() {\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  handlePopState: function(event) {\n    if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n    return this.navigate(window.location.href, {\n      action: \"pop\",\n      scroll: false,\n      popState: event.state,\n    });\n  },\n\n  revertBlockedPopState: function(from) {\n    try {\n      const previousState = this.currentHistoryState;\n      const pageState = previousState && typeof previousState === \"object\"\n        ? previousState[FARM_PAGE_STATE_KEY]\n        : undefined;\n      const restoredState = createHistoryState(from, pageState, previousState);\n      if (this.currentHistoryIndex != null) {\n        restoredState[FARM_HISTORY_INDEX_KEY] = this.currentHistoryIndex;\n      }\n      window.history.pushState(restoredState, \"\", from);\n      this.currentHistoryState = restoredState;\n    } catch {}\n  },\n\n  startNavigation: function(from, to, action) {\n    this.activeNavigation?.controller.abort(\"superseded\");\n    const navigation = {\n      id: ++this.navigationSequence,\n      controller: new AbortController(),\n      clientNavigation: null,\n    };\n    this.activeNavigation = navigation;\n    this.setNavigationState({\n      state: \"loading\",\n      pending: true,\n      from,\n      to: createNavigationLocation(to),\n      action,\n      startedAt: Date.now(),\n    });\n    return navigation;\n  },\n\n  isCurrentNavigation: function(navigation, clientNavigation) {\n    return this.activeNavigation?.id === navigation.id &&\n      !navigation.controller.signal.aborted &&\n      !clientNavigation?.signal.aborted;\n  },\n\n  finishNavigation: function(navigation) {\n    if (this.activeNavigation?.id !== navigation.id) return;\n    this.activeNavigation = null;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  },\n\n  cancelActiveNavigation: function() {\n    if (!this.activeNavigation) return;\n    farmClientRuntime.cancelNavigation(\n      this.activeNavigation.clientNavigation || undefined,\n      \"superseded\",\n    );\n    this.activeNavigation.controller.abort(\"superseded\");\n    this.activeNavigation = null;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  },\n\n  clearPrefetchedPath: function(url) {\n    const interceptionPrefix = url + \"\\\\nintercept:\";\n    for (const key of this.prefetchCache.keys()) {\n      if (key === url || key.startsWith(interceptionPrefix)) {\n        this.prefetchCache.delete(key);\n      }\n    }\n  },\n\n  setNavigationState: function(state) {\n    this.navigationState = state;\n    for (const listener of this.navigationListeners) listener(state);\n  },\n\n  pushState: function(state, href) {\n    this.writePageState(\"push\", state, href);\n  },\n\n  replaceState: function(state, href) {\n    this.writePageState(\"replace\", state, href);\n  },\n\n  writePageState: function(action, state, href) {\n    const url = new URL(href || window.location.href, window.location.origin);\n    this.writeHistoryEntry(action, url.pathname + url.search + url.hash, state, url, \"page-state\");\n  },\n\n  writeURLSearch: function(action, href) {\n    const url = new URL(href || window.location.href, window.location.origin);\n    const currentState = window.history.state;\n    const pageState = currentState && typeof currentState === \"object\"\n      ? currentState[FARM_PAGE_STATE_KEY]\n      : undefined;\n    this.writeHistoryEntry(\n      action,\n      url.pathname + url.search + url.hash,\n      pageState,\n      url,\n      \"url-search\",\n      false,\n    );\n    this.currentPath = url.pathname + url.search;\n  },\n\n  writeHistoryEntry: function(action, path, pageState, url, changeKind = \"url-search\", notify = true) {\n    if (action === \"pop\") return;\n    const nextState = createHistoryState(path, pageState, window.history.state);\n    const nextIndex = this.currentHistoryIndex == null\n      ? null\n      : action === \"replace\"\n        ? this.currentHistoryIndex\n        : this.currentHistoryIndex + 1;\n    if (nextIndex != null) nextState[FARM_HISTORY_INDEX_KEY] = nextIndex;\n    if (action === \"replace\") window.history.replaceState(nextState, \"\", url);\n    else window.history.pushState(nextState, \"\", url);\n    this.currentHistoryIndex = nextIndex;\n    this.currentHistoryState = nextState;\n    // Announce programmatic history writes without synthesizing popstate,\n    // which the router reserves for real back/forward navigation.\n    if (notify) {\n      window.dispatchEvent(\n        new CustomEvent(\"farm:historychange\", { detail: { kind: changeKind } }),\n      );\n    }\n  },\n\n  registerScrollElement: function(key, element) {\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) this.scrollElements.delete(key);\n    };\n  },\n\n  saveScrollPosition: function(pathname) {\n    try {\n      sessionStorage.setItem(\n        \"farm-scroll-\" + pathname,\n        JSON.stringify({ x: window.scrollX, y: window.scrollY }),\n      );\n      for (const [key, element] of this.scrollElements) {\n        sessionStorage.setItem(\n          scrollElementStorageKey(pathname, key),\n          JSON.stringify({ x: element.scrollLeft, y: element.scrollTop }),\n        );\n      }\n    } catch {}\n  },\n\n  restoreScrollPosition: function(pathname) {\n    try {\n      const saved = sessionStorage.getItem(\"farm-scroll-\" + pathname);\n      if (saved) {\n        const position = JSON.parse(saved);\n        setTimeout(() => window.scrollTo(position.x, position.y), 0);\n      }\n      for (const [key, element] of this.scrollElements) {\n        this.restoreScrollElement(pathname, key, element);\n      }\n    } catch {}\n  },\n\n  restoreScrollElement: function(pathname, key, element) {\n    try {\n      const saved = sessionStorage.getItem(scrollElementStorageKey(pathname, key));\n      if (!saved) return;\n      const position = JSON.parse(saved);\n      setTimeout(() => {\n        element.scrollLeft = position.x;\n        element.scrollTop = position.y;\n      }, 0);\n    } catch {}\n  },\n\n  runViewTransition: async function(enabled, callback) {\n    const startViewTransition = document.startViewTransition;\n    if (!enabled || typeof startViewTransition !== \"function\") {\n      await callback();\n      return;\n    }\n    const transition = startViewTransition.call(document, () => callback());\n    await transition.finished;\n  },\n`.trim();\n}\n\nfunction generateClientHydrationEntry(\n  clientPages: Array<{\n    pattern: string;\n    modulePath: string;\n    relativePath: string;\n    pageShouldHydrate: boolean;\n    islandStrategy: FarmIslandStrategy;\n    hasIsolatedClientBoundaries: boolean;\n    isolatedBoundaries: IsolatedClientBoundaryReference[];\n  }>,\n  layoutRoutes: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries: boolean;\n    isolatedBoundaries: IsolatedClientBoundaryReference[];\n  }>,\n  clientRouteSlots: UniversalRouteSlot[],\n  root: string,\n  srcDir: string,\n  docsSearchEnabled: boolean,\n  docsSearchModuleId: string | undefined,\n  docsEntryPath: string | undefined,\n  docsAdapterReact: string | undefined,\n  i18nConfig: ResolvedFarmConfig[\"i18n\"] = {\n    enabled: false,\n    basePath: \"/\",\n    locales: [\"en\"],\n    defaultLocale: \"en\",\n    messages: \"\",\n    routing: \"none\",\n    detection: [],\n    fallbackLocale: \"en\",\n    strict: false,\n    cookie: {\n      name: \"farm_locale\",\n      maxAge: 0,\n      path: \"/\",\n      sameSite: \"lax\",\n      secure: false,\n    },\n    direction: {},\n  },\n  plugins: readonly FarmPlugin[] = [],\n  renderer: FarmRenderer = REACT_RENDERER,\n  publicRuntimeConfig: Record<string, unknown> | undefined = undefined,\n  trailingSlash = false,\n  integrationProviders: ReturnType<typeof getIntegrationProviders> = [],\n  basePath = \"/\",\n  clientCachePersistence: ClientCachePersistenceEntryCode = { imports: \"\", init: \"\" },\n): string {\n  const toImportPath = (targetPath: string) => targetPath.replace(/\\\\/g, \"/\");\n  const clientPluginEntry: FarmClientPluginEntryCode = generateFarmClientPluginEntryCode(\n    plugins,\n    root,\n    srcDir,\n    publicRuntimeConfig,\n  );\n  const rendererClientImports = isReactRenderer(renderer)\n    ? `import React from \"react\";\\nimport { createRoot, hydrateRoot } from \"react-dom/client\";`\n    : `import React, { createRoot, hydrateRoot } from ${JSON.stringify(renderer.client)};`;\n  const providerClientCode = generateFarmIntegrationProviderClientCode(integrationProviders, root);\n\n  // Import global CSS (the Tailwind entry) only when the app ships one; an\n  // unconditional import of a missing file fails the client build with\n  // UNRESOLVED_IMPORT. Output validation already treats a missing globals.css\n  // as an intentionally style-free application.\n  const globalsCssPath = path.join(root, srcDir, \"app\", \"globals.css\");\n  const cssImport = existsSync(globalsCssPath)\n    ? `import ${JSON.stringify(toImportPath(globalsCssPath))};`\n    : \"\";\n\n  // Import layouts for wrapping client components\n  const layoutImportStatements: string[] = [];\n  const layoutRegistrations: string[] = [];\n\n  layoutRoutes.forEach((layout, index) => {\n    const relativePath = toImportPath(layout.modulePath);\n    if (!layout.hasIsolatedClientBoundaries) {\n      layoutImportStatements.push(`import Layout${index} from \"${relativePath}\";`);\n    }\n    layoutRegistrations.push(\n      `  { pattern: ${JSON.stringify(layout.pattern)}, Component: ${layout.hasIsolatedClientBoundaries ? \"null\" : `Layout${index}`}, shouldHydrate: ${JSON.stringify(layout.shouldHydrate)}, islandStrategy: ${JSON.stringify(layout.islandStrategy)} }`,\n    );\n  });\n\n  const layoutImports = layoutImportStatements.join(\"\\n\");\n  const i18nRoutingConfig = {\n    locales: i18nConfig.locales,\n    defaultLocale: i18nConfig.defaultLocale,\n    routing: i18nConfig.routing,\n  };\n  const i18nClientRuntime = i18nConfig.enabled\n    ? `\nimport { stripFarmLocaleFromPathname } from \"@farm.js/core/i18n\";\nimport { _setFarmI18nClientSnapshot } from \"@farm.js/core/i18n/client\";\n\nconst farmI18nConfig = ${JSON.stringify(i18nRoutingConfig)};\nif (window.__FARM_I18N__) {\n  _setFarmI18nClientSnapshot(window.__FARM_I18N__);\n}\n\nfunction getFarmRoutePathname(pathname) {\n  return stripFarmLocaleFromPathname(stripFarmBasePath(pathname), farmI18nConfig);\n}\n\nfunction isFarmLocaleDocumentChange(doc) {\n  const currentLocale = window.__FARM_I18N__?.locale || document.documentElement.lang;\n  const nextLocale = doc.documentElement?.lang;\n  return Boolean(currentLocale && nextLocale && currentLocale !== nextLocale);\n}\n`\n    : `\nfunction getFarmRoutePathname(pathname) {\n  return stripFarmBasePath(pathname);\n}\n\nfunction isFarmLocaleDocumentChange() {\n  return false;\n}\n`;\n  const docsNavigationRuntime = docsEntryPath\n    ? `\nconst farmDocsEntryPath = ${JSON.stringify(docsEntryPath)};\nfunction isFarmDocsPath(pathname) {\n  const routePathname = getFarmRoutePathname(pathname);\n  const normalizedPath = routePathname.length > 1 ? routePathname.replace(/\\\\/+$/, \"\") : routePathname;\n  return normalizedPath === farmDocsEntryPath || normalizedPath.startsWith(farmDocsEntryPath + \"/\");\n}\n`\n    : `\nfunction isFarmDocsPath() {\n  return false;\n}\n`;\n  const docsAdapterRuntime = docsAdapterReact\n    ? `\nimport * as FarmDocsAdapterReact from ${JSON.stringify(docsAdapterReact)};\n\nasync function hydrateFarmDocsAdapterRuntime() {\n  const runtime = window.__FARM_DOCS_ADAPTER__;\n  if (!runtime) return false;\n  if (typeof FarmDocsAdapterReact.hydrateFarmDocs !== \"function\") {\n    throw new Error(\"The configured Farm docs adapter does not export hydrateFarmDocs().\");\n  }\n  FarmDocsAdapterReact.hydrateFarmDocs({\n    config: runtime.config || {},\n    data: runtime.data,\n  });\n  return true;\n}\n`\n    : `\nasync function hydrateFarmDocsAdapterRuntime() {\n  return false;\n}\n`;\n\n  if (\n    clientPages.length === 0 &&\n    clientRouteSlots.length === 0 &&\n    !providerClientCode.hasProviders\n  ) {\n    // No client pages - just basic runtime with CSS and SPA navigation\n    return `\n// Farm.js Client Runtime (no client components)\n${cssImport}\n${layoutImports}\nimport { createClientPluginManager, getHashTargetElement, installChunkErrorRecovery, isFarmExternalNavigationURL, reconcileFarmDocumentHead, setFarmBasePath, setFarmTrailingSlashPreference, stripFarmBasePath } from \"@farm.js/core/internal/client-runtime\";\nimport { createFarmDeploymentMismatchError, createFarmDeploymentRequestHeaders, isFarmDeploymentMismatchResponse } from \"@farm.js/core/deployment\";\n${clientPluginEntry.imports}\n${clientCachePersistence.imports}\n${i18nClientRuntime}\n${docsNavigationRuntime}\n${docsAdapterRuntime}\n${generateFarmDocsSearchClientRuntime(docsSearchEnabled, docsSearchModuleId)}\n\nsetFarmBasePath(${JSON.stringify(basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(trailingSlash)});\ninstallChunkErrorRecovery();\n${clientCachePersistence.init}\nmountFarmDocsSearch();\n\n${generateUniversalRouterStateRuntime()}\n\n// SPA Router for server-rendered pages (HTML swap)\nconst spaRouter = {\n${generateUniversalRouterStateProperties()}\n  prefetchCache: new Map(),\n  \n  navigate: async function(href, options = {}) {\n    const url = new URL(href, window.location.origin);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n    if (isFarmDocsPath(url.pathname)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n\n    const action = options.action || (options.replace ? \"replace\" : \"push\");\n    const to = url.pathname + url.search;\n    if (!options.refresh && action !== \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      if (url.hash === window.location.hash) return;\n      const pageState = options.state === undefined\n        ? window.history.state?.[FARM_PAGE_STATE_KEY]\n        : options.state;\n      this.writeHistoryEntry(action, to, pageState, url);\n      if (options.scroll !== false) {\n        if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      }\n      return;\n    }\n    if (action === \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n      return;\n    }\n\n    const from = this.currentPath;\n    if (await this.shouldBlockNavigation({ from, to, action })) {\n      if (action === \"pop\") this.revertBlockedPopState(from);\n      return;\n    }\n    if (action === \"pop\") {\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n    }\n\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n    const navigation = this.startNavigation(from, url, action);\n    let clientNavigation;\n    try {\n      clientNavigation = await farmClientRuntime.beginNavigation({\n        from: action === \"pop\" ? null : window.location.href,\n        to: url,\n        action,\n      });\n      navigation.clientNavigation = clientNavigation;\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      const html = await this.fetchPage(\n        url.pathname + url.search,\n        options.refresh === true,\n        true,\n        navigation.controller.signal,\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      await farmClientRuntime.markNavigationLoaded(clientNavigation, html);\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      await this.runViewTransition(options.viewTransition, async () => {\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        if (!this.swapContent(html)) {\n          throw new Error(\"Farm could not swap the target document\");\n        }\n        this.writeHistoryEntry(action, url.pathname + url.search, options.state, url);\n        this.currentPath = to;\n        if (options.scroll !== false) {\n          if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n          else window.scrollTo(0, 0);\n        } else {\n          this.restoreScrollPosition(to);\n        }\n      });\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      await farmClientRuntime.resolveNavigation(clientNavigation);\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await farmClientRuntime.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      if (error?.name === \"FarmDeploymentMismatchError\") return;\n      console.error(\"[Farm.js] Navigation error:\", error);\n      if (action === \"pop\") window.location.reload();\n      else window.location.href = href;\n    }\n  },\n\n  refresh: function(options = {}) {\n    return this.navigate(window.location.href, {\n      ...options,\n      action: \"replace\",\n      replace: true,\n      refresh: true,\n      scroll: options.scroll === undefined ? false : options.scroll,\n    });\n  },\n  \n  fetchPage: async function(url, fresh = false, recover = true, signal) {\n    if (fresh) this.clearPrefetchedPath(url);\n    const cached = fresh ? undefined : this.prefetchCache.get(url);\n    if (cached) return cached;\n    \n    const response = await fetchFarmNavigationDocument(\n      url,\n      { \"Accept\": \"text/html\" },\n      recover,\n      signal,\n    );\n    if (!response.ok) throw new Error(\"Failed to fetch page\");\n    return response.text();\n  },\n  \n  swapContent: function(html) {\n    const parser = new DOMParser();\n    const doc = parser.parseFromString(html, \"text/html\");\n    if (isFarmLocaleDocumentChange(doc)) return false;\n    if (doc.getElementById(\"nd-docs-layout\")) return false;\n    \n    reconcileFarmDocumentHead(doc);\n    \n    // Swap root content\n    const newRoot = doc.getElementById(\"root\");\n    const currentRoot = document.getElementById(\"root\");\n    if (!newRoot || !currentRoot) return this.swapDocument(doc);\n    currentRoot.innerHTML = newRoot.innerHTML;\n    return true;\n  },\n\n  swapDocument: function(doc) {\n    if (!doc.documentElement || !doc.body) return false;\n\n    Array.from(document.documentElement.attributes).forEach(function(attr) {\n      if (!doc.documentElement.hasAttribute(attr.name)) {\n        document.documentElement.removeAttribute(attr.name);\n      }\n    });\n    Array.from(doc.documentElement.attributes).forEach(function(attr) {\n      document.documentElement.setAttribute(attr.name, attr.value);\n    });\n\n    document.head.innerHTML = doc.head ? doc.head.innerHTML : \"\";\n    document.body.innerHTML = doc.body.innerHTML;\n    delete window.__farmDocsRuntime;\n    delete window.__farmDocsPageActionsRuntime;\n\n    setTimeout(function() {\n      Array.from(document.querySelectorAll(\"script\")).forEach(function(script) {\n        const freshScript = document.createElement(\"script\");\n        Array.from(script.attributes).forEach(function(attr) {\n          freshScript.setAttribute(attr.name, attr.value);\n        });\n        freshScript.textContent = script.textContent || \"\";\n        script.replaceWith(freshScript);\n      });\n    }, 0);\n\n    return true;\n  },\n  prefetch: function(href) {\n    const url = new URL(href, window.location.origin);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) return;\n    if (isFarmDocsPath(url.pathname)) return;\n    \n    const pathname = url.pathname + url.search;\n    if (this.prefetchCache.has(pathname)) return;\n    \n    this.fetchPage(pathname, false, false)\n      .then(function(html) { spaRouter.prefetchCache.set(pathname, html); })\n      .catch(function(error) {\n        clearFarmPrefetchCacheOnDeploymentMismatch(spaRouter, error);\n      });\n  },\n\n  clearCache: function() {\n    this.prefetchCache.clear();\n  },\n  \n  observeForPrefetch: function(element) {\n    if (!(\"IntersectionObserver\" in window)) return;\n\n    const href = element.getAttribute(\"href\");\n    if (!href) return;\n\n    const observer = new IntersectionObserver(function(entries) {\n      entries.forEach(function(entry) {\n        if (entry.isIntersecting) {\n          spaRouter.prefetch(href);\n          observer.disconnect();\n          spaRouter.observers.delete(element);\n        }\n      });\n    }, { rootMargin: \"50px\" });\n\n    observer.observe(element);\n    this.observers.set(element, observer);\n  },\n\n  unobserveForPrefetch: function(element) {\n    const observer = this.observers.get(element);\n    if (!observer) return;\n    observer.unobserve(element);\n    observer.disconnect();\n    this.observers.delete(element);\n  }\n};\n\nconst farmClientRuntime = createClientPluginManager(\n  ${clientPluginEntry.registrations},\n  {\n    router: spaRouter,\n    isDev: false,\n    isProd: true,\n    deploymentId: window.__FARM_DEPLOYMENT_ID__,\n  },\n);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\n// Expose router globally\nspaRouter.initializeHistory();\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nvoid hydrateFarmDocsAdapterRuntime();\n\nwindow.addEventListener(\"beforeunload\", function(event) {\n  if (spaRouter.shouldBlockUnload()) {\n    event.preventDefault();\n    event.returnValue = \"\";\n  }\n  spaRouter.saveScrollPosition(window.location.pathname + window.location.search);\n});\n\n// Handle popstate (back/forward)\nwindow.addEventListener(\"popstate\", function(event) {\n  void spaRouter.handlePopState(event);\n});\n\n// Intercept link clicks\ndocument.addEventListener(\"click\", function(e) {\n  const target = e.target;\n  const anchor = target.closest ? target.closest(\"a\") : null;\n  if (!anchor) return;\n  \n  const href = anchor.getAttribute(\"href\");\n  if (!href) return;\n  if (anchor.hasAttribute(\"download\")) return;\n  if (hasAbsoluteNavigationHref(href)) return;\n  if (href.startsWith(\"#\")) return;\n  if (anchor.target && anchor.target !== \"_self\") return;\n  if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n  if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;\n  if (e.button !== 0) return;\n  if (e.defaultPrevented) return;\n  \n  e.preventDefault();\n  spaRouter.navigate(href);\n});\n`.trim();\n  }\n\n  // Generate imports for client components\n  const imports: string[] = [];\n  const routeEntries: string[] = [];\n  const routeSlotEntries: string[] = [];\n  const isolatedBoundaryModules = new Map<string, string>();\n\n  clientPages.forEach((page) => {\n    for (const boundary of page.isolatedBoundaries) {\n      isolatedBoundaryModules.set(\n        toViteModuleId(boundary.modulePath, root),\n        toImportPath(boundary.modulePath),\n      );\n    }\n    const load = page.pageShouldHydrate\n      ? `() => import(${JSON.stringify(toImportPath(page.modulePath))}).then((module) => module.default)`\n      : \"null\";\n    routeEntries.push(`  {\n    pattern: ${JSON.stringify(page.pattern)},\n    pageShouldHydrate: ${JSON.stringify(page.pageShouldHydrate)},\n    ${page.hasIsolatedClientBoundaries ? \"hasIsolatedClientBoundaries: true,\" : \"\"}\n    islandStrategy: ${JSON.stringify(page.islandStrategy)},\n    navigation: \"html-fragment\",\n    load: ${load},\n  }`);\n  });\n  const isolatedHydrationEnabled = isolatedBoundaryModules.size > 0;\n  const isolatedHydrationImport = isolatedHydrationEnabled\n    ? `import { createFarmIsolatedHydrationRuntime, wrapFarmIsolatedClientGraph } from \"@farm.js/core/internal/isolated-boundary\";`\n    : \"\";\n  const isolatedHydrationRuntime = isolatedHydrationEnabled\n    ? `const farmIsolatedBoundaryLoaders = {\n${Array.from(isolatedBoundaryModules.entries())\n  .map(\n    ([reference, modulePath]) =>\n      `  ${JSON.stringify(reference)}: () => import(${JSON.stringify(modulePath)}),`,\n  )\n  .join(\"\\n\")}\n};\nconst farmIsolatedHydrationRuntime = createFarmIsolatedHydrationRuntime({\n  ReactRuntime: React,\n  hydrateRoot,\n  load: async function(reference) {\n    const loader = farmIsolatedBoundaryLoaders[reference];\n    if (!loader) throw new Error(\"isolated client boundary loader was not found: \" + reference);\n    return loader();\n  },\n  schedule: scheduleFarmIslandHydration,\n  wrap: wrapWithIntegrationProviders,\n});\n\nfunction disposeFarmIsolatedClientBoundaries(scope) {\n  farmIsolatedHydrationRuntime.dispose(scope);\n}\n\nasync function hydrateFarmIsolatedClientBoundaries(scope = document, signal) {\n  await farmIsolatedHydrationRuntime.hydrate(scope, signal);\n}`\n    : \"\";\n  const routeClientGraphRuntime = isolatedHydrationEnabled\n    ? `function wrapFarmRouteClientGraph(element) {\n  return wrapFarmIsolatedClientGraph(React, element);\n}`\n    : `function wrapFarmRouteClientGraph(element) { return element; }`;\n  clientRouteSlots.forEach((slot, index) => {\n    const importPath = toImportPath(slot.modulePath);\n    imports.push(`import RouteSlot${index} from \"${importPath}\";`);\n    routeSlotEntries.push(`  {\n    name: ${JSON.stringify(slot.name)},\n    ownerPattern: ${JSON.stringify(slot.ownerPattern)},\n    pattern: ${JSON.stringify(slot.pattern)},\n    containerId: ${JSON.stringify(slot.containerId)},\n    interception: ${JSON.stringify(slot.interception)},\n    fallback: ${JSON.stringify(slot.fallback)},\n    Component: RouteSlot${index},\n  }`);\n  });\n\n  // Full SPA client with hydration for client components\n  return `\n// Farm.js Client Runtime - SPA with Hydration\n${cssImport}\n${layoutImports}\n${rendererClientImports}\n${isolatedHydrationImport}\n${providerClientCode.imports}\nimport { createClientPluginManager, getHashTargetElement, installChunkErrorRecovery, isFarmExternalNavigationURL, reconcileFarmDocumentHead, scheduleFarmIslandHydration, searchParamsToObject, setFarmBasePath, setFarmTrailingSlashPreference, stripFarmBasePath } from \"@farm.js/core/internal/client-runtime\";\nimport { createFarmDeploymentMismatchError, createFarmDeploymentRequestHeaders, isFarmDeploymentMismatchResponse } from \"@farm.js/core/deployment\";\nimport { isFarmRouteActive, matchFarmRoute } from \"@farm.js/core/router\";\n${clientPluginEntry.imports}\n${clientCachePersistence.imports}\n${i18nClientRuntime}\n${docsNavigationRuntime}\n${docsAdapterRuntime}\n\n${imports.join(\"\\n\")}\n${generateFarmDocsSearchClientRuntime(docsSearchEnabled, docsSearchModuleId)}\n\n${providerClientCode.runtime}\n\nsetFarmBasePath(${JSON.stringify(basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(trailingSlash)});\ninstallChunkErrorRecovery();\n${clientCachePersistence.init}\n\n// Client component routes\nconst clientRoutes = [\n${routeEntries.join(\",\\n\")}\n];\n\n${isolatedHydrationRuntime}\n${routeClientGraphRuntime}\n\nconst clientRouteSlots = [\n${routeSlotEntries.join(\",\\n\")}\n];\n\n// Layout routes for wrapping client components\nconst layoutRoutes = [\n${layoutRegistrations.join(\",\\n\")}\n];\n\n// Get applicable layouts for a pathname (sorted by depth, root first)\nfunction getApplicableLayouts(pathname) {\n  const applicable = [];\n  const normalizedPath = getFarmRoutePathname(pathname).replace(/\\\\/$/, '') || '/';\n  \n  for (const layout of layoutRoutes) {\n    if (layout.pattern === '/' || isFarmRouteActive(layout.pattern, normalizedPath, { exact: false })) {\n      applicable.push(layout);\n    }\n  }\n  \n  // Sort by depth (root first)\n  applicable.sort(function(a, b) {\n    const depthA = a.pattern.split('/').filter(Boolean).length;\n    const depthB = b.pattern.split('/').filter(Boolean).length;\n    return depthA - depthB;\n  });\n  \n  return applicable;\n}\n\nfunction hasHydratableLayout(pathname) {\n  return getApplicableLayouts(pathname).some(function(layout) {\n    return layout.shouldHydrate === true;\n  });\n}\n\n// Wrap a page element with applicable layouts\nfunction wrapWithLayouts(pageElement, pathname, params) {\n  const layouts = getApplicableLayouts(pathname);\n  let wrapped = pageElement;\n  \n  // Wrap from innermost to outermost (reverse order since layouts are root-first)\n  for (let i = layouts.length - 1; i >= 0; i--) {\n    const layout = layouts[i];\n    const LayoutComponent = layout.Component;\n    if (LayoutComponent) {\n      wrapped = React.createElement(LayoutComponent, { children: wrapped, params: params });\n      wrapped = React.createElement(\n        \"div\",\n        {\n          \"data-farm-layout-boundary\": \"true\",\n          \"data-farm-layout-pattern\": layout.pattern,\n          style: { display: \"contents\" },\n        },\n        wrapped,\n      );\n    }\n  }\n  \n  return wrapped;\n}\n\nfunction createLayoutPageBoundary(route, pageElement, serverHtml) {\n  const props = {\n    id: \"__farm_page__\",\n    \"data-farm-client\": route.pageShouldHydrate ? \"true\" : \"false\",\n    \"data-farm-layout-client\": \"true\",\n    \"data-farm-island\": \"page\",\n    \"data-farm-island-strategy\": route.islandStrategy || \"load\",\n  };\n  if (typeof serverHtml === \"string\") {\n    props.suppressHydrationWarning = true;\n    props.dangerouslySetInnerHTML = { __html: serverHtml };\n    return React.createElement(\"div\", props);\n  }\n  return React.createElement(\"div\", props, pageElement);\n}\n\n// Match pathname to client route\nfunction matchRoute(pathname) {\n  pathname = getFarmRoutePathname(pathname);\n  for (const route of clientRoutes) {\n    const params = matchFarmRoute(route.pattern, pathname);\n    if (params !== null) return { route: route, params: params };\n  }\n  return null;\n}\n\nasync function loadRouteComponent(route) {\n  if (!route.load) return null;\n  if (route.Component) return route.Component;\n  route.Component = await route.load();\n  return route.Component;\n}\n\nasync function createMatchedHydrationElement(matched, pathname, searchParams, serverHtml) {\n  const hydrateLayouts = hasHydratableLayout(pathname);\n  const params = matched.params;\n  let pageElement = null;\n\n  if (matched.route.pageShouldHydrate) {\n    const Component = await loadRouteComponent(matched.route);\n    if (!Component) return null;\n    if (typeof Component === \"function\" && Component.constructor && Component.constructor.name === \"AsyncFunction\") {\n      console.warn(\n        \"[Farm.js] Skipping hydration for \" + pathname +\n        \": async server components cannot run in the browser. Server-rendered HTML is preserved.\"\n      );\n      return null;\n    }\n    const props = { params: params, searchParams: Promise.resolve(searchParams) };\n    pageElement = React.createElement(Component, props);\n  } else if (hydrateLayouts) {\n    const serverPage = document.getElementById(\"__farm_page__\");\n    pageElement = createLayoutPageBoundary(\n      matched.route,\n      null,\n      typeof serverHtml === \"string\" ? serverHtml : serverPage ? serverPage.innerHTML : \"\",\n    );\n  }\n\n  if (!pageElement) return null;\n  if (!hydrateLayouts) {\n    return wrapFarmRouteClientGraph(wrapWithIntegrationProviders(pageElement));\n  }\n  if (matched.route.pageShouldHydrate) {\n    pageElement = createLayoutPageBoundary(matched.route, pageElement);\n  }\n  return wrapFarmRouteClientGraph(\n    wrapWithIntegrationProviders(wrapWithLayouts(pageElement, pathname, params)),\n  );\n}\n\nfunction matchesRoutePrefix(pathname, pattern) {\n  return pattern === \"/\" ||\n    isFarmRouteActive(pattern, getFarmRoutePathname(pathname), { exact: false });\n}\n\nfunction matchInterceptedRouteSlot(pathname, from) {\n  for (const slot of clientRouteSlots) {\n    if (!slot.interception || !matchesRoutePrefix(from, slot.ownerPattern)) continue;\n    const params = matchFarmRoute(slot.pattern, getFarmRoutePathname(pathname));\n    if (params !== null) return { slot: slot, params: params };\n  }\n  return null;\n}\n\nfunction routeSlotKey(slot) {\n  return slot.ownerPattern + \":\" + slot.name;\n}\n\nfunction findClientRouteSlot(slot) {\n  return clientRouteSlots.find(function(candidate) {\n    return candidate.name === slot.name &&\n      candidate.ownerPattern === slot.ownerPattern &&\n      candidate.pattern === slot.pattern &&\n      candidate.interception === slot.interception &&\n      candidate.fallback === slot.fallback;\n  });\n}\n\nfunction readRouteSlotPayload(doc) {\n  const script = doc.getElementById(\"__farm_route_slots_data__\");\n  if (!script?.textContent) return [];\n  try {\n    const parsed = JSON.parse(script.textContent);\n    return Array.isArray(parsed) ? parsed : [];\n  } catch {\n    return [];\n  }\n}\n\nconst routeSlotRoots = new Map();\nlet activeRouteInterception = null;\n\nfunction resetRouteSlotRoots() {\n  for (const root of routeSlotRoots.values()) {\n    try { root.unmount(); } catch {}\n  }\n  routeSlotRoots.clear();\n  activeRouteInterception = null;\n}\n\nfunction renderClientRouteSlot(slot, registration, mode) {\n  const container = document.getElementById(slot.containerId);\n  if (!container || !registration?.Component) return false;\n  const key = routeSlotKey(slot);\n  const existingRoot = routeSlotRoots.get(key);\n  const props = slot.props && typeof slot.props === \"object\" ? slot.props : {};\n  const element = wrapFarmRouteClientGraph(\n    wrapWithIntegrationProviders(React.createElement(registration.Component, props)),\n  );\n\n  if (mode === \"hydrate\") {\n    if (existingRoot) return true;\n    const root = hydrateRoot(container, element);\n    routeSlotRoots.set(key, root);\n    return true;\n  }\n\n  if (existingRoot) {\n    try { existingRoot.unmount(); } catch {}\n    routeSlotRoots.delete(key);\n  } else {\n    container.replaceChildren();\n  }\n  const root = createRoot(container);\n  root.render(element);\n  routeSlotRoots.set(key, root);\n  return true;\n}\n\nfunction hydrateInitialRouteSlots() {\n  const slots = Array.isArray(window.__FARM_ROUTE_SLOTS__)\n    ? window.__FARM_ROUTE_SLOTS__\n    : [];\n  for (const slot of slots) {\n    const registration = findClientRouteSlot(slot);\n    if (!registration) continue;\n    try {\n      renderClientRouteSlot(slot, registration, \"hydrate\");\n    } catch (error) {\n      console.warn(\"[Farm.js] Could not hydrate route slot:\", slot.name, error);\n    }\n  }\n}\n\nfunction renderRouteInterception(slot, registration, from, nextDocument) {\n  const container = document.getElementById(slot.containerId);\n  if (!container || !registration?.Component) return false;\n  const key = routeSlotKey(slot);\n  const previousSlot = (window.__FARM_ROUTE_SLOTS__ || []).find(function(candidate) {\n    return routeSlotKey(candidate) === key;\n  }) || null;\n  const previousHtml = container.innerHTML;\n\n  reconcileFarmDocumentHead(nextDocument);\n  if (!renderClientRouteSlot(slot, registration, \"render\")) return false;\n  activeRouteInterception = {\n    from: from,\n    key: key,\n    slot: slot,\n    previousSlot: previousSlot,\n    previousHtml: previousHtml,\n  };\n  return true;\n}\n\nfunction clearRouteInterception(destination) {\n  if (!activeRouteInterception) return false;\n  const active = activeRouteInterception;\n  activeRouteInterception = null;\n  const root = routeSlotRoots.get(active.key);\n  if (root) {\n    try { root.unmount(); } catch {}\n    routeSlotRoots.delete(active.key);\n  }\n  const container = document.getElementById(active.slot.containerId);\n  if (container) {\n    container.innerHTML = active.previousHtml;\n    if (active.previousSlot) {\n      const registration = findClientRouteSlot(active.previousSlot);\n      if (registration) {\n        try {\n          renderClientRouteSlot(active.previousSlot, registration, \"hydrate\");\n        } catch {}\n      }\n    }\n  }\n  return destination === active.from;\n}\n\n// State\nlet reactRoot = null;\nlet reactRootContainer = null;\nlet currentPathname = null;\nlet isHydrated = false;\nlet pendingPageHydrationController = null;\n\n${generateUniversalRouterStateRuntime()}\n\nfunction cancelPendingPageHydration() {\n  pendingPageHydrationController?.abort();\n  pendingPageHydrationController = null;\n}\n\nfunction resetReactRoot() {\n  cancelPendingPageHydration();\n  if (!reactRoot) return;\n  reactRoot.unmount();\n  reactRoot = null;\n  reactRootContainer = null;\n  isHydrated = false;\n}\n\n// Hydrate client components\nasync function hydrate() {\n  await farmClientRuntime.start();\n\n  if (await hydrateFarmDocsAdapterRuntime()) {\n    return;\n  }\n\n  const pathname = window.location.pathname;\n  const matched = matchRoute(pathname);\n  hydrateInitialRouteSlots();\n\n  if (!matched) {\n    return;\n  }\n\n  ${\n    isolatedHydrationEnabled\n      ? `if (\n    matched.route.hasIsolatedClientBoundaries &&\n    !matched.route.pageShouldHydrate &&\n    !hasHydratableLayout(pathname)\n  ) {\n    const hydrationController = new AbortController();\n    pendingPageHydrationController = hydrationController;\n    await hydrateFarmIsolatedClientBoundaries(document, hydrationController.signal);\n    return;\n  }`\n      : \"\"\n  }\n  \n  const rootContainer = document.getElementById(\"root\");\n  const container = hasHydratableLayout(pathname)\n    ? rootContainer\n    : document.getElementById(\"__farm_page__\") || rootContainer;\n  if (!container) {\n    console.error(\"[Farm.js] No root element found\");\n    return;\n  }\n  \n  container.dataset.farmIsland = \"page\";\n  container.dataset.farmIslandStrategy = matched.route.islandStrategy || \"load\";\n\n  const hydrationController = new AbortController();\n  pendingPageHydrationController = hydrationController;\n  try {\n    const pageHydration = scheduleFarmIslandHydration({\n      container,\n      strategy: matched.route.islandStrategy,\n      signal: hydrationController.signal,\n      hydrate: async function() {\n        if (\n          hydrationController.signal.aborted ||\n          !container.isConnected ||\n          window.location.pathname !== pathname\n        ) {\n          return;\n        }\n        const searchParams = searchParamsToObject(new URLSearchParams(window.location.search));\n        const wrappedElement = await createMatchedHydrationElement(\n          matched,\n          pathname,\n          searchParams,\n        );\n        if (!wrappedElement) return;\n        const shouldHydrate = !isHydrated && Boolean(container.innerHTML.trim());\n        const hydrationSession = await farmClientRuntime.beginHydration({\n          container,\n          mode: shouldHydrate ? \"hydrate\" : \"render\",\n        });\n\n        try {\n          if (hydrationController.signal.aborted || !container.isConnected) {\n            await farmClientRuntime.failHydration(\n              hydrationSession,\n              new DOMException(\"Route hydration was cancelled\", \"AbortError\"),\n            );\n            return;\n          }\n          if (shouldHydrate) {\n            reactRoot = hydrateRoot(container, wrappedElement);\n            reactRootContainer = container;\n            isHydrated = true;\n          } else {\n            if (!reactRoot) {\n              reactRoot = createRoot(container);\n              reactRootContainer = container;\n            }\n            reactRoot.render(wrappedElement);\n          }\n          currentPathname = pathname;\n          await farmClientRuntime.completeHydration(hydrationSession);\n        } catch (error) {\n          await farmClientRuntime.failHydration(hydrationSession, error);\n          console.error(\"[Farm.js] Hydration error:\", error);\n        }\n      },\n    });\n    ${\n      isolatedHydrationEnabled\n        ? `const isolatedHydration =\n      !hasHydratableLayout(pathname) &&\n      document.querySelector('farm-client-boundary[data-farm-client-boundary]')\n        ? hydrateFarmIsolatedClientBoundaries(document, hydrationController.signal)\n        : Promise.resolve();\n    await Promise.all([pageHydration, isolatedHydration]);`\n        : \"await pageHydration;\"\n    }\n  } finally {\n    if (pendingPageHydrationController === hydrationController) {\n      pendingPageHydrationController = null;\n    }\n  }\n}\n\nfunction findLayoutBoundary(root, pattern) {\n  const boundaries = root?.querySelectorAll?.('[data-farm-layout-boundary=\"true\"]') || [];\n  for (const boundary of boundaries) {\n    if (boundary.getAttribute(\"data-farm-layout-pattern\") === pattern) return boundary;\n  }\n  return null;\n}\n\nfunction getLayoutPatterns(root) {\n  return Array.from(root?.querySelectorAll?.('[data-farm-layout-boundary=\"true\"]') || [])\n    .map(function(element) { return element.getAttribute(\"data-farm-layout-pattern\"); })\n    .filter(Boolean);\n}\n\nfunction activateNavigationScripts(root) {\n  for (const script of Array.from(root?.querySelectorAll?.(\"script\") || [])) {\n    const freshScript = document.createElement(\"script\");\n    for (const attribute of Array.from(script.attributes)) {\n      freshScript.setAttribute(attribute.name, attribute.value);\n    }\n    freshScript.textContent = script.textContent || \"\";\n    script.replaceWith(freshScript);\n  }\n}\n\nfunction replaceSharedLayoutBoundary(currentRoot, nextRoot) {\n  const currentPatterns = getLayoutPatterns(currentRoot);\n  const nextPatterns = getLayoutPatterns(nextRoot);\n  let sharedCount = 0;\n  while (\n    sharedCount < currentPatterns.length &&\n    sharedCount < nextPatterns.length &&\n    currentPatterns[sharedCount] === nextPatterns[sharedCount]\n  ) sharedCount++;\n\n  const nextTreeRoot = nextPatterns.length\n    ? findLayoutBoundary(nextRoot, nextPatterns[0])\n    : nextRoot.querySelector(\"#__farm_page__\");\n  const currentTarget = sharedCount < currentPatterns.length\n    ? findLayoutBoundary(currentRoot, currentPatterns[sharedCount])\n    : currentRoot.querySelector(\"#__farm_page__\");\n  const nextTarget = sharedCount < nextPatterns.length\n    ? findLayoutBoundary(nextRoot, nextPatterns[sharedCount])\n    : nextRoot.querySelector(\"#__farm_page__\");\n\n  if (!currentTarget || !nextTarget) return false;\n  ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(currentTarget);\" : \"\"}\n  currentTarget.replaceWith(nextTarget);\n  activateNavigationScripts(nextTarget);\n  if (nextTreeRoot && nextTreeRoot !== nextTarget) nextTreeRoot.remove();\n\n  if (nextRoot.childNodes.length) {\n    const support = document.createElement(\"div\");\n    support.hidden = true;\n    support.dataset.farmFragmentSupport = \"true\";\n    while (nextRoot.firstChild) support.appendChild(nextRoot.firstChild);\n    document.body.appendChild(support);\n    activateNavigationScripts(support);\n    setTimeout(function() { support.remove(); }, 0);\n  }\n  return nextTarget;\n}\n\n// SPA Router\nconst spaRouter = {\n${generateUniversalRouterStateProperties()}\n  prefetchCache: new Map(),\n  \n  navigate: async function(href, options = {}) {\n    const url = new URL(href, window.location.origin);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n    if (isFarmDocsPath(url.pathname)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n\n    const action = options.action || (options.replace ? \"replace\" : \"push\");\n    const to = url.pathname + url.search;\n    if (!options.refresh && action !== \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      if (url.hash === window.location.hash) return;\n      const pageState = options.state === undefined\n        ? window.history.state?.[FARM_PAGE_STATE_KEY]\n        : options.state;\n      this.writeHistoryEntry(action, to, pageState, url);\n      if (options.scroll !== false) {\n        if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      }\n      return;\n    }\n    if (action === \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n      return;\n    }\n    \n    const pathname = url.pathname;\n    const matched = matchRoute(pathname);\n    const from = this.currentPath;\n    if (await this.shouldBlockNavigation({ from, to, action })) {\n      if (action === \"pop\") this.revertBlockedPopState(from);\n      return;\n    }\n    if (action === \"pop\") {\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n    }\n\n    // A route transition invalidates any trigger waiting on the previous DOM boundary.\n    cancelPendingPageHydration();\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n    const navigation = this.startNavigation(from, url, action);\n    let clientNavigation;\n\n    try {\n      clientNavigation = await farmClientRuntime.beginNavigation({\n        from: action === \"pop\" ? null : window.location.href,\n        to: url,\n        action,\n        route: matched\n          ? { pattern: matched.route.pattern, params: matched.params }\n          : undefined,\n      });\n      navigation.clientNavigation = clientNavigation;\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      if (!options.refresh && activeRouteInterception && clearRouteInterception(to)) {\n        this.currentPath = to;\n        await farmClientRuntime.markNavigationLoaded(clientNavigation, {\n          routeSlots: \"restored\",\n        });\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        await farmClientRuntime.resolveNavigation(clientNavigation);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n        this.finishNavigation(navigation);\n        return;\n      }\n      if (activeRouteInterception) {\n        clearRouteInterception(to);\n      }\n\n      const intercepted = options.refresh ? null : matchInterceptedRouteSlot(pathname, from);\n      if (intercepted) {\n        const html = await this.fetchPage(to, from, false, true, navigation.controller.signal);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        const doc = new DOMParser().parseFromString(html, \"text/html\");\n        const slotPayload = readRouteSlotPayload(doc);\n        const selectedSlot = slotPayload.find(function(slot) {\n          return slot.interception &&\n            slot.name === intercepted.slot.name &&\n            slot.ownerPattern === intercepted.slot.ownerPattern;\n        });\n\n        if (selectedSlot) {\n          await farmClientRuntime.markNavigationLoaded(clientNavigation, {\n            route: intercepted.slot.pattern,\n            params: intercepted.params,\n          });\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          if (renderRouteInterception(selectedSlot, intercepted.slot, from, doc)) {\n            this.writeHistoryEntry(action, to, options.state, url);\n            this.currentPath = to;\n            await farmClientRuntime.resolveNavigation(clientNavigation);\n            if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n            void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n            this.finishNavigation(navigation);\n            return;\n          }\n        }\n      }\n\n      if (!options.refresh && matched?.route.navigation === \"client-render\") {\n        // Navigation itself signals intent, so destination routes load eagerly even\n        // when their initial document hydration strategy is deferred.\n        const Component = await loadRouteComponent(matched.route);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        const params = matched.params;\n        const searchParams = searchParamsToObject(url.searchParams);\n        const props = { params: params, searchParams: Promise.resolve(searchParams) };\n        let pageElement = React.createElement(Component, props);\n        if (hasHydratableLayout(pathname)) {\n          pageElement = createLayoutPageBoundary(matched.route, pageElement);\n        }\n        const wrappedElement = wrapFarmRouteClientGraph(\n          wrapWithIntegrationProviders(wrapWithLayouts(pageElement, pathname, params)),\n        );\n\n        await farmClientRuntime.markNavigationLoaded(clientNavigation, {\n          route: matched.route.pattern,\n          params,\n        });\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n        await this.runViewTransition(options.viewTransition, async () => {\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          this.writeHistoryEntry(action, url.pathname + url.search, options.state, url);\n\n          const container = document.getElementById(\"root\");\n          if (container) {\n            if (reactRoot && reactRootContainer !== container) resetReactRoot();\n            if (!reactRoot) {\n              reactRoot = createRoot(container);\n              reactRootContainer = container;\n            }\n            reactRoot.render(wrappedElement);\n            currentPathname = pathname;\n          }\n          this.currentPath = to;\n        });\n      } else {\n        const html = await this.fetchPage(\n          url.pathname + url.search,\n          undefined,\n          options.refresh === true,\n          true,\n          navigation.controller.signal,\n        );\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        await farmClientRuntime.markNavigationLoaded(clientNavigation, html);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        await this.runViewTransition(options.viewTransition, async () => {\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          const swapped = await this.swapContent(\n            html,\n            url.pathname + url.search,\n            navigation,\n            clientNavigation,\n          );\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          if (!swapped) {\n            throw new Error(\"Farm could not swap the target document\");\n          }\n          this.writeHistoryEntry(action, url.pathname + url.search, options.state, url);\n          currentPathname = pathname;\n          this.currentPath = to;\n        });\n      }\n\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (options.scroll !== false) {\n        if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      } else {\n        this.restoreScrollPosition(to);\n      }\n      await farmClientRuntime.resolveNavigation(clientNavigation);\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await farmClientRuntime.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      if (error?.name === \"FarmDeploymentMismatchError\") return;\n      console.error(\"[Farm.js] Navigation error:\", error);\n      if (action === \"pop\") window.location.reload();\n      else window.location.href = href;\n    }\n  },\n\n  refresh: function(options = {}) {\n    return this.navigate(window.location.href, {\n      ...options,\n      action: \"replace\",\n      replace: true,\n      refresh: true,\n      scroll: options.scroll === undefined ? false : options.scroll,\n    });\n  },\n  \n  fetchPage: async function(url, interceptFrom, fresh = false, recover = true, signal) {\n    const cacheKey = interceptFrom ? url + \"\\\\nintercept:\" + interceptFrom : url;\n    if (fresh) this.clearPrefetchedPath(url);\n    const cached = fresh ? undefined : this.prefetchCache.get(cacheKey);\n    if (cached) return cached;\n    \n    const response = await fetchFarmNavigationDocument(\n      url,\n      {\n        \"Accept\": \"text/html\",\n        ...(interceptFrom ? { \"X-Farm-Intercept-From\": interceptFrom } : {}),\n      },\n      recover,\n      signal,\n    );\n    if (!response.ok) throw new Error(\"Failed to fetch page\");\n    const html = await response.text();\n    this.prefetchCache.set(cacheKey, html);\n    return html;\n  },\n  \n  swapContent: async function(html, targetPath, navigation, clientNavigation) {\n    const parser = new DOMParser();\n    const doc = parser.parseFromString(html, \"text/html\");\n    if (isFarmLocaleDocumentChange(doc)) return false;\n    if (doc.getElementById(\"nd-docs-layout\")) return false;\n    const nextRouteSlots = readRouteSlotPayload(doc);\n    const isNavigationCurrent = () =>\n      this.isCurrentNavigation(navigation, clientNavigation);\n    \n    reconcileFarmDocumentHead(doc);\n    \n    // Swap root content\n    const newRoot = doc.getElementById(\"root\");\n    const currentRoot = document.getElementById(\"root\");\n    if (!newRoot || !currentRoot) {\n      if (!isNavigationCurrent()) return false;\n      return this.swapDocument(doc);\n    }\n    const targetUrl = new URL(targetPath || window.location.href, window.location.origin);\n    const newPathname = targetUrl.pathname;\n    const matched = matchRoute(newPathname);\n    const hydrateLayouts = hasHydratableLayout(newPathname);\n    const nextPage = newRoot.querySelector(\"#__farm_page__\");\n\n    // If React already owns the shared layout, update that root. React keeps\n    // matching layout component instances and their state mounted.\n    if (matched && hydrateLayouts && reactRoot && reactRootContainer === currentRoot) {\n      const searchParams = searchParamsToObject(targetUrl.searchParams);\n      const wrappedElement = await createMatchedHydrationElement(\n        matched,\n        newPathname,\n        searchParams,\n        nextPage ? nextPage.innerHTML : \"\",\n      );\n      if (!isNavigationCurrent()) return false;\n      if (wrappedElement) {\n        reactRoot.render(wrappedElement);\n        window.__FARM_ROUTE_SLOTS__ = nextRouteSlots;\n        isHydrated = true;\n        return true;\n      }\n    }\n\n    const rootWasReactOwned = reactRootContainer === currentRoot;\n    resetReactRoot();\n    resetRouteSlotRoots();\n    const replacedSharedBoundary = rootWasReactOwned\n      ? null\n      : replaceSharedLayoutBoundary(currentRoot, newRoot);\n    let isolatedHydrationScope = replacedSharedBoundary || currentRoot;\n    if (!replacedSharedBoundary) {\n      ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(currentRoot);\" : \"\"}\n      currentRoot.innerHTML = newRoot.innerHTML;\n      activateNavigationScripts(currentRoot);\n      isolatedHydrationScope = currentRoot;\n    }\n    window.__FARM_ROUTE_SLOTS__ = nextRouteSlots;\n    hydrateInitialRouteSlots();\n\n    // Check if the new HTML contains an interactive route boundary.\n    if (matched) {\n      const searchParams = searchParamsToObject(targetUrl.searchParams);\n      const pageContainer =\n        hydrateLayouts ? currentRoot : document.getElementById(\"__farm_page__\") || currentRoot;\n      const wrappedElement = await createMatchedHydrationElement(\n        matched,\n        newPathname,\n        searchParams,\n      );\n      if (!isNavigationCurrent()) return false;\n      if (wrappedElement) {\n        reactRoot = hydrateRoot(pageContainer, wrappedElement);\n        reactRootContainer = pageContainer;\n        isHydrated = true;\n      }\n      ${\n        isolatedHydrationEnabled\n          ? `if (matched.route.hasIsolatedClientBoundaries && !hydrateLayouts) {\n        await hydrateFarmIsolatedClientBoundaries(\n          isolatedHydrationScope,\n          navigation.controller.signal,\n        );\n        if (!isNavigationCurrent()) return false;\n      }`\n          : \"\"\n      }\n    }\n    return true;\n  },\n\n  swapDocument: function(doc) {\n    if (!doc.documentElement || !doc.body) return false;\n\n    resetReactRoot();\n    resetRouteSlotRoots();\n    ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(document);\" : \"\"}\n\n    Array.from(document.documentElement.attributes).forEach(function(attr) {\n      if (!doc.documentElement.hasAttribute(attr.name)) {\n        document.documentElement.removeAttribute(attr.name);\n      }\n    });\n    Array.from(doc.documentElement.attributes).forEach(function(attr) {\n      document.documentElement.setAttribute(attr.name, attr.value);\n    });\n\n    document.head.innerHTML = doc.head ? doc.head.innerHTML : \"\";\n    document.body.innerHTML = doc.body.innerHTML;\n    delete window.__farmDocsRuntime;\n    delete window.__farmDocsPageActionsRuntime;\n\n    setTimeout(function() {\n      Array.from(document.querySelectorAll(\"script\")).forEach(function(script) {\n        const freshScript = document.createElement(\"script\");\n        Array.from(script.attributes).forEach(function(attr) {\n          freshScript.setAttribute(attr.name, attr.value);\n        });\n        freshScript.textContent = script.textContent || \"\";\n        script.replaceWith(freshScript);\n      });\n    }, 0);\n\n    return true;\n  },\n  prefetch: function(href) {\n    const url = new URL(href, window.location.origin);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) return;\n    if (isFarmDocsPath(url.pathname)) return;\n    \n    const pathname = url.pathname + url.search;\n    const interceptFrom = this.currentPath;\n    const cacheKey = pathname + \"\\\\nintercept:\" + interceptFrom;\n    if (this.prefetchCache.has(cacheKey)) return;\n    \n    this.fetchPage(pathname, interceptFrom, false, false)\n      .then(function(html) { spaRouter.prefetchCache.set(cacheKey, html); })\n      .catch(function(error) {\n        clearFarmPrefetchCacheOnDeploymentMismatch(spaRouter, error);\n      });\n  },\n  \n  observeForPrefetch: function(element) {\n    if (!(\"IntersectionObserver\" in window)) return;\n\n    const href = element.getAttribute(\"href\");\n    if (!href) return;\n\n    const observer = new IntersectionObserver(function(entries) {\n      entries.forEach(function(entry) {\n        if (entry.isIntersecting) {\n          spaRouter.prefetch(href);\n          observer.disconnect();\n          spaRouter.observers.delete(element);\n        }\n      });\n    }, { rootMargin: \"50px\" });\n\n    observer.observe(element);\n    this.observers.set(element, observer);\n  },\n\n  unobserveForPrefetch: function(element) {\n    const observer = this.observers.get(element);\n    if (!observer) return;\n    observer.unobserve(element);\n    observer.disconnect();\n    this.observers.delete(element);\n  }\n};\n\nconst farmClientRuntime = createClientPluginManager(\n  ${clientPluginEntry.registrations},\n  {\n    router: spaRouter,\n    isDev: false,\n    isProd: true,\n    deploymentId: window.__FARM_DEPLOYMENT_ID__,\n  },\n);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\n// Expose router globally\nspaRouter.initializeHistory();\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nwindow.addEventListener(\"beforeunload\", function(event) {\n  if (spaRouter.shouldBlockUnload()) {\n    event.preventDefault();\n    event.returnValue = \"\";\n  }\n  spaRouter.saveScrollPosition(window.location.pathname + window.location.search);\n});\n\n// Handle popstate (back/forward)\nwindow.addEventListener(\"popstate\", function(event) {\n  void spaRouter.handlePopState(event);\n});\n\n// Intercept link clicks\ndocument.addEventListener(\"click\", function(e) {\n  const target = e.target;\n  const anchor = target.closest ? target.closest(\"a\") : null;\n  if (!anchor) return;\n  \n  const href = anchor.getAttribute(\"href\");\n  if (!href) return;\n  if (anchor.hasAttribute(\"download\")) return;\n  if (hasAbsoluteNavigationHref(href)) return;\n  if (href.startsWith(\"#\")) return;\n  if (anchor.target && anchor.target !== \"_self\") return;\n  if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n  if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;\n  if (e.button !== 0) return;\n  if (e.defaultPrevented) return;\n  \n  e.preventDefault();\n  spaRouter.navigate(href);\n});\n\n// Initial hydration\nif (isFarmDocsSearchPage()) {\n  mountFarmDocsSearch();\n}\nvoid hydrate();\n`.trim();\n}\n\n/**\n * Build SSR bundle in memory (write: false)\n * Creates a virtual entry that bundles all API routes and page routes\n * Managers are created at runtime from the bundled code\n */\nasync function buildSSRInMemory(\n  productionVite: FarmProductionViteRuntime,\n  config: ResolvedFarmConfig,\n  root: string,\n  routeManager: RouteManager,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: ServerRenderer,\n  preset: string,\n  collectedPageRoutes: readonly UniversalPageRoute[],\n  collectedLayoutRoutes: ReadonlyArray<{ pattern: string; modulePath: string }>,\n  collectedRouteSlots: readonly UniversalRouteSlot[],\n  isolatedClientBoundaryModules: ReadonlySet<string>,\n  hydrationPlanCache: Map<string, ClientModuleHydrationPlan>,\n): Promise<{\n  bundle: OutputBundle;\n  entryFile: string;\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[];\n}> {\n  const viteBuild = productionVite.build;\n  const { farmPlugin } = await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n  const fs = await import(\"fs/promises\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n  const hasScopedPostcssConfig = hasProjectPostcssConfig(root);\n  let postcssConfigDir: string | undefined;\n  let tailwindVitePlugin: any = undefined;\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, root, {\n    ssr: true,\n  });\n  if (!hasScopedPostcssConfig) {\n    postcssConfigDir = await fs.mkdtemp(path.join(os.tmpdir(), \"farm-postcss-\"));\n    await fs.writeFile(\n      path.join(postcssConfigDir, \"postcss.config.cjs\"),\n      \"module.exports = { plugins: [] };\\n\",\n    );\n    try {\n      const tailwindVite = (await import(\"@tailwindcss/vite\")).default;\n      tailwindVitePlugin = adaptTailwindVitePlugin(tailwindVite(), productionVite.builder);\n    } catch (error) {\n      logger.warn(\n        `Tailwind plugin auto-enable failed for SSR; continuing without it: ${(error as Error).message}`,\n      );\n    }\n  }\n\n  let ssrBundle: OutputBundle;\n  let ssrEntryFile: string;\n\n  // Reuse the route and layout manifests already collected for the parallel\n  // client build instead of rescanning the same project tree.\n  const pageRoutes = collectedPageRoutes.map((route) => ({ ...route }));\n  const layoutRoutes = collectedLayoutRoutes.map((route) => ({ ...route }));\n  const routeSlots = collectedRouteSlots.map((slot) => ({ ...slot }));\n\n  const metadataImageRoutes: UniversalMetadataImageRoute[] = [];\n  for (const entry of routeManager.getMetadataImages().values()) {\n    if (entry.sourceType === \"static\") {\n      if (!entry.staticInfo) {\n        throw new Error(`Static metadata image ${entry.modulePath} is missing file info`);\n      }\n      metadataImageRoutes.push({\n        pattern: entry.pattern,\n        kind: entry.kind,\n        fileName: entry.fileName,\n        sourceType: \"static\",\n        staticInfo: entry.staticInfo,\n        data: (await fs.readFile(entry.modulePath)).toString(\"base64\"),\n      });\n      continue;\n    }\n\n    metadataImageRoutes.push({\n      pattern: entry.pattern,\n      kind: entry.kind,\n      fileName: entry.fileName,\n      sourceType: \"module\",\n      modulePath: entry.modulePath,\n    });\n  }\n\n  const applicationMetadataRoutes: UniversalApplicationMetadataRoute[] = Array.from(\n    routeManager.getMetadataRoutes().values(),\n    (entry) => ({\n      pattern: entry.pattern,\n      kind: entry.kind,\n      outputName: entry.outputName,\n      modulePath: entry.modulePath,\n    }),\n  );\n\n  // Generate API route manifest\n  const apiRoutes: Array<{\n    path: string;\n    filePath: string;\n    methods: string[];\n    pluginMethods?: string[];\n  }> = [];\n  for (const [routePath, route] of apiRouteManager.getRoutes()) {\n    apiRoutes.push({\n      path: routePath,\n      filePath: route.filePath,\n      methods: route.methods,\n      pluginMethods: route.pluginMethods,\n    });\n  }\n  const [configuredRedirects, configuredRewrites, configuredHeaderRoutes] = await Promise.all([\n    config.redirects(),\n    config.rewrites(),\n    config.headers(),\n  ]);\n  const redirectRoutes: ProgrammaticRedirectRoute[] = [\n    ...routeManager.getRedirects(),\n    ...configuredRedirects.map((redirect: RedirectConfig) => ({\n      source: redirect.source,\n      destination: redirect.destination,\n      permanent: redirect.permanent,\n      statusCode: redirect.statusCode,\n    })),\n  ];\n  const errorRoutes: UniversalBoundaryRoute[] = Array.from(\n    routeManager.getErrors().values(),\n    (entry) => ({\n      pattern: entry.pattern,\n      modulePath: entry.modulePath,\n    }),\n  );\n  const i18nCatalogs = config.i18n.enabled\n    ? (await readFarmI18nCatalogs(config.i18n)).catalogs\n    : {};\n\n  const appDirs = getFarmAppDirectories(config);\n  let openAPIReference: {\n    route: string;\n    html: string;\n    spec: unknown;\n    specRoute: string | null;\n  } | null = null;\n  if (config.openapi.enabled && config.openapi.route) {\n    const { OpenAPIManager, renderOpenAPIReferenceHTML } = await import(\"../openapi/manager\");\n    const openAPIManager = new OpenAPIManager(appDirs, config.openapi);\n    const spec = await openAPIManager.generateSpec();\n    if (!spec) {\n      throw new Error(\"Failed to generate the OpenAPI specification for the production build.\");\n    }\n    openAPIReference = {\n      route: config.openapi.route,\n      html: renderOpenAPIReferenceHTML(spec, config.openapi),\n      spec,\n      specRoute: config.openapi.specRoute || null,\n    };\n  }\n  const middlewareRoutes = await discoverMiddlewareRoutes(appDirs);\n  const instrumentationPath = resolveFarmInstrumentationFile(root, config.srcDir || \"src\");\n\n  // Check for custom not-found page\n  const notFoundPath = resolveFarmNotFoundComponentPath(config, appDirs);\n  if (notFoundPath) logger.info(`📋 Found custom 404 page: ${notFoundPath}`);\n\n  // Sort layouts by depth (root first)\n  layoutRoutes.sort((a, b) => {\n    const depthA = a.pattern.split(\"/\").filter(Boolean).length;\n    const depthB = b.pattern.split(\"/\").filter(Boolean).length;\n    return depthA - depthB;\n  });\n\n  logger.info(\n    `📋 Found ${pageRoutes.length} page routes, ${layoutRoutes.length} layouts, ${apiRoutes.length} API routes, ${applicationMetadataRoutes.length} metadata routes, and ${middlewareRoutes.length} middleware files`,\n  );\n\n  const configuredIntegrationValues = Object.values(config.integrations || {});\n  const hasAnyConfiguredIntegrations = configuredIntegrationValues.some(\n    (integration) => typeof integration === \"object\" && integration !== null,\n  );\n  const hasServerRuntimeIntegrations = configuredIntegrationValues.some(\n    (integration) =>\n      typeof integration === \"object\" &&\n      integration !== null &&\n      (!(\"serverRuntime\" in integration) || integration.serverRuntime !== false),\n  );\n  const hasIntegrationProviders = getIntegrationProviders(config.integrations).some(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  const hasObservabilityHandler =\n    !!config.observability &&\n    typeof config.observability === \"object\" &&\n    \"onEvent\" in config.observability;\n  const hasMdxComponentConfig = Boolean(config.mdx?.components);\n  const hasMiddlewareConfig = hasFarmMiddlewareConfig(config.middleware);\n  const hasRouteContextConfig = hasCustomFarmRouteContext(config);\n  const hasServerRuntimePlugins = hasFarmServerRuntimePlugins(config);\n  const configModulePath =\n    hasServerRuntimeIntegrations ||\n    hasObservabilityHandler ||\n    hasMdxComponentConfig ||\n    hasMiddlewareConfig ||\n    hasRouteContextConfig ||\n    hasServerRuntimePlugins ||\n    hasIntegrationProviders\n      ? await findFarmConfigPath(root)\n      : null;\n  const hasRuntimeConfigModule = hasFarmRuntimeConfigModule(config, configModulePath);\n  const hasRuntimeIntegrationConfig = hasRuntimeConfigModule && hasAnyConfiguredIntegrations;\n  const hasConfiguredRuntimePlugins = Boolean(\n    hasRuntimeConfigModule && (config.plugins || []).length > 0,\n  );\n\n  // Generate virtual entry code that imports and bundles all routes\n  // This ensures all route handlers are captured in the bundle closure\n  const virtualEntryCode = generateVirtualEntryCode(\n    apiRoutes,\n    pageRoutes,\n    layoutRoutes,\n    routeSlots,\n    errorRoutes,\n    metadataImageRoutes,\n    applicationMetadataRoutes,\n    middlewareRoutes,\n    redirectRoutes,\n    configuredRewrites,\n    configuredHeaderRoutes,\n    openAPIReference,\n    notFoundPath,\n    instrumentationPath,\n    config,\n    configModulePath,\n    hasServerRuntimeIntegrations,\n    hasRuntimeIntegrationConfig,\n    hasConfiguredRuntimePlugins,\n    preset,\n    i18nCatalogs,\n    isolatedClientBoundaryModules,\n    hydrationPlanCache,\n  );\n\n  // Find a temporary file path for the virtual entry\n  // We'll use a plugin to intercept this\n  const virtualEntryId = \"\\0virtual:farm-ssr-entry\";\n  const useExternalMetadataImageRuntime = shouldUseExternalMetadataImageRuntime(\n    preset,\n    metadataImageRoutes.some((image) => image.sourceType === \"module\"),\n  );\n  const rendererOptionalExternals = isReactRenderer(config.renderer)\n    ? []\n    : [\n        \"react\",\n        \"react/jsx-runtime\",\n        \"react/jsx-dev-runtime\",\n        \"react-dom\",\n        \"react-dom/client\",\n        \"react-dom/server\",\n      ];\n\n  try {\n    await viteBuild({\n      root,\n      build: {\n        target: \"esnext\",\n        ssr: true,\n        write: false, // ⭐ Keep in memory\n        ssrEmitAssets: true,\n        assetsInlineLimit: 0,\n        minify: false, // Skip minification for SSR (faster build, Nitro will minify)\n        sourcemap: false, // Skip sourcemaps for faster SSR build\n        rollupOptions: {\n          input: virtualEntryId,\n          // Externalize native modules and Node.js built-ins\n          external: [\n            \"fsevents\",\n            \"sharp\",\n            ...rendererOptionalExternals,\n            ...(useExternalMetadataImageRuntime ? [\"@vercel/og\"] : []),\n            \"@prisma/client\",\n            \"@prisma/client/default\",\n            \"@prisma/client/default.js\",\n            \".prisma/client\",\n            \".prisma/client/default\",\n            /^\\.prisma\\//,\n            /\\.node$/,\n            /^node:/,\n          ],\n          // Optimize tree-shaking\n          treeshake: {\n            moduleSideEffects: false,\n          },\n        },\n      },\n      // Use esbuild for faster transforms\n      esbuild: {\n        target: \"node18\",\n        // Adapters can render provider scripts by serializing function source.\n        // keepNames injects helper calls into those functions; after Nitro\n        // minifies the server chunk the helper is no longer in script scope.\n        keepNames: !(config.docs?.enabled && config.docs.adapter?.server),\n        jsxDev: false,\n      },\n      // SSR configuration to externalize problematic modules\n      ssr: {\n        // Externalize native modules and build tools that can't be bundled\n        // These have native binaries that won't work in serverless environments\n        external: [\n          \"fsevents\",\n          \"sharp\",\n          ...rendererOptionalExternals,\n          ...(useExternalMetadataImageRuntime ? [\"@vercel/og\"] : []),\n          \"esbuild\",\n          \"lightningcss\",\n          \"rollup\",\n          \"@rollup/rollup-darwin-arm64\",\n          \"@rollup/rollup-darwin-x64\",\n          \"@rollup/rollup-linux-x64-gnu\",\n          \"@rollup/rollup-linux-x64-musl\",\n          \"@rollup/rollup-linux-arm64-gnu\",\n          \"@rollup/rollup-linux-arm64-musl\",\n          \"@rollup/rollup-win32-x64-msvc\",\n          \"@rollup/rollup-win32-arm64-msvc\",\n          \"@rollup/rollup-win32-ia32-msvc\",\n          \"vite\",\n          \"vite-rolldown\",\n          \"nitro\",\n          \"nitropack\",\n          \"@prisma/client\",\n          \"@prisma/client/default\",\n          \"@prisma/client/default.js\",\n          \".prisma/client\",\n          \".prisma/client/default\",\n        ],\n        // Node deployments must bundle application dependencies with Farm's\n        // React runtime. Leaving a React component package external can make it\n        // resolve a second React instance at runtime and break hooks during SSR.\n        // Native and build-only packages above remain explicitly external.\n        noExternal:\n          preset === \"cloudflare-module\"\n            ? [\n                \"@farm.js/core\",\n                \"@farm.js/core/image\",\n                \"better-call\",\n                ...(metadataImageRoutes.some((image) => image.sourceType === \"module\")\n                  ? [\"@vercel/og\"]\n                  : []),\n              ]\n            : true,\n      },\n      define: {\n        __FARM_API_BASE_URL__: JSON.stringify(config.api.baseURL),\n        __FARM_ENV__: JSON.stringify(config.env || { server: {}, public: {} }),\n        __FARM_PUBLIC_ENV__: JSON.stringify(config.env?.public || {}),\n      },\n      plugins: [\n        createFarmThemeCssPlugin(config.theme, config.basePath),\n        ...(tailwindVitePlugin ? [tailwindVitePlugin] : []),\n        ...(rendererVitePlugins as any[]),\n        ...(config.vite.plugins || []),\n        ...(!useExternalMetadataImageRuntime &&\n        metadataImageRoutes.some((image) => image.sourceType === \"module\")\n          ? [createMetadataImageWasmPlugin()]\n          : []),\n        {\n          name: \"farm-react-production-mode\",\n          enforce: \"pre\",\n          transform(code, id) {\n            const normalizedId = id.replace(/\\\\/g, \"/\");\n            const isReactRuntime =\n              normalizedId.includes(\"/node_modules/react/\") ||\n              normalizedId.includes(\"/node_modules/react-dom/\");\n            const nodeEnvExpression = [\"process\", \"env\", \"NODE_ENV\"].join(\".\");\n\n            if (!isReactRuntime || !code.includes(nodeEnvExpression)) return null;\n\n            return {\n              code: code.split(nodeEnvExpression).join('\"production\"'),\n              map: null,\n            };\n          },\n        },\n        farmPlugin({ ...config, isolatedClientBoundaryModules }, pluginManager),\n        farmEnvironmentFunctionsPlugin(),\n        {\n          name: \"farm-virtual-ssr-entry\",\n          resolveId(id) {\n            if (id === virtualEntryId || id === \"\\0virtual:farm-ssr-entry\") {\n              return virtualEntryId;\n            }\n            return null;\n          },\n          load(id) {\n            if (id === virtualEntryId) {\n              return virtualEntryCode;\n            }\n            return null;\n          },\n        },\n        {\n          name: \"capture-ssr-bundle\",\n          generateBundle(_options, bundle) {\n            ssrBundle = bundle;\n\n            // Find entry file\n            for (const [fileName, file] of Object.entries(bundle)) {\n              if (file.type === \"chunk\" && file.isEntry) {\n                ssrEntryFile = fileName;\n                break;\n              }\n            }\n\n            if (!ssrEntryFile) {\n              throw new Error(\"No entry point found in SSR bundle\");\n            }\n          },\n        },\n      ],\n      mode: \"production\",\n      css: postcssConfigDir\n        ? {\n            postcss: postcssConfigDir,\n          }\n        : undefined,\n      resolve: {\n        alias: createFarmSourceAlias(root, config.srcDir),\n        // Route modules and the renderer adapter must share one runtime instance.\n        dedupe: [...(config.renderer.dedupe || [])],\n      },\n    });\n  } finally {\n    if (postcssConfigDir) {\n      try {\n        await fs.rm(postcssConfigDir, { recursive: true, force: true });\n      } catch {\n        // Ignore cleanup errors.\n      }\n    }\n  }\n\n  return {\n    bundle: ssrBundle!,\n    entryFile: ssrEntryFile!,\n    configuredHeaderRoutes,\n  };\n}\n\n/**\n * Generate virtual entry code that bundles all routes\n * This creates managers at runtime from bundled code\n */\nexport function generateFarmDocsRuntimeConfigExpression(docs: ResolvedFarmConfig[\"docs\"]): string {\n  if (!docs.enabled) return \"null\";\n\n  const baseConfig = {\n    ...docs,\n    contentDir: undefined,\n    config: undefined,\n  };\n  const nestedConfig = {\n    ...docs.config,\n    contentDir: undefined,\n  };\n\n  return `farmDocsBundledContentDir\n  ? {\n      ...${JSON.stringify(baseConfig)},\n      contentDir: farmDocsBundledContentDir,\n      config: {\n        ...${JSON.stringify(nestedConfig)},\n        contentDir: farmDocsBundledContentDir,\n      },\n    }\n  : ${JSON.stringify(docs)}`;\n}\n\n/**\n * Quote a filesystem path for use as an import specifier in generated code.\n * Windows paths contain backslashes, which JavaScript string literals treat\n * as escape sequences (e.g. `\\f` in `E:\\farm`), producing specifiers the\n * bundler cannot resolve. Normalize to forward slashes and JSON-quote.\n */\nexport function toVirtualEntryImportSpecifier(modulePath: string): string {\n  return JSON.stringify(modulePath.replace(/\\\\/g, \"/\"));\n}\n\nexport function generateConfiguredResponseHeadersRuntimeSource(): string {\n  return `\nfunction getConfiguredSetCookieHeaders(headers) {\n  const getSetCookie = headers.getSetCookie;\n  if (typeof getSetCookie === \"function\") return getSetCookie.call(headers);\n  const value = headers.get(\"set-cookie\");\n  return value ? [value] : [];\n}\n\nfunction applyConfiguredResponseHeaders(response, pathname) {\n  let headers;\n  for (const headerRoute of configuredHeaderRoutes) {\n    if (!matchRuntimePathPattern(headerRoute.source, pathname)) continue;\n    for (const header of headerRoute.headers) {\n      const currentHeaders = headers || response.headers;\n      const normalizedKey = header.key.toLowerCase();\n      if (normalizedKey === \"set-cookie\") {\n        if (getConfiguredSetCookieHeaders(currentHeaders).includes(header.value)) continue;\n        if (!headers) headers = new Headers(response.headers);\n        headers.append(\"Set-Cookie\", header.value);\n      } else {\n        const currentValue = currentHeaders.get(header.key);\n        if (currentValue === header.value) continue;\n        if (!headers) headers = new Headers(response.headers);\n        if (normalizedKey === \"link\") {\n          appendFarmLinkHeader(headers, header.value);\n        } else {\n          headers.set(header.key, header.value);\n        }\n      }\n    }\n  }\n\n  if (!headers) return response;\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n`.trim();\n}\n\nfunction generateVirtualEntryCode(\n  apiRoutes: Array<{ path: string; filePath: string; methods: string[]; pluginMethods?: string[] }>,\n  pageRoutes: UniversalPageRoute[],\n  layoutRoutes: Array<{ pattern: string; modulePath: string }>,\n  routeSlots: UniversalRouteSlot[],\n  errorRoutes: UniversalBoundaryRoute[],\n  metadataImageRoutes: UniversalMetadataImageRoute[],\n  applicationMetadataRoutes: UniversalApplicationMetadataRoute[],\n  middlewareRoutes: UniversalMiddlewareRoute[],\n  redirectRoutes: ProgrammaticRedirectRoute[],\n  configuredRewriteRoutes: RewriteConfig[],\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[],\n  openAPIReference: { route: string; html: string; spec: unknown; specRoute: string | null } | null,\n  notFoundPath: string | null,\n  instrumentationPath: string | null,\n  config: ResolvedFarmConfig,\n  configModulePath: string | null,\n  hasServerRuntimeIntegrations: boolean,\n  hasRuntimeIntegrationConfig: boolean,\n  hasConfiguredRuntimePlugins: boolean,\n  preset: string,\n  i18nCatalogs: FarmI18nCatalogs,\n  isolatedClientBoundaryModules: ReadonlySet<string>,\n  hydrationPlanCache: Map<string, ClientModuleHydrationPlan>,\n): string {\n  const hasPluginRuntime = hasRuntimeIntegrationConfig || hasConfiguredRuntimePlugins;\n  const adapterOwnsDocsRuntime = Boolean(\n    isReactRenderer(config.renderer) &&\n    config.docs?.enabled &&\n    config.docs.adapter?.server &&\n    config.docs.adapter.react,\n  );\n  const hasIsolatedClientGraphRuntime =\n    isReactRenderer(config.renderer) && isolatedClientBoundaryModules.size > 0;\n  const rendererServerImports = isReactRenderer(config.renderer)\n    ? `import * as React from \"react\";\\nimport * as ReactDOMServer from \"react-dom/server\";${\n        hasIsolatedClientGraphRuntime\n          ? '\\nimport { wrapFarmIsolatedClientGraph } from \"@farm.js/core/internal/isolated-boundary\";'\n          : \"\"\n      }`\n    : `import React, * as ReactDOMServer from ${JSON.stringify(config.renderer.server)};`;\n  const routeClientGraphServerRuntime = hasIsolatedClientGraphRuntime\n    ? `function wrapFarmRouteClientGraph(element) {\n  return wrapFarmIsolatedClientGraph(React, element);\n}`\n    : `function wrapFarmRouteClientGraph(element) { return element; }`;\n  const hasGeneratedMetadataImages = metadataImageRoutes.some(\n    (image) => image.sourceType === \"module\",\n  );\n  const hasMiddlewareRuntime =\n    middlewareRoutes.length > 0 || hasFarmMiddlewareConfig(config.middleware);\n  const farmDocsFontAssets = config.docs?.enabled\n    ? toFarmDocsPublicFontAssets(resolveFarmDocsFontAssets(config.root))\n    : [];\n  const integrationProviders = getIntegrationProviders(config.integrations);\n  const renderedIntegrationProviders = integrationProviders.filter(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  if (renderedIntegrationProviders.length > 0 && !isReactRenderer(config.renderer)) {\n    throw new Error(\"Integration provider components currently require the React renderer.\");\n  }\n  const providerServerModules = generateFarmIntegrationProviderServerModules(\n    renderedIntegrationProviders,\n    config.root,\n  );\n  const resolvedIntegrationProviderFallback = Object.fromEntries(\n    Object.entries(config.integrations).flatMap(([name, integration]) => {\n      const configuredProviders = (integration as { providers?: unknown } | null)?.providers;\n      const providers = Array.isArray(configuredProviders) ? configuredProviders : [];\n      if (providers.some((provider) => typeof provider?.component === \"function\")) {\n        throw new Error(\n          `Integration provider components in production must use an importable component reference, for example component: { module: \"@/components/provider\" }.`,\n        );\n      }\n      return providers.length > 0 ? [[name, { providers }]] : [];\n    }),\n  );\n  const unsupportedIntegrationProvider = renderedIntegrationProviders.find(\n    (provider) => provider.supportsIsolatedHydration !== true,\n  );\n  const isolatedHydrationMode = resolveFarmIsolatedClientHydrationMode(\n    config.experimental?.isolatedClientHydration,\n    {\n      serverComponents: config.experimental?.serverComponents === true,\n      hasUnsupportedIntegrationProvider: Boolean(unsupportedIntegrationProvider),\n    },\n  );\n  const layoutAppliesToRoute = (layoutPattern: string, routePattern: string) =>\n    layoutPattern === \"/\" ||\n    routePattern === layoutPattern ||\n    routePattern.startsWith(`${layoutPattern}/`);\n  const layoutHydrationPlans = layoutRoutes.map((layout) => ({\n    ...layout,\n    hydration: getCachedClientModuleHydrationPlan(\n      layout.modulePath,\n      config.root,\n      isolatedHydrationMode,\n      hydrationPlanCache,\n    ),\n  }));\n  const pageHydrationPlans = new Map(\n    pageRoutes\n      .filter((route) => !isFarmMarkdownPageFile(route.modulePath))\n      .map((route) => [\n        route.modulePath,\n        getCachedClientModuleHydrationPlan(\n          route.modulePath,\n          config.root,\n          isolatedHydrationMode,\n          hydrationPlanCache,\n        ),\n      ]),\n  );\n\n  enforceFarmIsolatedHydrationRouteBudget(\n    layoutHydrationPlans.map((layout) => ({\n      pattern: layout.pattern,\n      depth: layout.pattern.split(\"/\").filter(Boolean).length,\n      metadata: layout.hydration,\n    })),\n    pageRoutes\n      .filter((route) => !isFarmMarkdownPageFile(route.modulePath))\n      .map((route) => ({\n        pattern: route.pattern,\n        depth: route.pattern.split(\"/\").filter(Boolean).length,\n        metadata: pageHydrationPlans.get(route.modulePath)!,\n      })),\n    layoutAppliesToRoute,\n  );\n  const providerServerImports = [\n    providerServerModules.hasClerkProvider\n      ? `import { ClerkProvider as FarmClerkProvider } from \"@clerk/react\";`\n      : \"\",\n    providerServerModules.imports,\n  ]\n    .filter(Boolean)\n    .join(\"\\n\");\n\n  // Generate imports for all API routes\n  const apiImports: string[] = [];\n  const apiRegistrations: string[] = [];\n\n  apiRoutes.forEach((route, index) => {\n    if (!route.filePath) return;\n    const varName = `apiRoute${index}`;\n    apiImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(route.filePath)};`,\n    );\n    apiRegistrations.push(`\n  {\n    path: ${JSON.stringify(route.path)},\n    methods: ${JSON.stringify(route.methods.filter((method) => !route.pluginMethods?.includes(method)))},\n    endpoints: ${varName},\n  }`);\n  });\n\n  // Generate imports for all page routes\n  const pageImports: string[] = [];\n  const pageRegistrations: string[] = [];\n  const hasMarkdownPages = pageRoutes.some((route) => route.source !== undefined);\n  const orderedPageRoutes = pageRoutes\n    .map((route, index) => ({ route, index }))\n    .sort(\n      (left, right) =>\n        routePatternSpecificity(right.route.pattern) -\n          routePatternSpecificity(left.route.pattern) || left.index - right.index,\n    )\n    .map(({ route }) => route);\n\n  orderedPageRoutes.forEach((route, index) => {\n    const varName = `pageRoute${index}`;\n    if (isFarmMarkdownPageFile(route.modulePath)) {\n      pageRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(route.pattern)},\n    module: createFarmMarkdownRouteModule({\n      source: ${JSON.stringify(route.source ?? \"\")},\n      filePath: ${JSON.stringify(route.modulePath)},\n      components: farmMdxComponents,\n      config: farmMdxConfig,\n    }),\n    markdownSource: {\n      source: ${JSON.stringify(route.source ?? \"\")},\n      filePath: ${JSON.stringify(route.markdownSourcePath ?? route.modulePath)},\n    },\n  }`);\n      return;\n    }\n\n    pageImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(route.modulePath)};`,\n    );\n    const clientMetadata = pageHydrationPlans.get(route.modulePath)!;\n    pageRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(route.pattern)},\n    module: ${varName},\n    shouldHydrate: ${JSON.stringify(clientMetadata.shouldHydrate)},\n    islandStrategy: ${JSON.stringify(clientMetadata.islandStrategy)},\n    ${\n      route.source !== undefined\n        ? `markdownSource: {\n      source: ${JSON.stringify(route.source)},\n      filePath: ${JSON.stringify(route.markdownSourcePath)},\n    },`\n        : \"\"\n    }\n  }`);\n  });\n\n  // Generate imports for all layouts\n  const layoutImports: string[] = [];\n  const layoutRegistrations: string[] = [];\n\n  layoutHydrationPlans.forEach((layout, index) => {\n    const varName = `layoutRoute${index}`;\n    const clientMetadata = layout.hydration;\n    layoutImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(layout.modulePath)};`,\n    );\n    layoutRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(layout.pattern)},\n    module: ${varName},\n    shouldHydrate: ${JSON.stringify(clientMetadata.shouldHydrate)},\n    islandStrategy: ${JSON.stringify(clientMetadata.islandStrategy)},\n  }`);\n  });\n\n  const routeSlotImports: string[] = [];\n  const routeSlotRegistrations: string[] = [];\n  routeSlots.forEach((slot, index) => {\n    const varName = `routeSlot${index}`;\n    routeSlotImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(slot.modulePath)};`,\n    );\n    routeSlotRegistrations.push(`\n  {\n    name: ${JSON.stringify(slot.name)},\n    ownerPattern: ${JSON.stringify(slot.ownerPattern)},\n    pattern: ${JSON.stringify(slot.pattern)},\n    containerId: ${JSON.stringify(slot.containerId)},\n    interception: ${JSON.stringify(slot.interception)},\n    fallback: ${JSON.stringify(slot.fallback)},\n    module: ${varName},\n  }`);\n  });\n\n  // Generate imports for route-level error boundaries.\n  const errorImports: string[] = [];\n  const errorRegistrations: string[] = [];\n\n  errorRoutes.forEach((errorRoute, index) => {\n    const varName = `errorRoute${index}`;\n    errorImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(errorRoute.modulePath)};`,\n    );\n    errorRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(errorRoute.pattern)},\n    module: ${varName},\n  }`);\n  });\n\n  const metadataImageImports: string[] = [];\n  const metadataImageRegistrations: string[] = [];\n\n  metadataImageRoutes.forEach((image, index) => {\n    if (image.sourceType === \"module\" && image.modulePath) {\n      const varName = `metadataImageRoute${index}`;\n      metadataImageImports.push(\n        `import * as ${varName} from ${toVirtualEntryImportSpecifier(image.modulePath)};`,\n      );\n      metadataImageRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(image.pattern)},\n    kind: ${JSON.stringify(image.kind)},\n    fileName: ${JSON.stringify(image.fileName)},\n    sourceType: \"module\",\n    module: ${varName},\n  }`);\n      return;\n    }\n\n    metadataImageRegistrations.push(`  ${JSON.stringify(image)}`);\n  });\n\n  const applicationMetadataImports: string[] = [];\n  const applicationMetadataRegistrations: string[] = [];\n  applicationMetadataRoutes.forEach((metadata, index) => {\n    const varName = `applicationMetadataRoute${index}`;\n    applicationMetadataImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(metadata.modulePath)};`,\n    );\n    applicationMetadataRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(metadata.pattern)},\n    kind: ${JSON.stringify(metadata.kind)},\n    outputName: ${JSON.stringify(metadata.outputName)},\n    module: ${varName},\n  }`);\n  });\n\n  // Generate imports for all app middleware files\n  const middlewareImports: string[] = [];\n  const middlewareRegistrations: string[] = [];\n\n  middlewareRoutes.forEach((middlewareRoute, index) => {\n    const varName = `fileMiddleware${index}`;\n    middlewareImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(middlewareRoute.filePath)};`,\n    );\n    middlewareRegistrations.push(`\n  {\n    path: ${JSON.stringify(middlewareRoute.path)},\n    filePath: ${JSON.stringify(middlewareRoute.filePath)},\n    module: ${varName},\n  }`);\n  });\n\n  // Generate import for custom not-found page if exists\n  const notFoundImport = notFoundPath\n    ? `import * as CustomNotFound from ${toVirtualEntryImportSpecifier(notFoundPath)};`\n    : \"\";\n  const apiRouteHelpersImport =\n    apiRoutes.length > 0\n      ? `import { mergePluginAPIRoutes, getAllowedAPIRouteMethods, invokeAPIRouteEndpoint, matchAPIRouteAtBasePath, resolveAPIRouteEndpoint } from \"@farm.js/core/api/runtime\";`\n      : \"\";\n  const productionRuntimeImport = `import {\n  _runWithAfterRequest,\n  _runWithCurrentRequest,\n  _runWithAPIRequestRuntime,\n  _runWithMiddlewareContext,\n  _runWithMiddlewareData,\n  _setDefaultFarmThemeConfig,\n  addMetadataImageReference,\n  appendFarmRedirectQuery,\n  applyFarmBasePath,\n  applyFarmThemeDocument,\n  appendFarmLinkHeader,\n  applyProductionMiddlewareHeaders,\n  configureFarmCache,\n  configureFarmObservability,\n  createDefaultErrorMarkup,\n  createFarmInstrumentationLifecycle,\n  createFarmCacheKey,\n  createFarmMetadataRouteResponse,\n  createFarmThemeDocumentParts,\n  createFarmLocaleCookie,\n  createFarmProductionLifecycle,\n  createFarmNodeRequestAbortSignal,\n  createProductionMiddlewareRunner,\n  getTheme as getFarmTheme,\n  emitFarmEvent,\n  getFarmDataCache,\n  getFarmLocaleVaryHeaders,\n  getFarmRedirectError,\n  getDefaultErrorStatusText,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n  localizeFarmHref,\n  localizeFarmPathname,\n  manageFarmDocumentPreloads,\n  manageFarmLinkHeaderPreloads,\n  mergeMetadata,\n  matchesFarmIfNoneMatch,\n  normalizeRevalidatePath,\n  reportFarmPreloadWarnings,\n  renderMetadataHead,\n  resolveFarmRouteContext,\n  resolveFarmTrailingSlashRedirect,\n  resolveDefaultErrorStatus,\n  resolveFarmInstrumentationRuntime,\n  runWithFarmRequestSpan,\n  searchParamsToObject,\n  setFarmBasePath,\n  setFarmTrailingSlashPreference,\n  stripFarmBasePath,\n  stripFarmLocaleFromPathname,\n  withFarmRouteContext,\n} from \"@farm.js/core/internal/production-runtime\";`;\n  const productionSiteTelemetryImport = config.telemetry\n    ? `import { createFarmProductionSiteReporter } from \"@farm.js/core/internal/product-telemetry-runtime\";`\n    : \"\";\n  const metadataImageRuntimeImport = hasGeneratedMetadataImages\n    ? `import { createFarmMetadataImageResponse } from \"@farm.js/core/internal/metadata-image-runtime\";`\n    : \"\";\n  const pluginRuntimeImport = hasPluginRuntime\n    ? `import { PluginManager } from \"@farm.js/core/plugin\";`\n    : \"\";\n  const i18nServerImport = config.i18n.enabled\n    ? `import { _runWithFarmI18nRequest, _setDefaultFarmI18nRuntime, createFarmI18nRuntime, getFarmI18nClientSnapshot } from \"@farm.js/core/i18n/server\";`\n    : \"\";\n  const docsHandlerImport = config.docs?.enabled\n    ? adapterOwnsDocsRuntime\n      ? `import { isFarmDocsAPIRequest } from \"@farm.js/core/docs\";\nimport { createFarmDocsRuntimeHandler as createFarmDocsAdapterRuntimeHandler } from ${JSON.stringify(config.docs.adapter!.server)};\nimport * as FarmDocsAdapterReact from ${JSON.stringify(config.docs.adapter!.react)};`\n      : `import { createFarmDocsAPIHandler, createFarmDocsHandler, isFarmDocsAPIRequest } from \"@farm.js/core/docs\";`\n    : \"\";\n  const docsFontImport = config.docs?.enabled\n    ? `import { resolveFarmLayoutFonts } from \"@farm.js/core/font\";`\n    : \"\";\n  const docsRuntimeImport = config.docs?.enabled\n    ? `import { existsSync as farmDocsExistsSync } from \"node:fs\";\nimport { dirname as farmDocsDirname, join as farmDocsJoin } from \"node:path\";\nimport { fileURLToPath as farmDocsFileURLToPath } from \"node:url\";`\n    : \"\";\n  const markdownHandlerImport = config.md?.enabled\n    ? `import { applyMarkdownNegotiationHeaders, createMarkdownMirrorResponse } from \"@farm.js/core/markdown\";`\n    : \"\";\n  const appMarkdownImport = hasMarkdownPages\n    ? `import { createFarmMarkdownRouteModule, createFarmMarkdownSourceResponse } from \"@farm.js/core/app-markdown\";`\n    : \"const createFarmMarkdownSourceResponse = null;\";\n  // Always available: agents can request Markdown on any route, so the\n  // Markdown error body is not gated on the app having Markdown page files.\n  const markdownErrorImport = `import { FARM_MARKDOWN_CONTENT_TYPE, createFarmMarkdownErrorBody, farmRequestWantsMarkdown } from \"@farm.js/core/app-markdown\";`;\n  const mdxComponentsPath =\n    typeof config.mdx?.components === \"string\"\n      ? path.isAbsolute(config.mdx.components)\n        ? config.mdx.components\n        : path.join(config.root, config.mdx.components)\n      : null;\n  const mdxComponentsImport = mdxComponentsPath\n    ? `import * as FarmMdxComponentsModule from ${toVirtualEntryImportSpecifier(mdxComponentsPath)};`\n    : \"\";\n  const layerConfigPaths = (config.layers || [])\n    .map((layer) => layer.configFile)\n    .filter((configFile): configFile is string => Boolean(configFile))\n    .filter((configFile) => configFile !== configModulePath);\n  const layerConfigImports = layerConfigPaths\n    .map(\n      (configFile, index) =>\n        `import * as FarmLayerConfigModule${index} from ${toVirtualEntryImportSpecifier(configFile)};`,\n    )\n    .join(\"\\n\");\n  const layerConfigValues = layerConfigPaths.map(\n    (_configFile, index) =>\n      `(FarmLayerConfigModule${index}.default || FarmLayerConfigModule${index})`,\n  );\n  const integrationRuntimeExports = Array.from(\n    new Set([\n      ...(hasServerRuntimeIntegrations\n        ? [\"dispatchIntegrationRequest\", \"matchIntegrationRoute\"]\n        : []),\n      ...(hasRuntimeIntegrationConfig\n        ? [\"getRegisteredIntegrationAPIManifest\", \"resolveIntegrationPlugins\"]\n        : []),\n    ]),\n  );\n  const integrationRuntimeImport = integrationRuntimeExports.length\n    ? `import { ${integrationRuntimeExports.join(\", \")} } from \"@farm.js/core/integrations\";`\n    : \"\";\n  const instrumentationImport = instrumentationPath\n    ? `import * as FarmInstrumentationModule from ${toVirtualEntryImportSpecifier(instrumentationPath)};`\n    : \"\";\n  const integrationImports = `\n${configModulePath ? `import * as FarmUserConfigModule from ${toVirtualEntryImportSpecifier(configModulePath)};` : \"\"}\n${layerConfigImports}\n${integrationRuntimeImport}\n`;\n  const imageRuntime = resolveImageRuntime(config, preset);\n  const imageRuntimeImport =\n    imageRuntime === \"none\"\n      ? \"\"\n      : `import { createCloudflareImageTransformer, createFarmImageHandler } from \"@farm.js/core/image/server\";`;\n  const imageNodeRuntimeImport =\n    imageRuntime === \"node\"\n      ? `import { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } from \"@farm.js/core/image/sharp\";`\n      : \"\";\n  const apiHandlerCode =\n    apiRoutes.length > 0\n      ? `\nconst apiRouteMap = new Map(apiRoutes.map((route) => [route.path, route]));\n\nfunction matchLocalAPIRequest(request) {\n  return matchAPIRouteAtBasePath(\n    apiRouteMap,\n    new URL(request.url).pathname,\n    farmLocalAPIBasePath\n  );\n}\n\nasync function handleAPIRequest(request) {\n  const url = new URL(request.url);\n  const method = request.method.toUpperCase();\n  const match = matchLocalAPIRequest(request);\n\n  if (!match) {\n    return null;\n  }\n\n  const { route, params } = match;\n  const startedAt = Date.now();\n  emitFarmEvent({ type: \"route.matched\", pathname: url.pathname, route: route.path });\n  emitFarmEvent({\n    type: \"api.request.start\",\n    pathname: url.pathname,\n    route: route.path,\n    method,\n  });\n  const endpoint = resolveAPIRouteEndpoint(route, method);\n  if (!endpoint) {\n    const response = new Response(\n      JSON.stringify({ error: \"Method Not Allowed\" }),\n      {\n        status: 405,\n        headers: {\n          \"Allow\": getAllowedAPIRouteMethods(route).join(\", \"),\n          \"Content-Type\": \"application/json\",\n        },\n      }\n    );\n    emitFarmEvent({\n      type: \"api.request.complete\",\n      pathname: url.pathname,\n      route: route.path,\n      method,\n      status: response.status,\n      durationMs: Date.now() - startedAt,\n    });\n    return response;\n  }\n\n  try {\n    const response = await invokeAPIRouteEndpoint(\n      endpoint,\n      request,\n      params,\n      farmServerConfig.bodySizeLimit,\n    );\n    emitFarmEvent({\n      type: \"api.request.complete\",\n      pathname: url.pathname,\n      route: route.path,\n      method,\n      status: response.status,\n      durationMs: Date.now() - startedAt,\n    });\n    return response;\n  } catch (error) {\n    emitFarmEvent({\n      type: \"api.error\",\n      pathname: url.pathname,\n      route: route.path,\n      method,\n      durationMs: Date.now() - startedAt,\n      error,\n    });\n    console.error(\\`[API Error] \\${url.pathname}:\\`, error);\n    return new Response(\n      JSON.stringify({ error: \"Internal Server Error\" }),\n      { status: 500, headers: { \"Content-Type\": \"application/json\" } }\n    );\n  }\n}\n`\n      : `\nfunction matchLocalAPIRequest(_request) {\n  return null;\n}\n\nasync function handleAPIRequest(request) {\n  return null;\n}\n`;\n\n  return `\n// Farm.js SSR Entry - Generated at build time\n// All routes are bundled here, managers are created at runtime\n\n${apiImports.join(\"\\n\")}\n${pageImports.join(\"\\n\")}\n${layoutImports.join(\"\\n\")}\n${routeSlotImports.join(\"\\n\")}\n${errorImports.join(\"\\n\")}\n${metadataImageImports.join(\"\\n\")}\n${applicationMetadataImports.join(\"\\n\")}\n${middlewareImports.join(\"\\n\")}\n${notFoundImport}\n${apiRouteHelpersImport}\n${productionRuntimeImport}\n${productionSiteTelemetryImport}\n${metadataImageRuntimeImport}\n${pluginRuntimeImport}\n${i18nServerImport}\n${docsHandlerImport}\n${docsFontImport}\n${docsRuntimeImport}\n${markdownHandlerImport}\n${appMarkdownImport}\n${markdownErrorImport}\n${mdxComponentsImport}\n${integrationImports}\n${providerServerImports}\n${instrumentationImport}\n${imageRuntimeImport}\n${imageNodeRuntimeImport}\nimport { farmFontPreloadHeader } from \"virtual:farm-font-runtime\";\nimport { isFarmRouteActive } from \"@farm.js/core/router\";\n${rendererServerImports}\n\n${routeClientGraphServerRuntime}\n\nconst farmPreloadConfig = ${JSON.stringify(config.performance.preload)};\nconst farmProductionSiteTelemetry = ${\n    config.telemetry\n      ? `createFarmProductionSiteReporter({\n  renderer: ${JSON.stringify(config.renderer.name)},\n  deployTarget: ${JSON.stringify(config.deploy.target || \"custom\")},\n})`\n      : \"null\"\n  };\n\n// Custom 404 page component (if provided)\nconst hasCustomNotFound = ${notFoundPath ? \"true\" : \"false\"};\nconst CustomNotFoundComponent = ${notFoundPath ? \"CustomNotFound.default || CustomNotFound\" : \"null\"};\nconst farmUserConfig = ${\n    configModulePath ? \"(FarmUserConfigModule.default || FarmUserConfigModule)\" : \"null\"\n  };\nconst farmRuntimeConfigs = [${[...layerConfigValues, \"farmUserConfig\"].join(\", \")}].filter(Boolean);\nconst farmResolvedRuntimeConfig = Object.assign({}, ...farmRuntimeConfigs);\nsetFarmBasePath(${JSON.stringify(config.basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(config.trailingSlash)});\nconst hasConfiguredRouteContext = typeof farmResolvedRuntimeConfig.context === \"function\";\nconst configuredIntegrations = ${JSON.stringify(resolvedIntegrationProviderFallback)};\nfor (const runtimeConfig of farmRuntimeConfigs) {\n  for (const [name, integration] of Object.entries(runtimeConfig.integrations || {})) {\n    const fallback = configuredIntegrations[name];\n    configuredIntegrations[name] =\n      fallback?.providers &&\n      integration &&\n      typeof integration === \"object\" &&\n      integration.providers === undefined\n        ? { ...integration, providers: fallback.providers }\n        : integration;\n  }\n}\nconst farmIntegrationProviderModuleComponents = new Map([\n${providerServerModules.entries}\n]);\n\nfunction wrapWithFarmIntegrationProviders(element) {\n  const providers = Object.values(configuredIntegrations).flatMap(function(integration) {\n    return Array.isArray(integration?.providers) ? integration.providers : [];\n  });\n  let wrapped = element;\n  for (let index = providers.length - 1; index >= 0; index--) {\n    const provider = providers[index];\n    let Component = null;\n    if (typeof provider.component === \"function\") {\n      Component = provider.component;\n    } else if (provider.component?.module) {\n      const componentKey = provider.component.module + \"\\\\0\" + (provider.component.export || \"default\");\n      Component = farmIntegrationProviderModuleComponents.get(componentKey);\n    } else if (provider.type === \"clerk\") {\n      Component = ${providerServerModules.hasClerkProvider ? \"FarmClerkProvider\" : \"null\"};\n    }\n    if (!Component) {\n      if (!provider.component && provider.type !== \"clerk\") continue;\n      throw new Error(\"Integration provider \" + provider.name + \" did not export its configured component.\");\n    }\n    wrapped = React.createElement(Component, provider.props || {}, wrapped);\n  }\n  return wrapped;\n}\nconst serverRuntimeIntegrations = Object.fromEntries(\n  Object.entries(configuredIntegrations).filter(([, integration]) =>\n    integration && typeof integration === \"object\" && integration.serverRuntime !== false\n  ),\n);\nconst integrationRuntimeConfig = Object.assign({}, ...farmRuntimeConfigs, {\n  integrations: configuredIntegrations,\n});\nconst configuredPlugins = [\n  ${hasRuntimeIntegrationConfig ? \"...resolveIntegrationPlugins(serverRuntimeIntegrations),\" : \"\"}\n  ${\n    hasConfiguredRuntimePlugins\n      ? `...farmRuntimeConfigs.flatMap((runtimeConfig) =>\n    Array.isArray(runtimeConfig.plugins) ? runtimeConfig.plugins : [],\n  ),`\n      : \"\"\n  }\n];\nconst farmPluginRuntime = ${\n    hasPluginRuntime\n      ? `configuredPlugins.length > 0\n  ? (() => {\n      const manager = new PluginManager({\n        config: farmUserConfig || {},\n        isDev: false,\n        isProd: true,\n      });\n      manager.addPlugins(configuredPlugins);\n      return manager;\n    })()\n  : null`\n      : \"null\"\n  };\nconst hasFarmPluginHTMLTransforms = configuredPlugins.some(\n  (plugin) => plugin.render?.html || plugin.afterRender || plugin.transformHTML,\n);\nconst farmImageHandler = ${\n    imageRuntime === \"none\"\n      ? \"null\"\n      : imageRuntime === \"cloudflare\"\n        ? `createFarmImageHandler(${JSON.stringify(config.images)}, {\n  transform: createCloudflareImageTransformer(),\n  onError(error) { console.error(\"[Farm Image]\", error); },\n})`\n        : `createFarmImageHandler(${JSON.stringify(config.images)}, {\n  transform: createSharpImageTransformer(),\n  fetchRemote: createNodeImageFetcher(${JSON.stringify(config.images)}),\n  validateRemoteUrl: createNodeImageUrlValidator(${JSON.stringify(config.images)}),\n  onError(error) { console.error(\"[Farm Image]\", error); },\n})`\n  };\nconst farmMarkdownConfig = ${JSON.stringify(config.md)};\nconst farmMdxConfig = ${JSON.stringify({\n    ...config.mdx,\n    components: typeof config.mdx?.components === \"string\" ? config.mdx.components : undefined,\n  })};\nconst configuredFarmMdxComponents = farmUserConfig?.mdx?.components;\nconst farmMdxComponents = ${\n    mdxComponentsPath\n      ? `(FarmMdxComponentsModule.components || Reflect.get(FarmMdxComponentsModule, \"default\") || {})`\n      : `(configuredFarmMdxComponents && typeof configuredFarmMdxComponents === \"object\" ? configuredFarmMdxComponents : {})`\n  };\nconst farmObservabilityConfig = farmUserConfig?.observability ?? ${JSON.stringify(\n    config.observability ?? false,\n  )};\nconfigureFarmObservability(farmObservabilityConfig);\nconfigureFarmCache(farmResolvedRuntimeConfig.cache);\nconst farmI18nConfig = ${JSON.stringify(config.i18n)};\nconst farmServerConfig = ${JSON.stringify(config.server)};\nconst farmThemeConfig = ${JSON.stringify(config.theme)};\n_setDefaultFarmThemeConfig(farmThemeConfig);\nconst farmInstrumentationLifecycle = createFarmInstrumentationLifecycle(\n  ${instrumentationPath ? \"FarmInstrumentationModule\" : \"null\"},\n  {\n    root:\n      typeof globalThis.process?.cwd === \"function\" ? globalThis.process.cwd() : \".\",\n    mode: \"production\",\n    runtime: resolveFarmInstrumentationRuntime(${JSON.stringify(preset)}),\n  },\n);\nexport const farmProductionLifecycle = createFarmProductionLifecycle({\n  server: farmServerConfig,\n  start: async () => {\n    await farmInstrumentationLifecycle.start();\n    try {\n      await farmPluginRuntime?.startRuntime();\n    } catch (error) {\n      await farmInstrumentationLifecycle.shutdown();\n      throw error;\n    }\n  },\n  close: async (reason) => {\n    try {\n      await farmPluginRuntime?.closeRuntime(reason);\n    } finally {\n      await farmInstrumentationLifecycle.shutdown();\n    }\n  },\n});\nconst farmI18nRuntime = ${\n    config.i18n.enabled\n      ? `createFarmI18nRuntime(farmI18nConfig, ${JSON.stringify(i18nCatalogs)})`\n      : \"null\"\n  };\n${config.i18n.enabled ? \"_setDefaultFarmI18nRuntime(farmI18nRuntime);\" : \"\"}\nconst farmDocsBundledContentDir = ${\n    config.docs?.enabled\n      ? `(() => {\n  try {\n    const currentDir = farmDocsDirname(farmDocsFileURLToPath(import.meta.url));\n    const candidates = [\n      farmDocsJoin(currentDir, \"farm-docs-content\"),\n      farmDocsJoin(currentDir, \"..\", \"farm-docs-content\"),\n      farmDocsJoin(currentDir, \"..\", \"..\", \"farm-docs-content\"),\n    ];\n    return candidates.find((candidate) => farmDocsExistsSync(candidate)) || null;\n  } catch {\n    return null;\n  }\n})()`\n      : \"null\"\n  };\nconst farmDocsResolvedConfig = ${generateFarmDocsRuntimeConfigExpression(config.docs)};\nconst farmDocsRuntimeRoot = farmDocsBundledContentDir || ${JSON.stringify(config.root)};\nglobalThis.__FARM_DOCS_RUNTIME_CONFIG__ = {\n  root: farmDocsRuntimeRoot,\n  srcDir: ${JSON.stringify(config.srcDir)},\n  docs: farmDocsResolvedConfig,\n};\nconst farmDocsHandler = ${\n    config.docs?.enabled\n      ? adapterOwnsDocsRuntime\n        ? `createFarmDocsAdapterRuntimeHandler({\n  ...farmDocsResolvedConfig.config,\n  entry: farmDocsResolvedConfig.config?.entry || String(farmDocsResolvedConfig.entry || \"/docs\").replace(/^\\\\/+|\\\\/+$/g, \"\") || \"docs\",\n  docsPath: farmDocsResolvedConfig.entry,\n  contentDir: farmDocsResolvedConfig.contentDir || farmDocsResolvedConfig.config?.contentDir,\n}, {\n  rootDir: farmDocsRuntimeRoot,\n  clientEntry: \"/__farm_client_js_src__\",\n  stylesheets: [\"/farm-fonts.css\", \"/__farm_client_css_href__\"],\n  resolveLayoutFonts: (pathname) =>\n    resolveFarmLayoutFonts(\n      getApplicableLayouts(getFarmRoutePathname(pathname)).map((layout) => layout.module),\n    ),\n  loadReactModule: async () => FarmDocsAdapterReact,\n})`\n        : `createFarmDocsHandler(farmDocsResolvedConfig, {\n  root: farmDocsRuntimeRoot,\n  srcDir: ${JSON.stringify(config.srcDir)},\n  clientEntry: \"/__farm_client_js_src__\",\n  fontAssets: ${JSON.stringify(farmDocsFontAssets)},\n  resolveLayoutFonts: (pathname) =>\n    resolveFarmLayoutFonts(\n      getApplicableLayouts(getFarmRoutePathname(pathname)).map((layout) => layout.module),\n    ),\n  fontStylesheetHref: \"/farm-fonts.css\",\n  globalStylesheetHref: \"/assets/globals.css\",\n})`\n      : \"null\"\n  };\nconst farmDocsAPIHandler = ${\n    config.docs?.enabled\n      ? adapterOwnsDocsRuntime\n        ? \"null\"\n        : `createFarmDocsAPIHandler({ rootDir: farmDocsRuntimeRoot, srcDir: ${JSON.stringify(config.srcDir)}, docs: farmDocsResolvedConfig })`\n      : \"null\"\n  };\n\n// API routes bundled at build time\nconst apiRoutes = ${apiRoutes.length > 0 ? \"mergePluginAPIRoutes(\" : \"\"}[${apiRegistrations.join(\",\")}\n]${apiRoutes.length > 0 ? `, configuredPlugins, ${JSON.stringify(apiRoutes.map(({ path, methods }) => ({ path, methods })))})` : \"\"};\nconst farmLocalAPIBasePath = ${JSON.stringify(resolveFarmAPIServerBasePath(config.api))};\nconst farmOpenAPIReference = ${JSON.stringify(openAPIReference)};\n\nfunction isFarmLocalAPIPathname(pathname) {\n  return farmLocalAPIBasePath !== \"/\" &&\n    (pathname === farmLocalAPIBasePath ||\n      pathname.startsWith(farmLocalAPIBasePath + \"/\"));\n}\n\n// Page routes bundled at build time\nconst pageRoutes = [${pageRegistrations.join(\",\")}\n];\nconst exactPageRoutes = new Map();\nconst patternPageRoutes = [];\nfor (const route of pageRoutes) {\n  if (/[\\\\[\\\\]*:]/.test(route.pattern)) {\n    patternPageRoutes.push(route);\n  } else {\n    const exactPath = normalizeRuntimePath(route.pattern);\n    if (!exactPageRoutes.has(exactPath)) exactPageRoutes.set(exactPath, route);\n  }\n}\n\n// Layout routes bundled at build time (sorted by depth, root first)\nconst layoutRoutes = [${layoutRegistrations.join(\",\")}\n];\n\nconst routeSlots = [${routeSlotRegistrations.join(\",\")}\n];\n\n// Route-level error boundaries bundled at build time.\nconst errorRoutes = [${errorRegistrations.join(\",\")}\n];\n\n// Metadata image routes bundled at build time\nconst metadataImageRoutes = [${metadataImageRegistrations.join(\",\")}\n];\n\n// sitemap.ts, robots.ts, and manifest.ts routes bundled at build time\nconst applicationMetadataRoutes = [${applicationMetadataRegistrations.join(\",\")}\n];\n\n// Redirect routes bundled at build time\nconst redirectRoutes = ${JSON.stringify(redirectRoutes, null, 2)};\n\n// Legacy rewrites() entries resolved at build time for standalone parity.\nconst configuredRewriteRoutes = ${JSON.stringify(configuredRewriteRoutes, null, 2)};\n\n// Legacy headers() entries resolved at build time for standalone parity.\nconst configuredHeaderRoutes = ${JSON.stringify(configuredHeaderRoutes, null, 2)};\n\nfunction getFarmI18nSnapshot() {\n  return ${config.i18n.enabled ? \"getFarmI18nClientSnapshot()\" : \"undefined\"};\n}\n\nfunction getFarmRoutePathname(pathname) {\n  return farmI18nRuntime\n    ? stripFarmLocaleFromPathname(stripFarmBasePath(pathname), farmI18nConfig)\n    : stripFarmBasePath(pathname);\n}\n\nfunction serializeFarmInlineValue(value) {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\\\\\u003c\")\n    .replace(/\\\\u2028/g, \"\\\\\\\\u2028\")\n    .replace(/\\\\u2029/g, \"\\\\\\\\u2029\");\n}\n\nfunction renderFarmClientBootstrapScript(canonicalPath, selectedRouteSlots, pageProps) {\n  const integrationManifest = ${\n    hasRuntimeIntegrationConfig ? \"getRegisteredIntegrationAPIManifest()\" : \"{}\"\n  };\n  const serializedRouteSlots = serializeFarmInlineValue(selectedRouteSlots || []);\n  const serializedPageProps = serializeFarmInlineValue(pageProps || {});\n  let source = 'window.__FARM_PROPS__=' + serializedPageProps +\n    ';window.__FARM_INTEGRATION_API_MANIFEST__=' +\n    serializeFarmInlineValue(integrationManifest) +\n    ';window.__FARM_ROUTE_SLOTS__=' + serializedRouteSlots + ';';\n  if (typeof canonicalPath === \"string\" && canonicalPath.startsWith(\"/\")) {\n    const serializedPath = serializeFarmInlineValue(canonicalPath);\n    source += 'if(location.pathname+location.search!==' + serializedPath + '){' +\n      'history.replaceState(Object.assign({},history.state||{},{path:' + serializedPath + '}),\"\",' +\n      serializedPath + ');}';\n  }\n  return '<script id=\"__farm_route_slots_data__\" type=\"application/json\">' +\n    serializedRouteSlots +\n    '</script><script>' + source + '</script>';\n}\n\nfunction renderFarmRendererHydrationScript() {\n  return typeof ReactDOMServer.generateHydrationScript === \"function\"\n    ? ReactDOMServer.generateHydrationScript()\n    : \"\";\n}\n\nfunction escapeFarmHtmlAttribute(value) {\n  return String(value)\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nasync function renderFarmElement(ReactDOMServer, element) {\n  const streamErrors = [];\n  const encoder = new TextEncoder();\n  const decoder = new TextDecoder();\n  const normalizeChunk = function(chunk) {\n    if (typeof chunk === \"string\") return encoder.encode(chunk);\n    if (chunk instanceof Uint8Array) return chunk;\n    return new Uint8Array(chunk);\n  };\n  const decodeChunks = function(chunks) {\n    let html = \"\";\n    for (const chunk of chunks) {\n      html += decoder.decode(chunk, { stream: true });\n    }\n    return html + decoder.decode();\n  };\n  const throwStreamError = function() {\n    if (streamErrors.length > 0) throw streamErrors[0];\n  };\n\n  if (typeof ReactDOMServer.renderToReadableStream === \"function\") {\n    const stream = await ReactDOMServer.renderToReadableStream(element, {\n      onError(error) {\n        // redirect()/notFound() are control flow, not render failures: the\n        // request handler must still receive them to map the response status,\n        // but they should not produce a misleading SSR failure log.\n        streamErrors.push(error);\n        if (isFarmRedirectError(error) || isFarmNotFoundError(error)) return;\n        console.error(\"[Farm SSR stream]\", error);\n      },\n    });\n    const reader = stream.getReader();\n    const firstResult = await reader.read();\n    if (firstResult.done) {\n      throwStreamError();\n      return { html: \"\", shellHtml: \"\", streamErrors };\n    }\n\n    const firstChunk = normalizeChunk(firstResult.value);\n    let allReady = false;\n    const allReadyPromise = stream.allReady;\n    if (allReadyPromise && typeof allReadyPromise.then === \"function\") {\n      Promise.resolve(allReadyPromise).then(\n        function() {\n          allReady = true;\n        },\n        function() {},\n      );\n      // React resolves allReady in the same turn for a synchronous tree. A\n      // suspended tree remains pending, so its already-produced shell can be\n      // returned without rendering the element a second time.\n      await Promise.resolve();\n    }\n\n    if (allReady) {\n      const chunks = [firstChunk];\n      while (true) {\n        const result = await reader.read();\n        if (result.done) break;\n        chunks.push(normalizeChunk(result.value));\n      }\n      throwStreamError();\n      const html = decodeChunks(chunks);\n      return { html, shellHtml: html, streamErrors };\n    }\n\n    let replayFirstChunk = true;\n    const replayStream = new ReadableStream({\n      pull(controller) {\n        if (replayFirstChunk) {\n          replayFirstChunk = false;\n          controller.enqueue(firstChunk);\n          return;\n        }\n        return reader.read().then(\n          function(result) {\n            if (result.done) controller.close();\n            else controller.enqueue(normalizeChunk(result.value));\n          },\n          function(error) {\n            controller.error(error);\n          },\n        );\n      },\n      cancel(reason) {\n        return reader.cancel(reason);\n      },\n    });\n    return {\n      stream: replayStream,\n      shellHtml: new TextDecoder().decode(firstChunk),\n      streamErrors,\n    };\n  }\n\n  if (typeof ReactDOMServer.renderToPipeableStream === \"function\") {\n    let pipeableStream;\n    let streamController;\n    let streamClosed = false;\n    let streamStarted = false;\n    let allReady = false;\n    let decisionState = \"pending\";\n    let settleDecision;\n    let rejectDecision;\n    let settleComplete;\n    let rejectComplete;\n    const chunks = [];\n    const decision = new Promise(function(resolve, reject) {\n      settleDecision = resolve;\n      rejectDecision = reject;\n    });\n    const complete = new Promise(function(resolve, reject) {\n      settleComplete = resolve;\n      rejectComplete = reject;\n    });\n    const stream = new ReadableStream({\n      start(controller) {\n        streamController = controller;\n      },\n      cancel(reason) {\n        if (pipeableStream && typeof pipeableStream.abort === \"function\") {\n          pipeableStream.abort(reason);\n        }\n      },\n    });\n    const fail = function(error) {\n      if (!streamClosed) {\n        streamClosed = true;\n        if (decisionState === \"stream\") streamController.error(error);\n      }\n      if (decisionState === \"complete\") rejectComplete(error);\n      else if (decisionState === \"pending\") rejectDecision(error);\n    };\n    const destination = {\n      write(chunk) {\n        if (streamClosed) return false;\n        const normalized = normalizeChunk(chunk);\n        if (streamStarted) streamController.enqueue(normalized);\n        else chunks.push(normalized);\n        return true;\n      },\n      end() {\n        if (streamClosed) return;\n        streamClosed = true;\n        if (streamStarted) streamController.close();\n        settleComplete();\n      },\n      on() {\n        return destination;\n      },\n      destroy(error) {\n        fail(error || new Error(\"React server render stream was destroyed\"));\n      },\n    };\n    pipeableStream = ReactDOMServer.renderToPipeableStream(element, {\n      onShellReady() {\n        try {\n          pipeableStream.pipe(destination);\n          queueMicrotask(function() {\n            decisionState = allReady ? \"complete\" : \"stream\";\n            settleDecision(decisionState);\n          });\n        } catch (error) {\n          fail(error);\n        }\n      },\n      onAllReady() {\n        allReady = true;\n      },\n      onShellError: fail,\n      onError(error) {\n        // Same control-flow guard as the readable-stream path above.\n        streamErrors.push(error);\n        if (isFarmRedirectError(error) || isFarmNotFoundError(error)) return;\n        console.error(\"[Farm SSR stream]\", error);\n      },\n    });\n\n    if ((await decision) === \"complete\") {\n      await complete;\n      throwStreamError();\n      const html = decodeChunks(chunks);\n      return { html, shellHtml: html, streamErrors };\n    }\n\n    streamStarted = true;\n    for (const chunk of chunks) streamController.enqueue(chunk);\n    if (streamClosed) streamController.close();\n    return {\n      stream,\n      shellHtml: chunks.length > 0 ? new TextDecoder().decode(chunks[0]) : \"\",\n      streamErrors,\n    };\n  }\n\n  if (ReactDOMServer.renderToStringWithHead) {\n    const rendered = await ReactDOMServer.renderToStringWithHead(element);\n    return {\n      html: rendered.html,\n      head: rendered.head || \"\",\n      shellHtml: rendered.html,\n      streamErrors,\n    };\n  }\n  const html = await ReactDOMServer.renderToString(element);\n  return { html, head: \"\", shellHtml: html, streamErrors };\n}\n\nasync function renderFarmElementToString(ReactDOMServer, element) {\n  const rendered = await renderFarmElement(ReactDOMServer, element);\n  if (rendered.html !== undefined) return rendered.html;\n  const html = await new Response(rendered.stream).text();\n  if (rendered.streamErrors.length > 0) throw rendered.streamErrors[0];\n  return html;\n}\n\nfunction createFarmDocumentStream(contentStream, prefix, suffix, onComplete) {\n  const encoder = new TextEncoder();\n  const reader = contentStream.getReader();\n  return new ReadableStream({\n    start(controller) {\n      controller.enqueue(encoder.encode(prefix));\n    },\n    async pull(controller) {\n      try {\n        const result = await reader.read();\n        if (result.done) {\n          controller.enqueue(encoder.encode(suffix));\n          if (onComplete) onComplete();\n          controller.close();\n          return;\n        }\n        controller.enqueue(result.value);\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n    cancel(reason) {\n      return reader.cancel(reason);\n    },\n  });\n}\n\nfunction createFarmErrorDocument(html, title) {\n  const escapedTitle = escapeFarmHtmlAttribute(title || \"Application Error\");\n  const trimmedHtml = html.trim();\n  const hasFullDocument = trimmedHtml.startsWith(\"<html\") ||\n    trimmedHtml.startsWith(\"<!DOCTYPE\");\n\n  if (!hasFullDocument) {\n    return '<!DOCTYPE html>\\\\n<html lang=\"en\">\\\\n<head>\\\\n' +\n      '  <meta charset=\"utf-8\">\\\\n' +\n      '  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\\\\n' +\n      '  <link rel=\"icon\" href=\"data:,\">\\\\n' +\n      '  <title>' + escapedTitle + '</title>\\\\n' +\n      '  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\\\\n' +\n      renderFarmRendererHydrationScript() + '\\\\n' +\n      '</head>\\\\n<body>\\\\n' +\n      '  <div id=\"root\">' + html + '</div>\\\\n' +\n      '  ' + renderFarmClientBootstrapScript() + '\\\\n' +\n      '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n' +\n      '</body>\\\\n</html>';\n  }\n\n  let fullHtml = html;\n  if (!/\\\\sid=[\"']root[\"']/.test(fullHtml)) {\n    fullHtml = fullHtml\n      .replace(/<body([^>]*)>/i, '<body$1><div id=\"root\">')\n      .replace(/<\\\\/body>/i, '</div></body>');\n  }\n  fullHtml = fullHtml\n    .replace(/<head([^>]*)>/i, '<head$1>\\\\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">')\n    // Function replacements: dynamic markup may contain $-sequences ($&, $', $$)\n    // that a string replacement would expand, corrupting the document.\n    .replace(/<\\\\/head>/i, function() { return renderFarmRendererHydrationScript() + '\\\\n</head>'; })\n    .replace(/<head([^>]*)>([\\\\s\\\\S]*?)<\\\\/head>/i, function(match, attrs, headContent) {\n      return headContent.includes(\"<title\")\n        ? match\n        : '<head' + attrs + '>' + headContent + '\\\\n  <title>' + escapedTitle + '</title>\\\\n</head>';\n    })\n    .replace(\n      /<\\\\/body>/i,\n      function() {\n        return '  ' + renderFarmClientBootstrapScript() + '\\\\n' +\n          '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>';\n      },\n    );\n  return fullHtml.trim().startsWith(\"<!DOCTYPE\")\n    ? fullHtml\n    : \"<!DOCTYPE html>\\\\n\" + fullHtml;\n}\n\nfunction renderFarmI18nAlternateLinks(requestPath, snapshot) {\n  if (!snapshot || snapshot.routing === \"none\") return \"\";\n  const url = new URL(requestPath, \"http://farm.local\");\n  const routePathname = stripFarmLocaleFromPathname(url.pathname, snapshot);\n  const links = snapshot.locales.map(function(locale) {\n    const href = localizeFarmPathname(routePathname, locale, snapshot);\n    return '<link rel=\"alternate\" hreflang=\"' + escapeFarmHtmlAttribute(locale) +\n      '\" href=\"' + escapeFarmHtmlAttribute(href) + '\">';\n  });\n  links.push(\n    '<link rel=\"alternate\" hreflang=\"x-default\" href=\"' +\n      escapeFarmHtmlAttribute(\n        localizeFarmPathname(routePathname, snapshot.defaultLocale, snapshot)\n      ) +\n      '\">'\n  );\n  return links.join(\"\");\n}\n\nfunction applyFarmI18nDocument(html, requestPath, snapshot) {\n  if (!snapshot) return html;\n  const locale = escapeFarmHtmlAttribute(snapshot.locale);\n  const direction = escapeFarmHtmlAttribute(snapshot.direction);\n  let nextHtml = html.replace(/<html([^>]*)>/i, function(_match, attributes) {\n    const cleaned = attributes.replace(\n      /\\\\s+(?:lang|dir)=(?:\"[^\"]*\"|'[^']*'|[^\\\\s>]+)/gi,\n      \"\"\n    );\n    return '<html' + cleaned + ' lang=\"' + locale + '\" dir=\"' + direction + '\">';\n  });\n  const runtimeMarkup =\n    renderFarmI18nAlternateLinks(requestPath, snapshot) +\n    '<script>window.__FARM_I18N__ = ' + serializeFarmInlineValue(snapshot) + ';</script>';\n  nextHtml = nextHtml.replace(/<head([^>]*)>/i, function(_match, attributes) {\n    // Function replacement: runtimeMarkup may contain $-sequences ($&, $', $$).\n    return '<head' + attributes + '>' + runtimeMarkup;\n  });\n  return nextHtml;\n}\n\nfunction appendFarmVary(headers, value) {\n  const existing = headers.get(\"Vary\");\n  const values = new Set(\n    (existing ? existing.split(\",\") : []).map(function(entry) { return entry.trim(); }).filter(Boolean)\n  );\n  values.add(value);\n  headers.set(\"Vary\", Array.from(values).join(\", \"));\n}\n\nfunction applyFarmI18nResponse(response, resolution) {\n  if (!farmI18nRuntime || !resolution) return response;\n  const headers = new Headers(response.headers);\n  if (resolution.persist) {\n    headers.append(\"Set-Cookie\", createFarmLocaleCookie(resolution.locale, farmI18nConfig));\n  }\n  const varyHeaders = getFarmLocaleVaryHeaders(farmI18nConfig, resolution);\n  for (const header of varyHeaders) appendFarmVary(headers, header);\n  if (varyHeaders.length > 0) {\n    headers.set(\"Cache-Control\", \"private, no-store\");\n  }\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nfunction hasOnlyValidFarmLocaleCookie(cookieHeader) {\n  if (!farmI18nRuntime || !cookieHeader) return false;\n  const parts = cookieHeader.split(\";\");\n  if (parts.length !== 1) return false;\n\n  const cookie = parts[0].trim();\n  const separator = cookie.indexOf(\"=\");\n  if (separator <= 0) return false;\n\n  let name;\n  let value;\n  try {\n    name = decodeURIComponent(cookie.slice(0, separator).trim());\n    value = decodeURIComponent(cookie.slice(separator + 1).trim());\n  } catch {\n    return false;\n  }\n\n  return (\n    name === farmI18nConfig.cookie.name &&\n    farmI18nConfig.locales.includes(value)\n  );\n}\n\nfunction hasPrivateFarmRequestHeaders(request, farmLocaleResolution) {\n  if (request.headers.get(\"authorization\")) return true;\n  const cookieHeader = request.headers.get(\"cookie\");\n  if (!cookieHeader) return false;\n\n  return !(\n    farmLocaleResolution?.source === \"url\" &&\n    hasOnlyValidFarmLocaleCookie(cookieHeader)\n  );\n}\n\n${generateRuntimePathMatcherSource()}\n\nfunction getMatchingErrorBoundary(pathname) {\n  const pathSegments = splitRuntimePath(pathname);\n  let bestMatch = null;\n\n  for (const errorRoute of errorRoutes) {\n    const patternDepth = splitRuntimePath(errorRoute.pattern).length;\n    if (patternDepth > pathSegments.length) continue;\n    const candidatePath = patternDepth === 0\n      ? \"/\"\n      : \"/\" + pathSegments.slice(0, patternDepth).join(\"/\");\n    const params = matchRuntimePathPattern(errorRoute.pattern, candidatePath);\n    if (params === null) continue;\n\n    if (!bestMatch || patternDepth > bestMatch.depth) {\n      bestMatch = { route: errorRoute, params, depth: patternDepth };\n    }\n  }\n\n  return bestMatch;\n}\n\nfunction getMatchingMetadataImage(pathname, kind) {\n  const pathSegments = splitRuntimePath(pathname);\n  let bestMatch = null;\n\n  for (const image of metadataImageRoutes) {\n    if (image.kind !== kind) continue;\n    const patternDepth = splitRuntimePath(image.pattern).length;\n    if (patternDepth > pathSegments.length) continue;\n\n    const pagePath = patternDepth === 0\n      ? \"/\"\n      : \"/\" + pathSegments.slice(0, patternDepth).join(\"/\");\n    const params = matchRuntimePathPattern(image.pattern, pagePath);\n    if (params === null) continue;\n\n    if (!bestMatch || patternDepth > bestMatch.depth) {\n      bestMatch = { image, params, pagePath, depth: patternDepth };\n    }\n  }\n\n  return bestMatch;\n}\n\nfunction matchMetadataImageRequest(pathname) {\n  const normalizedPath = normalizeRuntimePath(pathname);\n  let kind;\n  let fileName;\n\n  if (normalizedPath === \"/opengraph-image\" || normalizedPath.endsWith(\"/opengraph-image\")) {\n    kind = \"opengraph\";\n    fileName = \"opengraph-image\";\n  } else if (normalizedPath === \"/twitter-image\" || normalizedPath.endsWith(\"/twitter-image\")) {\n    kind = \"twitter\";\n    fileName = \"twitter-image\";\n  } else {\n    return null;\n  }\n\n  const pagePath = normalizedPath.slice(0, -fileName.length - 1) || \"/\";\n  for (const image of metadataImageRoutes) {\n    if (image.kind !== kind) continue;\n    const params = matchRuntimePathPattern(image.pattern, pagePath);\n    if (params !== null) return { image, params, pagePath };\n  }\n\n  return null;\n}\n\nfunction createMetadataImageReference(match, locale) {\n  const image = match.image;\n  const metadata = image.sourceType === \"static\" ? image.staticInfo : image.module;\n  const basePath = match.pagePath === \"/\" ? \"\" : match.pagePath;\n  const version = image.sourceType === \"static\" ? \"?v=\" + image.staticInfo.hash : \"\";\n  const href = basePath + \"/\" + image.fileName + version;\n  const localizedHref = locale ? localizeFarmHref(href, locale, farmI18nConfig) : href;\n\n  return {\n    kind: image.kind,\n    href: applyFarmBasePath(localizedHref),\n    width: metadata?.width ?? metadata?.size?.width,\n    height: metadata?.height ?? metadata?.size?.height,\n    alt: metadata?.alt,\n    contentType: metadata?.contentType,\n  };\n}\n\nfunction decodeMetadataImage(data) {\n  const binary = atob(data);\n  const bytes = new Uint8Array(binary.length);\n  for (let index = 0; index < binary.length; index++) {\n    bytes[index] = binary.charCodeAt(index);\n  }\n  return bytes;\n}\n\nasync function handleMetadataImageRequest(request, routePathname) {\n  const url = new URL(request.url);\n  const match = matchMetadataImageRequest(routePathname || url.pathname);\n  if (!match) return null;\n\n  const method = request.method.toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    return new Response(null, { status: 405, headers: { Allow: \"GET, HEAD\" } });\n  }\n\n  const image = match.image;\n  if (image.sourceType === \"static\") {\n    const etag = '\"' + image.staticInfo.hash + '\"';\n    const isVersioned = url.searchParams.get(\"v\") === image.staticInfo.hash;\n    const headers = new Headers({\n      \"Content-Type\": image.staticInfo.contentType,\n      \"Content-Length\": String(image.staticInfo.byteLength),\n      \"Cache-Control\": isVersioned\n        ? \"public, max-age=31536000, immutable\"\n        : \"public, max-age=0, must-revalidate\",\n      \"ETag\": etag,\n      \"X-Content-Type-Options\": \"nosniff\",\n    });\n\n    if (matchesFarmIfNoneMatch(request.headers.get(\"if-none-match\"), etag)) {\n      return new Response(null, { status: 304, headers });\n    }\n\n    if (!image.bytes) image.bytes = decodeMetadataImage(image.data);\n    return new Response(method === \"HEAD\" ? null : image.bytes, { status: 200, headers });\n  }\n\n  try {\n    const imageModule = image.module;\n    if (!imageModule?.default) {\n      throw new Error(\"Metadata image module does not export a default component or handler\");\n    }\n\n    const searchParams = searchParamsToObject(url.searchParams);\n    const props = {\n      params: match.params,\n      searchParams: Promise.resolve(searchParams),\n      path: match.pagePath,\n    };\n    const value = typeof imageModule.default === \"function\"\n      ? await imageModule.default(props)\n      : imageModule.default;\n\n    ${\n      hasGeneratedMetadataImages\n        ? `return createFarmMetadataImageResponse(value, imageModule, {\n      method,\n      ifNoneMatch: request.headers.get(\"if-none-match\"),\n    });`\n        : 'throw new Error(\"Generated metadata image runtime is unavailable\");'\n    }\n  } catch (error) {\n    console.error(\"Metadata image render failed:\", error);\n    return new Response(\"Internal Server Error\", {\n      status: 500,\n      headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n    });\n  }\n}\n\nfunction matchApplicationMetadataRouteRequest(pathname) {\n  const normalizedPath = normalizeRuntimePath(pathname);\n  for (const metadata of applicationMetadataRoutes) {\n    const suffix = \"/\" + metadata.outputName;\n    if (normalizedPath !== suffix && !normalizedPath.endsWith(suffix)) continue;\n    const routePath = normalizedPath.slice(0, -suffix.length) || \"/\";\n    const params = matchRuntimePathPattern(metadata.pattern, routePath);\n    if (params !== null) return { metadata, params, routePath };\n  }\n  return null;\n}\n\nfunction getMatchingApplicationMetadataRoute(pathname, kind) {\n  const normalizedPath = normalizeRuntimePath(pathname);\n  const pathSegments = splitRuntimePath(normalizedPath);\n  let bestMatch = null;\n\n  for (const metadata of applicationMetadataRoutes) {\n    if (metadata.kind !== kind) continue;\n    const patternDepth = splitRuntimePath(metadata.pattern).length;\n    if (patternDepth > pathSegments.length) continue;\n    const routePath = patternDepth === 0\n      ? \"/\"\n      : \"/\" + pathSegments.slice(0, patternDepth).join(\"/\");\n    const params = matchRuntimePathPattern(metadata.pattern, routePath);\n    if (params === null) continue;\n    if (!bestMatch || patternDepth > bestMatch.depth) {\n      bestMatch = { metadata, params, routePath, depth: patternDepth };\n    }\n  }\n\n  return bestMatch;\n}\n\nfunction createApplicationMetadataHref(match, locale) {\n  const basePath = match.routePath === \"/\" ? \"\" : match.routePath;\n  const href = basePath + \"/\" + match.metadata.outputName;\n  const localizedHref = locale ? localizeFarmHref(href, locale, farmI18nConfig) : href;\n  return applyFarmBasePath(localizedHref);\n}\n\nasync function handleApplicationMetadataRouteRequest(request, routePathname) {\n  const url = new URL(request.url);\n  const match = matchApplicationMetadataRouteRequest(routePathname || url.pathname);\n  if (!match) return null;\n\n  const method = request.method.toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    return new Response(null, { status: 405, headers: { Allow: \"GET, HEAD\" } });\n  }\n\n  try {\n    const routeModule = match.metadata.module;\n    if (routeModule?.default === undefined) {\n      throw new Error(\"Metadata route module does not export a default value or handler\");\n    }\n    const value = typeof routeModule.default === \"function\"\n      ? await routeModule.default({\n          request,\n          params: match.params,\n          searchParams: url.searchParams,\n          path: match.routePath,\n        })\n      : routeModule.default;\n    return createFarmMetadataRouteResponse(match.metadata.kind, value, routeModule, { method });\n  } catch (error) {\n    console.error(\"Metadata route render failed:\", error);\n    return new Response(\"Internal Server Error\", {\n      status: 500,\n      headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n    });\n  }\n}\n\n${generateRedirectInterpolationSource()}\n\nfunction matchRedirectRoute(pathname, locale, search) {\n  for (const redirect of redirectRoutes) {\n    const params = matchRuntimePathPattern(redirect.source, pathname);\n    if (!params) continue;\n    const destination = interpolateRedirectDestination(redirect.destination, params);\n    const localizedDestination =\n      locale && destination.startsWith(\"/\") && !destination.startsWith(\"//\")\n        ? localizeFarmHref(destination, locale, farmI18nConfig)\n        : destination;\n    return {\n      destination: appendFarmRedirectQuery(localizedDestination, search),\n      statusCode: redirect.statusCode ?? (redirect.permanent ? 308 : 307),\n    };\n  }\n  return null;\n}\n\nfunction matchRewriteRoute(pathname, locale) {\n  for (const rewrite of configuredRewriteRoutes) {\n    const params = matchRuntimePathPattern(rewrite.source, pathname);\n    if (!params) continue;\n    const destination = interpolateRedirectDestination(rewrite.destination, params);\n    return locale && destination.startsWith(\"/\") && !destination.startsWith(\"//\")\n      ? localizeFarmHref(destination, locale, farmI18nConfig)\n      : destination;\n  }\n  return null;\n}\n\nfunction createRewrittenRequest(request, destination) {\n  const sourceUrl = new URL(request.url);\n  const destinationUrl = new URL(destination, sourceUrl);\n  if (!destinationUrl.search && sourceUrl.search) {\n    destinationUrl.search = sourceUrl.search;\n  }\n  return new Request(destinationUrl, request);\n}\n\n${generateConfiguredResponseHeadersRuntimeSource()}\n\n// App middleware files bundled at build time (sorted by depth, root first)\nconst fileMiddlewareModules = [${middlewareRegistrations.join(\",\")}\n];\n\nconst farmMiddlewareRunner = ${\n    hasMiddlewareRuntime\n      ? `createProductionMiddlewareRunner({\n  config: farmUserConfig?.middleware,\n  modules: fileMiddlewareModules,\n  i18n: farmI18nConfig,\n  server: farmServerConfig,\n})`\n      : \"null\"\n  };\n\n${apiHandlerCode}\n\nfunction matchLocalIntegrationRequest(request) {\n  ${\n    hasServerRuntimeIntegrations\n      ? `return matchIntegrationRoute(serverRuntimeIntegrations, {\n    pathname: new URL(request.url).pathname,\n    method: request.method,\n  });`\n      : \"return null;\"\n  }\n}\n\nasync function handleIntegrationRequest(request) {\n  const matchedIntegrationRoute = matchLocalIntegrationRequest(request);\n  if (!matchedIntegrationRoute) {\n    return null;\n  }\n\n  ${\n    hasServerRuntimeIntegrations\n      ? `\n  return dispatchIntegrationRequest(\n    {\n      integration: matchedIntegrationRoute.integration,\n      config: integrationRuntimeConfig,\n      isDev: false,\n      isProd: true,\n    },\n    request,\n  );`\n      : \"return null;\"\n  }\n}\n\n/**\n * Match URL to page route pattern\n */\nfunction matchPageRoute(pathname) {\n  const exactRoute = exactPageRoutes.get(normalizeRuntimePath(pathname));\n  if (exactRoute) return { route: exactRoute, params: {} };\n\n  for (const route of patternPageRoutes) {\n    const params = matchRuntimePathPattern(route.pattern, pathname);\n    if (params !== null) return { route, params };\n  }\n  return null;\n}\n\nfunction matchesRoutePrefix(pathname, pattern) {\n  return pattern === \"/\" ||\n    isFarmRouteActive(pattern, normalizeRuntimePath(pathname), { exact: false });\n}\n\nfunction routeSlotSpecificity(slot) {\n  return slot.pattern.split(\"/\").reduce(function(score, segment) {\n    if (!segment) return score;\n    // Optional catch-alls rank below their parent path (mirrors routeSpecificity).\n    if (segment.startsWith(\"[[...\")) return score - 1;\n    if (segment.startsWith(\"[...\")) return score + 2;\n    if (segment.startsWith(\"[\")) return score + 3;\n    return score + 10;\n  }, 0);\n}\n\nfunction matchRouteSlots(pathname, interceptFrom) {\n  const groups = new Map();\n  for (const slot of routeSlots) {\n    if (!matchesRoutePrefix(pathname, slot.ownerPattern)) continue;\n    const key = slot.ownerPattern + \":\" + slot.name;\n    const entries = groups.get(key) || [];\n    entries.push(slot);\n    groups.set(key, entries);\n  }\n\n  const normalizedFrom =\n    typeof interceptFrom === \"string\" && interceptFrom.startsWith(\"/\")\n      ? new URL(interceptFrom, \"http://farm.local\").pathname\n      : null;\n  const matches = [];\n\n  for (const entries of groups.values()) {\n    const candidates = entries\n      .filter(function(entry) { return !entry.fallback; })\n      .filter(function(entry) {\n        return !entry.interception ||\n          (normalizedFrom && matchesRoutePrefix(normalizedFrom, entry.ownerPattern));\n      })\n      .map(function(entry) {\n        return {\n          entry: entry,\n          params: matchRuntimePathPattern(entry.pattern, pathname),\n        };\n      })\n      .filter(function(candidate) { return candidate.params !== null; })\n      .sort(function(left, right) {\n        if (left.entry.interception !== right.entry.interception) {\n          return left.entry.interception ? -1 : 1;\n        }\n        return routeSlotSpecificity(right.entry) - routeSlotSpecificity(left.entry);\n      });\n\n    if (candidates[0]) {\n      matches.push({ ...candidates[0].entry, params: candidates[0].params });\n      continue;\n    }\n\n    const fallback = entries.find(function(entry) { return entry.fallback; });\n    if (fallback) matches.push({ ...fallback, params: {} });\n  }\n\n  return matches.sort(function(left, right) {\n    const ownerDepth =\n      left.ownerPattern.split(\"/\").filter(Boolean).length -\n      right.ownerPattern.split(\"/\").filter(Boolean).length;\n    return ownerDepth || left.name.localeCompare(right.name);\n  });\n}\n\nfunction hasLocalRequestRoute(request, routePathname) {\n  const pathname = new URL(request.url).pathname;\n  if (\n    farmOpenAPIReference &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.route)\n  ) {\n    return true;\n  }\n  if (matchLocalAPIRequest(request) || matchLocalIntegrationRequest(request)) {\n    return true;\n  }\n  if (\n    matchPageRoute(routePathname) ||\n    matchMetadataImageRequest(routePathname) ||\n    matchApplicationMetadataRouteRequest(routePathname)\n  ) {\n    return true;\n  }\n  if (${imageRuntime === \"none\" ? \"false\" : `pathname === ${JSON.stringify(config.images.path)}`}) {\n    return true;\n  }\n  ${\n    config.docs?.enabled\n      ? `const docsPath = normalizeRuntimePath(farmDocsResolvedConfig?.entry || \"/docs\");\n  if (\n    isFarmDocsAPIRequest(pathname) ||\n    docsPath === \"/\" ||\n    pathname === docsPath ||\n    pathname.startsWith(docsPath + \"/\")\n  ) {\n    return true;\n  }`\n      : \"\"\n  }\n  return false;\n}\n\nfunction getFarmPluginRequestOptions(request) {\n  const url = new URL(request.url);\n  const pathname = url.pathname;\n  const routePathname = getFarmRoutePathname(pathname);\n  const route = { pathname };\n  if (\n    farmOpenAPIReference &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.route)\n  ) {\n    return {\n      kind: \"docs\",\n      route: { ...route, pattern: normalizeRuntimePath(farmOpenAPIReference.route) },\n    };\n  }\n  const isDocsAPIRequest = ${config.docs?.enabled ? \"isFarmDocsAPIRequest(pathname)\" : \"false\"};\n  const integrationMatch = ${\n    hasServerRuntimeIntegrations\n      ? `matchIntegrationRoute(serverRuntimeIntegrations, {\n    pathname,\n    method: request.method,\n  })`\n      : \"null\"\n  };\n\n  if (integrationMatch) {\n    return {\n      kind: \"integration\",\n      route: {\n        ...route,\n        pattern: integrationMatch.route.path,\n        params: integrationMatch.params,\n      },\n    };\n  }\n\n  const docsPath = normalizeRuntimePath(farmDocsResolvedConfig?.entry || \"/docs\");\n  if (\n    isDocsAPIRequest ||\n    (farmDocsHandler && (pathname === docsPath || pathname.startsWith(docsPath + \"/\")))\n  ) {\n    return { kind: \"docs\", route: { ...route, pattern: docsPath } };\n  }\n\n  const apiMatch = ${apiRoutes.length > 0 ? \"matchLocalAPIRequest(request)\" : \"null\"};\n  if (apiMatch) {\n    return {\n      kind: \"api\",\n      route: { ...route, pattern: apiMatch.route.path, params: apiMatch.params },\n    };\n  }\n\n  const metadataImageMatch = matchMetadataImageRequest(routePathname);\n  if (metadataImageMatch) {\n    return {\n      kind: \"asset\",\n      route: {\n        ...route,\n        pattern: metadataImageMatch.image.pattern,\n        params: metadataImageMatch.params,\n      },\n    };\n  }\n\n  const applicationMetadataMatch = matchApplicationMetadataRouteRequest(routePathname);\n  if (applicationMetadataMatch) {\n    return {\n      kind: \"asset\",\n      route: {\n        ...route,\n        pattern: applicationMetadataMatch.metadata.pattern,\n        params: applicationMetadataMatch.params,\n      },\n    };\n  }\n\n  const pageMatch = matchPageRoute(routePathname);\n  if (pageMatch) {\n    return {\n      kind: \"page\",\n      route: {\n        ...route,\n        pattern: pageMatch.route.pattern,\n        params: pageMatch.params,\n      },\n    };\n  }\n\n  if (isFarmLocalAPIPathname(pathname)) {\n    return { kind: \"api\", route };\n  }\n\n  if (request.method === \"GET\" || request.method === \"HEAD\") {\n    return { kind: \"page\", route };\n  }\n\n  return { kind: \"request\", route };\n}\n\n/**\n * Get applicable layouts for a page path (from root to most specific)\n */\nfunction getApplicableLayouts(pathname) {\n  const applicable = [];\n  const normalizedPath = pathname.replace(/\\\\/$/, '') || '/';\n  \n  for (const layout of layoutRoutes) {\n    // Root layout (/) applies to everything\n    // Other layouts apply to their path and sub-paths\n    if (layout.pattern === '/' || isFarmRouteActive(layout.pattern, normalizedPath, { exact: false })) {\n      applicable.push(layout);\n    }\n  }\n  \n  // Sort by depth (root first, then nested)\n  applicable.sort((a, b) => {\n    const depthA = a.pattern.split('/').filter(Boolean).length;\n    const depthB = b.pattern.split('/').filter(Boolean).length;\n    return depthA - depthB;\n  });\n  \n  return applicable;\n}\n\n${\n  config.docs?.enabled\n    ? `async function wrapFarmDocsResponseWithLayouts(request, response) {\n  if (request.method === \"HEAD\") return response;\n  if (response.headers.get(\"x-farm-docs-adapter\")) return response;\n\n  const pathname = getFarmRoutePathname(new URL(request.url).pathname);\n  const applicableLayouts = getApplicableLayouts(pathname);\n  if (!applicableLayouts.some((layout) => layout.shouldHydrate === true)) {\n    return response;\n  }\n\n  const source = await response.text();\n  const bodyMatch = source.match(/<body([^>]*)>([\\\\s\\\\S]*?)<\\\\/body>/i);\n  if (!bodyMatch) {\n    return new Response(source, {\n      status: response.status,\n      statusText: response.statusText,\n      headers: response.headers,\n    });\n  }\n\n  const matchedRoute = matchPageRoute(pathname);\n  const params = matchedRoute?.params || {};\n  const hydrationStrategies = applicableLayouts.flatMap((layout) =>\n    layout.shouldHydrate && layout.islandStrategy ? [layout.islandStrategy] : [],\n  );\n  const islandStrategy = hydrationStrategies.every(\n    (strategy) => strategy === hydrationStrategies[0],\n  )\n    ? (hydrationStrategies[0] || \"load\")\n    : \"load\";\n  let wrappedElement = React.createElement(\"div\", {\n    id: \"__farm_page__\",\n    \"data-farm-client\": \"false\",\n    \"data-farm-layout-client\": \"true\",\n    \"data-farm-island\": \"page\",\n    \"data-farm-island-strategy\": islandStrategy,\n    dangerouslySetInnerHTML: { __html: bodyMatch[2] },\n  });\n\n  for (let index = applicableLayouts.length - 1; index >= 0; index--) {\n    const LayoutComponent = applicableLayouts[index].module.default;\n    if (LayoutComponent) {\n      wrappedElement = React.createElement(LayoutComponent, {\n        children: wrappedElement,\n        params,\n      });\n    }\n  }\n\n  const renderedRoot = await renderFarmElement(\n    ReactDOMServer,\n    React.createElement(\n      \"div\",\n      { id: \"root\" },\n      wrapFarmRouteClientGraph(wrapWithFarmIntegrationProviders(wrappedElement)),\n    ),\n  );\n  let rootMarkup = renderedRoot.html;\n  if (rootMarkup === undefined) {\n    rootMarkup = await new Response(renderedRoot.stream).text();\n    if (renderedRoot.streamErrors.length > 0) throw renderedRoot.streamErrors[0];\n  }\n  let html = source.replace(\n    bodyMatch[0],\n    // Function replacement: rendered markup may contain $-sequences ($&, $', $$).\n    function() { return \"<body\" + bodyMatch[1] + \">\" + rootMarkup + \"</body>\"; },\n  );\n  if (renderedRoot.head) {\n    // Renderer-emitted head markup (e.g. <svelte:head>). First <title> wins,\n    // so the prebuilt shell's fallback title yields when the renderer\n    // supplies one; explicit titles are left in place.\n    if (/<title[\\\\s>]/i.test(renderedRoot.head)) {\n      html = html.replace(/<title>Farm\\\\.js App<[/]title>/i, \"\");\n    }\n    html = html.replace(/<[/]head>/i, function() { return renderedRoot.head + \"\\\\n</head>\"; });\n  }\n  if (!html.includes('href=\"/__farm_client_css_href__\"')) {\n    const clientStylesheet = '  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\\\\n';\n    const firstStyleIndex = html.search(/<style(?:\\\\s|>)/i);\n    html =\n      firstStyleIndex >= 0\n        ? html.slice(0, firstStyleIndex) + clientStylesheet + html.slice(firstStyleIndex)\n        : html.replace(/<[/]head>/i, clientStylesheet + \"</head>\");\n  }\n  if (!html.includes('id=\"__farm_route_slots_data__\"')) {\n    html = html.replace(/<[/]body>/i, function() { return renderFarmClientBootstrapScript() + \"\\\\n</body>\"; });\n  }\n  if (!html.includes('src=\"/__farm_client_js_src__\"')) {\n    html = html.replace(\n      /<[/]body>/i,\n      '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>',\n    );\n  }\n  if (!html.includes('window._$HY')) {\n    html = html.replace(/<[/]head>/i, function() { return renderFarmRendererHydrationScript() + \"\\\\n</head>\"; });\n  }\n  const headers = new Headers(response.headers);\n  headers.delete(\"content-length\");\n  headers.delete(\"etag\");\n  return new Response(html, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}`\n    : \"\"\n}\n\nconst pprShellCache = getFarmDataCache();\nconst experimentalPPREnabled = ${JSON.stringify(config.experimental?.ppr === true)};\n\nfunction resolvePPRConfig(routeModule) {\n  if (!experimentalPPREnabled || !routeModule || routeModule.dynamic === \"force-dynamic\") {\n    return { enabled: false };\n  }\n\n  if (routeModule.dynamic === \"force-static\" || routeModule.dynamic === \"error\") {\n    return { enabled: false };\n  }\n\n  const enabled = routeModule.ppr === true || routeModule.experimental_ppr === true;\n  const revalidate =\n    typeof routeModule.revalidate === \"number\" && routeModule.revalidate > 0\n      ? routeModule.revalidate\n      : undefined;\n\n  return { enabled, revalidate };\n}\n\nfunction getPPRShellBypassReason(request, middlewareData, middlewareContext) {\n  const method = request.method.toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") return \"method\";\n  if (request.headers.get(\"cookie\")) return \"cookie\";\n  if (request.headers.get(\"authorization\")) return \"authorization\";\n  if (request.headers.get(\"x-farm-intercept-from\")) return \"route-interception\";\n  if (request.headers.get(\"x-farm-ppr-refresh\")) return \"refresh\";\n  if (hasConfiguredRouteContext) return \"route-context\";\n  if (middlewareData?.size) return \"middleware-data\";\n  if (middlewareContext?.size) return \"middleware-context\";\n  return undefined;\n}\n\nfunction getPPRShellCacheKey(url, locale) {\n  return createFarmCacheKey([\n    \"ppr\",\n    locale || \"\",\n    normalizeRevalidatePath(url.pathname),\n    url.search,\n  ]);\n}\n\nfunction getPPRHeaders(status, config) {\n  const headers = {\n    \"X-Farm-PPR\": status,\n  };\n\n  if (status === \"bypass\") {\n    headers[\"Cache-Control\"] = \"private, no-store\";\n    return headers;\n  }\n\n  if (typeof config.revalidate === \"number\" && config.revalidate > 0) {\n    headers[\"Cache-Control\"] = \\`s-maxage=\\${config.revalidate}, stale-while-revalidate\\`;\n  }\n\n  return headers;\n}\n\nfunction getRouteSharedCacheControl(routeModule, pprCanCache) {\n  if (!routeModule || routeModule.dynamic === \"force-dynamic\") {\n    return null;\n  }\n\n  const isStaticRoute =\n    routeModule.ssg === true ||\n    routeModule.dynamic === \"force-static\" ||\n    routeModule.dynamic === \"error\";\n  if (!isStaticRoute && !pprCanCache) {\n    return null;\n  }\n\n  const revalidate =\n    typeof routeModule.revalidate === \"number\" && routeModule.revalidate > 0\n      ? routeModule.revalidate\n      : 60;\n  return \"public, s-maxage=\" + revalidate + \", stale-while-revalidate=300\";\n}\n\nasync function getCachedPPRShell(cacheKey) {\n  const entry = await pprShellCache.getEntryAsync(cacheKey);\n  if (!entry) {\n    return null;\n  }\n\n  return entry.value.html;\n}\n\n/**\n * Main request handler - created at runtime with bundled routes\n */\nasync function handleFarmRequest(request) {\n  const response = await ${\n    config.i18n.enabled\n      ? `_runWithFarmI18nRequest(\n    farmI18nRuntime,\n    request,\n    async function(farmLocaleResolution) {\n      if (\n        farmLocaleResolution.redirect &&\n        (request.method === \"GET\" || request.method === \"HEAD\")\n      ) {\n        return applyFarmI18nResponse(\n          new Response(null, {\n            status: 307,\n            headers: { Location: farmLocaleResolution.redirect },\n          }),\n          farmLocaleResolution\n        );\n      }\n      const response = await handleFarmRequestInContext(request, farmLocaleResolution);\n      return applyFarmI18nResponse(response, farmLocaleResolution);\n    },\n    { redirect: !isFarmLocalAPIPathname(new URL(request.url).pathname) }\n  )`\n      : \"handleFarmRequestInContext(request, null)\"\n  };\n  ${\n    config.md?.enabled\n      ? `const pathname = getFarmRoutePathname(new URL(request.url).pathname);\n  if (matchPageRoute(pathname)) {\n    return applyMarkdownNegotiationHeaders(response, {\n      config: farmMarkdownConfig,\n      pathname,\n    });\n  }`\n      : \"\"\n  }\n  return response;\n}\n\nasync function handleFarmRequestInContext(\n  request,\n  farmLocaleResolution,\n  configuredRewriteApplied = false,\n  requestStartTime = Date.now(),\n) {\n  let url = new URL(request.url);\n  let pathname = url.pathname;\n  let routePathname = getFarmRoutePathname(pathname);\n\n  // Redirects have precedence over local routes. Configured rewrites use\n  // after-files semantics so emitted page, API, integration, docs, image, and\n  // metadata routes keep their normal method/status handling. Internal rewrite\n  // targets re-enter this handler so middleware and request-local state observe\n  // the rewritten URL; external destinations are proxied transparently.\n  if (!configuredRewriteApplied) {\n    const redirectMatch = matchRedirectRoute(\n      routePathname,\n      farmLocaleResolution?.locale,\n      url.search,\n    );\n    if (redirectMatch) {\n      return new Response(\"Redirecting to \" + redirectMatch.destination, {\n        status: redirectMatch.statusCode,\n        headers: { Location: redirectMatch.destination },\n      });\n    }\n\n    if (\n      configuredRewriteRoutes.length > 0 &&\n      !hasLocalRequestRoute(request, routePathname)\n    ) {\n      const rewriteDestination = matchRewriteRoute(\n        routePathname,\n        farmLocaleResolution?.locale,\n      );\n      if (rewriteDestination) {\n        const rewrittenRequest = createRewrittenRequest(request, rewriteDestination);\n        if (new URL(rewrittenRequest.url).origin !== url.origin) {\n          return globalThis.fetch(rewrittenRequest);\n        }\n        return _runWithCurrentRequest(rewrittenRequest, () =>\n          handleFarmRequestInContext(\n            rewrittenRequest,\n            farmLocaleResolution,\n            true,\n            requestStartTime,\n          )\n        );\n      }\n    }\n  }\n\n  if (farmImageHandler && pathname === ${JSON.stringify(config.images.path)}) {\n    const imageResponse = await farmImageHandler(request);\n    if (imageResponse) {\n      return imageResponse;\n    }\n  }\n\n  ${\n    hasServerRuntimeIntegrations\n      ? `\n  const integrationResponse = await handleIntegrationRequest(request.clone());\n  if (integrationResponse) {\n    return integrationResponse;\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    hasMiddlewareRuntime\n      ? `\n  const requestBeforeMiddleware = request;\n  const middlewareResult = await farmMiddlewareRunner(request);\n  if (middlewareResult.response) {\n    return middlewareResult.response;\n  }\n  request = middlewareResult.request;\n  const middlewareData = middlewareResult.data;\n  const middlewareContext = middlewareResult.context;\n  const middlewareHeaders = middlewareResult.headers;\n  url = new URL(request.url);\n  pathname = url.pathname;\n  routePathname = getFarmRoutePathname(pathname);\n\n  // Middleware may replace the Request when it rewrites a URL. Re-enter the\n  // request store so pages, layouts, and route context observe that rewritten\n  // request instead of the original outer-handler value.\n  const runResolvedRequest = async () => {\n  `\n      : `\n  const middlewareData = undefined;\n  const middlewareContext = undefined;\n  const middlewareHeaders = undefined;\n  `\n  }\n\n  ${\n    config.docs?.enabled\n      ? `\n  // Docs responses are served after app middleware so route guards and\n  // middleware headers apply to the docs engine like any other page content.\n  if (farmDocsHandler) {\n    const docsResponse = await farmDocsHandler(request.clone());\n    if (docsResponse) {\n      if (!docsResponse.headers.get(\"content-type\")?.toLowerCase().includes(\"text/html\")) {\n        return applyProductionMiddlewareHeaders(docsResponse, middlewareHeaders);\n      }\n      const wrappedDocsResponse = await wrapFarmDocsResponseWithLayouts(\n        request,\n        docsResponse,\n      );\n      const docsHeaders = new Headers(wrappedDocsResponse.headers);\n      docsHeaders.set(\"x-farm-preload-buffered\", \"1\");\n      return applyProductionMiddlewareHeaders(new Response(wrappedDocsResponse.body, {\n        status: wrappedDocsResponse.status,\n        statusText: wrappedDocsResponse.statusText,\n        headers: docsHeaders,\n      }), middlewareHeaders);\n    }\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    hasMarkdownPages\n      ? `\n  // The raw markdown source of a page route is the page's content in another\n  // representation; middleware guarding the route must run before serving it.\n  const markdownSourceResponse = await createFarmMarkdownSourceResponse?.({\n    request: request.clone(),\n    config: farmMdxConfig,\n    resolveSource: (targetPathname) => {\n      const match = matchPageRoute(getFarmRoutePathname(targetPathname));\n      return match?.route?.markdownSource || null;\n    },\n  });\n  if (markdownSourceResponse) {\n    return applyProductionMiddlewareHeaders(markdownSourceResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    config.md?.enabled\n      ? `\n  if (farmMarkdownConfig?.enabled) {\n    const markdownResponse = await createMarkdownMirrorResponse({\n      request: request.clone(),\n      config: farmMarkdownConfig,\n      routeExists: (targetPathname) =>\n        Boolean(matchPageRoute(getFarmRoutePathname(targetPathname))),\n      renderPage: (targetRequest) => handleFarmRequest(targetRequest),\n    });\n    if (markdownResponse) {\n      return applyProductionMiddlewareHeaders(markdownResponse, middlewareHeaders);\n    }\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    apiRoutes.length > 0\n      ? `\n  const apiResponse = await handleAPIRequest(request.clone());\n  if (apiResponse) {\n    return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n\n  if (\n    farmOpenAPIReference &&\n    farmOpenAPIReference.specRoute &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.specRoute)\n  ) {\n    const method = request.method.toUpperCase();\n    const specResponse = method === \"GET\" || method === \"HEAD\"\n      ? new Response(method === \"HEAD\" ? null : JSON.stringify(farmOpenAPIReference.spec), {\n          status: 200,\n          headers: {\n            \"Content-Type\": \"application/json; charset=utf-8\",\n            \"Cache-Control\": \"public, max-age=0, must-revalidate\",\n            \"X-Content-Type-Options\": \"nosniff\",\n          },\n        })\n      : new Response(\"Method Not Allowed\", {\n          status: 405,\n          headers: {\n            \"Allow\": \"GET, HEAD\",\n            \"Content-Type\": \"text/plain; charset=utf-8\",\n          },\n        });\n    return applyProductionMiddlewareHeaders(specResponse, middlewareHeaders);\n  }\n\n  if (\n    farmOpenAPIReference &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.route)\n  ) {\n    const method = request.method.toUpperCase();\n    const response = method === \"GET\" || method === \"HEAD\"\n      ? new Response(method === \"HEAD\" ? null : farmOpenAPIReference.html, {\n          status: 200,\n          headers: {\n            \"Content-Type\": \"text/html; charset=utf-8\",\n            \"Cache-Control\": \"public, max-age=0, must-revalidate\",\n            \"X-Content-Type-Options\": \"nosniff\",\n          },\n        })\n      : new Response(\"Method Not Allowed\", {\n          status: 405,\n          headers: {\n            \"Allow\": \"GET, HEAD\",\n            \"Content-Type\": \"text/plain; charset=utf-8\",\n          },\n        });\n    return applyProductionMiddlewareHeaders(response, middlewareHeaders);\n  }\n\n  ${\n    metadataImageRoutes.length > 0\n      ? `\n  const metadataImageResponse = await handleMetadataImageRequest(\n    request.clone(),\n    routePathname\n  );\n  if (metadataImageResponse) {\n    return applyProductionMiddlewareHeaders(metadataImageResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    applicationMetadataRoutes.length > 0\n      ? `\n  const applicationMetadataResponse = await handleApplicationMetadataRouteRequest(\n    request.clone(),\n    routePathname\n  );\n  if (applicationMetadataResponse) {\n    return applyProductionMiddlewareHeaders(applicationMetadataResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    config.docs?.enabled\n      ? `if (farmDocsAPIHandler && isFarmDocsAPIRequest(pathname)) {\n    const docsAPIResponse = await farmDocsAPIHandler(request.clone());\n    if (docsAPIResponse) {\n      return applyProductionMiddlewareHeaders(docsAPIResponse, middlewareHeaders);\n    }\n  }`\n      : \"\"\n  }\n\n  // Preserve the explicit JSON 404 for misses below the configured local API path.\n  if (isFarmLocalAPIPathname(pathname)) {\n    return applyProductionMiddlewareHeaders(new Response(\n      JSON.stringify({ error: \"API route not found\", pathname }),\n      { status: 404, headers: { \"Content-Type\": \"application/json\" } }\n    ), middlewareHeaders);\n  }\n\n  // Handle page routes (SSR)\n  emitFarmEvent({ type: \"render.start\", route: pathname, pathname });\n  const matchedRoute = matchPageRoute(routePathname);\n  if (matchedRoute) {\n    const trailingSlashLocation = resolveFarmTrailingSlashRedirect(\n      url,\n      ${JSON.stringify(config.trailingSlash)}\n    );\n    if (trailingSlashLocation) {\n      return applyProductionMiddlewareHeaders(\n        new Response(null, {\n          status: 308,\n          headers: { Location: trailingSlashLocation },\n        }),\n        middlewareHeaders\n      );\n    }\n    const { route, params } = matchedRoute;\n    emitFarmEvent({ type: \"route.matched\", pathname, route: route.pattern, params });\n    \n    try {\n      const pprConfig = resolvePPRConfig(route.module);\n      const pprBypassReason = pprConfig.enabled\n        ? getPPRShellBypassReason(request, middlewareData, middlewareContext)\n        : undefined;\n      let pprCanCache = pprConfig.enabled && !pprBypassReason;\n      const pprCacheKey = pprCanCache\n        ? getPPRShellCacheKey(url, farmLocaleResolution?.locale)\n        : null;\n      if (pprConfig.enabled && pprBypassReason) {\n        emitFarmEvent({ type: \"ppr.shell.bypass\", route: pathname, reason: pprBypassReason });\n        emitFarmEvent({ type: \"cache.bypass\", route: pathname, reason: pprBypassReason });\n        if (pprBypassReason === \"refresh\") {\n          emitFarmEvent({ type: \"ppr.refresh.start\", route: pathname });\n        }\n      }\n      if (pprCacheKey) {\n        const cachedPPRShell = await getCachedPPRShell(pprCacheKey);\n        if (cachedPPRShell) {\n          emitFarmEvent({ type: \"ppr.shell.hit\", route: pathname, key: pprCacheKey });\n          emitFarmEvent({\n            type: \"render.complete\",\n            route: pathname,\n            pathname,\n            status: 200,\n            durationMs: Date.now() - requestStartTime,\n          });\n          return applyProductionMiddlewareHeaders(new Response(cachedPPRShell, {\n            status: 200,\n            headers: {\n              \"Content-Type\": \"text/html; charset=utf-8\",\n              \"x-farm-preload-buffered\": \"1\",\n              ...(farmFontPreloadHeader ? { \"Link\": farmFontPreloadHeader } : {}),\n              ...getPPRHeaders(\"hit\", pprConfig),\n            },\n          }), middlewareHeaders);\n        }\n        emitFarmEvent({ type: \"ppr.shell.miss\", route: pathname, key: pprCacheKey });\n      }\n\n      // Get the page component and metadata\n      let PageComponent = route.module.default;\n      let pageStatus = 200;\n      const pageMetadata = route.module.metadata || {};\n      \n      // Get applicable layouts for this page\n      const applicableLayouts = getApplicableLayouts(routePathname);\n      const shouldHydrateLayout = applicableLayouts.some(\n        (layout) => layout.shouldHydrate === true,\n      );\n      const hydrationStrategies = [\n        ...(route.shouldHydrate && route.islandStrategy ? [route.islandStrategy] : []),\n        ...applicableLayouts.flatMap((layout) =>\n          layout.shouldHydrate && layout.islandStrategy ? [layout.islandStrategy] : [],\n        ),\n      ];\n      const hydrationIslandStrategy = hydrationStrategies.every(\n        (strategy) => strategy === hydrationStrategies[0],\n      )\n        ? (hydrationStrategies[0] || \"load\")\n        : \"load\";\n      const selectedRouteSlots = matchRouteSlots(\n        routePathname,\n        request.headers.get(\"x-farm-intercept-from\"),\n      );\n      \n      if (PageComponent) {\n        // Parse search params - make it a resolved Promise for async components\n        const searchParamsObj = searchParamsToObject(url.searchParams);\n        \n        // Render the page component\n        const routeContext = hasConfiguredRouteContext\n          ? await resolveFarmRouteContext(farmResolvedRuntimeConfig, {\n              request,\n              params,\n              search: searchParamsObj,\n              path: pathname,\n            })\n          : undefined;\n        const rawPageProps = withFarmRouteContext(\n          {\n            params,\n            searchParams: Promise.resolve(searchParamsObj),\n            path: pathname,\n            ...(middlewareData?.size ? { middleware: { data: middlewareData } } : {}),\n          },\n          routeContext,\n        );\n        // Generated programmatic route modules consume app context from the\n        // public context prop while source-created modules read the symbol\n        // carrier above. Expose it only while resolving server route data.\n        if (route.module.__farmResolveRouteProps && routeContext !== undefined) {\n          Object.defineProperty(rawPageProps, \"context\", {\n            value: routeContext,\n            enumerable: true,\n            configurable: true,\n          });\n        }\n        let pageProps;\n        try {\n          // Resolve top-level route state before starting the HTTP stream so\n          // redirects, notFound(), and failures keep their real status. Route\n          // data may still contain explicit defer() values for nested Suspense.\n          pageProps = route.module.__farmResolveRouteProps\n            ? await route.module.__farmResolveRouteProps(rawPageProps)\n            : (() => {\n              const routeSchemas = route.module.__farmRouteParsesProps\n                ? {}\n                : route.module.__farmRouteSchemas || {};\n              const parsedParams = routeSchemas.params?.parse\n                ? routeSchemas.params.parse(params)\n                : params;\n              const parsedSearch = routeSchemas.search?.parse\n                ? routeSchemas.search.parse(searchParamsObj)\n                : searchParamsObj;\n              return {\n                ...rawPageProps,\n                params: parsedParams,\n                search: parsedSearch,\n                searchParams: Promise.resolve(parsedSearch),\n              };\n            })();\n          if (\n            route.module.__farmResolveRouteProps &&\n            routeContext !== undefined &&\n            pageProps.context === routeContext\n          ) {\n            const { context: _routeContext, ...renderPageProps } = pageProps;\n            pageProps = renderPageProps;\n          }\n        } catch (routeStateError) {\n          if (isFarmRedirectError(routeStateError)) throw routeStateError;\n\n          const routeComponents = route.module.__farmRouteComponents;\n          const routeStateProps = {\n            ...rawPageProps,\n            search: searchParamsObj,\n            searchParams: Promise.resolve(searchParamsObj),\n            error: routeStateError,\n          };\n          if (isFarmNotFoundError(routeStateError) && routeComponents?.notFound) {\n            pageStatus = 404;\n            PageComponent = routeComponents.notFound;\n            pageProps = routeStateProps;\n          } else if (routeComponents?.error) {\n            pageStatus = 500;\n            PageComponent = routeComponents.error;\n            pageProps = routeStateProps;\n          } else {\n            throw routeStateError;\n          }\n        }\n\n        const renderedRouteSlots = await Promise.all(\n          selectedRouteSlots.map(async function(slot) {\n            const slotContext = hasConfiguredRouteContext\n              ? await resolveFarmRouteContext(farmResolvedRuntimeConfig, {\n                  request,\n                  params: slot.params,\n                  search: searchParamsObj,\n                  path: pathname,\n                })\n              : undefined;\n            const rawSlotProps = withFarmRouteContext(\n              {\n                params: slot.params,\n                searchParams: Promise.resolve(searchParamsObj),\n                path: pathname,\n                ...(middlewareData?.size ? { middleware: { data: middlewareData } } : {}),\n              },\n              slotContext,\n            );\n            if (slot.module.__farmResolveRouteProps && slotContext !== undefined) {\n              Object.defineProperty(rawSlotProps, \"context\", {\n                value: slotContext,\n                enumerable: true,\n                configurable: true,\n              });\n            }\n\n            const slotSchemas = slot.module.__farmRouteParsesProps\n              ? {}\n              : slot.module.__farmRouteSchemas || {};\n            let slotProps = slot.module.__farmResolveRouteProps\n              ? await slot.module.__farmResolveRouteProps(rawSlotProps)\n              : {\n                  ...rawSlotProps,\n                  params: slotSchemas.params?.parse\n                    ? slotSchemas.params.parse(slot.params)\n                    : slot.params,\n                  search: slotSchemas.search?.parse\n                    ? slotSchemas.search.parse(searchParamsObj)\n                    : searchParamsObj,\n                  searchParams: Promise.resolve(\n                    slotSchemas.search?.parse\n                      ? slotSchemas.search.parse(searchParamsObj)\n                      : searchParamsObj,\n                  ),\n                };\n            if (\n              slot.module.__farmResolveRouteProps &&\n              slotContext !== undefined &&\n              slotProps.context === slotContext\n            ) {\n              const { context: _slotContext, ...renderSlotProps } = slotProps;\n              slotProps = renderSlotProps;\n            }\n\n            return { ...slot, props: slotProps };\n          }),\n        );\n        const clientMiddleware = middlewareData?.size\n          ? { data: Object.fromEntries(middlewareData) }\n          : undefined;\n        const clientPageProps = {\n          params: pageProps.params,\n          search: pageProps.search ?? searchParamsObj,\n          searchParams: pageProps.search ?? searchParamsObj,\n          ...(\"data\" in pageProps ? { data: pageProps.data } : {}),\n          ...(pageProps.__farmCanonicalPath\n            ? { __farmCanonicalPath: pageProps.__farmCanonicalPath }\n            : {}),\n          ...(pageProps.__farmRoutePropsResolved\n            ? { __farmRoutePropsResolved: true }\n            : {}),\n          path: pathname,\n          ...(clientMiddleware ? { middleware: clientMiddleware } : {}),\n        };\n        const routeSlotPayload = renderedRouteSlots.map(function(slot) {\n          return {\n            name: slot.name,\n            ownerPattern: slot.ownerPattern,\n            pattern: slot.pattern,\n            containerId: slot.containerId,\n            interception: slot.interception,\n            fallback: slot.fallback,\n            props: {\n              params: slot.props.params,\n              search: slot.props.search || searchParamsObj,\n              searchParams: slot.props.search || searchParamsObj,\n              ...(\"data\" in slot.props ? { data: slot.props.data } : {}),\n              path: pathname,\n              ...(clientMiddleware ? { middleware: clientMiddleware } : {}),\n            },\n          };\n        });\n        \n        const renderPageElement = async () => {\n            // First, render the page content\n            let pageElement;\n\n            // Only genuinely async components are executed directly; source\n            // sniffing is unsound because any sync component whose source\n            // contains \"async\" (e.g. an async event handler) would be called\n            // outside React, breaking hooks and re-running side effects.\n            // Errors, including redirect/notFound controls, propagate to the\n            // outer request handler exactly like sync render errors.\n            if (typeof PageComponent === \"function\" && PageComponent.constructor.name === \"AsyncFunction\") {\n              const result = await PageComponent(pageProps);\n              if (React.isValidElement(result)) {\n                pageElement = result;\n              } else {\n                pageElement = React.createElement(\"div\", null, String(result));\n              }\n            } else {\n              // Sync component - create element directly\n              pageElement = React.createElement(PageComponent, pageProps);\n            }\n\n            if (route.shouldHydrate && !shouldHydrateLayout) {\n              pageElement = wrapFarmRouteClientGraph(pageElement);\n            }\n\n            pageElement = React.createElement(\n              \"div\",\n              {\n                id: \"__farm_page__\",\n                \"data-farm-segment\": \"page\",\n                \"data-farm-client\": route.shouldHydrate ? \"true\" : \"false\",\n                ...(shouldHydrateLayout\n                  ? { \"data-farm-layout-client\": \"true\" }\n                  : {}),\n                \"data-farm-island\": \"page\",\n                \"data-farm-island-strategy\": hydrationIslandStrategy,\n              },\n              pageElement,\n            );\n\n            // Wrap with layouts (from innermost to outermost)\n            // Layouts are sorted by depth (root first), so we process in reverse\n            let wrappedElement = pageElement;\n            for (let i = applicableLayouts.length - 1; i >= 0; i--) {\n              const layout = applicableLayouts[i];\n              const LayoutComponent = layout.module.default;\n              if (LayoutComponent) {\n                const slotProps = {};\n                for (const slot of renderedRouteSlots) {\n                  if (slot.ownerPattern !== layout.pattern) continue;\n                  slotProps[slot.name] = React.createElement(\n                    \"div\",\n                    {\n                      id: slot.containerId,\n                      \"data-farm-route-slot\": slot.name,\n                      \"data-farm-slot-owner\": slot.ownerPattern,\n                    },\n                    wrapFarmRouteClientGraph(\n                      React.createElement(slot.module.default, slot.props),\n                    ),\n                  );\n                }\n                wrappedElement = React.createElement(LayoutComponent, {\n                  children: wrappedElement,\n                  params,\n                  ...slotProps,\n                });\n                wrappedElement = React.createElement(\n                  \"div\",\n                  {\n                    \"data-farm-layout-boundary\": \"true\",\n                    \"data-farm-layout-pattern\": layout.pattern,\n                    style: { display: \"contents\" },\n                  },\n                  wrappedElement,\n                );\n              }\n            }\n\n          if (shouldHydrateLayout) {\n            wrappedElement = wrapFarmRouteClientGraph(wrappedElement);\n          }\n\n          wrappedElement = wrapWithFarmIntegrationProviders(wrappedElement);\n          return renderFarmElement(ReactDOMServer, wrappedElement);\n        };\n        const renderedPage = ${\n          hasMiddlewareRuntime\n            ? `await _runWithMiddlewareData(middlewareData, () =>\n          _runWithMiddlewareContext(middlewareContext, renderPageElement)\n        )`\n            : \"await renderPageElement()\"\n        };\n\n        // A completed document is not a reusable PPR shell: it already contains\n        // the request's resolved Suspense content. Until the production runtime\n        // can persist and resume the partial shell itself, buffer streamed PPR\n        // responses for late status errors but do not cache their dynamic HTML.\n        const shouldCachePPRShell = Boolean(pprCacheKey && !renderedPage.stream);\n        if (!shouldCachePPRShell && pprCacheKey) {\n          pprCanCache = false;\n          emitFarmEvent({\n            type: \"ppr.shell.bypass\",\n            route: pathname,\n            reason: \"suspense-stream\",\n          });\n          emitFarmEvent({ type: \"cache.bypass\", route: pathname, reason: \"suspense-stream\" });\n        }\n        \n        // Collect static and generated metadata from layouts and page.\n        // Later entries override earlier entries, matching the development renderer.\n        let mergedMetadata = {};\n        for (const layout of applicableLayouts) {\n          mergedMetadata = mergeMetadata(mergedMetadata, layout.module.metadata);\n          if (typeof layout.module.generateMetadata === \"function\") {\n            mergedMetadata = mergeMetadata(\n              mergedMetadata,\n              await layout.module.generateMetadata({ params: pageProps.params }),\n            );\n          }\n        }\n        mergedMetadata = mergeMetadata(mergedMetadata, pageMetadata);\n        if (typeof route.module.generateMetadata === \"function\") {\n          mergedMetadata = mergeMetadata(\n            mergedMetadata,\n            await route.module.generateMetadata(pageProps),\n          );\n        }\n\n        if (!mergedMetadata.manifest) {\n          const manifestMatch = getMatchingApplicationMetadataRoute(routePathname, \"manifest\");\n          if (manifestMatch) {\n            mergedMetadata.manifest = createApplicationMetadataHref(\n              manifestMatch,\n              farmLocaleResolution?.locale,\n            );\n          }\n        }\n\n        for (const kind of [\"opengraph\", \"twitter\"]) {\n          const imageMatch = getMatchingMetadataImage(routePathname, kind);\n          if (imageMatch) {\n            mergedMetadata = addMetadataImageReference(\n              mergedMetadata,\n              createMetadataImageReference(imageMatch, farmLocaleResolution?.locale),\n            );\n          }\n        }\n\n        const renderedMetadata = renderMetadataHead(mergedMetadata, { pathname, jsonLd: ${JSON.stringify(config.agent?.jsonLd ?? false)} });\n        const title = renderedMetadata.title;\n        const metaTags = renderedMetadata.tags;\n        const hasFavicon = renderedMetadata.hasFavicon;\n\n        const hasPrivateRequestHeaders = hasPrivateFarmRequestHeaders(\n          request,\n          farmLocaleResolution,\n        );\n        const hasRequestScopedRender = Boolean(\n          pageStatus >= 400 ||\n          request.headers.get(\"x-farm-intercept-from\") ||\n          hasPrivateRequestHeaders ||\n          hasConfiguredRouteContext ||\n          middlewareData?.size ||\n          middlewareContext?.size\n        );\n        const sharedCacheControl = getRouteSharedCacheControl(route.module, pprCanCache);\n        const responseHeaders = {\n          \"Content-Type\": \"text/html; charset=utf-8\",\n          \"Cache-Control\": renderedPage.stream || hasRequestScopedRender || !sharedCacheControl\n            ? \"private, no-store\"\n            : sharedCacheControl,\n          ...(farmFontPreloadHeader ? { \"Link\": farmFontPreloadHeader } : {}),\n          ...(pprConfig.enabled ? getPPRHeaders(pprCanCache ? \"miss\" : \"bypass\", pprConfig) : {}),\n        };\n        const farmI18nSnapshot = getFarmI18nSnapshot();\n        let html = renderedPage.html;\n        \n        // Check if the layout already rendered a full HTML document\n        const trimmedHtml = (html !== undefined ? html : renderedPage.shellHtml || \"\").trim();\n        const hasFullDocument = trimmedHtml.startsWith('<html') || trimmedHtml.startsWith('<!DOCTYPE');\n\n        // Stream a suspended body as soon as React's shell is ready. Full-document\n        // layouts, localized documents, and cacheable PPR shells still use the\n        // buffered path because they require whole-document transformation.\n        if (\n          pageStatus === 200 &&\n          renderedPage.stream &&\n          !hasFullDocument &&\n          !farmI18nSnapshot &&\n          !pprCacheKey\n        ) {\n          const farmThemeDocument = createFarmThemeDocumentParts(\n            farmThemeConfig,\n            farmResolvedRuntimeConfig.basePath,\n            getFarmTheme(request)\n          );\n          const streamPrefix = '<!DOCTYPE html>\\\\n<html lang=\"en\">\\\\n<head>\\\\n' +\n            farmThemeDocument.head + '\\\\n' +\n            '  <meta charset=\"utf-8\">\\\\n' +\n            '  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\\\\n' +\n            (hasFavicon ? '' : '  <link rel=\"icon\" href=\"data:,\">\\\\n') +\n            '  <title>' + title + '</title>' + metaTags + '\\\\n' +\n            '  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\\\\n' +\n            '  <link rel=\"modulepreload\" href=\"/__farm_client_js_src__\">\\\\n' +\n            renderFarmRendererHydrationScript() + '\\\\n' +\n            '</head>\\\\n<body>\\\\n  <div id=\"root\">';\n          const streamSuffix = '</div>\\\\n' +\n            '  ' + renderFarmClientBootstrapScript(\n              pageProps.__farmCanonicalPath,\n              routeSlotPayload,\n              clientPageProps\n            ) + '\\\\n' +\n            '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n' +\n            '</body>\\\\n</html>';\n          const themedStreamPrefix = streamPrefix.replace(\n            '<html lang=\"en\">',\n            () => '<html lang=\"en\"' + farmThemeDocument.attributes + '>'\n          );\n          const streamedDocument = createFarmDocumentStream(\n            renderedPage.stream,\n            themedStreamPrefix,\n            streamSuffix,\n            function() {\n              if (pprBypassReason === \"refresh\") {\n                emitFarmEvent({\n                  type: \"ppr.refresh.complete\",\n                  route: pathname,\n                  durationMs: Date.now() - requestStartTime,\n                });\n              }\n              emitFarmEvent({\n                type: \"render.complete\",\n                route: pathname,\n                pathname,\n                status: pageStatus,\n                durationMs: Date.now() - requestStartTime,\n              });\n            }\n          );\n          return applyProductionMiddlewareHeaders(new Response(streamedDocument, {\n            status: pageStatus,\n            headers: { ...responseHeaders, \"x-farm-preload-streaming\": \"1\" },\n          }), middlewareHeaders);\n        }\n\n        if (html === undefined) {\n          html = await new Response(renderedPage.stream).text();\n          if (renderedPage.streamErrors.length > 0) {\n            throw renderedPage.streamErrors[0];\n          }\n        }\n        \n        const rendererHead = renderedPage.head || \"\";\n        // First <title> wins: the fallback framework title yields to a\n        // renderer-emitted one; explicit metadata titles still come first.\n        const suppressDefaultTitle =\n          !renderedMetadata.hasExplicitTitle && /<title[\\\\s>]/i.test(rendererHead);\n        let fullHtml;\n        if (hasFullDocument) {\n          // Layout provides full HTML structure - inject CSS and client script\n          fullHtml = html\n            // Inject CSS link after opening head tag or first meta tag\n            .replace(/<head([^>]*)>/i, '<head$1>\\\\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">')\n            .replace(/<\\\\/head>/i, () => renderFarmRendererHydrationScript() + '\\\\n</head>')\n            // Inject title if not present and we have one\n            .replace(/<head([^>]*)>([\\\\s\\\\S]*?)<\\\\/head>/i, (match, attrs, headContent) => {\n              let nextHeadContent = headContent;\n              if (!headContent.includes('<title>') && title !== \"Farm.js App\") {\n                nextHeadContent += \"\\\\n  <title>\" + title + \"</title>\";\n              }\n              if (metaTags) nextHeadContent += metaTags;\n              // Renderer-emitted head markup (e.g. <svelte:head>). Function\n              // replacement below keeps $-sequences literal.\n              if (rendererHead) nextHeadContent += \"\\\\n  \" + rendererHead;\n              return nextHeadContent === headContent\n                ? match\n                : \"<head\" + attrs + \">\" + nextHeadContent + \"\\\\n</head>\";\n            })\n            // Inject client script before closing body tag. Function replacement:\n            // serialized page props may contain $-sequences ($&, $', $$) that a\n            // string replacement would expand into surrounding document markup,\n            // corrupting the inline bootstrap script.\n            .replace(\n              /<\\\\/body>/i,\n              () => '  ' + renderFarmClientBootstrapScript(\n                pageProps.__farmCanonicalPath,\n                routeSlotPayload,\n                clientPageProps\n              ) + '\\\\n' +\n                '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>',\n            );\n          \n          // Add DOCTYPE if not present\n          if (!fullHtml.trim().startsWith('<!DOCTYPE')) {\n            fullHtml = '<!DOCTYPE html>\\\\n' + fullHtml;\n          }\n        } else {\n          // No layout with full document - wrap in HTML structure\n          fullHtml = \\`<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  \\${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  \\${suppressDefaultTitle ? \"\" : \"<title>\" + title + \"</title>\"}\\${metaTags}\\${rendererHead ? \"\\\\n  \" + rendererHead : \"\"}\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\n  \\${renderFarmRendererHydrationScript()}\n</head>\n<body>\n  <div id=\"root\">\\${html}</div>\n  \\${renderFarmClientBootstrapScript(pageProps.__farmCanonicalPath, routeSlotPayload, clientPageProps)}\n  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\n</body>\n</html>\\`;\n        }\n        fullHtml = applyFarmI18nDocument(fullHtml, pathname, farmI18nSnapshot);\n        fullHtml = applyFarmThemeDocument(\n          fullHtml,\n          farmThemeConfig,\n          farmResolvedRuntimeConfig.basePath,\n          getFarmTheme(request)\n        );\n\n        if (\n          pageStatus === 200 &&\n          shouldCachePPRShell &&\n          pprCacheKey &&\n          request.method.toUpperCase() !== \"HEAD\"\n        ) {\n          await pprShellCache.setAsync(\n            pprCacheKey,\n            { html: fullHtml },\n            {\n              paths: [pathname],\n              tags: [\"ppr\"],\n              revalidate: pprConfig.revalidate ?? false,\n            }\n          );\n          emitFarmEvent({\n            type: \"ppr.shell.cached\",\n            route: pathname,\n            key: pprCacheKey,\n            revalidate: pprConfig.revalidate,\n          });\n        }\n\n        if (pprBypassReason === \"refresh\") {\n          emitFarmEvent({\n            type: \"ppr.refresh.complete\",\n            route: pathname,\n            durationMs: Date.now() - requestStartTime,\n          });\n        }\n\n        emitFarmEvent({\n          type: \"render.complete\",\n          route: pathname,\n          pathname,\n          status: pageStatus,\n          durationMs: Date.now() - requestStartTime,\n        });\n\n        return applyProductionMiddlewareHeaders(new Response(\n          fullHtml,\n          { \n            status: pageStatus,\n            headers: { ...responseHeaders, \"x-farm-preload-buffered\": \"1\" }\n          }\n        ), middlewareHeaders);\n      }\n    } catch (error) {\n      if (isFarmRedirectError(error)) {\n        const redirect = getFarmRedirectError(error);\n        const redirectUrl =\n          farmLocaleResolution?.locale &&\n          redirect.url.startsWith(\"/\") &&\n          !redirect.url.startsWith(\"//\")\n            ? localizeFarmHref(\n                redirect.url,\n                farmLocaleResolution.locale,\n                farmI18nConfig\n              )\n            : redirect.url;\n        emitFarmEvent({\n          type: \"route.redirect\",\n          from: pathname,\n          to: redirectUrl,\n          status: redirect.status,\n        });\n        emitFarmEvent({\n          type: \"render.complete\",\n          route: pathname,\n          pathname,\n          status: redirect.status,\n          durationMs: Date.now() - requestStartTime,\n        });\n        return applyProductionMiddlewareHeaders(new Response(null, {\n          status: redirect.status,\n          headers: {\n            Location: redirectUrl,\n          },\n        }), middlewareHeaders);\n      }\n\n      if (isFarmNotFoundError(error)) {\n        emitFarmEvent({ type: \"route.notFound\", pathname });\n        emitFarmEvent({\n          type: \"render.complete\",\n          route: pathname,\n          pathname,\n          status: 404,\n          durationMs: Date.now() - requestStartTime,\n        });\n        return applyProductionMiddlewareHeaders(new Response(\"Not Found\", {\n          status: 404,\n          headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n        }), middlewareHeaders);\n      }\n\n      emitFarmEvent({ type: \"render.error\", route: pathname, error });\n      console.error(\"SSR Error:\", error);\n      const errorStatus = resolveDefaultErrorStatus(error);\n      const errorStatusText = getDefaultErrorStatusText(errorStatus);\n\n      const errorBoundaryMatch = getMatchingErrorBoundary(routePathname);\n      if (errorBoundaryMatch?.route.module?.default) {\n        try {\n          const searchParamsObj = searchParamsToObject(url.searchParams);\n          const ErrorComponent = errorBoundaryMatch.route.module.default;\n          let errorElement = React.createElement(ErrorComponent, {\n            error,\n            reset: function() {},\n            params,\n            search: searchParamsObj,\n            searchParams: Promise.resolve(searchParamsObj),\n            path: pathname,\n            ...(middlewareData?.size ? { middleware: { data: middlewareData } } : {}),\n          });\n\n          const applicableLayouts = getApplicableLayouts(routePathname);\n          for (let i = applicableLayouts.length - 1; i >= 0; i--) {\n            const LayoutComponent = applicableLayouts[i].module.default;\n            if (LayoutComponent) {\n              errorElement = React.createElement(LayoutComponent, {\n                children: errorElement,\n                params,\n              });\n            }\n          }\n\n          errorElement = wrapWithFarmIntegrationProviders(errorElement);\n\n          const renderErrorElement = () =>\n            renderFarmElementToString(ReactDOMServer, errorElement);\n          const errorHtml = ${\n            hasMiddlewareRuntime\n              ? `await _runWithMiddlewareData(middlewareData, () =>\n            _runWithMiddlewareContext(middlewareContext, renderErrorElement)\n          )`\n              : \"await renderErrorElement()\"\n          };\n          const errorDocument = applyFarmThemeDocument(\n            applyFarmI18nDocument(\n              createFarmErrorDocument(errorHtml, \"Application Error\"),\n              pathname,\n              getFarmI18nSnapshot()\n            ),\n            farmThemeConfig,\n            farmResolvedRuntimeConfig.basePath,\n            getFarmTheme(request)\n          );\n          emitFarmEvent({\n            type: \"render.complete\",\n            route: pathname,\n            pathname,\n            status: errorStatus,\n            durationMs: Date.now() - requestStartTime,\n          });\n          return applyProductionMiddlewareHeaders(new Response(errorDocument, {\n            status: errorStatus,\n            headers: {\n              \"Content-Type\": \"text/html; charset=utf-8\",\n              \"Cache-Control\": \"private, no-store\",\n              \"x-farm-preload-buffered\": \"1\",\n            },\n          }), middlewareHeaders);\n        } catch (boundaryError) {\n          console.error(\"Route error boundary failed:\", boundaryError);\n        }\n      }\n\n      const fallbackHtml = createDefaultErrorMarkup({\n        statusCode: errorStatus,\n        statusText: errorStatusText,\n        requestPath: pathname,\n        method: request.method,\n        development: false,\n        mode: \"production\",\n      });\n      const fallbackDocument = applyFarmThemeDocument(\n        applyFarmI18nDocument(\n          createFarmErrorDocument(\n            fallbackHtml,\n            errorStatus + \" - \" + errorStatusText\n          ),\n          pathname,\n          getFarmI18nSnapshot()\n        ),\n        farmThemeConfig,\n        farmResolvedRuntimeConfig.basePath,\n        getFarmTheme(request)\n      );\n      return applyProductionMiddlewareHeaders(new Response(\n        fallbackDocument,\n        {\n          status: errorStatus,\n          headers: {\n            \"Content-Type\": \"text/html; charset=utf-8\",\n            \"Cache-Control\": \"private, no-store\",\n            \"x-farm-preload-buffered\": \"1\",\n          },\n        }\n      ), middlewareHeaders);\n    }\n  }\n\n  // 404 fallback - render proper HTML page\n  emitFarmEvent({ type: \"route.notFound\", pathname });\n\n  // Agents that navigate in Markdown (a \\`.md\\` URL or \\`Accept: text/markdown\\`)\n  // get a Markdown error body instead of the HTML not-found shell.\n  if (farmRequestWantsMarkdown(pathname, request.headers.get(\"accept\"))) {\n    emitFarmEvent({\n      type: \"render.complete\",\n      route: pathname,\n      pathname,\n      status: 404,\n      durationMs: Date.now() - requestStartTime,\n    });\n    return applyProductionMiddlewareHeaders(new Response(\n      createFarmMarkdownErrorBody(404, pathname, applyFarmBasePath(\"/\", farmResolvedRuntimeConfig.basePath)),\n      {\n        status: 404,\n        headers: {\n          \"Content-Type\": FARM_MARKDOWN_CONTENT_TYPE,\n          \"X-Farm-Markdown-Error\": \"404\",\n          \"Cache-Control\": \"no-store\",\n        },\n      }\n    ), middlewareHeaders);\n  }\n\n  try {\n    const defaultNotFoundHomeHref = applyFarmBasePath(\"/\", farmResolvedRuntimeConfig.basePath);\n    // Default 404 page component\n    function Default404Page() {\n      return React.createElement(React.Fragment, null,\n        React.createElement(\"style\", null, ${JSON.stringify(DEFAULT_NOT_FOUND_STYLES)}),\n        React.createElement(\"main\", {\n          className: \"farm-default-not-found\",\n          \"aria-labelledby\": \"farm-default-not-found-title\",\n          \"aria-describedby\": \"farm-default-not-found-description\",\n        },\n          React.createElement(\"div\", { className: \"farm-default-not-found__content\" },\n            React.createElement(\"h1\", {\n              id: \"farm-default-not-found-title\",\n              className: \"farm-default-not-found__code\",\n            }, \"404\"),\n            React.createElement(\"p\", {\n              id: \"farm-default-not-found-description\",\n              className: \"farm-default-not-found__description\",\n            }, \"Not found\"),\n            React.createElement(\"a\", {\n              className: \"farm-default-not-found__home\",\n              href: defaultNotFoundHomeHref,\n            }, \"GO HOME\")\n          )\n        )\n      );\n    }\n    \n    // Use custom 404 page if provided, otherwise use default\n    const NotFoundPage = hasCustomNotFound && CustomNotFoundComponent ? CustomNotFoundComponent : Default404Page;\n    \n    // Wrap 404 page with root layout if available\n    let notFoundElement = React.createElement(NotFoundPage, { pathname: pathname });\n    const applicableLayouts = getApplicableLayouts(\"/\");\n    \n    // Wrap with layouts (from innermost to outermost)\n    for (let i = applicableLayouts.length - 1; i >= 0; i--) {\n      const layout = applicableLayouts[i];\n      const LayoutComponent = layout.module.default;\n      if (LayoutComponent) {\n        notFoundElement = React.createElement(LayoutComponent, { children: notFoundElement, params: {} });\n      }\n    }\n    notFoundElement = wrapWithFarmIntegrationProviders(notFoundElement);\n    \n    const html = await ReactDOMServer.renderToString(notFoundElement);\n    \n    // Check if layout provides full HTML document\n    const trimmedHtml = html.trim();\n    const hasFullDocument = trimmedHtml.startsWith('<html') || trimmedHtml.startsWith('<!DOCTYPE');\n    \n    let fullHtml;\n    if (hasFullDocument) {\n      fullHtml = html\n        .replace(/<head([^>]*)>/i, '<head$1>\\\\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">')\n        .replace(/<\\\\/head>/i, () => renderFarmRendererHydrationScript() + '\\\\n</head>')\n        .replace(\n          /<\\\\/body>/i,\n          () => '  ' + renderFarmClientBootstrapScript() + '\\\\n' +\n            '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>',\n        );\n      if (!fullHtml.trim().startsWith('<!DOCTYPE')) {\n        fullHtml = '<!DOCTYPE html>\\\\n' + fullHtml;\n      }\n    } else {\n      fullHtml = \\`<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <link rel=\"icon\" href=\"data:,\">\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\n  <title>404 - Page Not Found</title>\n  \\${renderFarmRendererHydrationScript()}\n</head>\n<body>\n  <div id=\"root\">\\${html}</div>\n  \\${renderFarmClientBootstrapScript()}\n  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\n</body>\n</html>\\`;\n    }\n    fullHtml = applyFarmI18nDocument(fullHtml, pathname, getFarmI18nSnapshot());\n    fullHtml = applyFarmThemeDocument(\n      fullHtml,\n      farmThemeConfig,\n      farmResolvedRuntimeConfig.basePath,\n      getFarmTheme(request)\n    );\n    \n    emitFarmEvent({\n      type: \"render.complete\",\n      route: pathname,\n      pathname,\n      status: 404,\n      durationMs: Date.now() - requestStartTime,\n    });\n\n    return applyProductionMiddlewareHeaders(new Response(fullHtml, {\n      status: 404,\n      headers: {\n        \"Content-Type\": \"text/html; charset=utf-8\",\n        \"x-farm-preload-buffered\": \"1\",\n      }\n    }), middlewareHeaders);\n  } catch (error) {\n    console.error(\"404 render error:\", error);\n    const fallbackDocument = applyFarmThemeDocument(\n      \\`<!DOCTYPE html><html><head><title>404</title></head><body><h1>404 - Page Not Found</h1><p>The page \\${pathname} doesn't exist.</p><a href=\"\\${escapeFarmHtmlAttribute(applyFarmBasePath(\"/\", farmResolvedRuntimeConfig.basePath))}\">Go Home</a></body></html>\\`,\n      farmThemeConfig,\n      farmResolvedRuntimeConfig.basePath,\n      getFarmTheme(request)\n    );\n    return applyProductionMiddlewareHeaders(new Response(\n      fallbackDocument,\n      {\n        status: 404,\n        headers: { \"Content-Type\": \"text/html\", \"x-farm-preload-buffered\": \"1\" },\n      }\n    ), middlewareHeaders);\n  }\n  ${\n    hasMiddlewareRuntime\n      ? `\n  };\n  return request === requestBeforeMiddleware\n    ? runResolvedRequest()\n    : _runWithCurrentRequest(request, runResolvedRequest);\n  `\n      : \"\"\n  }\n}\n\nasync function handleFarmPluginRequest(request, runtimeOptions) {\n  if (!farmPluginRuntime || runtimeOptions.kind !== \"page\") {\n    return handleFarmRequest(request);\n  }\n\n  const pathname = runtimeOptions.route?.pathname || new URL(request.url).pathname;\n  const routePattern = runtimeOptions.route?.pattern || null;\n  const params = runtimeOptions.route?.params || {};\n  const layouts = getApplicableLayouts(getFarmRoutePathname(pathname));\n\n  await farmPluginRuntime.runHookParallel(\"beforeRouteMatch\", {\n    pathname,\n    method: request.method,\n  });\n  await farmPluginRuntime.runHookParallel(\"afterRouteMatch\", {\n    pathname,\n    matched: Boolean(routePattern),\n    routePattern,\n    params,\n    layoutPatterns: layouts.map((layout) => layout.pattern),\n  });\n\n  const renderPayload = {\n    pathname,\n    method: request.method,\n    routePattern,\n    params,\n  };\n  await farmPluginRuntime.runHookParallel(\"beforeRender\", renderPayload);\n\n  const response = await handleFarmRequest(request);\n  if (\n    !hasFarmPluginHTMLTransforms ||\n    !response.headers.get(\"content-type\")?.toLowerCase().includes(\"text/html\")\n  ) {\n    return response;\n  }\n\n  let html = await response.text();\n  html = await farmPluginRuntime.runHookSerial(\"transformHTML\", html);\n  html = await farmPluginRuntime.runHookSerial(\"afterRender\", html, renderPayload);\n\n  const headers = new Headers(response.headers);\n  headers.delete(\"content-length\");\n  headers.delete(\"x-farm-preload-streaming\");\n  headers.set(\"x-farm-preload-buffered\", \"1\");\n  return new Response(html, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nasync function applyFarmPreloadBudget(response, pathname) {\n  const headers = new Headers(response.headers);\n  const linkHeader = headers.get(\"Link\") || \"\";\n  const isHtml = headers.get(\"Content-Type\")?.toLowerCase().includes(\"text/html\");\n  const isStreaming = headers.get(\"x-farm-preload-streaming\") === \"1\";\n  const isBuffered = headers.get(\"x-farm-preload-buffered\") === \"1\";\n  headers.delete(\"x-farm-preload-streaming\");\n  headers.delete(\"x-farm-preload-buffered\");\n\n  if (!isHtml) {\n    if (!isStreaming && !isBuffered) return response;\n    return new Response(response.body, {\n      status: response.status,\n      statusText: response.statusText,\n      headers,\n    });\n  }\n\n  if (isStreaming || !isBuffered || response.body === null) {\n    const managed = manageFarmLinkHeaderPreloads(linkHeader, farmPreloadConfig);\n    if (managed.value) headers.set(\"Link\", managed.value);\n    else headers.delete(\"Link\");\n    reportFarmPreloadWarnings(managed.warnings, \"route \" + pathname);\n    return new Response(response.body, {\n      status: response.status,\n      statusText: response.statusText,\n      headers,\n    });\n  }\n\n  const html = await response.text();\n  const managed = manageFarmDocumentPreloads(html, linkHeader, farmPreloadConfig);\n  if (managed.linkHeader) headers.set(\"Link\", managed.linkHeader);\n  else headers.delete(\"Link\");\n  if (managed.html !== html) headers.delete(\"Content-Length\");\n  reportFarmPreloadWarnings(managed.warnings, \"route \" + pathname);\n  return new Response(managed.html, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\n// Export as Web Standard fetch API\nexport async function fetch(request, context) {\n  return _runWithAPIRequestRuntime({\n    basePath: farmLocalAPIBasePath,\n    dispatch: async (localRequest) =>\n      (await handleAPIRequest(localRequest)) ?? Response.json({ error: \"Not Found\" }, { status: 404 }),\n  }, () => handleFarmFetch(request, context));\n}\n\nasync function handleFarmFetch(request, context) {\n  const healthResponse = await farmProductionLifecycle.handleHealthRequest(request);\n  if (healthResponse) return healthResponse;\n\n  const productionSiteAttestation = farmProductionSiteTelemetry?.handleAttestation(request);\n  if (productionSiteAttestation) return productionSiteAttestation;\n\n  farmProductionSiteTelemetry?.report(\n    request.url,\n    typeof context?.waitUntil === \"function\" ? context.waitUntil.bind(context) : undefined,\n  );\n\n  return farmProductionLifecycle.runRequest(\n    () =>\n      runWithFarmRequestSpan(request, async () => {\n        const runtimeOptions = farmPluginRuntime ? getFarmPluginRequestOptions(request) : null;\n        const runRequest = () => farmPluginRuntime\n          ? farmPluginRuntime.runRuntimeRequest(\n              request,\n              (runtimeRequest) =>\n                _runWithCurrentRequest(runtimeRequest, () =>\n                  handleFarmPluginRequest(runtimeRequest, runtimeOptions)\n                ),\n              {\n                ...runtimeOptions,\n                waitUntil: typeof context?.waitUntil === \"function\"\n                  ? context.waitUntil.bind(context)\n                  : undefined,\n              },\n            )\n          : handleFarmRequest(request);\n\n        const response = await _runWithCurrentRequest(request, () =>\n          _runWithAfterRequest(request, runRequest, context),\n        );\n        const pathname = new URL(request.url).pathname;\n        return applyFarmPreloadBudget(applyConfiguredResponseHeaders(response, pathname), pathname);\n      }),\n    {\n      onResponseFinished: typeof context?.onResponseFinished === \"function\"\n        ? context.onResponseFinished\n        : undefined,\n    },\n  );\n}\nexport { createFarmNodeRequestAbortSignal };\nexport default { fetch, lifecycle: farmProductionLifecycle };\n  `.trim();\n}\n\n/**\n * Build with Nitro using virtual bundle\n * Routes are now bundled in the SSR entry, so we just need to wrap the handler\n */\nfunction matchesConfiguredRoute(source: string, pathname: string): boolean {\n  const sourceSegments = source.split(\"/\").filter(Boolean);\n  const pathnameSegments = pathname.split(\"/\").filter(Boolean);\n  let pathnameIndex = 0;\n\n  for (const sourceSegment of sourceSegments) {\n    if (sourceSegment === \"*\" || /^:[^/]+\\*$/.test(sourceSegment)) return true;\n\n    const pathnameSegment = pathnameSegments[pathnameIndex];\n    if (/^:[^/]+\\?$/.test(sourceSegment)) {\n      if (pathnameSegment !== undefined) pathnameIndex++;\n      continue;\n    }\n    if (pathnameSegment === undefined) return false;\n    if (!sourceSegment.startsWith(\":\") && sourceSegment !== pathnameSegment) return false;\n    pathnameIndex++;\n  }\n\n  return pathnameIndex === pathnameSegments.length;\n}\n\nfunction getPrerenderRouteHeaders(\n  pathname: string,\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[],\n): Record<string, string> {\n  const headers: Record<string, string> = {\n    \"cache-control\": \"public, max-age=0, must-revalidate\",\n  };\n  for (const route of configuredHeaderRoutes) {\n    if (!matchesConfiguredRoute(route.source, pathname)) continue;\n    for (const header of route.headers) headers[header.key.toLowerCase()] = header.value;\n  }\n  return headers;\n}\n\nfunction escapeRoutePattern(value: string): string {\n  return value.replace(/[|\\\\{}()[\\]^$+?.*]/g, \"\\\\$&\");\n}\n\nfunction middlewarePatternMatches(pattern: string | RegExp, pathname: string): boolean {\n  if (pattern instanceof RegExp) {\n    pattern.lastIndex = 0;\n    return pattern.test(pathname);\n  }\n\n  if (pattern === \"*\" || pattern === \"/(.*)\") return true;\n  if (pattern.endsWith(\"(.*)\")) {\n    const prefix = pattern.slice(0, -4);\n    return pathname === prefix || pathname.startsWith(`${prefix}/`);\n  }\n\n  const segments = pattern.split(\"/\").filter(Boolean);\n  if (segments.length === 0) return pathname === \"/\";\n  const expression = segments\n    .map((segment) => {\n      if (segment === \"**\") return \"(?:/.*)?\";\n      if (segment === \"*\") return \"/[^/]+\";\n      if (\n        /^:[^/]+\\*$/.test(segment) ||\n        /^\\[\\.\\.\\..+\\]$/.test(segment) ||\n        /^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)\n      ) {\n        return \"(?:/.*)?\";\n      }\n      if (/^:[^/]+\\+$/.test(segment)) return \"/.+\";\n      if (/^:[^/]+\\?$/.test(segment)) return \"(?:/[^/]+)?\";\n      if (segment.startsWith(\":\") || /^\\[.+\\]$/.test(segment)) return \"/[^/]+\";\n      return `/${escapeRoutePattern(segment).replace(/\\\\\\*/g, \"[^/]*\")}`;\n    })\n    .join(\"\");\n  return new RegExp(`^${expression}/?$`).test(pathname);\n}\n\nfunction configMiddlewareMayHandlePath(\n  config: ResolvedFarmConfig[\"middleware\"],\n  pathname: string,\n): boolean {\n  if (!hasFarmMiddlewareConfig(config)) return false;\n\n  const entries = (Array.isArray(config) ? config : [config]) as Array<{\n    matcher?: unknown | unknown[];\n    exclude?: Array<string | RegExp>;\n  }>;\n  return entries.some((entry) => {\n    if (entry.exclude?.some((pattern) => middlewarePatternMatches(pattern, pathname))) {\n      return false;\n    }\n\n    if (!entry.matcher) return true;\n    const matchers = Array.isArray(entry.matcher) ? entry.matcher : [entry.matcher];\n    return matchers.some((matcher) => {\n      // A request-aware matcher cannot be proven safe at build time.\n      if (typeof matcher === \"function\") return true;\n      return (\n        (typeof matcher === \"string\" || matcher instanceof RegExp) &&\n        middlewarePatternMatches(matcher, pathname)\n      );\n    });\n  });\n}\n\nfunction appMiddlewareMayHandlePath(\n  middlewareRoutes: readonly UniversalMiddlewareRoute[],\n  pathname: string,\n): boolean {\n  return middlewareRoutes.some((route) => {\n    if (route.path === \"/\") return true;\n    return (\n      middlewarePatternMatches(route.path, pathname) ||\n      middlewarePatternMatches(`${route.path}/**`, pathname)\n    );\n  });\n}\n\nfunction routePatternSpecificity(pattern: string): number {\n  return pattern\n    .split(\"/\")\n    .filter(Boolean)\n    .reduce((score, segment) => {\n      if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n      if (segment === \"*\" || segment.startsWith(\"[...\") || /:\\w+\\*$/.test(segment)) {\n        return score + 10;\n      }\n      if (/^\\[.+\\]$/.test(segment) || segment.startsWith(\":\")) return score + 50;\n      return score + 100;\n    }, 0);\n}\n\nfunction getEffectiveRouteRule(config: ResolvedFarmConfig, pathname: string) {\n  return Object.entries(config.routeRules)\n    .filter(([pattern]) => middlewarePatternMatches(pattern, pathname))\n    .sort(([left], [right]) => routePatternSpecificity(left) - routePatternSpecificity(right))\n    .reduce<Record<string, unknown>>((resolved, [, rule]) => Object.assign(resolved, rule), {});\n}\n\nfunction getManifestPageEntry(\n  manifest: FarmRouteRuntimeManifest,\n  pathname: string,\n): FarmRouteRuntimeManifestEntry | undefined {\n  return manifest.routes\n    .filter((entry) => entry.kind === \"page\" && middlewarePatternMatches(entry.pattern, pathname))\n    .sort(\n      (left, right) =>\n        routePatternSpecificity(right.pattern) - routePatternSpecificity(left.pattern),\n    )[0];\n}\n\nfunction getPhysicalPrerenderBypassReason(options: {\n  config: ResolvedFarmConfig;\n  middlewareRoutes: readonly UniversalMiddlewareRoute[];\n  routeRuntimeManifest: FarmRouteRuntimeManifest;\n  redirectSources: readonly string[];\n  rewriteSources: readonly string[];\n  pathname: string;\n}): string | undefined {\n  const {\n    config,\n    middlewareRoutes,\n    routeRuntimeManifest,\n    redirectSources,\n    rewriteSources,\n    pathname,\n  } = options;\n  if (config.i18n.enabled) return \"request-sensitive i18n\";\n  if (redirectSources.some((source) => middlewarePatternMatches(source, pathname))) {\n    return \"redirect\";\n  }\n  if (rewriteSources.some((source) => middlewarePatternMatches(source, pathname))) {\n    return \"rewrite\";\n  }\n  if (appMiddlewareMayHandlePath(middlewareRoutes, pathname)) return \"app middleware\";\n  if (configMiddlewareMayHandlePath(config.middleware, pathname)) return \"configured middleware\";\n  if (hasCustomFarmRouteContext(config)) return \"request context\";\n  if (hasFarmServerRuntimePlugins(config)) return \"server runtime plugin\";\n\n  const manifestEntry = getManifestPageEntry(routeRuntimeManifest, pathname);\n  if (manifestEntry?.rendering === \"dynamic\") return \"dynamic runtime manifest\";\n  if (\n    manifestEntry &&\n    (manifestEntry.runtime !== \"auto\" ||\n      Boolean(manifestEntry.regions?.length) ||\n      manifestEntry.maxDuration !== undefined)\n  ) {\n    return \"route runtime controls\";\n  }\n\n  const routeRule = getEffectiveRouteRule(config, pathname);\n  if (routeRule.prerender === false || routeRule.render === \"dynamic\" || routeRule.ssr === true) {\n    return \"dynamic route rule\";\n  }\n  if (\n    (routeRule.swr !== undefined && routeRule.swr !== false) ||\n    (routeRule.isr !== undefined && routeRule.isr !== false)\n  ) {\n    return \"runtime cache route rule\";\n  }\n\n  return undefined;\n}\n\nasync function buildNitroUniversal(\n  config: ResolvedFarmConfig,\n  routeManager: RouteManager,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: ServerRenderer,\n  preset: string,\n  root: string,\n  distDir: string,\n  ssrBundle: OutputBundle,\n  ssrEntryFile: string,\n  clientOutputDir: string,\n  routeRuntimeManifest: FarmRouteRuntimeManifest,\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[],\n  nitroRuntimeResultPromise: Promise<PromiseSettledResult<FarmNitroRuntime>>,\n  pluginManager?: PluginManager,\n) {\n  // Nitro is only needed while producing the deployment artifact. Keeping the\n  // import lazy prevents this build-only dependency from leaking into an\n  // application's standalone server bundle through @farm.js/core's root entry.\n  const [fs, nitroRuntimeResult] = await Promise.all([\n    import(\"fs/promises\"),\n    nitroRuntimeResultPromise,\n  ]);\n  if (nitroRuntimeResult.status === \"rejected\") throw nitroRuntimeResult.reason;\n  const nitro = nitroRuntimeResult.value;\n\n  const isVercel = preset === \"vercel\" || preset === \"vercel-edge\";\n  const isCloudflareWorker = preset === \"cloudflare-module\";\n  const outputDir = resolveDeployOutputPath(root, config.deploy.outputDir);\n  const ssrOutputDir = path.join(root, distDir, \"ssr\");\n  const imageRuntime = resolveImageRuntime(config, preset);\n  const hasGeneratedMetadataImages = Array.from(routeManager.getMetadataImages().values()).some(\n    (image) => image.sourceType === \"module\",\n  );\n  const useExternalMetadataImageRuntime = shouldUseExternalMetadataImageRuntime(\n    preset,\n    hasGeneratedMetadataImages,\n  );\n  const nitroRollupExternal = (id: string) =>\n    (useExternalMetadataImageRuntime && id === \"@vercel/og\") || isNitroRollupExternal(id);\n  const ssrExternalPackages = collectSSRExternalPackages(ssrBundle);\n  const copiedRuntimePackages = new Set([\n    ...(imageRuntime === \"node\" ? [\"sharp\"] : []),\n    ...(useExternalMetadataImageRuntime ? [\"@vercel/og\"] : []),\n  ]);\n  // Nitro normally rebundles the Vite SSR graph so its bare dependencies are\n  // deployable. Skip that duplicate pass only when Farm already knows how to\n  // package every remaining external; otherwise retain Nitro's proven path.\n  const isPrebuiltSSRCandidate =\n    preset === \"node-server\" &&\n    [...ssrExternalPackages].every((packageName) => copiedRuntimePackages.has(packageName));\n\n  logger.info(`📦 Nitro output directory: ${outputDir}`);\n  logger.info(`📦 SSR entry file: ${ssrEntryFile}`);\n  logger.info(`📦 Preset: ${preset}`);\n\n  const ssgCollectionPromise = routeManager.collectSSGPages();\n  const middlewareRoutesPromise = discoverMiddlewareRoutes(getFarmAppDirectories(config));\n  // Resolved config callbacks close over already-loaded arrays, so this does\n  // not re-run user discovery or fetch mutable external configuration.\n  const configuredResponseRoutesPromise = Promise.all([config.redirects(), config.rewrites()]);\n  const farmWorkflows = await prepareFarmWorkflowsForNitro(config);\n  const farmCron = await prepareFarmCronForNitro(config);\n  const [{ ssg: ssgPages }, middlewareRoutes, [configuredRedirects, configuredRewrites]] =\n    await Promise.all([\n      ssgCollectionPromise,\n      middlewareRoutesPromise,\n      configuredResponseRoutesPromise,\n    ]);\n  const redirectSources = [\n    ...routeManager.getRedirects().map((route) => route.source),\n    ...configuredRedirects.map((route: RedirectConfig) => route.source),\n  ];\n  const rewriteSources = configuredRewrites.map((route: RewriteConfig) => route.source);\n  const prerenderRoutes: string[] = [];\n  const skippedPrerenderRoutes: Array<{ pathname: string; reason: string }> = [];\n  for (const page of ssgPages) {\n    // Revalidated pages keep their runtime/CDN stale-while-revalidate\n    // behavior. Emitting them as public files would prevent the server from\n    // ever regenerating them.\n    if (page.revalidate !== undefined) continue;\n    if (prerenderRoutes.includes(page.urlPath)) continue;\n\n    const reason = getPhysicalPrerenderBypassReason({\n      config,\n      middlewareRoutes,\n      routeRuntimeManifest,\n      redirectSources,\n      rewriteSources,\n      pathname: page.urlPath,\n    });\n    if (reason) {\n      skippedPrerenderRoutes.push({ pathname: page.urlPath, reason });\n      continue;\n    }\n    prerenderRoutes.push(page.urlPath);\n  }\n  for (const skipped of skippedPrerenderRoutes) {\n    logger.info(`↪ Keeping SSG route ${skipped.pathname} server-handled (${skipped.reason})`);\n  }\n  if (farmWorkflows.workflows.length > 0) {\n    logger.info(`⏱️  Found ${farmWorkflows.workflows.length} Farm workflow task(s)`);\n  }\n  if (farmCron.jobs.length > 0) {\n    logger.info(`⏱️  Configured ${farmCron.jobs.length} Farm cron route(s)`);\n  }\n  if (preset === \"cloudflare-pages\" && farmCron.jobs.length > 0) {\n    logger.warn(\n      \"Cloudflare Pages does not install Cron Triggers. Use the cloudflare-module preset or an external scheduler with .farm/cron-manifest.json.\",\n    );\n  }\n\n  const scheduledTasks = mergeScheduledTasks(farmWorkflows.scheduledTasks, farmCron.scheduledTasks);\n  const cloudflareCronConfig = createFarmCronCloudflareConfig(farmCron.jobs);\n\n  // The client build has fully settled by now (fonts merged, output\n  // validated), so the stylesheet href baked into server code can carry the\n  // content hash of the bytes browsers will actually receive. Substituting in\n  // memory, before any consumer, covers the disk write below as well as the\n  // prebuilt-SSR copies and prerendering that reuse this bundle directly.\n  const [clientCssHref, clientJsSrc] = await Promise.all([\n    resolveHashedClientCssHref(clientOutputDir),\n    resolveHashedClientJsSrc(clientOutputDir),\n  ]);\n  for (const output of Object.values(ssrBundle)) {\n    if (output.type !== \"chunk\") continue;\n    // split/join rather than replaceAll: the package's lib target predates\n    // ES2021, and a fixed token needs no regex escaping either way.\n    if (output.code.includes(FARM_CLIENT_CSS_HREF_PLACEHOLDER)) {\n      output.code = output.code.split(FARM_CLIENT_CSS_HREF_PLACEHOLDER).join(clientCssHref);\n    }\n    if (output.code.includes(FARM_CLIENT_JS_SRC_PLACEHOLDER)) {\n      output.code = output.code.split(FARM_CLIENT_JS_SRC_PLACEHOLDER).join(clientJsSrc);\n    }\n  }\n\n  // Write SSR bundle to disk\n  await fs.mkdir(ssrOutputDir, { recursive: true });\n\n  for (const [fileName, output] of Object.entries(ssrBundle)) {\n    const filePath = path.join(ssrOutputDir, fileName);\n    // Ensure parent directory exists for nested chunks and emitted assets.\n    await fs.mkdir(path.dirname(filePath), { recursive: true });\n    await fs.writeFile(filePath, output.type === \"chunk\" ? output.code : output.source);\n  }\n\n  // Create the Nitro event handler adapter. Nitro accepts plain event handler\n  // functions, so keep this entry dependency-free for standalone output.\n  const nitroEntryPath = path.join(ssrOutputDir, \"nitro-entry.mjs\");\n\n  const nitroEntryCode = `\n// Farm.js Nitro Entry\n// This file adapts Farm's Web fetch handler to Nitro's event handler contract.\n\nimport { useNitroApp } from 'nitro/runtime'\nimport handler, { farmProductionLifecycle, createFarmNodeRequestAbortSignal } from './${ssrEntryFile}'\n\nexport { farmProductionLifecycle }\n\nconst farmNitroApp = useNitroApp()\nfarmNitroApp.hooks.hook('close', () =>\n  farmProductionLifecycle.close('production-server-closed')\n)\n\nfunction mergeVaryHeaders(target, source) {\n  const values = new Set(\n    [target.get('Vary'), source]\n      .filter(Boolean)\n      .flatMap((value) => value.split(','))\n      .map((value) => value.trim())\n      .filter(Boolean),\n  )\n\n  if (values.size > 0) target.set('Vary', Array.from(values).join(', '))\n}\n\nfunction createResponseFinishedHook(event) {\n  const nodeResponse = event.node?.res\n  if (!nodeResponse || typeof nodeResponse.once !== 'function') return undefined\n\n  return (callback) => {\n    if (nodeResponse.writableEnded || nodeResponse.writableFinished) {\n      queueMicrotask(callback)\n      return\n    }\n\n    let finished = false\n    const finish = () => {\n      if (finished) return\n      finished = true\n      nodeResponse.off('finish', finish)\n      nodeResponse.off('close', finish)\n      callback()\n    }\n    nodeResponse.once('finish', finish)\n    nodeResponse.once('close', finish)\n  }\n}\n\n// Export the event handler for Nitro\nexport default async function farmNitroEventHandler(event) {\n  // Some Node adapters abort their Request on normal IncomingMessage close.\n  // Use the same actual disconnect events as Farm's development server.\n  const node = event.node\n  const request = node?.req && node?.res\n    ? new Request(event.req, { signal: createFarmNodeRequestAbortSignal(node.req, node.res) })\n    : event.req\n  const response = await handler.fetch(request, {\n    waitUntil: (promise) => event.waitUntil(promise),\n    onResponseFinished: createResponseFinishedHook(event),\n  })\n\n  // Nitro records asset compression negotiation on the event response. Merge\n  // Farm's cache signals there so H3 preserves both sets of Vary values.\n  const farmVary = response.headers.get('Vary')\n  if (farmVary) mergeVaryHeaders(event.res.headers, farmVary)\n  return response\n}\n  `.trim();\n\n  await fs.writeFile(nitroEntryPath, nitroEntryCode);\n  const farmNodeServerEntryPath =\n    preset === \"node-server\" ? path.join(ssrOutputDir, \"farm-node-server-entry.mjs\") : null;\n  if (farmNodeServerEntryPath) {\n    await fs.writeFile(\n      farmNodeServerEntryPath,\n      createFarmNodeServerEntry({\n        nitroEntryFile: path.basename(nitroEntryPath),\n        nodeHandlerModule: resolveNitroRuntimeDependency(root, \"srvx/node\"),\n        server: config.server,\n        websocketAdapterModule: resolveNitroRuntimeDependency(root, \"crossws/adapters/node\"),\n      }),\n    );\n  }\n  const prebuiltSSRPlugin = createExternalSSRBundlePlugin(\n    nitroEntryPath,\n    ssrOutputDir,\n    ssrEntryFile,\n  );\n  const configuredNitroRouteRules = routeRulesToNitroRouteRules(config.routeRules);\n  const prerenderNitroRouteRules = Object.fromEntries(\n    prerenderRoutes.map((route) => {\n      const configuredRule = configuredNitroRouteRules[route] || {};\n      return [\n        route,\n        {\n          ...configuredRule,\n          prerender: true,\n          headers: {\n            ...getPrerenderRouteHeaders(route, configuredHeaderRoutes),\n            ...configuredRule.headers,\n          },\n        },\n      ];\n    }),\n  );\n\n  let nitroConfig: NitroConfig = {\n    preset,\n    ...(farmNodeServerEntryPath ? { entry: farmNodeServerEntryPath } : {}),\n    rootDir: root,\n    srcDir: root,\n    buildDir: path.join(root, distDir, \".nitro\"),\n    compatibilityDate: \"2024-12-01\",\n    output: {\n      dir: outputDir,\n      serverDir: path.join(outputDir, \"server\"),\n      publicDir: path.join(outputDir, \"public\"),\n    },\n    publicAssets: [\n      {\n        dir: clientOutputDir,\n        maxAge: 31536000,\n        baseURL: \"/\",\n      },\n    ],\n    ...(prerenderRoutes.length > 0\n      ? {\n          prerender: {\n            crawlLinks: false,\n            failOnError: true,\n            routes: prerenderRoutes,\n          },\n        }\n      : {}),\n    experimental: {\n      tasks: farmWorkflows.workflows.length > 0 || farmCron.jobs.length > 0,\n    },\n    tasks: {\n      ...farmWorkflows.tasks,\n      ...farmCron.tasks,\n    },\n    scheduledTasks: isVercel ? farmWorkflows.scheduledTasks : scheduledTasks,\n    ...(isCloudflareWorker && cloudflareCronConfig\n      ? {\n          cloudflare: cloudflareCronConfig,\n        }\n      : {}),\n    // Use serverHandlers to define our workflow handler first, then the catch-all handler.\n    handlers: [\n      ...(farmWorkflows.handlerPath\n        ? [\n            {\n              route: `${config.workflows.route}/**`,\n              handler: farmWorkflows.handlerPath,\n            },\n          ]\n        : []),\n      {\n        route: \"/**\",\n        handler: toPosixPath(nitroEntryPath),\n      },\n    ],\n    routeRules: {\n      ...(resolveFarmAPIServerBasePath(config.api) === \"/\"\n        ? {}\n        : {\n            [`${resolveFarmAPIServerBasePath(config.api)}/**`]: {\n              cors: true,\n              headers: {\n                \"Access-Control-Allow-Origin\": \"*\",\n                \"Access-Control-Allow-Methods\": \"*\",\n                \"Access-Control-Allow-Headers\": \"*\",\n              },\n            },\n          }),\n      \"/**\": {\n        prerender: false,\n      },\n      ...configuredNitroRouteRules,\n      // Exact user rules must retain their runtime settings without replacing\n      // the headers and prerender marker generated for a safe physical page.\n      ...prerenderNitroRouteRules,\n    },\n    externals: {\n      external: [\n        \"react\",\n        \"react-dom\",\n        \"@prisma/client\",\n        \"@prisma/client/default\",\n        \"@prisma/client/default.js\",\n        \".prisma/client\",\n        \".prisma/client/default\",\n        \"better-sqlite3\",\n        \"sharp\",\n        ...(useExternalMetadataImageRuntime ? [\"@vercel/og\"] : []),\n      ],\n    },\n    rollupConfig: {\n      external: nitroRollupExternal,\n      plugins:\n        hasGeneratedMetadataImages && !useExternalMetadataImageRuntime\n          ? [createMetadataImageWasmPlugin()]\n          : [],\n    },\n    // Keep the public Nitro boolean intact for build hooks. It is translated to\n    // Nitro's existing esbuild pass after hooks run, avoiding a second Terser pass.\n    minify: true,\n    sourceMap: false, // Skip sourcemaps for faster build\n  };\n  const initialSSRRebundleOptions = snapshotSSRRebundleOptions(nitroConfig);\n\n  if (pluginManager) {\n    nitroConfig = await pluginManager.runHookSerial(\"beforeNitroBuild\", nitroConfig);\n  }\n\n  const expectedServerDir = path.join(outputDir, \"server\");\n  const customRollupKeys = Object.keys(nitroConfig.rollupConfig || {}).filter(\n    (key) => key !== \"external\" && key !== \"plugins\",\n  );\n  const configuredEsbuild = nitroConfig.esbuild?.options;\n  const hasUnsupportedEsbuildOverrides = Boolean(\n    configuredEsbuild?.include !== undefined ||\n    configuredEsbuild?.exclude !== undefined ||\n    configuredEsbuild?.loaders !== undefined ||\n    configuredEsbuild?.sourceMap,\n  );\n  const hasLateBuildMutationConfig = Boolean(\n    Object.keys(nitroConfig.hooks || {}).length > 0 ||\n    (Array.isArray(nitroConfig.modules) ? nitroConfig.modules.some(Boolean) : nitroConfig.modules),\n  );\n  const hasUnsupportedSSRRebundleOverrides = !isDeepStrictEqual(\n    initialSSRRebundleOptions,\n    snapshotSSRRebundleOptions(nitroConfig),\n  );\n  const requestedBuilder = nitroConfig.builder ?? process.env.NITRO_BUILDER;\n  const canReusePrebuiltSSR =\n    isPrebuiltSSRCandidate &&\n    nitroConfig.preset === \"node-server\" &&\n    (requestedBuilder === undefined ||\n      requestedBuilder === \"rollup\" ||\n      requestedBuilder === \"rolldown\") &&\n    nitroConfig.sourceMap === false &&\n    !hasUnsupportedEsbuildOverrides &&\n    !hasLateBuildMutationConfig &&\n    !hasUnsupportedSSRRebundleOverrides &&\n    nitroConfig.rollupConfig?.external === nitroRollupExternal &&\n    !hasRollupPlugins(nitroConfig.rollupConfig?.plugins) &&\n    customRollupKeys.length === 0 &&\n    path.resolve(nitroConfig.output?.serverDir || \"\") === path.resolve(expectedServerDir) &&\n    Boolean(\n      nitroConfig.handlers?.some(\n        (handler) => path.resolve(handler?.handler || \"\") === nitroEntryPath,\n      ),\n    );\n  const selectRolldownBuilder =\n    canReusePrebuiltSSR && requestedBuilder === undefined && (await canUseRolldownBuilder());\n  if (selectRolldownBuilder) nitroConfig.builder = \"rolldown\";\n  const useRolldownBuilder =\n    canReusePrebuiltSSR && (nitroConfig.builder ?? process.env.NITRO_BUILDER) === \"rolldown\";\n\n  const shouldMinify = nitroConfig.minify !== false;\n  const configuredEsbuildOptions = nitroConfig.esbuild?.options || {};\n  const resolvedEsbuildOptions = {\n    ...configuredEsbuildOptions,\n    // Function-name helpers are unsafe for provider scripts that serialize a\n    // function with toString(); the helper is outside the emitted script scope.\n    keepNames:\n      config.docs?.enabled && config.docs.adapter?.server\n        ? false\n        : (configuredEsbuildOptions.keepNames ?? true),\n  };\n  const prebuiltSSREsbuildOptions =\n    config.docs?.enabled && config.docs.adapter?.server\n      ? resolvedEsbuildOptions\n      : configuredEsbuildOptions;\n  const effectiveMinify = configuredEsbuildOptions.minify ?? shouldMinify;\n  const useFarmEsbuildMinifier =\n    effectiveMinify &&\n    nitroConfig.sourceMap === false &&\n    !hasUnsupportedEsbuildOverrides &&\n    !hasLateBuildMutationConfig;\n  const esbuildChunkMinifier = useFarmEsbuildMinifier\n    ? createEsbuildChunkMinifyPlugin(resolvedEsbuildOptions)\n    : null;\n  if (canReusePrebuiltSSR) {\n    const configuredRollupPlugins = nitroConfig.rollupConfig?.plugins;\n    nitroConfig.rollupConfig = {\n      ...nitroConfig.rollupConfig,\n      plugins: [\n        ...(Array.isArray(configuredRollupPlugins)\n          ? configuredRollupPlugins\n          : configuredRollupPlugins\n            ? [configuredRollupPlugins]\n            : []),\n        prebuiltSSRPlugin,\n      ],\n    };\n  }\n\n  nitroConfig.minify = useFarmEsbuildMinifier ? false : shouldMinify;\n  nitroConfig.esbuild = {\n    ...nitroConfig.esbuild,\n    options: {\n      ...resolvedEsbuildOptions,\n      minify: useFarmEsbuildMinifier ? false : configuredEsbuildOptions.minify,\n      keepNames: resolvedEsbuildOptions.keepNames,\n      legalComments: configuredEsbuildOptions.legalComments ?? \"none\",\n    },\n  };\n\n  // Build with Nitro\n  const nitroInstance = await nitro.createNitro(nitroConfig);\n  if (farmNodeServerEntryPath) {\n    // The custom entry is only for the final long-running Node server. Nitro\n    // derives its prerenderer config from this config, so remove the override\n    // and let the nitro-prerender preset provide appFetch/closePrerenderer.\n    nitroInstance.hooks.hook(\"prerender:config\", (prerendererConfig) => {\n      delete prerendererConfig.entry;\n    });\n  }\n  nitroInstance.hooks.hook(\"prerender:init\", (prerenderer) => {\n    prerenderer.hooks.hook(\"rollup:before\", (_prerenderNitro, rollupConfig) => {\n      // Nitro's virtual modules (storage, tasks, ...) emit bare imports of\n      // Nitro's own runtime dependencies (unstorage, h3, ...). Their virtual\n      // importer is discarded during resolution, so under pnpm's strict\n      // node_modules layout these transitive dependencies cannot be resolved,\n      // and rollup silently leaves them as bare imports in the temporary\n      // prerender server. Importing that server from the output directory\n      // then fails with ERR_MODULE_NOT_FOUND (#403). Retry unresolved bare\n      // ids from Nitro's own package context so they bundle like the rest.\n      const configuredPlugins = rollupConfig.plugins;\n      rollupConfig.plugins = [\n        ...(Array.isArray(configuredPlugins)\n          ? configuredPlugins\n          : configuredPlugins\n            ? [configuredPlugins]\n            : []),\n        createPrerenderRuntimeResolverPlugin(config.root),\n      ];\n    });\n  });\n  await nitro.prepare(nitroInstance);\n  await nitro.copyPublicAssets(nitroInstance);\n  if (prerenderRoutes.length > 0 && canReusePrebuiltSSR) {\n    // The prerenderer builds and immediately imports a temporary server before\n    // the final Node adapter exists. Materialize the same prebuilt SSR package\n    // import for that temporary server so it can render the static routes.\n    nitroInstance.hooks.hook(\"prerender:init\", (prerenderer) => {\n      if (useRolldownBuilder) {\n        prerenderer.hooks.hook(\"rollup:before\", (_nitro, rollupConfig) => {\n          const rolldownConfig = rollupConfig as typeof rollupConfig & {\n            inject?: unknown;\n            jsx?: unknown;\n          };\n          delete rolldownConfig.inject;\n          delete rolldownConfig.jsx;\n        });\n      }\n      prerenderer.hooks.hook(\"compiled\", async () => {\n        const prerenderServerDir = path.join(outputDir, \"server\");\n        await copyPrebuiltSSRBundle(\n          ssrBundle,\n          path.join(prerenderServerDir, FARM_SSR_OUTPUT_DIR),\n          {},\n          false,\n          fs,\n        );\n        await registerPrebuiltSSRPackageImport(prerenderServerDir, ssrEntryFile, fs);\n      });\n    });\n  }\n  if (esbuildChunkMinifier || useRolldownBuilder) {\n    // Register after Nitro and user hooks are prepared so the minifier is the\n    // final renderChunk transform, matching Nitro's Terser ordering.\n    nitroInstance.hooks.hook(\"rollup:before\", (_nitro, rollupConfig) => {\n      if (useRolldownBuilder) {\n        // Nitro 3 alpha still emits transform options that this Rolldown API\n        // rejects. The generated native Node adapter contains neither JSX nor\n        // browser-global injections, so omit both without changing its output.\n        const rolldownConfig = rollupConfig as typeof rollupConfig & {\n          inject?: unknown;\n          jsx?: unknown;\n        };\n        delete rolldownConfig.inject;\n        delete rolldownConfig.jsx;\n      }\n      if (esbuildChunkMinifier) {\n        const configuredPlugins = rollupConfig.plugins;\n        rollupConfig.plugins = [\n          ...(Array.isArray(configuredPlugins)\n            ? configuredPlugins\n            : configuredPlugins\n              ? [configuredPlugins]\n              : []),\n          esbuildChunkMinifier,\n        ];\n      }\n    });\n  }\n  if (prerenderRoutes.length > 0) {\n    logger.info(`📄 Pre-rendering ${prerenderRoutes.length} SSG page(s)`);\n    await nitro.prerender(nitroInstance);\n  }\n  await nitro.build(nitroInstance);\n  await nitroInstance.close();\n\n  const copyResults = await Promise.allSettled([\n    canReusePrebuiltSSR\n      ? copyPrebuiltSSRBundle(\n          ssrBundle,\n          path.join(outputDir, \"server\", FARM_SSR_OUTPUT_DIR),\n          prebuiltSSREsbuildOptions,\n          effectiveMinify,\n          fs,\n        )\n      : Promise.resolve(),\n    imageRuntime === \"node\"\n      ? copySharpRuntime(config, root, path.join(outputDir, \"server\"), fs)\n      : Promise.resolve(),\n    useExternalMetadataImageRuntime\n      ? copyMetadataImageRuntime(root, path.join(outputDir, \"server\"), fs)\n      : Promise.resolve(),\n  ]);\n  const failedCopy = copyResults.find(\n    (result): result is PromiseRejectedResult => result.status === \"rejected\",\n  );\n  if (failedCopy) throw failedCopy.reason;\n\n  if (canReusePrebuiltSSR) {\n    await registerPrebuiltSSRPackageImport(path.join(outputDir, \"server\"), ssrEntryFile, fs);\n    logger.info(\"⚡ Reused Farm's prebuilt SSR bundle for the Node output\");\n  }\n  if (useRolldownBuilder) {\n    logger.info(\"⚡ Built the Node adapter with Rolldown\");\n  }\n\n  if (pluginManager) {\n    await pluginManager.runHookParallel(\"afterNitroBuild\", {\n      root,\n      preset,\n      distDir,\n      outputDir,\n    });\n  }\n\n  // Post-process for Vercel Build Output API v3\n  // Move server/ to functions/__nitro.func/ and update config.json\n  if (isVercel) {\n    await postProcessVercelOutput(root, outputDir, fs, config, farmWorkflows, routeRuntimeManifest);\n  }\n\n  logger.success(`✅ Nitro build completed with preset: ${preset}`);\n}\n\nasync function copyPrebuiltSSRBundle(\n  ssrBundle: OutputBundle,\n  targetDir: string,\n  configuredEsbuildOptions: NitroEsbuildOptions,\n  minify: boolean,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const {\n    include: _include,\n    exclude: _exclude,\n    sourceMap: _sourceMap,\n    loaders: _loaders,\n    ...configuredTransformOptions\n  } = configuredEsbuildOptions;\n  const hasConfiguredTransforms = Object.keys(configuredTransformOptions).some(\n    (option) => option !== \"minify\",\n  );\n  const transformOptions = createEsbuildTransformOptions(\n    configuredEsbuildOptions,\n    minify,\n    \"node18\",\n  );\n  const transform = minify || hasConfiguredTransforms ? (await import(\"esbuild\")).transform : null;\n\n  await fs.rm(targetDir, { recursive: true, force: true });\n  await Promise.all(\n    Object.entries(ssrBundle).map(async ([fileName, output]) => {\n      const targetPath = path.join(targetDir, fileName);\n      await fs.mkdir(path.dirname(targetPath), { recursive: true });\n\n      if (output.type === \"asset\") {\n        await fs.writeFile(targetPath, output.source);\n        return;\n      }\n\n      let code = output.code;\n      if (transform) {\n        const result = await transform(code, {\n          ...transformOptions,\n          sourcefile: fileName,\n        });\n        code = result.code;\n      }\n\n      await fs.writeFile(targetPath, code);\n    }),\n  );\n}\n\nasync function registerPrebuiltSSRPackageImport(\n  serverDir: string,\n  ssrEntryFile: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const packagePath = path.join(serverDir, \"package.json\");\n  const packageJSON = await fs\n    .readFile(packagePath, \"utf8\")\n    .then((contents) => JSON.parse(contents))\n    .catch((error: NodeJS.ErrnoException) => {\n      if (error.code === \"ENOENT\") return { type: \"module\" };\n      throw error;\n    });\n  const existingImports =\n    packageJSON.imports && typeof packageJSON.imports === \"object\" ? packageJSON.imports : {};\n  const outputEntry = `${FARM_SSR_OUTPUT_DIR}/${ssrEntryFile}`.replace(/\\\\/g, \"/\");\n\n  packageJSON.imports = {\n    ...existingImports,\n    [FARM_SSR_PACKAGE_IMPORT]: `./${outputEntry}`,\n  };\n  await fs.mkdir(serverDir, { recursive: true });\n  await fs.writeFile(packagePath, `${JSON.stringify(packageJSON, null, 2)}\\n`);\n}\n\n/**\n * Move a file or directory, falling back to copy-and-remove when rename is\n * not permitted. On Windows, fs.rename fails with EPERM/EACCES when another\n * process (antivirus, indexing, a running dev server) holds a handle on the\n * directory, and with EXDEV across drives; a copy is slower but succeeds.\n */\nexport async function moveVercelOutputPath(\n  src: string,\n  dest: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  try {\n    await fs.rename(src, dest);\n    return;\n  } catch (error) {\n    const code = (error as NodeJS.ErrnoException)?.code;\n    if (code !== \"EPERM\" && code !== \"EACCES\" && code !== \"EXDEV\" && code !== \"ENOTEMPTY\") {\n      throw error;\n    }\n  }\n  await fs.cp(src, dest, { recursive: true, force: true });\n  await fs.rm(src, { recursive: true, force: true });\n}\n\n/**\n * Post-process Vercel output to match Build Output API v3\n * Moves server/ to functions/__nitro.func/ and updates routes\n */\nasync function postProcessVercelOutput(\n  root: string,\n  outputDir: string,\n  fs: typeof import(\"fs/promises\"),\n  config: ResolvedFarmConfig,\n  farmWorkflows: PreparedFarmWorkflows,\n  routeRuntimeManifest: FarmRouteRuntimeManifest,\n) {\n  const serverDir = path.join(outputDir, \"server\");\n  const functionsDir = path.join(outputDir, \"functions\");\n  const nitroFuncDir = path.join(functionsDir, \"__nitro.func\");\n  const staticDir = path.join(outputDir, \"static\");\n  const publicDir = path.join(outputDir, \"public\");\n\n  // Create functions directory\n  await fs.mkdir(nitroFuncDir, { recursive: true });\n\n  // Move server contents to functions/__nitro.func/\n  const serverContents = await fs.readdir(serverDir);\n  for (const file of serverContents) {\n    const src = path.join(serverDir, file);\n    const dest = path.join(nitroFuncDir, file);\n    await moveVercelOutputPath(src, dest, fs);\n  }\n\n  // Remove the emptied server directory\n  await fs.rm(serverDir, { recursive: true, force: true });\n\n  // Rename public to static (Vercel expects static files in static/)\n  try {\n    await moveVercelOutputPath(publicDir, staticDir, fs);\n  } catch (error) {\n    // public might not exist\n    if ((error as NodeJS.ErrnoException)?.code !== \"ENOENT\") throw error;\n  }\n\n  // Add runtime assets before cloning route-specific functions.\n  await copyFarmDocsContentForVercel(config, root, nitroFuncDir, fs);\n  await copyPrismaClientForVercel(root, nitroFuncDir, fs);\n\n  // Update config.json routes to point to the function\n  const configPath = path.join(outputDir, \"config.json\");\n  const configContent = await fs.readFile(configPath, \"utf-8\");\n  const vercelConfig = JSON.parse(configContent);\n\n  const runtimeRoutes = await createFarmVercelRouteRuntimeFunctions(\n    outputDir,\n    routeRuntimeManifest,\n    fs,\n  );\n\n  // Rebuild the routes around Farm's `__nitro` function while preserving the\n  // preset's redirect and header routes (previously discarded). See\n  // buildFarmVercelRoutes for the full merge contract.\n  vercelConfig.routes = buildFarmVercelRoutes({\n    presetRoutes: Array.isArray(vercelConfig.routes) ? vercelConfig.routes : [],\n    runtimeRoutes,\n    apiBasePath: resolveFarmAPIServerBasePath(config.api),\n  });\n\n  const vercelConfigWithWorkflowCrons = applyFarmWorkflowVercelCrons(\n    vercelConfig,\n    farmWorkflows.workflows,\n  );\n  const vercelConfigWithCrons = applyFarmCronVercelCrons(\n    vercelConfigWithWorkflowCrons,\n    config.cron.jobs,\n  );\n\n  await fs.writeFile(configPath, JSON.stringify(vercelConfigWithCrons, null, 2));\n\n  logger.info(\"✅ Post-processed Vercel output for Build Output API v3\");\n}\n\nasync function copyFarmDocsContentForVercel(\n  config: ResolvedFarmConfig,\n  root: string,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n) {\n  const docsContentDir = resolveBuildDocsContentDir(config, root);\n  if (!docsContentDir) return;\n\n  const bundledContentDir = path.join(nitroFuncDir, \"chunks\", \"nitro\", \"farm-docs-content\");\n  const lastModifiedManifest = createFarmDocsLastModifiedManifest(docsContentDir, {\n    fallback: \"now\",\n  });\n  await fs.rm(bundledContentDir, { recursive: true, force: true });\n  await fs.mkdir(path.dirname(bundledContentDir), { recursive: true });\n  await fs.cp(docsContentDir, bundledContentDir, {\n    recursive: true,\n    force: true,\n  });\n  await fs.writeFile(\n    path.join(bundledContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST),\n    `${JSON.stringify(lastModifiedManifest, null, 2)}\\n`,\n  );\n\n  logger.info(`📚 Bundled docs content for Vercel: ${path.relative(root, docsContentDir)}`);\n}\n\nasync function copySharpRuntime(\n  config: ResolvedFarmConfig,\n  root: string,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  if (config.images.provider === \"none\") return;\n\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  let sharpRequire = projectRequire;\n  if (!resolvePackageJson(projectRequire, \"sharp\")) {\n    try {\n      // Applications are not required to depend on Sharp directly. Resolve\n      // Farm's optional dependency from the installed framework entry when the\n      // project dependency tree does not expose it.\n      sharpRequire = createRequire(projectRequire.resolve(\"@farm.js/core\"));\n    } catch {\n      // The existing missing-Sharp diagnostic below remains authoritative.\n    }\n  }\n  const copiedPackages = new Map<string, string>();\n  const packageCopies = new Map<string, Promise<void>>();\n  const targetNodeModules = path.join(nitroFuncDir, \"node_modules\");\n\n  function copyPackage(packageName: string, parentRequire: NodeJS.Require): Promise<void> {\n    const activeCopy = packageCopies.get(packageName);\n    if (activeCopy) return activeCopy;\n\n    const packageCopy = copyPackageOnce(packageName, parentRequire);\n    packageCopies.set(packageName, packageCopy);\n    return packageCopy;\n  }\n\n  async function copyPackageOnce(\n    packageName: string,\n    parentRequire: NodeJS.Require,\n  ): Promise<void> {\n    const packageJsonPath = resolvePackageJson(parentRequire, packageName);\n    if (!packageJsonPath) return;\n    const packageJson = JSON.parse(await fs.readFile(packageJsonPath, \"utf8\"));\n    const packageDir = path.dirname(packageJsonPath);\n    const targetDir = path.join(targetNodeModules, ...packageName.split(\"/\"));\n    copiedPackages.set(packageName, String(packageJson.version || \"*\"));\n\n    await fs.mkdir(path.dirname(targetDir), { recursive: true });\n    const packageRequire = createRequire(packageJsonPath);\n    const dependencies = {\n      ...packageJson.dependencies,\n      ...packageJson.optionalDependencies,\n    };\n    await Promise.all([\n      fs.cp(packageDir, targetDir, {\n        recursive: true,\n        force: true,\n        dereference: true,\n        // Reflinks make native runtime packaging nearly metadata-only on\n        // supporting filesystems and transparently fall back to byte copies.\n        mode: fsConstants.COPYFILE_FICLONE,\n      }),\n      ...Object.keys(dependencies).map((dependency) => copyPackage(dependency, packageRequire)),\n    ]);\n  }\n\n  await copyPackage(\"sharp\", sharpRequire);\n  if (!copiedPackages.has(\"sharp\")) {\n    throw new Error(\n      \"Farm image optimization requires sharp. Reinstall dependencies without omitting optional packages.\",\n    );\n  }\n\n  const functionPackagePath = path.join(nitroFuncDir, \"package.json\");\n  const functionPackage = JSON.parse(await fs.readFile(functionPackagePath, \"utf8\"));\n  functionPackage.dependencies = {\n    ...functionPackage.dependencies,\n    ...Object.fromEntries([...copiedPackages].sort(([left], [right]) => left.localeCompare(right))),\n  };\n  await fs.writeFile(functionPackagePath, JSON.stringify(functionPackage, null, 2));\n  logger.info(`🖼️  Bundled Sharp image runtime (${copiedPackages.size} packages)`);\n}\n\nasync function copyMetadataImageRuntime(\n  root: string,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  let runtimeRequire = projectRequire;\n  let packageJsonPath = resolvePackageJson(runtimeRequire, \"@vercel/og\");\n\n  if (!packageJsonPath) {\n    try {\n      runtimeRequire = createRequire(projectRequire.resolve(\"@farm.js/core\"));\n      packageJsonPath = resolvePackageJson(runtimeRequire, \"@vercel/og\");\n    } catch {\n      // The missing-runtime diagnostic below remains authoritative.\n    }\n  }\n\n  if (!packageJsonPath) {\n    throw new Error(\n      \"Generated metadata images require @vercel/og. Reinstall @farm.js/core with production dependencies.\",\n    );\n  }\n\n  const packageJson = JSON.parse(await fs.readFile(packageJsonPath, \"utf8\"));\n  const packageDir = path.dirname(packageJsonPath);\n  const targetDir = path.join(nitroFuncDir, \"node_modules\", \"@vercel\", \"og\");\n  await fs.mkdir(path.dirname(targetDir), { recursive: true });\n  await fs.cp(packageDir, targetDir, {\n    recursive: true,\n    force: true,\n    dereference: true,\n    mode: fsConstants.COPYFILE_FICLONE,\n  });\n\n  const functionPackagePath = path.join(nitroFuncDir, \"package.json\");\n  const functionPackage = JSON.parse(await fs.readFile(functionPackagePath, \"utf8\"));\n  functionPackage.dependencies = {\n    ...functionPackage.dependencies,\n    \"@vercel/og\": String(packageJson.version || \"0.11.1\"),\n  };\n  await fs.writeFile(functionPackagePath, JSON.stringify(functionPackage, null, 2));\n  logger.info(\"🖼️  Bundled generated metadata image runtime\");\n}\n\nfunction resolvePackageJson(parentRequire: NodeJS.Require, packageName: string): string | null {\n  for (const request of [`${packageName}/package.json`, `${packageName}/package`]) {\n    try {\n      return parentRequire.resolve(request);\n    } catch {\n      // Try the next package metadata export.\n    }\n  }\n  return null;\n}\n\nasync function copyPrismaClientForVercel(\n  root: string,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n) {\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n\n  let prismaClientDir: string;\n  try {\n    prismaClientDir = path.dirname(projectRequire.resolve(\"@prisma/client/default.js\"));\n  } catch {\n    return;\n  }\n\n  const generatedClientDir = path.join(prismaClientDir, \"..\", \"..\", \".prisma\", \"client\");\n\n  try {\n    await fs.access(generatedClientDir);\n  } catch {\n    return;\n  }\n\n  const targetNodeModules = path.join(nitroFuncDir, \"node_modules\");\n  const targetPrismaScopeDir = path.join(targetNodeModules, \"@prisma\");\n  const targetGeneratedDir = path.join(targetNodeModules, \".prisma\", \"client\");\n  const targetClientDir = path.join(targetPrismaScopeDir, \"client\");\n\n  await fs.mkdir(targetPrismaScopeDir, { recursive: true });\n  await fs.cp(prismaClientDir, targetClientDir, {\n    recursive: true,\n    force: true,\n  });\n  await fs.cp(generatedClientDir, targetGeneratedDir, {\n    recursive: true,\n    force: true,\n  });\n\n  const functionPackagePath = path.join(nitroFuncDir, \"package.json\");\n  const clientPackagePath = path.join(prismaClientDir, \"package.json\");\n  const [functionPackageContent, clientPackageContent] = await Promise.all([\n    fs.readFile(functionPackagePath, \"utf-8\"),\n    fs.readFile(clientPackagePath, \"utf-8\"),\n  ]);\n  const functionPackage = JSON.parse(functionPackageContent);\n  const clientPackage = JSON.parse(clientPackageContent);\n\n  functionPackage.dependencies = {\n    ...functionPackage.dependencies,\n    \"@prisma/client\": clientPackage.version,\n  };\n\n  await fs.writeFile(functionPackagePath, JSON.stringify(functionPackage, null, 2));\n}\n","import path from \"path\";\n\n/**\n * Stand-ins for the client asset URLs inside generated server code.\n * The client and SSR graphs build in parallel, so the final asset bytes\n * (fonts are merged into the stylesheet after Vite emits it) do not exist\n * yet when server code is generated. buildNitroUniversal substitutes the\n * real, content-hashed URLs once the client build has settled.\n */\nexport const FARM_CLIENT_CSS_HREF_PLACEHOLDER = \"/__farm_client_css_href__\";\nexport const FARM_CLIENT_JS_SRC_PLACEHOLDER = \"/__farm_client_js_src__\";\n\nasync function hashAndCopy(\n  sourcePath: string,\n  destinationDir: string,\n  hashedName: (hash: string) => string,\n): Promise<string | null> {\n  const fs = await import(\"fs/promises\");\n  try {\n    const bytes = await fs.readFile(sourcePath);\n    if (bytes.length === 0) return null;\n    const { createHash } = await import(\"node:crypto\");\n    const hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 8);\n    const name = hashedName(hash);\n    await fs.mkdir(destinationDir, { recursive: true });\n    await fs.writeFile(path.join(destinationDir, name), bytes);\n    return name;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Content-hash the final client stylesheet and return the href generated\n * server code should reference.\n *\n * The hash is taken after font CSS has been merged in, so any change to the\n * bytes a browser would receive changes the URL. The hashed copy lives under\n * assets/, where the -h fingerprint already qualifies for immutable caching;\n * the stable farm-client.css stays in place for anything that hardcoded it.\n * A missing or empty stylesheet falls back to the stable name, matching the\n * empty file written for intentionally style-free applications.\n */\nexport async function resolveHashedClientCssHref(clientOutputDir: string): Promise<string> {\n  const name = await hashAndCopy(\n    path.join(clientOutputDir, \"farm-client.css\"),\n    path.join(clientOutputDir, \"assets\"),\n    (hash) => `farm-client-h${hash}.css`,\n  );\n  return name ? `/assets/${name}` : \"/farm-client.css\";\n}\n\n/**\n * The client entry emitted by the current build, if it carries a content\n * fingerprint. Vite names it farm-client-h<hash>.js so its code-split chunks\n * import the fingerprinted name natively; emptyOutDir keeps stale builds from\n * leaving older fingerprints behind.\n */\nexport async function findFingerprintedClientEntry(\n  clientOutputDir: string,\n): Promise<string | null> {\n  const fs = await import(\"fs/promises\");\n  try {\n    const entries = await fs.readdir(clientOutputDir);\n    return entries.find((name) => /^farm-client-h[0-9a-f]+\\.js$/.test(name)) ?? null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Resolve the src generated server code should reference for the client\n * entry, and keep the stable name working.\n *\n * The entry cannot be duplicated under a second name: its chunks import back\n * into it (it is the shared runtime), so a copy would be instantiated twice\n * and React would see two instances. Instead the bundler emits the\n * fingerprinted name directly, and the stable farm-client.js becomes a\n * re-export shim — anything that hardcoded the old path still executes the\n * one real module.\n */\nexport async function resolveHashedClientJsSrc(clientOutputDir: string): Promise<string> {\n  const entryName = await findFingerprintedClientEntry(clientOutputDir);\n  if (!entryName) return \"/farm-client.js\";\n  const fs = await import(\"fs/promises\");\n  const shim = `export * from \"./${entryName}\";\\n`;\n  await fs.writeFile(path.join(clientOutputDir, \"farm-client.js\"), shim);\n  return `/${entryName}`;\n}\n","import path from \"path\";\nimport type { APIRouteManager } from \"./api/route-manager\";\nimport { resolveFarmAPIServerBasePath, resolveFarmAPIServerRoutePath } from \"./api/server-path\";\nimport type { ResolvedFarmConfig } from \"./config\";\nimport { getFarmPresetRuntime, type FarmPresetRuntime } from \"./deployment\";\nimport {\n  getFarmRouteRuntimeConfig,\n  hasFarmRouteRuntimeControls,\n  mergeFarmRouteRuntimeConfigs,\n  normalizeFarmRouteRuntimeConfig,\n  resolveFarmRouteRuleRuntimeConfig,\n  resolveFarmRouteRuntimeConfig,\n  type FarmRouteRuntimeManifest,\n  type FarmRouteRuntimeManifestEntry,\n} from \"./route-runtime\";\nimport type { RouteManager } from \"./routing/route-manager\";\nimport { resolveRouteRenderingConfigFromFile } from \"./ssg\";\n\nexport const FARM_ROUTE_RUNTIME_MANIFEST = \"route-runtime-manifest.json\";\n\nexport interface FarmRouteRuntimeDeploymentValidation {\n  runtime: FarmPresetRuntime;\n  warnings: string[];\n}\n\nexport async function createFarmRouteRuntimeManifest(options: {\n  config: ResolvedFarmConfig;\n  routeManager: RouteManager;\n  apiRouteManager: APIRouteManager;\n  root?: string;\n}): Promise<FarmRouteRuntimeManifest> {\n  const root = path.resolve(options.root || options.config.root || process.cwd());\n  const routes: FarmRouteRuntimeManifestEntry[] = [];\n\n  for (const [pattern, entry] of options.routeManager.getRoutes()) {\n    const routeModule = await options.routeManager.loadRouteModule(entry.modulePath);\n    const rendering = await resolveRouteRenderingConfigFromFile(routeModule, entry.modulePath);\n    const runtimeConfig = await options.routeManager.resolveRouteRuntimeConfig(pattern);\n\n    routes.push({\n      kind: \"page\",\n      pattern,\n      rendering: rendering.ssg ? \"static\" : \"dynamic\",\n      source: normalizeManifestSource(root, entry.modulePath),\n      ...runtimeConfig,\n    });\n  }\n\n  for (const [pattern, route] of options.apiRouteManager.getRoutes()) {\n    const publicPattern = resolveFarmAPIServerRoutePath(\n      pattern,\n      resolveFarmAPIServerBasePath(options.config.api),\n    );\n    const inherited = resolveFarmRouteRuleRuntimeConfig(publicPattern, options.config.routeRules);\n    const own = normalizeFarmRouteRuntimeConfig(\n      getFarmRouteRuntimeConfig(route),\n      `API route \"${pattern}\"`,\n    );\n\n    routes.push({\n      kind: \"api\",\n      pattern: publicPattern,\n      rendering: \"dynamic\",\n      source: normalizeManifestSource(root, route.filePath),\n      ...resolveFarmRouteRuntimeConfig(\n        mergeFarmRouteRuntimeConfigs(inherited, own),\n        `API route \"${pattern}\"`,\n      ),\n    });\n  }\n\n  for (const entry of options.routeManager.getMetadataRoutes().values()) {\n    const routeModule = await options.routeManager.loadRouteModule(entry.modulePath);\n    const pattern =\n      entry.pattern === \"/\" ? `/${entry.outputName}` : `${entry.pattern}/${entry.outputName}`;\n    const inherited = resolveFarmRouteRuleRuntimeConfig(pattern, options.config.routeRules);\n    const own = normalizeFarmRouteRuntimeConfig(\n      getFarmRouteRuntimeConfig(routeModule),\n      `Metadata route \"${pattern}\"`,\n    );\n\n    routes.push({\n      kind: \"metadata\",\n      pattern,\n      rendering: \"dynamic\",\n      source: normalizeManifestSource(root, entry.modulePath),\n      ...resolveFarmRouteRuntimeConfig(\n        mergeFarmRouteRuntimeConfigs(inherited, own),\n        `Metadata route \"${pattern}\"`,\n      ),\n    });\n  }\n\n  for (const [pattern, rule] of Object.entries(options.config.routeRules)) {\n    if (!hasFarmRouteRuntimeControls(rule)) continue;\n\n    routes.push({\n      kind: \"rule\",\n      pattern,\n      rendering: rule.prerender || rule.render === \"static\" ? \"static\" : \"dynamic\",\n      ...resolveFarmRouteRuntimeConfig(rule, `Route rule \"${pattern}\"`),\n    });\n  }\n\n  return {\n    version: 1,\n    routes,\n  };\n}\n\nexport async function writeFarmRouteRuntimeManifest(\n  directory: string,\n  manifest: FarmRouteRuntimeManifest,\n): Promise<string> {\n  const fs = await import(\"fs/promises\");\n  const manifestPath = path.join(directory, FARM_ROUTE_RUNTIME_MANIFEST);\n  await fs.mkdir(directory, { recursive: true });\n  await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n  return manifestPath;\n}\n\nexport function validateFarmRouteRuntimeDeployment(\n  manifest: FarmRouteRuntimeManifest,\n  preset: string,\n): FarmRouteRuntimeDeploymentValidation {\n  const runtime = getFarmPresetRuntime(preset);\n  const warnings = new Set<string>();\n\n  for (const route of manifest.routes) {\n    if (route.rendering === \"static\") continue;\n\n    if (runtime === \"unknown\" && route.runtime !== \"auto\") {\n      warnings.add(\n        `Preset \"${preset}\" has an unknown runtime, so Farm could not verify routes that explicitly require node or edge.`,\n      );\n    }\n\n    if (runtime !== \"unknown\" && route.runtime !== \"auto\" && route.runtime !== runtime) {\n      throw new Error(\n        `Route \"${route.pattern}\" requires the ${route.runtime} runtime, but preset \"${preset}\" emits ${runtime} functions. Choose a compatible preset or change the route runtime.`,\n      );\n    }\n\n    if (route.regions?.length && preset !== \"vercel\" && preset !== \"vercel-edge\") {\n      warnings.add(\n        `Preset \"${preset}\" does not map per-route regions; Farm kept them in ${FARM_ROUTE_RUNTIME_MANIFEST} for deployment adapters.`,\n      );\n    }\n\n    if (route.maxDuration && preset !== \"vercel\") {\n      warnings.add(\n        `Preset \"${preset}\" does not map per-route maxDuration; Farm kept it in ${FARM_ROUTE_RUNTIME_MANIFEST} for deployment adapters.`,\n      );\n    }\n  }\n\n  return { runtime, warnings: Array.from(warnings) };\n}\n\nfunction normalizeManifestSource(root: string, modulePath: string): string {\n  const queryIndex = modulePath.indexOf(\"?\");\n  const filePath = queryIndex === -1 ? modulePath : modulePath.slice(0, queryIndex);\n  const query = queryIndex === -1 ? \"\" : modulePath.slice(queryIndex);\n  const relativePath = path.isAbsolute(filePath) ? path.relative(root, filePath) : filePath;\n  return `${relativePath.replace(/\\\\/g, \"/\")}${query}`;\n}\n","import path from \"path\";\nimport {\n  createFarmRouteRuntimeKey,\n  type FarmRouteRuntimeManifest,\n  type FarmRouteRuntimeManifestEntry,\n  type ResolvedFarmRouteRuntimeConfig,\n} from \"../route-runtime\";\n\nexport interface FarmVercelRuntimeRoute {\n  src: string;\n  dest: string;\n  headers?: Record<string, string>;\n}\n\ntype FileSystemPromises = typeof import(\"fs/promises\");\n\n/** Materialize one Node function per distinct region/duration policy. */\nexport async function createFarmVercelRouteRuntimeFunctions(\n  outputDir: string,\n  manifest: FarmRouteRuntimeManifest,\n  fs: FileSystemPromises,\n): Promise<FarmVercelRuntimeRoute[]> {\n  const dynamicRoutes = manifest.routes.filter(\n    (route) => route.rendering === \"dynamic\" && route.runtime !== \"edge\",\n  );\n  if (!dynamicRoutes.some(hasVercelFunctionControls)) return [];\n\n  const configuredRoutes = dynamicRoutes\n    .filter((route) => route.kind !== \"rule\" || hasVercelFunctionControls(route))\n    .sort(compareRuntimeRoutes);\n  if (configuredRoutes.length === 0) return [];\n\n  const groups = new Map<\n    string,\n    { config: ResolvedFarmRouteRuntimeConfig; routes: FarmRouteRuntimeManifestEntry[] }\n  >();\n\n  for (const route of configuredRoutes) {\n    const config = {\n      runtime: route.runtime === \"auto\" ? \"node\" : route.runtime,\n      regions: route.regions,\n      maxDuration: route.maxDuration,\n    } satisfies ResolvedFarmRouteRuntimeConfig;\n    const key = createFarmRouteRuntimeKey(config);\n    const group = groups.get(key) || { config, routes: [] };\n    group.routes.push(route);\n    groups.set(key, group);\n  }\n\n  const functionsDir = path.join(outputDir, \"functions\");\n  const baseFunctionDir = path.join(functionsDir, \"__nitro.func\");\n  const destinations = new Map<string, string>();\n  let groupIndex = 0;\n\n  for (const [key, group] of groups) {\n    if (!group.config.regions?.length && !group.config.maxDuration) {\n      destinations.set(key, \"/__nitro\");\n      continue;\n    }\n\n    groupIndex += 1;\n    const functionName = `__farm_runtime_${groupIndex}`;\n    const functionDir = path.join(functionsDir, `${functionName}.func`);\n    await fs.cp(baseFunctionDir, functionDir, { recursive: true, force: true });\n    await configureVercelFunction(functionDir, group.config, fs);\n    destinations.set(key, `/${functionName}`);\n  }\n\n  const routes: FarmVercelRuntimeRoute[] = [];\n  const seenSources = new Set<string>();\n  for (const route of configuredRoutes) {\n    const src = farmRoutePatternToVercelSource(route.pattern);\n    if (seenSources.has(src)) continue;\n    seenSources.add(src);\n    const key = createFarmRouteRuntimeKey({\n      runtime: route.runtime === \"auto\" ? \"node\" : route.runtime,\n      regions: route.regions,\n      maxDuration: route.maxDuration,\n    });\n    routes.push({\n      src,\n      dest: destinations.get(key) || \"/__nitro\",\n      ...(route.kind === \"api\" || route.pattern.startsWith(\"/api/\")\n        ? {\n            headers: {\n              \"Access-Control-Allow-Origin\": \"*\",\n              \"Access-Control-Allow-Methods\": \"*\",\n              \"Access-Control-Allow-Headers\": \"*\",\n            },\n          }\n        : {}),\n    });\n  }\n\n  return routes;\n}\n\nexport function farmRoutePatternToVercelSource(pattern: string): string {\n  const normalized = normalizePattern(pattern);\n  if (normalized === \"/\") return \"/\";\n\n  let source = \"\";\n  for (const segment of normalized.split(\"/\").filter(Boolean)) {\n    if (segment === \"**\" || /^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)) {\n      source += \"(?:/(.*))?\";\n    } else if (/^\\[\\.\\.\\..+\\]$/.test(segment)) {\n      source += \"/(.+)\";\n    } else if (segment === \"*\" || /^\\[.+\\]$/.test(segment)) {\n      source += \"/([^/]+)\";\n    } else {\n      source += `/${escapeRegExp(segment)}`;\n    }\n  }\n\n  return source || \"/\";\n}\n\nasync function configureVercelFunction(\n  functionDir: string,\n  config: ResolvedFarmRouteRuntimeConfig,\n  fs: FileSystemPromises,\n): Promise<void> {\n  const configPath = path.join(functionDir, \".vc-config.json\");\n  const current = JSON.parse(await fs.readFile(configPath, \"utf8\"));\n  const next = {\n    ...current,\n    ...(config.regions?.length ? { regions: config.regions } : {}),\n    ...(config.maxDuration ? { maxDuration: config.maxDuration } : {}),\n  };\n  await fs.writeFile(configPath, `${JSON.stringify(next, null, 2)}\\n`);\n}\n\nfunction hasVercelFunctionControls(route: FarmRouteRuntimeManifestEntry): boolean {\n  return Boolean(route.regions?.length || route.maxDuration);\n}\n\nfunction compareRuntimeRoutes(\n  left: FarmRouteRuntimeManifestEntry,\n  right: FarmRouteRuntimeManifestEntry,\n): number {\n  const kindOrder = { page: 0, api: 0, metadata: 0, rule: 1 };\n  const kindDifference = kindOrder[left.kind] - kindOrder[right.kind];\n  if (kindDifference !== 0) return kindDifference;\n\n  const specificityDifference =\n    getPatternSpecificity(right.pattern) - getPatternSpecificity(left.pattern);\n  return specificityDifference || left.pattern.localeCompare(right.pattern);\n}\n\nfunction getPatternSpecificity(pattern: string): number {\n  return normalizePattern(pattern)\n    .split(\"/\")\n    .filter(Boolean)\n    .reduce((score, segment) => {\n      if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n      if (segment === \"*\" || segment.startsWith(\"[...\")) return score + 10;\n      if (/^\\[.+\\]$/.test(segment)) return score + 50;\n      return score + 100;\n    }, 0);\n}\n\nfunction normalizePattern(value: string): string {\n  const trimmed = value.trim();\n  const withSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n  return withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","export const FARM_IMMUTABLE_ASSET_CACHE_CONTROL = \"public, max-age=31536000, immutable\" as const;\n\nexport interface FarmVercelImmutableAssetRoute {\n  src: string;\n  headers: { \"Cache-Control\": typeof FARM_IMMUTABLE_ASSET_CACHE_CONTROL };\n  continue: true;\n  caseSensitive: true;\n}\n\n/**\n * Apply immutable caching only to Farm/Vite filenames carrying Farm's `-h`\n * content-fingerprint marker. Stable entry filenames and HTML are deliberately\n * excluded because they can change between deployments. The fingerprinted\n * client entry lives at the public root — its relative chunk imports pin it\n * there — so root-level farm-client-h files qualify alongside assets/chunks.\n *\n * Hashed client assets are emitted and served at the root even when a\n * basePath is configured — the client build sets no Vite `base` and Nitro\n * mounts the client output at \"/\" — so the route matches root paths\n * unconditionally.\n */\nexport function createFarmVercelImmutableAssetRoute(): FarmVercelImmutableAssetRoute {\n  const fingerprint = \"-h(?:[a-fA-F0-9]{8}|[a-fA-F0-9]{12}|[a-fA-F0-9]{16})\";\n\n  return {\n    src: `^/(?:(?:assets|chunks)/(?:.+/)*[^/]+|farm-client)${fingerprint}\\\\.(?!(?:[hH][tT][mM][lL]?)$)[^/]+$`,\n    headers: {\n      \"Cache-Control\": FARM_IMMUTABLE_ASSET_CACHE_CONTROL,\n    },\n    continue: true,\n    caseSensitive: true,\n  };\n}\n\nexport function isFarmVercelImmutableAssetPath(pathname: string): boolean {\n  return new RegExp(createFarmVercelImmutableAssetRoute().src).test(pathname);\n}\n\nexport interface FarmVercelRoute {\n  handle?: string;\n  src?: string;\n  dest?: string;\n  status?: number;\n  headers?: Record<string, string>;\n  continue?: boolean;\n  caseSensitive?: boolean;\n}\n\n/**\n * Rebuild the Vercel Build Output `routes` array around Farm's serverless\n * function while preserving the preset-generated source routes.\n *\n * Nitro's Vercel builder emits, before the `filesystem` handler, the redirect\n * and header routes declared through `routeRules` (this is how Farm ships its\n * configured `headers()` and per-prerendered-route cache policy on Vercel), then\n * a blanket immutable public-asset route. Farm previously discarded the whole\n * array, which silently dropped those redirect and header routes on Vercel while\n * they kept working on every other target.\n *\n * We keep the redirect/header source routes, replace the preset's blanket\n * immutable asset route (`continue: true`) with Farm's fingerprint-precise one so\n * stable filenames and HTML are not over-cached, and re-point Farm's runtime,\n * API, and catch-all routes at the `__nitro` function this post-processing\n * creates. Routes after the `filesystem` handler (ISR invocations, observability,\n * the preset's own `/__fallback` catch-all) are intentionally not carried over:\n * Farm keeps ISR routes server-handled, and the preset's catch-all targets a\n * function name Farm does not emit.\n */\nexport function buildFarmVercelRoutes(options: {\n  presetRoutes: FarmVercelRoute[];\n  runtimeRoutes: FarmVercelRoute[];\n  apiBasePath: string;\n}): FarmVercelRoute[] {\n  const { presetRoutes, runtimeRoutes, apiBasePath } = options;\n  const filesystemIndex = presetRoutes.findIndex((route) => route.handle === \"filesystem\");\n  const sourceRoutes = filesystemIndex >= 0 ? presetRoutes.slice(0, filesystemIndex) : [];\n  // Drop the preset's blanket immutable public-asset routes (the only\n  // pre-filesystem routes marked `continue: true`); Farm supplies its own\n  // precise immutable route below. Everything else here is a redirect or header\n  // route from routeRules and must be preserved.\n  const preservedSourceRoutes = sourceRoutes.filter((route) => route.continue !== true);\n\n  return [\n    ...preservedSourceRoutes,\n    createFarmVercelImmutableAssetRoute(),\n    { handle: \"filesystem\" },\n    ...runtimeRoutes,\n    ...(apiBasePath === \"/\"\n      ? []\n      : [\n          {\n            src: `${apiBasePath}/(.*)`,\n            dest: \"/__nitro\",\n            headers: {\n              \"Access-Control-Allow-Origin\": \"*\",\n              \"Access-Control-Allow-Methods\": \"*\",\n              \"Access-Control-Allow-Headers\": \"*\",\n            },\n          },\n        ]),\n    {\n      src: \"/(.*)\",\n      dest: \"/__nitro\",\n    },\n  ];\n}\n","import type { ResolvedFarmServerConfig } from \"../server-http\";\n\nexport interface FarmNodeServerEntryOptions {\n  nitroEntryFile: string;\n  nodeHandlerModule: string;\n  server: ResolvedFarmServerConfig;\n  websocketAdapterModule: string;\n}\n\n/** Generate the long-running Node adapter entry while retaining Nitro's routing runtime. */\nexport function createFarmNodeServerEntry(options: FarmNodeServerEntryOptions): string {\n  const serverConfig = JSON.stringify(options.server);\n  const nitroEntryImport = `./${options.nitroEntryFile.replace(/^\\.\\//, \"\")}`;\n\n  return `\nimport \"#nitro-internal-pollyfills\";\nimport { Server as HttpServer } from \"node:http\";\nimport { Server as HttpsServer } from \"node:https\";\nimport wsAdapter from ${JSON.stringify(options.websocketAdapterModule)};\nimport { toNodeHandler } from ${JSON.stringify(options.nodeHandlerModule)};\nimport { useNitroApp, useRuntimeConfig } from \"nitro/runtime\";\nimport {\n  getGracefulShutdownConfig,\n  setupGracefulShutdown,\n  startScheduleRunner,\n  trapUnhandledNodeErrors,\n} from \"nitro/runtime/internal\";\nimport { farmProductionLifecycle } from ${JSON.stringify(nitroEntryImport)};\n\nconst farmServerConfig = ${serverConfig};\nif (!process.env.NITRO_SHUTDOWN_TIMEOUT) {\n  process.env.NITRO_SHUTDOWN_TIMEOUT = String(farmServerConfig.gracefulShutdownTimeout);\n}\nconst shutdownConfig = getGracefulShutdownConfig();\n\nconst nitroApp = useNitroApp();\nnitroApp.hooks.hook(\"close\", async () => {\n  try {\n    await farmProductionLifecycle.close(\"production-server-closed\");\n  } catch (error) {\n    process.exitCode = 1;\n    throw error;\n  }\n});\n\nlet startupSignal;\nlet resolveStartupSignal;\nconst startupSignalPromise = new Promise((resolve) => {\n  resolveStartupSignal = resolve;\n});\nconst startupSignalListeners = new Map();\nif (!shutdownConfig.disabled) {\n  for (const signal of shutdownConfig.signals) {\n    const listener = (receivedSignal) => {\n      if (!startupSignal) {\n        startupSignal = receivedSignal;\n        resolveStartupSignal(receivedSignal);\n      }\n      farmProductionLifecycle.beginDrain(receivedSignal);\n    };\n    startupSignalListeners.set(signal, listener);\n    process.once(signal, listener);\n  }\n}\n\ntry {\n  await Promise.race([\n    Promise.resolve().then(() => farmProductionLifecycle.start()),\n    startupSignalPromise,\n  ]);\n} catch (error) {\n  await farmProductionLifecycle.close(\"production-start-failed\").catch((closeError) => {\n    console.error(\"[Farm] Runtime cleanup after startup failure failed:\", closeError);\n  });\n  throw error;\n} finally {\n  for (const [signal, listener] of startupSignalListeners) {\n    process.removeListener(signal, listener);\n  }\n}\n\nif (startupSignal) {\n  let startupCloseTimer;\n  const startupCloseCompleted = await Promise.race([\n    Promise.resolve()\n      .then(() => farmProductionLifecycle.close(startupSignal))\n      .then(\n        () => true,\n        (error) => {\n          console.error(\"[Farm] Runtime shutdown during startup failed:\", error);\n          process.exitCode = 1;\n          return true;\n        },\n      ),\n    new Promise((resolve) => {\n      startupCloseTimer = setTimeout(() => resolve(false), farmServerConfig.gracefulShutdownTimeout);\n    }),\n  ]);\n  clearTimeout(startupCloseTimer);\n  if (!startupCloseCompleted) {\n    console.warn(\"[Farm] Runtime startup did not settle before shutdown; forcing cleanup\");\n    let forcedCloseTimer;\n    const forcedCloseCompleted = await Promise.race([\n      Promise.resolve()\n        .then(() => farmProductionLifecycle.forceClose(startupSignal))\n        .then(\n          () => true,\n          (error) => {\n            console.error(\"[Farm] Forced runtime shutdown during startup failed:\", error);\n            process.exitCode = 1;\n            return true;\n          },\n        ),\n      new Promise((resolve) => {\n        forcedCloseTimer = setTimeout(\n          () => resolve(false),\n          farmServerConfig.gracefulShutdownTimeout,\n        );\n      }),\n    ]);\n    clearTimeout(forcedCloseTimer);\n    if (!forcedCloseCompleted) {\n      console.error(\"[Farm] Forced runtime shutdown during startup timed out\");\n      process.exitCode = 1;\n    }\n  }\n  process.exit(process.exitCode || 0);\n}\n\nconst cert = process.env.NITRO_SSL_CERT;\nconst key = process.env.NITRO_SSL_KEY;\nconst server = cert && key\n  ? new HttpsServer({ key, cert }, toNodeHandler(nitroApp.fetch))\n  : new HttpServer(toNodeHandler(nitroApp.fetch));\n\nserver.headersTimeout = farmServerConfig.headersTimeout;\nserver.requestTimeout = farmServerConfig.requestTimeout;\nserver.keepAliveTimeout = farmServerConfig.keepAliveTimeout;\n\nif (!shutdownConfig.disabled) {\n  for (const signal of shutdownConfig.signals) {\n    process.once(signal, () => farmProductionLifecycle.beginDrain(signal));\n  }\n}\n\nconst configuredPort = Number(process.env.NITRO_PORT || process.env.PORT);\nconst port = Number.isFinite(configuredPort) && configuredPort > 0 ? configuredPort : 3000;\nconst host = process.env.NITRO_HOST || process.env.HOST;\nconst socketPath = process.env.NITRO_UNIX_SOCKET;\nconst listener = server.listen(socketPath ? { path: socketPath } : { port, host }, () => {\n  const protocol = cert && key ? \"https\" : \"http\";\n  const addressInfo = listener.address();\n  if (typeof addressInfo === \"string\") {\n    console.log(\\`Listening on unix socket \\${addressInfo}\\`);\n    return;\n  }\n  if (!addressInfo) return;\n  const configuredBaseURL = useRuntimeConfig().app.baseURL || \"\";\n  const baseURL = configuredBaseURL.endsWith(\"/\") ? configuredBaseURL.slice(0, -1) : configuredBaseURL;\n  const address = addressInfo.family === \"IPv6\" ? \\`[\\${addressInfo.address}]\\` : addressInfo.address;\n  console.log(\\`Listening on \\${protocol}://\\${address}:\\${addressInfo.port}\\${baseURL}\\`);\n});\n\nserver.once(\"error\", async (error) => {\n  console.error(error);\n  process.exitCode = 1;\n  await farmProductionLifecycle.close(\"production-listen-error\").catch((closeError) => {\n    console.error(\"[Farm] Runtime cleanup after listen failure failed:\", closeError);\n  });\n});\n\ntrapUnhandledNodeErrors();\nsetupGracefulShutdown(listener, nitroApp);\n\nif (import.meta._websocket) {\n  const { handleUpgrade } = wsAdapter(nitroApp.h3App.websocket);\n  server.on(\"upgrade\", handleUpgrade);\n}\nif (import.meta._tasks) {\n  startScheduleRunner();\n}\n\nexport default {};\n  `.trim();\n}\n","import type {\n  build as viteBuild,\n  createServer as createViteServer,\n  loadEnv as viteLoadEnv,\n} from \"vite\";\n\nexport type FarmProductionViteBuilder = \"rollup\" | \"rolldown\";\n\nexport interface FarmProductionViteRuntime {\n  build: typeof viteBuild;\n  createServer: typeof createViteServer;\n  loadEnv: typeof viteLoadEnv;\n  builder: FarmProductionViteBuilder;\n}\n\nexport function canUseRolldownForRouteDiscovery(viteConfig: object | undefined): boolean {\n  return !viteConfig || Object.keys(viteConfig).length === 0;\n}\n\nexport function supportsRolldownVite(nodeVersion = process.versions.node): boolean {\n  const [major = 0, minor = 0] = nodeVersion.split(\".\").map(Number);\n  return major > 22 || (major === 22 && minor >= 12);\n}\n\nfunction requestedProductionViteBuilder(): FarmProductionViteBuilder | undefined {\n  const requested = process.env.FARM_VITE_BUILDER?.trim().toLowerCase();\n  if (!requested) return undefined;\n  if (requested === \"rollup\" || requested === \"rolldown\") return requested;\n  throw new Error('FARM_VITE_BUILDER must be either \"rolldown\" or \"rollup\"');\n}\n\nasync function loadRollupVite(): Promise<FarmProductionViteRuntime> {\n  const runtime = await import(\"vite\");\n  return {\n    build: runtime.build,\n    createServer: runtime.createServer,\n    loadEnv: runtime.loadEnv,\n    builder: \"rollup\",\n  };\n}\n\n/**\n * Prefer Vite's Rolldown-powered production builder on supported Node releases.\n * Vite 5 remains the compatibility path for unsupported runtimes, --no-optional installs,\n * and projects that explicitly request Rollup.\n */\nexport async function loadFarmProductionVite(): Promise<FarmProductionViteRuntime> {\n  const requested = requestedProductionViteBuilder();\n  if (requested === \"rollup\" || !supportsRolldownVite()) {\n    if (requested === \"rolldown\") {\n      throw new Error(\"FARM_VITE_BUILDER=rolldown requires Node 22.12 or newer\");\n    }\n    return loadRollupVite();\n  }\n\n  try {\n    const runtime = (await import(\"vite-rolldown\")) as unknown as typeof import(\"vite\");\n    return {\n      build: runtime.build,\n      createServer: runtime.createServer,\n      loadEnv: runtime.loadEnv,\n      builder: \"rolldown\",\n    };\n  } catch (error) {\n    if (requested === \"rolldown\") {\n      const detail = error instanceof Error ? `: ${error.message}` : \"\";\n      throw new Error(\n        `FARM_VITE_BUILDER=rolldown was requested, but the optional Vite Rolldown runtime could not be loaded${detail}`,\n      );\n    }\n    return loadRollupVite();\n  }\n}\n","import type { FarmProductionViteBuilder } from \"./production-vite\";\n\ntype VitePluginLike = {\n  name?: string;\n  transform?: unknown;\n};\n\ntype VitePluginHook = (...args: any[]) => any;\n\n/**\n * Tailwind 4.1 supports Farm's Node baseline, but its Vite plugin resolves\n * against Farm's Vite 5 compatibility dependency. When that plugin runs in\n * Vite 8 it mistakes the active environment for its own Vite environment and\n * calls an API that Vite 5 does not export. Keep its documented Vite 5 hook\n * path while Farm uses the Rolldown production builder.\n */\nexport function adaptTailwindVitePlugin<T>(pluginOption: T, builder: FarmProductionViteBuilder): T {\n  if (builder !== \"rolldown\") return pluginOption;\n  return adaptPluginOption(pluginOption) as T;\n}\n\nfunction adaptPluginOption(pluginOption: unknown): unknown {\n  if (Array.isArray(pluginOption)) return pluginOption.map(adaptPluginOption);\n  if (!pluginOption || typeof pluginOption !== \"object\") return pluginOption;\n\n  const plugin = pluginOption as VitePluginLike;\n  if (!plugin.name?.startsWith(\"@tailwindcss/vite:generate:\")) return pluginOption;\n\n  if (isVitePluginHook(plugin.transform)) {\n    return {\n      ...plugin,\n      transform: withVite5TransformContext(plugin.transform),\n    };\n  }\n\n  if (\n    plugin.transform &&\n    typeof plugin.transform === \"object\" &&\n    \"handler\" in plugin.transform &&\n    isVitePluginHook(plugin.transform.handler)\n  ) {\n    return {\n      ...plugin,\n      transform: {\n        ...plugin.transform,\n        handler: withVite5TransformContext(plugin.transform.handler),\n      },\n    };\n  }\n\n  return pluginOption;\n}\n\nfunction isVitePluginHook(value: unknown): value is VitePluginHook {\n  return typeof value === \"function\";\n}\n\nfunction withVite5TransformContext<T extends (...args: any[]) => any>(handler: T): T {\n  return function (this: object, ...args: Parameters<T>): ReturnType<T> {\n    const context = new Proxy(this, {\n      get(target, property, receiver) {\n        if (property === \"environment\") return undefined;\n        return Reflect.get(target, property, receiver);\n      },\n    });\n    return handler.apply(context, args);\n  } as T;\n}\n","import { build } from \"esbuild\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmInstrumentationModule } from \"./instrumentation-runtime\";\n\nexport * from \"./instrumentation-runtime\";\n\nconst INSTRUMENTATION_EXTENSIONS = [\"ts\", \"mts\", \"js\", \"mjs\"] as const;\n\nexport function resolveFarmInstrumentationFile(root: string, srcDir = \"src\"): string | null {\n  const candidates = [\n    ...INSTRUMENTATION_EXTENSIONS.map((extension) =>\n      path.join(root, srcDir, `instrumentation.${extension}`),\n    ),\n    ...INSTRUMENTATION_EXTENSIONS.map((extension) =>\n      path.join(root, `instrumentation.${extension}`),\n    ),\n  ].filter((candidate) => fs.existsSync(candidate));\n\n  if (candidates.length > 1) {\n    throw new Error(\n      `Farm.js found multiple instrumentation files:\\n${candidates\n        .map((candidate) => `- ${path.relative(root, candidate)}`)\n        .join(\"\\n\")}\\nKeep only one instrumentation file in the project root or ${srcDir}/.`,\n    );\n  }\n\n  return candidates[0] ?? null;\n}\n\nexport async function loadFarmInstrumentation(\n  filePath: string | null,\n  root: string,\n): Promise<FarmInstrumentationModule | null> {\n  if (!filePath) return null;\n\n  const outputDirectory = path.join(root, \".farm\", \".instrumentation-loader\");\n  const outputFile = path.join(outputDirectory, \"instrumentation.mjs\");\n  await fs.promises.mkdir(outputDirectory, { recursive: true });\n  await build({\n    entryPoints: [filePath],\n    outfile: outputFile,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: \"node20\",\n    packages: \"external\",\n    sourcemap: \"inline\",\n  });\n\n  const url = pathToFileURL(outputFile);\n  url.searchParams.set(\"t\", String(Date.now()));\n  return (await import(url.href)) as FarmInstrumentationModule;\n}\n","const productionNodeEnvStateKey = Symbol.for(\"@farm.js/core/production-node-env-state\");\n\ninterface ProductionNodeEnvState {\n  depth: number;\n  original: string | undefined;\n}\n\nfunction getProductionNodeEnvState(): ProductionNodeEnvState | undefined {\n  return Reflect.get(globalThis, productionNodeEnvStateKey) as ProductionNodeEnvState | undefined;\n}\n\n/**\n * Keep overlapping production operations on the production condition.\n *\n * The state lives on `globalThis` so independently loaded CJS/ESM copies of\n * Farm share one refcount. The first entrant captures the caller's value and\n * only the last operation to settle restores it.\n *\n * @internal\n */\nexport async function withProductionNodeEnv<T>(operation: () => T | PromiseLike<T>): Promise<T> {\n  let state = getProductionNodeEnvState();\n\n  if (state) {\n    state.depth += 1;\n  } else {\n    state = {\n      depth: 1,\n      original: process.env.NODE_ENV,\n    };\n    Reflect.set(globalThis, productionNodeEnvStateKey, state);\n  }\n\n  process.env.NODE_ENV = \"production\";\n\n  try {\n    return await operation();\n  } finally {\n    state.depth -= 1;\n\n    if (state.depth > 0) {\n      // A nested operation may have changed NODE_ENV. Keep the remaining\n      // production scopes pinned until the final scope settles.\n      process.env.NODE_ENV = \"production\";\n    } else {\n      Reflect.deleteProperty(globalThis, productionNodeEnvStateKey);\n      if (state.original === undefined) {\n        delete process.env.NODE_ENV;\n      } else {\n        process.env.NODE_ENV = state.original;\n      }\n    }\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 while offline pauses and rides the next\n            // reconnect instead of surfacing a connectivity error.\n            if (\n              currentOptions.networkMode === \"online\" &&\n              !isNavigatorOnline() &&\n              requestId >= lastResetIdRef.current\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\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","\"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","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};\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  if (engine.disabled) return;\n  const sets = Array.from(engine.pendingSets.entries());\n  const deletes = Array.from(engine.pendingDeletes);\n  engine.pendingSets.clear();\n  engine.pendingDeletes.clear();\n\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  }\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  };\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  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.clearing = true;\n  try {\n    engine.cache.clear();\n  } finally {\n    engine.clearing = false;\n  }\n  engine.pendingSets.clear();\n  engine.pendingDeletes.clear();\n  try {\n    await engine.adapter.clear();\n  } catch (error) {\n    disableEngine(engine, error);\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 {\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  initPersistedClientCache,\n  storageClientCacheAdapter,\n} from \"./client-cache-persistence\";\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 { 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","\"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 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 = new URL(href, window.location.origin);\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 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\nconst translate = (key: string, values?: Record<string, unknown>, rich = false): unknown => {\n  const snapshot = requireSnapshot();\n  const message = 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) => requireSnapshot().messages[key] ?? key;\nt.has = (key: string) => key in requireSnapshot().messages;\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","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","\"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 } from \"./navigation-url\";\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?: {\n    title?: string;\n    description?: string;\n  };\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    // Parse the URL\n    const url = new URL(href, window.location.origin);\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 = new URL(href, window.location.origin);\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 = new URL(\n      options.pageData.canonicalPath || options.fullPath,\n      window.location.origin,\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    this.currentHistoryPath =\n      new URL(historyPath, window.location.origin).pathname +\n      new URL(historyPath, window.location.origin).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      this.restoreScrollPosition(this.currentHistoryPath ?? options.fullPath);\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\n    this.cache.set(cacheKey, {\n      data,\n      timestamp: Date.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 and\n      // takes precedence over saved-position restoration, matching forward\n      // navigation and native browser back/forward. Saved positions are keyed\n      // without the hash, so restoreScrollPosition would not cover it.\n      if (window.location.hash) {\n        getHashTargetElement(window.location.hash)?.scrollIntoView();\n      } else if (this.options.scrollRestoration) {\n        this.restoreScrollPosition(window.location.pathname + window.location.search);\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    document.title = metadata?.title || \"Farm.js App\";\n\n    let description = document.querySelector('meta[name=\"description\"]');\n    if (!metadata?.description) {\n      description?.remove();\n      return;\n    }\n\n    if (!description) {\n      description = document.createElement(\"meta\");\n      description.setAttribute(\"name\", \"description\");\n      document.head.appendChild(description);\n    }\n    description.setAttribute(\"content\", metadata.description);\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 ? new URL(href, window.location.origin).toString() : 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 scroll position for a path\n   */\n  private restoreScrollPosition(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      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","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 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","export function isFarmExternalNavigationURL(url: URL, currentOrigin: string): boolean {\n  return (url.protocol !== \"http:\" && url.protocol !== \"https:\") || url.origin !== currentOrigin;\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 true;\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 true;\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}\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: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\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: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n}\n\n.farm-runtime-error__inline-code {\n  color: var(--farm-error-source-marker);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\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    margin-top: 10px;\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","\"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 = () => {\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    clientWindow.addEventListener(\"pagehide\", this.handlePageHide, {\n      once: true,\n    });\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","import { useRouter as useFarmRouter } from \"./client/router\";\nimport { getRouter as getFarmSPARouter } from \"./client/spa-router\";\nimport { applyFarmBasePath } from \"./base-path\";\n\nexport {\n  getFarmRedirectError,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n  notFound,\n  permanentRedirect,\n  redirect,\n} from \"./navigation-errors\";\nexport type { FarmRedirectSignal, FarmRedirectStatus } from \"./navigation-errors\";\n\nexport function useRouter() {\n  const router = useFarmRouter();\n  return {\n    push: router.push,\n    replace: router.replace,\n    back: router.back,\n    forward: router.forward,\n    refresh() {\n      if (typeof window === \"undefined\") return Promise.resolve();\n      return getFarmSPARouter().refresh();\n    },\n    prefetch(href: string) {\n      if (typeof window === \"undefined\") return Promise.resolve();\n      return getFarmSPARouter().prefetch(applyFarmBasePath(href));\n    },\n  };\n}\n\nexport function usePathname(): string {\n  return useFarmRouter().pathname;\n}\n\nexport function useSearchParams(): URLSearchParams {\n  return useFarmRouter().searchParams;\n}\n","import { getCurrentRequest } from \"./server/request\";\n\nexport interface RequestCookie {\n  name: string;\n  value: string;\n}\n\nexport interface ReadonlyHeaders extends Iterable<[string, string]> {\n  get(name: string): string | null;\n  has(name: string): boolean;\n  forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void;\n  entries(): IterableIterator<[string, string]>;\n  keys(): IterableIterator<string>;\n  values(): IterableIterator<string>;\n}\n\nexport interface ReadonlyRequestCookies extends Iterable<RequestCookie> {\n  get(name: string): RequestCookie | undefined;\n  getAll(name?: string): RequestCookie[];\n  has(name: string): boolean;\n  toString(): string;\n}\n\nexport function headers(): ReadonlyHeaders {\n  return new Headers(getCurrentRequest().headers) as ReadonlyHeaders;\n}\n\nexport function cookies(): ReadonlyRequestCookies {\n  const cookieHeader = getCurrentRequest().headers.get(\"cookie\") || \"\";\n  const parsed = parseCookieHeader(cookieHeader);\n\n  return {\n    get(name) {\n      return parsed.find((cookie) => cookie.name === name);\n    },\n    getAll(name) {\n      return name ? parsed.filter((cookie) => cookie.name === name) : [...parsed];\n    },\n    has(name) {\n      return parsed.some((cookie) => cookie.name === name);\n    },\n    toString() {\n      return cookieHeader;\n    },\n    [Symbol.iterator]() {\n      return parsed[Symbol.iterator]();\n    },\n  };\n}\n\nfunction parseCookieHeader(header: string): RequestCookie[] {\n  if (!header.trim()) return [];\n\n  return header\n    .split(\";\")\n    .map((part) => part.trim())\n    .filter(Boolean)\n    .map((part) => {\n      const separatorIndex = part.indexOf(\"=\");\n      if (separatorIndex === -1) {\n        return {\n          name: decodeCookiePart(part),\n          value: \"\",\n        };\n      }\n\n      return {\n        name: decodeCookiePart(part.slice(0, separatorIndex).trim()),\n        value: decodeCookiePart(part.slice(separatorIndex + 1).trim()),\n      };\n    })\n    .filter((cookie) => cookie.name.length > 0);\n}\n\nfunction decodeCookiePart(value: string) {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return value;\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEO,SAAS,4BACd,UAC0B;AAC1B,SAAO;AAAA,IACL,WAAW;AAAA,MACT,MAAM,UAAU,cAAc,WAAW,QAAQ,8BAA8B,UAAU;AAAA,MACzF,KAAK,UAAU,cAAc,WAAW,OAAO,8BAA8B,UAAU;AA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C5E;AAAA,IACA,IAAIA,OAAM;AACR,aAAO,OAAO,KAAK,CAAC,WAAW,OAAO,SAASA,KAAI;AAAA,IACrD;AAAA,IACA,WAAW;AACT,aAAO;AAAA,IACT;AAAA,IACA,CAAC,OAAO,QAAQ,IAAI;AAClB,aAAO,OAAO,OAAO,QAAQ,EAAE;AAAA,IACjC;AAAA,EACF;AACF;AArBgB;AAuBhB,SAAS,kBAAkB,QAAiC;AAC1D,MAAI,CAAC,OAAO,KAAK,EAAG,QAAO,CAAC;AAE5B,SAAO,OACJ,MAAM,GAAG,EACT,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EACzB,OAAO,OAAO,EACd,IAAI,CAAC,SAAS;AACb,UAAM,iBAAiB,KAAK,QAAQ,GAAG;AACvC,QAAI,mBAAmB,IAAI;AACzB,aAAO;AAAA,QACL,MAAM,iBAAiB,IAAI;AAAA,QAC3B,OAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO;AAAA,MACL,MAAM,iBAAiB,KAAK,MAAM,GAAG,cAAc,EAAE,KAAK,CAAC;AAAA,MAC3D,OAAO,iBAAiB,KAAK,MAAM,iBAAiB,CAAC,EAAE,KAAK,CAAC;AAAA,IAC/D;AAAA,EACF,CAAC,EACA,OAAO,CAAC,WAAW,OAAO,KAAK,SAAS,CAAC;AAC9C;AAtBS;AAwBT,SAAS,iBAAiB,OAAe;AACvC,MAAI;AACF,WAAO,mBAAmB,KAAK;AAAA,EACjC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AANS;","names":["path","name","path","relativePath","fs","memoryDriver","storage","name","module","resolveDriver","base","operation","api","path","route","globalState","listeners","resolve","cookies","headers","path","resolve","path","globalState","endpoint","route","name","api","operation","context","env","middleware","response","text","resolveStorageRuntimeClient","createIntegrationOrm","headers","route","headers","name","text","name","module","route","secretError","context","fs","path","isAbsolutePath","normalizePath","pathToFileURL","build","resolvePath","relativeFilePath","pathSeparator","text","import_node_path","name","fs","path","safeFileName","name","route","redirect","headers","headers","throwIfAborted","context","globalState","path","name","path","name","build","import_node_module","import_node_path","import_node_url","escapeRegExp","name","loadModule","route","page","import_promises","name","storage","name","resolve","now","context","PROGRAMMATIC_ROUTE_FILE_NAMES","api","createProgrammaticRouteModuleId","getProgrammaticRouteSearchClientOptions","isProgrammaticRoutesFileName","parseProgrammaticRouteModuleId","parseProgrammaticRoutePath","redirect","scanProgrammaticPagePaths","path","route","createElement","FarmProgrammaticPageContent","FarmProgrammaticPage","context","name","action","getProgrammaticRouteManifest","import_path","createElement","path","headers","import_promises","import_path","fs","path","name","route","layout","estimatedBoundaryCount","import_fs","import_path","import_url","path","import_promises","import_node_path","name","import_path","layout","path","createRouteModuleFromProgrammaticPage","module","createLayoutModuleFromProgrammaticLayout","route","page","context","storage","headers","import_node_async_hooks","path","fs","import_node_fs","import_node_path","context","initialTagCount","icon","name","context","headers","output","resolve","headers","path","name","path","name","import_node_path","isPlainObject","name","import_promises","headers","redirect","readCookie","locale","name","IntlMessageFormat","getRequestStore","import_node_async_hooks","init_server","path","relative","name","import_node_crypto","import_node_fs","import_promises","import_node_path","import_node_module","import_node_url","context","bytes","createElement","headers","isResponse","isRecord","resolveCacheControl","toArray","getFarmGlobalState","normalizeCookiePath","init_config","init_config","init_bridge","readCookie","name","init_server","init_bridge","init_config","relative","relativePath","fs","path","import_node_url","context","init_server","React","reactRenderToString","reactRenderToPipeableStream","page","name","serializeInlineValue","escapeHtmlAttribute","toMiddlewareMap","fs","path","import_node_url","init_renderer","init_server","capabilities","renderToPipeableStream","resolve","layout","headers","route","redirect","relativePath","html","normalizeBasePath","path","route","import_node_module","import_node_path","import_node_url","name","context","url","path","route","name","init_config","import_path","init_renderer","init_server","init_config","path","env","isRecord","path","fs","import_node_fs","import_node_path","path","fs","import_node_fs","import_node_path","headers","path","middleware","endpoint","betterCallEndpoint","context","result","path","endpoint","route","route","path","init_config","normalizePathname","route","init_route_pattern","route","endpoint","response","searchParamsToObject","headers","isWebResponse","text","init_runtime","init_config","init_route_pattern","fs","path","init_route_manager","init_server","init_runtime","route","relativePath","endpoint","getProgrammaticRouteManifest","decodeCookieValue","cookies","name","name","createContext","headers","cookies","applyResponseHeaders","context","module","picocolors","fs","path","middleware","module","createContext","result","match","name","import_node_fs","import_fs","import_path","route","relativePath","exports","path","name","route","path","fs","DEFAULT_OUT_FILE","CONFIG_FILENAMES","relativePath","fs","path","path","import_node_fs","import_node_path","findConfigPath","toTypeImportPath","registries","CONFIG_FILENAMES","relativePath","fs","path","name","import_node_fs","import_node_path","init_type_generator","name","import_fs","import_path","init_type_generator","applyReplacements","context","isAstNode","walkAst","readPropertyName","name","isFunctionNode","MODULE_EXTENSION_RE","storage","reportError","resolve","context","import_node_async_hooks","import_node_async_hooks","fs","path","import_promises","import_node_path","import_image_size","layout","throwIfAborted","name","resolve","headers","path","import_node_path","path","import_node_crypto","import_node_fs","import_node_path","init_config","path","import_node_path","context","path","relativePath","import_node_fs","import_node_path","path","import_node_fs","import_node_module","import_node_path","page","escapeXml","name","route","import_node_crypto","trimSlashes","normalizeEntry","path","escapeAttribute","escapeHtml","relative","DOCS_FILE_EXTENSIONS","titleFromMarkdown","page","text","body","icon","renderedSections","headers","import_node_fs","import_node_path","path","import_promises","import_node_module","import_node_path","import_node_url","path","env","route","existsSync","isRecord","fs","pathToFileURL","build","relativePath","redirect","headers","api","import_path","init_config","isRecord","isResolvedDocsConfig","headers","getDocsTitle","getDocsDescription","getLoadedDocsPages","context","page","toDocsSitemapPage","toDocsLlmsPage","getDocsLlmsOptions","getDocsDiscoveryOptions","buildFarmingDocsDiagnostics","import_docs","init_config","route","path","operation","fs","init_manager","normalizePath","route","storage","env","middleware","path","import_node_path","init_config","name","escapeHtml","escapeAttribute","route","throwIfAborted","pipeline","Readable","headers","name","resolve","address","defineConfig","publicEnv","headers","middleware","name","isHtmlResponse","env","declaration","relative","context","createNodeImageFetcher","createNodeImageUrlValidator","createSharpImageTransformer","isStaticMetadataImageFile","route","createFarmWorkflowRequestHandler","discoverFarmWorkflows","OpenAPIManager","layout","React","now","handler","createFarmDevtoolsSnapshot","renderFarmDevtoolsHtml","pathname","startTime","duration","method","urlPath","routeManager","parseRouteModuleProps","options","page","renderToString","server","parseRouteModuleSchema","resolveFarmLayers","os","fs","path","import_node_url","init_vite","init_route_manager","init_config","init_runtime","init_server","init_vite","context","createContext","route","after","promises","definePlugin","path","mkdir","routePaths","clientManifestPath","readFile","import_path","build","createContext","createProgrammaticRouteModuleId","getRouter","getTheme","isProgrammaticRoutesFileName","isWebResponse","parseProgrammaticRouteModuleId","parseProgrammaticRoutePath","scanProgrammaticPagePaths","import_react","init_config","module","redirect","context","headers","context","env","context","import_node_stream","headers","context","context","init_route_manager","init_config","headers","resolve","reportError","INTEGRATION_RUNTIME_REGISTRY_KEY","CURRENT_REQUEST_RESOLVER_KEY","INTEGRATION_REQUEST_DISPATCHER_KEY","isOperation","getIntegrationRuntimeRegistry","globalState","INTEGRATION_RUNTIME_REGISTRY_KEY","CURRENT_REQUEST_RESOLVER_KEY","INTEGRATION_REQUEST_DISPATCHER_KEY","INTEGRATION_DATA_HEADER","INTEGRATION_DATA_HEADER_MAX_LENGTH","BLOCKED_INTEGRATION_DATA_KEYS","isPlainIntegrationDataObject","getIntegrationDataHeaderByteLength","headers","api","operation","dispatchIntegrationRequest","body","createClientSafeIntegrationAPI","isOperation","now","listeners","init_config","init_route_pattern","route","path","segment","dynamic","api","path","headers","name","now","nextEntry","result","createResponseError","delay","invalidate","route","init_config","init_route_manager","init_runtime","endpoint","route","fs","path","relativePath","getProgrammaticRouteManifest","duration","headers","init_manager","import_react","import_jsx_runtime","React","import_jsx_runtime","parse","now","next","window","storage","name","path","middleware","serializeCookie","name","headers","isMiddlewareResponse","matchPattern","match","matchRoutePath","result","import_node_fs","import_node_path","path","fs","module","normalizePathname","encodePathSegment","value","route","path","decodePathSegment","createSearchParams","init_config","api","middleware","isFormData","formDataToObject","context","result","isPromiseLike","import_react","delay","resolve","isFormData","context","import_react","init_config","import_path","import_node_fs","init_route_manager","init_config","import_path","fs","createHash","name","path","import_path","import_fs","import_url","import_module","import_path","path","route","fs","relativePath","import_path","fs","route","path","escapeRegExp","route","context","import_node_fs","import_node_path","import_node_url","path","fs","path","clone","trimSlashes","fs","route","layout","farmPlugin","PluginManager","metadata","relativePath","page","os","redirect","OpenAPIManager","renderOpenAPIReferenceHTML","name","headers","fsConstants","operation","build","buildClient","path","farmI18nClientBridgePlugin","farmPlugin","PluginManager","createNitroConfig","mkdir","fs","readFile","import_react","resolve","import_react","isFormData","context","isUnsafeFormKey","formDataToObject","storage","now","import_react","getState","replaceState","name","import_react","init_bridge","getTheme","getTheme","import_react","import_intl_messageformat","IntlMessageFormat","t","import_jsx_runtime","prefetch","route","import_react","shouldBlockUnload","path","context","getRouter","path","context","route","pushState","getRouter","replaceState","now","storage","getStorage","context","path","text","name","createSourceFrame","document","resolve","name","name"]}