{"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/schema.ts","../src/schema-capabilities.ts","../src/schema-reference.ts","../src/schema-primary-key.ts","../src/schema-resolve.ts","../src/schema-sql.ts","../src/schema-migrate.ts","../src/schema-extend.ts","../src/schema-state.ts","../src/schema-steps.ts","../src/schema-foreign-keys.ts","../src/schema-owner.ts","../src/schema-tables.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/secret-compare.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/route-rendering.ts","../src/ssg.ts","../src/route-call-scanner.ts","../src/routes-shared.ts","../src/i18n/bridge.ts","../src/cache-invalidation-stream.ts","../src/cache.ts","../src/route-context.ts","../src/routes.ts","../src/routes.server.ts","../src/app-markdown-runtime.ts","../src/app-markdown.ts","../src/utils/file-module.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-json-ld.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/i18n/alternates.ts","../src/navigation/late-navigation-recovery.ts","../src/font-vite.ts","../src/response-body.ts","../src/metadata-image.ts","../src/llms-txt.ts","../src/metadata-route.ts","../src/agent-crawlers.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/integration-provider-build.ts","../src/server/error-diagnostics.ts","../src/security.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/api/config.ts","../src/app.ts","../src/env.ts","../src/plugin-dependencies.ts","../src/schema-step-types.ts","../src/plugin-options.ts","../src/plugin-runtime-endpoint.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/server-path.ts","../src/api/route-schema.ts","../src/api/route-shape.ts","../src/api/route-pattern.ts","../src/api/runtime.ts","../src/api/plugin-route-runtime.ts","../src/api/route-files.ts","../src/api/route-manager.ts","../src/request-cookies.ts","../src/middleware/cookie-header.ts","../src/middleware/context.ts","../src/middleware/module.ts","../src/cli-colors.ts","../src/middleware/path.ts","../src/middleware/matcher.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/schema-model-types.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-pattern.ts","../src/image-server.ts","../src/server/vite-config.ts","../src/docs/adapter-client.ts","../src/docs/fonts.ts","../src/theme/vite.ts","../src/navigation/page-data-error.ts","../src/plugins/rewrites.ts","../src/deployment-environment.ts","../src/preview-noindex.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/mcp-config.ts","../src/agent-config.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/scalar-assets.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/schema-dependencies.ts","../src/provider.tsx","../src/schema-rename.ts","../src/schema-check.ts","../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/client-retry.ts","../src/api/vite-plugin.ts","../src/openapi/index.ts","../src/openapi/scalar-component.tsx","../src/openapi/docs-route.tsx","../src/query/values.ts","../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/routing/matcher.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/docs/compiler.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/instrumentation-runtime.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/cache-invalidation-event-source.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/client/navigation-url.ts","../src/i18n/client-state.ts","../src/client/router.ts","../src/client/spa-router.ts","../src/client/history-sync.ts","../src/client/hash-target.ts","../src/client/metadata-reconciler.ts","../src/client/chunk-recovery.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\";\nimport type { FarmPresetRuntime } from \"./deployment\";\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 type FarmRendererRuntime = Exclude<FarmPresetRuntime, \"unknown\">;\n\nexport interface FarmRendererStreamingPrimitives {\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 FarmRendererStreamingCapabilities extends FarmRendererStreamingPrimitives {\n  /**\n   * Overrides the default stream primitives for a deployment runtime.\n   *\n   * The top-level values remain the fallback for development and unknown\n   * presets. Runtime overrides let a renderer describe packages whose exports\n   * change with bundler conditions, such as React DOM's Node and edge builds.\n   */\n  runtimes?: Partial<Record<FarmRendererRuntime, FarmRendererStreamingPrimitives>>;\n}\n\nexport interface FarmRendererCapabilities {\n  streaming: FarmRendererStreamingCapabilities;\n  /**\n   * Whether re-rendering an existing root diffs the new tree against the live\n   * DOM instead of rebuilding it.\n   *\n   * Virtual-DOM renderers (React, Preact, Vue) compare the incoming tree with\n   * what is mounted, so a client navigation that re-renders a shared layout\n   * keeps the matching DOM nodes, their focus, and their component state.\n   *\n   * Compile-time fine-grained renderers (Solid, Svelte) have no virtual DOM to\n   * diff against. Their updates flow through bindings created when elements\n   * were constructed, so handing them a freshly materialized tree replaces the\n   * nodes. That is a property of those runtimes, not a gap in their adapters,\n   * and callers that need state to survive a re-render must keep it in a root\n   * they do not re-render rather than expect reconciliation here.\n   */\n  reconcilesRerenders: boolean;\n  /**\n   * Whether this renderer can render a plain function component: one that\n   * takes props and returns an element tree, rather than a component built by\n   * the renderer's own compiler.\n   *\n   * React-shaped renderers do this natively. A compile-time renderer needs its\n   * adapter to recognize such a component and call it, because its own\n   * components are functions too and the two are otherwise indistinguishable.\n   * Farm uses this to decide whether integration provider components can be\n   * rendered at all, so it defaults to false and each adapter opts in once it\n   * handles them.\n   */\n  functionComponents: boolean;\n}\n\nexport interface FarmRendererCapabilitiesInput {\n  streaming?: Partial<FarmRendererStreamingPrimitives> & {\n    runtimes?: Partial<Record<FarmRendererRuntime, Partial<FarmRendererStreamingPrimitives>>>;\n  };\n  reconcilesRerenders?: boolean;\n  functionComponents?: boolean;\n}\n\n/** A client layout participating in a renderer-owned route update. */\nexport interface FarmRendererRouteLayout {\n  /** Stable route pattern used to decide whether the mounted layout chain changed. */\n  pattern: string;\n  /** Renderer-native layout component. */\n  Component: unknown;\n}\n\n/**\n * Renderer-neutral route state supplied during hydration and client navigation.\n *\n * Virtual-DOM renderers can ignore this and keep rendering `element`. A\n * fine-grained renderer can implement `renderRoute()` and keep the matching\n * layout chain mounted while it updates the page slot and route params through\n * its native reactive primitives.\n */\nexport interface FarmRendererRouteState {\n  /** Fully composed fallback tree for renderers that only implement render(). */\n  element: unknown;\n  /** Applicable layouts in outermost-to-innermost order. */\n  layouts: readonly FarmRendererRouteLayout[];\n  /** Page boundary or page element placed in the innermost layout slot. */\n  page: unknown;\n  /** Current dynamic route params. */\n  params: Readonly<Record<string, string>>;\n  /** Framework wrappers, such as integration providers, applied outside layouts. */\n  wrap?: (element: unknown) => unknown;\n}\n\n/** Browser root contract implemented by renderer client adapters. */\nexport interface FarmRendererClientRoot {\n  render(element: unknown): void;\n  /** Optional renderer-native route update that preserves matching layouts. */\n  renderRoute?(state: FarmRendererRouteState): void;\n  unmount(): void;\n}\n\n/** Browser entry exported by a renderer client module. */\nexport interface FarmRendererClientRuntime {\n  createRoot(container: Element): FarmRendererClientRoot;\n  /**\n   * Non-React renderers receive route state as the optional third argument so\n   * a renderer-owned root can establish its native reactive route bindings\n   * during initial hydration.\n   */\n  hydrateRoot(\n    container: Element,\n    element: unknown,\n    routeState?: FarmRendererRouteState,\n  ): FarmRendererClientRoot;\n}\n\nconst DEFAULT_RENDERER_CAPABILITIES: Readonly<FarmRendererCapabilities> = Object.freeze({\n  streaming: Object.freeze({ node: false, web: false }),\n  // Conservative default: assume a re-render rebuilds until a renderer states\n  // otherwise, so callers do not silently rely on reconciliation.\n  reconcilesRerenders: false,\n  functionComponents: false,\n});\n\nexport function getFarmRendererCapabilities(\n  renderer?: Pick<FarmRenderer, \"capabilities\">,\n): FarmRendererCapabilities {\n  const defaultStreaming = {\n    node: renderer?.capabilities?.streaming?.node ?? DEFAULT_RENDERER_CAPABILITIES.streaming.node,\n    web: renderer?.capabilities?.streaming?.web ?? DEFAULT_RENDERER_CAPABILITIES.streaming.web,\n  };\n  const runtimes = Object.fromEntries(\n    ([\"node\", \"edge\"] as const).flatMap((runtime) => {\n      const override = renderer?.capabilities?.streaming?.runtimes?.[runtime];\n      if (!override) return [];\n      return [\n        [\n          runtime,\n          {\n            node: override.node ?? defaultStreaming.node,\n            web: override.web ?? defaultStreaming.web,\n          },\n        ],\n      ];\n    }),\n  ) as Partial<Record<FarmRendererRuntime, FarmRendererStreamingPrimitives>>;\n\n  return {\n    streaming: {\n      ...defaultStreaming,\n      ...(Object.keys(runtimes).length > 0 ? { runtimes } : {}),\n    },\n    reconcilesRerenders:\n      renderer?.capabilities?.reconcilesRerenders ??\n      DEFAULT_RENDERER_CAPABILITIES.reconcilesRerenders,\n    functionComponents:\n      renderer?.capabilities?.functionComponents ??\n      DEFAULT_RENDERER_CAPABILITIES.functionComponents,\n  };\n}\n\nexport function getFarmRendererStreamingCapabilitiesForRuntime(\n  renderer: Pick<FarmRenderer, \"capabilities\"> | undefined,\n  runtime: FarmRendererRuntime | \"unknown\",\n): FarmRendererStreamingPrimitives {\n  const streaming = getFarmRendererCapabilities(renderer).streaming;\n  if (runtime === \"unknown\") return { node: streaming.node, web: streaming.web };\n  return streaming.runtimes?.[runtime] ?? { node: streaming.node, web: streaming.web };\n}\n\nexport function assertFarmRendererStreamingRuntime(\n  name: string,\n  renderer: Pick<FarmRenderer, \"capabilities\"> | undefined,\n  runtimeModule: Pick<\n    Partial<FarmServerRendererRuntime>,\n    \"capabilities\" | \"renderToPipeableStream\" | \"renderToReadableStream\"\n  >,\n  runtime: FarmRendererRuntime | \"unknown\",\n): FarmRendererStreamingPrimitives {\n  const declared = getFarmRendererStreamingCapabilitiesForRuntime(renderer, runtime);\n  const runtimeDeclaration = runtimeModule.capabilities?.streaming;\n\n  if (runtimeDeclaration) {\n    const advertised = getFarmRendererStreamingCapabilitiesForRuntime(\n      { capabilities: { streaming: runtimeDeclaration } },\n      runtime,\n    );\n    if ((declared.node && !advertised.node) || (declared.web && !advertised.web)) {\n      throw new Error(\n        `Renderer \\`${name}\\` server module advertises ${JSON.stringify(advertised)} streaming for the ${runtime} runtime, which does not satisfy its descriptor ${JSON.stringify(declared)}.`,\n      );\n    }\n  }\n\n  if (declared.node && typeof runtimeModule.renderToPipeableStream !== \"function\") {\n    throw new Error(\n      `Renderer \\`${name}\\` advertises Node streaming for the ${runtime} runtime but its server module does not export renderToPipeableStream().`,\n    );\n  }\n  if (declared.web && typeof runtimeModule.renderToReadableStream !== \"function\") {\n    throw new Error(\n      `Renderer \\`${name}\\` advertises Web streaming for the ${runtime} runtime but its server module does not export renderToReadableStream().`,\n    );\n  }\n\n  return declared;\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  /** Lets a server-only page under a route-owned client tree render its own isolated islands. */\n  isolateServerPageGraph?(element: unknown): unknown;\n  /**\n   * Optional: tag a plain function component so a renderer that compiles its\n   * own components can tell the two apart. Renderers without the hook treat\n   * every component the same way and do not need it.\n   */\n  markFunctionComponent?<T>(component: T): T;\n  /**\n   * Optional: locate where a streamed chunk stops being the static shell.\n   *\n   * Partial prerendering caches everything before the first dynamic boundary\n   * and refreshes the rest on the client, so it has to know where that\n   * boundary is. The markers are renderer-specific (React streams Fizz\n   * boundary ids and `$RC`/`$RS` reveal calls, Solid streams `<template\n   * id=\"pl-N\">` with `$df(N)`), so the renderer that emits them owns finding\n   * them. Returns the index to cut at, or -1 when the chunk is entirely\n   * static.\n   *\n   * A renderer that does not implement this gets no static shell at all:\n   * guessing would mean caching a per-request response as if it were shared.\n   */\n  findStaticShellBoundary?(chunk: string): number;\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?: FarmRendererCapabilitiesInput;\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      /** CSP nonce forwarded to renderer-owned inline streaming scripts. */\n      nonce?: string;\n    },\n  ) => {\n    pipe(destination: NodeJS.WritableStream): void;\n    /** Stop rendering; pending boundaries report `reason` to `onError`. */\n    abort?(reason?: unknown): void;\n  };\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: {\n      node: true,\n      web: false,\n      runtimes: { edge: { node: false, web: true } },\n    },\n    reconcilesRerenders: true,\n    functionComponents: true,\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\n/**\n * Order two route patterns from most to least specific.\n *\n * This is the single ordering contract for file routes. The development route\n * manager, the generated client matcher, and the production route table must\n * all use it: a build whose server ordering disagrees with its client ordering\n * renders one page on first load and a different one after a client navigation.\n */\nexport function compareRoutePatternSpecificity(\n  left: string,\n  right: string,\n  syntax: RoutePatternSyntax = \"page\",\n): number {\n  return compareRouteSpecificity(\n    getRoutePatternSpecificity(left, syntax),\n    getRoutePatternSpecificity(right, syntax),\n  );\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\n/**\n * Split a request pathname and decode each segment exactly once.\n *\n * This is the pathname a route matcher compares against: every page matcher\n * decodes per segment before comparing to a static pattern segment, so\n * `/%64ashboard` and `/dashboard` are the same route. A guard that compares the\n * raw pathname instead disagrees with the router about which URL a request is\n * for, which is how a percent-encoded path slips past an auth gate while still\n * rendering the protected page.\n *\n * Splitting before decoding is the load-bearing part: `%2F` decodes to `/`\n * inside its own segment and must never become a new separator, or a decoded\n * slash grows a path segment that was not in the request.\n */\nexport function canonicalizeRequestPathSegments(pathname: string): string[] {\n  const segments = pathname.split(\"/\").filter(Boolean);\n  // Nothing to decode on the overwhelmingly common request.\n  if (!pathname.includes(\"%\")) return segments;\n  return segments.map(decodeRouteSegment);\n}\n\n/**\n * The string form of {@link canonicalizeRequestPathSegments}, for matchers that\n * run a regex or a prefix check over the whole pathname instead of walking\n * segments.\n *\n * A decoded `/` is re-encoded as `%2F` so it stays inside its segment for a\n * matcher that treats `/` as a separator, and so a capture that a redirect or\n * rewrite reuses keeps the encoding it arrived with.\n *\n * A run of slashes collapses to one, because every route matcher drops empty\n * segments: `//dashboard` renders `/dashboard`, so a guard comparing `//dashboard`\n * against `/dashboard` let the protected page through. A trailing slash and case\n * are otherwise left exactly as they arrived: this changes which pathname a\n * pattern is compared against, never what the pattern means.\n *\n * Decoding happens once. A path that still contains `%` after decoding, such as\n * `%2541BC` decoding to `%41BC`, keeps it; decoding a second time would resolve\n * a different route than the request asked for.\n */\nexport function canonicalizeRequestPathname(pathname: string): string {\n  // The overwhelmingly common case is a pathname with nothing to decode or\n  // collapse, so keep it off the split/join path entirely.\n  const encoded = pathname.includes(\"%\");\n  if (!encoded && !pathname.includes(\"//\")) return pathname;\n\n  // Collapse before decoding, so a decoded `%2F` can never form a new run.\n  const collapsed = pathname.replace(/\\/{2,}/g, \"/\");\n  if (!encoded) return collapsed;\n\n  return collapsed\n    .split(\"/\")\n    .map((segment) => {\n      const decoded = decodeRouteSegment(segment);\n      return decoded === segment ? segment : decoded.replace(/\\//g, \"%2F\");\n    })\n    .join(\"/\");\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  return matchRouteParts(splitRoutePath(url), segments);\n}\n\n/** Decode a pathname once when it will be tested against multiple route chains. */\nexport function splitRoutePath(url: string): string[] {\n  return url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n}\n\n/** Match an already decoded pathname so route-table scans do not repeatedly split it. */\nexport function matchRouteParts(\n  urlParts: readonly string[],\n  segments: RouteSegment[],\n): { params: Record<string, string>; matches: boolean } {\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  return matchRoutePrefixParts(splitRoutePath(url), segments);\n}\n\n/** Match an owner chain against an already decoded pathname. */\nexport function matchRoutePrefixParts(\n  urlParts: readonly string[],\n  segments: RouteSegment[],\n): boolean {\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  // Farm created this connection, so it is Farm's to close, exactly once. Newer db0\n  // drivers dispose the database themselves; older ones have no dispose at all.\n  return {\n    ...driver,\n    async 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    // The caller owns this database. Newer db0 drivers close their database on\n    // dispose, so drop that hook and leave the connection open.\n    const { dispose: _dispose, ...driver } = db0DriverModule.default({\n      database,\n      tableName: options.tableName,\n    });\n    return driver;\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  // prefixStorage re-prefixes the key methods, but copies dispose/watch/getMount(s)\n  // straight from the parent, so on a namespaced view they operate on the whole\n  // global store: dispose() tears down every namespace, watch() sees (and leaks\n  // the raw keys of) every other namespace's writes, getMounts() lists them all.\n  // Scope those too, so a handle handed out as \"namespace X\" stays confined to X.\n  const store = globalStorage;\n  const prefix = `${base}:`;\n  const stripPrefix = (key: string) => (key.startsWith(prefix) ? key.slice(prefix.length) : key);\n  const viewUnwatchers = new Set<Awaited<ReturnType<Storage[\"watch\"]>>>();\n  const releaseViewWatchers = async () => {\n    const current = [...viewUnwatchers];\n    viewUnwatchers.clear();\n    await Promise.all(current.map((unwatch) => unwatch()));\n  };\n\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    async watch(callback) {\n      const unwatch = await store.watch((event, key) => {\n        if (key.startsWith(prefix)) callback(event, stripPrefix(key));\n      });\n      viewUnwatchers.add(unwatch);\n      return async () => {\n        viewUnwatchers.delete(unwatch);\n        await unwatch();\n      };\n    },\n    async unwatch() {\n      await releaseViewWatchers();\n    },\n    async dispose() {\n      // A namespaced view shares the global store's lifecycle and owns no\n      // drivers, so disposing it must not tear down the global store (that is\n      // what disposeStorage is for). Release only this view's watchers.\n      await releaseViewWatchers();\n    },\n    getMount(key = \"\") {\n      return store.getMount(prefix + key);\n    },\n    getMounts(base = \"\", options) {\n      return store\n        .getMounts(prefix + base, options)\n        .map((mount) => ({ ...mount, base: stripPrefix(mount.base) }));\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","/**\n * Farm's declarative data schema: a serializable description of models and\n * fields shared by integrations, applications, ORM generation, and any feature\n * that needs one schema story across storage targets.\n *\n * The shape is plain data, not code, so it can be inspected at build time,\n * mapped onto an ORM schema, and serialized to other tooling.\n */\n\nexport type FarmSchemaFieldType =\n  | \"id\"\n  | \"uuid\"\n  | \"string\"\n  | \"text\"\n  | \"boolean\"\n  | \"integer\"\n  | \"number\"\n  | \"datetime\"\n  | \"json\"\n  | \"enum\";\n\nexport interface FarmSchemaReference {\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 FarmSchemaField {\n  type: FarmSchemaFieldType;\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?: FarmSchemaReference;\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmSchemaConstraint {\n  type: \"unique\" | \"index\";\n  fields: readonly string[];\n  name?: string;\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmSchemaModel {\n  name?: string;\n  description?: string;\n  /**\n   * A table someone else creates, such as the app's or an auth library's\n   * `user`. It is described so references to it resolve to its real name, and\n   * so queries can read it, but Farm never creates it: migrate, generated ORM\n   * schemas, and conflict checks skip it.\n   */\n  external?: boolean;\n  fields: Record<string, FarmSchemaField>;\n  constraints?: readonly FarmSchemaConstraint[];\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmSchemaModelExtension {\n  name?: string;\n  description?: string;\n  fields?: Record<string, FarmSchemaField>;\n  constraints?: readonly FarmSchemaConstraint[];\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmSchemaModelOverride {\n  name?: string;\n  description?: string;\n  fields?: Record<string, Partial<FarmSchemaField>>;\n  constraints?: readonly FarmSchemaConstraint[];\n  meta?: Record<string, unknown>;\n}\n\nexport interface FarmSchema {\n  models: Record<string, FarmSchemaModel>;\n  meta?: Record<string, unknown>;\n  extend?: Record<string, FarmSchemaModelExtension>;\n  override?: Record<string, FarmSchemaModelOverride>;\n}\n\n/** App-level rules for the tables plugins and integrations declare. */\nexport interface FarmSchemaConfig {\n  /**\n   * Tables a plugin may add columns to, keyed by the plugin's migrate name.\n   * List the plugin's model names (`user`) or your real table names\n   * (`members_auth`). Without an entry, `farm <plugin> migrate` prints the\n   * `ALTER TABLE` and refuses to run it.\n   *\n   * ```ts\n   * schema: { allowExtend: { loyalty: [\"user\"] } }\n   * ```\n   */\n  allowExtend?: Record<string, readonly string[]>;\n  /**\n   * A plugin's existing tables that may get foreign keys to other plugins'\n   * tables, keyed by the plugin's migrate name. Tables created from now on\n   * get them automatically; an existing table may hold rows that point at\n   * nothing, so Farm checks for those first and adds the key only when allowed.\n   *\n   * ```ts\n   * schema: { allowForeignKeys: { billing: [\"subscription\"] } }\n   * ```\n   */\n  allowForeignKeys?: Record<string, readonly string[]>;\n}\n\n/**\n * Declare a data schema with full type inference preserved.\n *\n * ```ts\n * export const schema = defineSchema({\n *   models: {\n *     tasks: {\n *       fields: {\n *         id: { type: \"uuid\", primaryKey: true },\n *         title: { type: \"string\", required: true },\n *       },\n *     },\n *   },\n * });\n * ```\n */\nexport function defineSchema<TSchema extends FarmSchema>(schema: TSchema): TSchema {\n  return schema;\n}\n","import type { FarmSchemaField } from \"./schema\";\n\n/**\n * Reject a list field before a scalar-only schema target can silently change\n * its value shape. Targets that genuinely preserve arrays do not call this.\n */\nexport function assertNoSchemaListField(\n  field: Pick<FarmSchemaField, \"list\">,\n  fieldPath: string,\n  target: string,\n): void {\n  if (!field.list) {\n    return;\n  }\n\n  throw new Error(\n    `Schema field \"${fieldPath}\" declares list: true, but ${target} does not support list fields. Use type: \"json\" for an array value or model the values in a related table.`,\n  );\n}\n","import type { FarmSchemaReference } from \"./schema\";\n\n/** Keep the public reference default consistent across database-backed consumers. */\nexport function isDatabaseEnforcedReference(reference: FarmSchemaReference): boolean {\n  return reference.enforced === undefined || reference.enforced === \"db\";\n}\n","import type { FarmSchemaField } from \"./schema\";\n\nconst SUPPORTED_PRIMARY_KEY_TYPES = new Set([\"id\", \"uuid\", \"string\", \"integer\"]);\n\nexport function assertSupportedPrimaryKeyField(location: string, field: FarmSchemaField): void {\n  if (!field.primaryKey || SUPPORTED_PRIMARY_KEY_TYPES.has(field.type)) {\n    return;\n  }\n\n  throw new Error(\n    `Schema primary-key field \"${location}\" uses unsupported type \"${field.type}\". Supported types are id, uuid, string, and integer.`,\n  );\n}\n","import type { FarmSchema, FarmSchemaField, FarmSchemaModel } from \"./schema\";\nimport { assertSupportedPrimaryKeyField } from \"./schema-primary-key\";\n\nexport type ResolvedSchemaField = FarmSchemaField & {\n  name: string;\n};\n\nexport type ResolvedSchemaModel = Omit<FarmSchemaModel, \"fields\"> & {\n  name: string;\n  fields: Record<string, ResolvedSchemaField>;\n};\n\n/**\n * Resolve a schema's extensions, overrides, and name mappings.\n *\n * Table and column names fall back to the schema's own keys, which is what the\n * runtime ORM uses. Any other default would generate artifacts describing\n * tables the app cannot actually read.\n */\nexport function resolveSchemaModels(\n  ownerKey: string,\n  schema: FarmSchema,\n): Record<string, ResolvedSchemaModel> {\n  const models: Record<string, FarmSchemaModel> = Object.fromEntries(\n    Object.entries(schema.models).map(([modelKey, model]) => [modelKey, cloneSchemaModel(model)]),\n  );\n\n  for (const [modelKey, extension] of Object.entries(schema.extend || {})) {\n    const existing = models[modelKey];\n    models[modelKey] = {\n      ...(existing || { fields: {} }),\n      ...(extension.name ? { name: extension.name } : {}),\n      ...(extension.description ? { description: extension.description } : {}),\n      fields: {\n        ...existing?.fields,\n        ...extension.fields,\n      },\n      constraints: [...(existing?.constraints || []), ...(extension.constraints || [])],\n      meta: {\n        ...existing?.meta,\n        ...extension.meta,\n      },\n    };\n  }\n\n  for (const [modelKey, override] of Object.entries(schema.override || {})) {\n    const existing = models[modelKey];\n\n    if (!existing) {\n      throw new Error(\n        `Schema override for \"${ownerKey}.${modelKey}\" is invalid because that model does not exist.`,\n      );\n    }\n\n    const fields = {\n      ...existing.fields,\n    };\n\n    for (const [fieldKey, fieldOverride] of Object.entries(override.fields || {})) {\n      const existingField = fields[fieldKey];\n\n      if (!existingField && !fieldOverride.type) {\n        throw new Error(\n          `Schema override for \"${ownerKey}.${modelKey}.${fieldKey}\" is missing a field type.`,\n        );\n      }\n\n      fields[fieldKey] = {\n        ...existingField,\n        ...fieldOverride,\n      } as FarmSchemaField;\n    }\n\n    models[modelKey] = {\n      ...existing,\n      ...(override.name ? { name: override.name } : {}),\n      ...(override.description ? { description: override.description } : {}),\n      fields,\n      constraints: override.constraints || existing.constraints,\n      meta: {\n        ...existing.meta,\n        ...override.meta,\n      },\n    };\n  }\n\n  const resolvedModels: Record<string, ResolvedSchemaModel> = {};\n\n  for (const [modelKey, model] of Object.entries(models)) {\n    const modelName = model.name || modelKey;\n    const fieldNames = new Set<string>();\n    const resolvedFields: Record<string, ResolvedSchemaField> = {};\n\n    for (const [fieldKey, field] of Object.entries(model.fields)) {\n      const fieldName = field.name || fieldKey;\n      assertSupportedPrimaryKeyField(`${ownerKey}.${modelKey}.${fieldKey}`, field);\n\n      if (fieldNames.has(fieldName)) {\n        throw new Error(\n          `Schema model \"${ownerKey}.${modelKey}\" contains duplicate field name \"${fieldName}\".`,\n        );\n      }\n\n      fieldNames.add(fieldName);\n      resolvedFields[fieldKey] = {\n        ...field,\n        name: fieldName,\n      };\n    }\n\n    const primaryKeyFields = Object.entries(resolvedFields)\n      .filter(([, field]) => field.primaryKey)\n      .map(([fieldKey]) => fieldKey);\n\n    if (primaryKeyFields.length > 1) {\n      throw new Error(\n        `Schema model \"${ownerKey}.${modelKey}\" defines multiple primary-key fields: ${primaryKeyFields.map((fieldKey) => `\"${fieldKey}\"`).join(\", \")}. Composite primary keys are not supported.`,\n      );\n    }\n\n    for (const constraint of model.constraints || []) {\n      for (const fieldKey of constraint.fields) {\n        if (!Object.prototype.hasOwnProperty.call(resolvedFields, fieldKey)) {\n          throw new Error(\n            `Schema ${constraint.type} constraint on \"${ownerKey}.${modelKey}\" references missing field \"${fieldKey}\".`,\n          );\n        }\n      }\n    }\n\n    resolvedModels[modelKey] = {\n      ...model,\n      name: modelName,\n      fields: resolvedFields,\n    };\n  }\n\n  for (const [modelKey, model] of Object.entries(resolvedModels)) {\n    for (const [fieldKey, field] of Object.entries(model.fields)) {\n      const reference = field.reference;\n      if (!reference || !Object.prototype.hasOwnProperty.call(resolvedModels, reference.model)) {\n        continue;\n      }\n\n      const referencedModel = resolvedModels[reference.model]!;\n      if (!Object.prototype.hasOwnProperty.call(referencedModel.fields, reference.field)) {\n        throw new Error(\n          `Schema reference \"${ownerKey}.${modelKey}.${fieldKey}\" targets missing field \"${ownerKey}.${reference.model}.${reference.field}\".`,\n        );\n      }\n    }\n  }\n\n  return resolvedModels;\n}\n\nfunction cloneSchemaModel(model: FarmSchemaModel): FarmSchemaModel {\n  return {\n    ...model,\n    fields: Object.fromEntries(\n      Object.entries(model.fields).map(([fieldKey, field]) => [fieldKey, { ...field }]),\n    ),\n    constraints: model.constraints ? [...model.constraints] : undefined,\n    meta: model.meta ? { ...model.meta } : undefined,\n  };\n}\n","import type { FarmSchema, FarmSchemaReference } from \"./schema\";\nimport { assertNoSchemaListField } from \"./schema-capabilities\";\nimport { isDatabaseEnforcedReference } from \"./schema-reference\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\nimport type { ResolvedSchemaField, ResolvedSchemaModel } from \"./schema-resolve\";\n\nexport { assertNoSchemaListField } from \"./schema-capabilities\";\nexport { resolveSchemaModels } from \"./schema-resolve\";\nexport type { ResolvedSchemaField, ResolvedSchemaModel } from \"./schema-resolve\";\n\nexport type FarmSqlDialect = \"postgres\" | \"mysql\" | \"sqlite\";\n\nexport type CollectedSchemaModel = {\n  /** Namespace that owns the model: an integration key or a plugin name. */\n  ownerKey: string;\n  modelKey: string;\n  modelName: string;\n  exportName: string;\n  prismaModelName: string;\n  model: ResolvedSchemaModel;\n  /**\n   * Real table and column for references to models this owner describes but\n   * does not create (external, or outside its `models`), keyed by field. Only\n   * shown in comments: Farm never creates a foreign key to them.\n   */\n  referenceTargets?: Record<string, { table: string; column: string }>;\n  /**\n   * References to tables other owners create that may carry a real foreign\n   * key, keyed by field. Set by migrate after checking the database; only a\n   * table created now gets one inline.\n   */\n  foreignKeys?: Record<\n    string,\n    { table: string; column: string; onDelete: NonNullable<FarmSchemaReference[\"onDelete\"]> }\n  >;\n};\n\n/** `table.column` a field's reference points at, using real names when known. */\nexport function describeSchemaReference(model: CollectedSchemaModel, fieldKey: string): string {\n  const field = model.model.fields[fieldKey];\n  const target = model.referenceTargets?.[fieldKey];\n  if (target) return `${target.table}.${target.column}`;\n  return `${field?.reference?.model}.${field?.reference?.field}`;\n}\n\nconst SQL_ON_DELETE_ACTIONS = {\n  cascade: \"CASCADE\",\n  restrict: \"RESTRICT\",\n  setNull: \"SET NULL\",\n  noAction: \"NO ACTION\",\n} satisfies Record<NonNullable<FarmSchemaReference[\"onDelete\"]>, string>;\n\n/**\n * Flatten owners' schemas into one list, rejecting two models that would\n * resolve to the same table.\n *\n * `only` narrows an owner to the models it actually controls; an owner handed a\n * schema it shares with the rest of the app should not claim all of it.\n */\nexport function collectSchemaModels(\n  entries: ReadonlyArray<readonly [string, FarmSchema, (readonly string[])?]>,\n): CollectedSchemaModel[] {\n  const collectedModels: CollectedSchemaModel[] = [];\n  const seenModelNames = new Map<string, string>();\n\n  for (const [ownerKey, schema, only] of entries) {\n    const resolvedModels = resolveSchemaModels(ownerKey, schema);\n\n    for (const [modelKey, model] of Object.entries(resolvedModels)) {\n      if (only && !only.includes(modelKey)) continue;\n      // Someone else creates it; it is only described to resolve references.\n      if (model.external) continue;\n\n      const collisionKey = model.name.toLowerCase();\n      const previousOwner = seenModelNames.get(collisionKey);\n\n      if (previousOwner && previousOwner !== `${ownerKey}.${modelKey}`) {\n        throw new Error(\n          `Schema model \"${ownerKey}.${modelKey}\" resolves to \"${model.name}\", which conflicts with \"${previousOwner}\". Rename one of the models with schema.models.<model>.name.`,\n        );\n      }\n\n      seenModelNames.set(collisionKey, `${ownerKey}.${modelKey}`);\n\n      const referenceTargets: Record<string, { table: string; column: string }> = {};\n      for (const [fieldKey, field] of Object.entries(model.fields)) {\n        const reference = field.reference;\n        if (!reference || !Object.prototype.hasOwnProperty.call(resolvedModels, reference.model)) {\n          continue;\n        }\n        const target = resolvedModels[reference.model]!;\n        if (!target.external && (!only || only.includes(reference.model))) continue;\n        referenceTargets[fieldKey] = {\n          table: target.name,\n          column: target.fields[reference.field]?.name ?? reference.field,\n        };\n      }\n\n      collectedModels.push({\n        ownerKey,\n        modelKey,\n        modelName: model.name,\n        exportName: toCamelCase(`${ownerKey}_${modelKey}`),\n        prismaModelName: toPascalCase(`${ownerKey}_${modelKey}`),\n        model,\n        ...(Object.keys(referenceTargets).length > 0 ? { referenceTargets } : {}),\n      });\n    }\n  }\n\n  return collectedModels;\n}\n\nexport type FarmSqlStatement = {\n  kind: \"table\" | \"index\" | \"column\";\n  /** The object this statement creates, for drift reporting. */\n  target: string;\n  sql: string;\n};\n\n/**\n * Emit create statements for a set of models.\n *\n * Everything here is derivable from the schema: nothing is inferred from a live\n * database, so the output is stable and reviewable before it is applied.\n */\nexport function generateSqlStatements(\n  models: readonly CollectedSchemaModel[],\n  dialect: FarmSqlDialect,\n): FarmSqlStatement[] {\n  const modelLookup = createModelLookup(models);\n  const orderedModels = orderSchemaModelsByReferences(models, modelLookup);\n  const statements: FarmSqlStatement[] = [];\n\n  for (const model of orderedModels) {\n    statements.push({\n      kind: \"table\",\n      target: model.modelName,\n      sql: renderSqlTable(model, dialect, modelLookup),\n    });\n\n    for (const index of renderSqlIndexes(model, dialect)) {\n      statements.push(index);\n    }\n  }\n\n  return statements;\n}\n\n/** Render models as a standalone `.sql` file. */\nexport function renderSqlSchemaFile(\n  models: readonly CollectedSchemaModel[],\n  dialect: FarmSqlDialect,\n): string {\n  const lines = [\"-- Generated by Farm.js CLI. Review before applying.\", \"\"];\n  const modelLookup = createModelLookup(models);\n  const orderedModels = orderSchemaModelsByReferences(models, modelLookup);\n\n  for (const model of orderedModels) {\n    lines.push(\n      `-- Owner \"${model.ownerKey}\" model \"${model.modelKey}\"`,\n      renderSqlTable(model, dialect, modelLookup),\n      \"\",\n    );\n\n    for (const statement of renderSqlIndexes(model, dialect)) {\n      lines.push(statement.sql, \"\");\n    }\n  }\n\n  return lines.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\nfunction renderSqlTable(\n  model: CollectedSchemaModel,\n  dialect: FarmSqlDialect,\n  modelLookup: Map<string, CollectedSchemaModel>,\n) {\n  const tableName = quoteSqlIdentifier(dialect, model.modelName);\n  const lines = [`CREATE TABLE IF NOT EXISTS ${tableName} (`];\n  const columns: string[] = [];\n  const internalReferences = createInternalReferenceLookup(model, dialect, modelLookup);\n\n  for (const [fieldKey, field] of Object.entries(model.model.fields)) {\n    assertNoSchemaListField(\n      field,\n      `${model.ownerKey}.${model.modelKey}.${fieldKey}`,\n      `${dialect} SQL generation`,\n    );\n\n    const parts = [\n      `  ${quoteSqlIdentifier(dialect, field.name)}`,\n      getSqlColumnType(field, dialect),\n    ];\n\n    if (field.primaryKey) {\n      parts.push(\"PRIMARY KEY\");\n    } else if (!isNullableField(field)) {\n      parts.push(\"NOT NULL\");\n    }\n\n    if (!field.primaryKey && field.unique) {\n      parts.push(\"UNIQUE\");\n    }\n\n    const defaultValue = getSqlDefaultExpression(field, dialect);\n    if (defaultValue) {\n      parts.push(`DEFAULT ${defaultValue}`);\n    }\n\n    const crossOwner = model.foreignKeys?.[fieldKey];\n    const reference =\n      internalReferences.get(fieldKey) ??\n      (crossOwner\n        ? `REFERENCES ${quoteSqlIdentifier(dialect, crossOwner.table)} (${quoteSqlIdentifier(dialect, crossOwner.column)})${crossOwner.onDelete !== \"noAction\" ? ` ON DELETE ${SQL_ON_DELETE_ACTIONS[crossOwner.onDelete]}` : \"\"}`\n        : undefined);\n    if (reference) {\n      parts.push(reference);\n    } else if (field.reference) {\n      parts.push(\n        `/* references ${describeSchemaReference(model, fieldKey)}${field.reference.onDelete ? ` on delete ${field.reference.onDelete}` : \"\"} */`,\n      );\n    }\n\n    columns.push(parts.join(\" \"));\n  }\n\n  if (dialect === \"mysql\") {\n    for (const definition of collectSchemaIndexes(model, dialect)) {\n      columns.push(\n        `  ${definition.unique ? \"UNIQUE KEY\" : \"KEY\"} ${quoteSqlIdentifier(dialect, definition.name)} (${definition.columns.join(\", \")})`,\n      );\n    }\n  }\n\n  lines.push(columns.join(\",\\n\"));\n  lines.push(\");\");\n  return lines.join(\"\\n\");\n}\n\ntype SchemaIndexDefinition = {\n  name: string;\n  /** Already quoted for the dialect. */\n  columns: string[];\n  unique: boolean;\n};\n\n/** The indexes a model asks for, before any dialect decides how to declare them. */\nfunction collectSchemaIndexes(\n  model: CollectedSchemaModel,\n  dialect: FarmSqlDialect,\n): SchemaIndexDefinition[] {\n  const definitions: SchemaIndexDefinition[] = [];\n\n  for (const field of Object.values(model.model.fields)) {\n    if (!field.index) {\n      continue;\n    }\n\n    definitions.push({\n      name: `${model.modelName}_${field.name}_idx`,\n      columns: [quoteSqlIdentifier(dialect, field.name)],\n      unique: false,\n    });\n  }\n\n  for (const constraint of model.model.constraints || []) {\n    definitions.push({\n      name:\n        constraint.name ||\n        `${model.modelName}_${constraint.fields.map((fieldKey) => model.model.fields[fieldKey]?.name || fieldKey).join(\"_\")}_${constraint.type}`,\n      columns: constraint.fields.map((fieldKey) =>\n        quoteSqlIdentifier(dialect, model.model.fields[fieldKey]?.name || fieldKey),\n      ),\n      unique: constraint.type === \"unique\",\n    });\n  }\n\n  return definitions;\n}\n\nfunction renderSqlIndexes(\n  model: CollectedSchemaModel,\n  dialect: FarmSqlDialect,\n): FarmSqlStatement[] {\n  // MySQL has no `CREATE INDEX ... IF NOT EXISTS`, so its indexes are declared\n  // inside CREATE TABLE, where IF NOT EXISTS already covers re-runs.\n  if (dialect === \"mysql\") {\n    return [];\n  }\n\n  const tableName = quoteSqlIdentifier(dialect, model.modelName);\n\n  return collectSchemaIndexes(model, dialect).map((definition) => ({\n    kind: \"index\",\n    target: definition.name,\n    sql: `CREATE ${definition.unique ? \"UNIQUE \" : \"\"}INDEX IF NOT EXISTS ${quoteSqlIdentifier(dialect, definition.name)} ON ${tableName} (${definition.columns.join(\", \")});`,\n  }));\n}\n\nfunction createInternalReferenceLookup(\n  model: CollectedSchemaModel,\n  dialect: FarmSqlDialect,\n  modelLookup: Map<string, CollectedSchemaModel>,\n) {\n  const lookup = new Map<string, string>();\n\n  for (const [fieldKey, field] of Object.entries(model.model.fields)) {\n    if (!field.reference || !isDatabaseEnforcedReference(field.reference)) {\n      continue;\n    }\n\n    const referencedModel = modelLookup.get(`${model.ownerKey}.${field.reference.model}`);\n\n    if (referencedModel) {\n      const referencedField = field.reference.field;\n      const pieces = [\n        `REFERENCES ${quoteSqlIdentifier(dialect, referencedModel.modelName)} (${quoteSqlIdentifier(dialect, referencedModel.model.fields[referencedField]?.name || referencedField)})`,\n      ];\n\n      if (field.reference.onDelete) {\n        pieces.push(`ON DELETE ${SQL_ON_DELETE_ACTIONS[field.reference.onDelete]}`);\n      }\n\n      lookup.set(fieldKey, pieces.join(\" \"));\n    }\n  }\n\n  return lookup;\n}\n\nexport function getSqlColumnType(field: ResolvedSchemaField, dialect: FarmSqlDialect) {\n  if (dialect === \"postgres\") {\n    switch (field.type) {\n      case \"boolean\":\n        return \"BOOLEAN\";\n      case \"integer\":\n        return \"INTEGER\";\n      case \"number\":\n        return \"DOUBLE PRECISION\";\n      case \"datetime\":\n        return \"TIMESTAMPTZ\";\n      case \"json\":\n        return \"JSONB\";\n      default:\n        return \"TEXT\";\n    }\n  }\n\n  if (dialect === \"mysql\") {\n    switch (field.type) {\n      case \"boolean\":\n        return \"BOOLEAN\";\n      case \"integer\":\n        return \"INT\";\n      case \"number\":\n        return \"DOUBLE\";\n      case \"datetime\":\n        return \"DATETIME\";\n      case \"json\":\n        return \"JSON\";\n      case \"text\":\n        return \"TEXT\";\n      default:\n        return \"VARCHAR(255)\";\n    }\n  }\n\n  switch (field.type) {\n    case \"boolean\":\n    case \"integer\":\n      return \"INTEGER\";\n    case \"number\":\n      return \"REAL\";\n    default:\n      return \"TEXT\";\n  }\n}\n\nexport function getSqlDefaultExpression(field: ResolvedSchemaField, dialect: FarmSqlDialect) {\n  if (field.default === undefined) {\n    return null;\n  }\n\n  if (field.type === \"datetime\" && field.default === \"now\") {\n    return \"CURRENT_TIMESTAMP\";\n  }\n\n  if (typeof field.default === \"string\") {\n    return `'${escapeSqlString(field.default, dialect)}'`;\n  }\n\n  if (typeof field.default === \"number\") {\n    return String(field.default);\n  }\n\n  if (typeof field.default === \"boolean\") {\n    if (dialect === \"sqlite\") {\n      return field.default ? \"1\" : \"0\";\n    }\n    return field.default ? \"TRUE\" : \"FALSE\";\n  }\n\n  return null;\n}\n\nexport function isNullableField(field: ResolvedSchemaField) {\n  return field.nullable === true || field.required === false;\n}\n\nexport function quoteSqlIdentifier(dialect: FarmSqlDialect, value: string) {\n  if (dialect === \"mysql\") {\n    return `\\`${value.replace(/`/g, \"``\")}\\``;\n  }\n\n  return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction createModelLookup(models: readonly CollectedSchemaModel[]) {\n  return new Map(models.map((model) => [`${model.ownerKey}.${model.modelKey}`, model]));\n}\n\nfunction orderSchemaModelsByReferences(\n  models: readonly CollectedSchemaModel[],\n  modelLookup: Map<string, CollectedSchemaModel>,\n): CollectedSchemaModel[] {\n  const ordered: CollectedSchemaModel[] = [];\n  const states = new Map<string, \"visiting\" | \"visited\">();\n  const stack: CollectedSchemaModel[] = [];\n\n  const visit = (model: CollectedSchemaModel): void => {\n    const modelKey = getCollectedModelKey(model);\n    if (states.get(modelKey) === \"visited\") {\n      return;\n    }\n\n    states.set(modelKey, \"visiting\");\n    stack.push(model);\n\n    const dependencies = new Set<string>();\n    for (const field of Object.values(model.model.fields)) {\n      if (field.reference && isDatabaseEnforcedReference(field.reference)) {\n        dependencies.add(`${model.ownerKey}.${field.reference.model}`);\n      }\n    }\n\n    for (const dependencyKey of dependencies) {\n      const dependency = modelLookup.get(dependencyKey);\n      if (!dependency || dependency === model) {\n        continue;\n      }\n\n      if (states.get(dependencyKey) === \"visiting\") {\n        const cycleStart = stack.findIndex(\n          (candidate) => getCollectedModelKey(candidate) === dependencyKey,\n        );\n        const cycle = [...stack.slice(cycleStart), dependency]\n          .map((candidate) => `\"${getCollectedModelKey(candidate)}\"`)\n          .join(\" -> \");\n\n        throw new Error(\n          `Schema table references contain a cycle: ${cycle}. Database-enforced cross-table cycles cannot be created inline; remove one edge or manage that constraint separately.`,\n        );\n      }\n\n      visit(dependency);\n    }\n\n    stack.pop();\n    states.set(modelKey, \"visited\");\n    ordered.push(model);\n  };\n\n  for (const model of models) {\n    visit(model);\n  }\n\n  return ordered;\n}\n\nfunction getCollectedModelKey(model: CollectedSchemaModel) {\n  return `${model.ownerKey}.${model.modelKey}`;\n}\n\nexport function toSnakeCase(value: string) {\n  return value\n    .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n    .replace(/[\\s.-]+/g, \"_\")\n    .replace(/__+/g, \"_\")\n    .toLowerCase();\n}\n\nexport function toPascalCase(value: string) {\n  return value\n    .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n    .replace(/[\\s._-]+/g, \" \")\n    .split(\" \")\n    .filter(Boolean)\n    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n    .join(\"\");\n}\n\nexport function toCamelCase(value: string) {\n  const pascal = toPascalCase(value);\n  return pascal ? pascal.charAt(0).toLowerCase() + pascal.slice(1) : pascal;\n}\n\nexport function escapeSqlString(value: string, dialect?: FarmSqlDialect) {\n  // Standard-conforming SQL string literal: only quote doubling; backslashes\n  // are literal characters. MySQL is the exception - unless NO_BACKSLASH_ESCAPES\n  // is set it treats a backslash as an escape character, so a value containing\n  // one would escape the closing quote and break the statement.\n  const quoted = value.replace(/'/g, \"''\");\n  return dialect === \"mysql\" ? quoted.replace(/\\\\/g, \"\\\\\\\\\") : quoted;\n}\n","import type { FarmSchemaExtension } from \"./schema-extend\";\nimport {\n  generateSqlStatements,\n  getSqlColumnType,\n  getSqlDefaultExpression,\n  isNullableField,\n  quoteSqlIdentifier,\n  type CollectedSchemaModel,\n  type FarmSqlDialect,\n  type FarmSqlStatement,\n  type ResolvedSchemaField,\n} from \"./schema-sql\";\nimport { isDatabaseEnforcedReference } from \"./schema-reference\";\n\n/** The subset of a database client this needs: run a statement, read a result. */\nexport type FarmSchemaExecutor = {\n  /** Run a statement that returns nothing. */\n  execute(sql: string): Promise<void>;\n  /** Run a query and return its rows. */\n  query(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]>;\n};\n\nexport type FarmSchemaDrift = {\n  table: string;\n  /** Declared in the schema but absent from the table. */\n  missingColumns: string[];\n  /** Present in the table but not declared. Reported, never dropped. */\n  extraColumns: string[];\n  /** Columns whose stored definition differs from the schema. */\n  changedColumns: FarmSchemaColumnDrift[];\n  /** Declared indexes that are absent from the table. */\n  missingIndexes: FarmSchemaIndexDefinition[];\n  /** Stored indexes that are not declared by the schema. */\n  extraIndexes: FarmSchemaIndexDefinition[];\n  /** Declared foreign keys that are absent from the table. */\n  missingReferences: FarmSchemaReferenceDefinition[];\n  /** Stored foreign keys that are not declared by the schema. */\n  extraReferences: FarmSchemaReferenceDefinition[];\n};\n\nexport type FarmSchemaColumnDefinition = {\n  type: string;\n  nullable: boolean;\n  default: string | null;\n  primaryKey: boolean;\n};\n\nexport type FarmSchemaColumnDrift = {\n  column: string;\n  differences: Array<\"type\" | \"nullability\" | \"default\" | \"primaryKey\">;\n  expected: FarmSchemaColumnDefinition;\n  actual: FarmSchemaColumnDefinition;\n};\n\nexport type FarmSchemaIndexDefinition = {\n  name: string;\n  columns: string[];\n  unique: boolean;\n};\n\nexport type FarmSchemaReferenceDefinition = {\n  column: string;\n  referencedTable: string;\n  referencedColumn: string;\n  onDelete: \"cascade\" | \"restrict\" | \"setNull\" | \"noAction\";\n};\n\ntype DescribedColumn = Omit<FarmSchemaColumnDefinition, \"default\"> & {\n  name: string;\n  rawDefault: string | null;\n};\n\ntype DescribedIndex = FarmSchemaIndexDefinition & {\n  primary: boolean;\n};\n\ntype DescribedTable = {\n  columns: DescribedColumn[];\n  indexes: DescribedIndex[];\n  references: FarmSchemaReferenceDefinition[];\n};\n\nexport type FarmSchemaMigratePlan = {\n  dialect: FarmSqlDialect;\n  /** Statements for tables that do not exist yet. */\n  statements: FarmSqlStatement[];\n  /** Tables that exist and already match the schema. */\n  upToDate: string[];\n  /**\n   * Additions to tables that exist: columns that can join a table with rows\n   * (nullable, or with a default the database can write) and non-unique\n   * indexes. Applied with the rest of the plan. Anything else stays in drift.\n   */\n  upgrades?: Array<FarmSqlStatement & { table: string }>;\n  /** Tables that exist but differ in ways Farm will not change on its own. */\n  drift: FarmSchemaDrift[];\n  /**\n   * Foreign keys to other owners' tables that an existing table does not\n   * have yet. Never added automatically: they need the app's approval.\n   */\n  addableForeignKeys?: FarmSchemaAddableForeignKey[];\n};\n\nexport type FarmSchemaAddableForeignKey = {\n  modelKey: string;\n  table: string;\n  column: string;\n  referencedTable: string;\n  referencedColumn: string;\n  onDelete: FarmSchemaReferenceDefinition[\"onDelete\"];\n};\n\n/**\n * Compare resolved models against the live database and plan what to create.\n *\n * Creation is derivable from the schema alone, so it is safe to emit. Changing\n * an existing table is not: a rename and a drop-plus-add look identical here,\n * and one of them destroys data. Differences are reported for a human instead.\n */\nexport async function planSchemaMigration(\n  models: readonly CollectedSchemaModel[],\n  dialect: FarmSqlDialect,\n  executor: FarmSchemaExecutor,\n): Promise<FarmSchemaMigratePlan> {\n  const statements: FarmSqlStatement[] = [];\n  const upToDate: string[] = [];\n  const drift: FarmSchemaDrift[] = [];\n  const addableForeignKeys: FarmSchemaAddableForeignKey[] = [];\n  const upgrades: Array<FarmSqlStatement & { table: string }> = [];\n  const modelLookup = new Map(\n    models.map((model) => [`${model.ownerKey}.${model.modelKey}`, model]),\n  );\n\n  // Emitted once over the whole set so cross-model references resolve, then\n  // grouped: a table statement opens a group and its indexes follow it.\n  const byTable = new Map<string, FarmSqlStatement[]>();\n  let currentTable: FarmSqlStatement[] | undefined;\n  for (const statement of generateSqlStatements(models, dialect)) {\n    if (statement.kind === \"table\") {\n      currentTable = [];\n      byTable.set(statement.target, currentTable);\n    }\n    currentTable?.push(statement);\n  }\n\n  for (const model of models) {\n    const existing = await describeTable(executor, dialect, model.modelName);\n\n    if (!existing) {\n      statements.push(...(byTable.get(model.modelName) ?? []));\n      continue;\n    }\n\n    const expectedColumns = new Map(\n      Object.values(model.model.fields).map((field) => [field.name.toLowerCase(), field]),\n    );\n    const actualColumns = new Map(\n      existing.columns.map((column) => [column.name.toLowerCase(), column]),\n    );\n    const missingColumns = [...expectedColumns.values()]\n      .filter((field) => !actualColumns.has(field.name.toLowerCase()))\n      .map((field) => field.name);\n    const extraColumns = existing.columns\n      .filter((column) => !expectedColumns.has(column.name.toLowerCase()))\n      .map((column) => column.name);\n    const changedColumns: FarmSchemaColumnDrift[] = [];\n\n    for (const [columnKey, field] of expectedColumns) {\n      const actualColumn = actualColumns.get(columnKey);\n      if (!actualColumn) continue;\n\n      const expectedDefinition = expectedColumnDefinition(field, dialect);\n      const actualDefinition = actualColumnDefinition(actualColumn, field, dialect);\n      const differences: FarmSchemaColumnDrift[\"differences\"] = [];\n      if (expectedDefinition.type !== actualDefinition.type) differences.push(\"type\");\n      if (expectedDefinition.nullable !== actualDefinition.nullable) {\n        differences.push(\"nullability\");\n      }\n      if (expectedDefinition.default !== actualDefinition.default) differences.push(\"default\");\n      if (expectedDefinition.primaryKey !== actualDefinition.primaryKey) {\n        differences.push(\"primaryKey\");\n      }\n      if (differences.length > 0) {\n        changedColumns.push({\n          column: field.name,\n          differences,\n          expected: expectedDefinition,\n          actual: actualDefinition,\n        });\n      }\n    }\n\n    const expectedIndexes = collectExpectedIndexes(model);\n    const actualIndexes = existing.indexes.filter((index) => !index.primary);\n    const { missing: missingIndexes, extra: unmatchedIndexes } = compareDefinitions(\n      expectedIndexes,\n      actualIndexes,\n      indexSignature,\n    );\n    const expectedReferences = collectExpectedReferences(model, modelLookup);\n    // A foreign key to another owner's table is optional: created with the\n    // table, or added with approval later. Neither its presence nor its\n    // absence is drift.\n    const crossOwner = Object.entries(model.foreignKeys ?? {}).map(([fieldKey, key]) => ({\n      ...key,\n      column: model.model.fields[fieldKey]!.name,\n      referencedColumn: key.column,\n    }));\n    const isCrossOwnerOf =\n      (key: { column: string; table: string }) => (reference: FarmSchemaReferenceDefinition) =>\n        key.column.toLowerCase() === reference.column.toLowerCase() &&\n        key.table.toLowerCase() === reference.referencedTable.toLowerCase();\n    const isCrossOwner = (reference: FarmSchemaReferenceDefinition) =>\n      crossOwner.some((key) => isCrossOwnerOf(key)(reference));\n    const { missing: missingReferences, extra: unmatchedReferences } = compareDefinitions(\n      expectedReferences,\n      existing.references,\n      referenceSignature,\n    );\n    const extraReferences = unmatchedReferences.filter((reference) => !isCrossOwner(reference));\n    for (const key of crossOwner) {\n      if (existing.references.some(isCrossOwnerOf(key))) continue;\n      addableForeignKeys.push({\n        modelKey: model.modelKey,\n        table: model.modelName,\n        column: key.column,\n        referencedTable: key.table,\n        referencedColumn: key.referencedColumn,\n        onDelete: key.onDelete,\n      });\n    }\n    const referenceColumns = new Set(\n      existing.references.map((reference) => reference.column.toLowerCase()),\n    );\n    const extraIndexes = unmatchedIndexes.filter(\n      (index) =>\n        !(\n          dialect === \"mysql\" &&\n          !index.unique &&\n          index.columns.length === 1 &&\n          referenceColumns.has(index.columns[0]!.toLowerCase())\n        ),\n    );\n\n    // What can be added to a table that may hold rows is an upgrade; the rest\n    // stays drift, for a migration step or a person to decide.\n    const remainingColumns: string[] = [];\n    for (const column of missingColumns) {\n      const field = expectedColumns.get(column.toLowerCase())!;\n      if (field.primaryKey || field.unique || unsupportedColumnReason(field, dialect)) {\n        remainingColumns.push(column);\n        continue;\n      }\n      upgrades.push({\n        kind: \"column\",\n        table: model.modelName,\n        target: `${model.modelName}.${column}`,\n        sql: addColumnStatement(dialect, model.modelName, field),\n      });\n    }\n    const remainingIndexes: FarmSchemaIndexDefinition[] = [];\n    for (const index of missingIndexes) {\n      // A unique index fails on duplicate rows, so it is never added on its own.\n      const columnsExist = index.columns.every(\n        (column) => actualColumns.has(column.toLowerCase()) || !remainingColumns.includes(column),\n      );\n      if (index.unique || !columnsExist) {\n        remainingIndexes.push(index);\n        continue;\n      }\n      const columns = index.columns.map((column) => quoteSqlIdentifier(dialect, column)).join(\", \");\n      upgrades.push({\n        kind: \"index\",\n        table: model.modelName,\n        target: index.name,\n        sql: `CREATE INDEX${dialect === \"mysql\" ? \"\" : \" IF NOT EXISTS\"} ${quoteSqlIdentifier(dialect, index.name)} ON ${quoteTableName(dialect, model.modelName)} (${columns});`,\n      });\n    }\n\n    const entry = {\n      table: model.modelName,\n      missingColumns: remainingColumns,\n      extraColumns,\n      changedColumns,\n      missingIndexes: remainingIndexes,\n      extraIndexes: extraIndexes.map(({ name, columns, unique }) => ({ name, columns, unique })),\n      missingReferences,\n      extraReferences,\n    };\n    if (hasSchemaDrift(entry)) drift.push(entry);\n    else if (!upgrades.some((upgrade) => upgrade.table === model.modelName)) {\n      upToDate.push(model.modelName);\n    }\n  }\n\n  return { dialect, statements, upgrades, upToDate, drift, addableForeignKeys };\n}\n\n/** A table's columns as the database reports them, normalized per dialect. */\nexport type FarmSchemaTableDescription = {\n  columns: Array<{ name: string; type: string; nullable: boolean; primaryKey: boolean }>;\n};\n\n/**\n * Read any table, owned by Farm or not, or undefined when it does not exist.\n * Used to check references to tables the app or a library created. On\n * Postgres and MySQL a dotted name that is not itself a table, such as\n * Supabase's `auth.users`, is read as `schema.table`, and on Postgres an\n * unqualified name is found through the search path.\n */\nexport async function describeSchemaTable(\n  executor: FarmSchemaExecutor,\n  dialect: FarmSqlDialect,\n  table: string,\n): Promise<FarmSchemaTableDescription | undefined> {\n  const described = await describeTable(executor, dialect, table);\n  if (!described) {\n    if (dialect === \"sqlite\") return undefined;\n    const dot = table.indexOf(\".\");\n    if (dot > 0) {\n      return describeQualifiedTable(executor, dialect, table.slice(0, dot), table.slice(dot + 1));\n    }\n    // An unqualified name resolves through the search path, as the app's own\n    // queries resolve it. Farm creates its tables in the current schema, so\n    // only references to tables it does not create look further.\n    if (dialect === \"postgres\") {\n      const schema = await findOnSearchPath(executor, table);\n      return schema ? describeQualifiedTable(executor, dialect, schema, table) : undefined;\n    }\n    return undefined;\n  }\n  return {\n    columns: described.columns.map(({ name, type, nullable, primaryKey }) => ({\n      name,\n      type,\n      nullable,\n      primaryKey,\n    })),\n  };\n}\n\nasync function describeQualifiedTable(\n  executor: FarmSchemaExecutor,\n  dialect: \"postgres\" | \"mysql\",\n  schema: string,\n  table: string,\n): Promise<FarmSchemaTableDescription | undefined> {\n  const rows = await executor.query(\n    dialect === \"mysql\"\n      ? \"select column_name, column_type as type, is_nullable from information_schema.columns where table_schema = ? and table_name = ? order by ordinal_position\"\n      : \"select column_name, data_type as type, is_nullable from information_schema.columns where table_schema = $1 and table_name = $2 order by ordinal_position\",\n    [schema, table],\n  );\n  if (rows.length === 0) return undefined;\n  return {\n    columns: rows.map((row) => ({\n      name: String(readRowValue(row, \"column_name\")),\n      type: normalizeColumnType(dialect, String(readRowValue(row, \"type\"))),\n      nullable: String(readRowValue(row, \"is_nullable\")).toUpperCase() === \"YES\",\n      primaryKey: false,\n    })),\n  };\n}\n\n/** The first schema on the connection's search path holding this table. */\nasync function findOnSearchPath(\n  executor: FarmSchemaExecutor,\n  table: string,\n): Promise<string | undefined> {\n  const rows = await executor.query(\n    `select namespace.nspname as schema_name\n       from unnest(current_schemas(false)) with ordinality as path(name, position)\n       join pg_namespace namespace on namespace.nspname = path.name\n       join pg_class relation on relation.relnamespace = namespace.oid\n      where relation.relname = $1 and relation.relkind in ('r', 'p', 'v', 'f')\n      order by path.position\n      limit 1`,\n    [table],\n  );\n  const schema = rows[0] && readRowValue(rows[0], \"schema_name\");\n  return schema ? String(schema) : undefined;\n}\n\n/** A normalized table definition, or undefined when the table does not exist. */\nasync function describeTable(\n  executor: FarmSchemaExecutor,\n  dialect: FarmSqlDialect,\n  table: string,\n): Promise<DescribedTable | undefined> {\n  if (dialect === \"sqlite\") {\n    return describeSqliteTable(executor, table);\n  }\n\n  // Postgres binds $1 while MySQL binds ?, and the lookup is scoped to the\n  // schema the migration writes into. Without that scope a same-named table\n  // in another schema - or another database on the same MySQL server -\n  // reports columns for a table that does not exist here, so Farm decides it\n  // already exists and silently skips creating it.\n  const [sql, params]: [string, unknown[]] =\n    dialect === \"mysql\"\n      ? [\n          \"select column_name, data_type, column_type, is_nullable, column_default from information_schema.columns where table_name = ? and table_schema = database() order by ordinal_position\",\n          [table],\n        ]\n      : [\n          \"select column_name, data_type, udt_name, is_nullable, column_default from information_schema.columns where table_name = $1 and table_schema = current_schema() order by ordinal_position\",\n          [table],\n        ];\n  const rows = await executor.query(sql, params);\n  if (rows.length === 0) return undefined;\n\n  const columns: DescribedColumn[] = rows.map((row) => ({\n    name: String(readRowValue(row, \"column_name\")),\n    type: normalizeColumnType(\n      dialect,\n      String(\n        readRowValue(row, dialect === \"mysql\" ? \"column_type\" : \"data_type\") ??\n          readRowValue(row, \"data_type\"),\n      ),\n    ),\n    nullable: String(readRowValue(row, \"is_nullable\")).toUpperCase() === \"YES\",\n    rawDefault: nullableString(readRowValue(row, \"column_default\")),\n    primaryKey: false,\n  }));\n  const indexes = await describeServerIndexes(executor, dialect, table);\n  const primaryColumns = new Set(\n    indexes\n      .filter((index) => index.primary)\n      .flatMap((index) => index.columns.map((column) => column.toLowerCase())),\n  );\n  for (const column of columns) {\n    if (primaryColumns.has(column.name.toLowerCase())) {\n      column.primaryKey = true;\n      column.nullable = false;\n    }\n  }\n\n  return {\n    columns,\n    indexes,\n    references: await describeServerReferences(executor, dialect, table),\n  };\n}\n\nasync function describeSqliteTable(\n  executor: FarmSchemaExecutor,\n  table: string,\n): Promise<DescribedTable | undefined> {\n  const escapedTable = escapeSqlitePragmaValue(table);\n  const rows = await executor.query(`pragma table_info('${escapedTable}')`);\n  if (rows.length === 0) return undefined;\n\n  const columns: DescribedColumn[] = rows.map((row) => {\n    const primaryKey = Number(readRowValue(row, \"pk\") ?? 0) > 0;\n    return {\n      name: String(readRowValue(row, \"name\")),\n      type: normalizeColumnType(\"sqlite\", String(readRowValue(row, \"type\") ?? \"\")),\n      nullable: !primaryKey && Number(readRowValue(row, \"notnull\") ?? 0) === 0,\n      rawDefault: nullableString(readRowValue(row, \"dflt_value\")),\n      primaryKey,\n    };\n  });\n  const indexRows = await executor.query(`pragma index_list('${escapedTable}')`);\n  const indexes: DescribedIndex[] = [];\n\n  for (const row of indexRows) {\n    const name = String(readRowValue(row, \"name\"));\n    const columnRows = await executor.query(\n      `pragma index_info('${escapeSqlitePragmaValue(name)}')`,\n    );\n    indexes.push({\n      name,\n      columns: columnRows\n        .sort(\n          (left, right) =>\n            Number(readRowValue(left, \"seqno\") ?? 0) - Number(readRowValue(right, \"seqno\") ?? 0),\n        )\n        .map((column) => String(readRowValue(column, \"name\"))),\n      unique: asBoolean(readRowValue(row, \"unique\")),\n      primary: String(readRowValue(row, \"origin\") ?? \"\").toLowerCase() === \"pk\",\n    });\n  }\n\n  const referenceRows = await executor.query(`pragma foreign_key_list('${escapedTable}')`);\n  return {\n    columns,\n    indexes,\n    references: referenceRows.map((row) => ({\n      column: String(readRowValue(row, \"from\")),\n      referencedTable: String(readRowValue(row, \"table\")),\n      referencedColumn: String(readRowValue(row, \"to\")),\n      onDelete: normalizeDeleteAction(readRowValue(row, \"on_delete\")),\n    })),\n  };\n}\n\nasync function describeServerIndexes(\n  executor: FarmSchemaExecutor,\n  dialect: Exclude<FarmSqlDialect, \"sqlite\">,\n  table: string,\n): Promise<DescribedIndex[]> {\n  const [sql, params]: [string, unknown[]] =\n    dialect === \"mysql\"\n      ? [\n          \"select index_name, non_unique, column_name, seq_in_index from information_schema.statistics where table_name = ? and table_schema = database() order by index_name, seq_in_index\",\n          [table],\n        ]\n      : [\n          `select index_class.relname as index_name,\n                  index_info.indisunique as is_unique,\n                  index_info.indisprimary as is_primary,\n                  attribute.attname as column_name,\n                  index_key.column_position\n             from pg_catalog.pg_class table_class\n             join pg_catalog.pg_namespace namespace on namespace.oid = table_class.relnamespace\n             join pg_catalog.pg_index index_info on index_info.indrelid = table_class.oid\n             join pg_catalog.pg_class index_class on index_class.oid = index_info.indexrelid\n             join lateral unnest(index_info.indkey) with ordinality as index_key(attnum, column_position) on true\n             left join pg_catalog.pg_attribute attribute\n               on attribute.attrelid = table_class.oid and attribute.attnum = index_key.attnum\n            where table_class.relname = $1\n              and namespace.nspname = current_schema()\n              and index_key.column_position <= index_info.indnkeyatts\n            order by index_class.relname, index_key.column_position`,\n          [table],\n        ];\n  const rows = await executor.query(sql, params);\n  const grouped = new Map<\n    string,\n    DescribedIndex & { orderedColumns: Array<{ position: number; name: string }> }\n  >();\n\n  for (const row of rows) {\n    const name = String(readRowValue(row, \"index_name\"));\n    const index = grouped.get(name) ?? {\n      name,\n      columns: [],\n      unique:\n        dialect === \"mysql\"\n          ? Number(readRowValue(row, \"non_unique\") ?? 1) === 0\n          : asBoolean(readRowValue(row, \"is_unique\")),\n      primary:\n        dialect === \"mysql\"\n          ? name.toUpperCase() === \"PRIMARY\"\n          : asBoolean(readRowValue(row, \"is_primary\")),\n      orderedColumns: [],\n    };\n    const column = readRowValue(row, \"column_name\");\n    if (column !== undefined && column !== null) {\n      index.orderedColumns.push({\n        position: Number(\n          readRowValue(row, dialect === \"mysql\" ? \"seq_in_index\" : \"column_position\") ?? 0,\n        ),\n        name: String(column),\n      });\n    }\n    grouped.set(name, index);\n  }\n\n  return [...grouped.values()].map(({ orderedColumns, ...index }) => ({\n    ...index,\n    columns: orderedColumns\n      .sort((left, right) => left.position - right.position)\n      .map((column) => column.name),\n  }));\n}\n\nasync function describeServerReferences(\n  executor: FarmSchemaExecutor,\n  dialect: Exclude<FarmSqlDialect, \"sqlite\">,\n  table: string,\n): Promise<FarmSchemaReferenceDefinition[]> {\n  const [sql, params]: [string, unknown[]] =\n    dialect === \"mysql\"\n      ? [\n          `select key_columns.column_name,\n                  key_columns.referenced_table_name as referenced_table,\n                  key_columns.referenced_column_name as referenced_column,\n                  referential.delete_rule\n             from information_schema.key_column_usage key_columns\n             join information_schema.referential_constraints referential\n               on referential.constraint_schema = key_columns.constraint_schema\n              and referential.constraint_name = key_columns.constraint_name\n              and referential.table_name = key_columns.table_name\n            where key_columns.table_schema = database()\n              and key_columns.table_name = ?\n              and key_columns.referenced_table_name is not null\n            order by key_columns.constraint_name, key_columns.ordinal_position`,\n          [table],\n        ]\n      : [\n          `select key_columns.column_name,\n                  referenced_columns.table_name as referenced_table,\n                  referenced_columns.column_name as referenced_column,\n                  referential.delete_rule\n             from information_schema.table_constraints constraints\n             join information_schema.key_column_usage key_columns\n               on key_columns.constraint_catalog = constraints.constraint_catalog\n              and key_columns.constraint_schema = constraints.constraint_schema\n              and key_columns.constraint_name = constraints.constraint_name\n             join information_schema.referential_constraints referential\n               on referential.constraint_catalog = constraints.constraint_catalog\n              and referential.constraint_schema = constraints.constraint_schema\n              and referential.constraint_name = constraints.constraint_name\n             join information_schema.constraint_column_usage referenced_columns\n               on referenced_columns.constraint_catalog = referential.unique_constraint_catalog\n              and referenced_columns.constraint_schema = referential.unique_constraint_schema\n              and referenced_columns.constraint_name = referential.unique_constraint_name\n            where constraints.constraint_type = 'FOREIGN KEY'\n              and constraints.table_schema = current_schema()\n              and constraints.table_name = $1\n            order by constraints.constraint_name, key_columns.ordinal_position`,\n          [table],\n        ];\n  const rows = await executor.query(sql, params);\n  return rows.map((row) => ({\n    column: String(readRowValue(row, \"column_name\")),\n    referencedTable: String(readRowValue(row, \"referenced_table\")),\n    referencedColumn: String(readRowValue(row, \"referenced_column\")),\n    onDelete: normalizeDeleteAction(readRowValue(row, \"delete_rule\")),\n  }));\n}\n\nfunction expectedColumnDefinition(\n  field: ResolvedSchemaField,\n  dialect: FarmSqlDialect,\n): FarmSchemaColumnDefinition {\n  return {\n    type: normalizeColumnType(dialect, getSqlColumnType(field, dialect)),\n    nullable: !field.primaryKey && isNullableField(field),\n    default: expectedDefault(field),\n    primaryKey: field.primaryKey === true,\n  };\n}\n\nfunction actualColumnDefinition(\n  column: DescribedColumn,\n  field: ResolvedSchemaField,\n  dialect: FarmSqlDialect,\n): FarmSchemaColumnDefinition {\n  return {\n    type: column.type,\n    nullable: column.nullable,\n    default: normalizeDatabaseDefault(column.rawDefault, field, dialect),\n    primaryKey: column.primaryKey,\n  };\n}\n\nfunction expectedDefault(field: ResolvedSchemaField): string | null {\n  if (field.default === undefined) return null;\n  if (field.type === \"datetime\" && field.default === \"now\") return \"CURRENT_TIMESTAMP\";\n  if (typeof field.default === \"string\") return JSON.stringify(field.default);\n  if (typeof field.default === \"number\" || typeof field.default === \"boolean\") {\n    return String(field.default);\n  }\n  return null;\n}\n\nfunction normalizeDatabaseDefault(\n  value: string | null,\n  field: ResolvedSchemaField,\n  dialect: FarmSqlDialect,\n): string | null {\n  if (value === null) return null;\n  let normalized = stripWrappingParentheses(value.trim());\n  if (dialect === \"postgres\") {\n    normalized = normalized.replace(/::[\\w\\s\"]+$/u, \"\");\n  }\n  if (\n    field.type === \"datetime\" &&\n    /^(?:current_timestamp(?:\\(\\d+\\))?|now\\(\\))$/iu.test(normalized)\n  ) {\n    return \"CURRENT_TIMESTAMP\";\n  }\n  if (field.type === \"boolean\") {\n    const booleanValue = stripSqlQuotes(normalized).toLowerCase();\n    if ([\"1\", \"true\", \"t\", \"b'1'\"].includes(booleanValue)) return \"true\";\n    if ([\"0\", \"false\", \"f\", \"b'0'\"].includes(booleanValue)) return \"false\";\n  }\n  if (field.type === \"integer\" || field.type === \"number\") {\n    return stripSqlQuotes(normalized);\n  }\n  if ([\"id\", \"uuid\", \"string\", \"text\", \"enum\", \"datetime\"].includes(field.type)) {\n    return JSON.stringify(stripSqlQuotes(normalized).replace(/''/gu, \"'\"));\n  }\n  return normalized.toUpperCase();\n}\n\nfunction normalizeColumnType(dialect: FarmSqlDialect, value: string): string {\n  const type = value.trim().toLowerCase().replace(/\\s+/gu, \" \");\n  if (dialect === \"sqlite\") {\n    if (/int/u.test(type)) return \"integer\";\n    if (/(?:char|clob|text)/u.test(type)) return \"text\";\n    if (/(?:real|floa|doub)/u.test(type)) return \"real\";\n    if (/blob/u.test(type) || type === \"\") return \"blob\";\n    return \"numeric\";\n  }\n  if (dialect === \"mysql\") {\n    if (/^(?:bool|boolean|tinyint\\(1\\))/u.test(type)) return \"boolean\";\n    if (/^(?:int|integer)(?:\\(\\d+\\))?/u.test(type)) return \"integer\";\n    if (/^(?:double|double precision)/u.test(type)) return \"double\";\n    return type;\n  }\n  if ([\"int4\", \"integer\"].includes(type)) return \"integer\";\n  if ([\"float8\", \"double precision\"].includes(type)) return \"double precision\";\n  if ([\"timestamptz\", \"timestamp with time zone\"].includes(type)) return \"timestamptz\";\n  return type;\n}\n\nfunction collectExpectedIndexes(model: CollectedSchemaModel): FarmSchemaIndexDefinition[] {\n  const indexes: FarmSchemaIndexDefinition[] = [];\n  for (const field of Object.values(model.model.fields)) {\n    if (field.index) {\n      indexes.push({\n        name: `${model.modelName}_${field.name}_idx`,\n        columns: [field.name],\n        unique: false,\n      });\n    }\n    if (!field.primaryKey && field.unique) {\n      indexes.push({\n        name: `${model.modelName}_${field.name}_unique`,\n        columns: [field.name],\n        unique: true,\n      });\n    }\n  }\n  for (const constraint of model.model.constraints ?? []) {\n    indexes.push({\n      name:\n        constraint.name ??\n        `${model.modelName}_${constraint.fields.map((fieldKey) => model.model.fields[fieldKey]?.name ?? fieldKey).join(\"_\")}_${constraint.type}`,\n      columns: constraint.fields.map((fieldKey) => model.model.fields[fieldKey]?.name ?? fieldKey),\n      unique: constraint.type === \"unique\",\n    });\n  }\n  return indexes;\n}\n\nfunction collectExpectedReferences(\n  model: CollectedSchemaModel,\n  modelLookup: ReadonlyMap<string, CollectedSchemaModel>,\n): FarmSchemaReferenceDefinition[] {\n  const references: FarmSchemaReferenceDefinition[] = [];\n  for (const field of Object.values(model.model.fields)) {\n    if (!field.reference || !isDatabaseEnforcedReference(field.reference)) continue;\n    const target = modelLookup.get(`${model.ownerKey}.${field.reference.model}`);\n    if (!target) continue;\n    references.push({\n      column: field.name,\n      referencedTable: target.modelName,\n      referencedColumn: target.model.fields[field.reference.field]?.name ?? field.reference.field,\n      onDelete: field.reference.onDelete ?? \"noAction\",\n    });\n  }\n  return references;\n}\n\nfunction compareDefinitions<T>(\n  expected: readonly T[],\n  actual: readonly T[],\n  signature: (value: T) => string,\n): { missing: T[]; extra: T[] } {\n  const remaining = [...actual];\n  const missing: T[] = [];\n  for (const expectedValue of expected) {\n    const expectedSignature = signature(expectedValue);\n    const actualIndex = remaining.findIndex(\n      (actualValue) => signature(actualValue) === expectedSignature,\n    );\n    if (actualIndex === -1) missing.push(expectedValue);\n    else remaining.splice(actualIndex, 1);\n  }\n  return { missing, extra: remaining };\n}\n\nfunction indexSignature(index: FarmSchemaIndexDefinition): string {\n  return `${index.unique ? \"unique\" : \"index\"}:${index.columns.map((column) => column.toLowerCase()).join(\",\")}`;\n}\n\nfunction referenceSignature(reference: FarmSchemaReferenceDefinition): string {\n  return [\n    reference.column,\n    reference.referencedTable,\n    reference.referencedColumn,\n    reference.onDelete,\n  ]\n    .map((value) => value.toLowerCase())\n    .join(\":\");\n}\n\nfunction hasSchemaDrift(drift: FarmSchemaDrift): boolean {\n  return (\n    drift.missingColumns.length > 0 ||\n    drift.extraColumns.length > 0 ||\n    drift.changedColumns.length > 0 ||\n    drift.missingIndexes.length > 0 ||\n    drift.extraIndexes.length > 0 ||\n    drift.missingReferences.length > 0 ||\n    drift.extraReferences.length > 0\n  );\n}\n\nfunction readRowValue(row: Record<string, unknown>, name: string): unknown {\n  return row[name] ?? row[name.toUpperCase()];\n}\n\nfunction nullableString(value: unknown): string | null {\n  return value === undefined || value === null ? null : String(value);\n}\n\nfunction asBoolean(value: unknown): boolean {\n  return value === true || value === 1 || value === \"1\" || String(value).toLowerCase() === \"true\";\n}\n\nfunction normalizeDeleteAction(value: unknown): FarmSchemaReferenceDefinition[\"onDelete\"] {\n  switch (\n    String(value ?? \"NO ACTION\")\n      .toUpperCase()\n      .replace(/[_\\s]+/gu, \"\")\n  ) {\n    case \"CASCADE\":\n      return \"cascade\";\n    case \"RESTRICT\":\n      return \"restrict\";\n    case \"SETNULL\":\n      return \"setNull\";\n    default:\n      return \"noAction\";\n  }\n}\n\nfunction stripWrappingParentheses(value: string): string {\n  let result = value;\n  while (result.startsWith(\"(\") && result.endsWith(\")\")) {\n    result = result.slice(1, -1).trim();\n  }\n  return result;\n}\n\nfunction stripSqlQuotes(value: string): string {\n  if (\n    value.length >= 2 &&\n    ((value.startsWith(\"'\") && value.endsWith(\"'\")) ||\n      (value.startsWith('\"') && value.endsWith('\"')))\n  ) {\n    return value.slice(1, -1);\n  }\n  return value;\n}\n\nfunction escapeSqlitePragmaValue(value: string): string {\n  return value.replace(/'/gu, \"''\");\n}\n\nexport type FarmSchemaMigrateResult = {\n  applied: string[];\n  skipped: FarmSchemaDrift[];\n};\n\n/**\n * Run the plan's create statements. Drift is never applied: a plan that reports\n * differences leaves those tables untouched and says so.\n */\nexport async function applySchemaMigration(\n  plan: FarmSchemaMigratePlan,\n  executor: FarmSchemaExecutor,\n): Promise<FarmSchemaMigrateResult> {\n  const applied: string[] = [];\n  // New tables first, then additions to existing ones.\n  for (const statement of [...plan.statements, ...(plan.upgrades ?? [])]) {\n    await executor.execute(statement.sql);\n    applied.push(statement.target);\n  }\n  return { applied, skipped: plan.drift };\n}\n\n/**\n * Column type families a foreign key can join across. Same family is fine\n * (text and varchar, integer and bigint); different families need a cast to\n * join and can never carry a foreign key (text and uuid, text and integer).\n */\n/** @internal */\nexport function columnTypeFamily(type: string): string | undefined {\n  const value = type.trim().toLowerCase();\n  if (/^(bool|boolean|tinyint\\(1\\))/u.test(value)) return \"boolean\";\n  if (value.startsWith(\"uuid\")) return \"uuid\";\n  if (/(char|text|clob|citext|string)/u.test(value)) return \"text\";\n  if (/^(int|integer|smallint|bigint|mediumint|tinyint|int[248]|serial|bigserial)/u.test(value)) {\n    return \"integer\";\n  }\n  if (/^(double|real|float|numeric|decimal|number)/u.test(value)) return \"number\";\n  if (/^(timestamp|datetime|date)/u.test(value)) return \"datetime\";\n  if (value.startsWith(\"json\")) return \"json\";\n  // Enums, domains, arrays, binary: nothing to compare with confidence.\n  return undefined;\n}\n\nexport type FarmSchemaExtensionStatement = FarmSqlStatement & {\n  extension: FarmSchemaExtension;\n  fieldKey: string;\n  column: string;\n};\n\nexport type FarmSchemaExtensionPlan = {\n  /** `ALTER TABLE … ADD COLUMN` for each column the table does not have yet. */\n  statements: FarmSchemaExtensionStatement[];\n  /** Columns already there, as `table.column`. */\n  present: string[];\n  /** Extensions whose table does not exist, so nothing can be added yet. */\n  missingTables: FarmSchemaExtension[];\n  /** Columns that exist with a type the extension does not expect. Left alone. */\n  conflicts: Array<{\n    extension: FarmSchemaExtension;\n    column: string;\n    expected: string;\n    actual: string;\n  }>;\n  /** Columns this database cannot add as declared. */\n  unsupported: Array<{ extension: FarmSchemaExtension; column: string; reason: string }>;\n};\n\n/**\n * Plan the columns owners add to tables they do not own. Only additions:\n * a column that exists is never altered, whatever its definition.\n */\nexport async function planSchemaExtensions(\n  extensions: readonly FarmSchemaExtension[],\n  dialect: FarmSqlDialect,\n  executor: FarmSchemaExecutor,\n): Promise<FarmSchemaExtensionPlan> {\n  const plan: FarmSchemaExtensionPlan = {\n    statements: [],\n    present: [],\n    missingTables: [],\n    conflicts: [],\n    unsupported: [],\n  };\n\n  for (const extension of extensions) {\n    const table = await describeSchemaTable(executor, dialect, extension.table);\n    if (!table) {\n      plan.missingTables.push(extension);\n      continue;\n    }\n\n    for (const { fieldKey, field } of extension.fields) {\n      // Postgres compares quoted names exactly; MySQL and SQLite do not.\n      const existing = table.columns.find((column) =>\n        dialect === \"postgres\"\n          ? column.name === field.name\n          : column.name.toLowerCase() === field.name.toLowerCase(),\n      );\n      const expected = getSqlColumnType(field, dialect);\n\n      if (existing) {\n        const mine = columnTypeFamily(expected);\n        const theirs = columnTypeFamily(existing.type);\n        if (dialect !== \"sqlite\" && mine && theirs && mine !== theirs) {\n          plan.conflicts.push({ extension, column: field.name, expected, actual: existing.type });\n        } else {\n          plan.present.push(`${extension.table}.${field.name}`);\n        }\n        continue;\n      }\n\n      const reason = unsupportedColumnReason(field, dialect);\n      if (reason) {\n        plan.unsupported.push({ extension, column: field.name, reason });\n        continue;\n      }\n\n      plan.statements.push({\n        kind: \"column\",\n        target: `${extension.table}.${field.name}`,\n        sql: addColumnStatement(dialect, extension.table, field),\n        extension,\n        fieldKey,\n        column: field.name,\n      });\n    }\n  }\n  return plan;\n}\n\n/** `ALTER TABLE … ADD COLUMN` for a column that passed `unsupportedColumnReason`. */\nfunction addColumnStatement(dialect: FarmSqlDialect, table: string, field: ResolvedSchemaField) {\n  const defaultValue = getSqlDefaultExpression(field, dialect);\n  const parts = [\n    `ALTER TABLE ${quoteTableName(dialect, table)} ADD COLUMN`,\n    quoteSqlIdentifier(dialect, field.name),\n    getSqlColumnType(field, dialect),\n    ...(isNullableField(field) ? [] : [\"NOT NULL\"]),\n    ...(defaultValue ? [`DEFAULT ${defaultValue}`] : []),\n  ];\n  return `${parts.join(\" \")};`;\n}\n\n/** Why a column cannot be added to a table that may hold rows, if it cannot. */\nfunction unsupportedColumnReason(field: ResolvedSchemaField, dialect: FarmSqlDialect) {\n  const type = getSqlColumnType(field, dialect);\n  const defaultValue = getSqlDefaultExpression(field, dialect);\n  if (dialect === \"mysql\" && defaultValue && (type === \"TEXT\" || type === \"JSON\")) {\n    return `MySQL cannot give a ${type} column a default. Make it nullable without a default.`;\n  }\n  if (dialect === \"sqlite\" && defaultValue === \"CURRENT_TIMESTAMP\") {\n    return \"SQLite cannot add a column whose default is the current time. Make it nullable.\";\n  }\n  if (!isNullableField(field) && !defaultValue) {\n    return \"It is required but its default cannot be written in SQL. Make it nullable.\";\n  }\n  return undefined;\n}\n\n/** A table name for DDL; `schema.table` on Postgres and MySQL, as references read it. */\nfunction quoteTableName(dialect: FarmSqlDialect, table: string) {\n  const dot = table.indexOf(\".\");\n  if (dialect === \"sqlite\" || dot <= 0) return quoteSqlIdentifier(dialect, table);\n  return `${quoteSqlIdentifier(dialect, table.slice(0, dot))}.${quoteSqlIdentifier(dialect, table.slice(dot + 1))}`;\n}\n\n/** Render a plan as a reviewable SQL file. */\nexport function formatSchemaMigration(\n  plan: FarmSchemaMigratePlan,\n  owner: string,\n  options: { addsColumns?: boolean } = {},\n): string {\n  const header = [\n    `-- Generated by \\`farm ${owner} migrate\\` from the ${owner} schema.`,\n    `-- Dialect: ${plan.dialect}`,\n    options.addsColumns || (plan.upgrades?.length ?? 0) > 0\n      ? \"-- Review before applying. Existing tables only get what is added below; nothing is changed or dropped.\"\n      : \"-- Review before applying. Farm never alters existing tables.\",\n  ];\n  const upgrades = plan.upgrades ?? [];\n\n  if (plan.statements.length === 0 && upgrades.length === 0) {\n    header.push(\"--\", \"-- Nothing to create: every declared model already has a table.\");\n    return `${header.join(\"\\n\")}\\n`;\n  }\n\n  const sections = [\n    ...plan.statements.map((statement) => statement.sql),\n    ...(upgrades.length > 0\n      ? [\n          [\n            \"-- Added to tables that already exist:\",\n            ...upgrades.map((statement) => statement.sql),\n          ].join(\"\\n\"),\n        ]\n      : []),\n  ];\n  return `${header.join(\"\\n\")}\\n\\n${sections.join(\"\\n\\n\")}\\n`;\n}\n\n/** Human-readable summary of tables that exist but no longer match the schema. */\nexport function describeSchemaDrift(drift: readonly FarmSchemaDrift[]): string {\n  return drift\n    .map((entry) => {\n      const lines = [`  ${entry.table}`];\n      if (entry.missingColumns.length > 0) {\n        lines.push(`    missing in the database: ${entry.missingColumns.join(\", \")}`);\n      }\n      if (entry.extraColumns.length > 0) {\n        lines.push(`    not in the schema: ${entry.extraColumns.join(\", \")}`);\n      }\n      for (const column of entry.changedColumns) {\n        const differences = column.differences.map((difference) => {\n          if (difference === \"type\") {\n            return `type expected ${column.expected.type}, found ${column.actual.type}`;\n          }\n          if (difference === \"nullability\") {\n            return `nullability expected ${column.expected.nullable ? \"nullable\" : \"required\"}, found ${column.actual.nullable ? \"nullable\" : \"required\"}`;\n          }\n          if (difference === \"default\") {\n            return `default expected ${column.expected.default ?? \"none\"}, found ${column.actual.default ?? \"none\"}`;\n          }\n          return `primary key expected ${column.expected.primaryKey ? \"yes\" : \"no\"}, found ${column.actual.primaryKey ? \"yes\" : \"no\"}`;\n        });\n        lines.push(`    changed column ${column.column}: ${differences.join(\"; \")}`);\n      }\n      if (entry.missingIndexes.length > 0) {\n        lines.push(\n          `    missing indexes: ${entry.missingIndexes.map(formatIndexDefinition).join(\", \")}`,\n        );\n      }\n      if (entry.extraIndexes.length > 0) {\n        lines.push(\n          `    not in the schema indexes: ${entry.extraIndexes.map(formatIndexDefinition).join(\", \")}`,\n        );\n      }\n      if (entry.missingReferences.length > 0) {\n        lines.push(\n          `    missing references: ${entry.missingReferences.map(formatReferenceDefinition).join(\", \")}`,\n        );\n      }\n      if (entry.extraReferences.length > 0) {\n        lines.push(\n          `    not in the schema references: ${entry.extraReferences.map(formatReferenceDefinition).join(\", \")}`,\n        );\n      }\n      return lines.join(\"\\n\");\n    })\n    .join(\"\\n\");\n}\n\nfunction formatIndexDefinition(index: FarmSchemaIndexDefinition): string {\n  return `${index.name} (${index.unique ? \"unique: \" : \"\"}${index.columns.join(\", \")})`;\n}\n\nfunction formatReferenceDefinition(reference: FarmSchemaReferenceDefinition): string {\n  return `${reference.column} -> ${reference.referencedTable}.${reference.referencedColumn} on delete ${reference.onDelete}`;\n}\n\n/**\n * Adapt a raw database client to the executor the planner needs.\n *\n * Each client reports rows differently, so the shape is detected rather than\n * configured: `pg` returns `{ rows }`, `mysql2` returns `[rows]`, and\n * `node:sqlite` exposes prepare/exec. A key-value storage mount has no tables,\n * which is reported as `null` rather than an error.\n */\nexport function createSchemaExecutor(\n  client: unknown,\n  owner: string,\n): { executor: FarmSchemaExecutor; dialect: FarmSqlDialect } | null {\n  const candidate = client as Record<string, any>;\n\n  if (\n    candidate &&\n    typeof candidate.getItem === \"function\" &&\n    typeof candidate.setItem === \"function\"\n  ) {\n    return null;\n  }\n\n  if (typeof candidate?.prepare === \"function\" && typeof candidate?.exec === \"function\") {\n    return {\n      dialect: \"sqlite\",\n      executor: {\n        async execute(sql) {\n          candidate.exec(sql);\n        },\n        async query(sql) {\n          return candidate.prepare(sql).all() as Record<string, unknown>[];\n        },\n      },\n    };\n  }\n\n  if (typeof candidate?.query === \"function\") {\n    // pg and mysql2 both expose query(), so the driver is identified by what\n    // else it carries: mysql2 ships SQL formatting helpers that pg has no\n    // equivalent for. An unidentifiable client stays postgres, the\n    // long-standing default, and an explicit `dialect` on the declaration\n    // overrides this either way.\n    const isMysqlClient =\n      typeof candidate.escapeId === \"function\" || typeof candidate.format === \"function\";\n    return {\n      dialect: isMysqlClient ? \"mysql\" : \"postgres\",\n      executor: {\n        async execute(sql) {\n          await candidate.query(sql);\n        },\n        async query(sql, params) {\n          const result = await candidate.query(sql, params);\n          if (Array.isArray(result)) return (result[0] ?? []) as Record<string, unknown>[];\n          return (result?.rows ?? []) as Record<string, unknown>[];\n        },\n      },\n    };\n  }\n\n  throw new Error(\n    `${owner}: the configured client cannot run migrations. Pass a pg, mysql, or sqlite ` +\n      \"connection, or create the tables with your own migration tooling.\",\n  );\n}\n","import type { FarmSchema } from \"./schema\";\nimport { resolveSchemaModels, type ResolvedSchemaField } from \"./schema-resolve\";\n\n/**\n * Columns an owner adds to a table it does not own: `extend` on a model the\n * owner marks `external` (or does not claim). The app creates the table; the\n * owner only asks for these columns, and only an app that allows it gets them.\n */\nexport type FarmSchemaExtension = {\n  /** The owner's migrate name, such as `loyalty`. */\n  owner: string;\n  /** The owner's name for the model, such as `user`. */\n  modelKey: string;\n  /** The real table, after the app's renames, such as `members_auth`. */\n  table: string;\n  fields: Array<{ fieldKey: string; field: ResolvedSchemaField }>;\n};\n\n/**\n * The extensions in an owner's schema. Throws, naming the column, for a column\n * Farm cannot add safely to a table that may already hold rows.\n */\nexport function collectSchemaExtensions(\n  owner: string,\n  schema: FarmSchema,\n  models?: readonly string[],\n): FarmSchemaExtension[] {\n  if (!schema.extend) return [];\n  const resolved = resolveSchemaModels(owner, schema);\n  const extensions: FarmSchemaExtension[] = [];\n\n  for (const [modelKey, extension] of Object.entries(schema.extend)) {\n    const model = resolved[modelKey];\n    // Extending a table the owner creates just adds to that table.\n    if (!model || (!model.external && (!models || models.includes(modelKey)))) continue;\n\n    const fields = Object.keys(extension.fields ?? {}).map((fieldKey) => {\n      const field = model.fields[fieldKey]!;\n      assertAddableColumn(owner, modelKey, fieldKey, field);\n      return { fieldKey, field };\n    });\n    if (fields.length > 0) {\n      extensions.push({ owner, modelKey, table: model.name, fields });\n    }\n  }\n  return extensions;\n}\n\nfunction assertAddableColumn(\n  owner: string,\n  modelKey: string,\n  fieldKey: string,\n  field: ResolvedSchemaField,\n) {\n  const where = `${owner} adds \"${modelKey}.${fieldKey}\" to a table it does not own`;\n  if (field.primaryKey || field.unique || field.index || field.list) {\n    const what = field.primaryKey\n      ? \"a primary key\"\n      : field.unique\n        ? \"unique\"\n        : field.index\n          ? \"indexed\"\n          : \"a list\";\n    throw new Error(`${where}, which cannot be ${what}. Remove it from the extension.`);\n  }\n  if (field.nullable !== true && field.required !== false && field.default === undefined) {\n    throw new Error(\n      `${where}. The table may already have rows, so the column needs a \\`default\\` or \\`nullable: true\\`.`,\n    );\n  }\n}\n\n/** Whether the app allows an owner to add columns to this table. */\nexport function isSchemaExtensionAllowed(\n  allowExtend: Record<string, readonly string[]> | undefined,\n  extension: Pick<FarmSchemaExtension, \"owner\" | \"modelKey\" | \"table\">,\n): boolean {\n  if (!allowExtend || !Object.prototype.hasOwnProperty.call(allowExtend, extension.owner)) {\n    return false;\n  }\n  const allowed = allowExtend[extension.owner] ?? [];\n  return allowed.includes(extension.modelKey) || allowed.includes(extension.table);\n}\n\n/** The farm.config entry that allows an extension, for messages. */\nexport function describeSchemaExtensionApproval(\n  extension: Pick<FarmSchemaExtension, \"owner\" | \"modelKey\">,\n) {\n  return `schema: { allowExtend: { ${JSON.stringify(extension.owner)}: [${JSON.stringify(extension.modelKey)}] } }`;\n}\n","import type { FarmSchemaExecutor } from \"./schema-migrate\";\nimport { describeSchemaTable } from \"./schema-migrate\";\nimport {\n  escapeSqlString,\n  quoteSqlIdentifier,\n  type CollectedSchemaModel,\n  type FarmSqlDialect,\n} from \"./schema-sql\";\n\n// Values are written as escaped literals: Farm's SQLite executor takes no\n// parameters, and some SQLite drivers refuse to read rows from an INSERT.\nconst literal = (dialect: FarmSqlDialect, value: string | null) =>\n  value === null ? \"NULL\" : `'${escapeSqlString(value, dialect)}'`;\n\n/**\n * What Farm last applied for each owner, kept in the app's database: the\n * owner's version and a snapshot of its tables. Comparing it with what the\n * installed version declares tells the app what an upgrade changes.\n */\nexport const FARM_SCHEMA_STATE_TABLE = \"farm_schema_state\";\n\n/** An owner's tables, in database terms, independent of dialect. */\nexport type FarmSchemaSnapshot = {\n  tables: Record<\n    string,\n    {\n      columns: Record<\n        string,\n        { type: string; nullable: boolean; primaryKey: boolean; unique: boolean; default?: unknown }\n      >;\n      indexes: string[];\n    }\n  >;\n};\n\nexport type FarmSchemaState = {\n  version?: string;\n  snapshot: FarmSchemaSnapshot;\n  appliedAt: string;\n};\n\nexport type FarmSchemaChanges = {\n  addedTables: string[];\n  addedColumns: Array<{ table: string; column: string; type: string }>;\n  addedIndexes: string[];\n  /** Removed or redefined: never applied on their own. */\n  otherChanges: string[];\n  /** Columns the new version no longer has, with their old type. */\n  removedColumns?: Array<{ table: string; column: string; type: string }>;\n};\n\nexport function createSchemaSnapshot(models: readonly CollectedSchemaModel[]): FarmSchemaSnapshot {\n  const tables: FarmSchemaSnapshot[\"tables\"] = {};\n  for (const model of models) {\n    const columns: FarmSchemaSnapshot[\"tables\"][string][\"columns\"] = {};\n    const indexes: string[] = [];\n    for (const field of Object.values(model.model.fields)) {\n      columns[field.name] = {\n        type: field.type,\n        nullable: field.nullable === true || field.required === false,\n        primaryKey: field.primaryKey === true,\n        unique: field.unique === true,\n        ...(field.default !== undefined ? { default: field.default } : {}),\n      };\n      if (field.index) indexes.push(`${model.modelName}_${field.name}_idx`);\n    }\n    for (const constraint of model.model.constraints ?? []) {\n      indexes.push(\n        constraint.name ??\n          `${model.modelName}_${constraint.fields.map((key) => model.model.fields[key]?.name ?? key).join(\"_\")}_${constraint.type}`,\n      );\n    }\n    tables[model.modelName] = { columns, indexes: indexes.sort() };\n  }\n  return { tables };\n}\n\n/** What `next` adds and changes compared with `previous`. */\nexport function diffSchemaSnapshots(\n  previous: FarmSchemaSnapshot,\n  next: FarmSchemaSnapshot,\n): FarmSchemaChanges {\n  const changes: FarmSchemaChanges = {\n    addedTables: [],\n    addedColumns: [],\n    addedIndexes: [],\n    otherChanges: [],\n    removedColumns: [],\n  };\n  for (const [table, definition] of Object.entries(next.tables)) {\n    const before = previous.tables[table];\n    if (!before) {\n      changes.addedTables.push(table);\n      continue;\n    }\n    for (const [column, columnDefinition] of Object.entries(definition.columns)) {\n      const old = before.columns[column];\n      if (!old) {\n        changes.addedColumns.push({ table, column, type: columnDefinition.type });\n      } else if (JSON.stringify(old) !== JSON.stringify(columnDefinition)) {\n        changes.otherChanges.push(`${table}.${column} is redefined`);\n      }\n    }\n    for (const [column, old] of Object.entries(before.columns)) {\n      if (definition.columns[column]) continue;\n      changes.otherChanges.push(`${table}.${column} is removed`);\n      changes.removedColumns!.push({ table, column, type: old.type });\n    }\n    for (const index of definition.indexes) {\n      if (!before.indexes.includes(index)) changes.addedIndexes.push(index);\n    }\n  }\n  for (const table of Object.keys(previous.tables)) {\n    if (!next.tables[table]) changes.otherChanges.push(`${table} is removed`);\n  }\n  return changes;\n}\n\nexport function hasSchemaChanges(changes: FarmSchemaChanges): boolean {\n  return (\n    changes.addedTables.length +\n      changes.addedColumns.length +\n      changes.addedIndexes.length +\n      changes.otherChanges.length >\n    0\n  );\n}\n\n/** The state Farm recorded for an owner, or undefined before the first apply. Read-only. */\nexport async function readSchemaState(\n  executor: FarmSchemaExecutor,\n  dialect: FarmSqlDialect,\n  owner: string,\n): Promise<FarmSchemaState | undefined> {\n  const q = (name: string) => quoteSqlIdentifier(dialect, name);\n  let rows: Array<Record<string, unknown>>;\n  try {\n    if (!(await describeSchemaTable(executor, dialect, FARM_SCHEMA_STATE_TABLE))) return undefined;\n    rows = await executor.query(\n      `SELECT ${q(\"version\")}, ${q(\"snapshot\")}, ${q(\"applied_at\")} FROM ${q(FARM_SCHEMA_STATE_TABLE)} WHERE ${q(\"owner\")} = ${literal(dialect, owner)}`,\n    );\n  } catch {\n    // Unreadable (permissions, a damaged table): as if nothing was recorded.\n    return undefined;\n  }\n  const row = rows[0];\n  if (!row) return undefined;\n  const read = (name: string) => row[name] ?? row[name.toUpperCase()];\n  try {\n    const snapshot = read(\"snapshot\");\n    return {\n      version: read(\"version\") == null ? undefined : String(read(\"version\")),\n      snapshot: (typeof snapshot === \"string\"\n        ? JSON.parse(snapshot)\n        : snapshot) as FarmSchemaSnapshot,\n      appliedAt: String(read(\"applied_at\")),\n    };\n  } catch {\n    return undefined; // A damaged row is treated as no record.\n  }\n}\n\n/** Record what was just applied for an owner. */\nexport async function writeSchemaState(\n  executor: FarmSchemaExecutor,\n  dialect: FarmSqlDialect,\n  owner: string,\n  state: { version?: string; snapshot: FarmSchemaSnapshot },\n): Promise<void> {\n  const q = (name: string) => quoteSqlIdentifier(dialect, name);\n  const key = dialect === \"mysql\" ? \"VARCHAR(191)\" : \"TEXT\";\n  await executor.execute(\n    `CREATE TABLE IF NOT EXISTS ${q(FARM_SCHEMA_STATE_TABLE)} (${q(\"owner\")} ${key} PRIMARY KEY, ${q(\"version\")} ${dialect === \"mysql\" ? \"VARCHAR(255)\" : \"TEXT\"}, ${q(\"snapshot\")} ${dialect === \"mysql\" ? \"LONGTEXT\" : \"TEXT\"} NOT NULL, ${q(\"applied_at\")} ${dialect === \"mysql\" ? \"VARCHAR(64)\" : \"TEXT\"} NOT NULL)`,\n  );\n  const values = [\n    literal(dialect, owner),\n    literal(dialect, state.version ?? null),\n    literal(dialect, JSON.stringify(state.snapshot)),\n    literal(dialect, new Date().toISOString()),\n  ];\n  // Replace the owner's row: delete and insert works on every dialect.\n  await executor.execute(\n    `DELETE FROM ${q(FARM_SCHEMA_STATE_TABLE)} WHERE ${q(\"owner\")} = ${values[0]}`,\n  );\n  await executor.execute(\n    `INSERT INTO ${q(FARM_SCHEMA_STATE_TABLE)} (${q(\"owner\")}, ${q(\"version\")}, ${q(\"snapshot\")}, ${q(\"applied_at\")}) VALUES (${values.join(\", \")})`,\n  );\n}\n\n/** One line per change, for the upgrade summary. */\nexport function describeSchemaChanges(changes: FarmSchemaChanges): string[] {\n  return [\n    ...changes.addedTables.map((table) => `  + ${table}  new table`),\n    ...changes.addedColumns.map(({ table, column, type }) => `  + ${table}.${column}  ${type}`),\n    ...changes.addedIndexes.map((index) => `  + ${index}  index`),\n    ...changes.otherChanges.map((change) => `  ~ ${change}  (Farm will not do this on its own)`),\n  ];\n}\n","import type { FarmSchema } from \"./schema\";\nimport type { FarmSchemaMigrationStep } from \"./schema-step-types\";\nimport { readSchemaState, type FarmSchemaSnapshot } from \"./schema-state\";\nimport { describeSchemaTable, type FarmSchemaExecutor } from \"./schema-migrate\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\nimport {\n  escapeSqlString,\n  quoteSqlIdentifier,\n  type CollectedSchemaModel,\n  type FarmSqlDialect,\n} from \"./schema-sql\";\n\n/** Where Farm records the steps it ran for each owner. */\nexport const FARM_SCHEMA_STEPS_TABLE = \"farm_schema_steps\";\n\nexport type FarmPlannedSchemaStep = {\n  step: FarmSchemaMigrationStep;\n  /** What the step does, in the app's names. */\n  summary: string;\n  phase: \"before\" | \"after\";\n  statements: string[];\n  /**\n   * `run`: pending. `record`: the database already has the step's effect, so\n   * it is only recorded. `blocked`: it cannot run; `reason` says why.\n   */\n  state: \"run\" | \"record\" | \"blocked\";\n  reason?: string;\n  /** Deletes data: runs only with `--allow-destructive`. */\n  destructive?: boolean;\n};\n\nexport type FarmSchemaStepPlan = {\n  steps: FarmPlannedSchemaStep[];\n  /** Steps that ran here before, but whose definition has changed since. */\n  edited: string[];\n  /** Every step, when the tables are being created fresh at this version. */\n  fresh: boolean;\n};\n\n/** Identifies a step's definition, so an edit after it ran is noticed. */\nexport function schemaStepChecksum(step: FarmSchemaMigrationStep): string {\n  const { description: _description, ...definition } = step;\n  // FNV-1a: enough to notice an edit, and free of Node-only imports.\n  let hash = 0x811c9dc5;\n  for (const character of JSON.stringify(definition)) {\n    hash ^= character.codePointAt(0)!;\n    hash = Math.imul(hash, 0x01000193) >>> 0;\n  }\n  return hash.toString(16).padStart(8, \"0\");\n}\n\nexport type { FarmSchemaMigrationStep } from \"./schema-step-types\";\n\nconst literal = (dialect: FarmSqlDialect, value: string) => `'${escapeSqlString(value, dialect)}'`;\n\n/** Step ids recorded for an owner, with their checksums. Read-only. */\nexport async function readAppliedSchemaSteps(\n  executor: FarmSchemaExecutor,\n  dialect: FarmSqlDialect,\n  owner: string,\n): Promise<Map<string, string>> {\n  const applied = new Map<string, string>();\n  try {\n    if (!(await describeSchemaTable(executor, dialect, FARM_SCHEMA_STEPS_TABLE))) return applied;\n    const q = (name: string) => quoteSqlIdentifier(dialect, name);\n    const rows = await executor.query(\n      `SELECT ${q(\"id\")}, ${q(\"checksum\")} FROM ${q(FARM_SCHEMA_STEPS_TABLE)} WHERE ${q(\"owner\")} = ${literal(dialect, owner)}`,\n    );\n    for (const row of rows) {\n      const read = (name: string) => row[name] ?? row[name.toUpperCase()];\n      applied.set(String(read(\"id\")), String(read(\"checksum\")));\n    }\n  } catch {\n    // Unreadable: as if nothing ran, which structured steps then detect.\n  }\n  return applied;\n}\n\nfunction stepsTableStatement(dialect: FarmSqlDialect) {\n  const q = (name: string) => quoteSqlIdentifier(dialect, name);\n  const key = dialect === \"mysql\" ? \"VARCHAR(191)\" : \"TEXT\";\n  return `CREATE TABLE IF NOT EXISTS ${q(FARM_SCHEMA_STEPS_TABLE)} (${q(\"owner\")} ${key} NOT NULL, ${q(\"id\")} ${key} NOT NULL, ${q(\"checksum\")} ${dialect === \"mysql\" ? \"VARCHAR(64)\" : \"TEXT\"} NOT NULL, ${q(\"applied_at\")} ${dialect === \"mysql\" ? \"VARCHAR(64)\" : \"TEXT\"} NOT NULL, PRIMARY KEY (${q(\"owner\")}, ${q(\"id\")}))`;\n}\n\nfunction recordStatement(dialect: FarmSqlDialect, owner: string, step: FarmSchemaMigrationStep) {\n  const q = (name: string) => quoteSqlIdentifier(dialect, name);\n  return `INSERT INTO ${q(FARM_SCHEMA_STEPS_TABLE)} (${q(\"owner\")}, ${q(\"id\")}, ${q(\"checksum\")}, ${q(\"applied_at\")}) VALUES (${[owner, step.id, schemaStepChecksum(step), new Date().toISOString()].map((value) => literal(dialect, value)).join(\", \")})`;\n}\n\n/**\n * The steps still to do for an owner, in order, with the SQL each would run.\n * Structured steps look at the database first: a rename already done, by an\n * earlier release of Farm or by hand, is only recorded.\n */\nexport async function planSchemaSteps(input: {\n  owner: string;\n  schema: FarmSchema;\n  steps: readonly FarmSchemaMigrationStep[];\n  dialect: FarmSqlDialect;\n  executor: FarmSchemaExecutor;\n  applied: ReadonlyMap<string, string>;\n  /** None of the owner's tables exist and nothing was recorded. */\n  fresh: boolean;\n  /** The tables Farm last recorded this owner having: the only ones a step may drop from. */\n  recorded?: FarmSchemaSnapshot;\n  /** Tables other owners create, which no step of this owner may drop. */\n  othersTables?: ReadonlySet<string>;\n}): Promise<FarmSchemaStepPlan> {\n  const { owner, dialect, executor, applied } = input;\n  const plan: FarmSchemaStepPlan = { steps: [], edited: [], fresh: input.fresh };\n  const models = resolveSchemaModels(owner, input.schema);\n  const q = (name: string) => quoteSqlIdentifier(dialect, name);\n  const columnsOf = async (table: string) =>\n    (await describeSchemaTable(executor, dialect, table))?.columns.map((column) => column.name);\n  const has = (columns: readonly string[] | undefined, name: string) =>\n    Boolean(\n      columns?.some((column) =>\n        dialect === \"postgres\" ? column === name : column.toLowerCase() === name.toLowerCase(),\n      ),\n    );\n\n  for (const step of input.steps) {\n    const recorded = applied.get(step.id);\n    if (recorded !== undefined) {\n      if (recorded !== schemaStepChecksum(step)) plan.edited.push(step.id);\n      continue;\n    }\n    if (input.fresh) {\n      // Created at this version, the tables already have every step's effect.\n      plan.steps.push({\n        step,\n        summary: summarize(step, models),\n        phase: \"before\",\n        statements: [],\n        state: \"record\",\n      });\n      continue;\n    }\n\n    if (\"renameColumn\" in step) {\n      const table = models[step.renameColumn.model]!.name;\n      const to = models[step.renameColumn.model]!.fields[step.renameColumn.to]!.name;\n      const from = step.renameColumn.from;\n      const columns = await columnsOf(table);\n      const summary = `rename ${table}.${from} → ${table}.${to}`;\n      const planned: FarmPlannedSchemaStep = {\n        step,\n        summary,\n        phase: \"before\",\n        statements: [`ALTER TABLE ${q(table)} RENAME COLUMN ${q(from)} TO ${q(to)}`],\n        state: \"run\",\n      };\n      if (!columns) {\n        Object.assign(planned, { state: \"blocked\", reason: `\"${table}\" does not exist.` });\n      } else if (has(columns, from) && has(columns, to)) {\n        Object.assign(planned, {\n          state: \"blocked\",\n          reason: `both \"${from}\" and \"${to}\" exist, so renaming would lose one. Move the data and drop one column yourself.`,\n        });\n      } else if (!has(columns, from)) {\n        Object.assign(planned, {\n          state: has(columns, to) ? \"record\" : \"blocked\",\n          statements: [],\n          ...(has(columns, to) ? {} : { reason: `\"${table}\" has neither \"${from}\" nor \"${to}\".` }),\n        });\n      }\n      plan.steps.push(planned);\n    } else if (\"renameTable\" in step) {\n      const to = models[step.renameTable.to]!.name;\n      const from = step.renameTable.from;\n      const summary = `rename table ${from} → ${to}`;\n      const [hasFrom, hasTo] = [Boolean(await columnsOf(from)), Boolean(await columnsOf(to))];\n      plan.steps.push({\n        step,\n        summary,\n        phase: \"before\",\n        statements:\n          hasFrom && !hasTo\n            ? [\n                dialect === \"mysql\"\n                  ? `RENAME TABLE ${q(from)} TO ${q(to)}`\n                  : `ALTER TABLE ${q(from)} RENAME TO ${q(to)}`,\n              ]\n            : [],\n        state: hasFrom && !hasTo ? \"run\" : hasTo && !hasFrom ? \"record\" : \"blocked\",\n        ...(hasFrom && hasTo\n          ? { reason: `both \"${from}\" and \"${to}\" exist, so renaming would lose one.` }\n          : !hasFrom && !hasTo\n            ? { reason: `neither \"${from}\" nor \"${to}\" exists.` }\n            : {}),\n      });\n    } else if (\"dropColumn\" in step) {\n      const table = models[step.dropColumn.model]!.name;\n      const column = step.dropColumn.column;\n      const columns = await columnsOf(table);\n      const summary = `drop ${table}.${column}`;\n      const created = Boolean(input.recorded?.tables[table]?.columns[column]);\n      const planned: FarmPlannedSchemaStep = {\n        step,\n        summary,\n        phase: \"before\",\n        statements: [`ALTER TABLE ${q(table)} DROP COLUMN ${q(column)}`],\n        state: \"run\",\n        destructive: true,\n      };\n      if (!columns) {\n        Object.assign(planned, { state: \"blocked\", reason: `\"${table}\" does not exist.` });\n      } else if (!has(columns, column)) {\n        Object.assign(planned, { state: \"record\", statements: [] });\n      } else if (!created) {\n        Object.assign(planned, {\n          state: \"blocked\",\n          reason: `Farm has no record of ${owner} creating \"${table}.${column}\", so it will not drop it. Drop it yourself if it is no longer needed.`,\n        });\n      }\n      plan.steps.push(planned);\n    } else if (\"dropTable\" in step) {\n      const table = step.dropTable.table;\n      const exists = Boolean(await columnsOf(table));\n      const created = Boolean(input.recorded?.tables[table]);\n      const ownedElsewhere = [...(input.othersTables ?? [])].some(\n        (other) => other.toLowerCase() === table.toLowerCase(),\n      );\n      plan.steps.push({\n        step,\n        summary: `drop table ${table}`,\n        phase: \"before\",\n        statements: exists ? [`DROP TABLE ${q(table)}`] : [],\n        destructive: true,\n        ...(!exists\n          ? { state: \"record\" as const }\n          : ownedElsewhere\n            ? {\n                state: \"blocked\" as const,\n                reason: `another plugin creates \"${table}\", so ${owner} will not drop it.`,\n              }\n            : !created\n              ? {\n                  state: \"blocked\" as const,\n                  reason: `Farm has no record of ${owner} creating \"${table}\", so it will not drop it. Drop it yourself if it is no longer needed.`,\n                }\n              : { state: \"run\" as const }),\n      });\n    } else {\n      const sql = step.sql[dialect];\n      const statements = sql === undefined ? [] : typeof sql === \"string\" ? [sql] : [...sql];\n      plan.steps.push({\n        step,\n        summary: step.description ?? `custom SQL (${step.id})`,\n        phase: step.before ? \"before\" : \"after\",\n        statements,\n        state: sql === undefined ? \"blocked\" : \"run\",\n        ...(sql === undefined ? { reason: `it has no SQL for ${dialect}.` } : {}),\n      });\n    }\n  }\n  return plan;\n}\n\nfunction summarize(step: FarmSchemaMigrationStep, models: ReturnType<typeof resolveSchemaModels>) {\n  if (\"renameColumn\" in step) {\n    const model = models[step.renameColumn.model]!;\n    return `rename ${model.name}.${step.renameColumn.from} → ${model.name}.${model.fields[step.renameColumn.to]!.name}`;\n  }\n  if (\"renameTable\" in step) {\n    return `rename table ${step.renameTable.from} → ${models[step.renameTable.to]!.name}`;\n  }\n  if (\"dropColumn\" in step) {\n    return `drop ${models[step.dropColumn.model]!.name}.${step.dropColumn.column}`;\n  }\n  if (\"dropTable\" in step) return `drop table ${step.dropTable.table}`;\n  return step.description ?? `custom SQL (${step.id})`;\n}\n\n/**\n * Run one planned step and record it, as a single transaction where the\n * database allows: Postgres runs several statements sent together as one\n * implicit transaction, and SQLite takes BEGIN and COMMIT on its single\n * connection. MySQL commits schema changes immediately, so a failed step\n * there can leave its earlier statements applied.\n */\nexport async function runSchemaStep(\n  executor: FarmSchemaExecutor,\n  dialect: FarmSqlDialect,\n  owner: string,\n  planned: FarmPlannedSchemaStep,\n): Promise<void> {\n  await executor.execute(stepsTableStatement(dialect));\n  const statements = [\n    ...(planned.state === \"run\" ? planned.statements : []),\n    recordStatement(dialect, owner, planned.step),\n  ];\n  if (dialect === \"postgres\") {\n    await executor.execute(\n      statements.map((statement) => statement.replace(/;\\s*$/u, \"\")).join(\";\\n\"),\n    );\n    return;\n  }\n  if (dialect === \"sqlite\") {\n    await executor.execute(\"BEGIN\");\n    try {\n      for (const statement of statements) await executor.execute(statement);\n      await executor.execute(\"COMMIT\");\n    } catch (error) {\n      await executor.execute(\"ROLLBACK\").catch(() => {});\n      throw error;\n    }\n    return;\n  }\n  for (const statement of statements) await executor.execute(statement);\n}\n\n/** Copies of the models without what pending renames will produce. */\nexport function withoutRenameTargets(\n  models: CollectedSchemaModel[],\n  stepPlan: FarmSchemaStepPlan | undefined,\n): CollectedSchemaModel[] {\n  const pending = (stepPlan?.steps ?? []).filter((planned) => planned.state === \"run\");\n  if (pending.length === 0) return models;\n  const tables = new Set<string>();\n  const columns = new Map<string, Set<string>>();\n  for (const { step } of pending) {\n    if (\"renameTable\" in step) tables.add(step.renameTable.to);\n    if (\"renameColumn\" in step) {\n      const set = columns.get(step.renameColumn.model) ?? new Set();\n      set.add(step.renameColumn.to);\n      columns.set(step.renameColumn.model, set);\n    }\n  }\n  return models\n    .filter((model) => !tables.has(model.modelKey))\n    .map((model) => {\n      const skip = columns.get(model.modelKey);\n      if (!skip) return model;\n      const fields = Object.fromEntries(\n        Object.entries(model.model.fields).filter(([key]) => !skip.has(key)),\n      );\n      return { ...model, model: { ...model.model, fields } };\n    });\n}\n\n/**\n * The step plan for an owner as migrate and the check see it: what ran is\n * read from the database, and a database holding none of the owner's tables,\n * old names included, is a fresh install.\n */\nexport async function planOwnerSchemaSteps(input: {\n  owner: string;\n  schema: FarmSchema;\n  steps: readonly FarmSchemaMigrationStep[];\n  tables: readonly string[];\n  dialect: FarmSqlDialect;\n  executor: FarmSchemaExecutor;\n  /** No record is kept (an ORM owns the tables), so nothing is read. */\n  readApplied?: boolean;\n  /** Tables other owners create, which this owner's steps may not drop. */\n  othersTables?: ReadonlySet<string>;\n}): Promise<FarmSchemaStepPlan> {\n  const applied =\n    input.readApplied === false\n      ? new Map<string, string>()\n      : await readAppliedSchemaSteps(input.executor, input.dialect, input.owner);\n  const candidates = [\n    ...input.tables,\n    ...input.steps.flatMap((step) => (\"renameTable\" in step ? [step.renameTable.from] : [])),\n  ];\n  let fresh = applied.size === 0;\n  for (const table of candidates) {\n    if (!fresh) break;\n    if (await describeSchemaTable(input.executor, input.dialect, table)) fresh = false;\n  }\n  const recorded =\n    input.readApplied === false\n      ? undefined\n      : (await readSchemaState(input.executor, input.dialect, input.owner))?.snapshot;\n  return planSchemaSteps({ ...input, applied, fresh, recorded });\n}\n","import type { FarmSchemaExecutor } from \"./schema-migrate\";\nimport { columnTypeFamily, describeSchemaTable } from \"./schema-migrate\";\nimport type { FarmSchemaReference } from \"./schema\";\nimport { isDatabaseEnforcedReference } from \"./schema-reference\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\nimport { collectSchemaModels, getSqlColumnType, type FarmSqlDialect } from \"./schema-sql\";\nimport type { FarmSchemaTablesDeclaration } from \"./schema-owner\";\n\n/** A reference from one plugin's table to a table another plugin creates. */\nexport type FarmCrossOwnerReference = {\n  /** The owner whose table holds the reference. */\n  owner: string;\n  modelKey: string;\n  fieldKey: string;\n  table: string;\n  column: string;\n  referencedOwner: string;\n  referencedTable: string;\n  referencedColumn: string;\n  onDelete: NonNullable<FarmSchemaReference[\"onDelete\"]>;\n};\n\nexport type FarmCrossOwnerReferencePlan = {\n  /** A foreign key can be created for these: same database, compatible key. */\n  eligible: FarmCrossOwnerReference[];\n  /** The referenced table does not exist here yet; migrate its owner first. */\n  waiting: FarmCrossOwnerReference[];\n  /** Never a foreign key, and why. These stay as they are today. */\n  skipped: Array<{ reference: FarmCrossOwnerReference; reason: string }>;\n};\n\n/**\n * Which of an owner's references to other owners' tables can carry a real\n * foreign key. Only tables a Farm owner creates qualify, never the app's own:\n * a constraint on the app's table would change how the app deletes its rows.\n * The referenced table must be in this owner's database, the referenced\n * column must be its primary key or unique, and the column types must match.\n */\nexport async function planCrossOwnerReferences(\n  owner: Pick<FarmSchemaTablesDeclaration, \"name\" | \"schema\" | \"models\">,\n  others: readonly Pick<FarmSchemaTablesDeclaration, \"name\" | \"schema\" | \"models\">[],\n  dialect: FarmSqlDialect,\n  executor: FarmSchemaExecutor,\n): Promise<FarmCrossOwnerReferencePlan> {\n  const plan: FarmCrossOwnerReferencePlan = { eligible: [], waiting: [], skipped: [] };\n  const own = resolveSchemaModels(owner.name, owner.schema);\n  const creators = new Map<\n    string,\n    { owner: string; model: ReturnType<typeof collectSchemaModels>[number] }\n  >();\n  const byKey = new Map<string, ReturnType<typeof collectSchemaModels>[number]>();\n  for (const other of others) {\n    if (other.name === owner.name) continue;\n    try {\n      for (const model of collectSchemaModels([[other.name, other.schema, other.models]])) {\n        creators.set(model.modelName.toLowerCase(), { owner: other.name, model });\n        byKey.set(model.modelKey, model);\n      }\n    } catch {\n      // An invalid schema is reported by the check; it offers no keys.\n    }\n  }\n\n  for (const model of collectSchemaModels([[owner.name, owner.schema, owner.models]])) {\n    for (const [fieldKey, field] of Object.entries(model.model.fields)) {\n      const reference = field.reference;\n      if (!reference || !isDatabaseEnforcedReference(reference)) continue;\n      // Resolved the way the check resolves it: the owner's own description\n      // first, then a model another owner creates.\n      const described = Object.prototype.hasOwnProperty.call(own, reference.model)\n        ? own[reference.model]!.name\n        : byKey.get(reference.model)?.modelName;\n      const creator = described ? creators.get(described.toLowerCase()) : undefined;\n      if (!creator) continue; // The app's table, or nobody's: stays a comment.\n\n      const target = Object.entries(creator.model.model.fields).find(\n        ([key, candidate]) => key === reference.field || candidate.name === reference.field,\n      )?.[1];\n      const entry: FarmCrossOwnerReference = {\n        owner: owner.name,\n        modelKey: model.modelKey,\n        fieldKey,\n        table: model.modelName,\n        column: field.name,\n        referencedOwner: creator.owner,\n        referencedTable: creator.model.modelName,\n        referencedColumn: target?.name ?? reference.field,\n        onDelete: reference.onDelete ?? \"noAction\",\n      };\n\n      if (!target || !(target.primaryKey || target.unique)) {\n        plan.skipped.push({\n          reference: entry,\n          reason: `\"${entry.referencedTable}.${entry.referencedColumn}\" is not its primary key or unique.`,\n        });\n        continue;\n      }\n      const mine = columnTypeFamily(getSqlColumnType(field, dialect));\n      const theirs = columnTypeFamily(getSqlColumnType(target, dialect));\n      if (dialect !== \"sqlite\" && mine !== theirs) {\n        plan.skipped.push({ reference: entry, reason: \"the column types differ.\" });\n        continue;\n      }\n      const table = await describeSchemaTable(executor, dialect, entry.referencedTable);\n      if (!table) {\n        plan.waiting.push(entry);\n        continue;\n      }\n      const column = table.columns.find((candidate) =>\n        dialect === \"postgres\"\n          ? candidate.name === entry.referencedColumn\n          : candidate.name.toLowerCase() === entry.referencedColumn.toLowerCase(),\n      );\n      if (!column) {\n        plan.skipped.push({\n          reference: entry,\n          reason: `\"${entry.referencedTable}\" has no column \"${entry.referencedColumn}\".`,\n        });\n        continue;\n      }\n      plan.eligible.push(entry);\n    }\n  }\n  return plan;\n}\n\n/** Whether the app allows foreign keys to be added to an owner's existing table. */\nexport function isForeignKeyAllowed(\n  allowForeignKeys: Record<string, readonly string[]> | undefined,\n  reference: Pick<FarmCrossOwnerReference, \"owner\" | \"modelKey\" | \"table\">,\n): boolean {\n  if (\n    !allowForeignKeys ||\n    !Object.prototype.hasOwnProperty.call(allowForeignKeys, reference.owner)\n  ) {\n    return false;\n  }\n  const allowed = allowForeignKeys[reference.owner] ?? [];\n  return allowed.includes(reference.modelKey) || allowed.includes(reference.table);\n}\n\n/** The farm.config entry that allows it, for messages. */\nexport function describeForeignKeyApproval(\n  reference: Pick<FarmCrossOwnerReference, \"owner\" | \"modelKey\">,\n) {\n  return `schema: { allowForeignKeys: { ${JSON.stringify(reference.owner)}: [${JSON.stringify(reference.modelKey)}] } }`;\n}\n","import type { FarmSchema } from \"./schema\";\nimport type { FarmSqlDialect } from \"./schema-sql\";\nimport type { FarmSchemaMigrationStep } from \"./schema-step-types\";\n\n// How Farm records which tables a plugin or integration owns. Internal: plugins\n// set `schema` on definePlugin. Kept apart from schema-tables.ts, which pulls\n// in migration and SQL code, so definePlugin loads none of it.\n\n/**\n * Attached to a plugin or integration to say \"I own these tables\".\n *\n * Read by tooling so it can reach an already-resolved schema and connection\n * instead of re-reading and re-validating configuration.\n *\n * @internal\n */\nexport const FARM_SCHEMA_TABLES = Symbol.for(\"farm.schema-tables\");\n\n/** @internal What `definePlugin({ schema })` records on a plugin. */\nexport interface FarmSchemaTablesDeclaration {\n  /** Command namespace: this is the `<name>` in `farm <name> migrate`. */\n  name: string;\n  /** The schema whose models this owner stores. */\n  schema: FarmSchema;\n  /**\n   * Model keys this owner actually controls. Defaults to every model in the\n   * schema; narrow it when an app shares one schema with the rest of its code.\n   */\n  models?: readonly string[];\n  /**\n   * Resolves the configured database client, or the storage mount behind it.\n   *\n   * The app's resolved config is passed because an owner may read its\n   * connection from there rather than from its own options — an integration\n   * configured through `storage.client`, for example.\n   */\n  resolveClient(config: FarmSchemaOwnerConfig): Promise<unknown>;\n  /** Set explicitly when the client's dialect cannot be detected. */\n  dialect?: FarmSqlDialect;\n  /** Owners whose tables must exist first, by owner name. */\n  dependsOn?: readonly string[];\n  /** The owner's release, shown when an upgrade changes its tables. */\n  version?: string;\n  /** Ordered steps for changes Farm does not infer, such as renames. */\n  migrations?: readonly FarmSchemaMigrationStep[];\n}\n\n/**\n * Record that a plugin or integration owns tables, so `farm <name> migrate`,\n * `farm generate`, and `farm schema check` find them.\n *\n * @internal Not part of the plugin API: plugins set `schema` (and `database`)\n * on `definePlugin`, which calls this. Exported for Farm's own packages and for\n * code written against earlier betas.\n *\n * The declaration is non-enumerable, so it never reaches a config serializer or\n * a plugin's own option spreading.\n */\nexport function declareSchemaTables<TTarget extends object>(\n  target: TTarget,\n  declaration: FarmSchemaTablesDeclaration,\n): TTarget {\n  Object.defineProperty(target, FARM_SCHEMA_TABLES, {\n    value: declaration,\n    enumerable: false,\n    configurable: true,\n  });\n  return target;\n}\n\n/** @internal The declaration on a plugin, when it has one. */\nexport function readSchemaTables(candidate: unknown): FarmSchemaTablesDeclaration | undefined {\n  if (!candidate || (typeof candidate !== \"object\" && typeof candidate !== \"function\")) {\n    return undefined;\n  }\n  return (candidate as Record<symbol, FarmSchemaTablesDeclaration>)[FARM_SCHEMA_TABLES];\n}\n\n/** What an owner may read when resolving its client. */\nexport type FarmSchemaOwnerConfig = {\n  storage?: unknown;\n  integrations?: Record<string, unknown> | readonly unknown[];\n  [key: string]: unknown;\n};\n","import type { FarmSchemaConfig } from \"./schema\";\nimport {\n  collectSchemaExtensions,\n  describeSchemaExtensionApproval,\n  isSchemaExtensionAllowed,\n} from \"./schema-extend\";\nimport {\n  planOwnerSchemaSteps,\n  withoutRenameTargets,\n  runSchemaStep,\n  type FarmPlannedSchemaStep,\n  type FarmSchemaStepPlan,\n} from \"./schema-steps\";\nimport {\n  FARM_SCHEMA_STATE_TABLE,\n  createSchemaSnapshot,\n  describeSchemaChanges,\n  diffSchemaSnapshots,\n  hasSchemaChanges,\n  readSchemaState,\n  writeSchemaState,\n  type FarmSchemaChanges,\n} from \"./schema-state\";\nimport {\n  describeForeignKeyApproval,\n  isForeignKeyAllowed,\n  planCrossOwnerReferences,\n  type FarmCrossOwnerReference,\n} from \"./schema-foreign-keys\";\nimport {\n  applySchemaMigration,\n  createSchemaExecutor,\n  describeSchemaDrift,\n  formatSchemaMigration,\n  planSchemaExtensions,\n  planSchemaMigration,\n  type FarmSchemaExtensionPlan,\n  type FarmSchemaAddableForeignKey,\n  type FarmSchemaExecutor,\n  type FarmSchemaExtensionStatement,\n  type FarmSchemaMigratePlan,\n} from \"./schema-migrate\";\nimport {\n  collectSchemaModels,\n  quoteSqlIdentifier,\n  type CollectedSchemaModel,\n  type FarmSqlDialect,\n} from \"./schema-sql\";\nimport {\n  readSchemaTables,\n  type FarmSchemaOwnerConfig,\n  type FarmSchemaTablesDeclaration,\n} from \"./schema-owner\";\n\nexport {\n  declareSchemaTables,\n  FARM_SCHEMA_TABLES,\n  readSchemaTables,\n  type FarmSchemaOwnerConfig,\n  type FarmSchemaTablesDeclaration,\n} from \"./schema-owner\";\n\n/**\n * Every table owner an app has configured.\n *\n * Plugins and integrations are both searched, because either can own storage.\n */\nexport function findSchemaTableOwners(config: {\n  plugins?: readonly unknown[];\n  integrations?: Record<string, unknown> | readonly unknown[];\n}): FarmSchemaTablesDeclaration[] {\n  const integrations = config.integrations;\n  const candidates = [\n    ...(config.plugins ?? []),\n    ...(Array.isArray(integrations) ? integrations : Object.values(integrations ?? {})),\n  ];\n\n  const owners: FarmSchemaTablesDeclaration[] = [];\n  for (const candidate of candidates) {\n    const declaration = readSchemaTables(candidate);\n    // An integration may contribute plugins; its tables can be declared on\n    // either, so both are checked and duplicates collapse by name.\n    if (declaration && !owners.some((owner) => owner.name === declaration.name)) {\n      owners.push(declaration);\n    }\n  }\n  return owners;\n}\n\n/** Resolve one owner's declaration into the models tooling works with. */\nexport function collectOwnerModels(owner: FarmSchemaTablesDeclaration): CollectedSchemaModel[] {\n  return collectSchemaModels([[owner.name, owner.schema, owner.models]]);\n}\n\nexport interface MigrateSchemaTablesOptions {\n  /** The app's resolved config, handed to the owner's `resolveClient`. */\n  config?: FarmSchemaOwnerConfig;\n  /** Write the plan to this path instead of applying it. */\n  write?: string;\n  /** Execute the plan. */\n  apply?: boolean;\n  /**\n   * What to do with columns the owner adds to tables it does not own.\n   * `\"report\"` when the app's ORM owns those tables: they are never altered,\n   * only reported, so the ORM's migrations stay the source of truth.\n   */\n  extensions?: \"apply\" | \"report\";\n  /** Run migration steps that delete data, such as dropping a column. */\n  allowDestructive?: boolean;\n  log?: (message: string) => void;\n}\n\nexport interface MigrateSchemaTablesResult {\n  plan: FarmSchemaMigratePlan;\n  sql: string;\n  applied: string[];\n  /** Foreign keys to other owners' tables that this run did not create. */\n  foreignKeys: {\n    /** The other owner has not created its table yet. */\n    waiting: FarmCrossOwnerReference[];\n    /** On an existing table, not allowed in `schema.allowForeignKeys`. */\n    unapproved: FarmSchemaAddableForeignKey[];\n    /** On an existing SQLite table, which cannot get one. */\n    unsupported: FarmSchemaAddableForeignKey[];\n    /** Allowed, but rows already point at nothing. */\n    blocked: Array<{ key: FarmSchemaAddableForeignKey; orphans: number }>;\n  };\n  /** What the installed version changes compared with the last applied one. */\n  upgrade?: { from?: string; to?: string; changes: FarmSchemaChanges };\n  /** The owner's migration steps: what ran now, and what is still to do. */\n  steps: { plan?: FarmSchemaStepPlan; ran: string[]; pending: string[] };\n  /** Statements and steps `--apply` would run. */\n  planned: number;\n  /** Columns the owner adds to tables it does not own. */\n  extensions: FarmSchemaExtensionPlan & {\n    /** Additions the app has not allowed in `schema.allowExtend`. */\n    unapproved: FarmSchemaExtensionStatement[];\n    /** `table.column` still missing after this run, whatever the reason. */\n    pending: string[];\n  };\n}\n\nconst emptyExtensionPlan = (): FarmSchemaExtensionPlan => ({\n  statements: [],\n  present: [],\n  missingTables: [],\n  conflicts: [],\n  unsupported: [],\n});\n\n/**\n * Plan, and optionally apply, the tables one owner needs.\n *\n * Nothing is executed unless `apply` is set: the default is to hand back sql a\n * person can read before it touches a database. Columns added to tables the\n * owner does not own also need the app's `schema.allowExtend`.\n */\nexport async function migrateSchemaTables(\n  owner: FarmSchemaTablesDeclaration,\n  options: MigrateSchemaTablesOptions = {},\n): Promise<MigrateSchemaTablesResult> {\n  const log = options.log ?? (() => {});\n  const client = await owner.resolveClient(options.config ?? {});\n  const adapter = createSchemaExecutor(client, owner.name);\n\n  if (!adapter) {\n    log(\n      `Nothing to create: ${owner.name} stores data through a storage mount, which has no tables.`,\n    );\n    return {\n      plan: { dialect: \"sqlite\", statements: [], upToDate: [], drift: [] },\n      sql: \"\",\n      applied: [],\n      extensions: { ...emptyExtensionPlan(), unapproved: [], pending: [] },\n      foreignKeys: { waiting: [], unapproved: [], unsupported: [], blocked: [] },\n      steps: { ran: [], pending: [] },\n      planned: 0,\n    };\n  }\n\n  const { executor } = adapter;\n  const dialect = owner.dialect ?? adapter.dialect;\n  const schemaConfig = options.config?.schema as FarmSchemaConfig | undefined;\n  const reportOnly = options.extensions === \"report\";\n  const applying = Boolean(options.apply) && !reportOnly;\n\n  // Migration steps the owner ships: renames run before anything is planned,\n  // so a renamed column is never mistaken for one removed and one added.\n  const steps = owner.migrations ?? [];\n  let stepPlan: FarmSchemaStepPlan | undefined;\n  const stepsRan: string[] = [];\n  let stepsStopped: FarmPlannedSchemaStep | undefined;\n  if (steps.length > 0) {\n    const othersTables = new Set(\n      (options.config ? findSchemaTableOwners(options.config as never) : [])\n        .filter((other) => other.name !== owner.name)\n        .flatMap((other) => {\n          try {\n            return collectOwnerModels(other).map((model) => model.modelName);\n          } catch {\n            return [];\n          }\n        }),\n    );\n    stepPlan = await planOwnerSchemaSteps({\n      owner: owner.name,\n      schema: owner.schema,\n      steps,\n      tables: collectOwnerModels(owner).map((model) => model.modelName),\n      dialect,\n      executor,\n      readApplied: !reportOnly,\n      othersTables,\n    });\n    for (const id of stepPlan.edited) {\n      log(\n        `Migration step \"${id}\" changed after it ran here. Farm never runs a step twice; review the change yourself.`,\n      );\n    }\n  }\n  const runSteps = async (phase: \"before\" | \"after\") => {\n    for (const planned of stepPlan?.steps ?? []) {\n      if (stepsStopped) return;\n      if (planned.phase !== phase) continue;\n      if (planned.state === \"run\" && planned.destructive && !options.allowDestructive) {\n        stepsStopped = planned;\n        log(\n          `Stopped at migration step \"${planned.step.id}\" (${planned.summary}): it deletes data. Run again with --allow-destructive to let it. Later steps wait.`,\n        );\n        return;\n      }\n      if (planned.state === \"blocked\") {\n        stepsStopped = planned;\n        log(\n          `Stopped at migration step \"${planned.step.id}\" (${planned.summary}): ${planned.reason} Later steps wait for it.`,\n        );\n        return;\n      }\n      await runSchemaStep(executor, dialect, owner.name, planned);\n      stepsRan.push(planned.step.id);\n    }\n  };\n  if (applying) await runSteps(\"before\");\n\n  // References to other plugins' tables get a real foreign key when it is\n  // safe: inline for a table created now, with approval for an existing one.\n  const models = collectOwnerModels(owner);\n  // Planned without the columns and tables a pending rename will produce:\n  // until it runs they are missing, and adding them would strand the data.\n  const planningModels = applying ? models : withoutRenameTargets(models, stepPlan);\n  const others = options.config ? findSchemaTableOwners(options.config as never) : [];\n  const crossOwner = await planCrossOwnerReferences(owner, others, dialect, executor);\n  for (const reference of crossOwner.eligible) {\n    const model = planningModels.find((candidate) => candidate.modelKey === reference.modelKey);\n    if (!model) continue;\n    (model.foreignKeys ??= {})[reference.fieldKey] = {\n      table: reference.referencedTable,\n      column: reference.referencedColumn,\n      onDelete: reference.onDelete,\n    };\n  }\n  const plan = await planSchemaMigration(planningModels, dialect, executor);\n\n  // What this version changes compared with what was last applied here.\n  const snapshot = createSchemaSnapshot(models);\n  const state = await readSchemaState(executor, dialect, owner.name);\n  const changes = state ? diffSchemaSnapshots(state.snapshot, snapshot) : undefined;\n  const upgrade =\n    state && changes && hasSchemaChanges(changes)\n      ? { from: state.version, to: owner.version, changes }\n      : undefined;\n  const pendingSteps = (stepPlan?.steps ?? []).filter((planned) => planned.state !== \"record\");\n  if (upgrade || pendingSteps.length > 0) {\n    const versions =\n      upgrade?.from && upgrade.to && upgrade.from !== upgrade.to\n        ? `${owner.name} ${upgrade.from} → ${upgrade.to} changes its tables:`\n        : `${owner.name}'s tables changed since they were last migrated:`;\n    log(\n      [\n        versions,\n        ...describeStepChanges(stepPlan, Boolean(options.allowDestructive)),\n        ...describeSchemaChanges(withoutStepChanges(changes, stepPlan)),\n        ...renameHints(withoutStepChanges(changes, stepPlan)),\n      ].join(\"\\n\"),\n    );\n  }\n  // An ORM's migrations own the app's tables there, and track their own\n  // history; an extra table would only show up as drift in its tooling.\n  const recordState = async () => {\n    if (options.extensions === \"report\") return;\n    // The snapshot moves to this version only once every step has run: a\n    // drop step proves what the plugin created from the previous snapshot.\n    const unfinished = (stepPlan?.steps ?? []).some(\n      (planned) => !stepsRan.includes(planned.step.id),\n    );\n    if (stepsStopped || unfinished) return;\n    try {\n      await writeSchemaState(executor, dialect, owner.name, { version: owner.version, snapshot });\n    } catch (error) {\n      // The migration itself succeeded; only the record of it did not.\n      log(\n        `Applied, but could not record it in \"${FARM_SCHEMA_STATE_TABLE}\" (${error instanceof Error ? error.message : String(error)}). The next upgrade of ${owner.name} will be compared with the database instead of this version.`,\n      );\n    }\n  };\n\n  const addable = plan.addableForeignKeys ?? [];\n  const foreignKeysUnsupported = dialect === \"sqlite\" ? addable : [];\n  const foreignKeysAllowed =\n    dialect === \"sqlite\"\n      ? []\n      : addable.filter((key) =>\n          isForeignKeyAllowed(schemaConfig?.allowForeignKeys, { owner: owner.name, ...key }),\n        );\n  const foreignKeysUnapproved =\n    dialect === \"sqlite\" ? [] : addable.filter((key) => !foreignKeysAllowed.includes(key));\n\n  const extensionsPlan = await planSchemaExtensions(\n    collectSchemaExtensions(owner.name, owner.schema, owner.models),\n    dialect,\n    executor,\n  );\n  const allowExtend = schemaConfig?.allowExtend;\n  const approved = reportOnly\n    ? []\n    : extensionsPlan.statements.filter((statement) =>\n        isSchemaExtensionAllowed(allowExtend, statement.extension),\n      );\n  const unapproved = reportOnly\n    ? []\n    : extensionsPlan.statements.filter((statement) => !approved.includes(statement));\n  const sql =\n    formatSteps(stepPlan, \"before\", reportOnly) +\n    formatSchemaMigration(plan, owner.name, {\n      addsColumns: approved.length + foreignKeysAllowed.length > 0,\n    }) +\n    formatSteps(stepPlan, \"after\", reportOnly) +\n    formatForeignKeys(owner.name, dialect, foreignKeysAllowed, foreignKeysUnapproved) +\n    formatExtensions(owner.name, {\n      approved,\n      unapproved,\n      reported: reportOnly ? extensionsPlan.statements : [],\n    });\n\n  const pendingAfter = (added: ReadonlySet<string>) => [\n    ...extensionsPlan.statements\n      .map((statement) => statement.target)\n      .filter((target) => !added.has(target)),\n    ...extensionsPlan.unsupported.map((entry) => `${entry.extension.table}.${entry.column}`),\n    ...extensionsPlan.missingTables.flatMap((extension) =>\n      extension.fields.map(({ field }) => `${extension.table}.${field.name}`),\n    ),\n  ];\n  const blocked: Array<{ key: FarmSchemaAddableForeignKey; orphans: number }> = [];\n  const result = (applied: string[]): MigrateSchemaTablesResult => ({\n    plan,\n    sql,\n    applied,\n    extensions: { ...extensionsPlan, unapproved, pending: pendingAfter(new Set(applied)) },\n    foreignKeys: {\n      waiting: crossOwner.waiting,\n      unapproved: foreignKeysUnapproved,\n      unsupported: foreignKeysUnsupported,\n      blocked,\n    },\n    upgrade,\n    steps: {\n      plan: stepPlan,\n      ran: stepsRan,\n      pending: (stepPlan?.steps ?? [])\n        .filter((planned) => !stepsRan.includes(planned.step.id))\n        .map((planned) => planned.step.id),\n    },\n    planned: pendingStatements + runnableSteps,\n  });\n\n  // A table created now without its foreign key, because the other plugin\n  // has not created its table yet: say how to get both, in order.\n  const creating = new Set(plan.statements.map((statement) => statement.target));\n  for (const reference of crossOwner.waiting) {\n    if (!creating.has(reference.table)) continue;\n    log(\n      `\"${reference.table}.${reference.column}\" is created without a foreign key: ${reference.referencedOwner} has not created \"${reference.referencedTable}\" yet. Run \\`farm schema migrate\\` to create both in order.`,\n    );\n  }\n  for (const key of foreignKeysUnsupported) {\n    log(\n      `\"${key.table}.${key.column}\" has no foreign key to \"${key.referencedTable}\". SQLite can only add one when it creates the table.`,\n    );\n  }\n\n  if (plan.upToDate.length > 0) {\n    log(`Already up to date: ${plan.upToDate.join(\", \")}`);\n  }\n  if (plan.drift.length > 0) {\n    log(\n      `These tables exist but no longer match the schema. Farm will not change them:\\n${describeSchemaDrift(plan.drift)}`,\n    );\n  }\n  logExtensionProblems(owner.name, extensionsPlan, log);\n\n  const pendingStatements =\n    plan.statements.length +\n    (plan.upgrades?.length ?? 0) +\n    approved.length +\n    foreignKeysAllowed.length;\n  // Steps still to run (or record) here, up to the first one that cannot:\n  // blocked, or deleting data without --allow-destructive.\n  const blockedAt = (stepPlan?.steps ?? []).findIndex(\n    (planned) =>\n      planned.state === \"blocked\" ||\n      (planned.state === \"run\" && planned.destructive && !options.allowDestructive),\n  );\n  const runnableSteps = (stepPlan?.steps ?? [])\n    .slice(0, blockedAt === -1 ? undefined : blockedAt)\n    .filter((planned) => !stepsRan.includes(planned.step.id)).length;\n  if (\n    pendingStatements === 0 &&\n    runnableSteps === 0 &&\n    blockedAt === -1 &&\n    unapproved.length === 0 &&\n    foreignKeysUnapproved.length === 0 &&\n    (!reportOnly || extensionsPlan.statements.length === 0)\n  ) {\n    log(\"Nothing to create.\");\n    // A first --apply on an up-to-date database records where it stands.\n    if (options.apply) await recordState();\n    return result([]);\n  }\n\n  if (options.write) {\n    const { writeFile, mkdir } = await import(\"node:fs/promises\");\n    const { dirname } = await import(\"node:path\");\n    await mkdir(dirname(options.write), { recursive: true });\n    await writeFile(options.write, sql, \"utf8\");\n    log(`Wrote ${pendingStatements} statement(s) to ${options.write}`);\n    return result([]);\n  }\n\n  if (!options.apply) {\n    log(sql);\n    return result([]);\n  }\n\n  for (const approval of new Set(\n    unapproved.map((statement) => describeSchemaExtensionApproval(statement.extension)),\n  )) {\n    const columns = unapproved\n      .filter((statement) => describeSchemaExtensionApproval(statement.extension) === approval)\n      .map((statement) => statement.target);\n    log(\n      `Not allowed yet, so not added: ${columns.join(\", \")}. To allow it, add to farm.config: ${approval}`,\n    );\n  }\n\n  const created = await applySchemaMigration(plan, executor);\n  const applied = [...created.applied];\n  // Tables first: a column is only ever added after the owner's own tables exist.\n  for (const statement of approved) {\n    await executor.execute(statement.sql);\n    applied.push(statement.target);\n  }\n  // Foreign keys last, once every table and column they involve exists. A key\n  // on rows that already point at nothing would fail, so those are counted\n  // first and the key is left for the app to clean up.\n  for (const key of foreignKeysAllowed) {\n    const orphans = await countOrphans(executor, dialect, key);\n    if (orphans > 0) {\n      blocked.push({ key, orphans });\n      log(\n        `Cannot add the foreign key \"${key.table}.${key.column}\" → \"${key.referencedTable}\": ${orphans} row(s) point at no \"${key.referencedTable}\". Fix or remove them, then run again.`,\n      );\n      continue;\n    }\n    await executor.execute(foreignKeyStatement(dialect, key));\n    applied.push(`${key.table}.${key.column} → ${key.referencedTable}`);\n  }\n  for (const key of foreignKeysUnapproved) {\n    log(\n      `Not allowed yet, so not added: the foreign key \"${key.table}.${key.column}\" → \"${key.referencedTable}\". To allow it, add to farm.config: ${describeForeignKeyApproval({ owner: owner.name, modelKey: key.modelKey })}`,\n    );\n  }\n  if (applied.length > 0) log(`Created: ${applied.join(\", \")}`);\n  // Custom SQL last: a backfill can fill this release's new columns.\n  await runSteps(\"after\");\n  if (stepsRan.length > 0) log(`Ran migration steps: ${stepsRan.join(\", \")}`);\n  await recordState();\n  return result(applied);\n}\n\nfunction foreignKeyStatement(dialect: FarmSqlDialect, key: FarmSchemaAddableForeignKey) {\n  // The name Postgres would give it, within the 63-character identifier limit.\n  const name = `${key.table}_${key.column}_fkey`.slice(0, 63);\n  const onDelete = key.onDelete !== \"noAction\" ? ` ON DELETE ${SQL_ON_DELETE[key.onDelete]}` : \"\";\n  const q = (value: string) => quoteSqlIdentifier(dialect, value);\n  return `ALTER TABLE ${q(key.table)} ADD CONSTRAINT ${q(name)} FOREIGN KEY (${q(key.column)}) REFERENCES ${q(key.referencedTable)} (${q(key.referencedColumn)})${onDelete};`;\n}\n\nconst SQL_ON_DELETE = {\n  cascade: \"CASCADE\",\n  restrict: \"RESTRICT\",\n  setNull: \"SET NULL\",\n  noAction: \"NO ACTION\",\n} as const;\n\n/** Rows whose value points at no row in the referenced table. */\nasync function countOrphans(\n  executor: FarmSchemaExecutor,\n  dialect: FarmSqlDialect,\n  key: FarmSchemaAddableForeignKey,\n): Promise<number> {\n  const q = (name: string) => quoteSqlIdentifier(dialect, name);\n  const rows = await executor.query(\n    `SELECT COUNT(*) AS orphans FROM ${q(key.table)} child WHERE child.${q(key.column)} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${q(key.referencedTable)} parent WHERE parent.${q(key.referencedColumn)} = child.${q(key.column)})`,\n  );\n  const row = rows[0] ?? {};\n  return Number(row.orphans ?? row.ORPHANS ?? Object.values(row)[0] ?? 0);\n}\n\nfunction formatForeignKeys(\n  owner: string,\n  dialect: FarmSqlDialect,\n  allowed: readonly FarmSchemaAddableForeignKey[],\n  unapproved: readonly FarmSchemaAddableForeignKey[],\n): string {\n  const sections: string[] = [];\n  if (allowed.length > 0) {\n    sections.push(\n      [\n        `-- Foreign keys from ${owner}'s existing tables to other plugins' tables, allowed in farm.config.`,\n        \"-- Added only when no row points at nothing.\",\n        ...allowed.map((key) => foreignKeyStatement(dialect, key)),\n      ].join(\"\\n\"),\n    );\n  }\n  if (unapproved.length > 0) {\n    const approvals = [\n      ...new Set(\n        unapproved.map((key) => describeForeignKeyApproval({ owner, modelKey: key.modelKey })),\n      ),\n    ];\n    sections.push(\n      [\n        `-- Foreign keys from ${owner}'s existing tables to other plugins' tables. Not allowed yet, so not run.`,\n        \"-- To allow them, add to farm.config:\",\n        ...approvals.map((approval) => `--   ${approval}`),\n        ...unapproved.map((key) => `-- ${foreignKeyStatement(dialect, key)}`),\n      ].join(\"\\n\"),\n    );\n  }\n  return sections.length > 0 ? `\\n${sections.join(\"\\n\\n\")}\\n` : \"\";\n}\n\n/** The steps, numbered, as the upgrade summary shows them. */\nfunction describeStepChanges(\n  stepPlan: FarmSchemaStepPlan | undefined,\n  allowDestructive: boolean,\n): string[] {\n  const pending = (stepPlan?.steps ?? []).filter((planned) => planned.state !== \"record\");\n  return pending.map((planned, index) => {\n    const when = planned.phase === \"after\" ? \" (after the changes below)\" : \"\";\n    const deletes =\n      planned.destructive && planned.state === \"run\"\n        ? allowDestructive\n          ? \"  ⚠ deletes data\"\n          : \"  ⚠ deletes data, needs --allow-destructive\"\n        : \"\";\n    const blocked = planned.state === \"blocked\" ? `  ✗ blocked: ${planned.reason}` : \"\";\n    return `  ${index + 1}. ${planned.summary}${when}${deletes}${blocked}`;\n  });\n}\n\n/** The snapshot diff, minus what the owner's rename steps already explain. */\nfunction withoutStepChanges(\n  changes: FarmSchemaChanges | undefined,\n  stepPlan: FarmSchemaStepPlan | undefined,\n): FarmSchemaChanges {\n  const empty = {\n    addedTables: [],\n    addedColumns: [],\n    addedIndexes: [],\n    otherChanges: [],\n    removedColumns: [],\n  };\n  if (!changes) return empty;\n  const renamedTo = new Set<string>();\n  const renamedFrom = new Set<string>();\n  for (const { summary, step } of stepPlan?.steps ?? []) {\n    const match = /^rename (?:table )?(\\S+) → (\\S+)$/u.exec(summary);\n    if (!match || !(\"renameColumn\" in step || \"renameTable\" in step)) continue;\n    renamedFrom.add(match[1]!);\n    renamedTo.add(match[2]!);\n  }\n  return {\n    addedTables: changes.addedTables.filter((table) => !renamedTo.has(table)),\n    addedColumns: changes.addedColumns.filter(\n      ({ table, column }) => !renamedTo.has(`${table}.${column}`),\n    ),\n    addedIndexes: changes.addedIndexes,\n    otherChanges: changes.otherChanges.filter(\n      (change) => ![...renamedFrom].some((from) => change === `${from} is removed`),\n    ),\n    removedColumns: (changes.removedColumns ?? []).filter(\n      ({ table, column }) => !renamedFrom.has(`${table}.${column}`),\n    ),\n  };\n}\n\n/**\n * A column removed and another of the same type added in one table looks\n * like a rename the plugin forgot to ship a step for.\n */\nfunction renameHints(changes: FarmSchemaChanges): string[] {\n  const hints: string[] = [];\n  for (const removed of changes.removedColumns ?? []) {\n    const added = changes.addedColumns.find(\n      ({ table, type }) => table === removed.table && type === removed.type,\n    );\n    if (!added) continue;\n    hints.push(\n      `  ? if ${removed.table}.${removed.column} was renamed to ${added.table}.${added.column}, the plugin needs a migration step, or the data stays in ${removed.column}`,\n    );\n  }\n  return hints;\n}\n\nfunction formatSteps(\n  stepPlan: FarmSchemaStepPlan | undefined,\n  phase: \"before\" | \"after\",\n  reportOnly: boolean,\n): string {\n  const planned = (stepPlan?.steps ?? []).filter(\n    (entry) => entry.phase === phase && entry.state !== \"record\",\n  );\n  if (planned.length === 0) return \"\";\n  const heading =\n    phase === \"before\"\n      ? \"-- Migration steps, run before the changes below:\"\n      : \"-- Migration steps, run after the changes above:\";\n  const lines = [heading];\n  for (const entry of planned) {\n    lines.push(\n      `-- ${entry.step.id}: ${entry.summary}${entry.destructive ? \"  (deletes data)\" : \"\"}`,\n    );\n    if (entry.state === \"blocked\") {\n      lines.push(`--   blocked: ${entry.reason}`);\n      continue;\n    }\n    for (const statement of entry.statements) {\n      lines.push(reportOnly ? `-- ${statement};` : `${statement.replace(/;\\s*$/u, \"\")};`);\n    }\n  }\n  if (reportOnly) {\n    lines.push(\"-- Your ORM owns these tables: add the steps to its migrations instead.\");\n  }\n  return `${lines.join(\"\\n\")}\\n\\n`;\n}\n\nfunction formatExtensions(\n  owner: string,\n  groups: {\n    approved: readonly FarmSchemaExtensionStatement[];\n    unapproved: readonly FarmSchemaExtensionStatement[];\n    reported: readonly FarmSchemaExtensionStatement[];\n  },\n): string {\n  const sections: string[] = [];\n  if (groups.approved.length > 0) {\n    sections.push(\n      [\n        `-- Columns ${owner} adds to tables it does not own, allowed in farm.config.`,\n        ...groups.approved.map((statement) => statement.sql),\n      ].join(\"\\n\"),\n    );\n  }\n  if (groups.unapproved.length > 0) {\n    const approvals = [\n      ...new Set(\n        groups.unapproved.map((statement) => describeSchemaExtensionApproval(statement.extension)),\n      ),\n    ];\n    sections.push(\n      [\n        `-- Columns ${owner} adds to tables it does not own. Not allowed yet, so not run.`,\n        \"-- To allow them, add to farm.config:\",\n        ...approvals.map((approval) => `--   ${approval}`),\n        ...groups.unapproved.map((statement) => `-- ${statement.sql}`),\n      ].join(\"\\n\"),\n    );\n  }\n  if (groups.reported.length > 0) {\n    sections.push(\n      [\n        `-- Columns ${owner} adds to tables your ORM owns. Farm will not alter them:`,\n        \"-- add them to your ORM's schema and run its migration.\",\n        ...groups.reported.map((statement) => `-- ${statement.sql}`),\n      ].join(\"\\n\"),\n    );\n  }\n  return sections.length > 0 ? `\\n${sections.join(\"\\n\\n\")}\\n` : \"\";\n}\n\nfunction logExtensionProblems(\n  owner: string,\n  plan: FarmSchemaExtensionPlan,\n  log: (message: string) => void,\n) {\n  for (const extension of plan.missingTables) {\n    log(\n      `Cannot add ${extension.fields.map(({ field }) => field.name).join(\", \")} to \"${extension.table}\": the table does not exist. Run the migration that creates it (your ORM's, or a library's such as Better Auth) first.`,\n    );\n  }\n  for (const entry of plan.unsupported) {\n    log(`Cannot add \"${entry.extension.table}.${entry.column}\" for ${owner}: ${entry.reason}`);\n  }\n  for (const entry of plan.conflicts) {\n    log(\n      `\"${entry.extension.table}.${entry.column}\" already exists as ${entry.actual}; ${owner} expects ${entry.expected.toLowerCase()}. Farm will not change it.`,\n    );\n  }\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\";\nimport { canonicalizeRequestPathname } from \"../utils/decode\";\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  const localizedPathname = i18n?.enabled ? resolveFarmLocalePath(pathname, i18n) : { pathname };\n  return {\n    pathname: normalizeConfigRoutePathname(canonicalizeRequestPathname(localizedPathname.pathname)),\n    ...(i18n?.enabled && \"locale\" in localizedPathname ? { locale: localizedPathname.locale } : {}),\n  };\n}\n\n/**\n * Drop a trailing slash before matching, mirroring `normalizeRuntimePath` in\n * the generated production matcher. Without this a request for `/old/` misses\n * a `/old` rule in dev while matching it in a built app.\n */\nfunction normalizeConfigRoutePathname(pathname: string): string {\n  if (!pathname || pathname === \"/\") return \"/\";\n  return pathname.endsWith(\"/\") ? pathname.replace(/\\/+$/, \"\") || \"/\" : pathname;\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\n/**\n * Append a catch-all capture, absorbing the separator that precedes it.\n *\n * The production matcher works on split segments and lets a non-terminal\n * catch-all consume zero of them (`minConsume = 0`), so `/x/*` + `/y` matches\n * `/x/y` and `/files/:path*` matches `/files`. Emitting a bare `(.*)` after a\n * literal `/` instead demands at least that separator, so the same rule was\n * inert in dev. Folding the slash into the optional group is how path-to-regexp\n * expresses the same thing, and it keeps one capture group so capture indexes\n * are unchanged (a non-participating group reads back as \"\").\n */\nfunction appendCatchAll(pattern: string): string {\n  return pattern.endsWith(\"/\") ? `${pattern.slice(0, -1)}(?:/(.*))?` : `${pattern}(.*)`;\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] ? appendCatchAll(pattern) : `${pattern}([^/]+)`;\n      captureIndex += 1;\n      index += parameter[0].length;\n      continue;\n    }\n\n    if (source[index] === \"*\") {\n      tokens.push({ kind: \"wildcard\", captureIndex });\n      pattern = appendCatchAll(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 whose host matches the `Host` header *and* whose\n * scheme matches the rebuilt `request.url` scheme. The scheme check blocks\n * browser-driven protocol-downgrade CSRF and also rejects proxy-rebuilt\n * `request.url` values whose scheme differs from the browser origin. For\n * TLS-terminating proxies that leave `request.url` as `http:`, enable\n * `trustProxy` with a proxy-emitted `X-Forwarded-Proto: https`, or add the\n * browser origin to `serverActions.allowedOrigins`.\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\n/** Preserve plugin metadata across framework-owned Request replacements. */\nexport function copyRequestContext(\n  source: RequestContextCarrier,\n  target: RequestContextCarrier,\n): void {\n  const bucket = getRequestContextStore().get(source);\n  if (!bucket || source === target) return;\n  for (const [key, value] of bucket.privateData) {\n    setRequestContext(target, key, value, { exposeToPage: bucket.exposedData.has(key) });\n  }\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\";\nimport { copyRequestContext } from \"./request-context\";\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 function cloneFarmRequestWithContext(request: Request): Request {\n  const cloned = request.clone();\n  copyRequestContext(request, cloned);\n  return cloned;\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  const buffered = new Request(request, {\n    // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.\n    body: body.buffer,\n  });\n  copyRequestContext(request, buffered);\n  return buffered;\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 { assertNoSchemaListField } from \"./schema-capabilities\";\nimport { assertSupportedPrimaryKeyField } from \"./schema-primary-key\";\nimport { isDatabaseEnforcedReference } from \"./schema-reference\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\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 extends {\n  primaryKey: true;\n}\n  ? TField[\"type\"] extends \"id\" | \"uuid\" | \"string\" | \"integer\"\n    ? \"id\"\n    : never\n  : TField[\"type\"] extends \"id\" | \"uuid\" | \"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\ntype FarmIntegrationOrmModelShape = {\n  fields: Record<string, unknown>;\n};\n\nexport type InferFarmIntegrationOrmFields<TModel extends FarmIntegrationOrmModelShape> = {\n  [TFieldKey in keyof TModel[\"fields\"] & string]: InferFarmIntegrationOrmField<\n    Extract<TModel[\"fields\"][TFieldKey], FarmIntegrationSchemaField>\n  >;\n};\n\ntype ReplaceRecord<TBase, TReplacement> = Omit<TBase, keyof TReplacement> & TReplacement;\n\ntype SchemaExtensions<TSchema extends FarmIntegrationSchema> = NonNullable<TSchema[\"extend\"]>;\n\ntype SchemaOverrides<TSchema extends FarmIntegrationSchema> = NonNullable<TSchema[\"override\"]>;\n\ntype SchemaModelFields<TModel> = TModel extends { fields: infer TFields }\n  ? TFields\n  : TModel extends { fields?: infer TFields }\n    ? NonNullable<TFields>\n    : {};\n\ntype ExtendedSchemaModelFields<\n  TSchema extends FarmIntegrationSchema,\n  TModelKey extends PropertyKey,\n> = ReplaceRecord<\n  TModelKey extends keyof TSchema[\"models\"] ? SchemaModelFields<TSchema[\"models\"][TModelKey]> : {},\n  TModelKey extends keyof SchemaExtensions<TSchema>\n    ? SchemaModelFields<SchemaExtensions<TSchema>[TModelKey]>\n    : {}\n>;\n\ntype OverrideSchemaModelFields<\n  TSchema extends FarmIntegrationSchema,\n  TModelKey extends PropertyKey,\n> = TModelKey extends keyof SchemaOverrides<TSchema>\n  ? SchemaModelFields<SchemaOverrides<TSchema>[TModelKey]>\n  : {};\n\ntype ResolvedSchemaModelFields<\n  TSchema extends FarmIntegrationSchema,\n  TModelKey extends PropertyKey,\n  TExtendedFields = ExtendedSchemaModelFields<TSchema, TModelKey>,\n  TOverrideFields = OverrideSchemaModelFields<TSchema, TModelKey>,\n> = {\n  [TFieldKey in\n    | keyof TExtendedFields\n    | keyof TOverrideFields]: TFieldKey extends keyof TOverrideFields\n    ? TFieldKey extends keyof TExtendedFields\n      ? ReplaceRecord<TExtendedFields[TFieldKey], TOverrideFields[TFieldKey]>\n      : TOverrideFields[TFieldKey]\n    : TFieldKey extends keyof TExtendedFields\n      ? TExtendedFields[TFieldKey]\n      : never;\n};\n\ntype ResolvedFarmIntegrationSchemaModels<TSchema extends FarmIntegrationSchema> = {\n  [TModelKey in (keyof TSchema[\"models\"] | keyof SchemaExtensions<TSchema>) & string]: {\n    fields: ResolvedSchemaModelFields<TSchema, TModelKey>;\n  };\n};\n\nexport type InferFarmIntegrationOrmSchema<TSchema extends FarmIntegrationSchema> =\n  SchemaDefinition<{\n    [TModelKey in keyof ResolvedFarmIntegrationSchemaModels<TSchema> & string]: ModelDefinition<\n      InferFarmIntegrationOrmFields<\n        Extract<\n          ResolvedFarmIntegrationSchemaModels<TSchema>[TModelKey],\n          FarmIntegrationOrmModelShape\n        >\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  for (const [modelKey, modelSchema] of Object.entries(schema.models)) {\n    for (const [fieldKey, fieldSchema] of Object.entries(modelSchema.fields)) {\n      assertNoSchemaListField(\n        fieldSchema,\n        `${modelKey}.${fieldKey}`,\n        \"the Farm integration runtime ORM\",\n      );\n    }\n  }\n\n  const orm = await import(\"@farming-labs/orm\");\n  const models: Record<string, AnyModelDefinition> = {};\n  const resolvedModels = resolveSchemaModels(\"integration\", schema);\n\n  for (const [modelKey, modelSchema] of Object.entries(resolvedModels)) {\n    models[modelKey] = orm.model({\n      table: modelSchema.name ?? modelKey,\n      fields: createOrmModelFields(orm, modelKey, 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  modelKey: string,\n  modelSchema: FarmIntegrationSchemaModel,\n): Record<string, AnyFieldBuilder> {\n  return Object.fromEntries(\n    Object.entries(modelSchema.fields).map(([fieldKey, fieldSchema]) => [\n      fieldKey,\n      createOrmField(orm, modelKey, fieldKey, fieldSchema),\n    ]),\n  );\n}\n\nfunction createOrmField(\n  orm: typeof import(\"@farming-labs/orm\"),\n  modelKey: string,\n  fieldKey: string,\n  field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n  assertSupportedPrimaryKeyField(`integration.${modelKey}.${fieldKey}`, field);\n  let builder = createOrmFieldBuilder(orm, fieldKey, field) as AnyFieldBuilder;\n\n  if (!field.primaryKey && field.unique) {\n    builder = builder.unique();\n  }\n\n  if (!field.primaryKey && (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 && isDatabaseEnforcedReference(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  if (field.primaryKey) {\n    if (field.type === \"integer\") {\n      return orm.id({ type: \"integer\" });\n    }\n    if (field.type === \"string\") {\n      return new orm.FieldBuilder({\n        kind: \"id\",\n        nullable: false,\n        unique: true,\n        idType: \"string\",\n      });\n    }\n    return orm.id();\n  }\n\n  switch (field.type) {\n    case \"id\":\n    case \"uuid\":\n      return orm.string();\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\";\nimport { defineSchema } from \"./schema\";\nimport type {\n  FarmSchema,\n  FarmSchemaConstraint,\n  FarmSchemaField,\n  FarmSchemaFieldType,\n  FarmSchemaModel,\n  FarmSchemaModelExtension,\n  FarmSchemaModelOverride,\n  FarmSchemaReference,\n} from \"./schema\";\n\n// Keep the schema types available from the integrations entrypoint as well.\n// Integration declarations reference these types, and exporting them here\n// keeps those declarations nameable for consumers that import integration\n// helpers directly.\nexport type {\n  FarmSchema,\n  FarmSchemaConstraint,\n  FarmSchemaField,\n  FarmSchemaFieldType,\n  FarmSchemaModel,\n  FarmSchemaModelExtension,\n  FarmSchemaModelOverride,\n  FarmSchemaReference,\n} from \"./schema\";\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 { canonicalizeRequestPathname, canonicalizeRequestPathSegments } 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 { applyWebResponseHeaders, 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\n/**\n * Request-context key under which an integration middleware can hand\n * `Set-Cookie` values to the runtime when it returns `void` (i.e. lets the\n * request continue to the downstream route/page handler). The runtime reads\n * this key back after a `void` middleware return and forwards the cookies onto\n * the response it ultimately sends, so a server-side session refresh (or any\n * other cookie rotation) reaches the browser instead of being dropped.\n */\nexport const FARM_INTEGRATION_SET_COOKIES_KEY = \"farm:integration:set-cookies\";\n\n/**\n * Forward `Set-Cookie` values from an integration middleware that returns\n * `void` (the authenticated/passthrough branch) to the runtime, so they are\n * merged onto the response the runtime sends for the matched route. This is\n * the passthrough counterpart to appending `Set-Cookie` to a `Response` the\n * middleware returns directly (e.g. a failure redirect): both paths can rotate\n * auth cookies, and both must be able to reach the browser.\n */\nexport function forwardIntegrationSetCookies(\n  context: Pick<FarmIntegrationHandlerContext, \"req\">,\n  cookies: string[],\n): void {\n  if (cookies.length === 0) return;\n  const existing = context.req.get<string[]>(FARM_INTEGRATION_SET_COOKIES_KEY) ?? [];\n  context.req.set(FARM_INTEGRATION_SET_COOKIES_KEY, [...existing, ...cookies]);\n}\n\n/**\n * Read and clear the forwarded `Set-Cookie` values an integration middleware\n * stashed on the request context. Reading-and-clearing guarantees each batch\n * is applied at most once even when several middleware run for one request.\n */\nfunction takeForwardedIntegrationSetCookies(\n  context: Pick<FarmIntegrationHandlerContext, \"req\">,\n): string[] {\n  const cookies = context.req.get<string[]>(FARM_INTEGRATION_SET_COOKIES_KEY);\n  if (cookies && cookies.length > 0) {\n    context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);\n    return cookies;\n  }\n  if (cookies) {\n    context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);\n  }\n  return [];\n}\n\n/**\n * Return a copy of `response` carrying the forwarded `Set-Cookie` values, or\n * `response` unchanged when there is nothing to forward. Existing `Set-Cookie`\n * headers on the response are preserved (appended to, not replaced).\n */\nfunction appendIntegrationForwardedCookies(response: Response, cookies: string[]): Response {\n  if (cookies.length === 0) return response;\n  const headers = new Headers(response.headers);\n  for (const cookie of cookies) {\n    headers.append(\"set-cookie\", cookie);\n  }\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\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\n// The data schema is renderer- and feature-neutral: it now lives in ./schema\n// so applications can declare one without reaching into the integration API.\n// These aliases keep every shipped `*IntegrationSchema*` name working.\n\n/** @deprecated Use `FarmSchemaFieldType`. */\nexport type FarmIntegrationSchemaFieldType = FarmSchemaFieldType;\n\n/** @deprecated Use `FarmSchemaReference`. */\nexport type FarmIntegrationSchemaReference = FarmSchemaReference;\n\n/** @deprecated Use `FarmSchemaField`. */\nexport type FarmIntegrationSchemaField = FarmSchemaField;\n\n/** @deprecated Use `FarmSchemaConstraint`. */\nexport type FarmIntegrationSchemaConstraint = FarmSchemaConstraint;\n\n/** @deprecated Use `FarmSchemaModel`. */\nexport type FarmIntegrationSchemaModel = FarmSchemaModel;\n\n/** @deprecated Use `FarmSchemaModelExtension`. */\nexport type FarmIntegrationSchemaModelExtension = FarmSchemaModelExtension;\n\n/** @deprecated Use `FarmSchemaModelOverride`. */\nexport type FarmIntegrationSchemaModelOverride = FarmSchemaModelOverride;\n\n/** @deprecated Use `FarmSchema`. */\nexport type FarmIntegrationSchema = FarmSchema;\n\n/** @deprecated Use `defineSchema`. This is an exact alias, not a wrapper. */\nexport const defineIntegrationSchema = defineSchema;\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  const method = normalizeIntegrationRequestMethod(input.method);\n  if (!method) {\n    return null;\n  }\n  const pathSegments = canonicalizeRequestPathSegments(input.pathname);\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, method)) {\n        continue;\n      }\n\n      const params = matchPathSegments(route[INTEGRATION_ROUTE_SEGMENTS], pathSegments);\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<TConfig, TSchema extends FarmIntegrationSchema | undefined>(\n  value: FarmIntegrationConfigInput<TConfig, TSchema>,\n): value is FarmIntegrationConfigDefinition<TConfig, TSchema> {\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 pathSegments = canonicalizeRequestPathSegments(pathname);\n      const method = normalizeIntegrationRequestMethod(req.method);\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\n          // A middleware that returns `void` lets the request continue to the\n          // downstream route/page handler, so its rotated `Set-Cookie` values\n          // cannot ride on its own response. It hands them to the runtime via\n          // forwardIntegrationSetCookies; merge them onto the Node response now\n          // (appending, so a later short-circuit Response or the page renderer\n          // can add its own Set-Cookie without dropping these). Read-and-clear\n          // so multiple middleware for one request each forward at most once.\n          const forwardedCookies = takeForwardedIntegrationSetCookies(handlerContext);\n          if (forwardedCookies.length > 0) {\n            const setCookieHeaders = new Headers();\n            for (const cookie of forwardedCookies) {\n              setCookieHeaders.append(\"set-cookie\", cookie);\n            }\n            applyWebResponseHeaders(res, setCookieHeaders, { appendSetCookie: true });\n          }\n\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 =\n          method && matchesMethod(route.methods, method)\n            ? matchPathSegments(route[INTEGRATION_ROUTE_SEGMENTS], pathSegments)\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  [INTEGRATION_ROUTE_SEGMENTS]: readonly string[];\n};\n\nconst INTEGRATION_ROUTE_SEGMENTS = Symbol(\"farm.integrationRouteSegments\");\nconst EMPTY_NORMALIZED_INTEGRATION_ROUTES: NormalizedIntegrationRoute[] = [];\nconst normalizedIntegrationRoutesCache = new WeakMap<\n  readonly FarmIntegrationRoute[],\n  NormalizedIntegrationRoute[]\n>();\n\nfunction normalizeIntegrationRoutes(\n  routes: readonly FarmIntegrationRoute[],\n): NormalizedIntegrationRoute[] {\n  if (routes.length === 0) {\n    return EMPTY_NORMALIZED_INTEGRATION_ROUTES;\n  }\n\n  const cached = normalizedIntegrationRoutesCache.get(routes);\n  if (cached) {\n    return cached;\n  }\n\n  const normalized = 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          [INTEGRATION_ROUTE_SEGMENTS]: splitPath(route.path),\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  normalizedIntegrationRoutesCache.set(routes, normalized);\n  return normalized;\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     * Receives `Set-Cookie` values that a middleware forwarded via\n     * forwardIntegrationSetCookies while returning `void`, when this dispatch\n     * ends without a Response of its own. The request continues downstream, so\n     * the caller owns merging them onto whatever response it finally produces.\n     * Only called on the `null` return path: a Response returned from here has\n     * already had the forwarded cookies appended.\n     */\n    onForwardedCookies?: (cookies: string[]) => void;\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 pathSegments = canonicalizeRequestPathSegments(pathname);\n  const method = normalizeIntegrationRequestMethod(request.method);\n  const middleware = [...(integration.middleware || [])];\n\n  // Cookies an integration middleware forwards via forwardIntegrationSetCookies\n  // while returning `void` (letting the request continue). They are merged onto\n  // whichever Response this dispatch ultimately returns so a server-side\n  // refresh/rotation reaches the browser instead of being dropped. Top-level\n  // and per-route middleware both contribute here; read-and-clear keeps each\n  // batch applied at most once.\n  const forwardedSetCookies: string[] = [];\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      forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(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 appendIntegrationForwardedCookies(response, forwardedSetCookies);\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 =\n      method && matchesMethod(route.methods, method)\n        ? matchPathSegments(route[INTEGRATION_ROUTE_SEGMENTS], pathSegments)\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 appendIntegrationForwardedCookies(validation.response, forwardedSetCookies);\n      }\n      handlerContext.input = validation.input;\n\n      for (const middlewareEntry of route.middleware || []) {\n        const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n        forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(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 appendIntegrationForwardedCookies(middlewareResponse, forwardedSetCookies);\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 appendIntegrationForwardedCookies(response, forwardedSetCookies);\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 appendIntegrationForwardedCookies(response, forwardedSetCookies);\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  // Nothing here produced a Response, so the request continues downstream. A\n  // middleware that returned `void` may still have rotated auth cookies; hand\n  // them to the caller instead of dropping them, because the response they\n  // belong on is the one the page/API handler is about to produce.\n  if (forwardedSetCookies.length > 0) {\n    options.onForwardedCookies?.(forwardedSetCookies);\n  }\n\n  return null;\n}\n\n/**\n * Run every configured integration's middleware and routes for one request.\n *\n * Integration middleware is not route scoped: it is the mechanism behind\n * `protectedRoutes` guards and provider session refresh, so it has to run for\n * ordinary page and API requests that match no integration route at all. That\n * makes this, not `matchIntegrationRoute`, the correct entry point for a\n * runtime dispatching integrations for every request.\n *\n * The first integration that produces a Response short-circuits the rest.\n * `Set-Cookie` values forwarded by middleware that returned `void` are\n * collected: they ride the short-circuiting Response when there is one, and are\n * otherwise handed back so the caller can merge them onto the downstream\n * response.\n */\nexport async function dispatchIntegrationRequests(\n  integrations: FarmIntegrationsUserConfig | undefined,\n  runtime: Omit<RegisteredIntegrationRuntime, \"integration\">,\n  request: Request,\n  options: { currentRequest?: Request } = {},\n): Promise<{ response: Response | null; setCookies: string[] }> {\n  const setCookies: string[] = [];\n  if (!integrations) {\n    return { response: null, setCookies };\n  }\n\n  for (const integration of Object.values(integrations)) {\n    if (!integration || !isFarmIntegration(integration)) {\n      continue;\n    }\n\n    // Skip integrations that mount no request handlers at all so they do not\n    // pay for body buffering on every request.\n    const hasMiddleware = (integration.middleware || []).length > 0;\n    const hasRoutes = normalizeIntegrationRoutes(integration.routes || []).length > 0;\n    if (!hasMiddleware && !hasRoutes) {\n      continue;\n    }\n\n    const response = await dispatchIntegrationRequest(\n      { ...runtime, integration },\n      // Each dispatch buffers the body it is given, so hand every integration\n      // its own clone rather than a Request another dispatch already read.\n      request.clone(),\n      {\n        currentRequest: options.currentRequest,\n        onForwardedCookies: (cookies) => setCookies.push(...cookies),\n      },\n    );\n\n    if (response) {\n      return {\n        response: appendIntegrationForwardedCookies(response, setCookies),\n        setCookies: [],\n      };\n    }\n  }\n\n  return { response: null, setCookies };\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 normalizeIntegrationRequestMethod(method: string | undefined): string | undefined {\n  return method ? method.toUpperCase() : undefined;\n}\n\nfunction matchesMethod(methods: readonly string[], normalizedMethod: string): boolean {\n  return methods.some((candidate) => candidate === \"ALL\" || candidate === normalizedMethod);\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  // An integration matcher is a guard (`protectedRoutes` compiles straight into\n  // one), so it has to see the same pathname the route matchers do. Comparing\n  // the raw pathname let `/%64ashboard` miss a `/dashboard` matcher while the\n  // page router still served the protected page. Resolved on first use so a\n  // match-everything matcher stays allocation free.\n  let canonicalPathname: string | undefined;\n  let canonicalSegments: string[] | undefined;\n\n  for (const item of list) {\n    if (item === \"/(.*)\" || item === \"*\") {\n      return {};\n    }\n    if (item.endsWith(\"(.*)\")) {\n      canonicalPathname ??= canonicalizeRequestPathname(pathname);\n      const prefix = item.slice(0, -4);\n      if (canonicalPathname === prefix || canonicalPathname.startsWith(`${prefix}/`)) {\n        return {};\n      }\n      continue;\n    }\n    canonicalSegments ??= canonicalizeRequestPathSegments(pathname);\n    const params = matchPathSegments(splitPath(item), canonicalSegments);\n    if (params) {\n      return params;\n    }\n  }\n\n  return null;\n}\n\n/**\n * Walk an integration route pattern against already-canonical request segments.\n *\n * `pathSegments` arrive decoded exactly once, so nothing here decodes again: a\n * second pass would turn a literal `%2541BC` segment into `ABC` and resolve a\n * record the request never asked for.\n */\nfunction matchPathSegments(\n  routeSegments: readonly string[],\n  pathSegments: readonly string[],\n): FarmIntegrationRouteParams | null {\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.slice(pathIndex);\n      return params;\n    }\n\n    if (isDynamicSegment(routeSegment)) {\n      params[getSegmentParamName(routeSegment)] = 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 path from \"node:path\";\nimport 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\n/**\n * The MDX components module a Markdown page renders from, as an absolute path. Undefined when\n * the components are an inline object, which cannot be analyzed for client components.\n */\nexport function resolveFarmMdxComponentsModulePath(\n  config: FarmMdxResolvedConfig | undefined,\n  root: string,\n): string | undefined {\n  const components = config?.components;\n  if (typeof components !== \"string\") return undefined;\n  return path.isAbsolute(components) ? components : path.join(root, components);\n}\n","/** Content type for Markdown responses, including agent-facing error bodies. */\nexport const FARM_MARKDOWN_CONTENT_TYPE = \"text/markdown; charset=utf-8\";\n\nexport function farmRequestWantsMarkdown(\n  pathname: string,\n  accept: string | null | undefined,\n): boolean {\n  return pathname.toLowerCase().endsWith(\".md\") || requestAcceptsMarkdown(accept);\n}\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 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  /** @internal Reuse a parse only while its href still matches this request. */\n  requestUrl?: URL;\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 =\n    options.requestUrl?.href === options.request.url\n      ? options.requestUrl\n      : 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 alternatePath = getFarmMarkdownAlternatePath(options.config, options.pathname);\n  if (!alternatePath) {\n    return response;\n  }\n\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\n// Wraps the index of a code block set aside during conversion. NUL is not\n// valid in HTML text, so rendered pages do not produce this placeholder.\nconst CODE_BLOCK_MARK = \"\\u0000\";\nconst CODE_BLOCK_PLACEHOLDER = /\\u0000(\\d+)\\u0000/g;\n\n// Elements that start a new block. Their text belongs on its own line.\nconst BLOCK_TAGS =\n  /<\\/?(ul|ol|main|section|article|header|footer|nav|aside|div|form|fieldset|legend|figure|figcaption|table|thead|tbody|tfoot|tr|dl|dt|dd|details|summary|address)\\b[^>]*>/gi;\n\n// Elements a browser always lays out as their own box, so they never sit inside\n// a word and a separator is safe. Without one, `<label>Token</label><button>Open\n// </button>` read as \"TokenOpen\". Inline wrappers such as span, a, or em stay\n// joined because animations and markup split single words across them.\nconst BOX_TAGS =\n  /<\\/?(label|button|input|select|textarea|option|output|meter|progress|td|th)\\b[^>]*>/gi;\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  // Hidden elements go before the body is extracted, since extraction drops the\n  // <main> or <body> tag whose own attributes may hide it, and after scripts go,\n  // so markup quoted in a script string is never read as an element.\n  let source = extractHtmlBody(\n    removeHiddenElements(\n      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  );\n\n  // Code blocks are set aside behind placeholders so the tidying below never\n  // touches them, and each gets a fence longer than any backtick run inside it,\n  // so code that itself shows ``` fences cannot close the block early.\n  const codeBlocks: string[] = [];\n  const setAsideCodeBlock = (_: string, code: string) => {\n    const content = decodeHtml(stripTags(code)).trim();\n    // A reduce, not Math.max(...runs): a large block can exceed the argument limit.\n    const longestRun = (content.match(/`+/g) ?? []).reduce(\n      (longest, run) => Math.max(longest, run.length),\n      0,\n    );\n    const fence = \"`\".repeat(Math.max(3, longestRun + 1));\n    codeBlocks.push(`${fence}\\n${content}\\n${fence}`);\n    return `\\n\\n${CODE_BLOCK_MARK}${codeBlocks.length - 1}${CODE_BLOCK_MARK}\\n\\n`;\n  };\n  source = source.replace(\n    /<pre\\b[^>]*><code\\b[^>]*>([\\s\\S]*?)<\\/code><\\/pre>/gi,\n    setAsideCodeBlock,\n  );\n  source = source.replace(/<pre\\b[^>]*>([\\s\\S]*?)<\\/pre>/gi, setAsideCodeBlock);\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    // The nested call returns decoded text, so it is escaped again before\n    // rejoining this pass, which decodes once at the end. Code blocks inside\n    // were already set aside by this call and the nested call leaves their\n    // placeholders alone; each is quoted line by line, blank lines included,\n    // and set aside again so the rest of this pass leaves it untouched.\n    const quote = htmlToMarkdown(content, { includeMetadata: false })\n      .split(\"\\n\")\n      .filter((line) => line.trim().length > 0)\n      .map((line) => {\n        const code =\n          line.startsWith(CODE_BLOCK_MARK) && line.endsWith(CODE_BLOCK_MARK)\n            ? codeBlocks[Number(line.slice(1, -1))]\n            : undefined;\n        if (code === undefined) return `> ${escapeHtmlText(line)}`;\n        codeBlocks.push(\n          code\n            .split(\"\\n\")\n            .map((codeLine) => (codeLine ? `> ${codeLine}` : \">\"))\n            .join(\"\\n\"),\n        );\n        return `${CODE_BLOCK_MARK}${codeBlocks.length - 1}${CODE_BLOCK_MARK}`;\n      })\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(BLOCK_TAGS, \"\\n\")\n    .replace(BOX_TAGS, \" \")\n    .replace(/<br\\s*\\/?>/gi, \"\\n\")\n    .replace(/<hr\\s*\\/?>/gi, \"\\n\\n---\\n\\n\");\n\n  // Text keeps its HTML entities through every pass above, so an escaped\n  // `&lt;div&gt;` is never mistaken for a tag; it is decoded exactly once, here,\n  // after the last tags are gone. Then collapse the spacing that tag separators\n  // and indented source HTML leave behind (four leading spaces would read as a\n  // code block), and restore the code blocks set aside above, untouched.\n  let markdown = decodeHtml(stripTags(source))\n    .split(\"\\n\")\n    .map((line) => line.replace(/[ \\t]+/g, \" \").trim())\n    .join(\"\\n\")\n    .replace(/\\n{3,}/g, \"\\n\\n\")\n    .trim()\n    // Placeholders this call did not create belong to an outer call (a blockquote).\n    .replace(CODE_BLOCK_PLACEHOLDER, (match, index: string) => codeBlocks[Number(index)] ?? match);\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\n/**\n * Quality value an `Accept` header assigns a media type, or 0 when the client\n * will not take it.\n *\n * `q=0` means \"not acceptable\" per RFC 9110, so it has to be distinguished from\n * an absent entry rather than treated as a match. Wildcards are opt-in: a client\n * sending `*&#47;*` will take anything, which says nothing about whether it would\n * rather have Markdown than HTML, so callers negotiating between two concrete\n * types should ask for exact entries only.\n */\nexport function farmAcceptQuality(\n  accept: string | null | undefined,\n  mediaType: string,\n  options: { wildcards?: boolean } = {},\n): number {\n  if (!accept) return 0;\n  const target = mediaType.toLowerCase();\n  const [targetType] = target.split(\"/\");\n  let best = 0;\n\n  for (const entry of accept.split(\",\")) {\n    const [candidate, ...parameters] = entry\n      .trim()\n      .toLowerCase()\n      .split(\";\")\n      .map((part) => part.trim());\n    if (!candidate) continue;\n\n    const matches =\n      candidate === target ||\n      (options.wildcards === true && (candidate === \"*/*\" || candidate === `${targetType}/*`));\n    if (!matches) continue;\n\n    const quality = parameters.find((parameter) => parameter.startsWith(\"q=\"));\n    const value = quality === undefined ? 1 : Number(quality.slice(2));\n    if (!Number.isFinite(value) || value <= 0) continue;\n    if (value > best) best = value;\n  }\n\n  return best;\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\n/** @internal The `.md` URL that serves a page's Markdown mirror. */\nexport function getFarmMarkdownMirrorPath(pathname: string): string {\n  return getMarkdownAlternatePath(pathname);\n}\n\n/**\n * @internal The `.md` URL to advertise for the HTML page at `pathname`, or\n * null when it has no Markdown mirror. Both the `Link` response header and the\n * `<link rel=\"alternate\">` in the document head come from this.\n */\nexport function getFarmMarkdownAlternatePath(\n  config: FarmMarkdownResolvedConfig | undefined,\n  pathname: string,\n): string | null {\n  const target = resolveMarkdownMirrorTarget(config, pathname, { accept: \"text/markdown\" });\n  return target ? getMarkdownAlternatePath(target.pathname) : null;\n}\n\n/** @internal Whether `pathname` has a Markdown mirror under `config`. */\nexport function isFarmMarkdownMirrorExposed(\n  config: FarmMarkdownResolvedConfig | undefined,\n  pathname: string,\n): boolean {\n  if (!config?.enabled) return false;\n  return config.expose === true || findExposedMarkdownRoute(config, pathname) !== null;\n}\n\n/** @internal Matches a page pathname against a route pattern such as `/docs/[...slug]`. */\nexport function matchesFarmMarkdownRoutePattern(pattern: string, pathname: string): boolean {\n  return routeMatches(pattern, pathname);\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  let source = \"\";\n  pattern.split(\"/\").forEach((segment, index) => {\n    // [[...name]] is optional: it matches the base path and anything below it.\n    if (/^\\[\\[\\.\\.\\.[^\\]]+\\]\\]$/.test(segment)) {\n      source += \"(?:/.*)?\";\n      return;\n    }\n    const prefix = index === 0 ? \"\" : \"/\";\n    if (/^\\[\\.\\.\\.[^\\]]+\\]$/.test(segment)) {\n      source += `${prefix}.*`;\n    } else if (/^\\[[^\\]]+\\]$/.test(segment)) {\n      source += `${prefix}[^/]+`;\n    } else {\n      source += prefix + segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n    }\n  });\n\n  return new RegExp(`^${source}$`).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\n/**\n * Converts inline HTML to Markdown. The result keeps its HTML entities:\n * htmlToMarkdown decodes once, after every tag is gone.\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}](${href})`;\n    })\n    .replace(\n      /<img\\b[^>]*src=[\"']([^\"']+)[\"'][^>]*alt=[\"']([^\"']*)[\"'][^>]*\\/?>/gi,\n      (_, src, alt) => {\n        return `![${alt}](${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 `\\`${stripTags(content).trim()}\\``;\n    })\n    .replace(/<br\\s*\\/?>/gi, \"\\n\")\n    .replace(BLOCK_TAGS, \" \")\n    .replace(BOX_TAGS, \" \");\n\n  return stripTags(source).replace(/\\s+/g, \" \");\n}\n\n// Elements with no closing tag, which an attribute can hide on their own.\nconst VOID_TAGS = new Set([\n  \"area\",\n  \"base\",\n  \"br\",\n  \"col\",\n  \"embed\",\n  \"hr\",\n  \"img\",\n  \"input\",\n  \"link\",\n  \"meta\",\n  \"source\",\n  \"track\",\n  \"wbr\",\n]);\n\n/**\n * Removes elements hidden from assistive technology, with everything inside\n * them: `aria-hidden=\"true\"`, which marks decoration such as separators and the\n * duplicated copy of a marquee, and the `hidden` attribute. A reader of the\n * Markdown mirror should get what a screen reader gets. `hidden=\"until-found\"`\n * stays, since that content can still be found and revealed.\n */\nfunction removeHiddenElements(html: string): string {\n  const openingTag = /<([a-zA-Z][\\w:-]*)((?:[^>\"']|\"[^\"]*\"|'[^']*')*)>/g;\n  let result = \"\";\n  let cursor = 0;\n  let match: RegExpExecArray | null;\n  while ((match = openingTag.exec(html))) {\n    const [tag, name, attributes] = match;\n    if (!isHiddenElement(attributes)) continue;\n    const start = match.index;\n    let end = start + tag.length;\n    if (!VOID_TAGS.has(name.toLowerCase()) && !isSelfClosingTag(tag)) {\n      // Unclosed, it is left in place rather than taking the rest of the page with it.\n      const close = findClosingTagEnd(html, name, end);\n      if (close === undefined) continue;\n      end = close;\n    }\n    result += html.slice(cursor, start);\n    cursor = end;\n    openingTag.lastIndex = end;\n  }\n  return result + html.slice(cursor);\n}\n\nfunction isHiddenElement(attributes: string): boolean {\n  const attribute = /([^\\s\"'=<>/]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+)))?/g;\n  let match: RegExpExecArray | null;\n  while ((match = attribute.exec(attributes))) {\n    const name = match[1]!.toLowerCase();\n    const value = (match[2] ?? match[3] ?? match[4] ?? \"\").trim().toLowerCase();\n    if (name === \"aria-hidden\" && value === \"true\") return true;\n    if (name === \"hidden\" && value !== \"until-found\") return true;\n  }\n  return false;\n}\n\n/**\n * `<path d=\"M0\" />`, but not `<a href=/docs/>`, whose slash ends an unquoted\n * value. HTML ignores the flag on other elements, but honoring it where it is\n * written keeps a self-closed SVG child from pairing with a later close tag.\n */\nfunction isSelfClosingTag(tag: string): boolean {\n  return /(?:^<[a-zA-Z][\\w:-]*|[\\s\"'])\\/>$/.test(tag);\n}\n\n/**\n * The end of the tag that closes the element opened before `from`, counting\n * nesting. Every tag is matched whole, quoted attribute values included, so a\n * tag written inside an attribute value is never taken for a real one.\n */\nfunction findClosingTagEnd(html: string, name: string, from: number): number | undefined {\n  const tags = /<(\\/?)([a-zA-Z][\\w:-]*)(?:[^>\"']|\"[^\"]*\"|'[^']*')*>/g;\n  tags.lastIndex = from;\n  const target = name.toLowerCase();\n  let depth = 1;\n  let match: RegExpExecArray | null;\n  while ((match = tags.exec(html))) {\n    if (match[2]!.toLowerCase() !== target) continue;\n    if (match[1]) {\n      depth -= 1;\n      if (depth === 0) return match.index + match[0].length;\n    } else if (!isSelfClosingTag(match[0])) {\n      depth += 1;\n    }\n  }\n  return undefined;\n}\n\nfunction stripTags(input: string): string {\n  return input.replace(/<[^>]+>/g, \"\");\n}\n\nfunction escapeHtmlText(input: string): string {\n  return input.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\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 * Compare a caller-supplied secret against the configured one without leaking\n * how much of it matched.\n *\n * `===` on strings stops at the first differing character, so the time it takes\n * to reject a guess grows with the length of the correct prefix. Over enough\n * requests that recovers a cron or workflow secret one character at a time. This\n * always inspects every position instead.\n *\n * Deliberately not node:crypto's `timingSafeEqual`: these callers are bundled\n * into the generated Nitro runtime, which also targets edge and browser-like\n * environments where importing node:crypto breaks the build.\n */\nexport function farmSecretsMatch(provided: string, expected: string): boolean {\n  if (typeof provided !== \"string\" || typeof expected !== \"string\") return false;\n  // An unset secret must never authorize a request, including an empty guess.\n  if (expected.length === 0) return false;\n\n  // Folding the lengths in rejects a wrong-length guess without an early return.\n  let mismatch = provided.length ^ expected.length;\n  const length = Math.max(provided.length, expected.length);\n  for (let index = 0; index < length; index += 1) {\n    const providedCode = index < provided.length ? provided.charCodeAt(index) : 0;\n    const expectedCode = index < expected.length ? expected.charCodeAt(index) : 0;\n    mismatch |= providedCode ^ expectedCode;\n  }\n\n  return mismatch === 0;\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 { farmSecretsMatch } from \"./secret-compare\";\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\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const secretError = verifyWorkflowSecret(request, options.config);\n    if (secretError) return secretError;\n\n    const workflow = workflowsById.get(id);\n    if (!workflow) {\n      return Response.json({ error: `Workflow \"${id}\" was not found.` }, { status: 404 });\n    }\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/task\";\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/task\";\nimport {\n  createFarmRequestBodyErrorResponse,\n  farmSecretsMatch,\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  // Match the dev-path verifyWorkflowSecret's resolution (readFarmEnvironmentValue):\n  // runtime bindings on globalThis.__env__ first, then process.env. Reading\n  // process.env alone misses a Cloudflare Workers secret, so a correctly\n  // configured deployment would see no secret and reject every request with 401.\n  const runtimeBindings = globalThis.__env__;\n  const runtimeSecret =\n    runtimeBindings && typeof runtimeBindings === \"object\" ? runtimeBindings[secretEnv] : undefined;\n  const resolved =\n    typeof runtimeSecret === \"string\"\n      ? runtimeSecret\n      : typeof process !== \"undefined\"\n        ? process.env?.[secretEnv]\n        : undefined;\n  return inlineSecret || resolved || \"\";\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 (farmSecretsMatch(headerSecret, secret) || farmSecretsMatch(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\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n\n    if (!workflowIds.has(id)) {\n      return json({ error: \"Workflow \" + id + \" was not found.\" }, 404);\n    }\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 (farmSecretsMatch(bearer, secret) || farmSecretsMatch(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 { farmSecretsMatch } from \"./secret-compare\";\nimport { 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\n/**\n * Whether the process explicitly declares a development or test environment.\n *\n * An absent NODE_ENV is not a development signal. Plenty of container images and\n * serverless runtimes leave it unset, so treating \"not production\" as\n * development leaves an unsecured cron route open wherever the variable simply\n * was never set. Matches the fail-closed gate the auth0 and workos integrations\n * use for their development secrets.\n */\nfunction isExplicitDevelopmentEnv(): boolean {\n  const nodeEnv = readEnvironmentValue(\"NODE_ENV\");\n  return nodeEnv === \"development\" || nodeEnv === \"test\";\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 || (!getFarmRuntimeBindings() && isExplicitDevelopmentEnv())\n    );\n  }\n\n  const authorization = request.headers.get(\"authorization\") || \"\";\n  const bearer = /^Bearer (.*)$/i.exec(authorization)?.[1] || \"\";\n  const headerSecret = request.headers.get(\"x-farm-cron-secret\") || \"\";\n  // Both are checked so a caller may use either header; neither short-circuits\n  // on the first differing character.\n  return farmSecretsMatch(bearer, secret) || farmSecretsMatch(headerSecret, 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 { useNitroApp } from \"nitro/app\";\nimport { defineTask } from \"nitro/task\";\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\nconst TRACING_RUNTIME = Symbol.for(\"@farm.js/core/tracing-runtime/v1\");\nconst runtime = globalThis as typeof globalThis & {\n  [TRACING_RUNTIME]?: FarmResolvedTracingConfig;\n};\n// Match the shared event bus across separately loaded core entries. Otherwise an\n// external plugin's events would reach listeners but silently lose trace context.\nconst tracingState = (runtime[TRACING_RUNTIME] ??= 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    Object.assign(tracingState, {\n      ...config,\n      spans: new Set(config.spans),\n      attributes: { ...config.attributes },\n      ignorePaths: [...config.ignorePaths],\n    });\n    return;\n  }\n  Object.assign(\n    tracingState,\n    normalizeFarmTracingConfig(config as FarmTracingUserConfig | undefined),\n  );\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  Object.assign(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 =\n    tracingState.enabled && tracingState.spans.has(\"request\") ? new URL(request.url) : undefined;\n  const shouldTrace =\n    url && !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\n/** A registered MCP tool callback completed; not an HTTP response or an agent run. */\nexport type FarmMCPEvent = FarmEventBase & {\n  type: \"mcp.tool.complete\";\n  /** Configured transport path, never a raw request URL. */\n  route: string;\n  server: string;\n  tool: string;\n  outcome: \"success\" | \"error\";\n  durationMs: number;\n};\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  | FarmMCPEvent\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 OBSERVABILITY_RUNTIME = Symbol.for(\"@farm.js/core/observability-runtime/v1\");\ninterface ObservabilityRuntime {\n  handlers: Set<FarmEventHandler>;\n  unfilteredHandlers: Set<FarmEventHandler>;\n  config: FarmResolvedObservabilityConfig;\n}\n// Plugins can load a different core entry (CJS/ESM or Vite/source). Like the\n// request and after() stores, event delivery belongs to the runtime, not a copy\n// of this module. Keep the state object stable so reset/configure reach all copies.\nconst runtime = globalThis as typeof globalThis & {\n  [OBSERVABILITY_RUNTIME]?: ObservabilityRuntime;\n};\nconst shared = (runtime[OBSERVABILITY_RUNTIME] ??= {\n  handlers: new Set<FarmEventHandler>(),\n  unfilteredHandlers: new Set<FarmEventHandler>(),\n  config: { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) },\n});\nconst runtimeHandlers = shared.handlers;\nconst unfilteredRuntimeHandlers = shared.unfilteredHandlers;\nconst observabilityState = shared.config;\n\nexport function configureFarmObservability(config: FarmObservabilityUserConfig | undefined): void {\n  Object.assign(\n    observabilityState,\n    { events: undefined },\n    normalizeFarmObservabilityConfig(config),\n  );\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  Object.assign(observabilityState, {\n    logs: false,\n    handlers: [],\n    events: undefined,\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    \"server\",\n    \"tool\",\n    \"outcome\",\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 FarmCacheInvalidationSource = \"local\" | \"broadcast\" | \"live\";\nexport type FarmCacheInvalidationListener = (\n  key: string,\n  source: FarmCacheInvalidationSource,\n) => 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(\n  key: string,\n  source: FarmCacheInvalidationSource = \"local\",\n): 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, source);\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(\n  keys: unknown,\n  source: FarmCacheInvalidationSource = \"local\",\n): void {\n  if (!Array.isArray(keys)) return;\n\n  for (const key of keys) {\n    if (typeof key === \"string\") {\n      notifyFarmCacheInvalidation(key, source);\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","import type { RouteModule } from \"./types\";\n\n/**\n * The rendering-mode merge shared by every consumer of route directives.\n *\n * Development resolves `\"use ssg; 60\"` and friends by reading the route\n * source; production output cannot read files, so the build bakes the parsed\n * directive into each route registration and the generated server entry\n * merges it here with the module's exports - the same precedence, one\n * implementation, no filesystem dependency so edge presets stay clean.\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 DirectiveRenderingConfig {\n  ssg: boolean;\n  ppr: boolean;\n  revalidate?: number;\n  dynamic?: RouteRenderingDynamic;\n  directive: string;\n  /**\n   * The route's source reads request state (headers, cookies, search params),\n   * so its HTML is per request and must never enter a shared artifact or a\n   * shared cache. Determined from source at build time, because the runtime\n   * only ever sees module exports.\n   */\n  requestBound?: boolean;\n}\n\nexport function 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\n/** Merge a parsed rendering directive with a route module's explicit exports. */\nexport function mergeRouteRenderingDirectiveConfig(\n  directiveConfig: DirectiveRenderingConfig | undefined,\n  mod: RouteModule | null | undefined,\n  options?: RouteRenderingOptions,\n): RouteRenderingConfig {\n  const pprEnabled = options?.experimentalPPR === true;\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  // A request-bound route cannot be static however it asked to be: the\n  // directive, an `ssg` export, a positive `revalidate`, and `force-static` all\n  // reach this point as ssg, and each of them would publish one visitor's HTML\n  // under a shared cache-control. This mirrors resolveRouteRenderingConfig, so\n  // the build, the prerender pass and the production runtime agree.\n  if (directiveConfig?.requestBound && ssg) {\n    ssg = 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 * 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 {\n  mergeRouteRenderingDirectiveConfig,\n  type DirectiveRenderingConfig,\n  type RouteRenderingConfig,\n  type RouteRenderingDynamic,\n  type RouteRenderingOptions,\n} from \"./route-rendering\";\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 {\n  DirectiveRenderingConfig,\n  RouteRenderingConfig,\n  RouteRenderingDynamic,\n  RouteRenderingOptions,\n} from \"./route-rendering\";\n\nexport interface StaticRouteCandidateAnalysis {\n  candidate: boolean;\n  blockers: 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  return mergeRouteRenderingDirectiveConfig(parseRouteRenderingDirective(source), mod, options);\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\nexport function 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 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 optionalCatchAllParams = getOptionalCatchAllParameterNames(route.path);\n          const materializedPages = paths.map((params) => ({\n            urlPath: materializeSSGRoutePath(route.path, params),\n            filePath: route.filePath,\n            params: normalizeStaticPathParams(params, optionalCatchAllParams),\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 getOptionalCatchAllParameterNames(routePattern: string): ReadonlySet<string> {\n  return new Set(\n    routePattern\n      .split(\"/\")\n      .map((segment) => segment.match(OPTIONAL_CATCH_ALL_SEGMENT)?.[1])\n      .filter((name): name is string => Boolean(name)),\n  );\n}\n\nfunction normalizeStaticPathParams(\n  params: StaticPathParams,\n  optionalCatchAllParams: ReadonlySet<string>,\n): Record<string, string> {\n  const entries = Object.entries(params).map(([key, value]): [string, string] => {\n    const emptyOptionalCatchAll =\n      optionalCatchAllParams.has(key) &&\n      (isMissingPathValue(value) || (isStaticPathArray(value) && value.length === 0));\n    return [\n      key,\n      emptyOptionalCatchAll\n        ? \"\"\n        : isStaticPathArray(value)\n          ? value.map(String).join(\"/\")\n          : String(value),\n    ];\n  });\n\n  for (const name of optionalCatchAllParams) {\n    if (!Object.prototype.hasOwnProperty.call(params, name)) {\n      entries.push([name, \"\"]);\n    }\n  }\n\n  return Object.fromEntries(entries);\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","/**\n * Tokenizer-aware extractor for programmatic route path literals.\n *\n * `page(\"/…\")` / `createRoute(\"/…\")` declarations are discovered by scanning raw source\n * files. A naive regex over the raw source matches the same call shape inside comments,\n * string literals, regex literals, and member-access calls (e.g. `pager.page(\"/x\")`),\n * which can feed non-call text through `normalizeProgrammaticRoutePath` (crashing the\n * type-generation step) or silently widen the generated route unions with phantom paths.\n *\n * This module walks the source with a tiny lexer that classifies every code region\n * (skipping comments, string literals, template literals, and regex literals) and only\n * collects string-literal first arguments of real `page(…)` / `createRoute(…)` call\n * expressions. The previous significant token is tracked so member-access calls are\n * excluded and `/` is disambiguated as a regex literal versus a division operator.\n *\n * Static template-literal arguments (`` page(`/products/list`, …) `` with no `${…}`)\n * are preserved; dynamic templates are excluded.\n */\n\nexport function extractProgrammaticPageCallPathLiterals(source: string): string[] {\n  const results = new Set<string>();\n  const length = source.length;\n  let cursor = 0;\n  const controlParentheses: boolean[] = [];\n  let nextParenthesisIsControl = false;\n\n  type PrevKind =\n    | \"none\"\n    | \"identifier\"\n    | \"keyword\"\n    | \"value\" // string, template, regex, number, or value keyword\n    | \"dot\" // `.` member access\n    | \"questionDot\" // `?.` optional member access\n    | \"spread\" // `...`\n    | \"open\" // `(`, `[`, `{`\n    | \"close\" // `)`, `]`, `}`\n    | \"operator\"; // anything else that may begin an expression\n  let prev: PrevKind = \"none\";\n\n  const isWhitespace = (char: string): boolean =>\n    char === \" \" ||\n    char === \"\\t\" ||\n    char === \"\\n\" ||\n    char === \"\\r\" ||\n    char === \"\\f\" ||\n    char === \"\\v\";\n  const isIdentifierStart = (char: string): boolean => /[A-Za-z_$]/.test(char);\n  const isIdentifierPart = (char: string): boolean => /[A-Za-z0-9_$]/.test(char);\n  const isDigit = (char: string): boolean => char >= \"0\" && char <= \"9\";\n\n  // Keywords that are followed by an expression (regex literals may follow).\n  const EXPRESSION_KEYWORDS = new Set([\n    \"return\",\n    \"typeof\",\n    \"delete\",\n    \"void\",\n    \"new\",\n    \"throw\",\n    \"instanceof\",\n    \"in\",\n    \"of\",\n    \"await\",\n    \"yield\",\n    \"else\",\n    \"do\",\n    \"case\",\n  ]);\n  // Identifier-like keywords that denote a value (division follows).\n  const VALUE_KEYWORDS = new Set([\"true\", \"false\", \"null\", \"this\", \"super\", \"undefined\"]);\n  const CONTROL_PAREN_KEYWORDS = new Set([\"if\", \"for\", \"while\", \"switch\", \"with\", \"catch\"]);\n\n  const REGEX_CONTEXT: ReadonlySet<PrevKind> = new Set([\n    \"none\",\n    \"open\",\n    \"operator\",\n    \"keyword\",\n    \"spread\",\n  ]);\n\n  function readIdentifier(start: number): { end: number; text: string } {\n    let end = start;\n    while (end < length && isIdentifierPart(source[end])) end++;\n    return { end, text: source.slice(start, end) };\n  }\n\n  function readStringLiteral(\n    start: number,\n    quote: string,\n  ): { end: number; content: string } | null {\n    let end = start + 1;\n    while (end < length) {\n      const char = source[end];\n      if (char === \"\\\\\") {\n        end += 2;\n        continue;\n      }\n      if (char === quote) {\n        return { end: end + 1, content: source.slice(start + 1, end) };\n      }\n      end++;\n    }\n    return null;\n  }\n\n  function readTemplateLiteral(start: number): {\n    end: number;\n    content: string;\n    dynamic: boolean;\n  } | null {\n    let end = start + 1;\n    let dynamic = false;\n    while (end < length) {\n      const char = source[end];\n      if (char === \"\\\\\") {\n        end += 2;\n        continue;\n      }\n      if (char === \"`\") {\n        return { end: end + 1, content: source.slice(start + 1, end), dynamic };\n      }\n      if (char === \"$\" && source[end + 1] === \"{\") {\n        dynamic = true;\n        const after = skipTemplateInterpolation(end + 2);\n        if (after === -1) return null;\n        end = after;\n        continue;\n      }\n      end++;\n    }\n    return null;\n  }\n\n  function skipTemplateInterpolation(start: number): number {\n    let end = start;\n    let depth = 1;\n    while (end < length && depth > 0) {\n      const char = source[end];\n      if (char === \"\\\\\") {\n        end += 2;\n        continue;\n      }\n      if (char === \"{\") {\n        depth++;\n        end++;\n        continue;\n      }\n      if (char === \"}\") {\n        depth--;\n        end++;\n        continue;\n      }\n      if (char === '\"' || char === \"'\") {\n        const result = readStringLiteral(end, char);\n        if (!result) return -1;\n        end = result.end;\n        continue;\n      }\n      if (char === \"`\") {\n        const result = readTemplateLiteral(end);\n        if (!result) return -1;\n        end = result.end;\n        continue;\n      }\n      end++;\n    }\n    return depth === 0 ? end : -1;\n  }\n\n  function readRegexLiteral(start: number): number | null {\n    let end = start + 1;\n    let inClass = false;\n    while (end < length) {\n      const char = source[end];\n      if (char === \"\\\\\") {\n        end += 2;\n        continue;\n      }\n      if (char === \"[\") {\n        inClass = true;\n        end++;\n        continue;\n      }\n      if (char === \"]\") {\n        inClass = false;\n        end++;\n        continue;\n      }\n      if (char === \"/\" && !inClass) {\n        end++;\n        while (end < length && source[end] >= \"a\" && source[end] <= \"z\") end++;\n        return end;\n      }\n      if (char === \"\\n\") return null;\n      end++;\n    }\n    return null;\n  }\n\n  function skipLineComment(start: number): number {\n    let end = start + 2;\n    while (end < length && source[end] !== \"\\n\") end++;\n    return end;\n  }\n\n  function skipBlockComment(start: number): number {\n    let end = start + 2;\n    while (end < length) {\n      if (source[end] === \"*\" && source[end + 1] === \"/\") return end + 2;\n      end++;\n    }\n    return end;\n  }\n\n  function readNumber(start: number): number {\n    const first = source[start];\n    let end = start;\n    if (first === \"0\") {\n      const prefix = source[start + 1];\n      if (\n        prefix === \"x\" ||\n        prefix === \"X\" ||\n        prefix === \"o\" ||\n        prefix === \"O\" ||\n        prefix === \"b\" ||\n        prefix === \"B\"\n      ) {\n        end = start + 2;\n        while (end < length && /[0-9a-fA-F_]/.test(source[end])) end++;\n        if (source[end] === \"n\") end++;\n        return end;\n      }\n    }\n    while (end < length && (isDigit(source[end]) || source[end] === \"_\")) end++;\n    if (source[end] === \".\") {\n      end++;\n      while (end < length && (isDigit(source[end]) || source[end] === \"_\")) end++;\n    }\n    if (source[end] === \"e\" || source[end] === \"E\") {\n      end++;\n      if (source[end] === \"+\" || source[end] === \"-\") end++;\n      while (end < length && (isDigit(source[end]) || source[end] === \"_\")) end++;\n    }\n    if (source[end] === \"n\") end++;\n    return end;\n  }\n\n  function classifyWord(text: string): PrevKind {\n    if (VALUE_KEYWORDS.has(text)) return \"value\";\n    if (EXPRESSION_KEYWORDS.has(text)) return \"keyword\";\n    return \"identifier\";\n  }\n\n  while (cursor < length) {\n    const char = source[cursor];\n\n    if (isWhitespace(char)) {\n      cursor++;\n      continue;\n    }\n\n    if (char === \"/\" && source[cursor + 1] === \"/\") {\n      cursor = skipLineComment(cursor);\n      continue;\n    }\n    if (char === \"/\" && source[cursor + 1] === \"*\") {\n      cursor = skipBlockComment(cursor);\n      continue;\n    }\n\n    if (char === '\"' || char === \"'\") {\n      const result = readStringLiteral(cursor, char);\n      prev = \"value\";\n      nextParenthesisIsControl = false;\n      cursor = result ? result.end : length;\n      continue;\n    }\n\n    if (char === \"`\") {\n      const result = readTemplateLiteral(cursor);\n      prev = \"value\";\n      nextParenthesisIsControl = false;\n      cursor = result ? result.end : length;\n      continue;\n    }\n\n    if (char === \"/\" && REGEX_CONTEXT.has(prev)) {\n      const end = readRegexLiteral(cursor);\n      if (end !== null) {\n        prev = \"value\";\n        nextParenthesisIsControl = false;\n        cursor = end;\n        continue;\n      }\n      // Not a regex literal: fall through to operator handling.\n    }\n\n    if (isIdentifierStart(char)) {\n      const { end: idEnd, text } = readIdentifier(cursor);\n      const isMemberAccess = prev === \"dot\" || prev === \"questionDot\";\n\n      let next = idEnd;\n      while (next < length && isWhitespace(source[next])) next++;\n\n      if (!isMemberAccess && (text === \"page\" || text === \"createRoute\") && source[next] === \"(\") {\n        let argStart = next + 1;\n        while (argStart < length && isWhitespace(source[argStart])) argStart++;\n        const quote = source[argStart];\n\n        if (quote === '\"' || quote === \"'\") {\n          const arg = readStringLiteral(argStart, quote);\n          if (arg) {\n            results.add(arg.content);\n            prev = \"value\";\n            nextParenthesisIsControl = false;\n            cursor = arg.end;\n            continue;\n          }\n        } else if (quote === \"`\") {\n          const arg = readTemplateLiteral(argStart);\n          if (arg) {\n            if (!arg.dynamic) results.add(arg.content);\n            prev = \"value\";\n            nextParenthesisIsControl = false;\n            cursor = arg.end;\n            continue;\n          }\n        }\n      }\n\n      prev = classifyWord(text);\n      nextParenthesisIsControl = CONTROL_PAREN_KEYWORDS.has(text);\n      cursor = idEnd;\n      continue;\n    }\n\n    if (isDigit(char) || (char === \".\" && isDigit(source[cursor + 1] || \"\"))) {\n      prev = \"value\";\n      nextParenthesisIsControl = false;\n      cursor = readNumber(cursor);\n      continue;\n    }\n\n    if (char === \"?\" && source[cursor + 1] === \".\") {\n      prev = \"questionDot\";\n      nextParenthesisIsControl = false;\n      cursor += 2;\n      continue;\n    }\n    if (char === \".\" && source[cursor + 1] === \".\" && source[cursor + 2] === \".\") {\n      prev = \"spread\";\n      nextParenthesisIsControl = false;\n      cursor += 3;\n      continue;\n    }\n    if (char === \".\" && source[cursor + 1] === \".\") {\n      prev = \"operator\";\n      nextParenthesisIsControl = false;\n      cursor += 2;\n      continue;\n    }\n    if (char === \".\") {\n      prev = \"dot\";\n      nextParenthesisIsControl = false;\n      cursor += 1;\n      continue;\n    }\n\n    if (char === \"(\") {\n      controlParentheses.push(nextParenthesisIsControl);\n      nextParenthesisIsControl = false;\n      prev = \"open\";\n      cursor++;\n      continue;\n    }\n    if (char === \"[\" || char === \"{\") {\n      nextParenthesisIsControl = false;\n      prev = \"open\";\n      cursor++;\n      continue;\n    }\n    if (char === \")\") {\n      // A regex literal may begin an expression statement immediately after a\n      // control-flow condition (`if (ready) /.../.test(value)`). A plain\n      // \"close\" token would misread that slash as division and then discover\n      // phantom page() calls inside the regex body.\n      prev = controlParentheses.pop() ? \"keyword\" : \"close\";\n      nextParenthesisIsControl = false;\n      cursor++;\n      continue;\n    }\n    if (char === \"]\" || char === \"}\") {\n      prev = \"close\";\n      nextParenthesisIsControl = false;\n      cursor++;\n      continue;\n    }\n\n    prev = \"operator\";\n    nextParenthesisIsControl = false;\n    cursor++;\n  }\n\n  return results.size > 0 ? Array.from(results) : [];\n}\n","import type { ParsedRoute } from \"./types\";\nimport {\n  assertBrowserStableRoutePath,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n} from \"./routing/specificity\";\nimport { extractProgrammaticPageCallPathLiterals } from \"./route-call-scanner\";\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  // The id ends in the route path, so a path like /feed.xml would make the\n  // production transform read the module as XML. The generated module is\n  // plain JavaScript; a trailing `lang.js` marker says so whatever the path.\n  return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeProgrammaticRoutePath(routePath))}&lang.js`;\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\n  for (const routePath of extractProgrammaticPageCallPathLiterals(source)) {\n    paths.add(normalizeProgrammaticRoutePath(routePath));\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 { encodeFarmCacheInvalidations, subscribeFarmCacheInvalidation } from \"./cache-invalidation\";\n\nconst DEFAULT_HEARTBEAT_INTERVAL_MS = 15_000;\nconst DEFAULT_RETRY_MS = 3_000;\nconst MAX_BUFFERED_BYTES = 64 * 1024;\nconst MAX_PENDING_KEYS = 1_024;\nconst textEncoder = new TextEncoder();\n\nexport interface FarmCacheInvalidationStreamOptions {\n  /** Stop the stream when the owning request is aborted. */\n  signal?: AbortSignal;\n  /** Limit which invalidation keys this client may observe. */\n  filter?: (key: string) => boolean;\n  /** SSE heartbeat interval. Set to false to disable heartbeats. */\n  heartbeatIntervalMs?: number | false;\n  /** EventSource reconnect delay announced to the browser. */\n  retryMs?: number;\n}\n\nfunction positiveDuration(value: number | undefined, fallback: number): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0\n    ? Math.floor(value)\n    : fallback;\n}\n\n/**\n * Create an app-owned SSE response that forwards this server instance's cache\n * invalidations. Authenticate the request before calling this helper and use\n * `filter` to keep tenant- or user-scoped keys private.\n */\nexport function createFarmCacheInvalidationStream(\n  options: FarmCacheInvalidationStreamOptions = {},\n): Response {\n  const heartbeatIntervalMs =\n    options.heartbeatIntervalMs === false\n      ? false\n      : positiveDuration(options.heartbeatIntervalMs, DEFAULT_HEARTBEAT_INTERVAL_MS);\n  const retryMs = positiveDuration(options.retryMs, DEFAULT_RETRY_MS);\n  let unsubscribe: (() => void) | undefined;\n  let heartbeat: ReturnType<typeof setInterval> | undefined;\n  let controller: ReadableStreamDefaultController<Uint8Array> | undefined;\n  let closed = false;\n  let flushScheduled = false;\n  const pending = new Set<string>();\n  let pendingBytes = 0;\n\n  const enqueue = (value: string) => {\n    if (closed || !controller) return;\n    const chunk = textEncoder.encode(value);\n    if (chunk.byteLength > (controller.desiredSize ?? 0)) {\n      overflow();\n      return;\n    }\n    controller.enqueue(chunk);\n  };\n\n  const cleanup = () => {\n    unsubscribe?.();\n    unsubscribe = undefined;\n    if (heartbeat !== undefined) clearInterval(heartbeat);\n    heartbeat = undefined;\n    options.signal?.removeEventListener(\"abort\", abort);\n    pending.clear();\n    pendingBytes = 0;\n  };\n\n  const stop = (closeController: boolean) => {\n    if (closed) return;\n    closed = true;\n    cleanup();\n    if (closeController) controller?.close();\n  };\n\n  const abort = () => stop(true);\n\n  const overflow = () => {\n    if (closed) return;\n    stop(false);\n    // Erroring discards queued chunks as well as releasing the bus listener.\n    // A slow consumer must not retain unbounded output while disconnected.\n    controller?.error(new Error(\"Farm cache invalidation stream exceeded its buffer limit.\"));\n  };\n\n  const flush = () => {\n    flushScheduled = false;\n    if (closed || pending.size === 0) return;\n    const encoded = encodeFarmCacheInvalidations([...pending]);\n    pending.clear();\n    pendingBytes = 0;\n    if (encoded !== null) enqueue(`data: ${encoded}\\n\\n`);\n  };\n\n  const stream = new ReadableStream<Uint8Array>(\n    {\n      start(nextController) {\n        controller = nextController;\n        if (options.signal?.aborted) {\n          stop(true);\n          return;\n        }\n\n        enqueue(`: connected\\nretry: ${retryMs}\\n\\n`);\n        unsubscribe = subscribeFarmCacheInvalidation((key) => {\n          if (closed || options.filter?.(key) === false) return;\n          // A filter may abort its own request. Do not retain work after cleanup.\n          if (closed || pending.has(key)) return;\n          // Bound the raw UTF-16 strings before encoding or waiting for a microtask.\n          if (\n            pending.size >= MAX_PENDING_KEYS ||\n            pendingBytes + key.length * 2 > MAX_BUFFERED_BYTES\n          ) {\n            overflow();\n            return;\n          }\n          pending.add(key);\n          pendingBytes += key.length * 2;\n          if (!flushScheduled) {\n            flushScheduled = true;\n            queueMicrotask(flush);\n          }\n        });\n        options.signal?.addEventListener(\"abort\", abort, { once: true });\n        if (heartbeatIntervalMs !== false) {\n          heartbeat = setInterval(() => {\n            // Heartbeats are keep-alives, not history to replay to a slow reader.\n            if (controller?.desiredSize === MAX_BUFFERED_BYTES) enqueue(\": heartbeat\\n\\n\");\n          }, heartbeatIntervalMs);\n        }\n      },\n      cancel() {\n        stop(false);\n      },\n    },\n    { highWaterMark: MAX_BUFFERED_BYTES, size: (chunk) => chunk.byteLength },\n  );\n\n  return new Response(stream, {\n    headers: {\n      \"Cache-Control\": \"no-cache, no-transform\",\n      \"Content-Type\": \"text/event-stream; charset=utf-8\",\n    },\n  });\n}\n","import { emitFarmEvent } from \"./observability\";\nimport { notifyFarmCacheInvalidation, notifyFarmCacheTask } from \"./cache-invalidation\";\nimport { getActiveFarmI18nSnapshot } from \"./i18n/bridge\";\n\nexport { applyFarmCacheInvalidations } from \"./cache-invalidation\";\nexport { createFarmCacheInvalidationStream } from \"./cache-invalidation-stream\";\nexport type { FarmCacheInvalidationStreamOptions } from \"./cache-invalidation-stream\";\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\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. `__farmDefinedCacheKeyData` is reserved for Farm's type\n * system and must not be declared by application types.\n */\nexport type DefinedCacheKey<TData, TKey extends RouteDataCacheKey = RouteDataCacheKey> = TKey & {\n  /** @internal Reserved type-only brand shared by the ESM and CommonJS declarations. */\n  readonly __farmDefinedCacheKeyData: 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  /** Maximum process-local entries retained in memory. @default 1024 */\n  maxEntries?: number;\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 activeGenerations = new Set<{ tags: ReadonlySet<string>; createdVersion: number }>();\n  private version = 0;\n  private generation = 0;\n  private adapter?: FarmCacheAdapter;\n  private namespace = \"farm\";\n  private local = true;\n  private maxEntries = 1_024;\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.activeGenerations.clear();\n    this.version = 0;\n    this.adapter = config.adapter;\n    this.namespace = normalizeCacheNamespace(config.namespace || \"farm\");\n    this.local = !config.adapter;\n    this.maxEntries = normalizePositiveInteger(config.maxEntries, 1_024, \"cache.maxEntries\");\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    this.touchEntry(key, entry);\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 revalidate = normalizeRevalidate(options.revalidate);\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,\n    };\n\n    this.storeLocalEntry(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 revalidate = normalizeRevalidate(options.revalidate);\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,\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    if (deleted) this.pruneInvalidatedTagVersions();\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 (deleted) this.pruneInvalidatedTagVersions();\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.activeGenerations.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    normalizeRevalidate(options.revalidate);\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    const initialCreatedVersion = this.version;\n    const activeGeneration = {\n      tags: new Set(tags),\n      createdVersion: initialCreatedVersion,\n    };\n    this.activeGenerations.add(activeGeneration);\n\n    try {\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      this.activeGenerations.delete(activeGeneration);\n      this.pruneInvalidatedTagVersions();\n      if (leaseToken && adapter?.releaseLease) {\n        try {\n          await adapter.releaseLease(leaseKey, leaseToken);\n        } catch (error) {\n          emitFarmEvent({ type: \"cache.error\", key, operation: \"set\", error });\n        }\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    const count = this.countEntriesForTag(normalizedTag);\n    this.invalidatedTagVersions.delete(normalizedTag);\n    this.invalidatedTagVersions.set(normalizedTag, ++this.version);\n    this.pruneInvalidatedTagVersions();\n    return count;\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.storeLocalEntry({\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 touchEntry(key: string, entry: InternalFarmCacheEntry): void {\n    this.entries.delete(key);\n    this.entries.set(key, entry);\n  }\n\n  private storeLocalEntry(entry: InternalFarmCacheEntry): void {\n    this.entries.delete(entry.key);\n    this.entries.set(entry.key, entry);\n\n    while (this.entries.size > this.maxEntries) {\n      const oldestKey = this.entries.keys().next().value as string | undefined;\n      if (oldestKey === undefined) break;\n      this.entries.delete(oldestKey);\n    }\n    this.pruneInvalidatedTagVersions();\n  }\n\n  private pruneInvalidatedTagVersions(): void {\n    // Stop as soon as a dependent entry or fill is found; do not materialize\n    // the entire cache for each invalidated tag on the write path.\n    tags: for (const [tag, invalidatedVersion] of this.invalidatedTagVersions) {\n      for (const entry of this.entries.values()) {\n        if (entry.tags.has(tag) && entry.createdVersion < invalidatedVersion) continue tags;\n      }\n      for (const generation of this.activeGenerations) {\n        if (generation.tags.has(tag) && generation.createdVersion < invalidatedVersion)\n          continue tags;\n      }\n      this.invalidatedTagVersions.delete(tag);\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  normalized = new URL(normalized, \"http://farm.invalid\").pathname;\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    throw new TypeError(\"Cache revalidate must be false or a finite, non-negative number.\");\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 normalizePositiveInteger(\n  value: number | undefined,\n  fallback: number,\n  name: string,\n): number {\n  if (value === undefined) return fallback;\n  if (!Number.isSafeInteger(value) || value <= 0) {\n    throw new TypeError(`${name} must be a positive integer.`);\n  }\n  return value;\n}\n\nfunction delay(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction normalizeCacheOptionsTags(options: FarmCacheOptions): Set<string> {\n  const tags = new Set<string>();\n  for (const tag of options.tags ?? []) {\n    tags.add(normalizeCacheTag(tag));\n  }\n  for (const routePath of options.paths ?? []) {\n    tags.add(createPathCacheTag(routePath));\n  }\n  return tags;\n}\n\nfunction assertFarmCacheEntry(\n  entry: FarmCacheEntry,\n  expectedKey: string,\n): asserts entry is FarmCacheEntry {\n  if (\n    !entry ||\n    typeof entry !== \"object\" ||\n    entry.key !== expectedKey ||\n    !Array.isArray(entry.tags) ||\n    typeof entry.createdAt !== \"number\"\n  ) {\n    throw new TypeError(\n      `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`,\n    );\n  }\n}\n\nfunction assertFarmCacheInvalidationTarget(\n  target: unknown,\n): asserts target is FarmCacheInvalidationTarget {\n  if (!target || typeof target !== \"object\") {\n    throw new TypeError(\"Cache invalidation targets must be { key }, { path }, or { tag }.\");\n  }\n\n  if (\"key\" in target) {\n    const key = (target as { key?: unknown }).key;\n    if (typeof key === \"string\" || Array.isArray(key)) return;\n  } else if (\"path\" in target && typeof (target as { path?: unknown }).path === \"string\") {\n    return;\n  } else if (\"tag\" in target && typeof (target as { tag?: unknown }).tag === \"string\") {\n    return;\n  }\n\n  throw new TypeError(\"Cache invalidation targets must contain a string/array key, path, or tag.\");\n}\n\nfunction getFunctionCacheIdentity(fn: Function): string {\n  // The name alone collides across modules — two different functions both\n  // named getUser would share cache entries. Include a hash of the source so\n  // only genuinely identical functions share, and the identity stays stable\n  // across processes and restarts.\n  const name = fn.name || \"anonymous\";\n  return `${name}:${hashFunctionSource(String(fn))}`;\n}\n\nfunction hashFunctionSource(source: string): string {\n  // FNV-1a, 32-bit.\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < source.length; index++) {\n    hash ^= source.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(36);\n}\n\nfunction compareCodepoint(a: string, b: string): number {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction serializeBinaryBytes(bytes: Uint8Array): string {\n  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction serializeCanonicalStringEntries(\n  entries: Iterable<readonly [string, string]>,\n  seen: WeakSet<object>,\n): string {\n  const valuesByKey = new Map<string, string[]>();\n  for (const [key, item] of entries) {\n    const values = valuesByKey.get(key);\n    if (values) values.push(item);\n    else valuesByKey.set(key, [item]);\n  }\n\n  return Array.from(valuesByKey.keys())\n    .sort(compareCodepoint)\n    .flatMap((key) =>\n      valuesByKey\n        .get(key)!\n        .map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`),\n    )\n    .join(\",\");\n}\n\nfunction isPlainCacheKeyObject(value: object): value is Record<string, unknown> {\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype === null) return true;\n\n  const constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n  return (\n    Object.getPrototypeOf(prototype) === null &&\n    typeof constructor === \"function\" &&\n    constructor.name === \"Object\"\n  );\n}\n\nfunction getCacheKeyValueType(value: object): string {\n  const prototype = Object.getPrototypeOf(value);\n  const constructor = prototype\n    ? Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value\n    : undefined;\n  if (typeof constructor === \"function\" && constructor.name) {\n    return constructor.name;\n  }\n\n  return Object.prototype.toString.call(value).slice(8, -1) || \"object\";\n}\n\nfunction stableSerialize(value: unknown, seen = new WeakSet<object>()): string {\n  if (value === null) return \"null\";\n  if (value === undefined) return \"undefined\";\n\n  const valueType = typeof value;\n  if (valueType === \"string\") return JSON.stringify(value);\n  if (valueType === \"number\" || valueType === \"boolean\" || valueType === \"bigint\") {\n    return `${valueType}:${String(value)}`;\n  }\n  if (valueType === \"symbol\") {\n    return `symbol:${String(value)}`;\n  }\n  if (valueType === \"function\") {\n    return `function:${getFunctionCacheIdentity(value as Function)}`;\n  }\n\n  if (value instanceof Date) {\n    // toISOString throws on an Invalid Date. Key building must not throw on a\n    // supported type, so all invalid dates share one stable marker and the\n    // caller's own validation decides what to do with the input.\n    return Number.isNaN(value.getTime()) ? \"date:invalid\" : `date:${value.toISOString()}`;\n  }\n  if (value instanceof URL) {\n    return `url:${value.toString()}`;\n  }\n  if (value instanceof RegExp) {\n    return `regexp:${value.toString()}`;\n  }\n  if (value instanceof ArrayBuffer) {\n    return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n  }\n  if (typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer) {\n    return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n  }\n  if (ArrayBuffer.isView(value)) {\n    const viewType = Object.prototype.toString.call(value).slice(8, -1);\n    const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n    return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;\n  }\n\n  if (value && typeof value === \"object\") {\n    if (seen.has(value)) {\n      return \"[Circular]\";\n    }\n    seen.add(value);\n\n    if (Array.isArray(value)) {\n      const items: string[] = [];\n      for (let index = 0; index < value.length; index++) {\n        items.push(\n          Object.prototype.hasOwnProperty.call(value, index)\n            ? stableSerialize(value[index], seen)\n            : \"[Hole]\",\n        );\n      }\n      seen.delete(value);\n      return `[${items.join(\",\")}]`;\n    }\n\n    // Set and Map keep their contents internally, so Object.entries is empty\n    // for both. Serialize the contents and sort them by codepoint so equal\n    // contents give the same key regardless of insertion order.\n    if (value instanceof Set) {\n      const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);\n      seen.delete(value);\n      return `set:[${items.join(\",\")}]`;\n    }\n    if (value instanceof Map) {\n      const items = Array.from(\n        value,\n        ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`,\n      ).sort(compareCodepoint);\n      seen.delete(value);\n      return `map:[${items.join(\",\")}]`;\n    }\n    // URLSearchParams and Headers keep their contents internally, so\n    // Object.entries is empty for both (same rationale as Set/Map above).\n    // Canonicalize key order while preserving the order of repeated values for\n    // each key. URLSearchParams treats `a=1&a=2` and `a=2&a=1` as observably\n    // different inputs, while `b=2&a=1` and `a=1&b=2` should still share a key.\n    if (value instanceof URLSearchParams) {\n      const serialized = serializeCanonicalStringEntries(value, seen);\n      seen.delete(value);\n      return `urlsearchparams:[${serialized}]`;\n    }\n    if (value instanceof Headers) {\n      const serialized = serializeCanonicalStringEntries(value, seen);\n      seen.delete(value);\n      return `headers:[${serialized}]`;\n    }\n\n    if (!isPlainCacheKeyObject(value)) {\n      throw new TypeError(\n        `Cache keys do not support ${getCacheKeyValueType(value)} values. Convert the value to an explicit stable string or structured key before caching.`,\n      );\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 { extractProgrammaticPageCallPathLiterals } from \"./route-call-scanner\";\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  // The id ends in the route path, so a path like /feed.xml would make the\n  // production transform read the module as XML. The generated module is\n  // plain JavaScript; a trailing `lang.js` marker says so whatever the path.\n  return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeRoutePath(routePath))}&lang.js`;\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\n  for (const routePath of extractProgrammaticPageCallPathLiterals(source)) {\n    if (routePath) {\n      paths.add(normalizeRoutePath(routePath));\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 { pathToFileURL } from \"url\";\nimport type { ComponentType } from \"react\";\nimport type { Metadata, RouteModule } from \"./types\";\nimport { requestAcceptsMarkdown } from \"./markdown\";\nimport type { FarmMdxComponents, FarmMdxResolvedConfig } from \"./app-markdown-config\";\n\n// Preserve the existing entry points while keeping response-only imports\n// independent of the MDX compiler's dynamic dependency graph.\nexport {\n  FARM_MARKDOWN_CONTENT_TYPE,\n  createFarmMarkdownErrorBody,\n  farmRequestWantsMarkdown,\n} from \"./markdown\";\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\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 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","import { readFile } from \"fs/promises\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport {\n  createFarmMarkdownRouteModule,\n  type FarmMarkdownPageModuleInput,\n} from \"./app-markdown-runtime\";\nimport {\n  resolveMdxConfig,\n  type FarmMdxComponents,\n  type FarmMdxResolvedConfig,\n} from \"./app-markdown-config\";\n\nexport * from \"./app-markdown-runtime\";\nexport {\n  resolveFarmMdxComponentsModulePath,\n  resolveMdxConfig,\n  type FarmMdxComponent,\n  type FarmMdxComponents,\n  type FarmMdxResolvedConfig,\n  type FarmMdxUserConfig,\n} from \"./app-markdown-config\";\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  } satisfies FarmMarkdownPageModuleInput);\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","import { pathToFileURL } from \"node:url\";\n\nexport function toFileModuleUrl(filePath: string): string {\n  return pathToFileURL(filePath).href;\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\n/**\n * How a captured interaction is reproduced once its island has hydrated.\n *\n * `click` and `submit` are held: the original event is prevented so the island\n * can hydrate, then reproduced against the same target. Activation-only\n * interactions carry no kind. They start hydration early and let native\n * behavior proceed untouched, which is what a focus or a keystroke needs.\n */\nexport type FarmIslandReplayKind = \"click\" | \"submit\";\n\n/**\n * Events that can activate a deferred island before its chunk has loaded.\n *\n * The inline pre-hydration script and the island runtime must listen to the\n * same set. An event only one of them knows about is either swallowed with no\n * hydration to follow, or never captured at all.\n */\nexport const FARM_ISLAND_ACTIVATION_EVENTS = [\"click\", \"submit\", \"pointerdown\", \"focusin\"] as const;\n\n/** Activation events whose interaction is held and replayed after hydration. */\nexport const FARM_ISLAND_REPLAYED_EVENTS = [\"click\", \"submit\"] as const;\n\n/** Elements whose activation is held and replayed rather than merely observed. */\nexport const FARM_ISLAND_REPLAYABLE_SELECTOR =\n  'button,[role=\"button\"],input[type=\"button\"],input[type=\"submit\"],input[type=\"reset\"]';\n","import fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { isFarmIslandStrategy, type FarmIslandStrategy } from \"../island\";\nimport { isReactRenderer, type FarmRenderer } from \"../renderer\";\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, and its client components could not become\n   * isolated islands either. The server-rendered HTML stays intact and those\n   * client components are not interactive.\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   * The owner is an async server component whose client components hydrate\n   * as isolated islands. Set regardless of the experiment mode.\n   */\n  asyncOwnerIslands?: true;\n  /** Packages whose client components a Markdown page or async owner renders as static server HTML. */\n  staticPackageBoundaries?: string[];\n}\n\nexport interface FarmClientHydrationPlanOptions {\n  /**\n   * Hydrate the client components of an async server page or layout as\n   * isolated islands whatever the experiment mode is. React cannot run the\n   * async owner in the browser, so independent roots are the only way its\n   * client components become interactive. Pass false for renderers without\n   * isolated roots, and when an integration provider has to wrap the whole\n   * route.\n   */\n  asyncOwnerIslands?: boolean;\n}\n\n/**\n * Async owners get islands on React, the renderer with isolated roots, unless\n * an integration provider has to wrap the whole route (an island would render\n * outside it).\n */\nexport function getFarmClientHydrationPlanOptions(\n  renderer: Pick<FarmRenderer, \"name\"> | undefined,\n  hasUnsupportedIntegrationProvider: boolean,\n): FarmClientHydrationPlanOptions {\n  return { asyncOwnerIslands: isReactRenderer(renderer) && !hasUnsupportedIntegrationProvider };\n}\n\n/** The warning for an async owner whose client components stay static. */\nexport function describeSuppressedAsyncHydration(subject: string, reason?: string): string {\n  const remediation = reason\n    ? \"Fix the reason above, or render the interactive UI from a synchronous owner.\"\n    : 'Move the interactive UI into an eligible \"use client\" boundary, or render it from a synchronous owner.';\n  return (\n    `${subject} is an async server component with client-side hydration enabled. React cannot ` +\n    `hydrate an async component, and that hydration could not be moved to isolated islands${reason ? ` (${reason})` : \"\"}, ` +\n    `so it stays server-rendered without client-side interactivity. ${remediation}`\n  );\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  options: FarmClientHydrationPlanOptions = {},\n): ClientModuleHydrationPlan {\n  const metadata = getClientModuleMetadata(modulePath, root);\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  // An async owner has no route-wide root to fall back to, so its client\n  // components become islands whatever the mode, and the cost guard (which\n  // weighs islands against that route-wide root) does not apply.\n  const asyncOwner =\n    metadata.suppressedAsyncHydration === true && options.asyncOwnerIslands === true;\n\n  if (mode === \"off\" && !asyncOwner) return emptyPlan();\n\n  // Legacy metadata already inspected the owner. Only reread it when isolation\n  // analysis is needed, including async-owner islands with the experiment off.\n  const resolvedPath = resolveModuleSourcePath(modulePath, root);\n  const content = readIfExists(resolvedPath ?? \"\");\n  const parsed = parseClientModuleMetadata(content, true);\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  // An async owner never hydrates as a whole, so a package client component it renders (an icon\n  // library, say) stays static HTML instead of keeping every local island static too.\n  const inspection = collectIsolatedClientBoundaries(resolvedPath, root, {\n    allowDynamicCardinality: asyncOwner,\n    staticPackageBoundaries: asyncOwner,\n  });\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 (!asyncOwner && 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\" || asyncOwner;\n  const plan: ClientModuleHydrationPlan = {\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  if (asyncOwner) {\n    delete plan.suppressedAsyncHydration;\n    plan.asyncOwnerIslands = true;\n    if (inspection.staticPackages.length > 0)\n      plan.staticPackageBoundaries = inspection.staticPackages;\n  }\n  return plan;\n}\n\n/**\n * A Markdown page renders its configured MDX components into server HTML and has no route-wide\n * client root. Like an async owner, the client components those MDX components import hydrate\n * as isolated islands whatever the experiment mode is.\n */\nexport function getMarkdownPageHydrationPlan(\n  componentsModulePath: string | undefined,\n  root: string | undefined,\n  mode: FarmIsolatedClientHydrationMode = \"off\",\n  options: FarmClientHydrationPlanOptions = {},\n): ClientModuleHydrationPlan {\n  const plan: ClientModuleHydrationPlan = {\n    isClientComponent: false,\n    shouldHydrate: false,\n    islandStrategy: null,\n    mode,\n    legacyShouldHydrate: false,\n    legacyIslandStrategy: null,\n    estimatedIsolatedRootCount: 0,\n    isolatedHydrationEligible: false,\n    hasIsolatedClientBoundaries: false,\n    isolatedBoundaries: [],\n  };\n  if (!componentsModulePath || options.asyncOwnerIslands !== true) return plan;\n  const resolvedPath = resolveModuleSourcePath(componentsModulePath, root);\n  if (!resolvedPath) {\n    return { ...plan, fallbackReason: \"the MDX components module could not be resolved\" };\n  }\n  const inspection = collectIsolatedClientBoundaries(resolvedPath, root, {\n    allowDynamicCardinality: true,\n    staticPackageBoundaries: true,\n  });\n  if (inspection.fallbackReason) return { ...plan, fallbackReason: inspection.fallbackReason };\n  if (inspection.staticPackages.length > 0)\n    plan.staticPackageBoundaries = inspection.staticPackages;\n  if (inspection.boundaries.length === 0) return plan;\n  return {\n    ...plan,\n    estimatedIsolatedRootCount: inspection.estimatedBoundaryCount,\n    isolatedHydrationEligible: true,\n    hasIsolatedClientBoundaries: true,\n    isolatedBoundaries: inspection.boundaries,\n    asyncOwnerIslands: true,\n  };\n}\n\n/**\n * Every Markdown page shares the configured MDX components module, so one inspection of it plans\n * all of them. Inspecting it per page walked the same import graph synchronously once per page,\n * which on a large site blocked the build long enough to time out module loads.\n */\nexport function createMarkdownPageHydrationPlanner(\n  componentsModulePath: string | undefined,\n  root: string | undefined,\n  mode: FarmIsolatedClientHydrationMode = \"off\",\n  options: FarmClientHydrationPlanOptions = {},\n): () => ClientModuleHydrationPlan {\n  let plan: ClientModuleHydrationPlan | undefined;\n  // Each page gets its own copy: the route budget rewrites a page's plan in place.\n  return () => ({\n    ...(plan ??= getMarkdownPageHydrationPlan(componentsModulePath, root, mode, options)),\n  });\n}\n\ninterface FarmIsolatedHydrationRoutePlan {\n  mode: FarmIsolatedClientHydrationMode;\n  asyncOwnerIslands?: true;\n  suppressedAsyncHydration?: true;\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 (metadata.asyncOwnerIslands) {\n    // An async owner has no route-wide root: it goes back to server-only.\n    delete metadata.asyncOwnerIslands;\n    metadata.suppressedAsyncHydration = true;\n    metadata.fallbackReason = fallbackReason ?? \"a parent layout hydrates the whole route\";\n    return;\n  }\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\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    const fallbackReason = `the matched route ${route.pattern} can create ${totalRootCount} isolated roots, above the measured limit of ${boundaryLimit}`;\n\n    const remainingRootCount = () =>\n      applicableLayouts.reduce(\n        (count, layout) =>\n          count +\n          (layout.metadata.hasIsolatedClientBoundaries\n            ? layout.metadata.estimatedIsolatedRootCount\n            : 0),\n        0,\n      ) +\n      (route.metadata.hasIsolatedClientBoundaries ? route.metadata.estimatedIsolatedRootCount : 0);\n\n    // A fallback can expose a later overflow. Re-evaluate the complete chain\n    // until its isolated roots fit instead of stopping after the first owner.\n    while (remainingRootCount() > boundaryLimit) {\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\n      if (overflowingLayout) {\n        restoreRouteWideHydration(overflowingLayout.metadata, fallbackReason);\n        continue;\n      }\n      if (route.metadata.hasIsolatedClientBoundaries) {\n        restoreRouteWideHydration(route.metadata, fallbackReason);\n        continue;\n      }\n      break;\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  // A page's islands survive a route-wide layout: the layout keeps a page that does not hydrate\n  // as server HTML, and the client starts the islands inside it (createFarmServerPageBoundary).\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  options: {\n    /** Accept boundaries rendered a data-dependent number of times. */\n    allowDynamicCardinality?: boolean;\n    /**\n     * Render package client components as static server HTML instead of rejecting the owner.\n     * Only for owners with no route-wide fallback, where rejecting leaves everything static.\n     */\n    staticPackageBoundaries?: boolean;\n  } = {},\n): {\n  boundaries: IsolatedClientBoundaryReference[];\n  estimatedBoundaryCount: number;\n  staticPackages: string[];\n  costGuardExceeded?: boolean;\n  fallbackReason?: string;\n} {\n  const boundaries = new Map<string, IsolatedClientBoundaryReference>();\n  const staticPackages = new Set<string>();\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          if (options.staticPackageBoundaries) {\n            staticPackages.add(specifier);\n            continue;\n          }\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 (\n        staticUses > 0 &&\n        !options.allowDynamicCardinality &&\n        hasDynamicJsxCardinality(content, localBindings)\n      ) {\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    staticPackages: Array.from(staticPackages),\n    costGuardExceeded,\n    fallbackReason,\n  };\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  matchRouteParts,\n  matchRoutePrefix,\n  matchRoutePrefixParts,\n  splitRoutePath,\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  resolveFarmMdxComponentsModulePath,\n  resolveMdxConfig,\n} from \"../app-markdown\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { toFileModuleUrl } from \"../utils/file-module\";\nimport {\n  enforceFarmIsolatedHydrationRouteBudget,\n  getClientModuleHydrationPlan,\n  createMarkdownPageHydrationPlanner,\n  getFarmClientHydrationPlanOptions,\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    /** Why an async page's client components could not become islands. */\n    suppressedAsyncHydrationReason?: string;\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    suppressedAsyncHydration?: true;\n    /** Why an async layout's client-side hydration could not become islands. */\n    suppressedAsyncHydrationReason?: string;\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\" | \"llms\" | \"llms-full\";\n  outputName: \"sitemap.xml\" | \"robots.txt\" | \"manifest.webmanifest\" | \"llms.txt\" | \"llms-full.txt\";\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 orderedLayouts: RouteEntry[] = [];\n  private routeSlots: Map<string, RouteSlotEntry> = new Map();\n  private routeSlotOwnerSegments: Map<string, ParsedRoute[\"segments\"]> = 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.orderedLayouts = [];\n    this.routeSlots.clear();\n    this.routeSlotOwnerSegments.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    this.orderedLayouts = Array.from(this.layouts.values()).sort(\n      (left, right) => left.route.segments.length - right.route.segments.length,\n    );\n    for (const slot of this.routeSlots.values()) {\n      if (!this.routeSlotOwnerSegments.has(slot.ownerPattern)) {\n        this.routeSlotOwnerSegments.set(\n          slot.ownerPattern,\n          parseRoutePath(`${slot.ownerPattern}/page.tsx`).segments,\n        );\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    const pathParts = splitRoutePath(normalizedPath);\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 = matchRouteParts(pathParts, 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, pathParts);\n    const slots = this.findMatchingRouteSlots(normalizedPath, pathParts, 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 planOptions = getFarmClientHydrationPlanOptions(\n      this.config.renderer,\n      Boolean(unsupportedIntegrationProvider),\n    );\n    const layoutEntries = Array.from(this.layouts.values()).map((entry) => ({\n      entry,\n      metadata: getClientModuleHydrationPlan(\n        entry.modulePath,\n        normalizedProjectRoot,\n        isolatedMode,\n        planOptions,\n      ),\n    }));\n\n    // A Markdown page's client components come from the configured MDX components module.\n    const markdownPagePlan = createMarkdownPageHydrationPlanner(\n      resolveFarmMdxComponentsModulePath(resolveMdxConfig(this.config.mdx), normalizedProjectRoot),\n      normalizedProjectRoot,\n      isolatedMode,\n      planOptions,\n    );\n    const routeEntries = Array.from(this.routes.values()).map((entry) => ({\n      entry,\n      metadata: isFarmMarkdownPageFile(entry.modulePath)\n        ? markdownPagePlan()\n        : getClientModuleHydrationPlan(\n            entry.modulePath,\n            normalizedProjectRoot,\n            isolatedMode,\n            planOptions,\n          ),\n    }));\n    // Every Markdown page shares the components module, so one warning covers them all.\n    const markdownFallback = routeEntries.find(\n      ({ entry, metadata }) => isFarmMarkdownPageFile(entry.modulePath) && metadata.fallbackReason,\n    );\n    if (markdownFallback) {\n      logger.warn(\n        `[Farm.js] client components in Markdown pages stay static: ${markdownFallback.metadata.fallbackReason}.`,\n      );\n    }\n    const markdownStaticPackages = routeEntries.find(\n      ({ entry, metadata }) =>\n        isFarmMarkdownPageFile(entry.modulePath) && metadata.staticPackageBoundaries,\n    )?.metadata.staticPackageBoundaries;\n    if (markdownStaticPackages) {\n      logger.info(\n        `[Farm.js] Markdown pages render client components from ${markdownStaticPackages.join(\", \")} as static HTML: package client components cannot be isolated yet.`,\n      );\n    }\n    for (const { entry, metadata } of [...layoutEntries, ...routeEntries]) {\n      if (isFarmMarkdownPageFile(entry.modulePath) || !metadata.staticPackageBoundaries) continue;\n      logger.info(\n        `[Farm.js] ${entry.pattern} is async, so it renders client components from ${metadata.staticPackageBoundaries.join(\", \")} as static HTML: package client components cannot be isolated yet.`,\n      );\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        ...(metadata.suppressedAsyncHydration && metadata.fallbackReason\n          ? { suppressedAsyncHydrationReason: metadata.fallbackReason }\n          : {}),\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      suppressedAsyncHydration: metadata.suppressedAsyncHydration,\n      ...(metadata.suppressedAsyncHydration && metadata.fallbackReason\n        ? { suppressedAsyncHydrationReason: metadata.fallbackReason }\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  /**\n   * Rebuild route metadata transactionally for HMR. If a file is temporarily\n   * invalid while it is being edited, keep the last usable plan so unrelated\n   * updates and the next repair can still compare against it.\n   *\n   * @internal\n   */\n  regenerateClientManifest(projectRoot: string = this.config.root): FarmClientRouteManifest {\n    const previousCache = this.clientManifestCache;\n    this.clientManifestCache = undefined;\n    try {\n      return this.generateClientManifest(projectRoot);\n    } catch (error) {\n      this.clientManifestCache = previousCache;\n      throw error;\n    }\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(\n      \"**/{sitemap,robots,manifest,llms,llms-full}.{ts,js}\",\n      appDir,\n    );\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    return await import(/* @vite-ignore */ toFileModuleUrl(filePath));\n  }\n\n  /**\n   * Find all layouts that should wrap a given path\n   */\n  private findMatchingLayouts(\n    pathname: string,\n    pathnameParts = splitRoutePath(pathname),\n  ): RouteEntry[] {\n    const matchingLayouts: RouteEntry[] = [];\n\n    for (const layoutEntry of this.orderedLayouts) {\n      if (matchRoutePrefixParts(pathnameParts, layoutEntry.route.segments)) {\n        matchingLayouts.push(layoutEntry);\n      }\n    }\n\n    return matchingLayouts;\n  }\n\n  private findMatchingRouteSlots(\n    pathname: string,\n    pathnameParts: readonly string[],\n    interceptFrom?: string,\n  ): MatchedRouteSlot[] {\n    const groups = new Map<string, RouteSlotEntry[]>();\n    for (const entry of this.routeSlots.values()) {\n      if (!this.matchesRoutePrefix(pathname, entry.ownerPattern, pathnameParts)) 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 normalizedFromParts = normalizedFrom ? splitRoutePath(normalizedFrom) : 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, normalizedFromParts)),\n        )\n        .map((entry) => ({\n          entry,\n          match: matchRouteParts(pathnameParts, 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(\n    pathname: string,\n    pattern: string,\n    pathnameParts: readonly string[] = splitRoutePath(pathname),\n  ): boolean {\n    if (pattern === \"/\") return true;\n    const patternSegments =\n      this.routeSlotOwnerSegments.get(pattern) ?? parseRoutePath(`${pattern}/page.tsx`).segments;\n    return matchRoutePrefixParts(pathnameParts, 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  if (fileName === \"llms\") {\n    return { kind: \"llms\", fileName: \"llms\", outputName: \"llms.txt\" };\n  }\n  if (fileName === \"llms-full\") {\n    return { kind: \"llms-full\", fileName: \"llms-full\", outputName: \"llms-full.txt\" };\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\", \"llms\", \"llms-full\"] 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  const closeEnd = closeIndex + \"</html>\".length;\n  let document = markup.slice(start, closeEnd);\n  // React may flush Suspense reveal scripts after closing the app-authored\n  // document and Farm's outer segment wrappers. Preserve that streamed tail\n  // by moving it back inside the document body.\n  const streamedTail = markup\n    .slice(closeEnd)\n    .replace(/^(?:\\s*<\\/div>)+/i, \"\")\n    .trim();\n  if (streamedTail) {\n    document = document.replace(/<\\/body>/i, () => `${streamedTail}</body>`);\n  }\n  return document;\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\n/** Remove document title elements before inserting a higher-priority title. */\nexport function removeFarmDocumentTitles(markup: string): string {\n  return markup.replace(/<title\\b[^>]*>[\\s\\S]*?<\\/title>\\s*/gi, \"\");\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  /** Existing attributes Farm owns and must replace before merging. */\n  replaceHtmlAttributes?: readonly 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(/<html\\b([^>]*)>/i, (_match, attrs: string) => {\n      let nextAttributes = attrs;\n      for (const name of assets.replaceHtmlAttributes ?? []) {\n        const escapedName = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n        nextAttributes = nextAttributes.replace(\n          new RegExp(\"\\\\s+\" + escapedName + \"=(?:\\\"[^\\\"]*\\\"|'[^']*'|[^\\\\s>]+)\", \"gi\"),\n          \"\",\n        );\n      }\n      return `<html${nextAttributes}${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: 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","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\n/**\n * The public origin of a web `Request`, for the production runtime. The\n * adapter's `request.url` is authoritative unless `trustProxy` is on; then\n * `X-Forwarded-Host` and `X-Forwarded-Proto` override it with the same\n * validation `resolveFarmRequestURL` applies to a Node request in development.\n */\nexport function resolveFarmWebRequestOrigin(\n  request: Request,\n  options: Pick<FarmRequestURLOptions, \"trustProxy\"> = {},\n): string {\n  const url = new URL(request.url);\n  if (!options.trustProxy) return url.origin;\n\n  const forwardedHost = firstForwardedHeaderValue(\n    request.headers.get(\"x-forwarded-host\") ?? undefined,\n  );\n  const forwardedProto = firstForwardedHeaderValue(\n    request.headers.get(\"x-forwarded-proto\") ?? undefined,\n  )?.toLowerCase();\n  const proto =\n    forwardedProto === \"https\" || forwardedProto === \"http\"\n      ? forwardedProto\n      : url.protocol === \"https:\"\n        ? \"https\"\n        : \"http\";\n  return resolveRequestOrigin(proto, forwardedHost, url.host);\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","import type { FarmAgentJsonLd } from \"./agent-config\";\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 */\nexport function 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 type { FarmAgentJsonLd } from \"./agent-config\";\nimport { renderFarmAgentJsonLd, serializeJsonLd } from \"./agent-json-ld\";\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\n/**\n * Marks head tags rendered from app-defined metadata that no fixed selector can\n * match, so client navigation can find and replace them.\n */\nexport const FARM_METADATA_ATTRIBUTE = \"data-farm-metadata\";\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    jsonLd: mergeMetadataJsonLd(base.jsonLd, next.jsonLd),\n    title: mergeMetadataTitle(base.title, next.title),\n    other: mergeNestedMetadata(base.other, next.other),\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    verification: mergeNestedMetadata(base.verification, next.verification),\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\n/** Layout and page JSON-LD accumulate instead of replacing each other. */\nfunction mergeMetadataJsonLd(base: Metadata[\"jsonLd\"], next: Metadata[\"jsonLd\"]) {\n  if (base === undefined) return next;\n  if (next === undefined) return base;\n  return [...normalizeArray(base), ...normalizeArray(next)] as NonNullable<Metadata[\"jsonLd\"]>;\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\nconst MARKDOWN_MIME_TYPE = \"text/markdown\";\n\n/**\n * Advertise a page's Markdown mirror as `alternates.types[\"text/markdown\"]`\n * unless the page already declares one. `href` comes from the request path, so\n * it is kept same-origin the same way the default canonical is.\n */\nexport function addMetadataMarkdownAlternate(\n  metadata: MetadataRecord,\n  href: string | null | undefined,\n): MetadataRecord {\n  if (!href) return metadata;\n\n  const alternates = isRecord(metadata.alternates) ? metadata.alternates : {};\n  const types = isRecord(alternates.types) ? alternates.types : {};\n  if (Object.keys(types).some((type) => type.toLowerCase() === MARKDOWN_MIME_TYPE)) {\n    return metadata;\n  }\n\n  return {\n    ...metadata,\n    alternates: {\n      ...alternates,\n      types: { ...types, [MARKDOWN_MIME_TYPE]: sanitizeSelfCanonicalPathname(href) },\n    },\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  if (isRecord(resolvedMetadata.robots)) {\n    appendMetaName(tags, \"googlebot\", normalizeRobots(resolvedMetadata.robots.googleBot));\n  }\n\n  const alternates = (resolvedMetadata as any).alternates;\n  const explicitCanonical = isRecord(alternates) ? alternates.canonical : undefined;\n  // Default the canonical link to the current path when the route does not set\n  // one. This is a self-referential canonical (absolute when `metadataBase` is\n  // configured), which is safe for every page and gives agents/crawlers a\n  // stable identity for the URL.\n  const canonicalHref =\n    explicitCanonical != null\n      ? resolveMetadataUrl(explicitCanonical, metadataBase)\n      : options.pathname\n        ? resolveMetadataUrl(sanitizeSelfCanonicalPathname(options.pathname), metadataBase)\n        : undefined;\n  if (canonicalHref) {\n    appendLink(tags, \"canonical\", canonicalHref);\n  }\n\n  if (isRecord(alternates) && isRecord(alternates.languages)) {\n    for (const [language, href] of Object.entries(alternates.languages)) {\n      appendLink(tags, \"alternate\", resolveMetadataUrl(href, metadataBase), {\n        hreflang: language,\n      });\n    }\n  }\n\n  if (isRecord(alternates) && isRecord(alternates.types)) {\n    for (const [type, value] of Object.entries(alternates.types)) {\n      for (const entry of normalizeArray(value)) {\n        const link = isRecord(entry) ? entry : { url: entry };\n        appendLink(tags, \"alternate\", resolveMetadataUrl(link.url, metadataBase), {\n          type,\n          title: link.title,\n        });\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  appendNamedMetaRecord(tags, resolvedMetadata.other);\n  appendOpenGraph(tags, resolvedMetadata.openGraph, metadataBase);\n  appendTwitter(tags, resolvedMetadata.twitter, metadataBase);\n  appendVerification(tags, resolvedMetadata.verification);\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  // Page and layout JSON-LD is marked so client navigation swaps it, while the\n  // unmarked site-level script above stays put.\n  for (const entry of normalizeArray(resolvedMetadata.jsonLd)) {\n    if (!isRecord(entry)) continue;\n    tags.push(\n      `<script type=\"application/ld+json\" ${FARM_METADATA_ATTRIBUTE}>${serializeJsonLd(entry)}</script>`,\n    );\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  if (openGraph.type === \"article\") {\n    appendMetaProperty(tags, \"article:published_time\", normalizeDate(openGraph.publishedTime));\n    appendMetaProperty(tags, \"article:modified_time\", normalizeDate(openGraph.modifiedTime));\n    for (const author of normalizeArray(openGraph.authors)) {\n      appendMetaProperty(tags, \"article:author\", author);\n    }\n    appendMetaProperty(tags, \"article:section\", openGraph.section);\n    for (const tag of normalizeArray(openGraph.tags)) {\n      appendMetaProperty(tags, \"article:tag\", tag);\n    }\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\n/**\n * Meta tags named by the app. No fixed selector matches them, so they carry the\n * marker client navigation sweeps by; tags with names Farm knows do not.\n */\nfunction appendNamedMetaRecord(tags: string[], record: unknown) {\n  if (!isRecord(record)) return;\n\n  for (const [name, value] of Object.entries(record)) {\n    for (const content of normalizeArray(value)) {\n      appendMetaName(tags, name, content, true);\n    }\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, marked = false) {\n  const normalized = normalizeContent(content);\n  if (!normalized || !name) return;\n  const marker = marked ? ` ${FARM_METADATA_ATTRIBUTE}` : \"\";\n  tags.push(\n    `<meta name=\"${escapeAttribute(name)}\" content=\"${escapeAttribute(normalized)}\"${marker}>`,\n  );\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\nconst VERIFICATION_META_NAMES = [\n  [\"google\", \"google-site-verification\"],\n  [\"bing\", \"msvalidate.01\"],\n  [\"yandex\", \"yandex-verification\"],\n] as const;\n\nfunction appendVerification(tags: string[], verification: Metadata[\"verification\"]) {\n  if (!isRecord(verification)) return;\n\n  for (const [key, name] of VERIFICATION_META_NAMES) {\n    for (const token of normalizeArray(verification[key])) {\n      appendMetaName(tags, name, token);\n    }\n  }\n  appendNamedMetaRecord(tags, verification.other);\n}\n\nfunction appendLink(\n  tags: string[],\n  rel: string,\n  href: unknown,\n  attrs: Record<string, unknown> = {},\n) {\n  const normalizedHref = normalizeContent(href);\n  if (!normalizedHref) return;\n\n  const attrText = Object.entries(attrs)\n    .map(([key, value]) => {\n      const normalized = normalizeContent(value);\n      return normalized ? ` ${key}=\"${escapeAttribute(normalized)}\"` : \"\";\n    })\n    .join(\"\");\n\n  tags.push(\n    `<link rel=\"${escapeAttribute(rel)}\" href=\"${escapeAttribute(normalizedHref)}\"${attrText}>`,\n  );\n}\n\nfunction normalizeMetadataImages(\n  value: unknown,\n  metadataBase?: string,\n): Array<{\n  url: string;\n  width?: number;\n  height?: number;\n  alt?: string;\n  type?: string;\n}> {\n  return normalizeArray(value)\n    .map((item) => {\n      if (typeof item === \"string\") {\n        return { url: resolveMetadataUrl(item, metadataBase) || item };\n      }\n\n      if (!isRecord(item)) return null;\n      const rawUrl = item.url || item.src;\n      const url = resolveMetadataUrl(rawUrl, metadataBase);\n      if (!url) return null;\n\n      return {\n        url,\n        width: normalizeNumber(item.width),\n        height: normalizeNumber(item.height),\n        alt: typeof item.alt === \"string\" ? item.alt : undefined,\n        type: typeof item.type === \"string\" ? item.type : undefined,\n      };\n    })\n    .filter((item): item is NonNullable<typeof item> => item !== null);\n}\n\nfunction normalizeArray(value: unknown): unknown[] {\n  if (value == null) return [];\n  return Array.isArray(value) ? value : [value];\n}\n\nfunction hasMetadataImages(value: unknown): boolean {\n  return normalizeMetadataImages(value).length > 0;\n}\n\n/**\n * Resolve a metadata title into displayable text. Exported so client-side\n * navigation resolves the object form the same way SSR does instead of\n * stringifying it into \"[object Object]\".\n */\nexport function resolveMetadataTitle(title: Metadata[\"title\"]): string | undefined {\n  if (typeof title === \"string\") return title;\n  if (isRecord(title)) {\n    return normalizeContent(title.default);\n  }\n  return undefined;\n}\n\nfunction normalizeKeywords(keywords: Metadata[\"keywords\"]): string | undefined {\n  if (Array.isArray(keywords)) return keywords.filter(Boolean).join(\", \");\n  return keywords;\n}\n\nconst ROBOTS_FLAGS = [\"noarchive\", \"nosnippet\", \"noimageindex\"] as const;\nconst ROBOTS_VALUES = [\n  \"max-snippet\",\n  \"max-image-preview\",\n  \"max-video-preview\",\n  \"unavailable_after\",\n] as const;\n\n/** Serialize `robots` or `robots.googleBot` into a robots meta `content` value. */\nfunction normalizeRobots(robots: unknown): 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  for (const flag of ROBOTS_FLAGS) {\n    if (robots[flag] === true) values.push(flag);\n  }\n  for (const directive of ROBOTS_VALUES) {\n    const value = normalizeContent(robots[directive]);\n    if (value) values.push(`${directive}:${value}`);\n  }\n  return values.join(\", \") || undefined;\n}\n\nfunction resolveMetadataBase(metadata: MetadataRecord): string | undefined {\n  const base = metadata.metadataBase;\n  if (!base) return undefined;\n  return String(base);\n}\n\n/**\n * Keep the defaulted self-canonical on this origin. The pathname comes straight\n * from the request URL, and forms like `//evil.com` or `/\\evil.com` resolve to a\n * cross-origin URL through `new URL()` (and browsers treat `\\` as `/`), which\n * would advertise an attacker's domain as the page's canonical identity. Any\n * request path introducing an authority is collapsed to a single leading slash\n * so the canonical stays same-origin. Developer-supplied `alternates.canonical`\n * is trusted and does not pass through here.\n */\nfunction sanitizeSelfCanonicalPathname(pathname: string): string {\n  if (typeof pathname !== \"string\" || pathname.length === 0) return \"/\";\n  const collapsed = pathname.replace(/^[/\\\\]+/, \"/\");\n  return collapsed.startsWith(\"/\") ? collapsed : `/${collapsed}`;\n}\n\nfunction resolveMetadataUrl(value: unknown, metadataBase?: string): string | undefined {\n  const normalized = normalizeContent(value);\n  if (!normalized) return undefined;\n  if (!metadataBase) return normalized;\n\n  try {\n    return new URL(normalized, metadataBase).toString();\n  } catch {\n    return normalized;\n  }\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n  if (typeof value === \"number\" && Number.isFinite(value)) return value;\n  if (typeof value === \"string\") {\n    const parsed = Number(value);\n    return Number.isFinite(parsed) ? parsed : undefined;\n  }\n  return undefined;\n}\n\nfunction normalizeDate(value: unknown): string | undefined {\n  if (value instanceof Date) {\n    return Number.isNaN(value.getTime()) ? undefined : value.toISOString();\n  }\n  return normalizeContent(value);\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  /** Called only after a deferred response reaches the end of its stream. */\n  onComplete?: () => 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>(\n  response: Response,\n  options: DeferredDataResponseOptions = {},\n): Promise<T> {\n  const contentType = response.headers.get(\"Content-Type\") || \"\";\n  if (!contentType.toLowerCase().startsWith(FARM_DEFERRED_CONTENT_TYPE)) {\n    const data = (await response.json()) as T;\n    notifyDeferredComplete(options);\n    return data;\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      // The loop ends the same way whether every deferred arrived or the\n      // connection was cut mid-stream, so completion is judged by what is\n      // still outstanding. Reporting completion for a truncated stream let\n      // the caller cache page data whose deferred fields are already\n      // rejected, and a later visit replayed those errors instead of\n      // refetching.\n      const outstanding = rejectPendingDeferred(\n        controllers,\n        \"Deferred route data stream ended before completion\",\n      );\n      if (outstanding === 0) notifyDeferredComplete(options);\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\nfunction notifyDeferredComplete(options: DeferredDataResponseOptions): void {\n  try {\n    options.onComplete?.();\n  } catch {\n    // Completion observers must not break deferred stream consumption.\n  }\n}\n\ninterface EncodingContext {\n  records: DeferredRecord[];\n  ids: Map<Deferred<unknown>, string>;\n  nextId: number;\n}\n\ninterface ControlledDeferred {\n  promise: Promise<unknown> & {\n    status?: \"pending\" | \"fulfilled\" | \"rejected\";\n    value?: unknown;\n    reason?: unknown;\n  };\n  resolve(value: unknown): void;\n  reject(error: unknown): void;\n}\n\nfunction createEncodingContext(records: readonly DeferredRecord[] = []): EncodingContext {\n  return {\n    records: [...records],\n    ids: new Map(records.map((record) => [record.promise, record.id])),\n    nextId: records.reduce((highest, record) => {\n      const value = Number(record.id.replace(/^d/, \"\"));\n      return Number.isFinite(value) ? Math.max(highest, value + 1) : highest;\n    }, records.length),\n  };\n}\n\nfunction encodeDeferredValue(\n  value: unknown,\n  context: EncodingContext,\n  ancestors: WeakSet<object>,\n): unknown {\n  if (isDeferred(value)) {\n    let id = context.ids.get(value);\n    if (!id) {\n      id = `d${context.nextId++}`;\n      context.ids.set(value, id);\n      context.records.push({ id, promise: value as Deferred<unknown> });\n    }\n    return { [FARM_DEFERRED_MARKER]: id };\n  }\n  if (!value || typeof value !== \"object\") return value;\n  if (Array.isArray(value)) {\n    assertNotCircular(value, ancestors);\n    const output = value.map((item) => encodeDeferredValue(item, context, ancestors));\n    ancestors.delete(value);\n    return output;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) return value;\n\n  assertNotCircular(value, ancestors);\n  const output: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    defineDataProperty(output, key, encodeDeferredValue(item, context, ancestors));\n  }\n  ancestors.delete(value);\n  // User data that happens to have the marker shape must not be revived as a\n  // deferred reference. Real ids never start with \"!\", so prefix-escape the\n  // value; revive strips one \"!\" back off.\n  if (isDeferredMarker(output)) {\n    return { [FARM_DEFERRED_MARKER]: `!${output[FARM_DEFERRED_MARKER]}` };\n  }\n  return output;\n}\n\nfunction reviveDeferredValue(\n  value: unknown,\n  controllers: Map<string, ControlledDeferred>,\n  settlements?: DeferredSettlements,\n  applyingSettlements = new Set<string>(),\n): unknown {\n  if (isDeferredMarker(value)) {\n    const id = value[FARM_DEFERRED_MARKER];\n    // Escaped user data, not a deferred reference — restore the original.\n    if (id.startsWith(\"!\")) {\n      return { [FARM_DEFERRED_MARKER]: id.slice(1) };\n    }\n    const controller = getControlledDeferred(id, controllers);\n    const settlement = settlements?.[id];\n    if (settlement && controller.promise.status === \"pending\") {\n      if (applyingSettlements.has(id)) return controller.promise;\n      applyingSettlements.add(id);\n      if (settlement.status === \"fulfilled\") {\n        controller.resolve(\n          reviveDeferredValue(settlement.value, controllers, settlements, applyingSettlements),\n        );\n      } else {\n        controller.reject(new DeferredDataError(settlement.error.message));\n      }\n      applyingSettlements.delete(id);\n    } else if (settlements && controller.promise.status === \"pending\") {\n      controller.reject(new DeferredDataError(\"Deferred route data was not resolved\"));\n    }\n    return controller.promise;\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) =>\n      reviveDeferredValue(item, controllers, settlements, applyingSettlements),\n    );\n  }\n  if (!value || typeof value !== \"object\") return value;\n\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) return value;\n  const output: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    defineDataProperty(\n      output,\n      key,\n      reviveDeferredValue(item, controllers, settlements, applyingSettlements),\n    );\n  }\n  return output;\n}\n\n// Assign an own key preserving its data. A plain `output[key] = value` runs the\n// `Object.prototype.__proto__` setter when `key` is the string \"__proto__\" (the\n// shape JSON.parse of external input produces), which silently drops the entry\n// and mutates the object's prototype instead of storing the value. Defining the\n// property sidesteps the accessor for that one key; other keys keep the fast path.\nfunction defineDataProperty(output: Record<string, unknown>, key: string, value: unknown): void {\n  if (key === \"__proto__\") {\n    Object.defineProperty(output, key, {\n      value,\n      enumerable: true,\n      writable: true,\n      configurable: true,\n    });\n  } else {\n    output[key] = value;\n  }\n}\n\nfunction getControlledDeferred(\n  id: string,\n  controllers: Map<string, ControlledDeferred>,\n): ControlledDeferred {\n  const existing = controllers.get(id);\n  if (existing) return existing;\n\n  let nativeResolve!: (value: unknown) => void;\n  let nativeReject!: (error: unknown) => void;\n  const promise = new Promise<unknown>((resolve, reject) => {\n    nativeResolve = resolve;\n    nativeReject = reject;\n  }) as ControlledDeferred[\"promise\"];\n  promise.status = \"pending\";\n  promise.catch(() => undefined);\n\n  const controlled: ControlledDeferred = {\n    promise,\n    resolve(value) {\n      if (promise.status !== \"pending\") return;\n      promise.status = \"fulfilled\";\n      promise.value = value;\n      nativeResolve(value);\n    },\n    reject(error) {\n      if (promise.status !== \"pending\") return;\n      promise.status = \"rejected\";\n      promise.reason = error;\n      nativeReject(error);\n    },\n  };\n  controllers.set(id, controlled);\n  return controlled;\n}\n\nfunction readDeferredState(promise: Deferred<unknown>): DeferredState {\n  const tracked = deferredStates.get(promise);\n  if (tracked && tracked.status !== \"pending\") return tracked;\n\n  const reactState = promise as Deferred<unknown> & {\n    status?: string;\n    value?: unknown;\n    reason?: unknown;\n  };\n  if (reactState.status === \"fulfilled\") {\n    return { status: \"fulfilled\", value: reactState.value };\n  }\n  if (reactState.status === \"rejected\") {\n    return { status: \"rejected\", reason: reactState.reason };\n  }\n  return tracked || { status: \"pending\" };\n}\n\nfunction isDeferredMarker(value: unknown): value is { [FARM_DEFERRED_MARKER]: string } {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    Object.keys(value).length === 1 &&\n    typeof (value as Record<string, unknown>)[FARM_DEFERRED_MARKER] === \"string\",\n  );\n}\n\nfunction assertNotCircular(value: object, ancestors: WeakSet<object>): void {\n  if (ancestors.has(value)) {\n    throw new TypeError(\"Deferred route data must be JSON-serializable and cannot be circular\");\n  }\n  ancestors.add(value);\n}\n\nfunction createDeferredPublicError() {\n  return {\n    code: FARM_DEFERRED_ERROR_CODE,\n    message: \"Deferred route data failed to load\",\n  } as const;\n}\n\nfunction createRejectedSettlement(): DeferredSettlement {\n  return { status: \"rejected\", error: createDeferredPublicError() };\n}\n\nfunction reportDeferredError(\n  options: DeferredDataResponseOptions,\n  error: unknown,\n  id: string,\n): void {\n  try {\n    options.onError?.(error, id);\n  } catch {\n    // Error reporting must not break the response stream.\n  }\n}\n\nfunction encodeDeferredMessage(message: Record<string, unknown>): string {\n  return `${JSON.stringify(message)}\\n`;\n}\n\nfunction parseDeferredMessage(line: string): any {\n  try {\n    return JSON.parse(line);\n  } catch {\n    throw new DeferredDataError(\"Deferred route data response contains invalid JSON\");\n  }\n}\n\n/** Rejects every deferred still outstanding, and reports how many there were. */\nfunction rejectPendingDeferred(\n  controllers: Map<string, ControlledDeferred>,\n  message: string,\n): number {\n  let rejected = 0;\n  for (const controller of controllers.values()) {\n    if (controller.promise.status === \"pending\") {\n      controller.reject(new DeferredDataError(message));\n      rejected += 1;\n    }\n  }\n  return rejected;\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 isFarmI18nCatalogFile(\n  config: Pick<ResolvedFarmI18nConfig, \"enabled\" | \"messages\" | \"locales\">,\n  file: string,\n): boolean {\n  if (!config.enabled) return false;\n  const normalizedFile = file.replace(/\\\\/g, \"/\");\n  return config.locales.some(\n    (locale) => resolveFarmI18nMessagePath(config, locale).replace(/\\\\/g, \"/\") === normalizedFile,\n  );\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    // The locale canonical is always trailing-slash-free, but the app's dedicated\n    // trailing-slash redirect owns that normalization. When the only difference is\n    // a trailing slash, defer to it: otherwise, under trailingSlash: true, the i18n\n    // redirect (strip) and the trailing-slash redirect (add) bounce a locale URL\n    // between 307 and 308 forever and every locale page becomes unreachable.\n    const differsOnlyByTrailingSlash =\n      canonicalPath !== url.pathname &&\n      (url.pathname.length > 1 ? url.pathname.replace(/\\/+$/, \"\") : url.pathname) === canonicalPath;\n    const redirect =\n      options.redirect !== false && canonicalPath !== url.pathname && !differsOnlyByTrailingSlash\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  const base = locales.find((locale) => locale.toLowerCase() === language);\n  if (base) return base;\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 { localizeFarmPathname, type FarmLocalePathConfig } from \"./routing\";\n\nexport interface FarmLocaleAlternateLinkOptions {\n  /**\n   * The route's `metadataBase`. Preferred over the request origin when it is an\n   * absolute http(s) URL, so every alternate advertises the app's canonical host.\n   */\n  metadataBase?: unknown;\n  /**\n   * The trusted request origin (`server.trustProxy` decides whether forwarded\n   * authority headers count). Used when no usable `metadataBase` is set.\n   */\n  origin?: string;\n}\n\n/**\n * Render `<link rel=\"alternate\" hreflang>` tags for every configured locale plus\n * `x-default`. Search engines ignore relative hreflang URLs, so each href is\n * resolved against `metadataBase`, otherwise against the request origin. With\n * neither available the localized path is emitted as-is.\n */\nexport function renderFarmLocaleAlternateLinks(\n  pathname: string,\n  config: FarmLocalePathConfig,\n  options: FarmLocaleAlternateLinkOptions = {},\n): string {\n  if (config.routing === \"none\") return \"\";\n  const base = resolveAlternateBase(options);\n  const link = (hreflang: string, locale: string) =>\n    `<link rel=\"alternate\" hreflang=\"${escapeHtmlAttribute(hreflang)}\" href=\"${escapeHtmlAttribute(\n      resolveAlternateHref(localizeFarmPathname(pathname, locale, config), base),\n    )}\">`;\n  const links = config.locales.map((locale) => link(locale, locale));\n  links.push(link(\"x-default\", config.defaultLocale));\n  return links.join(\"\");\n}\n\nfunction resolveAlternateBase(options: FarmLocaleAlternateLinkOptions): URL | undefined {\n  for (const candidate of [options.metadataBase, options.origin]) {\n    if (typeof candidate !== \"string\" && !(candidate instanceof URL)) continue;\n    try {\n      const url = new URL(candidate);\n      if (url.protocol === \"http:\" || url.protocol === \"https:\") return url;\n    } catch {\n      // A relative or malformed metadataBase falls through to the request origin.\n    }\n  }\n  return undefined;\n}\n\nfunction resolveAlternateHref(pathname: string, base: URL | undefined): string {\n  if (!base) return pathname;\n  // A leading `//` or `\\` would make the path an authority and move the\n  // alternate off the base host, so it is collapsed to one slash first.\n  return new URL(pathname.replace(/^[/\\\\]+/, \"/\"), base).href;\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","/**\n * Document tails for a redirect() or notFound() thrown after a streamed\n * response already sent its 200 shell. The status can no longer change, so\n * the document recovers in the browser, as Next.js does: a redirect replaces\n * the location, and notFound() swaps the page for the not-found UI, marks\n * the document noindex so crawlers do not index the missing page, and tells\n * client startup not to hydrate the page that threw.\n */\n\nconst PAGE_CONTAINER_ID = \"__farm_page__\";\nconst TEMPLATE_ID = \"__farm_late_not_found__\";\n\nfunction serializeForInlineScript(value: string): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\n/**\n * Only http(s) targets may become a client-side redirect: `location.replace`\n * would run a `javascript:` URL. Parsed the way browsers parse it, so tab,\n * newline and case tricks normalize first.\n */\nexport function isLateRedirectTarget(url: string): boolean {\n  try {\n    const protocol = new URL(url, \"https://farm.invalid\").protocol;\n    return protocol === \"http:\" || protocol === \"https:\";\n  } catch {\n    return false;\n  }\n}\n\n/** Empty when the target is not an http(s) URL; the page then stays as rendered. */\nexport function createLateRedirectRecovery(url: string): string {\n  if (!isLateRedirectTarget(url)) return \"\";\n  return `<script>window.location.replace(${serializeForInlineScript(url)})</script>`;\n}\n\n/** `content` is the rendered not-found markup (the app's not-found page or the built-in one). */\nexport function createLateNotFoundRecovery(content: string): string {\n  return (\n    `<template id=\"${TEMPLATE_ID}\">${content}</template>` +\n    `<script>(function(){var t=document.getElementById(\"${TEMPLATE_ID}\");` +\n    `var p=document.getElementById(\"${PAGE_CONTAINER_ID}\");` +\n    `if(t&&p){p.replaceChildren(t.content.cloneNode(true));}if(t)t.remove();` +\n    // Client startup reads this and never hydrates the page that threw.\n    `document.documentElement.dataset.farmLateNotFound=\"true\";` +\n    `var m=document.createElement(\"meta\");m.name=\"robots\";m.content=\"noindex\";` +\n    `document.head.appendChild(m);})();</script>`\n  );\n}\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      let resolvedType: unknown;\n      try {\n        resolvedType = type._init(type._payload);\n      } catch (suspension) {\n        if (suspension && typeof (suspension as Promise<unknown>).then === \"function\") {\n          await suspension;\n          resolvedType = type._init(type._payload);\n        } else {\n          throw suspension;\n        }\n      }\n      return prepareMetadataImageNode(createElement(resolvedType as any, 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","/**\n * llms.txt (https://llmstxt.org): a Markdown index at `/llms.txt` that tells\n * language models what a site is and where its readable pages live, plus\n * `/llms-full.txt`, the same index with each page's Markdown inlined.\n *\n * `agent.llmsTxt` in farm.config.ts serves a generated index of the app's static\n * pages. A `src/app/llms.ts` metadata route replaces it with whatever it returns,\n * and receives the generated pages and defaults to build on. The development\n * renderer and the generated production server both call into this module, so\n * the two serve the same file.\n */\nimport { applyFarmBasePath } from \"./base-path\";\nimport {\n  getFarmMarkdownMirrorPath,\n  isFarmMarkdownMirrorExposed,\n  matchesFarmMarkdownRoutePattern,\n  type FarmMarkdownResolvedConfig,\n} from \"./markdown\";\n\nexport interface FarmLlmsTxtLink {\n  title: string;\n  url: string;\n  description?: string;\n}\n\nexport interface FarmLlmsTxtSection {\n  title: string;\n  links: FarmLlmsTxtLink[];\n}\n\nexport interface FarmLlmsTxt {\n  /** Site or project name, rendered as the `# H1`. Required by the format. */\n  title: string;\n  /** One-sentence summary, rendered as a `> blockquote`. */\n  summary?: string;\n  /** Free-form Markdown placed after the summary. */\n  details?: string;\n  /** `## H2` sections of links. A section titled \"Optional\" marks skippable links. */\n  sections?: FarmLlmsTxtSection[];\n}\n\n/** A static page of the app, ready to use as an llms.txt link. */\nexport interface FarmLlmsTxtPage extends FarmLlmsTxtLink {\n  /** The page's route path, such as `/docs/install`. */\n  path: string;\n}\n\nexport interface FarmLlmsTxtUserConfig {\n  /** Set to `false` to turn llms.txt off while keeping these options. */\n  enabled?: boolean;\n  /** Site name for the `# H1`. Defaults to the root layout's metadata title. */\n  title?: string;\n  /** Summary for the `> blockquote`. Defaults to the root layout's metadata description. */\n  summary?: string;\n  /** Markdown placed after the summary. */\n  details?: string;\n  /**\n   * Route patterns to list, using the same syntax as `md.expose`\n   * (`/docs/[...slug]`). Defaults to every static page.\n   */\n  include?: string[];\n  /** Route patterns to leave out, such as `/admin/[...path]`. */\n  exclude?: string[];\n  /**\n   * Also serve `/llms-full.txt`, the index with each page's Markdown mirror inlined.\n   *\n   * @default true\n   */\n  full?: boolean;\n  /**\n   * Seconds a CDN may cache the generated files. Rendering llms-full.txt renders\n   * every listed page, so cache it on busy sites. Defaults to no caching.\n   */\n  revalidate?: number;\n}\n\nexport interface ResolvedFarmLlmsTxtConfig {\n  enabled: boolean;\n  title?: string;\n  summary?: string;\n  details?: string;\n  include: string[];\n  exclude: string[];\n  full: boolean;\n  revalidate?: number;\n}\n\nexport interface FarmLlmsTxtPageSource {\n  pattern: string;\n  metadata?: unknown;\n}\n\nexport function resolveFarmLlmsTxtConfig(\n  input: boolean | FarmLlmsTxtUserConfig | undefined,\n): ResolvedFarmLlmsTxtConfig {\n  if (!input) return { enabled: false, include: [], exclude: [], full: false };\n  if (input === true) return { enabled: true, include: [], exclude: [], full: true };\n  if (typeof input !== \"object\") {\n    throw new TypeError(\"agent.llmsTxt must be true, false, or an options object.\");\n  }\n  // Also accepts its own output, so already-resolved config passes through unchanged.\n  if (input.enabled === false) return { enabled: false, include: [], exclude: [], full: false };\n\n  for (const key of [\"title\", \"summary\", \"details\"] as const) {\n    if (input[key] !== undefined && typeof input[key] !== \"string\") {\n      throw new TypeError(`agent.llmsTxt.${key} must be a string.`);\n    }\n  }\n  if (input.full !== undefined && typeof input.full !== \"boolean\") {\n    throw new TypeError(\"agent.llmsTxt.full must be a boolean.\");\n  }\n  if (\n    input.revalidate !== undefined &&\n    (typeof input.revalidate !== \"number\" ||\n      !Number.isFinite(input.revalidate) ||\n      input.revalidate < 0)\n  ) {\n    throw new TypeError(\"agent.llmsTxt.revalidate must be a number of seconds.\");\n  }\n\n  return {\n    enabled: true,\n    ...(input.title ? { title: input.title } : {}),\n    ...(input.summary ? { summary: input.summary } : {}),\n    ...(input.details ? { details: input.details } : {}),\n    include: resolveRoutePatterns(input.include, \"include\"),\n    exclude: resolveRoutePatterns(input.exclude, \"exclude\"),\n    full: input.full !== false,\n    ...(input.revalidate !== undefined ? { revalidate: input.revalidate } : {}),\n  };\n}\n\nfunction resolveRoutePatterns(value: unknown, key: \"include\" | \"exclude\"): string[] {\n  if (value === undefined) return [];\n  if (!Array.isArray(value)) {\n    throw new TypeError(`agent.llmsTxt.${key} must be an array of route patterns.`);\n  }\n  return value.map((pattern, index) => {\n    if (typeof pattern !== \"string\" || !pattern.startsWith(\"/\")) {\n      throw new TypeError(\n        `agent.llmsTxt.${key}[${index}] must be a route pattern starting with \"/\", such as \"/docs/[...slug]\".`,\n      );\n    }\n    return pattern;\n  });\n}\n\nexport function collectFarmLlmsTxtPages(\n  sources: Iterable<FarmLlmsTxtPageSource>,\n  options: {\n    origin: string;\n    basePath?: string;\n    markdown?: FarmMarkdownResolvedConfig;\n    include?: string[];\n    exclude?: string[];\n  },\n): FarmLlmsTxtPage[] {\n  const include = options.include ?? [];\n  const exclude = options.exclude ?? [];\n  const pages = new Map<string, FarmLlmsTxtPage>();\n\n  for (const source of sources) {\n    const path = source.pattern;\n    // Dynamic routes have no single URL to list; an llms.ts can add their pages.\n    if (path.includes(\"[\") || pages.has(path)) continue;\n    if (\n      include.length &&\n      !include.some((pattern) => matchesFarmMarkdownRoutePattern(pattern, path))\n    ) {\n      continue;\n    }\n    if (exclude.some((pattern) => matchesFarmMarkdownRoutePattern(pattern, path))) continue;\n\n    // llmstxt.org prefers links to Markdown; use the page's mirror when it has one.\n    const target = isFarmMarkdownMirrorExposed(options.markdown, path)\n      ? getFarmMarkdownMirrorPath(path)\n      : path;\n    const description = readMetadataString(source.metadata, \"description\");\n    pages.set(path, {\n      path,\n      title: readMetadataTitle(source.metadata) ?? fallbackPageTitle(path),\n      url: `${options.origin}${applyFarmBasePath(target, options.basePath)}`,\n      ...(description ? { description } : {}),\n    });\n  }\n\n  return [...pages.values()].sort((left, right) => left.path.localeCompare(right.path));\n}\n\nexport function createFarmDefaultLlmsTxt(options: {\n  origin: string;\n  pages: FarmLlmsTxtPage[];\n  config: ResolvedFarmLlmsTxtConfig;\n  rootMetadata?: unknown;\n}): FarmLlmsTxt {\n  const { config, pages } = options;\n  const summary = config.summary ?? readMetadataString(options.rootMetadata, \"description\");\n\n  return {\n    title:\n      config.title ??\n      readMetadataTitle(options.rootMetadata) ??\n      pages.find((page) => page.path === \"/\")?.title ??\n      new URL(options.origin).host,\n    ...(summary ? { summary } : {}),\n    ...(config.details ? { details: config.details } : {}),\n    sections: pages.length\n      ? [\n          {\n            title: \"Pages\",\n            links: pages.map(({ title, url, description }) => ({\n              title,\n              url,\n              ...(description ? { description } : {}),\n            })),\n          },\n        ]\n      : [],\n  };\n}\n\nexport function serializeFarmLlmsTxt(value: unknown): string {\n  // A string is the complete file, written by hand; serve it as-is.\n  if (typeof value === \"string\") {\n    if (!value.trim()) throw new TypeError(\"llms.ts returned an empty llms.txt\");\n    return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n  }\n  if (!isRecord(value)) {\n    throw new TypeError(\"llms.ts must return llms.txt text, an llms.txt object, or a Response\");\n  }\n  const title = requireText(value.title, \"llms.ts must return a non-empty title\");\n  const summary = optionalText(value.summary, \"llms.ts summary must be a string\");\n  const details = optionalText(value.details, \"llms.ts details must be a string\");\n  if (value.sections !== undefined && !Array.isArray(value.sections)) {\n    throw new TypeError(\"llms.ts sections must be an array\");\n  }\n\n  const blocks = [`# ${toSingleLine(title)}`];\n  if (summary?.trim()) blocks.push(`> ${toSingleLine(summary)}`);\n  if (details?.trim()) blocks.push(details.trim());\n\n  for (const [sectionIndex, section] of ((value.sections as unknown[]) ?? []).entries()) {\n    if (!isRecord(section)) {\n      throw new TypeError(`llms.ts section ${sectionIndex} must be an object`);\n    }\n    const sectionTitle = requireText(\n      section.title,\n      `llms.ts section ${sectionIndex} must include a non-empty title`,\n    );\n    if (!Array.isArray(section.links)) {\n      throw new TypeError(`llms.ts section \"${sectionTitle}\" must include a links array`);\n    }\n\n    const links = section.links.map((link, linkIndex) => {\n      const where = `llms.ts section \"${sectionTitle}\" link ${linkIndex}`;\n      if (!isRecord(link)) throw new TypeError(`${where} must be an object`);\n      const linkTitle = requireText(link.title, `${where} must include a non-empty title`);\n      const url = requireText(link.url, `${where} must include a non-empty url`);\n      const description = optionalText(link.description, `${where} description must be a string`);\n      return `- [${escapeLinkText(linkTitle)}](${escapeLinkUrl(url)})${\n        description?.trim() ? `: ${toSingleLine(description)}` : \"\"\n      }`;\n    });\n    blocks.push(`## ${toSingleLine(sectionTitle)}`, links.join(\"\\n\"));\n  }\n\n  return `${blocks.filter(Boolean).join(\"\\n\\n\")}\\n`;\n}\n\n/**\n * Reads a page's Markdown the way an agent would: a fresh `.md` request with no\n * cookies or credentials, so a page behind auth answers 401 and is left out of\n * a file that CDNs may cache, instead of leaking into it.\n */\nexport function createFarmLlmsMarkdownReader(\n  fetchMarkdown: (request: Request) => Promise<Response>,\n): (url: string) => Promise<string | null> {\n  return async (url) => {\n    try {\n      const response = await fetchMarkdown(\n        new Request(url, { headers: { accept: \"text/markdown\" } }),\n      );\n      const type = response.headers.get(\"content-type\") ?? \"\";\n      if (!response.ok || !type.toLowerCase().startsWith(\"text/markdown\")) {\n        await response.body?.cancel();\n        return null;\n      }\n      return await response.text();\n    } catch {\n      return null;\n    }\n  };\n}\n\n/**\n * Renders llms-full.txt: the llms.txt header, then one block per linked page with\n * its Markdown inlined, in the layout the docs engine uses. A string passes\n * through unchanged. Only same-origin links are fetched.\n */\nexport async function renderFarmLlmsFullTxt(\n  value: unknown,\n  options: {\n    origin: string;\n    readMarkdown: (url: string) => Promise<string | null>;\n    concurrency?: number;\n  },\n): Promise<string> {\n  // Validates the value, and returns strings unchanged apart from the final newline.\n  const index = serializeFarmLlmsTxt(value);\n  if (typeof value === \"string\") return index;\n\n  const llms = value as FarmLlmsTxt;\n  const links: FarmLlmsTxtLink[] = [];\n  const seen = new Set<string>();\n  for (const section of llms.sections ?? []) {\n    for (const link of section.links) {\n      if (seen.has(link.url)) continue;\n      seen.add(link.url);\n      links.push(link);\n    }\n  }\n\n  const contents = await mapWithConcurrency(links, options.concurrency ?? 4, (link) =>\n    shouldInlineLlmsLink(link.url, options.origin) ? options.readMarkdown(link.url) : null,\n  );\n\n  const blocks = [`# ${toSingleLine(llms.title)}`];\n  if (llms.summary?.trim()) blocks.push(`> ${toSingleLine(llms.summary)}`);\n  if (llms.details?.trim()) blocks.push(llms.details.trim());\n  const pages = links.map((link, index) => {\n    const parts = [`## ${toSingleLine(link.title)}`, `URL: ${escapeLinkUrl(link.url)}`];\n    if (link.description?.trim()) parts.push(toSingleLine(link.description));\n    const content = stripFrontmatter(contents[index] ?? \"\").trim();\n    if (content) parts.push(content);\n    return parts.join(\"\\n\\n\");\n  });\n  if (pages.length) blocks.push(pages.join(\"\\n\\n---\\n\\n\"));\n  return `${blocks.join(\"\\n\\n\")}\\n`;\n}\n\n// Markdown sources keep their YAML frontmatter, whose --- lines would read as page\n// separators. The block header already carries the title and description.\nfunction stripFrontmatter(markdown: string): string {\n  const match = /^\\uFEFF?---\\r?\\n[\\s\\S]*?\\r?\\n---[ \\t]*(?:\\r?\\n|$)/.exec(markdown);\n  return match ? markdown.slice(match[0].length) : markdown;\n}\n\nfunction shouldInlineLlmsLink(url: string, origin: string): boolean {\n  let target: URL;\n  try {\n    target = new URL(url, origin);\n  } catch {\n    return false;\n  }\n  // Inlining llms.txt or llms-full.txt itself would recurse.\n  return target.origin === origin && !/\\/llms(-full)?\\.txt$/.test(target.pathname);\n}\n\nasync function mapWithConcurrency<T, R>(\n  items: T[],\n  limit: number,\n  run: (item: T) => Promise<R> | R,\n): Promise<R[]> {\n  const results: R[] = [];\n  let next = 0;\n  const worker = async () => {\n    while (next < items.length) {\n      const index = next++;\n      results[index] = await run(items[index]);\n    }\n  };\n  await Promise.all(Array.from({ length: Math.min(Math.max(limit, 1), items.length) }, worker));\n  return results;\n}\n\nfunction readMetadataTitle(metadata: unknown): string | undefined {\n  if (!isRecord(metadata)) return undefined;\n  const { title } = metadata;\n  if (typeof title === \"string\") return title.trim() || undefined;\n  if (isRecord(title)) {\n    for (const key of [\"absolute\", \"default\"] as const) {\n      const value = title[key];\n      if (typeof value === \"string\" && value.trim()) return value.trim();\n    }\n  }\n  return undefined;\n}\n\nfunction readMetadataString(metadata: unknown, key: string): string | undefined {\n  if (!isRecord(metadata)) return undefined;\n  const value = metadata[key];\n  return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction fallbackPageTitle(path: string): string {\n  if (path === \"/\") return \"Home\";\n  const segments = path.split(\"/\").filter(Boolean);\n  const segment = segments[segments.length - 1] ?? path;\n  const words = segment.replace(/[-_]+/g, \" \").trim();\n  return words ? words[0].toUpperCase() + words.slice(1) : path;\n}\n\n// Headings, quotes, and list items are single lines; newlines in a value would\n// otherwise start new Markdown blocks.\nfunction toSingleLine(value: string): string {\n  return value.replace(/\\s+/g, \" \").trim();\n}\n\nfunction escapeLinkText(value: string): string {\n  return toSingleLine(value).replace(/[\\\\[\\]]/g, \"\\\\$&\");\n}\n\n// encodeURIComponent writes UTF-8 and escapes whitespace and angle brackets, but\n// leaves \"(\" and \")\" alone, and \")\" would end the Markdown link early.\nfunction escapeLinkUrl(value: string): string {\n  return value\n    .trim()\n    .replace(/[\\s()<>]/g, (character) =>\n      character === \"(\" ? \"%28\" : character === \")\" ? \"%29\" : encodeURIComponent(character),\n    );\n}\n\nfunction requireText(value: unknown, message: string): string {\n  if (typeof value !== \"string\" || !value.trim()) throw new TypeError(message);\n  return value;\n}\n\nfunction optionalText(value: unknown, message: string): string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value !== \"string\") throw new TypeError(message);\n  return value;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n  serializeFarmLlmsTxt,\n  type FarmLlmsTxt,\n  type FarmLlmsTxtLink,\n  type FarmLlmsTxtPage,\n  type FarmLlmsTxtSection,\n} from \"./llms-txt\";\nimport { omitFarmResponseBody } from \"./response-body\";\n\nexport type ApplicationMetadataRouteKind = \"sitemap\" | \"robots\" | \"manifest\" | \"llms\" | \"llms-full\";\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  /**\n   * The object an `llms.ts` metadata route returns, rendered as llms.txt. An\n   * `llms.ts` can also return the complete file as a string, or a `Response`.\n   */\n  export type LlmsTxt = FarmLlmsTxt;\n  export type LlmsTxtSection = FarmLlmsTxtSection;\n  export type LlmsTxtLink = FarmLlmsTxtLink;\n  /** A static page of the app, usable directly as an llms.txt link. */\n  export type LlmsTxtPage = FarmLlmsTxtPage;\n\n  /** What an `llms.ts` default-export function receives. */\n  export interface LlmsTxtContext extends MetadataRouteContext {\n    /** The app's static pages, linking to their Markdown mirrors when exposed. */\n    pages: LlmsTxtPage[];\n    /** The llms.txt that `agent.llmsTxt` would serve, to extend instead of replace. */\n    defaults: LlmsTxt;\n  }\n\n  /**\n   * What an `llms-full.ts` default-export function receives. Returning an\n   * `LlmsTxt` object inlines each same-origin link's Markdown; returning a string\n   * serves it as the complete file.\n   */\n  export interface LlmsFullTxtContext extends LlmsTxtContext {\n    /** A page's Markdown mirror, read without the request's cookies; `null` if unavailable. */\n    markdown(url: string): Promise<string | null>;\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        : kind === \"llms\" || kind === \"llms-full\"\n          ? serializeFarmLlmsTxt(value)\n          : serializeManifest(value);\n  const contentType =\n    kind === \"sitemap\"\n      ? \"application/xml; charset=utf-8\"\n      : kind === \"robots\" || kind === \"llms\" || kind === \"llms-full\"\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","/**\n * robots.txt rules for AI crawlers.\n *\n * `agent.crawlers` serves a generated `/robots.txt` that allows or blocks known\n * AI search and training crawlers. It is off by default. A `public/robots.txt`\n * or `src/app/robots.ts` still owns the path, and the generated file takes\n * `/robots.txt` from the docs engine. The development renderer and the\n * generated production server both call into this module, so the two serve the\n * same file.\n */\nimport { applyFarmBasePath } from \"./base-path\";\nimport type { MetadataRoute } from \"./metadata-route\";\n\n/**\n * robots.txt user-agent tokens for AI crawlers, as each vendor documents them.\n *\n * - `search`: agents that fetch pages to cite or link them in answers, either\n *   by crawling for a search index or when a user asks about a page.\n * - `training`: crawlers, and tokens like `Google-Extended`, that control\n *   whether content is used to train models.\n *\n * User-triggered agents (`ChatGPT-User`, `Claude-User`, `Perplexity-User`) act\n * on a person's request, and some vendors say robots.txt may not apply to them.\n */\nexport const FARM_AI_CRAWLERS = {\n  search: [\n    \"OAI-SearchBot\",\n    \"ChatGPT-User\",\n    \"Claude-SearchBot\",\n    \"Claude-User\",\n    \"PerplexityBot\",\n    \"Perplexity-User\",\n  ],\n  training: [\n    \"GPTBot\",\n    \"ClaudeBot\",\n    \"Google-Extended\",\n    \"CCBot\",\n    \"Applebot-Extended\",\n    \"Meta-ExternalAgent\",\n    \"Bytespider\",\n  ],\n} as const satisfies Record<\"search\" | \"training\", readonly string[]>;\n\nexport type FarmCrawlerPolicy = \"allow\" | \"block\";\n\nexport interface FarmAgentCrawlers {\n  /** Set to `false` to stop serving the generated robots.txt while keeping these options. */\n  enabled?: boolean;\n  /**\n   * AI search and user-triggered agents such as OAI-SearchBot, Claude-SearchBot,\n   * and PerplexityBot. Left unset, they follow the `User-agent: *` rules.\n   */\n  search?: FarmCrawlerPolicy;\n  /**\n   * AI training crawlers such as GPTBot, ClaudeBot, Google-Extended, and CCBot.\n   * Left unset, they follow the `User-agent: *` rules.\n   */\n  training?: FarmCrawlerPolicy;\n  /**\n   * More robots.txt groups, written after the generated ones. Crawlers combine\n   * groups that name the same agent. A rule for `*` replaces the default\n   * `User-agent: *` / `Allow: /` group.\n   */\n  rules?: MetadataRoute.RobotsRule[];\n  /**\n   * Absolute sitemap URLs. Defaults to the app's `sitemap.ts` route, resolved\n   * against the root layout's `metadataBase`; with neither, no `Sitemap:` line.\n   */\n  sitemap?: string | string[];\n}\n\nexport interface ResolvedFarmAgentCrawlers {\n  enabled: boolean;\n  search?: FarmCrawlerPolicy;\n  training?: FarmCrawlerPolicy;\n  rules: MetadataRoute.RobotsRule[];\n  sitemap?: string[];\n}\n\nconst LINE_BREAK = /[\\r\\n]/;\n\nexport function resolveFarmAgentCrawlers(\n  input: boolean | FarmAgentCrawlers | ResolvedFarmAgentCrawlers | undefined,\n): ResolvedFarmAgentCrawlers {\n  if (!input) return { enabled: false, rules: [] };\n  if (input === true) return { enabled: true, rules: [] };\n  if (typeof input !== \"object\" || Array.isArray(input)) {\n    throw new TypeError(\"agent.crawlers must be true, false, or an options object.\");\n  }\n  // Also accepts its own output, so already-resolved config passes through unchanged.\n  if (input.enabled === false) return { enabled: false, rules: [] };\n\n  for (const key of [\"search\", \"training\"] as const) {\n    const policy = input[key];\n    if (policy !== undefined && policy !== \"allow\" && policy !== \"block\") {\n      throw new TypeError(`agent.crawlers.${key} must be \"allow\" or \"block\".`);\n    }\n  }\n\n  return {\n    enabled: true,\n    ...(input.search ? { search: input.search } : {}),\n    ...(input.training ? { training: input.training } : {}),\n    rules: resolveRobotsRules(input.rules),\n    ...(input.sitemap !== undefined ? { sitemap: resolveSitemapUrls(input.sitemap) } : {}),\n  };\n}\n\nfunction resolveRobotsRules(value: unknown): MetadataRoute.RobotsRule[] {\n  if (value === undefined) return [];\n  if (!Array.isArray(value)) {\n    throw new TypeError(\"agent.crawlers.rules must be an array of robots.txt rules.\");\n  }\n  return value.map((rule, index) => {\n    const name = `agent.crawlers.rules[${index}]`;\n    if (!rule || typeof rule !== \"object\" || Array.isArray(rule)) {\n      throw new TypeError(`${name} must be an object.`);\n    }\n    const userAgent = readDirectiveValues(rule.userAgent, `${name}.userAgent`);\n    if (userAgent.length === 0) {\n      throw new TypeError(`${name}.userAgent must name at least one user agent.`);\n    }\n    const allow = readDirectiveValues(rule.allow, `${name}.allow`);\n    const disallow = readDirectiveValues(rule.disallow, `${name}.disallow`);\n    if (\n      rule.crawlDelay !== undefined &&\n      (typeof rule.crawlDelay !== \"number\" ||\n        !Number.isFinite(rule.crawlDelay) ||\n        rule.crawlDelay < 0)\n    ) {\n      throw new TypeError(`${name}.crawlDelay must be a number of seconds.`);\n    }\n    return {\n      userAgent,\n      ...(allow.length ? { allow } : {}),\n      ...(disallow.length ? { disallow } : {}),\n      ...(rule.crawlDelay !== undefined ? { crawlDelay: rule.crawlDelay } : {}),\n    };\n  });\n}\n\n/** A string or string array of robots.txt values; a line break would start a new directive. */\nfunction readDirectiveValues(value: unknown, name: string): string[] {\n  if (value === undefined) return [];\n  const values = Array.isArray(value) ? value : [value];\n  for (const item of values) {\n    if (typeof item !== \"string\" || !item || LINE_BREAK.test(item)) {\n      throw new TypeError(`${name} must be a non-empty string or an array of them.`);\n    }\n  }\n  return values;\n}\n\nfunction resolveSitemapUrls(value: unknown): string[] {\n  const values = Array.isArray(value) ? value : [value];\n  for (const item of values) {\n    if (typeof item !== \"string\" || !toAbsoluteHttpUrl(item) || LINE_BREAK.test(item)) {\n      throw new TypeError(\"agent.crawlers.sitemap must be an absolute URL or an array of them.\");\n    }\n  }\n  return values;\n}\n\nfunction toAbsoluteHttpUrl(value: unknown): URL | null {\n  if (typeof value !== \"string\" && !(value instanceof URL)) return null;\n  try {\n    const url = new URL(String(value));\n    return url.protocol === \"https:\" || url.protocol === \"http:\" ? url : null;\n  } catch {\n    return null;\n  }\n}\n\nexport interface FarmAgentRobotsOptions {\n  crawlers: ResolvedFarmAgentCrawlers;\n  /** The app's root sitemap route, such as `/sitemap.xml`, when it has one. */\n  sitemapPath?: string;\n  /** The root layout's `metadataBase`, which makes the sitemap URL absolute. */\n  metadataBase?: unknown;\n  basePath?: string;\n}\n\n/** The robots.txt `agent.crawlers` serves. */\nexport function createFarmAgentRobots(options: FarmAgentRobotsOptions): MetadataRoute.Robots {\n  const { crawlers } = options;\n  const rules: MetadataRoute.RobotsRule[] = [];\n  for (const group of [\"search\", \"training\"] as const) {\n    const policy = crawlers[group];\n    if (!policy) continue;\n    rules.push({\n      userAgent: [...FARM_AI_CRAWLERS[group]],\n      ...(policy === \"allow\" ? { allow: \"/\" } : { disallow: \"/\" }),\n    });\n  }\n  rules.push(...crawlers.rules);\n  const namesEveryAgent = crawlers.rules.some((rule) =>\n    (Array.isArray(rule.userAgent) ? rule.userAgent : [rule.userAgent]).includes(\"*\"),\n  );\n  if (!namesEveryAgent) rules.push({ userAgent: \"*\", allow: \"/\" });\n\n  const sitemap = crawlers.sitemap ?? resolveDefaultSitemap(options);\n  return { rules, ...(sitemap.length > 0 ? { sitemap } : {}) };\n}\n\nfunction resolveDefaultSitemap(options: FarmAgentRobotsOptions): string[] {\n  if (!options.sitemapPath) return [];\n  // The request's Host header is not a trustworthy origin for a file crawlers and CDNs cache.\n  const base = toAbsoluteHttpUrl(options.metadataBase);\n  if (!base) return [];\n  return [new URL(applyFarmBasePath(options.sitemapPath, options.basePath), base).href];\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  background: #080808;\n}\n\n.farm-default-error {\n  --farm-error-bg: #080808;\n  --farm-error-panel: #0d0d0d;\n  --farm-error-fg: #f3f3f3;\n  --farm-error-muted: #9a9a9a;\n  --farm-error-subtle: #6f6f6f;\n  --farm-error-line: rgba(255, 255, 255, 0.1);\n  --farm-error-line-strong: rgba(255, 255, 255, 0.2);\n  --farm-error-button-bg: #f1f1f1;\n  --farm-error-button-fg: #0a0a0a;\n  --farm-error-source-line: rgba(255, 255, 255, 0.055);\n  --farm-error-source-marker: #f3f3f3;\n  --farm-error-font-sans: \"Geist Variable\", \"Geist Sans\", Geist, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  --farm-error-font-mono: \"Geist Mono Variable\", \"Geist Mono\", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  color: var(--farm-error-fg);\n  background: var(--farm-error-bg);\n  font-family: var(--farm-error-font-sans);\n  font-synthesis: none;\n  color-scheme: dark;\n  text-rendering: optimizeLegibility;\n}\n\n.farm-default-error,\n.farm-default-error * {\n  box-sizing: border-box;\n}\n\n.farm-default-error__frame {\n  width: min(100%, 1180px);\n  height: 100vh;\n  height: 100svh;\n  display: grid;\n  grid-template-rows: auto minmax(0, 1fr) auto;\n  margin: 0 auto;\n  padding: clamp(24px, 4vw, 52px);\n}\n\n.farm-default-error__brand {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 11px;\n  font-weight: 520;\n  line-height: 1;\n  letter-spacing: 0.08em;\n}\n\n.farm-default-error__brand > span:first-child {\n  color: var(--farm-error-fg);\n}\n\n.farm-default-error__brand-divider,\n.farm-default-error__status-divider,\n.farm-default-error__footer-divider {\n  color: var(--farm-error-subtle);\n}\n\n.farm-default-error__content {\n  width: min(100%, 680px);\n  min-width: 0;\n  align-self: center;\n  margin: 0 auto;\n  padding: clamp(64px, 10vh, 112px) 0;\n}\n\n/* The full page fits the screen: the frame is one screen tall and its content\n   scrolls inside it when the details run long. The dev overlay reuses these\n   classes without the frame and keeps its own scrolling. */\n.farm-default-error__frame > .farm-default-error__content {\n  max-height: 100%;\n  align-self: safe center;\n  padding-top: clamp(24px, 8vh, 112px);\n  padding-bottom: clamp(24px, 8vh, 112px);\n  overflow-y: auto;\n}\n\n.farm-default-error--development .farm-default-error__content {\n  width: min(100%, 900px);\n}\n\n.farm-default-error > .farm-default-error__content {\n  align-self: center;\n  padding-right: 24px;\n  padding-left: 24px;\n}\n\n.farm-default-error__status,\n.farm-default-error__eyebrow {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin: 0 0 24px;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  font-weight: 520;\n  line-height: 1.4;\n  letter-spacing: 0.055em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__status-mark {\n  width: 6px;\n  height: 6px;\n  flex: 0 0 auto;\n  background: var(--farm-error-fg);\n}\n\n.farm-default-error__code {\n  margin: 0 0 18px;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-mono);\n  font-size: clamp(48px, 8vw, 72px);\n  font-weight: 540;\n  line-height: 0.95;\n  letter-spacing: -0.055em;\n}\n\n.farm-default-error__summary {\n  margin: 0;\n}\n\n.farm-default-error__title {\n  max-width: 680px;\n  margin: 0;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-sans);\n  font-size: clamp(36px, 5.2vw, 56px);\n  font-weight: 560;\n  line-height: 1.04;\n  letter-spacing: -0.052em;\n  text-wrap: balance;\n}\n\n.farm-default-error__message {\n  max-width: 590px;\n  margin: 18px 0 0;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-sans);\n  font-size: clamp(16px, 2vw, 19px);\n  line-height: 1.55;\n  letter-spacing: -0.012em;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__actions {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 10px;\n  margin-top: 30px;\n}\n\n.farm-default-error__action {\n  min-height: 44px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 17px;\n  border: 1px solid var(--farm-error-line-strong);\n  border-radius: 7px;\n  color: var(--farm-error-fg);\n  background: transparent;\n  font: inherit;\n  font-family: var(--farm-error-font-mono);\n  font-size: 13px;\n  font-weight: 560;\n  line-height: 1;\n  letter-spacing: 0.015em;\n  text-decoration: none;\n  cursor: pointer;\n  transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out, transform 100ms ease-out;\n}\n\n.farm-default-error__action--primary {\n  border-color: var(--farm-error-button-bg);\n  color: var(--farm-error-button-fg);\n  background: var(--farm-error-button-bg);\n}\n\n.farm-default-error__panel {\n  margin-top: 42px;\n  border-top: 1px solid var(--farm-error-line-strong);\n}\n\n.farm-default-error__row {\n  min-height: 45px;\n  display: grid;\n  grid-template-columns: 92px minmax(0, 1fr);\n  align-items: center;\n  border-bottom: 1px solid var(--farm-error-line);\n}\n\n.farm-default-error__label,\n.farm-default-error__value,\n.farm-default-error__details-title,\n.farm-default-error__source-path,\n.farm-default-error__meta,\n.farm-default-error__footer-action {\n  font-family: var(--farm-error-font-mono);\n}\n\n.farm-default-error__label {\n  color: var(--farm-error-subtle);\n  font-size: 10px;\n  font-weight: 560;\n  letter-spacing: 0.09em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__value {\n  min-width: 0;\n  padding: 11px 0;\n  color: var(--farm-error-muted);\n  font-size: 12px;\n  line-height: 1.55;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__details {\n  padding: 24px 0 0;\n  border-bottom: 1px solid var(--farm-error-line);\n}\n\n.farm-default-error__details-header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 16px;\n  margin-bottom: 12px;\n}\n\n.farm-default-error__details-title {\n  margin: 0;\n  color: var(--farm-error-muted);\n  font-size: 10px;\n  font-weight: 560;\n  line-height: 1;\n  letter-spacing: 0.09em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__copy {\n  min-height: 32px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 10px;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 6px;\n  color: var(--farm-error-muted);\n  background: transparent;\n  font: inherit;\n  font-size: 11px;\n  cursor: pointer;\n  transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out;\n}\n\n.farm-default-error__source {\n  overflow: hidden;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 7px;\n  background: var(--farm-error-panel);\n}\n\n.farm-default-error__source-path {\n  margin: 0;\n  padding: 10px 13px;\n  border-bottom: 1px solid var(--farm-error-line);\n  color: var(--farm-error-muted);\n  font-size: 11px;\n  line-height: 1.45;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__source-code {\n  margin: 0;\n  padding: 8px 0;\n  overflow-x: auto;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  line-height: 1.75;\n  tab-size: 2;\n}\n\n.farm-default-error__source-code > code {\n  display: block;\n  white-space: normal;\n}\n\n.farm-default-error__source-line {\n  min-width: max-content;\n  display: grid;\n  grid-template-columns: 68px minmax(0, 1fr);\n  padding: 0 14px 0 0;\n  border-left: 1px solid transparent;\n}\n\n.farm-default-error__source-line--active {\n  border-left-color: var(--farm-error-source-marker);\n  background: var(--farm-error-source-line);\n}\n\n.farm-default-error__source-gutter {\n  padding-right: 14px;\n  color: var(--farm-error-subtle);\n  text-align: right;\n  user-select: none;\n}\n\n.farm-default-error__source-line--active .farm-default-error__source-gutter {\n  color: var(--farm-error-source-marker);\n}\n\n.farm-default-error__source-text {\n  white-space: pre;\n}\n\n.farm-default-error__details-empty {\n  margin: 0;\n  padding: 14px;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 7px;\n  color: var(--farm-error-muted);\n  background: var(--farm-error-panel);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  line-height: 1.5;\n}\n\n.farm-default-error__meta {\n  margin: 12px 0 20px;\n  color: var(--farm-error-subtle);\n  font-size: 10px;\n  line-height: 1.5;\n  letter-spacing: 0.035em;\n}\n\n.farm-default-error__footer {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: center;\n  gap: 12px;\n  padding-top: 24px;\n}\n\n.farm-default-error__footer-action {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  padding: 0;\n  border: 0;\n  color: var(--farm-error-muted);\n  background: transparent;\n  font-size: 10px;\n  font-weight: 540;\n  line-height: 1.4;\n  letter-spacing: 0.065em;\n  text-decoration: none;\n  cursor: pointer;\n  transition: color 150ms ease-out;\n}\n\n.farm-default-error__docs-icon {\n  width: 14px;\n  height: 14px;\n  flex: 0 0 auto;\n  stroke: currentColor;\n  stroke-width: 1.25;\n  stroke-linecap: round;\n  stroke-linejoin: round;\n}\n\n.farm-default-error__sr-only {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  padding: 0;\n  margin: -1px;\n  overflow: hidden;\n  clip: rect(0, 0, 0, 0);\n  white-space: nowrap;\n  border: 0;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  .farm-default-error__action:hover {\n    border-color: var(--farm-error-fg);\n    background: var(--farm-error-source-line);\n  }\n\n  .farm-default-error__action--primary:hover {\n    border-color: var(--farm-error-muted);\n    background: var(--farm-error-muted);\n  }\n\n  .farm-default-error__copy:hover {\n    border-color: var(--farm-error-line-strong);\n    color: var(--farm-error-fg);\n    background: var(--farm-error-source-line);\n  }\n\n  .farm-default-error__footer-action:hover {\n    color: var(--farm-error-fg);\n  }\n}\n\n.farm-default-error__copy:active,\n.farm-default-error__action:active {\n  transform: translateY(1px);\n}\n\n.farm-default-error__copy:focus-visible,\n.farm-default-error__action:focus-visible,\n.farm-default-error__footer-action:focus-visible {\n  outline: 2px solid var(--farm-error-fg);\n  outline-offset: 3px;\n}\n\n@media (max-width: 620px) {\n  .farm-default-error__frame {\n    padding: 22px 18px 26px;\n  }\n\n  .farm-default-error__content {\n    padding: 56px 0 68px;\n  }\n\n  .farm-default-error__frame > .farm-default-error__content {\n    padding-top: 32px;\n    padding-bottom: 36px;\n  }\n\n  .farm-default-error > .farm-default-error__content {\n    padding: 48px 18px;\n  }\n\n  .farm-default-error__title {\n    font-size: clamp(34px, 11vw, 44px);\n  }\n\n  .farm-default-error__message {\n    margin-top: 15px;\n  }\n\n  .farm-default-error__actions {\n    display: grid;\n    grid-template-columns: 1fr;\n  }\n\n  .farm-default-error__action {\n    width: 100%;\n  }\n\n  .farm-default-error__row {\n    grid-template-columns: 1fr;\n    gap: 2px;\n    padding: 11px 0;\n  }\n\n  .farm-default-error__value {\n    padding: 0;\n  }\n\n  .farm-default-error__details-header {\n    align-items: flex-start;\n    flex-direction: column;\n  }\n\n  .farm-default-error__copy {\n    width: 100%;\n  }\n\n  .farm-default-error__source-line {\n    grid-template-columns: 54px minmax(0, 1fr);\n  }\n}\n\n@media (prefers-color-scheme: light) {\n  .farm-default-error {\n    --farm-error-bg: #f7f7f5;\n    --farm-error-panel: #ffffff;\n    --farm-error-fg: #141414;\n    --farm-error-muted: #666666;\n    --farm-error-subtle: #8a8a8a;\n    --farm-error-line: rgba(0, 0, 0, 0.1);\n    --farm-error-line-strong: rgba(0, 0, 0, 0.19);\n    --farm-error-button-bg: #141414;\n    --farm-error-button-fg: #ffffff;\n    --farm-error-source-line: rgba(0, 0, 0, 0.045);\n    --farm-error-source-marker: #141414;\n    color-scheme: light;\n  }\n}\n\n.dark .farm-default-error,\n[data-theme=\"dark\"] .farm-default-error,\n[data-color-scheme=\"dark\"] .farm-default-error {\n  --farm-error-bg: #080808;\n  --farm-error-panel: #0d0d0d;\n  --farm-error-fg: #f3f3f3;\n  --farm-error-muted: #9a9a9a;\n  --farm-error-subtle: #6f6f6f;\n  --farm-error-line: rgba(255, 255, 255, 0.1);\n  --farm-error-line-strong: rgba(255, 255, 255, 0.2);\n  --farm-error-button-bg: #f1f1f1;\n  --farm-error-button-fg: #0a0a0a;\n  --farm-error-source-line: rgba(255, 255, 255, 0.055);\n  --farm-error-source-marker: #f3f3f3;\n  color-scheme: dark;\n}\n\n.light .farm-default-error,\n[data-theme=\"light\"] .farm-default-error,\n[data-color-scheme=\"light\"] .farm-default-error {\n  --farm-error-bg: #f7f7f5;\n  --farm-error-panel: #ffffff;\n  --farm-error-fg: #141414;\n  --farm-error-muted: #666666;\n  --farm-error-subtle: #8a8a8a;\n  --farm-error-line: rgba(0, 0, 0, 0.1);\n  --farm-error-line-strong: rgba(0, 0, 0, 0.19);\n  --farm-error-button-bg: #141414;\n  --farm-error-button-fg: #ffffff;\n  --farm-error-source-line: rgba(0, 0, 0, 0.045);\n  --farm-error-source-marker: #141414;\n  color-scheme: light;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .farm-default-error__copy,\n  .farm-default-error__action,\n  .farm-default-error__footer-action {\n    transition: none;\n  }\n\n  .farm-default-error__copy:active,\n  .farm-default-error__action:active {\n    transform: none;\n  }\n}\n`;\n","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: \"This request could not be completed\",\n  401: \"Authentication is required\",\n  403: \"You do not have access to this page\",\n  404: \"This 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: \"Something went wrong\",\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 details, then 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: \"The application ran into an unexpected problem. Try again in a moment.\",\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}\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]\");var back=root.querySelector(\"[data-farm-error-back]\");if(retry)retry.addEventListener(\"click\",function(){window.location.reload()});if(back)back.addEventListener(\"click\",function(){if(window.history.length>1){window.history.back()}else{window.location.assign(\"/\")}})})();</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\nconst ERROR_DOCS_ICON = `<svg class=\"farm-default-error__docs-icon\" viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M2.75 2.75h3.5A1.75 1.75 0 0 1 8 4.5v8.75a1.75 1.75 0 0 0-1.75-1.75h-3.5v-8.75Z\"/><path d=\"M13.25 2.75h-3.5A1.75 1.75 0 0 0 8 4.5v8.75a1.75 1.75 0 0 1 1.75-1.75h3.5v-8.75Z\"/></svg>`;\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 isServerError = statusCode >= 500;\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\">Technical details</h2></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  const primaryAction = isServerError\n    ? `<button class=\"farm-default-error__action farm-default-error__action--primary\" type=\"button\" data-farm-error-retry>TRY AGAIN</button>`\n    : `<button class=\"farm-default-error__action farm-default-error__action--primary\" type=\"button\" data-farm-error-back>GO BACK</button>`;\n  const debugAction = development\n    ? `<span class=\"farm-default-error__footer-divider\" aria-hidden=\"true\">/</span><button class=\"farm-default-error__footer-action\" 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>`\n    : \"\";\n\n  return `<style>${DEFAULT_ERROR_STYLES}</style><main class=\"farm-default-error${development ? \" farm-default-error--development\" : \"\"}\" data-farm-default-error role=\"alert\" aria-labelledby=\"farm-default-error-title\" aria-describedby=\"farm-default-error-description\"><div class=\"farm-default-error__frame\"><div class=\"farm-default-error__brand\" aria-hidden=\"true\"><span>FARM.JS</span><span class=\"farm-default-error__brand-divider\">/</span><span>ERROR</span></div><div class=\"farm-default-error__content\"><p class=\"farm-default-error__status\"><span class=\"farm-default-error__status-mark\" aria-hidden=\"true\"></span><span>${statusCode}</span><span class=\"farm-default-error__status-divider\" aria-hidden=\"true\">/</span><span>${escapeHtml(statusText)}</span></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><div class=\"farm-default-error__actions\">${primaryAction}<a class=\"farm-default-error__action\" href=\"/\">RETURN HOME</a></div><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><footer class=\"farm-default-error__footer\"><a class=\"farm-default-error__footer-action\" href=\"https://farmjs.dev/docs\" target=\"_blank\" rel=\"noopener noreferrer\">${ERROR_DOCS_ICON}<span>VIEW DOCUMENTATION</span></a>${debugAction}</footer></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.4\",\n  \"description\": \"Core Farm.js framework for modern integrated apps\",\n  \"keywords\": [\n    \"@farm.js/core\",\n    \"framework\",\n    \"react\",\n    \"rsc\",\n    \"server-components\",\n    \"ssr\",\n    \"vite\"\n  ],\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/farming-labs/farm.js\",\n    \"directory\": \"packages/farm\"\n  },\n  \"files\": [\n    \"dist\",\n    \"types\"\n  ],\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.mjs\",\n  \"types\": \"./dist/index.d.ts\",\n  \"typesVersions\": {\n    \"*\": {\n      \"middleware\": [\n        \"./types/middleware.d.ts\",\n        \"./dist/middleware.d.ts\"\n      ],\n      \"version\": [\n        \"./dist/version.d.ts\"\n      ],\n      \"router\": [\n        \"./dist/router.d.ts\"\n      ],\n      \"routes\": [\n        \"./dist/routes.d.ts\"\n      ],\n      \"storage\": [\n        \"./dist/storage.d.ts\"\n      ],\n      \"integrations\": [\n        \"./dist/integrations.d.ts\"\n      ],\n      \"schema\": [\n        \"./dist/schema.d.ts\"\n      ],\n      \"cache\": [\n        \"./dist/cache.d.ts\"\n      ],\n      \"deferred\": [\n        \"./dist/deferred.d.ts\"\n      ],\n      \"after\": [\n        \"./dist/after.d.ts\"\n      ],\n      \"navigation\": [\n        \"./dist/navigation.d.ts\"\n      ],\n      \"headers\": [\n        \"./dist/headers.d.ts\"\n      ],\n      \"theme\": [\n        \"./dist/theme/index.d.ts\"\n      ],\n      \"theme/client\": [\n        \"./dist/theme/client.d.ts\"\n      ],\n      \"theme/runtime\": [\n        \"./dist/theme/runtime.d.ts\"\n      ],\n      \"theme/server\": [\n        \"./dist/theme/server.d.ts\"\n      ],\n      \"docs\": [\n        \"./dist/docs.d.ts\"\n      ],\n      \"markdown\": [\n        \"./dist/markdown.d.ts\"\n      ],\n      \"app-markdown\": [\n        \"./dist/app-markdown.d.ts\"\n      ],\n      \"internal/app-markdown-runtime\": [\n        \"./dist/internal/app-markdown-runtime.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      \"json-ld\": [\n        \"./dist/json-ld.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      \"og\": [\n        \"./dist/og.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/docs-precompiled-runtime\": [\n        \"./dist/internal/docs-precompiled-runtime.d.ts\"\n      ],\n      \"internal/client-runtime\": [\n        \"./dist/internal/client-runtime.d.ts\"\n      ],\n      \"internal/client-error-overlay\": [\n        \"./dist/internal/client-error-overlay.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      \"internal/request-cookies\": [\n        \"./dist/internal/request-cookies.d.ts\"\n      ],\n      \"config\": [\n        \"./dist/config.d.ts\"\n      ],\n      \"renderer\": [\n        \"./dist/renderer.d.ts\"\n      ],\n      \"renderer-client\": [\n        \"./dist/renderer-client.d.ts\"\n      ],\n      \"api\": [\n        \"./types/api.d.ts\",\n        \"./dist/api.d.ts\"\n      ],\n      \"api/client\": [\n        \"./dist/api/client.d.ts\"\n      ],\n      \"api/route-manager\": [\n        \"./dist/api/route-manager.d.ts\"\n      ],\n      \"api/runtime\": [\n        \"./dist/api/runtime.d.ts\"\n      ],\n      \"request\": [\n        \"./dist/request.d.ts\"\n      ],\n      \"client\": [\n        \"./types/client.d.ts\",\n        \"./dist/client.d.ts\"\n      ],\n      \"client/lifecycle\": [\n        \"./dist/client/lifecycle.d.ts\"\n      ],\n      \"server\": [\n        \"./dist/server.d.ts\"\n      ],\n      \"vite\": [\n        \"./dist/vite.d.ts\"\n      ],\n      \"plugin\": [\n        \"./dist/plugin.d.ts\"\n      ],\n      \"query\": [\n        \"./dist/query/index.d.ts\"\n      ],\n      \"*\": [\n        \"./dist/*.d.ts\"\n      ]\n    }\n  },\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.mjs\",\n      \"require\": \"./dist/index.cjs\",\n      \"default\": \"./dist/index.mjs\"\n    },\n    \"./version\": {\n      \"types\": \"./dist/version.d.ts\",\n      \"import\": \"./dist/version.mjs\",\n      \"require\": \"./dist/version.cjs\"\n    },\n    \"./config\": {\n      \"types\": \"./dist/config.d.ts\",\n      \"import\": \"./dist/config.mjs\",\n      \"require\": \"./dist/config.cjs\"\n    },\n    \"./renderer\": {\n      \"types\": \"./dist/renderer.d.ts\",\n      \"import\": \"./dist/renderer.mjs\",\n      \"require\": \"./dist/renderer.cjs\"\n    },\n    \"./renderer-client\": {\n      \"types\": \"./dist/renderer-client.d.ts\",\n      \"import\": \"./dist/renderer-client.mjs\",\n      \"require\": \"./dist/renderer-client.cjs\"\n    },\n    \"./renderer/react/server\": {\n      \"types\": \"./dist/renderer/react/server.d.ts\",\n      \"import\": \"./dist/renderer/react/server.mjs\",\n      \"require\": \"./dist/renderer/react/server.cjs\"\n    },\n    \"./renderer/react/client\": {\n      \"types\": \"./dist/renderer/react/client.d.ts\",\n      \"import\": \"./dist/renderer/react/client.mjs\",\n      \"require\": \"./dist/renderer/react/client.cjs\"\n    },\n    \"./renderer/react/vite\": {\n      \"types\": \"./dist/renderer/react/vite.d.ts\",\n      \"import\": \"./dist/renderer/react/vite.mjs\",\n      \"require\": \"./dist/renderer/react/vite.cjs\"\n    },\n    \"./server\": {\n      \"types\": \"./dist/server.d.ts\",\n      \"import\": \"./dist/server.mjs\",\n      \"require\": \"./dist/server.cjs\"\n    },\n    \"./client\": {\n      \"types\": \"./types/client.d.ts\",\n      \"import\": \"./dist/client.mjs\",\n      \"require\": \"./dist/client.cjs\"\n    },\n    \"./client/lifecycle\": {\n      \"types\": \"./dist/client/lifecycle.d.ts\",\n      \"import\": \"./dist/client/lifecycle.mjs\",\n      \"require\": \"./dist/client/lifecycle.cjs\"\n    },\n    \"./storage\": {\n      \"types\": \"./dist/storage.d.ts\",\n      \"import\": \"./dist/storage.mjs\",\n      \"require\": \"./dist/storage.cjs\"\n    },\n    \"./integrations\": {\n      \"types\": \"./dist/integrations.d.ts\",\n      \"import\": \"./dist/integrations.mjs\",\n      \"require\": \"./dist/integrations.cjs\"\n    },\n    \"./schema\": {\n      \"types\": \"./dist/schema.d.ts\",\n      \"import\": \"./dist/schema.mjs\",\n      \"require\": \"./dist/schema.cjs\"\n    },\n    \"./cache\": {\n      \"types\": \"./dist/cache.d.ts\",\n      \"import\": \"./dist/cache.mjs\",\n      \"require\": \"./dist/cache.cjs\"\n    },\n    \"./deferred\": {\n      \"types\": \"./dist/deferred.d.ts\",\n      \"import\": \"./dist/deferred.mjs\",\n      \"require\": \"./dist/deferred.cjs\"\n    },\n    \"./after\": {\n      \"types\": \"./dist/after.d.ts\",\n      \"import\": \"./dist/after.mjs\",\n      \"require\": \"./dist/after.cjs\"\n    },\n    \"./navigation\": {\n      \"types\": \"./dist/navigation.d.ts\",\n      \"import\": \"./dist/navigation.mjs\",\n      \"require\": \"./dist/navigation.cjs\"\n    },\n    \"./headers\": {\n      \"types\": \"./dist/headers.d.ts\",\n      \"import\": \"./dist/headers.mjs\",\n      \"require\": \"./dist/headers.cjs\"\n    },\n    \"./theme\": {\n      \"types\": \"./dist/theme/index.d.ts\",\n      \"import\": \"./dist/theme/index.mjs\",\n      \"require\": \"./dist/theme/index.cjs\"\n    },\n    \"./theme/client\": {\n      \"types\": \"./dist/theme/client.d.ts\",\n      \"import\": \"./dist/theme/client.mjs\",\n      \"require\": \"./dist/theme/client.cjs\"\n    },\n    \"./theme/runtime\": {\n      \"types\": \"./dist/theme/runtime.d.ts\",\n      \"import\": \"./dist/theme/runtime.mjs\",\n      \"require\": \"./dist/theme/runtime.cjs\"\n    },\n    \"./theme/server\": {\n      \"types\": \"./dist/theme/server.d.ts\",\n      \"import\": \"./dist/theme/server.mjs\",\n      \"require\": \"./dist/theme/server.cjs\"\n    },\n    \"./docs\": {\n      \"types\": \"./dist/docs.d.ts\",\n      \"import\": \"./dist/docs.mjs\",\n      \"require\": \"./dist/docs.cjs\"\n    },\n    \"./markdown\": {\n      \"types\": \"./dist/markdown.d.ts\",\n      \"import\": \"./dist/markdown.mjs\",\n      \"require\": \"./dist/markdown.cjs\"\n    },\n    \"./app-markdown\": {\n      \"types\": \"./dist/app-markdown.d.ts\",\n      \"import\": \"./dist/app-markdown.mjs\",\n      \"require\": \"./dist/app-markdown.cjs\"\n    },\n    \"./observability\": {\n      \"types\": \"./dist/observability.d.ts\",\n      \"import\": \"./dist/observability.mjs\",\n      \"require\": \"./dist/observability.cjs\"\n    },\n    \"./instrumentation\": {\n      \"types\": \"./dist/instrumentation.d.ts\",\n      \"import\": \"./dist/instrumentation.mjs\",\n      \"require\": \"./dist/instrumentation.cjs\"\n    },\n    \"./workflows\": {\n      \"types\": \"./dist/workflows.d.ts\",\n      \"import\": \"./dist/workflows.mjs\",\n      \"require\": \"./dist/workflows.cjs\"\n    },\n    \"./cron\": {\n      \"types\": \"./dist/cron.d.ts\",\n      \"import\": \"./dist/cron.mjs\",\n      \"require\": \"./dist/cron.cjs\"\n    },\n    \"./server-fn\": {\n      \"types\": \"./dist/server-fn.d.ts\",\n      \"import\": \"./dist/server-fn.mjs\",\n      \"require\": \"./dist/server-fn.cjs\"\n    },\n    \"./server-fn/client\": {\n      \"types\": \"./dist/server-fn-client.d.ts\",\n      \"import\": \"./dist/server-fn-client.mjs\",\n      \"require\": \"./dist/server-fn-client.cjs\"\n    },\n    \"./server-query\": {\n      \"types\": \"./dist/server-query.d.ts\",\n      \"import\": \"./dist/server-query.mjs\",\n      \"require\": \"./dist/server-query.cjs\"\n    },\n    \"./server-query/client\": {\n      \"types\": \"./dist/server-query-client.d.ts\",\n      \"import\": \"./dist/server-query-client.mjs\",\n      \"require\": \"./dist/server-query-client.cjs\"\n    },\n    \"./server-action-security\": {\n      \"types\": \"./dist/server-action-security.d.ts\",\n      \"import\": \"./dist/server-action-security.mjs\",\n      \"require\": \"./dist/server-action-security.cjs\"\n    },\n    \"./deployment\": {\n      \"types\": \"./dist/deployment.d.ts\",\n      \"import\": \"./dist/deployment.mjs\",\n      \"require\": \"./dist/deployment.cjs\"\n    },\n    \"./env\": {\n      \"types\": \"./dist/env.d.ts\",\n      \"import\": \"./dist/env.mjs\",\n      \"require\": \"./dist/env.cjs\"\n    },\n    \"./env-types\": {\n      \"types\": \"./dist/env-types.d.ts\",\n      \"import\": \"./dist/env-types.mjs\",\n      \"require\": \"./dist/env-types.cjs\"\n    },\n    \"./environment\": {\n      \"types\": \"./dist/environment.d.ts\",\n      \"import\": \"./dist/environment.mjs\",\n      \"require\": \"./dist/environment.cjs\"\n    },\n    \"./environment/vite\": {\n      \"types\": \"./dist/environment/vite.d.ts\",\n      \"import\": \"./dist/environment/vite.mjs\",\n      \"require\": \"./dist/environment/vite.cjs\"\n    },\n    \"./font\": {\n      \"types\": \"./dist/font.d.ts\",\n      \"import\": \"./dist/font.mjs\",\n      \"require\": \"./dist/font.cjs\"\n    },\n    \"./vite\": {\n      \"types\": \"./dist/vite.d.ts\",\n      \"import\": \"./dist/vite.mjs\",\n      \"require\": \"./dist/vite.cjs\"\n    },\n    \"./plugin\": {\n      \"types\": \"./dist/plugin.d.ts\",\n      \"import\": \"./dist/plugin.mjs\",\n      \"require\": \"./dist/plugin.cjs\"\n    },\n    \"./plugin/server\": {\n      \"types\": \"./dist/server-plugins.d.ts\",\n      \"import\": \"./dist/server-plugins.mjs\",\n      \"require\": \"./dist/server-plugins.cjs\"\n    },\n    \"./plugin/client\": {\n      \"types\": \"./dist/client-plugins.d.ts\",\n      \"import\": \"./dist/client-plugins.mjs\",\n      \"require\": \"./dist/client-plugins.cjs\"\n    },\n    \"./query\": {\n      \"types\": \"./dist/query/index.d.ts\",\n      \"import\": \"./dist/query/index.mjs\",\n      \"require\": \"./dist/query/index.cjs\"\n    },\n    \"./query/parsers\": {\n      \"types\": \"./dist/query/parsers.d.ts\",\n      \"import\": \"./dist/query/parsers.mjs\",\n      \"require\": \"./dist/query/parsers.cjs\"\n    },\n    \"./query/client\": {\n      \"types\": \"./dist/query/client.d.ts\",\n      \"import\": \"./dist/query/client.mjs\",\n      \"require\": \"./dist/query/client.cjs\"\n    },\n    \"./query/server\": {\n      \"types\": \"./dist/query/server.d.ts\",\n      \"import\": \"./dist/query/server.mjs\",\n      \"require\": \"./dist/query/server.cjs\"\n    },\n    \"./middleware\": {\n      \"types\": \"./dist/middleware.d.ts\",\n      \"import\": \"./dist/middleware.mjs\",\n      \"require\": \"./dist/middleware.cjs\"\n    },\n    \"./api\": {\n      \"types\": \"./dist/api.d.ts\",\n      \"import\": \"./dist/api.mjs\",\n      \"require\": \"./dist/api.cjs\"\n    },\n    \"./api/client\": {\n      \"types\": \"./dist/api/client.d.ts\",\n      \"import\": \"./dist/api/client.mjs\",\n      \"require\": \"./dist/api/client.cjs\"\n    },\n    \"./api/route-manager\": {\n      \"types\": \"./dist/api/route-manager.d.ts\",\n      \"import\": \"./dist/api/route-manager.mjs\",\n      \"require\": \"./dist/api/route-manager.cjs\"\n    },\n    \"./api/runtime\": {\n      \"types\": \"./dist/api/runtime.d.ts\",\n      \"import\": \"./dist/api/runtime.mjs\",\n      \"require\": \"./dist/api/runtime.cjs\"\n    },\n    \"./request\": {\n      \"types\": \"./dist/request.d.ts\",\n      \"import\": \"./dist/request.mjs\",\n      \"require\": \"./dist/request.cjs\"\n    },\n    \"./router\": {\n      \"types\": \"./dist/router.d.ts\",\n      \"import\": \"./dist/router.mjs\",\n      \"require\": \"./dist/router.cjs\"\n    },\n    \"./routes\": {\n      \"types\": \"./dist/routes.d.ts\",\n      \"import\": \"./dist/routes.mjs\",\n      \"require\": \"./dist/routes.cjs\"\n    },\n    \"./testing\": {\n      \"types\": \"./dist/testing.d.ts\",\n      \"import\": \"./dist/testing.mjs\",\n      \"require\": \"./dist/testing.cjs\"\n    },\n    \"./agent-runtime\": {\n      \"types\": \"./dist/agent-runtime.d.ts\",\n      \"import\": \"./dist/agent-runtime.mjs\",\n      \"require\": \"./dist/agent-runtime.cjs\"\n    },\n    \"./json-ld\": {\n      \"types\": \"./dist/json-ld.d.ts\",\n      \"import\": \"./dist/json-ld.mjs\",\n      \"require\": \"./dist/json-ld.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    \"./og\": {\n      \"types\": \"./dist/og.d.ts\",\n      \"import\": \"./dist/og.mjs\",\n      \"require\": \"./dist/og.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/app-markdown-runtime\": {\n      \"types\": \"./dist/internal/app-markdown-runtime.d.ts\",\n      \"import\": \"./dist/internal/app-markdown-runtime.mjs\",\n      \"require\": \"./dist/internal/app-markdown-runtime.cjs\"\n    },\n    \"./internal/docs-precompiled-runtime\": {\n      \"types\": \"./dist/internal/docs-precompiled-runtime.d.ts\",\n      \"import\": \"./dist/internal/docs-precompiled-runtime.mjs\",\n      \"require\": \"./dist/internal/docs-precompiled-runtime.cjs\"\n    },\n    \"./internal/compression-runtime\": {\n      \"types\": \"./dist/internal/compression-runtime.d.ts\",\n      \"import\": \"./dist/internal/compression-runtime.mjs\",\n      \"require\": \"./dist/internal/compression-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/client-error-overlay\": {\n      \"types\": \"./dist/internal/client-error-overlay.d.ts\",\n      \"import\": \"./dist/internal/client-error-overlay.mjs\",\n      \"require\": \"./dist/internal/client-error-overlay.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    \"./internal/request-cookies\": {\n      \"types\": \"./dist/internal/request-cookies.d.ts\",\n      \"import\": \"./dist/internal/request-cookies.mjs\",\n      \"require\": \"./dist/internal/request-cookies.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.118\",\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.32\",\n    \"image-size\": \"^2.0.4\",\n    \"intl-messageformat\": \"11.2.12\",\n    \"marked\": \"^12.0.2\",\n    \"nitro\": \"3.0.260903-beta\",\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.10\",\n    \"vite\": \"^5.0.10\",\n    \"zod\": \"^4.1.12\"\n  },\n  \"devDependencies\": {\n    \"@clerk/react\": \"^6.4.3\",\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.35.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 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\n/**\n * Whether a provider component comes from a module the renderer compiles\n * itself, rather than a plain function component.\n *\n * Only the renderer's own declared extensions count here. The resolved set\n * from getFarmRendererComponentExtensions() always folds in .ts/.tsx/.js/.jsx,\n * and that is exactly the distinction this needs to keep: under the Svelte\n * renderer a .svelte provider is a Svelte component while a .tsx provider is a\n * function component.\n */\nexport function isRendererCompiledComponent(\n  moduleId: string,\n  rendererComponentExtensions: readonly string[],\n): boolean {\n  const lowered = moduleId.toLowerCase();\n  return rendererComponentExtensions.some((extension) => lowered.endsWith(extension.toLowerCase()));\n}\n\n/**\n * Renderers that compile their own components cannot tell a function\n * component from one of their own at runtime, so Farm marks the ones it wires\n * up. Renderers without the hook (React) get the identity function.\n */\nconst FARM_PROVIDER_MARK_HELPER = [\n  \"const farmMarkProviderComponent =\",\n  '  typeof React.markFunctionComponent === \"function\"',\n  \"    ? React.markFunctionComponent\",\n  \"    : function (component) { return component; };\",\n].join(\"\\n\");\n\nexport function generateFarmIntegrationProviderClientCode(\n  providers: FarmIntegrationProvider[],\n  root: string,\n  rendererComponentExtensions: readonly 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      if (\n        rendererComponentExtensions.length > 0 &&\n        !isRendererCompiledComponent(provider.component.module, rendererComponentExtensions)\n      ) {\n        componentExpression = `farmMarkProviderComponent(${componentExpression})`;\n      }\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  const markHelper = registrations.some((registration) =>\n    registration.includes(\"farmMarkProviderComponent(\"),\n  )\n    ? `${FARM_PROVIDER_MARK_HELPER}\\n`\n    : \"\";\n\n  return {\n    hasProviders: renderedProviders.length > 0,\n    imports: imports.join(\"\\n\"),\n    runtime: `${markHelper}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  rendererComponentExtensions: readonly string[] = [],\n): { imports: string; entries: string; helpers: string; hasClerkProvider: boolean } {\n  const imports: string[] = [];\n  const entries: string[] = [];\n  let needsMarkHelper = false;\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    let componentExpression = `${namespace}[${JSON.stringify(provider.component.export || \"default\")}]`;\n    if (\n      rendererComponentExtensions.length > 0 &&\n      !isRendererCompiledComponent(provider.component.module, rendererComponentExtensions)\n    ) {\n      componentExpression = `farmMarkProviderComponent(${componentExpression})`;\n      needsMarkHelper = true;\n    }\n    entries.push(\n      `[${JSON.stringify(createFarmIntegrationProviderModuleKey(provider.component))}, ${componentExpression}]`,\n    );\n  });\n\n  return {\n    imports: imports.join(\"\\n\"),\n    entries: entries.join(\",\\n\"),\n    helpers: needsMarkHelper ? FARM_PROVIDER_MARK_HELPER : \"\",\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 * 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|client[_-]?secret|secret[_-]?key|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","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   * Generate a fresh nonce for every dynamic HTML response and per-page\n   * script hashes for prerendered HTML. Farm adds the matching sources to the\n   * governing script directive and stamps dynamic script elements with the\n   * response nonce.\n   */\n  nonce?: boolean;\n}\n\nexport type FarmCspConfig = string | FarmCspOptions;\n\nexport interface FarmSecurityConfig {\n  /** App-wide CSP for dynamic responses and prerendered output. */\n  csp?: FarmCspConfig | false;\n  /** @deprecated Use csp. */\n  contentSecurityPolicy?: never;\n}\n\nexport interface ResolvedFarmCspConfig {\n  value: string;\n  reportOnly: boolean;\n  nonce: 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        nonce: 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  const nonce = validateNonce(csp.nonce);\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        nonce,\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      nonce,\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  nonce?: string,\n): { key: string; value: string } | undefined {\n  if (!security.csp) return undefined;\n  if (security.csp.nonce && !nonce) return undefined;\n  return {\n    key: security.csp.reportOnly\n      ? \"Content-Security-Policy-Report-Only\"\n      : \"Content-Security-Policy\",\n    value: nonce ? applyFarmCspNonceToPolicy(security.csp.value, nonce) : security.csp.value,\n  };\n}\n\nexport function createFarmCspNonce(security: ResolvedFarmSecurityConfig): string | undefined {\n  if (!security.csp || !security.csp.nonce) return undefined;\n  const bytes = new Uint8Array(16);\n  globalThis.crypto.getRandomValues(bytes);\n  return Array.from(bytes, (value) => value.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport function applyFarmCspNonceToPolicy(policy: string, nonce: string): string {\n  validateCspNonce(nonce);\n  return applyFarmCspScriptSourcesToPolicy(policy, [`'nonce-${nonce}'`]);\n}\n\nexport function applyFarmCspHashesToPolicy(policy: string, hashes: readonly string[]): string {\n  const sources = hashes.map((hash) => {\n    if (!/^sha(?:256|384|512)-[A-Za-z0-9+/]+={0,2}$/.test(hash)) {\n      throw new TypeError(`Invalid CSP script hash: ${JSON.stringify(hash)}.`);\n    }\n    return `'${hash}'`;\n  });\n  return applyFarmCspScriptSourcesToPolicy(policy, sources);\n}\n\nfunction applyFarmCspScriptSourcesToPolicy(policy: string, sources: readonly string[]): string {\n  const uniqueSources = [...new Set(sources)];\n  if (uniqueSources.length === 0) return policy;\n  const segments = policy\n    .split(\";\")\n    .map((segment) => segment.trim())\n    .filter(Boolean);\n  const names = segments.map((segment) => segment.split(/\\s+/, 1)[0]!.toLowerCase());\n  const governingName = names.includes(\"script-src-elem\")\n    ? \"script-src-elem\"\n    : names.includes(\"script-src\")\n      ? \"script-src\"\n      : names.includes(\"default-src\")\n        ? \"default-src\"\n        : undefined;\n\n  if (!governingName) return `${policy}; script-src ${uniqueSources.join(\" \")}`;\n  return segments\n    .map((segment, index) => {\n      if (names[index] !== governingName) return segment;\n      const existing = new Set(segment.split(/\\s+/));\n      const missing = uniqueSources.filter((source) => !existing.has(source));\n      return missing.length > 0 ? `${segment} ${missing.join(\" \")}` : segment;\n    })\n    .join(\"; \");\n}\n\nexport function addFarmCspNonceToScriptTags(html: string, nonce: string): string {\n  validateCspNonce(nonce);\n  return createFarmCspNonceRewriter(nonce).write(html, true);\n}\n\nexport function removeFarmCspNoncesFromScriptTags(html: string): string {\n  return createFarmScriptTagRewriter(stripScriptNonceAttribute).write(html, true);\n}\n\nexport async function createFarmCspScriptHashes(html: string): Promise<string[]> {\n  const hashes: string[] = [];\n  const seen = new Set<string>();\n  for (const content of collectFarmInlineScriptContents(html)) {\n    const digest = await globalThis.crypto.subtle.digest(\n      \"SHA-256\",\n      new TextEncoder().encode(content),\n    );\n    let binary = \"\";\n    for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);\n    const hash = `sha256-${globalThis.btoa(binary)}`;\n    if (!seen.has(hash)) {\n      seen.add(hash);\n      hashes.push(hash);\n    }\n  }\n  return hashes;\n}\n\nexport async function applyFarmCspHashesToHtml(\n  html: string,\n  security: ResolvedFarmSecurityConfig,\n): Promise<{ html: string; header: { key: string; value: string } } | undefined> {\n  if (!security.csp || !security.csp.nonce) return undefined;\n  const staticHtml = removeFarmCspNoncesFromScriptTags(html);\n  const hashes = await createFarmCspScriptHashes(staticHtml);\n  return {\n    html: staticHtml,\n    header: {\n      key: security.csp.reportOnly\n        ? \"Content-Security-Policy-Report-Only\"\n        : \"Content-Security-Policy\",\n      value: applyFarmCspHashesToPolicy(security.csp.value, hashes),\n    },\n  };\n}\n\nexport function applyFarmCspNonceToResponse(\n  response: Response,\n  security: ResolvedFarmSecurityConfig,\n): Response {\n  if (!security.csp || !security.csp.nonce) return response;\n  if (!response.headers.get(\"content-type\")?.toLowerCase().includes(\"text/html\")) return response;\n\n  const nonce = createFarmCspNonce(security)!;\n  const securityHeader = getFarmSecurityHeader(security, nonce)!;\n  const headers = new Headers(response.headers);\n  headers.set(securityHeader.key, securityHeader.value);\n  headers.delete(\"content-length\");\n\n  if (!response.body) {\n    return new Response(null, {\n      status: response.status,\n      statusText: response.statusText,\n      headers,\n    });\n  }\n\n  const decoder = new TextDecoder();\n  const encoder = new TextEncoder();\n  const rewriter = createFarmCspNonceRewriter(nonce);\n  const body = response.body.pipeThrough(\n    new TransformStream<Uint8Array, Uint8Array>({\n      transform(chunk, controller) {\n        const output = rewriter.write(decoder.decode(chunk, { stream: true }));\n        if (output) controller.enqueue(encoder.encode(output));\n      },\n      flush(controller) {\n        const output = rewriter.write(decoder.decode(), true);\n        if (output) controller.enqueue(encoder.encode(output));\n      },\n    }),\n  );\n\n  return new Response(body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\n/**\n * Whether a resolved CSP would block the inline scripts the framework injects\n * into SSR documents (theme bootstrap, hydration bootstraps).\n *\n * Without nonce mode, those scripts carry no nonce and their content varies\n * per page, so a static hash cannot allow them either. They run only when the\n * governing directive (`script-src-elem`, then `script-src`, then\n * `default-src`) allows `'unsafe-inline'` and lists no nonce, hash, or\n * `'strict-dynamic'` source: browsers ignore `'unsafe-inline'` as soon as any\n * of those is present. A policy with no script-governing directive does not\n * restrict inline scripts, so it is not flagged. Nonce mode handles this at\n * response time and therefore never reports the static policy as blocking.\n */\nexport function farmCspBlocksFrameworkInlineScripts(security: ResolvedFarmSecurityConfig): boolean {\n  if (!security.csp) return false;\n  if (security.csp.nonce) return false;\n\n  const directives = parseCspDirectives(security.csp.value);\n  const governing =\n    directives.get(\"script-src-elem\") ??\n    directives.get(\"script-src\") ??\n    directives.get(\"default-src\");\n  if (!governing) return false;\n\n  const sources = governing.map((source) => source.toLowerCase());\n  const disablesUnsafeInline = sources.some(\n    (value) =>\n      value === \"'strict-dynamic'\" ||\n      value.startsWith(\"'nonce-\") ||\n      value.startsWith(\"'sha256-\") ||\n      value.startsWith(\"'sha384-\") ||\n      value.startsWith(\"'sha512-\"),\n  );\n  return !sources.includes(\"'unsafe-inline'\") || disablesUnsafeInline;\n}\n\nfunction parseCspDirectives(value: string): Map<string, string[]> {\n  const directives = new Map<string, string[]>();\n  for (const segment of value.split(\";\")) {\n    const parts = segment.trim().split(/\\s+/).filter(Boolean);\n    if (parts.length === 0) continue;\n    const name = parts[0]!.toLowerCase();\n    if (!directives.has(name)) directives.set(name, parts.slice(1));\n  }\n  return directives;\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 validateNonce(value: unknown): boolean {\n  if (value === undefined) return false;\n  if (typeof value !== \"boolean\") {\n    throw new TypeError(\"security.csp.nonce must be a boolean.\");\n  }\n  return value;\n}\n\nfunction validateCspNonce(value: string): void {\n  if (!/^[A-Za-z0-9+/_-]+={0,2}$/.test(value)) {\n    throw new TypeError(\"A CSP nonce must be a base64 or base64url value.\");\n  }\n}\n\nexport function createFarmCspNonceRewriter(nonce: string) {\n  validateCspNonce(nonce);\n  return createFarmScriptTagRewriter((tag) => stampScriptTag(tag, nonce));\n}\n\nfunction createFarmScriptTagRewriter(transformScriptTag: (tag: string) => string) {\n  let pending = \"\";\n  let rawTextElement: string | undefined;\n\n  return {\n    write(chunk: string, final = false): string {\n      pending += chunk;\n      let output = \"\";\n\n      while (pending) {\n        const lower = pending.toLowerCase();\n        if (rawTextElement) {\n          if (rawTextElement === \"plaintext\") {\n            output += pending;\n            pending = \"\";\n            break;\n          }\n          const closing = `</${rawTextElement}`;\n          const start = findHtmlToken(lower, closing);\n          if (start === -1) {\n            if (final) {\n              output += pending;\n              pending = \"\";\n            } else {\n              const keep = matchingSuffixLength(lower, closing);\n              output += pending.slice(0, pending.length - keep);\n              pending = pending.slice(pending.length - keep);\n            }\n            break;\n          }\n\n          output += pending.slice(0, start);\n          pending = pending.slice(start);\n          const end = findHtmlTagEnd(pending);\n          if (end === -1) {\n            if (final) {\n              output += pending;\n              pending = \"\";\n            }\n            break;\n          }\n          output += pending.slice(0, end + 1);\n          pending = pending.slice(end + 1);\n          rawTextElement = undefined;\n          continue;\n        }\n\n        const start = pending.indexOf(\"<\");\n        if (start === -1) {\n          output += pending;\n          pending = \"\";\n          break;\n        }\n        output += pending.slice(0, start);\n        pending = pending.slice(start);\n        const lowerTag = pending.toLowerCase();\n\n        if (pending.startsWith(\"<!--\")) {\n          const end = pending.indexOf(\"-->\", 4);\n          if (end === -1) {\n            if (final) {\n              output += pending;\n              pending = \"\";\n            }\n            break;\n          }\n          output += pending.slice(0, end + 3);\n          pending = pending.slice(end + 3);\n          continue;\n        }\n        if (!final && \"<!--\".startsWith(pending)) break;\n\n        const tagNameMatch = lowerTag.match(/^<\\/?([a-z][a-z0-9:-]*)\\b/);\n        if (!tagNameMatch) {\n          if (!final && /^<\\/?[a-z][a-z0-9:-]*$/i.test(pending)) break;\n          output += pending[0];\n          pending = pending.slice(1);\n          continue;\n        }\n\n        const end = findHtmlTagEnd(pending);\n        if (end === -1) {\n          if (!final) break;\n          output += pending;\n          pending = \"\";\n          break;\n        }\n\n        const tag = pending.slice(0, end + 1);\n        const tagName = tagNameMatch[1]!.toLowerCase();\n        const isClosing = lowerTag.startsWith(\"</\");\n        const isSelfClosing = /\\/\\s*>$/.test(tag);\n        output += !isClosing && tagName === \"script\" ? transformScriptTag(tag) : tag;\n        pending = pending.slice(end + 1);\n        if (!isClosing && !isSelfClosing && rawTextElements.has(tagName)) {\n          rawTextElement = tagName;\n        }\n      }\n\n      return output;\n    },\n  };\n}\n\nconst rawTextElements = new Set([\n  \"iframe\",\n  \"noembed\",\n  \"noframes\",\n  \"plaintext\",\n  \"script\",\n  \"style\",\n  \"textarea\",\n  \"title\",\n  \"xmp\",\n]);\n\nfunction stampScriptTag(tag: string, nonce: string): string {\n  const opening = tag.match(/^<script\\b/i)?.[0];\n  if (!opening) return tag;\n  const attributes = stripScriptNonceAttribute(tag).slice(opening.length, -1);\n  return `<script nonce=\"${nonce}\"${attributes}>`;\n}\n\nfunction stripScriptNonceAttribute(tag: string): string {\n  let normalized = tag;\n  let range = findScriptTagAttributeRange(normalized, \"nonce\");\n  while (range) {\n    normalized = normalized.slice(0, range.start) + normalized.slice(range.end);\n    range = findScriptTagAttributeRange(normalized, \"nonce\");\n  }\n  return normalized;\n}\n\nfunction collectFarmInlineScriptContents(html: string): string[] {\n  const contents: string[] = [];\n  let offset = 0;\n\n  while (offset < html.length) {\n    const start = html.indexOf(\"<\", offset);\n    if (start === -1) break;\n    if (html.startsWith(\"<!--\", start)) {\n      const commentEnd = html.indexOf(\"-->\", start + 4);\n      offset = commentEnd === -1 ? html.length : commentEnd + 3;\n      continue;\n    }\n\n    const remaining = html.slice(start);\n    const tagNameMatch = remaining.toLowerCase().match(/^<\\/?([a-z][a-z0-9:-]*)\\b/);\n    if (!tagNameMatch) {\n      offset = start + 1;\n      continue;\n    }\n    const tagEnd = findHtmlTagEnd(remaining);\n    if (tagEnd === -1) break;\n    const tag = remaining.slice(0, tagEnd + 1);\n    const tagName = tagNameMatch[1]!.toLowerCase();\n    const isClosing = remaining.startsWith(\"</\");\n    const isSelfClosing = /\\/\\s*>$/.test(tag);\n    offset = start + tagEnd + 1;\n    if (isClosing || isSelfClosing || !rawTextElements.has(tagName)) continue;\n\n    if (tagName === \"plaintext\") break;\n    const closingStart = findHtmlToken(html.toLowerCase().slice(offset), `</${tagName}`);\n    const contentEnd = closingStart === -1 ? html.length : offset + closingStart;\n    if (tagName === \"script\" && !findScriptTagAttributeRange(tag, \"src\")) {\n      contents.push(html.slice(offset, contentEnd));\n    }\n    if (closingStart === -1) break;\n    const closingEnd = findHtmlTagEnd(html.slice(contentEnd));\n    if (closingEnd === -1) break;\n    offset = contentEnd + closingEnd + 1;\n  }\n\n  return contents;\n}\n\nfunction findScriptTagAttributeRange(\n  tag: string,\n  expectedName: string,\n): { start: number; end: number } | undefined {\n  const opening = tag.match(/^<script\\b/i)?.[0];\n  if (!opening) return undefined;\n  let offset = opening.length;\n\n  while (offset < tag.length - 1) {\n    const whitespaceStart = offset;\n    while (/\\s/.test(tag[offset] || \"\")) offset++;\n    if (tag[offset] === \"/\" || tag[offset] === \">\" || offset >= tag.length - 1) break;\n\n    const nameStart = offset;\n    while (offset < tag.length && !/[\\s=/>]/.test(tag[offset]!)) offset++;\n    const name = tag.slice(nameStart, offset).toLowerCase();\n    while (/\\s/.test(tag[offset] || \"\")) offset++;\n    if (tag[offset] === \"=\") {\n      offset++;\n      while (/\\s/.test(tag[offset] || \"\")) offset++;\n      const quote = tag[offset] === '\"' || tag[offset] === \"'\" ? tag[offset++] : undefined;\n      if (quote) {\n        while (offset < tag.length && tag[offset] !== quote) offset++;\n        if (tag[offset] === quote) offset++;\n      } else {\n        while (offset < tag.length && !/[\\s>]/.test(tag[offset]!)) offset++;\n      }\n    }\n    if (name === expectedName) return { start: whitespaceStart, end: offset };\n  }\n\n  return undefined;\n}\n\nfunction findHtmlToken(input: string, token: string): number {\n  let offset = 0;\n  while (offset < input.length) {\n    const index = input.indexOf(token, offset);\n    if (index === -1) return -1;\n    const boundary = input[index + token.length];\n    if (boundary === undefined || /[\\s/>]/.test(boundary)) return index;\n    offset = index + 1;\n  }\n  return -1;\n}\n\nfunction matchingSuffixLength(input: string, token: string): number {\n  const limit = Math.min(token.length - 1, input.length);\n  for (let length = limit; length > 0; length--) {\n    if (token.startsWith(input.slice(-length))) return length;\n  }\n  return 0;\n}\n\nfunction findHtmlTagEnd(tag: string): number {\n  let quote: '\"' | \"'\" | undefined;\n  for (let index = 1; index < tag.length; index++) {\n    const character = tag[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;\n    }\n  }\n  return -1;\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 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/**\n * @internal Starts a fresh island scope below a hydrating layout's client graph. The layout keeps\n * a page that does not hydrate as server HTML, so that page's client components are islands of\n * their own, not part of the layout's React tree.\n */\nexport function isolateFarmServerPageGraph(\n  ReactRuntime: typeof React,\n  element: React.ReactNode,\n): React.ReactElement {\n  const Context = getBoundaryGraphContext(ReactRuntime);\n  return ReactRuntime.createElement(Context.Provider, { value: false }, 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  dispose(): void;\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  onRecoverableError?: (error: unknown) => void;\n}\n\nfunction isEarlyHydrationUpdate(error: unknown): boolean {\n  return (\n    error instanceof Error &&\n    (error.message ===\n      \"This root received an early update, before anything was able hydrate. Switched the entire root to client rendering.\" ||\n      error.message.startsWith(\"Minified React error #424;\"))\n  );\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 releasePending = () => {\n          if (pending.get(container) === controller) pending.delete(container);\n        };\n        // An aborted pass will never hydrate this container, so stop reserving it as\n        // soon as it aborts rather than when `scheduled` settles. A slow module import\n        // keeps the scheduled work pending long after the abort, and until it settles\n        // the next pass filters this boundary out and leaves it inert. `dispose` drops\n        // its reservations on abort for the same reason.\n        controller.signal.addEventListener(\"abort\", releasePending, { once: true });\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          releasePending();\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                let disposing = false;\n                const root = options.hydrateRoot(container, graphElement, {\n                  onUncaughtError: restore,\n                  onRecoverableError(error) {\n                    // React 18/19 also report an early update when unmount cancels a root\n                    // before its first commit. Only that synchronous teardown diagnostic\n                    // is expected; live-root updates and real mismatches still report.\n                    if (disposing && isEarlyHydrationUpdate(error)) return;\n                    if (typeof globalThis.reportError === \"function\") globalThis.reportError(error);\n                    else console.error(error);\n                  },\n                });\n                roots.set(container, {\n                  root,\n                  dispose() {\n                    disposing = true;\n                    try {\n                      root.unmount();\n                    } finally {\n                      disposing = false;\n                    }\n                  },\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                // A module import that rejects after this pass was aborted must not\n                // restore server HTML over whatever owns the container now, and a\n                // failure `restore` already reported must not be reported twice.\n                if (controller.signal.aborted) return;\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.dispose();\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\n/**\n * @internal A page a hydrating layout keeps as verbatim server HTML. React owns only the\n * wrapper, so the islands inside start after React commits that HTML and stop when it is\n * replaced on navigation or the layout unmounts. The containers are captured when they start\n * because React has already swapped the HTML by the time the cleanup runs.\n */\nexport function createFarmServerPageBoundary(\n  ReactRuntime: typeof React,\n  runtime: Pick<ReturnType<typeof createFarmIsolatedHydrationRuntime>, \"hydrate\" | \"dispose\">,\n): React.ComponentType<Record<string, unknown> & { dangerouslySetInnerHTML: { __html: string } }> {\n  return function FarmServerPage(props) {\n    const ref = ReactRuntime.useRef<HTMLDivElement>(null);\n    const html = props.dangerouslySetInnerHTML.__html;\n    ReactRuntime.useLayoutEffect(() => {\n      const page = ref.current;\n      if (!page) return;\n      const islands = Array.from(\n        page.querySelectorAll(\"farm-client-boundary[data-farm-client-boundary]\"),\n      );\n      if (islands.length === 0) return;\n      const controller = new AbortController();\n      runtime.hydrate(page, controller.signal).catch((error) => {\n        console.error(\"[Farm.js] Could not hydrate the islands in this page:\", error);\n      });\n      return () => {\n        controller.abort();\n        // Unmounting another root while this commit is still running is not allowed, so the\n        // captured islands are released right after it.\n        queueMicrotask(() => {\n          for (const island of islands) runtime.dispose(island);\n        });\n      };\n    }, [html]);\n    return ReactRuntime.createElement(\"div\", { ...props, ref });\n  };\n}\n","import React from \"react\";\nimport {\n  renderToPipeableStream as reactRenderToPipeableStream,\n  renderToString as reactRenderToString,\n} from \"react-dom/server\";\nimport {\n  isolateFarmServerPageGraph,\n  wrapFarmIsolatedClientGraph,\n} 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 isolateServerPageGraph = (element: React.ReactNode) =>\n  isolateFarmServerPageGraph(React, element);\nexport const renderToString = reactRenderToString;\nexport const renderToPipeableStream = reactRenderToPipeableStream;\n\nexport default React;\n\n/**\n * React DOM's streaming runtime reveals a Suspense boundary with `$RC`/`$RS`/\n * `$RV`/`$RX` calls and labels the segments with Fizz ids such as `id=\"S:1\"`.\n * The first of those in a chunk is where the static shell ends.\n */\nexport function findStaticShellBoundary(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) return -1;\n\n  const markerIndex = Math.min(...markerIndexes);\n  const tagStart = chunk.lastIndexOf(\"<\", markerIndex);\n  return tagStart >= 0 ? tagStart : markerIndex;\n}\n","import * as fs from \"fs\";\nimport * as https from \"https\";\nimport { isIP } from \"net\";\nimport * as path from \"path\";\nimport * as tls from \"tls\";\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  removeFarmDocumentTitles,\n} from \"./full-document\";\nimport {\n  describeSuppressedAsyncHydration,\n  getClientModuleMetadata,\n} from \"../utils/client-component\";\nimport { Readable, 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  addMetadataMarkdownAlternate,\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 } from \"../i18n/routing\";\nimport {\n  renderFarmLocaleAlternateLinks,\n  type FarmLocaleAlternateLinkOptions,\n} from \"../i18n/alternates\";\nimport {\n  createLateNotFoundRecovery,\n  createLateRedirectRecovery,\n} from \"../navigation/late-navigation-recovery\";\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  collectFarmLlmsTxtPages,\n  createFarmDefaultLlmsTxt,\n  createFarmLlmsMarkdownReader,\n  renderFarmLlmsFullTxt,\n  resolveFarmLlmsTxtConfig,\n} from \"../llms-txt\";\nimport { getFarmMarkdownAlternatePath, resolveMarkdownConfig } from \"../markdown\";\nimport { createFarmAgentRobots, resolveFarmAgentCrawlers } from \"../agent-crawlers\";\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  assertFarmRendererStreamingRuntime,\n  getFarmRendererCapabilities,\n  getFarmRendererComponentExtensions,\n  getFarmRendererStreamingCapabilitiesForRuntime,\n  isReactRenderer,\n  readFarmRendererWebStream,\n  resolveFarmRendererModule,\n  type FarmServerRendererRuntime,\n  resolveFarmComponentExtensions,\n} from \"../renderer\";\nimport { isRendererCompiledComponent } from \"../integration-provider-build\";\nimport { pathToFileURL } from \"node:url\";\nimport { FARM_ISLAND_REPLAYABLE_SELECTOR } from \"../island\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport { createDefaultErrorDiagnostics } from \"./error-diagnostics\";\nimport {\n  addFarmCspNonceToScriptTags,\n  createFarmCspNonceRewriter,\n  createFarmCspNonce,\n  getFarmSecurityHeader,\n  resolveFarmSecurityConfig,\n  type ResolvedFarmSecurityConfig,\n} from \"../security\";\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  /**\n   * Origin the shell's hreflang alternates resolved against, or \"\" when the\n   * shell emits none. Kept in the key so one host never serves another host's\n   * absolute alternate URLs.\n   */\n  origin?: 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, reason?: string): void {\n  if (warnedSuppressedAsyncHydrationModules.has(modulePath)) return;\n  warnedSuppressedAsyncHydrationModules.add(modulePath);\n  logger.warn(describeSuppressedAsyncHydration(modulePath, reason));\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(\n  requestPath: string,\n  snapshot: FarmI18nClientSnapshot,\n  options: FarmLocaleAlternateLinkOptions,\n): string {\n  if (snapshot.routing === \"none\") return \"\";\n  const url = new URL(requestPath, \"http://farm.local\");\n  return renderFarmLocaleAlternateLinks(url.pathname, snapshot, options);\n}\n\n/**\n * Refresh a cached PPR shell's dynamic content in the background, once per\n * document. Inlined, so it stays hand-minified.\n *\n * Hydration awaits `__FARM_PPR_REFRESH_PROMISE__`, which settles after the first\n * attempt whether it succeeds or fails, so a failing refresh never delays\n * hydration. A failed attempt (rejected request, non-2xx response, or a document\n * with no #root) leaves the shell untouched and retries with backoff, at most\n * PPR_REFRESH_MAX_ATTEMPTS times; while offline it waits for the `online` event\n * instead of spending an attempt. Retries only apply before hydration starts\n * (the client sets `__FARM_PPR_HYDRATING__`), so they never replace DOM React\n * owns. When retries stop without success the latch is released, so a later\n * explicit refresh can run.\n */\nexport const PPR_REFRESH_MAX_ATTEMPTS = 3;\n\nexport function createPPRRefreshScript(): string {\n  return `<script>(function(){if(window.__FARM_PPR_REFRESHING__)return;window.__FARM_PPR_REFRESHING__=true;var owner=document.currentScript;function applyState(doc){doc.querySelectorAll(\"script[data-farm-refresh-state]\").forEach(function(source){var script=document.createElement(\"script\");if(owner&&owner.nonce)script.nonce=owner.nonce;script.textContent=source.textContent||\"\";document.head.appendChild(script);script.remove();});}function key(node){return node.nodeType===1?node.getAttribute(\"id\"):null}function compatible(current,next){if(current.nodeType!==next.nodeType)return false;if(current.nodeType===1&&current.tagName!==next.tagName)return false;var currentKey=key(current);var nextKey=key(next);return currentKey||nextKey?currentKey===nextKey:true}function syncAttributes(current,next){Array.from(current.attributes).forEach(function(attribute){if(!next.hasAttribute(attribute.name))current.removeAttribute(attribute.name)});Array.from(next.attributes).forEach(function(attribute){if(current.getAttribute(attribute.name)!==attribute.value)current.setAttribute(attribute.name,attribute.value)})}function syncChildren(current,next){var cursor=current.firstChild;Array.from(next.childNodes).forEach(function(nextChild){if(cursor&&compatible(cursor,nextChild)){var matched=cursor;cursor=cursor.nextSibling;syncNode(matched,nextChild);return}var candidate=cursor;while(candidate&&!compatible(candidate,nextChild))candidate=candidate.nextSibling;if(candidate){current.insertBefore(candidate,cursor);syncNode(candidate,nextChild);return}current.insertBefore(nextChild.cloneNode(true),cursor)});while(cursor){var stale=cursor;cursor=cursor.nextSibling;stale.remove()}}function syncNode(current,next){if(current.nodeType===3||current.nodeType===8){if(current.nodeValue!==next.nodeValue)current.nodeValue=next.nodeValue;return}if(current.nodeType!==1)return;var tag=current.tagName;var value=tag===\"INPUT\"&&current.type===\"file\"?null:\"value\" in current?current.value:null;var checked=\"checked\" in current?current.checked:null;var selected=tag===\"SELECT\"?Array.from(current.options).map(function(option){return option.selected}):null;var focused=document.activeElement===current;var selection=focused&&typeof current.selectionStart===\"number\"?[current.selectionStart,current.selectionEnd,current.selectionDirection]:null;syncAttributes(current,next);syncChildren(current,next);if(value!==null)current.value=value;if(checked!==null)current.checked=checked;if(selected)Array.from(current.options).forEach(function(option,index){option.selected=selected[index]===true});if(selection)try{current.setSelectionRange(selection[0],selection[1],selection[2])}catch{}}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 false;applyState(doc);syncNode(current,next);return true}var attempts=0,settle;window.__FARM_PPR_REFRESH_PROMISE__=new Promise(function(resolve){settle=resolve;});function release(){window.__FARM_PPR_REFRESHING__=false;}function retry(){settle();if(window.__FARM_PPR_HYDRATING__||attempts>=${PPR_REFRESH_MAX_ATTEMPTS})return release();if(navigator.onLine===false){window.addEventListener(\"online\",run,{once:true});return;}setTimeout(run,1000*Math.pow(2,attempts-1));}function run(){if(window.__FARM_PPR_HYDRATING__)return release();attempts++;fetch(window.location.href,{cache:\"no-store\",credentials:\"same-origin\",headers:{\"x-farm-ppr-refresh\":\"1\"}}).then(function(response){if(!response.ok)throw new Error(\"status \"+response.status);return response.text();}).then(function(html){if(window.__FARM_PPR_HYDRATING__)return release();if(!replaceRoot(html))throw new Error(\"no root\");settle();}).catch(retry);}run();})();</script>`;\n}\n\nexport function createPreHydrationClickQueueScript(): string {\n  // Inlined into every document, so this stays hand-minified rather than\n  // importing from the island runtime, which has not loaded yet at this point.\n  //\n  // Two kinds of interaction are handled. A click or a submit is HELD: the\n  // event is prevented and queued so the island can hydrate and the action can\n  // be reproduced against the same target. A pointerdown or a focusin is only\n  // OBSERVED: it starts hydration early and native behavior proceeds, so\n  // typing into a field or toggling a checkbox is never swallowed. The event\n  // set here must match FARM_ISLAND_ACTIVATION_EVENTS.\n  const selector = JSON.stringify(FARM_ISLAND_REPLAYABLE_SELECTOR);\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 inHydrated(node){return !!(node&&node.closest&&node.closest('[data-farm-island-hydrated=\"true\"]'))}function closestQueuedTarget(target){while(target&&target!==document.documentElement){if(target.matches&&target.matches(${selector}))return target;target=target.parentElement}return null}function announce(target,kind){document.dispatchEvent(new CustomEvent(\"farm:island-interaction\",{detail:{target:target,kind:kind||null}}))}function hold(event,target,kind){if(queue.some(function(item){return item.target===target}))return;queue.push({target:target,kind:kind,createdAt:Date.now()});announce(target,kind);event.preventDefault();event.stopImmediatePropagation()}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]\")||inHydrated(target))return;hold(event,target,\"click\")},true);document.addEventListener(\"submit\",function(event){if(window.__FARM_HYDRATED__)return;if(event.defaultPrevented)return;var form=event.target;if(!form||form.nodeName!==\"FORM\"||inHydrated(form))return;hold(event,form,\"submit\")},true);function observe(event){if(window.__FARM_HYDRATED__)return;var target=event.target;if(!(target&&target.closest)||inHydrated(target))return;announce(target,null)}document.addEventListener(\"pointerdown\",observe,true);document.addEventListener(\"focusin\",observe,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  return `<script data-farm-refresh-state>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\n/**\n * GETs a page from this HTTPS dev server. The connection goes to the server's\n * own socket address, while SNI and certificate verification use the hostname\n * the page was requested under, which is the name the dev certificate covers.\n */\nfunction requestOwnHttpsServer(\n  request: Request,\n  address: { host: string; port: number },\n): Promise<Response> {\n  const url = new URL(request.url);\n  const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n  return new Promise((resolve, reject) => {\n    const outgoing = https.request(\n      {\n        host: address.host,\n        port: address.port,\n        method: \"GET\",\n        path: `${url.pathname}${url.search}`,\n        headers: { ...Object.fromEntries(request.headers), host: url.host },\n        // SNI carries names only, never IP addresses.\n        ...(isIP(hostname) ? {} : { servername: hostname }),\n        checkServerIdentity: (_, certificate) => tls.checkServerIdentity(hostname, certificate),\n      },\n      (incoming) => {\n        const headers = new Headers();\n        for (const [name, value] of Object.entries(incoming.headers)) {\n          for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) {\n            headers.append(name, item);\n          }\n        }\n        const status = incoming.statusCode ?? 502;\n        const hasBody = ![204, 205, 304].includes(status);\n        if (!hasBody) incoming.resume();\n        resolve(\n          new Response(hasBody ? (Readable.toWeb(incoming) as ReadableStream) : null, {\n            status,\n            headers,\n          }),\n        );\n      },\n    );\n    outgoing.on(\"error\", reject);\n    outgoing.end();\n  });\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  private security: ResolvedFarmSecurityConfig;\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.security = resolveFarmSecurityConfig(config.security);\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    assertFarmRendererStreamingRuntime(\n      this.config.renderer.name,\n      this.config.renderer,\n      runtime,\n      \"node\",\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 streaming = getFarmRendererStreamingCapabilitiesForRuntime(this.config.renderer, \"node\");\n    const renderToPipeableStream = 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 (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    } else if (\n      input.layoutShouldHydrate &&\n      !input.pageShouldHydrate &&\n      this.rendererRuntime.isolateServerPageGraph\n    ) {\n      // As in renderPage: the layout keeps this page as server HTML, so its islands stay islands.\n      element = this.rendererRuntime.isolateServerPageGraph(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 = \"\", origin = \"\"): string {\n    const key = [\"ppr\", locale, normalizeRevalidatePath(pathname), search];\n    return createFarmCacheKey(origin ? [...key, origin] : key);\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 = \"\", origin = \"\") {\n    return this.dataCache.getEntryAsync<CachedPPRShell>(\n      this.getPPRCacheKey(pathname, search, locale, origin),\n    );\n  }\n\n  private async cachePPRShell(options: PPRShellCacheOptions, html: string): Promise<void> {\n    const key = this.getPPRCacheKey(\n      options.pathname,\n      options.search,\n      options.locale,\n      options.origin,\n    );\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    if (this.security.csp && this.security.csp.nonce) {\n      return \"csp-nonce\";\n    }\n\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          // No request drives a background regeneration, so the cached document's\n          // hreflang alternates resolve against metadataBase only.\n          const fullDocument = this.createFullHTML(\n            html,\n            pageMetadata.shouldHydrate === true,\n            page.urlPath,\n            metadataHead,\n            { metadata: mergedMetadata },\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, undefined, { req }),\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 cspNonce = createFarmCspNonce(this.security);\n    if (cspNonce) {\n      (req as any).__FARM_CSP_NONCE__ = cspNonce;\n      const header = getFarmSecurityHeader(this.security, cspNonce)!;\n      res.setHeader(header.key, header.value);\n    }\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 generatedLlmsKind = this.getGeneratedLlmsKind(pathname);\n      if (generatedLlmsKind) {\n        await this.renderGeneratedLlmsTxt(req, res, generatedLlmsKind);\n        completeRender(res.statusCode || 200, pathname);\n        return;\n      }\n\n      if (pathname === \"/robots.txt\" && this.getAgentCrawlers().enabled) {\n        await this.renderGeneratedRobotsTxt(req, res);\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 (\n        !(req as any).__FARM_CSP_NONCE__ &&\n        shouldServePrerenderedPage(process.env.NODE_ENV, req.method)\n      ) {\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 pprI18nSnapshot = canCachePPRShell ? getFarmI18nClientSnapshot() : undefined;\n      const pprShellOptions: PPRShellCacheOptions | undefined = canCachePPRShell\n        ? {\n            pathname,\n            search: url.search,\n            locale: pprI18nSnapshot?.locale ?? \"\",\n            origin: pprI18nSnapshot && pprI18nSnapshot.routing !== \"none\" ? url.origin : \"\",\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(\n          pathname,\n          url.search,\n          pprShellOptions.locale,\n          pprShellOptions.origin,\n        );\n        const cachedPPRShell = await this.getCachedPPRShell(\n          pathname,\n          url.search,\n          pprShellOptions.locale,\n          pprShellOptions.origin,\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(\n          route.modulePath,\n          routeManifestEntry?.suppressedAsyncHydrationReason,\n        );\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              suppressedAsyncHydration?: true;\n              suppressedAsyncHydrationReason?: string;\n            }\n          | undefined;\n        if (manifestEntry?.suppressedAsyncHydration) {\n          warnSuppressedAsyncHydrationOnce(\n            layout.modulePath,\n            manifestEntry.suppressedAsyncHydrationReason,\n          );\n        }\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            } else if (\n              shouldHydrateLayout &&\n              !(isClientComponent || shouldHydrate) &&\n              this.rendererRuntime.isolateServerPageGraph\n            ) {\n              // The hydrating layout keeps this page as server HTML, so its client components\n              // render as their own islands instead of joining the layout's React tree.\n              pageElement = this.rendererRuntime.isolateServerPageGraph(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        // Production gates on the same capability (nitro/universal-build.ts).\n        // A renderer identity check here left every non-React renderer that\n        // can host function components throwing in development while its\n        // build worked, and named the provider kind rather than the\n        // integration in the message.\n        const rendererCapabilities = getFarmRendererCapabilities(this.config.renderer);\n        if (!rendererCapabilities.functionComponents) {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` requires a renderer that can host ` +\n              `function components; \\`${this.config.renderer?.name ?? \"the configured renderer\"}\\` cannot.`,\n          );\n        }\n        if (provider.type === \"clerk\" && !isReactRenderer(this.config.renderer)) {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` uses Clerk's React components, which ` +\n              \"require the React renderer.\",\n          );\n        }\n        let ProviderComponent;\n        let providerSourceModule: string | undefined;\n        if (isFarmIntegrationProviderComponentReference(provider.component)) {\n          providerSourceModule = provider.component.module;\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        // A renderer that compiles its own components cannot tell a plain\n        // function component from one of its own, so the build marks the ones\n        // Farm wires up (integration-provider-build.ts). Development resolves\n        // the module itself and must mark it the same way, or the compat root\n        // tries to instantiate a function as a compiled component.\n        if (\n          provider.type !== \"clerk\" &&\n          typeof this.rendererRuntime.markFunctionComponent === \"function\" &&\n          !isRendererCompiledComponent(\n            providerSourceModule ?? \"\",\n            resolveFarmComponentExtensions(this.config.renderer?.componentExtensions),\n          )\n        ) {\n          ProviderComponent = this.rendererRuntime.markFunctionComponent(ProviderComponent);\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    // Advertise the Markdown mirror in the head as well as the Link header,\n    // using the public path the .md request will be resolved against.\n    const snapshot = getFarmI18nClientSnapshot();\n    const publicPathname = applyFarmBasePath(\n      snapshot ? localizeFarmHref(options.pathname, snapshot.locale, snapshot) : options.pathname,\n      this.config.basePath,\n    );\n    metadata = addMetadataMarkdownAlternate(\n      metadata,\n      getFarmMarkdownAlternatePath(resolveMarkdownConfig(this.config.md as any), publicPathname),\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 llmsContext: Partial<Awaited<ReturnType<ServerRenderer[\"createLlmsTxtContext\"]>>> =\n        match.metadata.kind === \"llms\" || match.metadata.kind === \"llms-full\"\n          ? await this.createLlmsTxtContext(request, {\n              full: match.metadata.kind === \"llms-full\",\n              req,\n            })\n          : {};\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              ...llmsContext,\n            })\n          : routeModule.default;\n      // llms-full objects need each page's Markdown, which only this side can fetch.\n      const body =\n        match.metadata.kind === \"llms-full\" && !(value instanceof Response)\n          ? await renderFarmLlmsFullTxt(value, {\n              origin: url.origin,\n              readMarkdown: llmsContext.markdown!,\n            })\n          : value;\n      const response = createFarmMetadataRouteResponse(match.metadata.kind, body, 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  /** `/llms.txt` and `/llms-full.txt` from `agent.llmsTxt` when no file route owns them. */\n  private getGeneratedLlmsKind(pathname: string): \"llms\" | \"llms-full\" | null {\n    const config = resolveFarmLlmsTxtConfig(this.config.agent?.llmsTxt);\n    if (!config.enabled) return null;\n    if (pathname === \"/llms.txt\") return \"llms\";\n    return pathname === \"/llms-full.txt\" && config.full ? \"llms-full\" : null;\n  }\n\n  private async renderGeneratedLlmsTxt(\n    req: FarmRequest,\n    res: FarmResponse,\n    kind: \"llms\" | \"llms-full\",\n  ): Promise<void> {\n    try {\n      const request = createWebRequestFromFarmRequest(req, {\n        trustProxy: this.config.server?.trustProxy,\n      });\n      const config = resolveFarmLlmsTxtConfig(this.config.agent?.llmsTxt);\n      const context = await this.createLlmsTxtContext(request, { full: kind === \"llms-full\", req });\n      const body =\n        kind === \"llms-full\"\n          ? await renderFarmLlmsFullTxt(context.defaults, {\n              origin: new URL(request.url).origin,\n              readMarkdown: context.markdown!,\n            })\n          : context.defaults;\n      await sendWebResponse(\n        res as any,\n        createFarmMetadataRouteResponse(\n          kind,\n          body,\n          { revalidate: config.revalidate },\n          { method: req.method },\n        ),\n      );\n    } catch (error) {\n      logger.error(`Generated ${kind}.txt failed: ${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 getAgentCrawlers() {\n    return resolveFarmAgentCrawlers(this.config.agent?.crawlers);\n  }\n\n  /** `/robots.txt` from `agent.crawlers` when no robots.ts owns it. */\n  private async renderGeneratedRobotsTxt(req: FarmRequest, res: FarmResponse): Promise<void> {\n    try {\n      const sitemapPath =\n        this.routeManager.matchMetadataRoute(\"/sitemap.xml\")?.metadata.kind === \"sitemap\"\n          ? \"/sitemap.xml\"\n          : undefined;\n      const rootLayout = this.routeManager.getLayouts().get(\"/\");\n      const rootMetadata =\n        sitemapPath && rootLayout\n          ? (await this.routeManager.loadLayoutModule(rootLayout.modulePath)).metadata\n          : undefined;\n      const robots = createFarmAgentRobots({\n        crawlers: this.getAgentCrawlers(),\n        sitemapPath,\n        metadataBase: (rootMetadata as { metadataBase?: unknown } | undefined)?.metadataBase,\n        basePath: this.config.basePath,\n      });\n      await sendWebResponse(\n        res as any,\n        createFarmMetadataRouteResponse(\"robots\", robots, {}, { method: req.method }),\n      );\n    } catch (error) {\n      logger.error(`Generated robots.txt failed: ${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  /** Same inputs the production server gives llms.txt: static pages and root metadata. */\n  private async createLlmsTxtContext(\n    request: Request,\n    options: { full?: boolean; req?: FarmRequest } = {},\n  ): Promise<{\n    pages: ReturnType<typeof collectFarmLlmsTxtPages>;\n    defaults: ReturnType<typeof createFarmDefaultLlmsTxt>;\n    markdown?: (url: string) => Promise<string | null>;\n  }> {\n    const config = resolveFarmLlmsTxtConfig(this.config.agent?.llmsTxt);\n    const origin = new URL(request.url).origin;\n    const staticRoutes = [...this.routeManager.getRoutes()].filter(\n      ([pattern]) => !pattern.includes(\"[\"),\n    );\n    const sources = await Promise.all(\n      staticRoutes.map(async ([pattern, route]) => {\n        try {\n          const metadata = (await this.routeManager.loadRouteModule(route.modulePath)).metadata;\n          return { pattern, metadata: metadata as unknown };\n        } catch (error) {\n          // The page itself will surface this error; list it with its fallback title.\n          logger.warn(`Could not read metadata for ${pattern} in llms.txt: ${error}`);\n          return { pattern };\n        }\n      }),\n    );\n\n    const rootLayout = this.routeManager.getLayouts().get(\"/\");\n    const rootMetadata = rootLayout\n      ? (await this.routeManager.loadLayoutModule(rootLayout.modulePath)).metadata\n      : undefined;\n    const pages = collectFarmLlmsTxtPages(sources, {\n      origin,\n      basePath: this.config.basePath,\n      markdown: resolveMarkdownConfig(this.config.md as any),\n      include: config.include,\n      exclude: config.exclude,\n    });\n    return {\n      pages,\n      defaults: createFarmDefaultLlmsTxt({ origin, pages, config, rootMetadata }),\n      ...(options.full ? { markdown: this.createDevMarkdownReader(options.req) } : {}),\n    };\n  }\n\n  /**\n   * Reads page mirrors back through this dev server, the way its .md handler\n   * renders pages, so Markdown sources and agent overrides are included. Requests\n   * go to the server's own socket address: the page URLs carry the Host header,\n   * which a client controls, and fetching them would let anyone who can reach a\n   * network-exposed dev server point it at other hosts. Over HTTPS the certificate\n   * is still checked against the requested hostname. HEAD reads nothing, since its\n   * body is discarded.\n   */\n  private createDevMarkdownReader(req?: FarmRequest): (url: string) => Promise<string | null> {\n    const socket = req?.socket as\n      | { localAddress?: string; localPort?: number; encrypted?: boolean }\n      | undefined;\n    if (req?.method?.toUpperCase() === \"HEAD\" || !socket?.localAddress || !socket.localPort) {\n      return async () => null;\n    }\n    if (socket.encrypted) {\n      const address = { host: socket.localAddress, port: socket.localPort };\n      return createFarmLlmsMarkdownReader((page) => requestOwnHttpsServer(page, address));\n    }\n    const host = socket.localAddress.includes(\":\")\n      ? `[${socket.localAddress}]`\n      : socket.localAddress;\n    const localOrigin = `http://${host}:${socket.localPort}`;\n    const read = createFarmLlmsMarkdownReader((page) => fetch(page));\n    return (url) => {\n      const target = new URL(url);\n      return read(`${localOrigin}${target.pathname}${target.search}`);\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(\n        this.secureDocumentHTML(\n          req,\n          this.createFullHTML(html, false, options.pathname, undefined, { req }),\n        ),\n      );\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 data-farm-refresh-state>\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)};\nwindow.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = ${JSON.stringify(\n        (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true,\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())};\nwindow.__FARM_I18N__ = ${getFarmI18nClientSnapshot() ? serializeInlineValue(getFarmI18nClientSnapshot()) : \"null\"};\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 rendererHasTitle = /<title[\\s>]/i.test(rendererHead);\n      const i18nSnapshot = getFarmI18nClientSnapshot();\n      const alternateTags = i18nSnapshot\n        ? renderI18nAlternateLinks(\n            (req as any).__FARM_ROUTE__ || req.url || \"/\",\n            i18nSnapshot,\n            this.getI18nAlternateOptions(req, (req as any).__FARM_METADATA__),\n          )\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        const shouldReplaceLayoutTitle = hasExplicitTitle || rendererHasTitle;\n        const documentHtml = shouldReplaceLayoutTitle\n          ? removeFarmDocumentTitles(fullDocument)\n          : fullDocument;\n        const effectiveRendererHead = hasExplicitTitle\n          ? removeFarmDocumentTitles(rendererHead)\n          : rendererHead;\n        html = composeFarmFullDocument(documentHtml, {\n          htmlAttributes: `${\n            i18nSnapshot\n              ? ` lang=\"${escapeHtmlAttribute(i18nSnapshot.locale)}\" dir=\"${escapeHtmlAttribute(i18nSnapshot.direction)}\"`\n              : \"\"\n          }${themeDocument.attributes}`,\n          replaceHtmlAttributes: [\n            ...(i18nSnapshot ? [\"lang\", \"dir\"] : []),\n            ...(themeDocument.attributes ? [\"data-theme\"] : []),\n          ],\n          headAssets: [\n            themeDocument.head,\n            `<meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">`,\n            hasExplicitTitle ? documentTitleTag : \"\",\n            metaTags,\n            alternateTags,\n            effectiveRendererHead,\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      const securedHtml = this.secureDocumentHTML(req, html);\n      if ((req.method || \"GET\").toUpperCase() !== \"HEAD\") res.write(securedHtml);\n      res.end();\n      // The buffered document is rendered per request and never split at a\n      // static boundary, so a shell capture must not store it: caching it\n      // would serve this visitor's data to everyone until revalidation.\n      if (!options.captureStaticShell) await options.onComplete?.(securedHtml);\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      // Splitting a static shell out of the stream requires knowing where the\n      // first dynamic boundary is, and only the renderer that emitted the\n      // markers can say. Without that, every chunk would look static and a\n      // per-request response would be cached as a shared shell, so skip the\n      // shell entirely rather than guess.\n      const findStaticShellBoundary = this.rendererRuntime.findStaticShellBoundary;\n      const staticShellParts: string[] | undefined =\n        options.captureStaticShell && findStaticShellBoundary ? [] : undefined;\n      let staticShellClosed = false;\n      let suspenseHoleEmitted = false;\n      let didError = false;\n      // redirect() and notFound() thrown while React renders the shell's first\n      // pass (a synchronous page under a loading boundary) still decide the\n      // response, because nothing has been sent. One thrown after the shell\n      // went out can only be recovered in the document.\n      let shellFlushed = false;\n      let pendingNavigationError: unknown = null;\n      let lateNavigationError: unknown = null;\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 data-farm-refresh-state>\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)};\nwindow.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = ${JSON.stringify(\n        (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true,\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())};\nwindow.__FARM_I18N__ = ${getFarmI18nClientSnapshot() ? serializeInlineValue(getFarmI18nClientSnapshot()) : \"null\"};\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(\n            (req as any).__FARM_ROUTE__ || req.url || \"/\",\n            i18nSnapshot,\n            this.getI18nAlternateOptions(req, (req as any).__FARM_METADATA__),\n          )\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      // A hydrating layout tree already starts with its layout boundary, and the client hydrates\n      // #root with exactly that tree (as production renders it), so it must not gain a wrapper.\n      const streamRoot =\n        (req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ === true\n          ? element\n          : this.rendererRuntime.createElement(\"div\", { style: { display: \"contents\" } }, element);\n      const devStyleLinks = this.collectDevStyleLinks();\n      const cspNonce = this.getCspNonce(req);\n      const secureDocumentHTML = (html: string) =>\n        cspNonce ? addFarmCspNonceToScriptTags(html, cspNonce) : html;\n      const createLateNavigationRecovery = (navigationError: unknown) =>\n        this.createLateNavigationRecoveryHTML(req, navigationError);\n      const { pipe, abort } = renderToPipeableStream(streamRoot, {\n        nonce: cspNonce,\n        onShellReady() {\n          if (pendingNavigationError) {\n            abort?.(pendingNavigationError);\n            if (clearMiddlewareData) {\n              clearMiddlewareData();\n            }\n            reject(pendingNavigationError);\n            return;\n          }\n          shellFlushed = true;\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          const securedShell = secureDocumentHTML(shell);\n          htmlParts.push(securedShell);\n          staticShellParts?.push(securedShell);\n\n          let firstChunk = true;\n          let checkedFullDocument = false;\n          const cspNonceRewriter = cspNonce ? createFarmCspNonceRewriter(cspNonce) : undefined;\n          const cspStreamDecoder = cspNonceRewriter ? new TextDecoder() : undefined;\n          const recordRenderedChunk = (chunkText: string) => {\n            if (!chunkText) return;\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 && findStaticShellBoundary && !staticShellClosed) {\n              const dynamicIndex = findStaticShellBoundary(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          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)\n                ? cspStreamDecoder\n                  ? cspStreamDecoder.decode(chunk, { stream: true })\n                  : chunk.toString()\n                : String(chunk);\n              const securedChunkText = cspNonceRewriter\n                ? cspNonceRewriter.write(chunkText)\n                : chunkText;\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              recordRenderedChunk(securedChunkText);\n\n              const onWrite = () => {\n                if (typeof (res as any).flush === \"function\") (res as any).flush();\n                callback();\n              };\n              if (cspNonceRewriter) res.write(securedChunkText, onWrite);\n              else res.write(chunk, encoding, onWrite);\n            },\n            final: (callback) => {\n              if (lateNavigationError) {\n                const navigationError = lateNavigationError;\n                lateNavigationError = null;\n                createLateNavigationRecovery(navigationError).then(\n                  (recovery: string) => {\n                    const secured = secureDocumentHTML(recovery);\n                    htmlParts.push(secured);\n                    res.write(secured);\n                    finishStream(callback);\n                  },\n                  (error: unknown) => {\n                    logger.error(`Could not recover from a late navigation error: ${error}`);\n                    finishStream(callback);\n                  },\n                );\n                return;\n              }\n              finishStream(callback);\n            },\n          });\n          const finishStream = (callback: (error?: Error | null) => void) => {\n            if (cspNonceRewriter) {\n              const tail = cspNonceRewriter.write(cspStreamDecoder!.decode(), true);\n              recordRenderedChunk(tail);\n              if (tail) res.write(tail);\n            }\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 = secureDocumentHTML(\n              createDocumentFooter({\n                suspenseRevealFallback,\n                deferredHydrationScript: createDeferredHydrationScript(deferredProps.records),\n              }),\n            );\n            htmlParts.push(footer);\n            res.write(footer);\n            res.end();\n            callback();\n            if (clearMiddlewareData) {\n              clearMiddlewareData();\n            }\n            // A shell capture without a renderer-owned boundary detector has\n            // nothing safe to store: falling back to the full streamed\n            // response would cache one visitor's rendered data as the shared\n            // shell. Cache only what was actually split out as static.\n            if (\n              !didError &&\n              options.onComplete &&\n              (!options.captureStaticShell || staticShellParts)\n            ) {\n              if (staticShellParts) {\n                staticShellParts.push(\n                  createDocumentFooter({\n                    suspenseRevealFallback,\n                    refreshPPR: staticShellClosed,\n                  }),\n                );\n              }\n\n              const cachedHtml = staticShellParts ? staticShellParts.join(\"\") : 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          // 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(securedShell);\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 (isFarmRedirectError(error) || isFarmNotFoundError(error)) {\n            if (!shellFlushed) pendingNavigationError ??= error;\n            else lateNavigationError ??= error;\n            return;\n          }\n          if (!isWebResponse(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  /**\n   * Answer a redirect() or notFound() thrown by middleware, before anything was\n   * sent. Returns false for any other error.\n   */\n  async respondToNavigationError(\n    req: FarmRequest,\n    res: FarmResponse,\n    error: unknown,\n  ): Promise<boolean> {\n    if (isFarmRedirectError(error)) {\n      const redirect = getFarmRedirectError(error)!;\n      res.statusCode = redirect.status;\n      // Middleware runs before locale routing; like ctx.redirect(), the target\n      // goes out as written (the production runner does the same).\n      res.setHeader(\"Location\", redirect.url);\n      res.end();\n      return true;\n    }\n    if (isFarmNotFoundError(error)) {\n      await this.render404(req, res);\n      return true;\n    }\n    return false;\n  }\n\n  private localizeRedirectUrl(url: string): string {\n    const snapshot = getFarmI18nClientSnapshot();\n    return snapshot && url.startsWith(\"/\") && !url.startsWith(\"//\")\n      ? localizeFarmHref(url, snapshot.locale, snapshot)\n      : url;\n  }\n\n  /** The app's not-found component, or null when it relies on the built-in page. */\n  private async loadNotFoundComponent(): Promise<unknown> {\n    const notFoundPath = resolveFarmNotFoundComponentPath(\n      this.config,\n      getFarmAppDirectories(this.config),\n    );\n    if (!notFoundPath) return null;\n    const notFoundModule = await this.routeManager.loadRouteModule(notFoundPath);\n    return notFoundModule.default ?? null;\n  }\n\n  private defaultNotFoundContent(): string {\n    const homeHref = escapeHtmlAttribute(applyFarmBasePath(\"/\", this.config.basePath));\n    return `<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\n  /**\n   * A redirect() or notFound() thrown after the shell was sent can no longer\n   * change the status. Like Next.js, finish the document so it recovers:\n   * redirect in the browser, or swap the page for the not-found UI and mark\n   * the document noindex.\n   */\n  private async createLateNavigationRecoveryHTML(\n    req: FarmRequest,\n    error: unknown,\n  ): Promise<string> {\n    if (isFarmRedirectError(error)) {\n      return createLateRedirectRecovery(this.localizeRedirectUrl(getFarmRedirectError(error)!.url));\n    }\n    const pathname = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    }).pathname;\n    // The layouts are already in the streamed shell, so only the page area is\n    // replaced. A not-found page that needs context from its layout cannot\n    // render on its own; recover with the built-in page instead.\n    let content = this.defaultNotFoundContent();\n    const NotFoundComponent = await this.loadNotFoundComponent();\n    if (NotFoundComponent) {\n      try {\n        content = await this.rendererRuntime.renderToString(\n          await this.wrapWithIntegrationProviders(\n            this.rendererRuntime.createElement(NotFoundComponent, { pathname }),\n          ),\n        );\n      } catch (error) {\n        logger.warn(`not-found page could not render outside its layout, using Farm's: ${error}`);\n      }\n    }\n    return createLateNotFoundRecovery(content);\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        const NotFoundComponent = await this.loadNotFoundComponent();\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, undefined, { req });\n          res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n          res.write(this.secureDocumentHTML(req, 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 defaultContent = this.defaultNotFoundContent();\n\n    const html = this.createFullHTML(defaultContent, false, pathname, undefined, { req });\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    res.write(this.secureDocumentHTML(req, 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      `<link rel=\"icon\" href=\"data:,\">\\n  <title>${statusCode} - ${statusText}</title>`,\n      { req },\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(this.secureDocumentHTML(req, html));\n    res.end();\n  }\n\n  /**\n   * Where i18n hreflang alternates resolve to absolute URLs: the route's\n   * metadataBase, otherwise the request origin under the same trustProxy rule\n   * as every other request URL.\n   */\n  private getI18nAlternateOptions(\n    req: FarmRequest | undefined,\n    metadata: unknown,\n  ): FarmLocaleAlternateLinkOptions {\n    return {\n      metadataBase: (metadata as { metadataBase?: unknown } | undefined)?.metadataBase,\n      origin: req\n        ? resolveFarmRequestURL(req, { trustProxy: this.config.server?.trustProxy }).origin\n        : undefined,\n    };\n  }\n\n  private createFullHTML(\n    content: string,\n    isClientComponent = false,\n    requestPath = \"/\",\n    metadataHead?: string,\n    alternates: { req?: FarmRequest; metadata?: unknown } = {},\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\n      ? renderI18nAlternateLinks(\n          requestPath,\n          i18nSnapshot,\n          this.getI18nAlternateOptions(alternates.req, alternates.metadata),\n        )\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    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(\n        metadataHead ? removeFarmDocumentTitles(fullDocument) : fullDocument,\n        {\n          htmlAttributes: `${\n            i18nSnapshot\n              ? ` lang=\"${escapeHtmlAttribute(i18nSnapshot.locale)}\" dir=\"${escapeHtmlAttribute(i18nSnapshot.direction)}\"`\n              : \"\"\n          }${themeDocument.attributes}`,\n          replaceHtmlAttributes: [\n            ...(i18nSnapshot ? [\"lang\", \"dir\"] : []),\n            ...(themeDocument.attributes ? [\"data-theme\"] : []),\n          ],\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\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 getCspNonce(req: FarmRequest): string | undefined {\n    const value = (req as any).__FARM_CSP_NONCE__;\n    return typeof value === \"string\" ? value : undefined;\n  }\n\n  private secureDocumentHTML(req: FarmRequest, html: string): string {\n    const nonce = this.getCspNonce(req);\n    return nonce ? addFarmCspNonceToScriptTags(html, nonce) : 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      min-height: 34px;\n      padding: 0 11px;\n      border: 1px solid rgb(255 255 255 / 0.16);\n      border-radius: 6px;\n      background: rgb(8 8 8 / 0.94);\n      box-shadow: 0 8px 24px rgb(0 0 0 / 0.2);\n      color: rgb(250 250 250);\n      font: 500 10px/1 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n      letter-spacing: 0;\n      opacity: 0;\n      pointer-events: none;\n      transform: translateY(4px);\n      transition: opacity 120ms ease-out, transform 120ms ease-out;\n      -webkit-backdrop-filter: blur(12px);\n      backdrop-filter: blur(12px);\n    }\n    #__farm_build_activity__[data-visible=\"true\"] {\n      opacity: 1;\n      transform: translateY(0);\n    }\n    .farm-build-activity__brand {\n      display: inline-flex;\n      align-items: center;\n      gap: 7px;\n      flex: none;\n    }\n    .farm-build-activity__mark {\n      width: 17px;\n      height: 16px;\n      flex: none;\n    }\n    .farm-build-activity__wordmark {\n      color: rgb(255 255 255);\n      font-size: 11px;\n      font-weight: 400;\n      line-height: 1;\n    }\n    .farm-build-activity__wordmark-suffix { color: rgb(255 255 255 / 0.52); }\n    .farm-build-activity__divider {\n      width: 1px;\n      height: 14px;\n      margin: 0 9px;\n      flex: none;\n      background: rgb(255 255 255 / 0.14);\n    }\n    .farm-build-activity__loader {\n      display: grid;\n      width: 15px;\n      grid-template-columns: repeat(3, 4px);\n      gap: 1.5px;\n      flex: none;\n    }\n    .farm-build-activity__cell {\n      width: 4px;\n      height: 4px;\n      border-radius: 1px;\n      background: currentColor;\n      opacity: 0.15;\n    }\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell {\n      animation: farm-build-activity-pixel-on 650ms ease-in-out infinite;\n    }\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(1),\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(5),\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(7) {\n      animation-delay: 90ms;\n    }\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(2),\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(6),\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(8) {\n      animation-delay: 180ms;\n    }\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(3),\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(9) {\n      animation-delay: 270ms;\n    }\n    #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell:nth-child(4) {\n      animation-delay: 0ms;\n    }\n    #__farm_build_activity__[data-state=\"ready\"] .farm-build-activity__cell,\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__cell {\n      opacity: 0.08;\n    }\n    #__farm_build_activity__[data-state=\"ready\"] .farm-build-activity__cell:nth-child(3),\n    #__farm_build_activity__[data-state=\"ready\"] .farm-build-activity__cell:nth-child(5),\n    #__farm_build_activity__[data-state=\"ready\"] .farm-build-activity__cell:nth-child(6),\n    #__farm_build_activity__[data-state=\"ready\"] .farm-build-activity__cell:nth-child(7),\n    #__farm_build_activity__[data-state=\"ready\"] .farm-build-activity__cell:nth-child(8),\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__cell:nth-child(1),\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__cell:nth-child(3),\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__cell:nth-child(5),\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__cell:nth-child(7),\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__cell:nth-child(9) {\n      opacity: 1;\n    }\n    .farm-build-activity__label {\n      margin-left: 7px;\n      color: rgb(255 255 255 / 0.62);\n      font-size: 9px;\n      letter-spacing: 0.06em;\n      text-transform: uppercase;\n      white-space: nowrap;\n    }\n    .farm-build-activity__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    #__farm_build_activity__[data-state=\"error\"] {\n      border-color: rgb(248 113 113 / 0.55);\n    }\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__loader,\n    #__farm_build_activity__[data-state=\"error\"] .farm-build-activity__label {\n      color: rgb(254 202 202);\n    }\n    @keyframes farm-build-activity-pixel-on {\n      0%, 32%, 100% { opacity: 0.15; }\n      14% { opacity: 1; }\n    }\n    @media (prefers-reduced-motion: reduce) {\n      #__farm_build_activity__ { transition: none; }\n      #__farm_build_activity__[data-state=\"building\"] .farm-build-activity__cell {\n        animation: none;\n        opacity: 0.28;\n      }\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 createBrandMark = () => {\n      const namespace = \"http://www.w3.org/2000/svg\";\n      const mark = document.createElementNS(namespace, \"svg\");\n      mark.setAttribute(\"class\", \"farm-build-activity__mark\");\n      mark.setAttribute(\"viewBox\", \"125 68 161 152\");\n      mark.setAttribute(\"fill\", \"none\");\n      mark.setAttribute(\"aria-hidden\", \"true\");\n\n      const shapes = [\n        [\"M157 68H133C128.582 68 125 71.5817 125 76V100C125 104.418 128.582 108 133 108H157C161.418 108 165 104.418 165 100V76C165 71.5817 161.418 68 157 68Z\", \"#F5F5F4\"],\n        [\"M182.383 68H280.617C282.045 68 283.414 68.8429 284.423 70.3431C285.433 71.8434 286 73.8783 286 76V100C286 102.122 285.433 104.157 284.423 105.657C283.414 107.157 282.045 108 280.617 108H182.383C180.955 108 179.586 107.157 178.577 105.657C177.567 104.157 177 102.122 177 100V76C177 73.8783 177.567 71.8434 178.577 70.3431C179.586 68.8429 180.955 68 182.383 68ZM271.852 81C270.747 81 269.852 81.8954 269.852 83V93C269.852 94.1046 270.747 95 271.852 95H277.272C278.376 95 279.272 94.1046 279.272 93V83C279.272 81.8954 278.376 81 277.272 81H271.852Z\", \"#F5F5F4\"],\n        [\"M157 124H133C128.582 124 125 127.582 125 132V156C125 160.418 128.582 164 133 164H157C161.418 164 165 160.418 165 156V132C165 127.582 161.418 124 157 124Z\", \"#A3A3A3\"],\n        [\"M280.334 124H182.666C179.537 124 177 127.582 177 132V156C177 160.418 179.537 164 182.666 164H280.334C283.463 164 286 160.418 286 156V132C286 127.582 283.463 124 280.334 124Z\", \"#A3A3A3\"],\n        [\"M157 180H133C128.582 180 125 183.582 125 188V212C125 216.418 128.582 220 133 220H157C161.418 220 165 216.418 165 212V188C165 183.582 161.418 180 157 180Z\", \"#595959\"],\n        [\"M230.189 180H182.811C179.602 180 177 183.582 177 188V212C177 216.418 179.602 220 182.811 220H230.189C233.398 220 236 216.418 236 212V188C236 183.582 233.398 180 230.189 180Z\", \"#595959\"],\n      ];\n      for (const [index, [pathData, fill]] of shapes.entries()) {\n        const path = document.createElementNS(namespace, \"path\");\n        path.setAttribute(\"d\", pathData);\n        path.setAttribute(\"fill\", fill);\n        if (index === 1) {\n          path.setAttribute(\"fill-rule\", \"evenodd\");\n          path.setAttribute(\"clip-rule\", \"evenodd\");\n        }\n        mark.appendChild(path);\n      }\n      return mark;\n    };\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\n        const brand = document.createElement(\"span\");\n        brand.className = \"farm-build-activity__brand\";\n        brand.setAttribute(\"aria-hidden\", \"true\");\n        const wordmark = document.createElement(\"span\");\n        wordmark.className = \"farm-build-activity__wordmark\";\n        const suffix = document.createElement(\"span\");\n        suffix.className = \"farm-build-activity__wordmark-suffix\";\n        suffix.textContent = \".JS\";\n        wordmark.append(\"FARM\", suffix);\n        brand.append(createBrandMark(), wordmark);\n\n        const divider = document.createElement(\"span\");\n        divider.className = \"farm-build-activity__divider\";\n        divider.setAttribute(\"aria-hidden\", \"true\");\n\n        const loader = document.createElement(\"span\");\n        loader.className = \"farm-build-activity__loader\";\n        loader.setAttribute(\"aria-hidden\", \"true\");\n        for (let index = 0; index < 9; index += 1) {\n          const cell = document.createElement(\"span\");\n          cell.className = \"farm-build-activity__cell\";\n          loader.appendChild(cell);\n        }\n\n        const label = document.createElement(\"span\");\n        label.className = \"farm-build-activity__label\";\n        label.setAttribute(\"aria-hidden\", \"true\");\n        label.dataset.farmBuildLabel = \"\";\n        const message = document.createElement(\"span\");\n        message.className = \"farm-build-activity__sr-only\";\n        message.dataset.farmBuildMessage = \"\";\n        indicator.append(loader, label, divider, brand, message);\n        document.body.appendChild(indicator);\n      }\n      return indicator;\n    };\n\n    const show = (state, label, message) => {\n      window.clearTimeout(hideTimer);\n      const indicator = ensureIndicator();\n      indicator.dataset.state = state;\n      indicator.dataset.visible = \"true\";\n      indicator.querySelector(\"[data-farm-build-label]\").textContent = label;\n      indicator.querySelector(\"[data-farm-build-message]\").textContent = message;\n    };\n    const hide = () => {\n      const indicator = document.getElementById(indicatorId);\n      if (indicator) indicator.dataset.visible = \"false\";\n    };\n    const onBeforeUpdate = () => show(\"building\", \"Updating\", \"Farm.js updating\");\n    const onAfterUpdate = () => {\n      show(\"ready\", \"Ready\", \"Farm.js ready\");\n      hideTimer = window.setTimeout(hide, 500);\n    };\n    const onError = () => show(\"error\", \"Build failed\", \"Farm.js build failed\");\n    const onBeforeFullReload = () => {\n      try {\n        window.sessionStorage.setItem(reloadMarker, \"1\");\n      } catch {}\n      show(\"building\", \"Updating\", \"Farm.js 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>();\nlet nextWarningExpiry = Infinity;\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  if (warnings.length === 0 && reportedWarnings.size === 0) return;\n  const now = Date.now();\n  // Most responses arrive before any entry can expire. Keep empty-call cleanup\n  // and wall-clock rollback semantics without scanning live history each time.\n  if (now >= nextWarningExpiry) {\n    nextWarningExpiry = Infinity;\n    for (const [key, reportedAt] of reportedWarnings) {\n      const expiresAt = reportedAt + PRELOAD_WARNING_TTL_MS;\n      if (now >= expiresAt) reportedWarnings.delete(key);\n      else nextWarningExpiry = Math.min(nextWarningExpiry, expiresAt);\n    }\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    nextWarningExpiry = Math.min(nextWarningExpiry, now + PRELOAD_WARNING_TTL_MS);\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  nextWarningExpiry = Infinity;\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  // getHtmlPreloadKind needs a literal `preload` relation token inside the link\n  // tag, so no link that starts after the last token can be a candidate. Stop\n  // the scan there (font preloads usually sit in <head>), and skip it entirely,\n  // including modulepreload-only pages, when there is no token. Possible matches\n  // still use the full parser below, even in inert text. Other runtime input\n  // types retain the existing full scan and its errors.\n  const lastToken = typeof html === \"string\" ? findLastPreloadToken(html) : Infinity;\n  if (lastToken === -1) return [];\n\n  const elements: HtmlLinkElement[] = [];\n  // Fold only the prefix the scan can reach. A raw-text element that opens\n  // before the last token but closes after it folds the rest on demand.\n  let lowerHtml = foldHtmlTagCase(\n    lastToken === Infinity ? html : html.slice(0, lastToken + RAW_TEXT_TAG_LOOKAHEAD),\n  );\n  // Sticky matches stay anchored at this tag without slicing the rest of the\n  // document. Keep their cursors local to this synchronous scan.\n  const rawTextTag = /<(script|style|template|textarea|title|noscript|svg)(?=[\\s/>])/y;\n  const linkTag = /<link(?=[\\s/>])/iy;\n  const ordinaryTag = /<\\/?[A-Za-z][\\w:-]*(?=[\\s/>])/y;\n  let cursor = 0;\n\n  while (cursor < html.length) {\n    const start = html.indexOf(\"<\", cursor);\n    if (start === -1 || start > lastToken) break;\n\n    if (html.startsWith(\"<!--\", start)) {\n      const commentEnd = html.indexOf(\"-->\", start + 4);\n      cursor = commentEnd === -1 ? html.length : commentEnd + 3;\n      continue;\n    }\n\n    rawTextTag.lastIndex = start;\n    const rawText = rawTextTag.exec(lowerHtml);\n    if (rawText?.[1]) {\n      const openingEnd = findHtmlTagEnd(html, start);\n      if (openingEnd === -1) break;\n      if (rawText[1] === \"svg\" && html[openingEnd - 2] === \"/\") {\n        cursor = openingEnd;\n        continue;\n      }\n      let closingStart = findHtmlClosingTag(lowerHtml, rawText[1], openingEnd);\n      if (closingStart === -1 && lowerHtml.length < html.length) {\n        lowerHtml = foldHtmlTagCase(html);\n        closingStart = findHtmlClosingTag(lowerHtml, rawText[1], openingEnd);\n      }\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    linkTag.lastIndex = start;\n    if (linkTag.test(html)) {\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    ordinaryTag.lastIndex = start;\n    if (ordinaryTag.test(html)) {\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\n// Longest raw-text opener the scan matches at a tag start (\"<template\", \"<textarea\",\n// \"<noscript\") plus its boundary character, with margin.\nconst RAW_TEXT_TAG_LOOKAHEAD = 16;\nconst PRELOAD_TOKEN = /\\bpreload\\b/gi;\n\nfunction findLastPreloadToken(html: string): number {\n  let last = -1;\n  PRELOAD_TOKEN.lastIndex = 0;\n  for (let match = PRELOAD_TOKEN.exec(html); match; match = PRELOAD_TOKEN.exec(html)) {\n    last = match.index;\n  }\n  return last;\n}\n\nfunction foldHtmlTagCase(html: string): string {\n  const lowerHtml = html.toLowerCase();\n  // Unicode lowercasing can expand UTF-16 offsets (for example, İ -> i̇).\n  // Tag names only need ASCII folding; preserve source offsets for the scan.\n  return lowerHtml.length === html.length\n    ? lowerHtml\n    : html.replace(/[A-Z]/g, (letter) => letter.toLowerCase());\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","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      schema: config.schema || {},\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","/**\n * Plugins that need other plugins. A dependency is named by the other\n * plugin's full name (`farm:teams`), the part after its last `:` or `/`\n * (`teams`, also its `farm <name> migrate` command), or an integration key.\n */\n\n/** `farm:teams` and `@acme/teams` → `teams`. */\nexport function pluginShortName(name: string): string {\n  return name.slice(Math.max(name.lastIndexOf(\":\"), name.lastIndexOf(\"/\")) + 1);\n}\n\ntype DependentPlugin = { name: string; dependsOn?: readonly string[] };\n\n/**\n * Fail while the config loads when a plugin needs one that is not configured,\n * names itself, or the declared dependencies form a cycle.\n */\nexport function assertPluginDependencies(\n  plugins: readonly DependentPlugin[],\n  integrations?: Record<string, unknown> | readonly unknown[],\n): void {\n  const integrationKeys =\n    integrations && !Array.isArray(integrations) ? Object.keys(integrations) : [];\n  const matches = (plugin: DependentPlugin, dependency: string) =>\n    plugin.name === dependency || pluginShortName(plugin.name) === dependency;\n\n  for (const plugin of plugins) {\n    if (plugin.dependsOn === undefined) continue;\n    if (\n      !Array.isArray(plugin.dependsOn) ||\n      plugin.dependsOn.some((entry) => typeof entry !== \"string\" || entry.trim() === \"\")\n    ) {\n      throw new TypeError(\n        `Plugin \"${plugin.name}\" has an invalid \\`dependsOn\\`: list plugin names, such as [\"teams\"].`,\n      );\n    }\n    for (const dependency of plugin.dependsOn) {\n      if (matches(plugin, dependency)) {\n        throw new Error(`Plugin \"${plugin.name}\" lists itself in \\`dependsOn\\`.`);\n      }\n      const found =\n        plugins.some((candidate) => candidate !== plugin && matches(candidate, dependency)) ||\n        integrationKeys.includes(dependency);\n      if (!found) {\n        const configured = [\n          ...plugins.map((candidate) => candidate.name),\n          ...integrationKeys,\n        ].filter((name) => name !== plugin.name);\n        throw new Error(\n          `Plugin \"${plugin.name}\" depends on \"${dependency}\", which is not configured. Add it to \\`plugins\\` (or \\`integrations\\`) in farm.config.${configured.length > 0 ? ` Configured: ${configured.join(\", \")}.` : \"\"}`,\n        );\n      }\n    }\n  }\n\n  // A cycle in what plugins declare is a mistake: neither can come first.\n  const state = new Map<DependentPlugin, \"visiting\" | \"done\">();\n  const path: DependentPlugin[] = [];\n  const visit = (plugin: DependentPlugin) => {\n    if (state.get(plugin) === \"done\") return;\n    if (state.get(plugin) === \"visiting\") {\n      const cycle = [...path.slice(path.indexOf(plugin)), plugin].map((entry) =>\n        pluginShortName(entry.name),\n      );\n      throw new Error(`Plugins depend on each other in a cycle: ${cycle.join(\" → \")}.`);\n    }\n    state.set(plugin, \"visiting\");\n    path.push(plugin);\n    for (const dependency of plugin.dependsOn ?? []) {\n      for (const candidate of plugins) {\n        if (candidate !== plugin && matches(candidate, dependency)) visit(candidate);\n      }\n    }\n    path.pop();\n    state.set(plugin, \"done\");\n  };\n  for (const plugin of plugins) visit(plugin);\n}\n","import type { FarmSchema } from \"./schema\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\nimport type { FarmSqlDialect } from \"./schema-sql\";\n\n// Kept apart from schema-steps.ts, which reads and writes databases, so\n// definePlugin can validate steps without loading any of it.\n\n/**\n * An ordered change a plugin release makes to its own tables that Farm will\n * not infer: a rename looks exactly like a removal plus an addition. Each step\n * runs once per database, in the order listed.\n *\n * Names are the plugin's own: `model` and `to` are keys in the current\n * schema, so the app's renames apply; `from` is the old name in the database.\n */\nexport type FarmSchemaMigrationStep = { id: string; description?: string } & (\n  | { renameColumn: { model: string; from: string; to: string } }\n  | { renameTable: { from: string; to: string } }\n  /**\n   * Deletes data, so it runs only with `--allow-destructive`, and only on a\n   * column or table Farm recorded this plugin creating.\n   */\n  | { dropColumn: { model: string; column: string } }\n  | { dropTable: { table: string } }\n  | {\n      /** Per dialect; a dialect without SQL cannot run the step. */\n      sql: Partial<Record<FarmSqlDialect, string | readonly string[]>>;\n      /**\n       * Custom SQL runs after this release's new tables and columns exist, so\n       * a backfill can fill them. Set `before` to run it with the renames.\n       */\n      before?: boolean;\n    }\n);\n\n/** Throw, while the config loads, for a step list that cannot work. */\nexport function validateSchemaSteps(\n  owner: string,\n  schema: FarmSchema,\n  steps: readonly FarmSchemaMigrationStep[] | undefined,\n): void {\n  if (steps === undefined) return;\n  if (!Array.isArray(steps)) {\n    throw new TypeError(`${owner}: \\`migrations\\` must be a list of steps.`);\n  }\n  const models = resolveSchemaModels(owner, schema);\n  const ids = new Set<string>();\n  for (const step of steps) {\n    const where = `${owner} migration \"${step?.id}\"`;\n    if (!step || typeof step.id !== \"string\" || step.id.trim() === \"\") {\n      throw new TypeError(`${owner}: every migration step needs a non-empty \\`id\\`.`);\n    }\n    if (ids.has(step.id))\n      throw new Error(`${owner}: two migration steps share the id \"${step.id}\".`);\n    ids.add(step.id);\n    const kinds = [\"renameColumn\", \"renameTable\", \"dropColumn\", \"dropTable\", \"sql\"].filter(\n      (kind) => kind in step,\n    );\n    if (kinds.length !== 1) {\n      throw new Error(\n        `${where} must be exactly one of renameColumn, renameTable, dropColumn, dropTable, or sql.`,\n      );\n    }\n    if (\"renameColumn\" in step) {\n      const { model, from, to } = step.renameColumn;\n      const target = Object.prototype.hasOwnProperty.call(models, model)\n        ? models[model]\n        : undefined;\n      if (!target)\n        throw new Error(`${where} renames a column of \"${model}\", which is not a model.`);\n      if (!Object.prototype.hasOwnProperty.call(target.fields, to)) {\n        throw new Error(`${where} renames to \"${model}.${to}\", which is not a field.`);\n      }\n      if (typeof from !== \"string\" || from.trim() === \"\") {\n        throw new Error(`${where} needs the old column name in \\`from\\`.`);\n      }\n    } else if (\"renameTable\" in step) {\n      const { from, to } = step.renameTable;\n      if (!Object.prototype.hasOwnProperty.call(models, to)) {\n        throw new Error(`${where} renames a table to \"${to}\", which is not a model.`);\n      }\n      if (typeof from !== \"string\" || from.trim() === \"\") {\n        throw new Error(`${where} needs the old table name in \\`from\\`.`);\n      }\n    } else if (\"dropColumn\" in step) {\n      const { model, column } = step.dropColumn;\n      const target = Object.prototype.hasOwnProperty.call(models, model)\n        ? models[model]\n        : undefined;\n      if (!target) {\n        throw new Error(`${where} drops a column of \"${model}\", which is not a model.`);\n      }\n      if (typeof column !== \"string\" || column.trim() === \"\") {\n        throw new Error(`${where} needs the column to drop in \\`column\\`.`);\n      }\n      // A step can only remove what this release no longer declares.\n      const current = Object.entries(target.fields).find(\n        ([key, field]) => key === column || field.name === column,\n      );\n      if (current) {\n        throw new Error(`${where} drops \"${model}.${column}\", which is still in the schema.`);\n      }\n    } else if (\"dropTable\" in step) {\n      const { table } = step.dropTable;\n      if (typeof table !== \"string\" || table.trim() === \"\") {\n        throw new Error(`${where} needs the table to drop in \\`table\\`.`);\n      }\n      const current = Object.entries(models).find(\n        ([key, model]) => key === table || model.name === table,\n      );\n      if (current) {\n        throw new Error(\n          `${where} drops \"${table}\", which is still in the schema${current[1].external ? \" as a table the plugin does not own\" : \"\"}.`,\n        );\n      }\n    } else {\n      const sql = step.sql;\n      const dialects = Object.keys(sql ?? {});\n      if (!sql || typeof sql !== \"object\" || dialects.length === 0) {\n        throw new Error(`${where} needs SQL for at least one of postgres, mysql, or sqlite.`);\n      }\n    }\n  }\n}\n","/**\n * Typed, validated plugin options.\n *\n * A plugin factory takes one options object. Describing it with a Standard\n * Schema (Zod, Valibot, ArkType, ...) gives the call site its input type for\n * autocomplete, gives the plugin the parsed type with defaults applied, and\n * rejects bad options while the config loads instead of deep inside a hook.\n */\n\ntype MaybePromise<T> = T | Promise<T>;\n\ntype FarmPluginOptionsIssuePathSegment = PropertyKey | { readonly key: PropertyKey };\n\nexport interface FarmPluginOptionsIssue {\n  readonly message: string;\n  readonly path?: ReadonlyArray<FarmPluginOptionsIssuePathSegment> | undefined;\n}\n\ntype FarmPluginOptionsResult<TOutput> =\n  | { readonly value: TOutput; readonly issues?: undefined }\n  | { readonly issues: ReadonlyArray<FarmPluginOptionsIssue> };\n\n/** The part of the Standard Schema interface plugin options need. */\nexport interface FarmPluginOptionsSchema<TInput = unknown, TOutput = TInput> {\n  readonly \"~standard\": {\n    readonly version: 1;\n    readonly vendor: string;\n    readonly validate: (value: unknown) => MaybePromise<FarmPluginOptionsResult<TOutput>>;\n    readonly types?: { readonly input: TInput; readonly output: TOutput } | undefined;\n  };\n}\n\n/** What the app passes to the plugin factory. */\nexport type InferPluginOptionsInput<TSchema> =\n  TSchema extends FarmPluginOptionsSchema<infer TInput, any> ? TInput : never;\n\n/** What the plugin receives, after parsing and defaults. */\nexport type InferPluginOptionsOutput<TSchema> =\n  TSchema extends FarmPluginOptionsSchema<any, infer TOutput> ? TOutput : never;\n\n/**\n * The factory a plugin exports. Options can be left out when every option is\n * optional, so `plugin()` and `plugin({})` mean the same thing.\n */\nexport type FarmPluginFactory<TInput, TPlugin> = {} extends TInput\n  ? (options?: TInput) => TPlugin\n  : (options: TInput) => TPlugin;\n\n/** Thrown when an app passes options its plugin's schema rejects. */\nexport class FarmPluginOptionsError extends TypeError {\n  readonly issues: ReadonlyArray<FarmPluginOptionsIssue>;\n\n  constructor(issues: ReadonlyArray<FarmPluginOptionsIssue>) {\n    const lines = issues.map((issue) => {\n      const path = formatIssuePath(issue.path);\n      return `  - ${path ? `${path}: ` : \"\"}${issue.message}`;\n    });\n    super(`Invalid plugin options:\\n${lines.join(\"\\n\")}`);\n    this.name = \"FarmPluginOptionsError\";\n    this.issues = issues;\n  }\n}\n\nfunction formatIssuePath(path: FarmPluginOptionsIssue[\"path\"]): string {\n  if (!path?.length) return \"\";\n  return path\n    .map((segment) => {\n      const key = typeof segment === \"object\" && segment !== null ? segment.key : segment;\n      return typeof key === \"symbol\" ? key.toString() : String(key);\n    })\n    .join(\".\");\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n  return (\n    (typeof value === \"object\" || typeof value === \"function\") &&\n    value !== null &&\n    typeof (value as PromiseLike<unknown>).then === \"function\"\n  );\n}\n\n/** True for a Standard Schema: an object exposing `~standard.validate`. */\nexport function isPluginOptionsSchema(value: unknown): value is FarmPluginOptionsSchema {\n  if ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) return false;\n  const standard = (value as { \"~standard\"?: { validate?: unknown } })[\"~standard\"];\n  return typeof standard?.validate === \"function\";\n}\n\n/**\n * Validate options against their schema. Plugins are created while the config\n * loads, which is synchronous, so an asynchronous schema is rejected rather\n * than silently skipped. Missing options are validated as `{}`.\n */\nexport function parsePluginOptions<TSchema extends FarmPluginOptionsSchema<any, any>>(\n  schema: TSchema,\n  options: unknown,\n): InferPluginOptionsOutput<TSchema> {\n  const standard = schema?.[\"~standard\"];\n  if (!standard || typeof standard.validate !== \"function\") {\n    throw new TypeError(\n      \"A plugin's `options` needs a Standard Schema, such as a Zod, Valibot, or ArkType schema.\",\n    );\n  }\n\n  const result = standard.validate(options === undefined ? {} : options);\n  if (isPromiseLike(result)) {\n    throw new TypeError(\n      \"Plugin option schemas must validate synchronously: plugins are created while the config loads. Remove asynchronous refinements or transforms from the schema.\",\n    );\n  }\n  if (result.issues) throw new FarmPluginOptionsError(result.issues);\n  return result.value as InferPluginOptionsOutput<TSchema>;\n}\n","import type { FarmPlugin } from \"./plugin\";\n\n/** @internal Normalize and validate an exact application-relative plugin endpoint path. */\nexport function normalizeFarmPluginRuntimeEndpointPath(\n  pathname: string,\n  label = \"Farm plugin runtime endpoint\",\n): string {\n  if (typeof pathname !== \"string\" || pathname.trim() !== pathname || pathname.length === 0) {\n    throw new TypeError(`${label} path must be a non-empty pathname without surrounding spaces`);\n  }\n  if (\n    !pathname.startsWith(\"/\") ||\n    pathname.startsWith(\"//\") ||\n    pathname.includes(\"?\") ||\n    pathname.includes(\"#\") ||\n    pathname.includes(\"*\")\n  ) {\n    throw new TypeError(`${label} path must be an exact pathname such as \"/status\"`);\n  }\n  if (\n    pathname.includes(\"\\\\\") ||\n    Array.from(pathname).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  ) {\n    throw new TypeError(`${label} path cannot contain backslashes or control characters`);\n  }\n\n  for (const segment of pathname.split(\"/\").slice(1)) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      throw new TypeError(`${label} path contains a malformed percent escape`);\n    }\n    if (decoded.includes(\"/\") || decoded.includes(\"\\\\\")) {\n      throw new TypeError(`${label} path cannot contain percent-encoded path separators`);\n    }\n    if (\n      Array.from(decoded).some((character) => {\n        const code = character.charCodeAt(0);\n        return code <= 31 || (code >= 127 && code <= 159);\n      })\n    ) {\n      throw new TypeError(`${label} path cannot contain control characters`);\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new TypeError(`${label} path cannot contain dot segments`);\n    }\n  }\n\n  return normalizeRuntimeEndpointRequestPath(pathname);\n}\n\n/** @internal Normalize a URL pathname for exact endpoint matching. */\nexport function normalizeRuntimeEndpointRequestPath(pathname: string): string {\n  return pathname.length > 1 ? pathname.replace(/\\/+$/, \"\") || \"/\" : pathname;\n}\n\n/** @internal Whether a server plugin can change how a specific application path is served. */\nexport function farmPluginMayAffectRuntimePath(plugin: FarmPlugin, pathname: string): boolean {\n  const runtime = plugin.runtime;\n  const endpoints = runtime?.endpoints;\n  const hasUnscopedRequestHooks = Boolean(\n    plugin.init ||\n    plugin.ready ||\n    plugin.shutdown ||\n    runtime?.context ||\n    runtime?.before ||\n    runtime?.after ||\n    runtime?.error ||\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    plugin.beforeRequest ||\n    plugin.afterResponse,\n  );\n  if (hasUnscopedRequestHooks) return true;\n\n  if (Array.isArray(endpoints) && endpoints.length > 0) {\n    const normalizedPathname = normalizeRuntimeEndpointRequestPath(pathname);\n    return endpoints.some(\n      (endpoint) =>\n        normalizeFarmPluginRuntimeEndpointPath(\n          endpoint.path,\n          `Farm plugin \"${plugin.name}\" runtime endpoint`,\n        ) === normalizedPathname,\n    );\n  }\n\n  return Boolean(plugin.setup || runtime?.start || runtime?.close);\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          const serialized = JSON.stringify(next.value);\n          if (serialized === undefined) {\n            throw new TypeError(\"Farm JSON stream chunks must be JSON-serializable values\");\n          }\n          controller.enqueue(encoder.encode(`${serialized}\\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\";\nimport type { EndpointOpenAPIMetadata } from \"../openapi/types\";\n\n// Part of every endpoint's public shape (`openapi` and `__openapi` below). An\n// interface cannot be inlined into a consumer's declarations, so it has to be\n// nameable from the entry a consumer imports. `export *` in api/index.ts exposes\n// it as @farm.js/core/api; plugin.ts re-exports it for plugin authors.\nexport type { EndpointOpenAPIMetadata };\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\ntype InferHeadersInput<T> = [T] extends [never] ? never : InferInput<T>;\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\n/** Metadata used when an installed MCP transport exposes this endpoint as a tool. */\nexport interface EndpointMCPMetadata {\n  /** Optional MCP tool name. Farm derives one from the method and path when omitted. */\n  name?: string;\n  title?: string;\n  description?: string;\n  readOnlyHint?: boolean;\n  destructiveHint?: boolean;\n  idempotentHint?: boolean;\n  openWorldHint?: boolean;\n}\n\n/** Opt an endpoint into MCP discovery with derived or explicit tool metadata. */\nexport type EndpointMCPOptions = true | EndpointMCPMetadata;\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  /** OpenAPI-only operation metadata. This does not enforce authentication at runtime. */\n  openapi?: EndpointOpenAPIMetadata;\n  /**\n   * Opt this endpoint into an installed MCP transport. This is discovery metadata only;\n   * transport and endpoint authorization remain required separately.\n   */\n  mcp?: EndpointMCPOptions;\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  THeadersInput = THeaders,\n> = {\n  __types: {\n    body: TBody;\n    inputBody: TBodyInput;\n    query: TQuery;\n    inputQuery: TQueryInput;\n    headers: THeaders;\n    inputHeaders: THeadersInput;\n    response: TResponse;\n    errors: TErrors;\n  };\n  __path?: string;\n  __method?: string;\n  __openapi?: EndpointOpenAPIMetadata;\n  __mcp?: EndpointMCPOptions;\n} & ((options?: {\n  body?: TBodyInput;\n  query?: TQueryInput;\n  headers?: THeadersInput;\n}) => 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  InferHeadersInput<THeaders>\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    openapi: _openapi,\n    mcp: _mcp,\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  endpoint.__openapi = options.openapi;\n  endpoint.__mcp = options.mcp;\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 EndpointMCPOptions,\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  /** Opt this app-owned endpoint into an installed MCP transport. */\n  mcp?: EndpointMCPOptions;\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 interface PluginLocalAPIEndpoint {\n  readonly path: string;\n  readonly method: RouteMethod;\n  readonly input: Readonly<RouteInputSchemas>;\n  readonly output?: RouteSchema;\n  readonly mcp?: EndpointMCPOptions;\n  invoke(request: Request, params?: Readonly<Record<string, string | string[]>>): Promise<Response>;\n}\n\n/**\n * Read-only access to app-owned API endpoints while plugin routes are mounted.\n * Plugin routes are intentionally excluded so a plugin cannot recurse through\n * itself or depend on plugin registration order.\n */\nexport interface PluginLocalAPI {\n  /** False during type-only route discovery, where app endpoint modules are unavailable. */\n  readonly available: boolean;\n  get(method: RouteMethod, path: string): PluginLocalAPIEndpoint | undefined;\n  /** Enumerate app-owned endpoints. Plugin routes are excluded. */\n  list(): readonly PluginLocalAPIEndpoint[];\n}\n\nexport type PluginRoutesFactory<R extends PluginRoutes = PluginRoutes> = (context: {\n  route: RouteFactory;\n  api: PluginLocalAPI;\n}) => R;\n\nconst unavailablePluginLocalAPI: PluginLocalAPI = Object.freeze({\n  available: false,\n  get() {\n    return undefined;\n  },\n  list() {\n    return [];\n  },\n});\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          mcp: options.mcp,\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  context: { api?: PluginLocalAPI } = {},\n): PluginRoutes {\n  return plugins.flatMap((plugin) => {\n    if (!plugin.routes) return [];\n    const routes = plugin.routes({\n      route: createRouteFactory(),\n      api: context.api ?? unavailablePluginLocalAPI,\n    });\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  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  // Prefer an explicitly asynchronous parser. Some Standard Schema adapters try\n  // a synchronous parse first, then repeat async refinements when it fails.\n  if (schema.parseAsync) return schema.parseAsync(value);\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.parse) return schema.parse(value);\n  throw new TypeError(\"Route validators must implement Standard Schema or parse().\");\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 { 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\ninterface CompiledAPIRouteSegment {\n  value?: string;\n  dynamic?: { name: string; catchAll: boolean; optional: boolean };\n}\n\ninterface CompiledAPIRouteEntry {\n  path: string;\n  segments: CompiledAPIRouteSegment[];\n  specificity: RouteSegmentSpecificity[];\n}\n\n// Cache only route metadata, not table membership or winners. Live Map mutations,\n// HMR replacement, and edits to route.path therefore remain visible immediately.\nconst compiledEntries = new WeakMap<object, CompiledAPIRouteEntry>();\n\ninterface IndexedAPIRoute<T extends { path: string }> {\n  route: T;\n  compiled: CompiledAPIRouteEntry;\n  order: number;\n}\n\ninterface APIRoutePrefix<T extends { path: string }> {\n  children: Map<string, APIRoutePrefix<T>>;\n  candidates: IndexedAPIRoute<T>[];\n}\n\n/**\n * @internal Snapshot matcher for the generated production route table only.\n * The public live-Map matcher below intentionally does not use this index.\n */\nexport function createStaticAPIRouteMatcher<T extends { path: string }>(routes: readonly T[]) {\n  const table = new Map(routes.map((route) => [route.path, Object.freeze({ ...route })]));\n  const root: APIRoutePrefix<T> = { children: new Map(), candidates: [] };\n  let order = 0;\n  for (const route of table.values()) {\n    const compiled = compileRouteEntry(route.path);\n    let node = root;\n    // Only prune by a proven static prefix. Dynamic/catch-all tails still use\n    // the authoritative matcher, including its existing specificity rules.\n    for (const segment of compiled.segments) {\n      if (segment.dynamic) break;\n      let child = node.children.get(segment.value!);\n      if (!child) {\n        child = { children: new Map(), candidates: [] };\n        node.children.set(segment.value!, child);\n      }\n      node = child;\n    }\n    node.candidates.push({ route, compiled, order: order++ });\n  }\n\n  return (pathname: string): APIRouteMatch<T> | null => {\n    const exactRoute = table.get(pathname);\n    if (exactRoute) return { route: exactRoute, params: {} };\n    const normalizedPathname = normalizePathname(pathname);\n    if (normalizedPathname !== pathname) {\n      const normalizedRoute = table.get(normalizedPathname);\n      if (normalizedRoute) return { route: normalizedRoute, params: {} };\n    }\n    const segments = getPathSegments(normalizedPathname).map(decodePathSegment);\n    let best: IndexedAPIRoute<T> | undefined;\n    let bestMatch: APIRouteMatch<T> | null = null;\n    let node: APIRoutePrefix<T> | undefined = root;\n    let depth = 0;\n    while (node) {\n      for (const candidate of node.candidates) {\n        const params = matchRouteEntry(candidate.compiled, segments);\n        if (!params) continue;\n        const comparison = best\n          ? compareRouteSpecificity(candidate.compiled.specificity, best.compiled.specificity)\n          : -1;\n        if (comparison < 0 || (comparison === 0 && candidate.order < best!.order)) {\n          best = candidate;\n          bestMatch = { route: candidate.route, params };\n        }\n      }\n      node = depth < segments.length ? node.children.get(segments[depth++]!) : undefined;\n    }\n    return bestMatch;\n  };\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) return { route: exactRoute, params: {} };\n\n  const normalizedPathname = normalizePathname(pathname);\n  if (normalizedPathname !== pathname) {\n    const normalizedRoute = routes.get(normalizedPathname);\n    if (normalizedRoute) return { route: normalizedRoute, params: {} };\n  }\n\n  const pathnameSegments = getPathSegments(normalizedPathname).map(decodePathSegment);\n  let bestMatch: APIRouteMatch<T> | null = null;\n  let bestSpecificity: RouteSegmentSpecificity[] | null = null;\n  for (const route of routes.values()) {\n    const routePath = route.path;\n    let entry = compiledEntries.get(route);\n    if (!entry || entry.path !== routePath) {\n      entry = compileRouteEntry(routePath);\n      compiledEntries.set(route, entry);\n    }\n    const params = matchRouteEntry(entry, pathnameSegments);\n    if (!params) continue;\n    if (\n      bestSpecificity === null ||\n      compareRouteSpecificity(entry.specificity, bestSpecificity) < 0\n    ) {\n      bestMatch = { route, params };\n      bestSpecificity = entry.specificity;\n    }\n  }\n  return bestMatch;\n}\n\nfunction compileRouteEntry(path: string): CompiledAPIRouteEntry {\n  const segments = getPathSegments(path).map((segment) => {\n    const dynamic = parseDynamicSegment(segment);\n    return dynamic ? { dynamic } : { value: decodePathSegment(segment) };\n  });\n  return {\n    path,\n    segments,\n    specificity: segments.map((segment) => {\n      const dynamic = segment.dynamic;\n      if (!dynamic) return \"static\";\n      if (!dynamic.catchAll) return \"dynamic\";\n      return dynamic.optional ? \"optional-catch-all\" : \"catch-all\";\n    }),\n  };\n}\n\nfunction matchRouteEntry(\n  entry: CompiledAPIRouteEntry,\n  pathnameSegments: readonly string[],\n): APIRouteParams | null {\n  const params: APIRouteParams = {};\n  let pathIndex = 0;\n\n  for (const routeSegment of entry.segments) {\n    const dynamicSegment = routeSegment.dynamic;\n\n    if (dynamicSegment?.catchAll) {\n      const remainingSegments = pathnameSegments.slice(pathIndex);\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] = pathnameSegment;\n      pathIndex++;\n      continue;\n    }\n\n    if (routeSegment.value !== 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 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 { parseRouteSchema } from \"./route-schema\";\nexport { mergePluginAPIRoutes } from \"./plugin-route-runtime\";\n\nexport {\n  matchAPIRoute,\n  type APIRouteParams,\n  type APIRouteParamValue,\n  type APIRouteMatch,\n} from \"./route-pattern\";\nimport {\n  createStaticAPIRouteMatcher,\n  matchAPIRoute,\n  type APIRouteParams,\n  type APIRouteMatch,\n} from \"./route-pattern\";\n/**\n * Every method an API route module can export. Route discovery in core and in\n * the plain-Vite plugin reads this list, so a handler exported under any of\n * these names is served wherever the route is.\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\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/** @internal Prepare the fixed API table owned by a generated production bundle. */\nexport function createStaticAPIRouteMatcherAtBasePath<T extends { path: string }>(\n  routes: readonly T[],\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): (pathname: string) => APIRouteMatch<T> | null {\n  const match = createStaticAPIRouteMatcher(routes);\n  return (pathname) => {\n    const directMatch = match(pathname);\n    if (directMatch) return directMatch;\n    const canonicalPathname = resolveFarmAPICanonicalPathname(pathname, serverBasePath);\n    return canonicalPathname === pathname ? null : match(canonicalPathname);\n  };\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  let body: string | undefined;\n  try {\n    body = JSON.stringify(result);\n  } catch (error) {\n    const serializationError = new TypeError(\n      \"API route result must be a JSON-serializable value or a Response.\",\n    );\n    (serializationError as TypeError & { cause?: unknown }).cause = error;\n    throw serializationError;\n  }\n\n  if (body === undefined) {\n    throw new TypeError(\"API route result must be a JSON-serializable value or a Response.\");\n  }\n\n  return new Response(body, {\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  if (contentType === \"multipart/form-data\") {\n    try {\n      return { body: formDataToObject(await request.clone().formData()) };\n    } catch {\n      return invalidRequestBody(\"The request body is not valid multipart form data.\");\n    }\n  }\n\n  let text: string;\n  try {\n    text = await request.clone().text();\n  } catch {\n    if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n      return invalidRequestBody(\"The request body is not valid JSON.\");\n    }\n    if (contentType === \"application/x-www-form-urlencoded\") {\n      return invalidRequestBody(\"The request body is not valid URL-encoded form data.\");\n    }\n    return { body: undefined };\n  }\n\n  if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n    // QUERY requires a Content-Type header even when it carries no body, and\n    // generated clients intentionally send application/json for that case.\n    // Preserve the bodyless representation so optional or schema-less QUERY\n    // endpoints can validate and run as they did before.\n    if (!text && request.method.toUpperCase() === \"QUERY\") {\n      return { body: undefined };\n    }\n    try {\n      return { body: JSON.parse(text) };\n    } catch {\n      return invalidRequestBody(\"The request body is not valid JSON.\");\n    }\n  }\n\n  if (contentType === \"application/x-www-form-urlencoded\") {\n    return { body: searchParamsToObject(new URLSearchParams(text)) };\n  }\n\n  if (!text) return { body: undefined };\n\n  // A body is only parsed as JSON when the request says it is JSON, or when it\n  // declares no type at all (the permissive path kept for non-browser callers\n  // that omit the header).\n  //\n  // Parsing a *declared* non-JSON type as JSON removed the barrier that keeps\n  // browsers from reaching this surface cross-origin: `text/plain`,\n  // `application/x-www-form-urlencoded`, and `multipart/form-data` are the\n  // CORS \"simple\" types that a cross-site page may send with credentials and\n  // without a preflight. Honouring the declared type means such a request no\n  // longer arrives as a parsed JSON object.\n  if (contentType === undefined) {\n    try {\n      return { body: JSON.parse(text) };\n    } catch {\n      return { body: undefined };\n    }\n  }\n\n  return { body: undefined };\n}\n\nfunction invalidRequestBody(message: string): RequestBodyParseResult {\n  return {\n    error: new Response(\n      JSON.stringify({\n        error: \"Invalid request body\",\n        message,\n      }),\n      {\n        status: 400,\n        headers: { \"Content-Type\": \"application/json\" },\n      },\n    ),\n  };\n}\n\nfunction formDataToObject(\n  formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n  return entriesToObject(formData.entries());\n}\n\nfunction searchParamsToObject(searchParams: URLSearchParams): Record<string, string | string[]> {\n  return entriesToObject(searchParams.entries());\n}\n\nfunction entriesToObject<TValue>(\n  entries: IterableIterator<[string, TValue]>,\n): Record<string, TValue | TValue[]> {\n  const output: Record<string, TValue | TValue[]> = Object.create(null);\n  for (const [key, value] of entries) {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n    const current = output[key];\n    if (current === undefined) {\n      output[key] = value;\n    } else if (Array.isArray(current)) {\n      current.push(value);\n    } else {\n      output[key] = [current, value];\n    }\n  }\n  return output;\n}\n\nasync function validateInput(\n  schema: any,\n  value: unknown,\n  error: string,\n): Promise<unknown | Response> {\n  if (!schema) return value;\n  try {\n    return await parseRouteSchema(schema, value);\n  } catch (validationError: any) {\n    return Response.json(\n      {\n        error,\n        details: (validationError.issues || validationError.errors || []).map((issue: any) => ({\n          path: issue.path,\n          message: issue.message,\n          code: issue.code,\n        })),\n      },\n      { status: 400 },\n    );\n  }\n}\n","import {\n  resolvePluginRoutes,\n  type PluginLocalAPI,\n  type PluginLocalAPIEndpoint,\n  type PluginRoutesFactory,\n  type RouteMethod,\n} from \"./route\";\nimport { invokeAPIRouteEndpoint } from \"./runtime\";\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  options: { bodySizeLimit?: number } = {},\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  const api = createPluginLocalAPI(existing, options.bodySizeLimit);\n  for (const definition of resolvePluginRoutes(plugins, { api })) {\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    const actualSignature = signature(result);\n    const expectedSignature = signature(expected);\n    if (actualSignature !== expectedSignature) {\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          `Expected:\\n${expectedSignature || \"(none)\"}\\nReceived:\\n${actualSignature || \"(none)\"}`,\n      );\n    }\n  }\n  return result;\n}\n\nfunction createPluginLocalAPI(\n  routes: readonly MountedRoute[],\n  bodySizeLimit?: number,\n): PluginLocalAPI {\n  const endpoints = new Map<string, PluginLocalAPIEndpoint>();\n  for (const route of routes) {\n    for (const method of route.methods) {\n      const normalizedMethod = method.toUpperCase() as RouteMethod;\n      const endpoint = route.endpoints[normalizedMethod];\n      if (typeof endpoint !== \"function\") continue;\n      const descriptor: PluginLocalAPIEndpoint = Object.freeze({\n        path: route.path,\n        method: normalizedMethod,\n        input: Object.freeze({\n          body: endpoint.__types?.body,\n          query: endpoint.__types?.query,\n          params: endpoint.__types?.params,\n          headers: endpoint.__types?.headers,\n        }),\n        output: endpoint.__output,\n        mcp:\n          endpoint.__mcp === true\n            ? true\n            : endpoint.__mcp\n              ? Object.freeze({ ...endpoint.__mcp })\n              : undefined,\n        invoke(request: Request, params: Readonly<Record<string, string | string[]>> = {}) {\n          return invokeAPIRouteEndpoint(endpoint, request, { ...params }, bodySizeLimit);\n        },\n      });\n      endpoints.set(`${normalizedMethod} ${route.path}`, descriptor);\n    }\n  }\n  const listedEndpoints = Object.freeze(Array.from(endpoints.values()));\n\n  return Object.freeze({\n    available: true,\n    get(method: RouteMethod, path: string) {\n      return endpoints.get(`${method.toUpperCase()} ${path}`);\n    },\n    list() {\n      return listedEndpoints;\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 { toFileModuleUrl } from \"../utils/file-module\";\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  API_ROUTE_METHODS,\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 { API_ROUTE_METHODS };\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, undefined, {\n          bodySizeLimit: this.bodySizeLimit,\n        }).map((route) => [route.path, route]),\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    return await import(/* @vite-ignore */ toFileModuleUrl(filePath));\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","export interface ParsedRequestCookie {\n  name: string;\n  value: string;\n}\n\n/** Parse request cookies in wire order without collapsing duplicate names. */\nexport function parseRequestCookieHeader(header: string | null | undefined): ParsedRequestCookie[] {\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): string {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return value;\n  }\n}\n","import type { CookieOptions } from \"./types\";\nimport { parseRequestCookieHeader } from \"../request-cookies\";\n\nexport function parseMiddlewareCookieHeader(cookieHeader?: string | null): Record<string, string> {\n  const cookies = Object.create(null) as Record<string, string>;\n  for (const cookie of parseRequestCookieHeader(cookieHeader)) {\n    if (!Object.prototype.hasOwnProperty.call(cookies, cookie.name)) {\n      cookies[cookie.name] = cookie.value;\n    }\n  }\n\n  return cookies;\n}\n\n/**\n * Apply the attributes a cookie name prefix makes mandatory.\n *\n * Browsers reject a `Set-Cookie` whose name starts with `__Host-` or\n * `__Secure-` unless it carries `Secure` (and, for `__Host-`, `Path=/` with no\n * `Domain`). A rejected header is discarded silently, so emitting one without\n * these attributes makes both a set and a *deletion* a no-op — a logout that\n * looks like it worked while the session cookie stays live. The attributes are\n * therefore derived from the name rather than trusted from the caller.\n */\nexport function applyCookieNamePrefixRequirements(\n  name: string,\n  options: CookieOptions,\n): CookieOptions {\n  if (name.startsWith(\"__Host-\")) {\n    return { ...options, secure: true, path: \"/\", domain: undefined };\n  }\n  if (name.startsWith(\"__Secure-\")) {\n    return { ...options, secure: true };\n  }\n  return options;\n}\n\nexport function serializeMiddlewareCookie(\n  name: string,\n  value: string,\n  options: CookieOptions = {},\n): string {\n  const resolved = applyCookieNamePrefixRequirements(name, options);\n  let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n  if (resolved.maxAge != null) cookie += `; Max-Age=${resolved.maxAge}`;\n  if (resolved.expires) cookie += `; Expires=${resolved.expires.toUTCString()}`;\n  cookie += `; Path=${resolved.path || \"/\"}`;\n  if (resolved.domain) cookie += `; Domain=${resolved.domain}`;\n  if (resolved.secure) cookie += \"; Secure\";\n  if (resolved.httpOnly) cookie += \"; HttpOnly\";\n  if (resolved.sameSite) {\n    cookie += `; SameSite=${resolved.sameSite.charAt(0).toUpperCase()}${resolved.sameSite.slice(1)}`;\n  }\n\n  return cookie;\n}\n\n/**\n * Serialize the tombstone that removes a cookie. A deletion only matches the\n * stored cookie when its `Path` and `Domain` match the ones it was set with,\n * so callers must be able to pass them through.\n */\nexport function serializeMiddlewareCookieDeletion(\n  name: string,\n  options: CookieOptions = {},\n): string {\n  return serializeMiddlewareCookie(name, \"\", { ...options, maxAge: 0, expires: new Date(0) });\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 {\n  parseMiddlewareCookieHeader,\n  serializeMiddlewareCookie as serializeCookie,\n  serializeMiddlewareCookieDeletion,\n} from \"./cookie-header\";\n\n/**\n * Serialize a cookie\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, options: CookieOptions = {}): void {\n    delete this.cookies[name];\n    // Path and Domain must match the cookie that was set, or the tombstone\n    // addresses a different cookie and the original survives.\n    this.setCookies.push(serializeMiddlewareCookieDeletion(name, options));\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, ctx.url);\n      ctx.url = newUrl;\n      ctx.pathname = newUrl.pathname;\n      ctx.searchParams = newUrl.searchParams;\n      ctx.route = newUrl.pathname;\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","import { canonicalizeRequestPathname } from \"../utils/decode\";\nimport type { MiddlewareConfig, MiddlewareContext, MiddlewareMatcher } from \"./types\";\n\ninterface CompiledPathPattern {\n  kind: \"path\";\n  regex: RegExp;\n  params: string[];\n}\n\ninterface CompiledRegExpPattern {\n  kind: \"regexp\";\n  regex: RegExp;\n}\n\ninterface CompiledSubtreePattern {\n  kind: \"subtree\";\n  prefix: string;\n}\n\ninterface CompiledAllPattern {\n  kind: \"all\";\n}\n\ntype CompiledPattern =\n  | CompiledPathPattern\n  | CompiledRegExpPattern\n  | CompiledSubtreePattern\n  | CompiledAllPattern;\n\ntype CompiledMatcher = CompiledPattern | ((ctx: MiddlewareContext) => boolean);\n\nexport interface CompiledMiddlewareConfig {\n  matcher?: CompiledMatcher[];\n  exclude?: CompiledPattern[];\n}\n\ninterface CachedMiddlewareConfig {\n  compiled: CompiledMiddlewareConfig;\n  matcher: MiddlewareConfig[\"matcher\"];\n  matcherEntries?: MiddlewareMatcher[];\n  excludeEntries?: (string | RegExp)[];\n}\n\nconst compiledConfigCache = new WeakMap<MiddlewareConfig, CachedMiddlewareConfig>();\n\ninterface FileMiddlewareRoute {\n  path: string;\n}\n\nconst compiledRouteCache = new WeakMap<\n  FileMiddlewareRoute,\n  {\n    path: string;\n    exact: CompiledPattern;\n    nested: CompiledPattern;\n  }\n>();\n\n/** Internal file-route preparation shared by discovery and the production runner. */\nexport function compileMiddlewareRoute(entry: FileMiddlewareRoute) {\n  const path = entry.path;\n  if (path === \"/\") return undefined;\n  const cached = compiledRouteCache.get(entry);\n  if (cached?.path === path) return cached;\n  const compiled = {\n    path,\n    exact: compilePattern(path),\n    nested: compilePattern(`${path}/:__farmRest*`),\n  };\n  compiledRouteCache.set(entry, compiled);\n  return compiled;\n}\n\nexport function matchesMiddlewareRoute(\n  pathname: string,\n  entry: FileMiddlewareRoute,\n): { matched: boolean; params?: Record<string, string> } {\n  // Compare the live path so edits through getMiddlewares() remain observable.\n  // Weak ownership also releases old patterns when discovery/HMR replaces entries.\n  const compiled = compileMiddlewareRoute(entry);\n  if (!compiled) return { matched: true };\n  const canonicalPathname = canonicalizeRequestPathname(pathname);\n  const exactMatch = matchPattern(compiled.exact, canonicalPathname);\n  if (exactMatch.matched) return exactMatch;\n  const nestedMatch = matchPattern(compiled.nested, canonicalPathname);\n  if (!nestedMatch.matched) return { matched: false };\n  const params = { ...nestedMatch.params };\n  delete params.__farmRest;\n  return { matched: true, params: Object.keys(params).length > 0 ? params : undefined };\n}\n\nfunction sameEntries<T>(\n  current: readonly T[] | undefined,\n  previous: readonly T[] | undefined,\n): boolean {\n  return current === undefined || previous === undefined\n    ? current === previous\n    : current.length === previous.length &&\n        current.every((entry, index) => entry === previous[index]);\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): CompiledPathPattern {\n  const params: string[] = [];\n  const segments = pattern.split(\"/\").filter(Boolean);\n\n  if (segments.length === 0) {\n    return { kind: \"path\", 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    kind: \"path\",\n    regex: new RegExp(`^${parts.join(\"\")}$`),\n    params,\n  };\n}\n\nfunction compilePattern(pattern: string | RegExp): CompiledPattern {\n  if (pattern instanceof RegExp) {\n    return { kind: \"regexp\", regex: pattern };\n  }\n\n  if (pattern === \"*\" || pattern === \"/(.*)\") {\n    return { kind: \"all\" };\n  }\n\n  if (pattern.endsWith(\"(.*)\")) {\n    return {\n      kind: \"subtree\",\n      prefix: pattern.slice(0, -4).replace(/\\/$/, \"\"),\n    };\n  }\n\n  return compilePathPattern(pattern);\n}\n\nexport function compileMiddlewareConfig(config: MiddlewareConfig): CompiledMiddlewareConfig {\n  const compiled = {\n    matcher: config.matcher\n      ? toMatcherList(config.matcher).map((matcher) =>\n          typeof matcher === \"function\" ? matcher : compilePattern(matcher),\n        )\n      : undefined,\n    exclude: config.exclude?.map(compilePattern),\n  };\n  compiledConfigCache.set(config, {\n    compiled,\n    matcher: config.matcher,\n    matcherEntries: Array.isArray(config.matcher) ? config.matcher.slice() : undefined,\n    excludeEntries: config.exclude?.slice(),\n  });\n  return compiled;\n}\n\nfunction matchPattern(\n  pattern: CompiledPattern,\n  pathname: string,\n): { matched: boolean; params?: Record<string, string> } {\n  if (pattern.kind === \"all\") {\n    return { matched: true };\n  }\n\n  if (pattern.kind === \"subtree\") {\n    return {\n      matched: pathname === pattern.prefix || pathname.startsWith(`${pattern.prefix}/`),\n    };\n  }\n\n  pattern.regex.lastIndex = 0;\n  const match = pattern.regex.exec(pathname);\n  if (!match) {\n    return { matched: false };\n  }\n\n  if (pattern.kind === \"regexp\") {\n    return {\n      matched: true,\n      params: match.groups ? { ...match.groups } : undefined,\n    };\n  }\n\n  const values: Record<string, string> = {};\n  pattern.params.forEach((param, index) => {\n    // The captured text came out of the canonical pathname, so it is already\n    // decoded once. Decoding it again would turn a literal \"%2541BC\" segment\n    // into \"ABC\".\n    values[param] = match[index + 1] || \"\";\n  });\n\n  return {\n    matched: true,\n    params: Object.keys(values).length > 0 ? values : undefined,\n  };\n}\n\nexport function matchesCompiledMiddlewareConfig(\n  pathname: string,\n  config: CompiledMiddlewareConfig,\n  ctx: MiddlewareContext,\n): { matched: boolean; params?: Record<string, string> } {\n  let canonicalPathname: string | undefined;\n  // Canonicalize at most once for the whole config, and skip the work entirely\n  // for configs containing only function matchers.\n  const getCanonicalPathname = () => (canonicalPathname ??= canonicalizeRequestPathname(pathname));\n\n  if (config.exclude) {\n    for (const pattern of config.exclude) {\n      if (matchPattern(pattern, getCanonicalPathname()).matched) {\n        return { matched: false };\n      }\n    }\n  }\n\n  if (config.matcher) {\n    for (const matcher of config.matcher) {\n      if (typeof matcher === \"function\") {\n        if (matcher(ctx)) {\n          return { matched: true };\n        }\n        continue;\n      }\n\n      const result = matchPattern(matcher, getCanonicalPathname());\n      if (result.matched) {\n        return result;\n      }\n    }\n    return { matched: false };\n  }\n\n  return { matched: true };\n}\n\nexport function matchesMiddlewareConfig(\n  pathname: string,\n  config: MiddlewareConfig,\n  ctx: MiddlewareContext,\n): { matched: boolean; params?: Record<string, string> } {\n  const cached = compiledConfigCache.get(config);\n  const unchanged =\n    cached &&\n    (Array.isArray(config.matcher)\n      ? sameEntries(config.matcher, cached.matcherEntries)\n      : config.matcher === cached.matcher) &&\n    sameEntries(config.exclude, cached.excludeEntries);\n  const compiled = unchanged ? cached.compiled : compileMiddlewareConfig(config);\n  return matchesCompiledMiddlewareConfig(pathname, compiled, ctx);\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 { toFileModuleUrl } from \"../utils/file-module\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type {\n  FarmMiddlewareConfig,\n  MiddlewareFunction,\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 {\n  getFarmRedirectError,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n} from \"../navigation-errors\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\nimport { stripFarmBasePath } from \"../base-path\";\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\";\nimport {\n  compileMiddlewareConfig,\n  matchesMiddlewareConfig,\n  compileMiddlewareRoute,\n  matchesMiddlewareRoute,\n} from \"./matcher\";\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      compileMiddlewareConfig(middlewareConfig);\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        compileMiddlewareRoute(middleware);\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(\"/\").filter(Boolean).length;\n      const depthB = b.path.split(\"/\").filter(Boolean).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        module = await import(/* @vite-ignore */ toFileModuleUrl(filePath));\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      if (normalized.config) {\n        compileMiddlewareConfig(normalized.config);\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    // Match the app path page routing sees: without basePath (the locale step\n    // strips it too), as the production runner does.\n    const routePathname = this.i18n?.enabled\n      ? stripFarmLocaleFromPathname(pathname, this.i18n)\n      : stripFarmBasePath(pathname, this.i18n?.basePath ?? \"/\");\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: matchesMiddlewareRoute(routePathname, mw) }))\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        // redirect() and notFound() are control flow: the caller answers them.\n        emitFarmEvent(\n          isFarmRedirectError(error) || isFarmNotFoundError(error)\n            ? {\n                type: \"middleware.shortCircuit\",\n                ...middlewareEvent,\n                status: isFarmRedirectError(error) ? getFarmRedirectError(error)!.status : 404,\n              }\n            : { type: \"middleware.error\", ...middlewareEvent, 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    return matchesMiddlewareConfig(pathname, config, ctx);\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 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","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 { createRequire } from \"module\";\nimport { join, relative, dirname, extname } from \"path\";\nimport { initSync, parse } from \"es-module-lexer\";\nimport type { Loader } from \"esbuild\";\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 JSX_ROUTE_LOADERS: Record<string, Loader> = { \".jsx\": \"jsx\", \".tsx\": \"tsx\" };\nlet esbuildTransformSync: typeof import(\"esbuild\").transformSync | undefined;\n\n// Required on the first JSX route rather than imported, so loading core never\n// loads esbuild (which refuses to start in DOM-like test environments).\nfunction transformJSXRoute(content: string, loader: Loader, filePath: string): string {\n  esbuildTransformSync ??= (\n    createRequire(typeof __filename === \"string\" ? __filename : import.meta.url)(\n      \"esbuild\",\n    ) as typeof import(\"esbuild\")\n  ).transformSync;\n  return esbuildTransformSync(content, { loader, sourcefile: filePath }).code;\n}\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, filePath);\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, filePath: string): string[] {\n    if (!moduleLexerInitialized) {\n      initSync();\n      moduleLexerInitialized = true;\n    }\n    const httpMethods = [\"GET\", \"HEAD\", \"QUERY\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"];\n    // es-module-lexer cannot read JSX, so compile route.tsx/route.jsx first. The\n    // output is only lexed for export names, and type-only exports are erased.\n    const loader = JSX_ROUTE_LOADERS[extname(filePath)];\n    const source = loader ? transformJSXRoute(content, loader, filePath) : content;\n    const [, exports] = parse(source);\n    const valueExports = new Set(\n      exports\n        .filter((specifier) => !this.isTypeOnlyExportSpecifier(source, 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 createRouteTreeNode = () => Object.create(null) as Record<string, any>;\n    const nestedStructure = createRouteTreeNode();\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] = createRouteTreeNode();\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 (!Object.prototype.hasOwnProperty.call(current, part)) {\n              current[part] = createRouteTreeNode();\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  /**\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 type { FarmPlugin } from \"./plugin\";\nimport type { FarmSchemaField } from \"./schema\";\nimport { readSchemaTables } from \"./schema-tables\";\nimport { resolveSchemaModels } from \"./schema-sql\";\n\n/**\n * Render the `SyncModels` / `SyncModelInputs` declaration-merging block for the\n * generated `farm.d.ts`, from the schema the sync plugin declares.\n *\n * Only the sync plugin's declaration is browser-facing: other plugins declare\n * tables (Stripe's billing tables, for instance) purely so `farm <plugin>\n * migrate` can create them, and their rows must not surface as client types.\n *\n * Returns null when the app has no sync plugin, so apps without sync see no\n * new section and no churn in their generated file.\n */\nexport function createSyncModelTypeDeclarations(\n  plugins: readonly FarmPlugin[] | undefined,\n): string | null {\n  const rowEntries: string[] = [];\n  const insertEntries: string[] = [];\n\n  for (const plugin of plugins ?? []) {\n    const declaration = readSchemaTables(plugin);\n    if (!declaration || declaration.name !== \"sync\") continue;\n\n    const exposed = declaration.models ? new Set(declaration.models) : null;\n    const models = resolveSchemaModels(declaration.name, declaration.schema);\n\n    for (const [modelKey, model] of Object.entries(models)) {\n      if (exposed && !exposed.has(modelKey)) continue;\n      if (model.external) continue;\n      rowEntries.push(renderModelEntry(modelKey, model.fields, \"row\"));\n      insertEntries.push(renderModelEntry(modelKey, model.fields, \"insert\"));\n    }\n  }\n\n  if (rowEntries.length === 0) return null;\n\n  return `/**\n * Sync model types from the schema passed to sync() in farm.config.\n * useLiveQuery, useRow, and useSyncAction resolve model names and row\n * types against these maps. Regenerated when the schema changes.\n */\ndeclare module \"@farm.js/sync/client\" {\n  interface SyncModels {\n${rowEntries.join(\"\\n\")}\n  }\n\n  interface SyncModelInputs {\n${insertEntries.join(\"\\n\")}\n  }\n}`;\n}\n\nfunction renderModelEntry(\n  modelKey: string,\n  fields: Record<string, FarmSchemaField>,\n  shape: \"row\" | \"insert\",\n): string {\n  const lines = Object.entries(fields).map(([fieldKey, field]) => {\n    const nullable = field.nullable === true || field.required === false;\n    // Columns the engine or the database fills in: the key, defaults, the\n    // incremental cursor. An insert may always omit them.\n    const optional =\n      shape === \"insert\" &&\n      (nullable ||\n        field.primaryKey === true ||\n        field.default !== undefined ||\n        isCursorField(fieldKey, field));\n    const type = `${fieldTsType(field)}${nullable ? \" | null\" : \"\"}`;\n    return `      ${propertyName(fieldKey)}${optional ? \"?\" : \"\"}: ${type};`;\n  });\n  return `    ${propertyName(modelKey)}: {\\n${lines.join(\"\\n\")}\\n    };`;\n}\n\nfunction fieldTsType(field: FarmSchemaField): string {\n  const base = (() => {\n    switch (field.type) {\n      case \"boolean\":\n        return \"boolean\";\n      case \"integer\":\n      case \"number\":\n        return \"number\";\n      case \"json\":\n        return \"unknown\";\n      case \"enum\":\n        return field.values?.length\n          ? field.values.map((value) => JSON.stringify(value)).join(\" | \")\n          : \"string\";\n      // id, uuid, string, text, datetime all travel as strings over JSON.\n      default:\n        return \"string\";\n    }\n  })();\n  if (!field.list) return base;\n  return base.includes(\" \") ? `(${base})[]` : `${base}[]`;\n}\n\n/** Mirrors the sync runtime's cursor convention: a datetime `updatedAt`. */\nfunction isCursorField(fieldKey: string, field: FarmSchemaField): boolean {\n  return field.type === \"datetime\" && (fieldKey === \"updatedAt\" || field.name === \"updated_at\");\n}\n\nfunction propertyName(key: string): string {\n  return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);\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\";\nimport { createSyncModelTypeDeclarations } from \"./schema-model-types\";\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    const syncModelTypes = createSyncModelTypeDeclarations(options.plugins);\n    if (syncModelTypes) unifiedSections.push(syncModelTypes);\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  /** Dotted paths the renderer serves without a route file, such as a configured /llms.txt. */\n  generatedPaths: readonly string[] = [],\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    generatedPaths.includes(pathname),\n  );\n  return !matchesAppRoute || devServableFileExists(pathname, baseDirs);\n}\n\n/** Vite query flags that turn a file request into a module request. */\nconst VITE_MODULE_QUERY_FLAGS = [\n  \"import\",\n  \"raw\",\n  \"url\",\n  \"inline\",\n  \"worker\",\n  \"sharedworker\",\n] as const;\nconst SCRIPT_FETCH_DESTINATIONS = new Set([\"script\", \"worker\", \"sharedworker\", \"serviceworker\"]);\n\n/**\n * Whether a dev request is Vite loading a module, not a visitor or an agent\n * asking for a page. A `.md` file imported by app or dependency code (an\n * eager `import.meta.glob` over Markdown, for example) arrives as\n * `/README.md?import` from a module script; the Markdown mirror and its 404\n * must leave it to Vite, or the import fails and the page never hydrates.\n */\nexport function isViteModuleRequest(\n  url: URL,\n  headers: Record<string, string | string[] | undefined>,\n): boolean {\n  if (VITE_MODULE_QUERY_FLAGS.some((flag) => url.searchParams.has(flag))) return true;\n  const destination = headers[\"sec-fetch-dest\"];\n  const value = Array.isArray(destination) ? destination[0] : destination;\n  return value !== undefined && SCRIPT_FETCH_DESTINATIONS.has(value.toLowerCase());\n}\n\n/** Root files the docs engine answers that an app can serve itself. */\nconst DOCS_ENGINE_APP_OWNABLE_PATHS = new Set([\n  \"/llms.txt\",\n  \"/llms-full.txt\",\n  \"/sitemap.xml\",\n  \"/robots.txt\",\n]);\n\n/**\n * Whether the app serves one of the docs engine's root files itself:\n * /llms.txt or /llms-full.txt through `agent.llmsTxt` or an llms.ts or\n * llms-full.ts route, /sitemap.xml through sitemap.ts, /robots.txt through\n * robots.ts, or any of them through a file in the public dir. Development then\n * keeps the docs engine off that path, as production does, where platforms\n * serve public files before any route. Other files under the project root do\n * not count: production does not emit them.\n */\nexport function farmAppOwnsDocsEnginePath(\n  pathname: string,\n  options: {\n    generatedPaths: readonly string[];\n    routeManager?: DottedPathRouteMatcher | null;\n    publicDir: string | false | undefined;\n  },\n): boolean {\n  if (!DOCS_ENGINE_APP_OWNABLE_PATHS.has(pathname)) return false;\n  return (\n    options.generatedPaths.includes(pathname) ||\n    Boolean(options.routeManager?.matchMetadataRoute(pathname)) ||\n    devServableFileExists(pathname, [options.publicDir])\n  );\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","interface ImagePathPattern {\n  pathname?: string;\n}\n\n// Policy objects own the cache, not untrusted request paths. Weak keys allow\n// replaced configurations to be collected; checking pathname also supports\n// callers that pass mutable resolved configurations directly to the handler.\nconst compiledPatterns = new WeakMap<ImagePathPattern, { pathname: string; matcher: RegExp }>();\n\nexport function matchesImagePathPattern(value: string, pattern: ImagePathPattern): boolean {\n  const pathname = pattern.pathname ?? \"/**\";\n  let compiled = compiledPatterns.get(pattern);\n  if (!compiled || compiled.pathname !== pathname) {\n    const escaped = pathname.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n    // eslint-disable-next-line no-control-regex -- Internal sentinel for the existing ** glob grammar.\n    const source = escaped.replace(/\\*\\*/g, \"\\0\").replace(/\\*/g, \"[^/]*\").replace(/\\0/g, \".*\");\n    compiled = { pathname, matcher: new RegExp(`^${source}$`) };\n    compiledPatterns.set(pattern, compiled);\n  }\n  return compiled.matcher.test(value);\n}\n","import type {\n  FarmImageFormat,\n  FarmImageLocalPattern,\n  FarmImageRemotePattern,\n  ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { matchesFarmIfNoneMatch } from \"./server-http\";\nimport { matchesImagePathPattern } from \"./image-pattern\";\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  /** Adapter-owned origin for local asset fetches. Never derive this from request headers. @internal */\n  trustedLocalOrigin?: string | URL | (() => string | URL | undefined);\n  onError?: (error: unknown, request: Request) => void;\n  cacheEntries?: number;\n}\n\nexport interface FarmImageHandlerContext {\n  /** Adapter-owned origin for this request. Never derive this from request headers. @internal */\n  trustedLocalOrigin?: string | URL;\n}\n\nexport type FarmImageHandler = (\n  request: Request,\n  context?: FarmImageHandlerContext,\n) => 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, context): Promise<Response | null> {\n    const requestUrl = new URL(request.url);\n    if (requestUrl.pathname !== config.path) return null;\n\n    try {\n      const trustedLocalOrigin = resolveTrustedLocalOrigin(\n        context?.trustedLocalOrigin ?? options.trustedLocalOrigin,\n      );\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(\n        requestUrl,\n        trustedLocalOrigin,\n        config,\n        options.validateRemoteUrl,\n      );\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            trustedLocalOrigin,\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\n/**\n * Expand an IPv6 address into its eight 16-bit hextets, or null when the value\n * is not a parseable IPv6 address.\n *\n * Textual comparison is not enough for this boundary: the same address has many\n * spellings, and `new URL()` rewrites some of them. `::ffff:127.0.0.1` becomes\n * `::ffff:7f00:1`, and `::1` may arrive fully expanded, so every form has to be\n * reduced to numbers before any range check.\n */\nfunction parseIpv6Hextets(value: string): number[] | null {\n  // Drop any zone index (fe80::1%eth0); it does not affect the address.\n  let text = value.split(\"%\", 1)[0] ?? \"\";\n  if (!text.includes(\":\")) return null;\n\n  // A trailing dotted quad (::ffff:127.0.0.1) contributes the low two hextets.\n  let tail: number[] = [];\n  const lastColon = text.lastIndexOf(\":\");\n  const candidate = text.slice(lastColon + 1);\n  if (candidate.includes(\".\")) {\n    const octets = parseIpv4Octets(candidate);\n    if (!octets) return null;\n    tail = [(octets[0]! << 8) | octets[1]!, (octets[2]! << 8) | octets[3]!];\n    text = text.slice(0, lastColon);\n    // \"::1.2.3.4\" leaves \"::\" here, and \"1.2.3.4\" alone leaves \"\" — not IPv6.\n    if (text === \"\") return null;\n  }\n\n  const compressionParts = text.split(\"::\");\n  if (compressionParts.length > 2) return null;\n\n  const parseGroup = (group: string): number[] | null => {\n    if (group === \"\") return [];\n    const hextets: number[] = [];\n    for (const part of group.split(\":\")) {\n      if (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n      hextets.push(Number.parseInt(part, 16));\n    }\n    return hextets;\n  };\n\n  const head = parseGroup(compressionParts[0] ?? \"\");\n  const rest = parseGroup(compressionParts[1] ?? \"\");\n  if (!head || !rest) return null;\n\n  const explicit = [...head, ...rest, ...tail];\n  if (compressionParts.length === 1) {\n    return explicit.length === 8 ? explicit : null;\n  }\n\n  // \"::\" stands for at least one zero hextet.\n  if (explicit.length >= 8) return null;\n  const zeros = Array.from({ length: 8 - explicit.length }, () => 0);\n  return [...head, ...zeros, ...rest, ...tail];\n}\n\nfunction parseIpv4Octets(value: string): number[] | null {\n  const parts = value.split(\".\");\n  if (parts.length !== 4 || parts.some((part) => !/^\\d{1,3}$/.test(part))) return null;\n  const octets = parts.map(Number);\n  return octets.some((part) => part > 255) ? null : octets;\n}\n\nfunction isPrivateIpv4(octets: readonly number[]): boolean {\n  const [a, b] = octets as [number, number];\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\nexport function isPrivateImageAddress(address: string): boolean {\n  const value = address\n    .trim()\n    .toLowerCase()\n    .replace(/^\\[|\\]$/g, \"\");\n\n  const hextets = parseIpv6Hextets(value);\n  if (hextets) {\n    const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets as [\n      number,\n      number,\n      number,\n      number,\n      number,\n      number,\n      number,\n      number,\n    ];\n    const zeroPrefix = h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0;\n\n    // An address that embeds IPv4 is only as safe as that IPv4 address:\n    // IPv4-mapped (::ffff:0:0/96), IPv4-translated (::ffff:0:0:0/96), and the\n    // deprecated IPv4-compatible (::/96) forms all reach the v4 host.\n    const embedsIpv4 =\n      zeroPrefix &&\n      ((h4 === 0 && h5 === 0xffff) || (h4 === 0xffff && h5 === 0) || (h4 === 0 && h5 === 0));\n    if (embedsIpv4 && (h6 !== 0 || h7 !== 0)) {\n      return isPrivateIpv4([h6 >> 8, h6 & 0xff, h7 >> 8, h7 & 0xff]);\n    }\n\n    // Unspecified (::) and loopback (::1) in any spelling.\n    if (zeroPrefix && h4 === 0 && h5 === 0 && h6 === 0 && (h7 === 0 || h7 === 1)) return true;\n    // Unique-local fc00::/7, link-local fe80::/10, multicast ff00::/8.\n    if ((h0 & 0xfe00) === 0xfc00) return true;\n    if ((h0 & 0xffc0) === 0xfe80) return true;\n    if ((h0 & 0xff00) === 0xff00) return true;\n    return false;\n  }\n\n  const octets = parseIpv4Octets(value);\n  return octets ? isPrivateIpv4(octets) : false;\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  trustedLocalOrigin: string | undefined,\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(\"/\")\n      ? new URL(raw, trustedLocalOrigin ?? requestUrl.origin)\n      : new URL(raw);\n  } catch {\n    throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, \"Invalid image source URL\");\n  }\n\n  await validateImageSourceUrl(\n    sourceUrl,\n    requestUrl.origin,\n    trustedLocalOrigin,\n    config,\n    validateRemoteUrl,\n  );\n  return sourceUrl;\n}\n\nasync function validateImageSourceUrl(\n  sourceUrl: URL,\n  requestOrigin: string,\n  trustedLocalOrigin: string | undefined,\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  const isLocalSource =\n    sourceUrl.origin === requestOrigin || sourceUrl.origin === trustedLocalOrigin;\n  if (isLocalSource) {\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    if (sourceUrl.origin === trustedLocalOrigin) return;\n  } else 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  trustedLocalOrigin: string | undefined,\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 =\n      currentUrl.origin === trustedLocalOrigin ? 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(\n      currentUrl,\n      requestOrigin,\n      trustedLocalOrigin,\n      config,\n      validateRemoteUrl,\n    );\n  }\n}\n\nfunction resolveTrustedLocalOrigin(\n  configured: CreateFarmImageHandlerOptions[\"trustedLocalOrigin\"],\n): string | undefined {\n  const value = typeof configured === \"function\" ? configured() : configured;\n  if (!value) return undefined;\n\n  const url = new URL(value);\n  if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n    throw new TypeError(\"trustedLocalOrigin must use http or https\");\n  }\n  return url.origin;\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    matchesImagePathPattern(url.pathname, pattern) &&\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      matchesImagePathPattern(url.pathname, pattern) &&\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 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","/**\n * The client half of a docs runtime adapter, written into the generated client\n * entry. The adapter's React module is imported only on pages the docs server\n * rendered, which set `window.__FARM_DOCS_ADAPTER__`. An adapter can bundle\n * every docs page with it, so importing it statically would make every other\n * page of the app download all of them.\n */\nexport function generateFarmDocsAdapterClientRuntime(reactModule: string | undefined): string {\n  if (!reactModule) {\n    return `\nasync function hydrateFarmDocsAdapterRuntime() {\n  return false;\n}\n`;\n  }\n\n  return `\nasync function hydrateFarmDocsAdapterRuntime() {\n  const runtime = window.__FARM_DOCS_ADAPTER__;\n  if (!runtime) return false;\n  const FarmDocsAdapterReact = await import(${JSON.stringify(reactModule)});\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}\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 { 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","/**\n * What a hosting provider says about the current deployment, read from the\n * environment variables it sets. Production-site telemetry and\n * `agent.noindexPreviews` both read these, with opposite fallbacks: telemetry\n * treats a deployment it cannot classify as production, and noindexPreviews\n * treats it as not a preview. Either way an unknown setup keeps its default\n * behavior instead of being guessed at.\n *\n * Cloudflare Pages is deliberately absent: it exposes `CF_PAGES_BRANCH` for both\n * production and preview deployments and no environment flag that distinguishes\n * them, so there is nothing here that could be read without guessing. Its\n * preview URLs already carry `X-Robots-Tag: noindex`.\n */\n\ntype FarmDeploymentEnv = Readonly<Record<string, string | undefined>>;\n\n/**\n * Only a provider's production environment represents a production site;\n * preview, branch, and development deployments are not. A deployment whose\n * provider exposes no environment metadata counts as production, so self-hosted\n * sites keep reporting.\n */\nexport function isFarmProductionDeploymentEnvironment(\n  env: FarmDeploymentEnv = process.env,\n): boolean {\n  // Vercel exposes the deployment environment at build and runtime.\n  const environment = normalizeEnvironment(env.VERCEL_ENV);\n  const targetEnvironment = normalizeEnvironment(env.VERCEL_TARGET_ENV);\n  if (environment && environment !== \"production\") return false;\n  if (targetEnvironment && targetEnvironment !== \"production\") return false;\n\n  // Netlify: CONTEXT is production | deploy-preview | branch-deploy | dev.\n  // CONTEXT is a generic name, so it is only trusted when NETLIFY marks the\n  // build as Netlify's.\n  if (isTrue(env.NETLIFY)) {\n    const context = normalizeEnvironment(env.CONTEXT);\n    if (context && context !== \"production\") return false;\n  }\n\n  // Render marks pull-request preview services.\n  if (isTrue(env.IS_PULL_REQUEST)) return false;\n\n  return true;\n}\n\n/**\n * Whether the environment marks this as a preview deployment. `FARM_PREVIEW`\n * decides when set (`1`/`true` or `0`/`false`); otherwise a provider has to say\n * so explicitly:\n *\n * - Vercel: `VERCEL_ENV=preview`, which custom environments such as staging use too.\n * - Netlify: `CONTEXT=deploy-preview` or `branch-deploy`, with `NETLIFY` set.\n *   Netlify sets these at build time only.\n * - Render: `IS_PULL_REQUEST=true`.\n *\n * Local development is not a preview deployment.\n */\nexport function isFarmPreviewDeploymentEnvironment(env: FarmDeploymentEnv | undefined): boolean {\n  return resolveFarmPreviewDeployment(env, false);\n}\n\n/**\n * Preview status for a running server: the runtime environment, or the\n * environment it was built in. Netlify exposes its deploy context only to the\n * build, so the build's answer is carried into the server bundle. An explicit\n * `FARM_PREVIEW` at runtime still wins over the build.\n */\nexport function resolveFarmPreviewDeployment(\n  env: FarmDeploymentEnv | undefined,\n  builtAsPreview: boolean,\n): boolean {\n  const explicit = env?.FARM_PREVIEW;\n  if (isTrue(explicit)) return true;\n  if (isFalse(explicit)) return false;\n  if (builtAsPreview || !env) return builtAsPreview;\n\n  if (normalizeEnvironment(env.VERCEL_ENV) === \"preview\") return true;\n  if (isTrue(env.NETLIFY)) {\n    const context = normalizeEnvironment(env.CONTEXT);\n    if (context === \"deploy-preview\" || context === \"branch-deploy\") return true;\n  }\n  return isTrue(env.IS_PULL_REQUEST);\n}\n\nfunction normalizeEnvironment(value: string | undefined): string | undefined {\n  const normalized = value?.trim().toLowerCase();\n  return normalized || undefined;\n}\n\nfunction isTrue(value: string | undefined): boolean {\n  return value !== undefined && [\"1\", \"true\", \"yes\", \"on\"].includes(value.toLowerCase());\n}\n\nfunction isFalse(value: string | undefined): boolean {\n  return value !== undefined && [\"0\", \"false\", \"no\", \"off\"].includes(value.toLowerCase());\n}\n","/**\n * `agent.noindexPreviews`: keep preview deployments out of search indexes by\n * sending `X-Robots-Tag: noindex, nofollow` with every response Farm's server\n * produces there. Off by default. The development server and the generated\n * production server both use this module; preview detection lives in\n * `deployment-environment.ts`.\n */\n\n/** The header value `agent.noindexPreviews` sends on a preview deployment. */\nexport const FARM_PREVIEW_ROBOTS_TAG = \"noindex, nofollow\";\n\nexport function resolveFarmNoindexPreviews(input: unknown): boolean {\n  if (input === undefined) return false;\n  if (typeof input !== \"boolean\") {\n    throw new TypeError(\"agent.noindexPreviews must be a boolean.\");\n  }\n  return input;\n}\n\n/**\n * Mark a response as not indexable. Responses with immutable headers, such as\n * a proxied `fetch()` result, are copied first.\n */\nexport function applyFarmPreviewRobotsTag(response: Response): Response {\n  try {\n    response.headers.set(\"X-Robots-Tag\", FARM_PREVIEW_ROBOTS_TAG);\n    return response;\n  } catch {\n    const headers = new Headers(response.headers);\n    headers.set(\"X-Robots-Tag\", FARM_PREVIEW_ROBOTS_TAG);\n    return new Response(response.body, {\n      status: response.status,\n      statusText: response.statusText,\n      headers,\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  // Page and layout `metadata.jsonLd` (FARM_METADATA_ATTRIBUTE). The site-level\n  // agent JSON-LD and app-authored scripts carry no marker and stay in place.\n  'script[type=\"application/ld+json\"][data-farm-metadata]',\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 { farmAcceptQuality } from \"../markdown\";\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  html: string,\n): string {\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        getContext: 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  if (url.pathname.endsWith(\".md\")) return true;\n\n  const accept = request.headers.get(\"accept\");\n  // Substring matching cannot see `q=0`, so `text/markdown;q=0` (an explicit\n  // refusal) used to be served Markdown anyway. Only an exact entry counts:\n  // `*/*` means \"anything\", not \"Markdown over HTML\".\n  const markdown = Math.max(\n    farmAcceptQuality(accept, \"text/markdown\"),\n    farmAcceptQuality(accept, \"text/plain\"),\n  );\n  if (markdown <= 0) return false;\n\n  // A client listing text/plain as a low-quality fallback behind text/html\n  // wants the HTML page; serve Markdown only when it is at least as welcome.\n  return markdown >= farmAcceptQuality(accept, \"text/html\", { wildcards: true });\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-code-copy data-copied=\"false\" aria-label=\"Copy code\" title=\"Copy code\"><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 renderMarkdownDocument(\n  body: string,\n  depth: number,\n): { html: string; tocItems: TocItem[] } {\n  const slug = createSlugger();\n  const renderer = new Renderer();\n  const maxLevel = Math.max(2, Math.min(depth, 6));\n  const tocItems: TocItem[] = [];\n\n  renderer.heading = (text, level, raw) => {\n    const title = raw || stripHtml(text);\n    const id = slug(title);\n    if (level >= 2 && level <= maxLevel) {\n      tocItems.push({ id, title, level });\n    }\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: html.trim(), tocItems };\n}\n\ninterface TocItem {\n  id: string;\n  title: string;\n  level: number;\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))};const markCodeCopied=(button)=>{button.dataset.copied=\"true\";button.setAttribute(\"aria-label\",\"Copied\");button.title=\"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\",\"Copy code\");button.title=\"Copy code\";button.dataset.copyTimeout=\"0\"},4500))};document.addEventListener(\"click\",async(event)=>{const source=event.target instanceof Element?event.target:null;const codeButton=source?.closest(\"[data-code-copy]\");if(codeButton instanceof HTMLButtonElement){event.preventDefault();const code=codeButton.closest(\"figure\")?.querySelector(\"code\");if(!(code instanceof HTMLElement))return;const content=code.innerText||code.textContent||\"\";if(!content)return;await writeClipboard(content);markCodeCopied(codeButton);return}const target=source?.closest('[data-page-action=\"copy-markdown\"]');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  // Rendering and TOC extraction share the same preprocessed Marked pass. This\n  // guarantees MDX lines removed before rendering, Setext/CommonMark edge\n  // cases, and duplicate-slug counters cannot diverge between the article and\n  // its navigation.\n  const renderedMarkdown = renderMarkdownDocument(page.body, getThemeTocDepth(docs));\n  const tocItems = renderedMarkdown.tocItems;\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, renderedMarkdown.html)}\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 { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmLayoutFonts } from \"../font\";\nimport { resolveFarmDocsContentDir } from \"./handler\";\nimport type { FarmDocsCompiledManifest } from \"./precompiled-runtime\";\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\ninterface FarmDocsAdapterEdgeCompilerModule {\n  compileFarmDocsEdgeManifest?: (\n    config: Record<string, unknown>,\n    options: {\n      rootDir: string;\n      clientEntry: string;\n      stylesheets: string[];\n    },\n  ) => FarmDocsCompiledManifest | Promise<FarmDocsCompiledManifest>;\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 interface FarmDocsAdapterEdgeCompileOptions {\n  root: string;\n  srcDir?: string;\n  clientEntry: string;\n  fontStylesheetHref?: string;\n  globalStylesheetHref?: string;\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\nfunction createFarmDocsAdapterRuntimeConfig(\n  docs: FarmDocsResolvedConfig,\n  options: { root: string; srcDir?: string },\n): Record<string, unknown> {\n  return {\n    ...docs.config,\n    entry: docs.config.entry || docs.entry.replace(/^\\/+|\\/+$/g, \"\") || \"docs\",\n    docsPath: docs.entry,\n    contentDir: resolveFarmDocsContentDir(docs, options),\n  };\n}\n\nfunction getFarmDocsAdapterStylesheets(options: {\n  fontStylesheetHref?: string;\n  globalStylesheetHref?: string;\n}): string[] {\n  return [options.fontStylesheetHref, options.globalStylesheetHref].filter(\n    (value): value is string => typeof value === \"string\" && value.length > 0,\n  );\n}\n\nexport async function compileFarmDocsAdapterEdgeManifest(\n  docs: FarmDocsResolvedConfig,\n  options: FarmDocsAdapterEdgeCompileOptions,\n): Promise<FarmDocsCompiledManifest> {\n  if (!hasFarmDocsRuntimeAdapter(docs)) {\n    throw new Error(\"Farm docs adapter requires server and react runtime entrypoints.\");\n  }\n  const compilerEntry = docs.adapter.edgeCompiler;\n  if (!compilerEntry) {\n    throw new Error(\n      `Farm docs adapter ${JSON.stringify(docs.adapter.id)} does not declare the edge compiler required for this deployment.`,\n    );\n  }\n\n  const requireFromApp = createRequire(path.join(options.root, \"package.json\"));\n  let compilerPath: string;\n  try {\n    compilerPath = requireFromApp.resolve(compilerEntry);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(\n      `Farm docs adapter ${JSON.stringify(docs.adapter.id)} edge compiler ${JSON.stringify(compilerEntry)} could not be resolved from the application: ${message}`,\n    );\n  }\n\n  const compilerModule = (await import(\n    /* @vite-ignore */ pathToFileURL(compilerPath).href\n  )) as FarmDocsAdapterEdgeCompilerModule;\n  if (typeof compilerModule.compileFarmDocsEdgeManifest !== \"function\") {\n    throw new Error(\n      `Farm docs adapter ${JSON.stringify(docs.adapter.id)} does not export compileFarmDocsEdgeManifest from ${JSON.stringify(compilerEntry)}.`,\n    );\n  }\n\n  const manifest = await compilerModule.compileFarmDocsEdgeManifest(\n    createFarmDocsAdapterRuntimeConfig(docs, options),\n    {\n      rootDir: options.root,\n      clientEntry: options.clientEntry,\n      stylesheets: getFarmDocsAdapterStylesheets(options),\n    },\n  );\n  if (\n    !manifest ||\n    manifest.protocol !== 1 ||\n    !manifest.routes ||\n    typeof manifest.routes !== \"object\" ||\n    !manifest.api ||\n    typeof manifest.api !== \"object\"\n  ) {\n    throw new Error(\n      `Farm docs adapter ${JSON.stringify(docs.adapter.id)} returned an invalid edge manifest.`,\n    );\n  }\n  return manifest;\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 = createFarmDocsAdapterRuntimeConfig(docs, options);\n\n  return serverModule.createFarmDocsRuntimeHandler(runtimeConfig as Record<string, unknown>, {\n    rootDir: options.root,\n    clientEntry: options.clientEntry,\n    stylesheets: getFarmDocsAdapterStylesheets(options),\n    resolveLayoutFonts: options.resolveLayoutFonts,\n    loadReactModule: () => options.loadModule(docs.adapter.react!),\n  });\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmPlugin } from \"./plugin\";\nimport type { EndpointMCPMetadata, TypedEndpoint } from \"./api/endpoint\";\nimport type { RouteMethod } from \"./api/route\";\nimport type { RouteSchema, RouteSchemaInput, RouteSchemaOutput } from \"./api/route-schema\";\n\n/** A server-only endpoint reference. Config references must declare an explicit /api path. */\nexport type FarmMCPEndpoint = TypedEndpoint<any, any, any, any, any, any, any, any>;\n\nexport interface FarmMCPExecuteContext {\n  /** The principal returned by authorize, or { subject: \"anonymous\" } for public servers. */\n  readonly authorization: Readonly<FarmMCPAuthorization>;\n  readonly request: Request;\n  /** Observe this signal in cancellable work. Cancellation cannot undo side effects. */\n  readonly signal: AbortSignal;\n}\n\n/** A server-only tool with no corresponding HTTP endpoint. */\nexport interface FarmMCPStandaloneTool<\n  Schema extends RouteSchema = RouteSchema,\n  Result = unknown,\n  OutputSchema extends RouteSchema | undefined = undefined,\n> extends EndpointMCPMetadata {\n  name: string;\n  /** Must describe an object and support input JSON Schema conversion. */\n  inputSchema: Schema;\n  /** Validate/transform returned data and advertise its output shape inside MCP's result envelope. */\n  outputSchema?: OutputSchema;\n  /** Return JSON-serializable data, not a Response or an MCP protocol envelope. */\n  execute(\n    input: RouteSchemaOutput<Schema>,\n    context: FarmMCPExecuteContext,\n  ): OutputSchema extends RouteSchema\n    ? NoInfer<RouteSchemaInput<OutputSchema>> | Promise<NoInfer<RouteSchemaInput<OutputSchema>>>\n    : Result | Promise<Result>;\n  endpoint?: never;\n}\n\n/** Compose endpoint references and standalone tools. */\nexport type FarmMCPToolDefinition =\n  | FarmMCPEndpoint\n  | (EndpointMCPMetadata & { endpoint: FarmMCPEndpoint; execute?: never })\n  | FarmMCPStandaloneTool<any, unknown, any>;\n\n/** Resolved tool identity, without handlers, validators, or a way to bypass authorization. */\nexport type FarmMCPTool = Readonly<EndpointMCPMetadata> & {\n  readonly name: string;\n} & (\n    | { readonly kind: \"endpoint\"; readonly method: RouteMethod; readonly path: string }\n    | { readonly kind: \"standalone\"; readonly method?: never; readonly path?: never }\n  );\n\nexport interface FarmMCPServer {\n  readonly name: string;\n  readonly version: string;\n  readonly path: `/api/${string}`;\n}\n\nexport interface FarmMCPAuthorization extends Record<string, unknown> {\n  /** Stable application principal identifier. Never written to a response or log by Farm. */\n  subject: string;\n  scopes?: string[];\n  /** Allowed tool names for this request. Omit for all configured tools; [] denies all tools. */\n  tools?: readonly string[];\n}\n\nexport interface FarmMCPAuthorizeContext {\n  request: Request;\n  /** Untrusted requested name for a tools/call; authorization runs separately for every JSON-RPC batch item. */\n  tool?: string;\n  /** Complete configured catalog, before applying this caller's permissions. */\n  tools: readonly FarmMCPTool[];\n  /** Resolved transport identity, for policies shared by multiple MCP endpoints. */\n  server: FarmMCPServer;\n}\n\nexport interface FarmMCPConfig {\n  /** Set false to disable MCP without removing its configuration. @default true */\n  enabled?: boolean;\n  /** Canonical Farm API path for the Streamable HTTP endpoint. @default \"/api/mcp\" */\n  path?: `/api/${string}`;\n  /** MCP server identity. @default \"farm-api\" */\n  name?: string;\n  /** MCP server version. @default \"1.0.0\" */\n  version?: string;\n  /** Explicit endpoint/standalone tool allowlist. Omit to discover route-owned MCP metadata. */\n  tools?: readonly FarmMCPToolDefinition[];\n  /** Authorize every MCP request. Returning false responds with 401 before protocol handling. */\n  authorize?: (\n    context: FarmMCPAuthorizeContext,\n  ) => FarmMCPAuthorization | false | Promise<FarmMCPAuthorization | false>;\n  /** Deliberate escape hatch for public servers. Authentication is required by default. */\n  allowUnauthenticated?: boolean;\n}\n\nexport type FarmMCPUserConfig = FarmMCPConfig | false;\n\nexport interface ResolvedFarmMCPConfig extends FarmMCPConfig {\n  enabled: boolean;\n}\n\ninterface FarmMCPRuntimeModule {\n  createFarmMCPPlugin(config: FarmMCPConfig): FarmPlugin;\n}\n\nexport function resolveFarmMCPConfig(input: FarmMCPUserConfig | undefined): ResolvedFarmMCPConfig {\n  if (input === false || input === undefined) return { enabled: false };\n  if (!input || typeof input !== \"object\" || Array.isArray(input)) {\n    throw new TypeError(\"mcp must be a configuration object or false.\");\n  }\n  return { ...input, enabled: input.enabled !== false };\n}\n\nexport async function resolveFarmMCPPlugin(\n  config: ResolvedFarmMCPConfig,\n  options: { root: string },\n): Promise<FarmPlugin | 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/mcp/internal\");\n  } catch {\n    throw new Error(\n      \"The `mcp` config requires @farm.js/mcp. Install it with `pnpm add @farm.js/mcp` and try again.\",\n    );\n  }\n\n  const runtime = (await import(\n    /* @vite-ignore */ pathToFileURL(modulePath).href\n  )) as FarmMCPRuntimeModule;\n  if (typeof runtime.createFarmMCPPlugin !== \"function\") {\n    throw new Error(\n      \"The installed @farm.js/mcp package is incompatible with this version of @farm.js/core.\",\n    );\n  }\n  return runtime.createFarmMCPPlugin(config);\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 */\nimport {\n  resolveFarmAgentCrawlers,\n  type FarmAgentCrawlers,\n  type ResolvedFarmAgentCrawlers,\n} from \"./agent-crawlers\";\nimport {\n  resolveFarmLlmsTxtConfig,\n  type FarmLlmsTxtUserConfig,\n  type ResolvedFarmLlmsTxtConfig,\n} from \"./llms-txt\";\nimport { resolveFarmNoindexPreviews } from \"./preview-noindex\";\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   * On a preview deployment, send `X-Robots-Tag: noindex, nofollow` with every\n   * response from Farm's server. Previews are detected from `FARM_PREVIEW`,\n   * `VERCEL_ENV=preview`, Netlify's deploy-preview and branch-deploy contexts,\n   * and Render pull request previews. Production is unaffected.\n   *\n   * @default false\n   */\n  noindexPreviews?: boolean;\n  /**\n   * Serve `/llms.txt` (https://llmstxt.org): a Markdown index of the app's static\n   * pages, linking to their Markdown mirrors. `true` builds it from page metadata;\n   * an object sets the title, summary, details, and which routes to list. A\n   * `src/app/llms.ts` metadata route replaces the generated file.\n   *\n   * @default false\n   */\n  llmsTxt?: boolean | FarmLlmsTxtUserConfig;\n  /**\n   * Serve a generated `/robots.txt` that allows or blocks AI search agents\n   * (`search`) and AI training crawlers (`training`), plus your own `rules`.\n   * `true` serves only `User-agent: *` / `Allow: /` and the sitemap. A\n   * `public/robots.txt` or `src/app/robots.ts` replaces the generated file.\n   *\n   * @default false\n   */\n  crawlers?: boolean | FarmAgentCrawlers;\n}\n\nexport interface ResolvedFarmAgentConfig {\n  jsonLd: FarmAgentJsonLd | false;\n  noindexPreviews: boolean;\n  llmsTxt: ResolvedFarmLlmsTxtConfig;\n  crawlers: ResolvedFarmAgentCrawlers;\n}\n\nexport function resolveFarmAgentConfig(\n  input: FarmAgentUserConfig | undefined,\n): ResolvedFarmAgentConfig {\n  const jsonLd = input?.jsonLd;\n  return {\n    jsonLd: !jsonLd ? false : jsonLd === true ? {} : jsonLd,\n    noindexPreviews: resolveFarmNoindexPreviews(input?.noindexPreviews),\n    llmsTxt: resolveFarmLlmsTxtConfig(input?.llmsTxt),\n    crawlers: resolveFarmAgentCrawlers(input?.crawlers),\n  };\n}\n\n// Keep the existing internal imports compatible while browser metadata consumes\n// rendering directly, without pulling in crawler and preview configuration.\nexport { renderFarmAgentJsonLd, serializeJsonLd } from \"./agent-json-ld\";\nexport type { FarmAgentJsonLdContext } from \"./agent-json-ld\";\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 { FarmSchemaConfig } from \"./schema\";\nimport { assertPluginDependencies } from \"./plugin-dependencies\";\nimport 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 {\n  resolveFarmMCPConfig,\n  resolveFarmMCPPlugin,\n  type FarmMCPUserConfig,\n  type ResolvedFarmMCPConfig,\n} from \"./mcp-config\";\nimport { resolveFarmPerformanceConfig, type ResolvedFarmPerformanceConfig } from \"./preload\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  farmCspBlocksFrameworkInlineScripts,\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 type { OpenAPISecurityMode } from \"./openapi/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  FarmMCPAuthorization,\n  FarmMCPEndpoint,\n  FarmMCPToolDefinition,\n  FarmMCPStandaloneTool,\n  FarmMCPExecuteContext,\n  FarmMCPTool,\n  FarmMCPServer,\n  FarmMCPAuthorizeContext,\n  FarmMCPConfig,\n  FarmMCPUserConfig,\n  ResolvedFarmMCPConfig,\n} from \"./mcp-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  FarmRendererRuntime,\n  FarmRendererStreamingCapabilities,\n  FarmRendererStreamingPrimitives,\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  /** Default authentication requirement for operations without an endpoint override. */\n  security?: OpenAPISecurityMode;\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  /** Compose opted-in API routes and standalone tools through an authenticated MCP transport. */\n  mcp?: FarmMCPUserConfig;\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\n/** Validate the app's schema rules while the config loads. */\nfunction resolveSchemaConfig(config: FarmSchemaConfig | undefined): FarmSchemaConfig {\n  if (config === undefined) return {};\n  if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n    throw new TypeError(\"`schema` in farm.config must be an object.\");\n  }\n  for (const key of [\"allowExtend\", \"allowForeignKeys\"] as const) {\n    const entries = config[key];\n    if (entries === undefined) continue;\n    if (!entries || typeof entries !== \"object\" || Array.isArray(entries)) {\n      throw new TypeError(\n        `\\`schema.${key}\\` must map a plugin's migrate name to a list of model or table names.`,\n      );\n    }\n    for (const [owner, tables] of Object.entries(entries)) {\n      if (!Array.isArray(tables) || tables.some((table) => typeof table !== \"string\")) {\n        throw new TypeError(\n          `\\`schema.${key}.${owner}\\` must be a list of model or table names, such as [\"user\"].`,\n        );\n      }\n    }\n  }\n  return config;\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    | \"mcp\"\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  mcp: ResolvedFarmMCPConfig;\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    const value = env[key]?.trim().toLowerCase();\n    if (value === \"1\" || value === \"true\") 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  if (farmCspBlocksFrameworkInlineScripts(security)) {\n    logger.warn(\n      \"security.csp blocks the inline scripts Farm injects for theming and hydration. \" +\n        \"Set security.csp.nonce to true for managed dynamic nonces and prerendered hashes, \" +\n        \"or make the governing script directive allow 'unsafe-inline' without a nonce, \" +\n        \"hash, or 'strict-dynamic' source.\",\n    );\n  }\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  const mcp = resolveFarmMCPConfig(userConfig.mcp);\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 nativeMCPPlugin = await resolveFarmMCPPlugin(mcp, { root });\n  if (nativeMCPPlugin && userConfig.plugins?.some((plugin) => plugin?.name === \"farm:api-mcp\")) {\n    throw new Error(\n      \"Choose either the top-level `mcp` config or `apiMcp()` in `plugins`; they configure the same MCP transport.\",\n    );\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    ...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    schema: resolveSchemaConfig(userConfig.schema),\n    cache: userConfig.cache || {},\n    auth,\n    mcp,\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: [\n      ...resolveIntegrationPlugins(integrations),\n      ...(nativeMCPPlugin ? [nativeMCPPlugin] : []),\n      ...(userConfig.plugins || []),\n    ],\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  // Every plugin is known now, including those integrations contribute.\n  assertPluginDependencies(resolved.plugins, resolved.integrations as never);\n\n  return resolved;\n}\n\nfunction formatConfigLoadError(error: unknown): string {\n  if (error && (typeof error === \"object\" || typeof error === \"function\")) {\n    for (const property of [\"message\", \"stack\", \"name\"] as const) {\n      try {\n        const value = Reflect.get(error, property);\n        if (typeof value === \"string\" && value) return value;\n      } catch {\n        // Continue to the next diagnostic when an exotic getter throws.\n      }\n    }\n  }\n  try {\n    return String(error);\n  } catch {\n    return \"Unknown config loader error\";\n  }\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) {\n      const configError = new Error(\n        `Failed to load config from ${relativePath}: ${formatConfigLoadError(error)}`,\n      );\n      (configError as Error & { cause?: unknown }).cause = error;\n      throw configError;\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 { resolveApiReferenceOpenApiDiscovery } from \"@farming-labs/docs/server\";\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        getContext: 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: resolveApiReferenceOpenApiDiscovery(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        getContext: 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 type {\n  EndpointOpenAPIMetadata,\n  EndpointOpenAPIResponseMetadata,\n  OpenAPISecurityMode,\n} from \"./types\";\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\nexport interface OpenAPIGeneratorContext {\n  mode?: \"development\" | \"production\";\n  /** Resolved Farm `api.baseURL`, including its API path. */\n  apiBaseURL?: string;\n}\n\ntype AllowedType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\nconst allowedType = new Set([\"string\", \"number\", \"boolean\", \"array\", \"object\"]);\nconst zodTypeNameKinds: Record<string, string> = {\n  ZodArray: \"array\",\n  ZodBoolean: \"boolean\",\n  ZodDefault: \"default\",\n  ZodEnum: \"enum\",\n  ZodLiteral: \"literal\",\n  ZodNullable: \"nullable\",\n  ZodNumber: \"number\",\n  ZodObject: \"object\",\n  ZodOptional: \"optional\",\n  ZodRecord: \"record\",\n  ZodString: \"string\",\n  ZodTuple: \"tuple\",\n  ZodUnion: \"union\",\n};\n\nfunction getZodKind(schema: unknown): string | undefined {\n  if (!schema || typeof schema !== \"object\") return undefined;\n  const definition = (schema as any)._def;\n  if (!definition || typeof definition !== \"object\") return undefined;\n  if (typeof definition.type === \"string\") return definition.type;\n  return typeof definition.typeName === \"string\"\n    ? zodTypeNameKinds[definition.typeName]\n    : undefined;\n}\n\nfunction getZodObjectShape(schema: unknown): Record<string, unknown> | undefined {\n  if (getZodKind(schema) !== \"object\") return undefined;\n  const candidate = (schema as any).shape ?? (schema as any)._def?.shape;\n  const shape = typeof candidate === \"function\" ? candidate() : candidate;\n  return shape && typeof shape === \"object\" ? shape : undefined;\n}\n\nfunction isStandardSchema(schema: unknown): boolean {\n  return (\n    !!schema &&\n    typeof schema === \"object\" &&\n    typeof (schema as any)[\"~standard\"]?.validate === \"function\"\n  );\n}\n\n/**\n * OpenAPI `type` for a literal's value(s). A single-type literal keeps its JS\n * type; mixed-type literal sets fall back to string (the enum still carries the\n * exact values). bigint maps to integer.\n */\nfunction openAPITypeForLiteralValues(values: readonly unknown[]): AllowedType {\n  if (values.length === 0) return \"string\";\n  const jsType = typeof values[0];\n  if (!values.every((value) => typeof value === jsType)) return \"string\";\n  switch (jsType) {\n    case \"number\":\n      return \"number\";\n    case \"bigint\":\n      return \"number\";\n    case \"boolean\":\n      return \"boolean\";\n    default:\n      return \"string\";\n  }\n}\n\nexport class OpenAPIGenerator {\n  private config: OpenAPIConfig;\n  private appDir: string;\n  private context: OpenAPIGeneratorContext;\n\n  constructor(appDir: string, config: OpenAPIConfig, context: OpenAPIGeneratorContext = {}) {\n    this.appDir = appDir;\n    this.config = config;\n    this.context = context;\n  }\n\n  /**\n   * Get type from Zod type\n   */\n  private getTypeFromZodType(zodType: unknown): AllowedType {\n    const tag = getZodKind(zodType);\n    return typeof tag === \"string\" && allowedType.has(tag) ? (tag as AllowedType) : \"string\";\n  }\n\n  /**\n   * Whether a schema field must be supplied by the caller. A field with a\n   * default is supplied by the server when omitted, so — like an explicitly\n   * optional field — it is not required. Only ZodOptional was excluded before,\n   * which documented every `.default()` field as required.\n   */\n  private isRequiredField(value: unknown): boolean {\n    const kind = getZodKind(value);\n    return kind !== \"optional\" && kind !== \"default\";\n  }\n\n  /**\n   * Process Zod type to OpenAPI schema\n   */\n  private processZodType(zodType: unknown): any {\n    const kind = getZodKind(zodType);\n    const definition = (zodType as any)?._def;\n\n    if (!kind) {\n      return isStandardSchema(zodType)\n        ? { description: \"Schema metadata is unavailable for this Standard Schema validator.\" }\n        : { description: \"Schema metadata is unavailable.\" };\n    }\n\n    // Optionality controls whether a value must be supplied; it does not make\n    // JSON null valid for the wrapped schema.\n    if (kind === \"optional\") {\n      return this.processZodType(definition.innerType);\n    }\n\n    // Nullable schemas explicitly accept JSON null.\n    if (kind === \"nullable\") {\n      const innerType = definition.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 (kind === \"default\") {\n      return this.processZodType(definition.innerType);\n    }\n\n    // Handle ZodObject\n    if (kind === \"object\") {\n      const shape = getZodObjectShape(zodType);\n      if (shape) {\n        const properties: Record<string, any> = {};\n        const required: string[] = [];\n        Object.entries(shape).forEach(([key, value]) => {\n          if (getZodKind(value) || isStandardSchema(value)) {\n            properties[key] = this.processZodType(value);\n            if (this.isRequiredField(value)) {\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 (kind === \"array\") {\n      return {\n        type: \"array\",\n        items: this.processZodType(\n          definition.element ?? (typeof definition.type === \"object\" ? definition.type : undefined),\n        ),\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodEnum\n    if (kind === \"enum\") {\n      const options =\n        (zodType as any).options ??\n        (definition.entries ? Object.values(definition.entries) : definition.values);\n      return {\n        type: \"string\",\n        enum: options,\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodLiteral: emit the concrete value(s) as an enum rather than\n    // dropping the constraint and documenting a bare string.\n    if (kind === \"literal\") {\n      const values =\n        (definition.values as unknown[]) ??\n        (Object.prototype.hasOwnProperty.call(definition, \"value\") ? [definition.value] : []);\n      return {\n        type: openAPITypeForLiteralValues(values),\n        ...(values.length > 0 ? { enum: [...values] } : {}),\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodUnion (including discriminated unions): oneOf over the members.\n    if (kind === \"union\") {\n      const options = (definition.options as unknown[]) ?? [];\n      return {\n        oneOf: options.map((option) => this.processZodType(option)),\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodRecord: an object whose values share a schema.\n    if (kind === \"record\") {\n      return {\n        type: \"object\",\n        additionalProperties: this.processZodType(definition.valueType),\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodTuple: a fixed-length (unless variadic) array. OpenAPI 3.0 has no\n    // positional items, so the element schemas are unioned; the length is pinned\n    // when there is no rest element.\n    if (kind === \"tuple\") {\n      const items = (definition.items as unknown[]) ?? [];\n      const rest = definition.rest;\n      const itemSchemas = [...items, ...(rest ? [rest] : [])].map((item) =>\n        this.processZodType(item),\n      );\n      const tupleSchema: any = {\n        type: \"array\",\n        items: itemSchemas.length === 1 ? itemSchemas[0] : { oneOf: itemSchemas },\n        description: (zodType as any).description,\n      };\n      if (!rest) {\n        tupleSchema.minItems = items.length;\n        tupleSchema.maxItems = items.length;\n      }\n      return tupleSchema;\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 check of definition.checks ?? []) {\n      if (check?.kind === \"min\") {\n        constraints.push([kind === \"string\" ? \"minLength\" : \"minimum\", check.value]);\n      } else if (check?.kind === \"max\") {\n        constraints.push([kind === \"string\" ? \"maxLength\" : \"maximum\", check.value]);\n      }\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  private getResponses(metadata: EndpointOpenAPIMetadata): Record<string, any> {\n    const responses = Object.entries(metadata.responses ?? {}).filter(\n      (entry): entry is [string, EndpointOpenAPIResponseMetadata] => entry[1] !== undefined,\n    );\n    if (responses.length === 0) {\n      return {\n        default: {\n          description: \"Response metadata is unavailable.\",\n        },\n      };\n    }\n\n    return Object.fromEntries(\n      responses.map(([status, response]) => [status, this.getResponse(response)]),\n    );\n  }\n\n  private getResponse(response: EndpointOpenAPIResponseMetadata): Record<string, any> {\n    if (response.body === \"empty\") {\n      return {\n        description: response.description ?? \"Empty response\",\n      };\n    }\n\n    if (response.body === \"binary\") {\n      return {\n        description: response.description ?? \"Binary response\",\n        content: {\n          [response.contentType ?? \"application/octet-stream\"]: {\n            schema: { type: \"string\", format: \"binary\" },\n          },\n        },\n      };\n    }\n\n    const contentType =\n      response.body === \"json\"\n        ? (response.contentType ?? \"application/json\")\n        : response.contentType;\n    return {\n      description:\n        response.description ?? (response.body === \"json\" ? \"JSON response\" : \"Streaming response\"),\n      content: {\n        [contentType]: response.schema ? { schema: response.schema } : {},\n      },\n    };\n  }\n\n  /**\n   * Generate OpenAPI spec from API routes\n   */\n  async generateSpec(routes: APIRouteInfo[], requestOrigin?: string): 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.resolveServers(requestOrigin),\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      for (const variant of this.getOpenAPIPathVariants(path)) {\n        spec.paths[variant.path] ??= {};\n\n        for (const route of routeList) {\n          for (const method of route.methods) {\n            if (variant.operationIdSuffix === \"base\") {\n              const existingOperation =\n                method === \"QUERY\"\n                  ? spec.paths[variant.path][\"x-oai-additionalOperations\"]?.QUERY\n                  : spec.paths[variant.path][method.toLowerCase()];\n              if (existingOperation) continue;\n            }\n\n            const operation = await this.generateOperation(\n              route,\n              method,\n              variant.path,\n              variant.operationIdSuffix,\n            );\n            if (method === \"QUERY\") {\n              const additionalOperations =\n                spec.paths[variant.path][\"x-oai-additionalOperations\"] ?? {};\n              additionalOperations.QUERY = operation;\n              spec.paths[variant.path][\"x-oai-additionalOperations\"] = additionalOperations;\n            } else {\n              spec.paths[variant.path][method.toLowerCase()] = operation;\n            }\n          }\n        }\n      }\n    }\n\n    return spec;\n  }\n\n  /**\n   * Resolve server entries in decreasing order of authority: explicit OpenAPI\n   * servers, Farm's public API base, the current development request origin,\n   * and finally a mode-appropriate default.\n   */\n  resolveServers(requestOrigin?: string): NonNullable<OpenAPISpec[\"servers\"]> {\n    if (this.config.servers !== undefined) return this.config.servers;\n\n    const apiBaseURL = this.context.apiBaseURL || \"/api\";\n    if (/^https?:\\/\\//i.test(apiBaseURL)) {\n      return [{ url: apiBaseURL, description: \"Farm API server\" }];\n    }\n\n    if (requestOrigin) {\n      return [\n        {\n          url: new URL(apiBaseURL, `${requestOrigin.replace(/\\/$/, \"\")}/`).toString(),\n          description: \"Current development server\",\n        },\n      ];\n    }\n\n    if (this.context.mode === \"production\") {\n      return [{ url: apiBaseURL, description: \"Same-origin API server\" }];\n    }\n\n    return [\n      {\n        url: new URL(apiBaseURL, \"http://localhost:3000/\").toString(),\n        description: \"Development server\",\n      },\n    ];\n  }\n\n  /**\n   * Convert a Farm.js API path to OpenAPI path format.\n   *\n   * Strips the `/api` prefix and rewrites dynamic segments to OpenAPI's\n   * `{name}` templating: `[id]` -> `{id}`, `[...slug]` -> `{slug}`, and\n   * `[[...slug]]` -> `{slug}`. Leaving the bracket form produces a path key that\n   * is invalid OpenAPI, which breaks \"try it\" and any generated client.\n   */\n  private convertToOpenAPIPath(path: string): string {\n    const converted = path\n      .replace(/^\\/api/, \"\")\n      .replace(/\\[\\[\\.\\.\\.([^\\]]+)\\]\\]/g, \"{$1}\")\n      .replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \"{$1}\")\n      .replace(/\\[([^\\]]+)\\]/g, \"{$1}\");\n    return converted || \"/\";\n  }\n\n  /**\n   * OpenAPI does not permit optional path parameters. An optional catch-all\n   * therefore becomes two concrete paths: the empty base path and the\n   * parameterized catch-all path.\n   */\n  private getOpenAPIPathVariants(path: string): Array<{\n    path: string;\n    operationIdSuffix?: string;\n  }> {\n    if (!/\\/\\[\\[\\.\\.\\.[^\\]]+\\]\\]/.test(path)) {\n      return [{ path: this.convertToOpenAPIPath(path) }];\n    }\n\n    const basePath = path.replace(/\\/\\[\\[\\.\\.\\.[^\\]]+\\]\\]/g, \"\") || \"/api\";\n    return [\n      { path: this.convertToOpenAPIPath(basePath), operationIdSuffix: \"base\" },\n      { path: this.convertToOpenAPIPath(path) },\n    ];\n  }\n\n  /**\n   * Path parameters implied by a Farm.js API path's dynamic segments. Every\n   * path parameter is `required: true` per the OpenAPI spec (a path parameter\n   * cannot be optional), including catch-all segments.\n   */\n  private getPathParameters(openAPIPath: string): any[] {\n    return [...openAPIPath.matchAll(/\\{([^}]+)\\}/g)].map((match) => ({\n      name: match[1],\n      in: \"path\",\n      required: true,\n      schema: { type: \"string\" },\n    }));\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      const bodySchema = handler?.__types?.body ?? handler?._type?.body;\n      if (bodySchema) {\n        return {\n          required: this.isRequiredField(bodySchema),\n          content: {\n            \"application/json\": {\n              schema: this.processZodType(bodySchema),\n            },\n          },\n        };\n      }\n\n      return undefined;\n    } catch (error) {\n      // Missing metadata must not make the runtime contract stricter.\n      console.warn(`Could not extract schema from ${route.filePath}:`, error);\n      return {\n        required: false,\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              description: \"Request body\",\n            },\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      const querySchema = handler?.__types?.query ?? handler?._type?.query;\n      const shape = getZodObjectShape(querySchema);\n      if (shape) {\n        Object.entries(shape).forEach(([key, value]) => {\n          if (getZodKind(value) || isStandardSchema(value)) {\n            parameters.push({\n              name: key,\n              in: \"query\",\n              required: this.isRequiredField(value),\n              schema: this.processZodType(value),\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(\n    route: APIRouteInfo,\n    method: string,\n    openAPIPath = this.convertToOpenAPIPath(route.path),\n    operationIdSuffix?: string,\n  ): Promise<any> {\n    const metadata = await this.getEndpointOpenAPIMetadata(route, method);\n    const security = this.getSecurityRequirements(\n      metadata.security ?? this.config.security ?? \"public\",\n    );\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, operationIdSuffix),\n      tags: this.generateTags(route.path),\n      ...(security ? { security } : {}),\n      responses: this.getResponses(metadata),\n    };\n\n    // Path parameters (from dynamic route segments) precede query parameters.\n    const parameters = [\n      ...this.getPathParameters(openAPIPath),\n      ...(await this.getParameters(route, method)),\n    ];\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      const requestBody = await this.getRequestBody(route, method);\n      if (requestBody) {\n        operation.requestBody = requestBody;\n      }\n    }\n\n    return operation;\n  }\n\n  private async getEndpointOpenAPIMetadata(\n    route: APIRouteInfo,\n    method: string,\n  ): Promise<EndpointOpenAPIMetadata> {\n    try {\n      const routeModule = await import(/* @vite-ignore */ route.filePath);\n      return routeModule[method]?.__openapi ?? {};\n    } catch {\n      return {};\n    }\n  }\n\n  private getSecurityRequirements(mode: OpenAPISecurityMode): any[] | undefined {\n    if (mode === \"public\") return undefined;\n    if (mode === \"bearer\") return [{ bearerAuth: [] }];\n    if (mode === \"cookie\") return [{ apiKeyCookie: [] }];\n    return [{ bearerAuth: [] }, { apiKeyCookie: [] }];\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, suffix?: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\").replace(/\\//g, \"_\");\n    return `${method.toLowerCase()}_${cleanPath}${suffix ? `_${suffix}` : \"\"}`;\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","export const SCALAR_API_REFERENCE_VERSION = \"1.38.1\";\n\nconst SCALAR_CDN_BASE = `https://cdn.jsdelivr.net/npm/@scalar/api-reference@${SCALAR_API_REFERENCE_VERSION}`;\n\nexport const SCALAR_API_REFERENCE_SCRIPT = {\n  url: `${SCALAR_CDN_BASE}/dist/browser/standalone.js`,\n  integrity: \"sha384-87uSxO5SeoAG+4aLsnXHJWpb9Gx1biSeaI0O4O5z9OBFe7ZaEJ1LlvVGBo2CkcSO\",\n} as const;\n\nexport const SCALAR_API_REFERENCE_STYLES = {\n  url: `${SCALAR_CDN_BASE}/dist/style.css`,\n  integrity: \"sha384-D1NAbn/NwPaQ5LosRasICtufkVzdUvZZ4+PuXyFYOuR/AzPE0G5BOkXqju29Np+S\",\n} as const;\n","import { OpenAPIGenerator, type OpenAPIGeneratorContext, type OpenAPISpec } from \"./generator\";\nimport { APITypeGenerator } from \"../type-generator\";\nimport type { OpenAPIConfig } from \"../config\";\nimport { SCALAR_API_REFERENCE_SCRIPT } from \"./scalar-assets\";\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\n      src=\"${SCALAR_API_REFERENCE_SCRIPT.url}\"\n      integrity=\"${SCALAR_API_REFERENCE_SCRIPT.integrity}\"\n      crossorigin=\"anonymous\"\n    ></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(\n    appDir: string | readonly string[],\n    config: OpenAPIConfig,\n    context: OpenAPIGeneratorContext = {},\n  ) {\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, context);\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(requestOrigin?: string): Promise<any> {\n    const spec = this.specCache ?? (await this.generateSpec());\n    if (!requestOrigin || !spec) return spec;\n\n    return {\n      ...spec,\n      servers: this.generator.resolveServers(requestOrigin),\n    };\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(requestOrigin?: string) {\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(requestOrigin);\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  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      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      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      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      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      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      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      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      value: snapshot.integrations.length,\n      content: renderIntegrations(snapshot),\n    },\n    {\n      id: \"middleware\",\n      label: \"Middleware\",\n      description: \"Request layers and source modules\",\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      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      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      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      value: snapshot.cron.length,\n      content: renderCron(snapshot),\n    },\n    {\n      id: \"workflows\",\n      label: \"Workflows\",\n      description: \"Discovered workflow modules\",\n      value: snapshot.workflows.length,\n      content: renderWorkflows(snapshot),\n    },\n    {\n      id: \"features\",\n      label: \"Framework features\",\n      description: \"Resolved configuration switches\",\n      content: renderFeatureMatrix(snapshot),\n    },\n    {\n      id: \"environment\",\n      label: \"Environment\",\n      description: \"Validated key names only\",\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      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      content: renderJson(snapshot),\n    },\n    {\n      id: \"routes\",\n      label: \"Routes\",\n      description: \"Pages and route boundaries\",\n      value: snapshot.routes.length,\n      content: renderJson(snapshot.routes),\n    },\n    {\n      id: \"api\",\n      label: \"API\",\n      description: \"Typed server endpoints\",\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      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      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    .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-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    })();\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 type { IncomingMessage, ServerResponse } from \"node:http\";\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 {\n  createMarkdownMirrorResponse,\n  getFarmMarkdownAlternatePath,\n  getFarmMarkdownMirrorPath,\n  resolveMarkdownMirrorTarget,\n} from \"./markdown\";\nimport { resolveFarmLlmsTxtConfig } from \"./llms-txt\";\nimport { resolveFarmAgentCrawlers } from \"./agent-crawlers\";\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 {\n  farmAppOwnsDocsEnginePath,\n  isViteModuleRequest,\n  shouldBypassFarmRouterForDottedPath,\n} 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 { isFarmI18nCatalogFile, resolveFarmI18nMessagePath } from \"./i18n/config\";\nimport { getFarmI18nClientSnapshot } from \"./i18n/server\";\nimport { renderFarmLocaleAlternateLinks } from \"./i18n/alternates\";\nimport type { FarmI18nClientSnapshot } from \"./i18n/types\";\nimport {\n  createFarmClientOptimizeDepsConfig,\n  createFarmClientOptimizeDepsEntries,\n  createFarmSourceAlias,\n} from \"./server/vite-config\";\nimport { generateFarmDocsAdapterClientRuntime } from \"./docs/adapter-client\";\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  getFarmRendererCapabilities,\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 { addMetadataMarkdownAlternate, mergeMetadata } from \"./metadata\";\nimport { FARM_CONFIG_REWRITES_PLUGIN_NAME } from \"./plugins/rewrites\";\nimport { isFarmPreviewDeploymentEnvironment } from \"./deployment-environment\";\nimport { FARM_PREVIEW_ROBOTS_TAG } from \"./preview-noindex\";\nimport { resolveFarmRequestURL } from \"./server/request\";\nimport { reportOpenAPIDevGenerationResult } from \"./openapi/dev-status\";\n\n/** Paths `agent.llmsTxt` serves without a route file. */\nfunction farmLlmsTxtGeneratedPaths(config: { agent?: { llmsTxt?: unknown } }): string[] {\n  const llms = resolveFarmLlmsTxtConfig(config.agent?.llmsTxt as never);\n  if (!llms.enabled) return [];\n  return llms.full ? [\"/llms.txt\", \"/llms-full.txt\"] : [\"/llms.txt\"];\n}\n\n/** Paths `agent.llmsTxt` and `agent.crawlers` serve without a route file. */\nfunction farmAgentGeneratedPaths(config: {\n  agent?: { llmsTxt?: unknown; crawlers?: unknown };\n}): string[] {\n  const crawlers = resolveFarmAgentCrawlers(config.agent?.crawlers as never);\n  return [...farmLlmsTxtGeneratedPaths(config), ...(crawlers.enabled ? [\"/robots.txt\"] : [])];\n}\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\n/** Core entries whose runtime must never ship to the browser. */\nconst FARM_SERVER_ONLY_ENTRIES = new Set([\"@farm.js/core/og\"]);\n\n/**\n * Fail a browser graph that imports a server-only core entry, instead of\n * bundling its server runtime (for `@farm.js/core/og`, the `@vercel/og` wasm\n * renderer) into client code.\n */\nexport function farmServerOnlyEntriesPlugin(): Plugin {\n  return {\n    name: \"farm:server-only-entries\",\n    enforce: \"pre\",\n    resolveId(id, importer, options) {\n      if (options?.ssr || !FARM_SERVER_ONLY_ENTRIES.has(id)) return null;\n      this.error(\n        `${id} is server-only and cannot be imported into client code${\n          importer ? ` (imported by ${importer})` : \"\"\n        }. Use it from an API route or another server module.`,\n      );\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  // Pre-rendered without a request or route metadata, so there is no origin to\n  // resolve against and the hrefs stay paths.\n  return `${renderFarmLocaleAlternateLinks(requestPath, snapshot)}${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  resolveTraceUrl: (request: Connect.IncomingMessage) => URL = (request) =>\n    resolveFarmRequestURL(request as FarmRequest),\n): Connect.NextHandleFunction {\n  const middleware = _withAfterNodeMiddleware(handler);\n  return (req, res, next) => {\n    const traceUrl = resolveTraceUrl(req);\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\n/**\n * Whether Farm should append its own client-root HMR handler to a\n * `\"use client\"` module.\n *\n * Re-rendering the whole root on every edit only makes sense for a renderer\n * that diffs the result against the live DOM. Rebuilding renderers such as\n * Solid would otherwise wipe the page's state for a one-character edit. They\n * ship their own HMR integration, which can only preserve component state if\n * Farm leaves the module unaccepted.\n */\nexport function shouldEmitFarmClientRootHmr(renderer?: FarmRenderer): boolean {\n  return getFarmRendererCapabilities(resolveFarmRenderer(renderer)).reconcilesRerenders;\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      // agent.noindexPreviews marks every dev response, Vite's own included, when\n      // the environment says this is a preview (`FARM_PREVIEW=1 farm dev`).\n      if (farmConfig.agent?.noindexPreviews) {\n        server.middlewares.use((_req, res, next) => {\n          if (isFarmPreviewDeploymentEnvironment(process.env)) {\n            res.setHeader(\"X-Robots-Tag\", FARM_PREVIEW_ROBOTS_TAG);\n          }\n          next();\n        });\n      }\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          // Vite owns this address. Unlike request.url, it cannot be replaced by\n          // a caller-controlled Host header.\n          trustedLocalOrigin: () => server.resolvedUrls?.local[0],\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.locales.map((locale) =>\n            resolveFarmI18nMessagePath(farmConfig.i18n, locale),\n          ),\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) => isFarmI18nCatalogFile(farmConfig.i18n, file);\n      let typeArtifactGenScheduled: ReturnType<typeof setTimeout> | null = null;\n      let pendingTypeArtifacts = createEmptyTypeArtifactSelection();\n      let pendingTypeArtifactReason = \"\";\n      let routeRefreshScheduled: ReturnType<typeof setTimeout> | null = null;\n      let pendingRouteRefreshIncludesMiddleware = false;\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          const isRouteRefreshEvent =\n            (ev !== \"change\" || isStaticMetadataImageFile(file)) &&\n            (isAppRuntimeFile(file) ||\n              isProgrammaticRouteFile(file) ||\n              (isProgrammaticRouteSourceFile(file) &&\n                (ev === \"unlink\" || fileContainsProgrammaticPageRoute(file))));\n          if (isRouteRefreshEvent) {\n            if (file.includes(\"middleware.\")) {\n              pendingRouteRefreshIncludesMiddleware = true;\n            }\n            if (!routeRefreshScheduled) {\n              routeRefreshScheduled = setTimeout(() => {\n                routeRefreshScheduled = null;\n                const reloadsMiddleware = pendingRouteRefreshIncludesMiddleware;\n                pendingRouteRefreshIncludesMiddleware = false;\n                Promise.all([\n                  refreshRouteDiscovery?.(`${ev} ${file}`),\n                  reloadsMiddleware ? 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\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          mode: \"development\",\n          apiBaseURL: typeof options.api?.baseURL === \"string\" ? options.api.baseURL : undefined,\n        });\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        // The app's layouts are authored for whichever renderer it selected, so\n        // they have to be composed and rendered through that renderer's server\n        // module. The production entry already resolves this the same way\n        // (nitro/universal-build.ts, rendererServerImports); importing react\n        // and react-dom/server literally here made dev disagree with prod for\n        // every non-React app.\n        const docsRenderer = resolveFarmRenderer((farmApp?.getConfig() ?? options).renderer);\n        const [rendererRuntime, layoutModules] = await Promise.all([\n          isReactRenderer(docsRenderer)\n            ? import(\"./renderer/react/server\")\n            : server.ssrLoadModule(docsRenderer.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 = rendererRuntime.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 = rendererRuntime.createElement(LayoutComponent, {\n              children: wrappedElement,\n              params,\n            });\n          }\n        }\n\n        const rootMarkup = await rendererRuntime.renderToString(\n          rendererRuntime.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(\n          handler,\n          {\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          (request) => {\n            const currentConfig = farmApp?.getConfig() ?? options;\n            const currentServerConfig = resolveFarmServerConfig(currentConfig.server);\n            return resolveFarmRequestURL(request as FarmRequest, {\n              trustProxy: currentServerConfig.trustProxy,\n            });\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          // The OpenAPI spec and reference, docs, raw markdown-source, the\n          // markdown mirror, and the Markdown 404 fallback expose page content\n          // or route-existence, so app middleware must pass before they are\n          // sent — matching the production entry, where these handlers run\n          // 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 runFarmMiddlewareWithNavigation(\n              farmApp.getServerRenderer(),\n              middlewareRequest,\n              req,\n              res,\n              () => middlewareManager!.execute(req, res),\n            );\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 (await runAppMiddlewareForContentRoute()) return;\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(parsedRequestUrl.origin);\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            if (await runAppMiddlewareForContentRoute()) return;\n            const docsHandler = openAPIManager.getDocsRouteHandler(parsedRequestUrl.origin);\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          // Vite loading a `.md` file as a module is not a request for docs or Markdown.\n          const viteModuleRequest = isViteModuleRequest(parsedRequestUrl, req.headers);\n          // An app's own llms.txt, llms-full.txt, sitemap.xml, and robots.txt (agent.llmsTxt,\n          // agent.crawlers, a root llms.ts, llms-full.ts, sitemap.ts, or robots.ts, or a public\n          // file) take those paths from the docs engine, as in production.\n          const appOwnsDocsEnginePath = farmAppOwnsDocsEnginePath(requestPathname, {\n            generatedPaths: farmAgentGeneratedPaths(farmConfig),\n            routeManager: farmApp.getRouteManager(),\n            publicDir: server.config.publicDir,\n          });\n          if (farmDocsHandler && !appOwnsDocsEnginePath && !viteModuleRequest) {\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 = viteModuleRequest\n            ? null\n            : 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 = viteModuleRequest\n            ? null\n            : 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 (!viteModuleRequest && farmRequestWantsMarkdown(requestPathname, req.headers.accept)) {\n            const markdownRoute = farmApp\n              .getRouteManager()\n              .matchRoute(normalizeFarmMarkdownRoutePath(requestPathname));\n            if (!markdownRoute.route) {\n              if (await runAppMiddlewareForContentRoute()) return;\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 = getFarmMarkdownMirrorPath(markdownPageTarget.pathname);\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                signal: createFarmNodeRequestAbortSignal(req, res),\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                signal: createFarmNodeRequestAbortSignal(req, res),\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 = resolveFarmRequestURL(req as FarmRequest, {\n              trustProxy: currentServerConfig.trustProxy,\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                // Like production, the handler can see the client go away.\n                const request = new Request(url, {\n                  method: req.method,\n                  headers,\n                  body: toRequestBody(body),\n                  signal: createFarmNodeRequestAbortSignal(req, res),\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                  signal: createFarmNodeRequestAbortSignal(req, res),\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(\n              requestPathname,\n              farmApp?.getRouteManager(),\n              [server.config.publicDir, server.config.root],\n              farmAgentGeneratedPaths(farmConfig),\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                // 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\n                // Collect metadata exactly the way a full-page load does:\n                // static and generated interleaved per layer, deep-merged with\n                // mergeMetadata so a page's openGraph extends a layout's\n                // instead of replacing it. Layouts receive the params,\n                // the route receives its full resolved props.\n                for (const layoutModule of layoutModules) {\n                  mergedMetadata = mergeMetadata(mergedMetadata, (layoutModule as any).metadata);\n                  if (typeof (layoutModule as any).generateMetadata === \"function\") {\n                    mergedMetadata = mergeMetadata(\n                      mergedMetadata,\n                      await (layoutModule as any).generateMetadata({ params: routeProps.params }),\n                    );\n                  }\n                }\n                mergedMetadata = mergeMetadata(mergedMetadata, (routeModule as any).metadata);\n                if (typeof (routeModule as any).generateMetadata === \"function\") {\n                  mergedMetadata = mergeMetadata(\n                    mergedMetadata,\n                    await (routeModule as any).generateMetadata(routeProps),\n                  );\n                }\n                mergedMetadata = addMetadataMarkdownAlternate(\n                  mergedMetadata,\n                  getFarmMarkdownAlternatePath(farmApp.getConfig().md, targetRequestUrl.pathname),\n                );\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                  // The full merged metadata, not a title/description\n                  // projection: client navigation reconciles the same head\n                  // tags a full-page load renders, so it needs the same input.\n                  metadata: mergedMetadata,\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 requestedPathname = resolveFarmRequestURL(req as FarmRequest, {\n            trustProxy: currentServerConfig.trustProxy,\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          // `runtime.before` may return a replacement Request, and the page has\n          // to be routed on whatever the session yields: that is what\n          // `runRuntimeRequest` does in the production entry, where the routed\n          // request is the session's. So the session opens before the route is\n          // resolved. The session options still describe the requested route,\n          // because production computes them from the incoming request too.\n          const requestedMatch = routeManager.matchRoute(requestedPathname);\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: requestedPathname,\n                    pattern: requestedMatch?.route?.pattern || null,\n                    params: requestedMatch?.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: requestedPathname });\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          // A replacement request is matched on its own pathname, including when\n          // it matches nothing and has to 404 on the rewritten path. An ordinary\n          // request is not re-matched, so the common path still matches once.\n          const pathname = runtimeSession\n            ? new URL(runtimeSession.request.url).pathname\n            : requestedPathname;\n          const routeMatch =\n            pathname === requestedPathname ? requestedMatch : routeManager.matchRoute(pathname);\n\n          if (pm && hasBeforeRouteMatchHook) {\n            await pm.runHookParallel(\"beforeRouteMatch\", {\n              pathname,\n              method,\n            });\n          }\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\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 runFarmMiddlewareWithNavigation(\n                farmApp.getServerRenderer(),\n                middlewareRequest,\n                req,\n                res,\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            (isReactRenderer(renderer) &&\n              (\n                options.isolatedClientBoundaryModules ??\n                farmApp?.getRouteManager().getIsolatedClientBoundaryModules(root)\n              )?.size > 0),\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        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        // The plan selects a boundary when the experiment is enabled or when an\n        // async server page or layout renders it (those islands do not depend\n        // on the experiment).\n        const selectedForIsolatedHydration =\n          selectedIsolatedModules?.has(path.resolve(cleanId)) === true;\n        if (\n          isReactRenderer(resolveFarmRenderer(currentConfig.renderer)) &&\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        // Re-rendering the whole root on every edit only makes sense for a\n        // renderer that diffs the result against the live DOM. On Solid and\n        // Svelte `render()` tears the tree down and rebuilds it, so a one\n        // character change in any client component would wipe the page's\n        // state. Those renderers ship their own HMR integration (solid-refresh\n        // and svelte's hot API) which preserves component state, so leave the\n        // module for them to accept: appending our own `import.meta.hot.accept`\n        // here would swallow the update instead of letting theirs run.\n        const hmrCode = !shouldEmitFarmClientRootHmr(currentConfig.renderer)\n          ? \"\"\n          : `\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      const planRouteManager = farmApp?.getRouteManager();\n      const isHydrationPlanSource =\n        currentSrcRoot !== null &&\n        normalizedFile.startsWith(`${currentSrcRoot}/`) &&\n        /\\.[cm]?[jt]sx?$/.test(normalizedFile);\n      // Any source module can become an async owner's client boundary. Replan\n      // React source updates even when the previous plan had no islands, but\n      // keep CSS, generated output and files outside src off this static pass.\n      const tracksAsyncOwnerIslands =\n        isReactRenderer(currentFarmConfig?.renderer) && planRouteManager !== undefined;\n      if (\n        isHydrationPlanSource &&\n        (isolatedHydrationMode === \"enabled\" ||\n          isolatedHydrationMode === \"analyze\" ||\n          tracksAsyncOwnerIslands)\n      ) {\n        const routeManager = planRouteManager;\n        if (routeManager) {\n          try {\n            const previousPlan = JSON.stringify(\n              routeManager.generateClientManifest(currentFarmConfig.root),\n            );\n            const previousBoundaries = new Set(\n              routeManager.getIsolatedClientBoundaryModules(currentFarmConfig.root),\n            );\n            const nextPlan = JSON.stringify(\n              routeManager.regenerateClientManifest(currentFarmConfig.root),\n            );\n            const nextBoundaries = routeManager.getIsolatedClientBoundaryModules(\n              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              // A component that gained or lost island ownership needs a fresh transform.\n              for (const boundary of new Set([...previousBoundaries, ...nextBoundaries])) {\n                if (previousBoundaries.has(boundary) === nextBoundaries.has(boundary)) continue;\n                // The plan resolves platform paths; Vite keys files by POSIX paths.\n                for (const mod of server.moduleGraph.getModulesByFile(toPosixPath(boundary)) ??\n                  []) {\n                  server.moduleGraph.invalidateModule(mod);\n                }\n              }\n              // The client entry includes the island runtime only when a plan needs it.\n              for (const clientId of [\"/@farm/client\", \"/@farm/client.js\"]) {\n                const clientModule = server.moduleGraph.getModuleById(clientId);\n                if (clientModule) server.moduleGraph.invalidateModule(clientModule);\n              }\n              server.ws.send({ type: \"full-reload\", path: \"*\" });\n              return [];\n            }\n          } catch (error) {\n            logger.warn(\n              `[Farm.js] Could not refresh the client hydration plan after ${file}: ${error instanceof Error ? error.message : String(error)}`,\n            );\n            // regenerateClientManifest() restored the last usable plan. Do not\n            // fall through to the generic app-module invalidation below, which\n            // would discard that plan while the edited source is still invalid.\n            return modules;\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\n/**\n * Run app middleware so that redirect() and notFound() answer the request (a\n * redirect, or the app's not-found page) instead of failing it with a 500,\n * matching the production middleware runner.\n */\nfunction runFarmMiddlewareWithNavigation(\n  renderer: ReturnType<FarmApp[\"getServerRenderer\"]>,\n  middlewareRequest: Request,\n  req: IncomingMessage,\n  res: ServerResponse,\n  execute: () => Promise<boolean>,\n): Promise<boolean> {\n  return renderer.runWithRequestContext(middlewareRequest, async () => {\n    try {\n      return await execute();\n    } catch (error) {\n      if (await renderer.respondToNavigationError(req as any, res as any, error)) return true;\n      throw error;\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(\n    integrationProviders,\n    root,\n    renderer.componentExtensions ?? [],\n  );\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, createFarmServerPageBoundary, wrapFarmIsolatedClientGraph } from '@farm.js/core/internal/isolated-boundary'`\n    : \"\";\n  const docsAdapterImportBlock = generateFarmDocsAdapterClientRuntime(docsAdapterReact);\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// A hydrating layout keeps a non-hydrating page as server HTML; this wrapper runs its islands.\nconst FarmServerPage = createFarmServerPageBoundary(React, 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 { replayFarmQueuedInteraction, 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\nfunction wrapFarmClientRouteGraph(element) {\n  const wrapped = wrapWithIntegrationProviders(element);\n  ${isolatedHydrationEnabled ? \"return wrapFarmIsolatedClientGraph(React, wrapped);\" : \"return wrapped;\"}\n}\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.prefetchObserver = null;\n    this.observedPrefetchLinks = new Map();\n    this.prefetchTimers = new Map();\n    this.viewportPrefetchQueue = [];\n    this.viewportPrefetchTasksByHref = new Map();\n    this.viewportPrefetchTasksByElement = new Map();\n    this.activeViewportPrefetches = 0;\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    this.unobserveForPrefetch(element);\n    const observer = this.getPrefetchObserver();\n    this.observedPrefetchLinks.set(element, href);\n    observer.observe(element);\n  }\n\n  unobserveForPrefetch(element) {\n    if (this.observedPrefetchLinks.delete(element)) {\n      this.prefetchObserver?.unobserve(element);\n    }\n    const timer = this.prefetchTimers.get(element);\n    if (timer !== undefined) {\n      clearTimeout(timer);\n      this.prefetchTimers.delete(element);\n    }\n    this.cancelViewportPrefetch(element);\n  }\n\n  getPrefetchObserver() {\n    if (this.prefetchObserver) return this.prefetchObserver;\n    this.prefetchObserver = new IntersectionObserver((entries) => {\n      for (const entry of entries) {\n        if (!entry.isIntersecting) continue;\n        const element = entry.target;\n        const href = this.observedPrefetchLinks.get(element);\n        if (!href) continue;\n        this.prefetchObserver.unobserve(element);\n        this.observedPrefetchLinks.delete(element);\n        const timer = setTimeout(() => {\n          if (this.prefetchTimers.get(element) !== timer) return;\n          this.prefetchTimers.delete(element);\n          this.enqueueViewportPrefetch(element, href);\n        }, 100);\n        this.prefetchTimers.set(element, timer);\n      }\n    }, { rootMargin: '200px' });\n    return this.prefetchObserver;\n  }\n\n  enqueueViewportPrefetch(element, href) {\n    let task = this.viewportPrefetchTasksByHref.get(href);\n    if (!task) {\n      task = { href, elements: new Set(), cancelled: false, started: false };\n      this.viewportPrefetchTasksByHref.set(href, task);\n      this.viewportPrefetchQueue.push(task);\n    }\n    task.elements.add(element);\n    this.viewportPrefetchTasksByElement.set(element, task);\n    this.drainViewportPrefetchQueue();\n  }\n\n  cancelViewportPrefetch(element) {\n    const task = this.viewportPrefetchTasksByElement.get(element);\n    if (!task) return;\n    this.viewportPrefetchTasksByElement.delete(element);\n    task.elements.delete(element);\n    if (task.elements.size > 0) return;\n    if (task.started) return;\n    task.cancelled = true;\n    if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n      this.viewportPrefetchTasksByHref.delete(task.href);\n    }\n  }\n\n  drainViewportPrefetchQueue() {\n    while (this.activeViewportPrefetches < 4 && this.viewportPrefetchQueue.length > 0) {\n      const task = this.viewportPrefetchQueue.shift();\n      if (task.cancelled || task.elements.size === 0) {\n        if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n          this.viewportPrefetchTasksByHref.delete(task.href);\n        }\n        continue;\n      }\n      task.started = true;\n      this.activeViewportPrefetches += 1;\n      let prefetchResult;\n      try {\n        prefetchResult = this.prefetch(task.href);\n      } catch {\n        prefetchResult = undefined;\n      }\n      Promise.resolve(prefetchResult)\n        .catch(() => undefined)\n        .finally(() => {\n          if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n            this.viewportPrefetchTasksByHref.delete(task.href);\n          }\n          for (const element of task.elements) {\n            if (this.viewportPrefetchTasksByElement.get(element) === task) {\n              this.viewportPrefetchTasksByElement.delete(element);\n            }\n          }\n          this.activeViewportPrefetches -= 1;\n          this.drainViewportPrefetchQueue();\n        });\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  // Vite awaits a promise returned from dispose before evaluating the new\n  // module, so the old runtime is fully closed before its successor starts.\n  // The router is destroyed afterwards — plugins may still touch navigation\n  // during close — and unconditionally, or every entry reload would leave\n  // another popstate/beforeunload listener behind.\n  import.meta.hot.dispose(async () => {\n    try {\n      await farmClientRuntime.close('hmr');\n    } finally {\n      spaRouter.destroy();\n    }\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 instanceof Element) || target.isConnected === false) continue;\n    // A held submit is replayed as a submit; click() on a form does nothing.\n    setTimeout(() => replayFarmQueuedInteraction(target, queuedClick.kind), 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 wrapFarmClientRouteGraph(wrappedTree);\n}\n\nfunction hydrateFarmRoute(container, route) {\n  ${\n    isReactRenderer(renderer)\n      ? \"return hydrateRoot(container, route.element);\"\n      : \"return route.layouts.length > 0 ? hydrateRoot(container, route.element, route) : hydrateRoot(container, route.element);\"\n  }\n}\n\nfunction renderFarmRoute(root, route) {\n  if (route?.layouts?.length > 0 && typeof root.renderRoute === 'function') {\n    root.renderRoute(route);\n  } else {\n    root.render(route.element);\n  }\n}\n\nfunction createLayoutPageBoundary(\n  pageShouldHydrate,\n  islandStrategy,\n  pageElement,\n  serverHtml,\n) {\n  const props = {\n    id: '__farm_page__',\n    // Same attributes as the server's page boundary, or React reports a mismatch.\n    'data-farm-segment': '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(${isolatedHydrationEnabled ? \"FarmServerPage\" : \"'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  // Import layouts before the page, root first, so Vite injects their CSS in the same\n  // layout-then-page order as the server's stylesheet links and the production bundle.\n  const loadedLayouts = layoutShouldHydrate ? await loadLayoutComponents(layouts) : [];\n  if (signal?.aborted) return false;\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  let routeState = null;\n  if (layoutShouldHydrate) {\n    if (pageShouldHydrate) {\n      pageElement = createLayoutPageBoundary(true, islandStrategy, pageElement);\n    }\n    const wrappedTree = wrapWithLoadedLayouts(pageElement, loadedLayouts, params);\n    wrappedElement = wrapFarmClientRouteGraph(wrappedTree);\n    routeState = {\n      element: wrappedElement,\n      layouts: loadedLayouts,\n      page: pageElement,\n      params,\n      wrap: wrapFarmClientRouteGraph,\n    };\n  } else if (useHydrate && container?.id === '__farm_page__') {\n    wrappedElement = wrapFarmClientRouteGraph(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  if (routeState) routeState.element = wrappedElement;\n\n  if (useHydrate) {\n    try {\n      reactRoot = routeState\n        ? hydrateFarmRoute(container, routeState)\n        : hydrateRoot(container, wrappedElement);\n      window.__FARM_REACT_ROOT__ = reactRoot;\n      return true;\n    } catch (error) {\n      appRoot = createRoot(container);\n      if (routeState) renderFarmRoute(appRoot, routeState);\n      else 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    renderFarmRoute(existingRoot, routeState);\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  if (routeState) renderFarmRoute(appRoot, routeState);\n  else 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 window.__FARM_PPR_REFRESH_PROMISE__;\n  // A PPR refresh that is still retrying must not replace DOM once hydration starts.\n  window.__FARM_PPR_HYDRATING__ = true;\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    // A notFound() after the streamed shell swapped the page for the\n    // not-found UI (late-navigation-recovery): never hydrate the page that\n    // threw. Islands outside the page still hydrate.\n    const lateNotFound = document.documentElement.dataset.farmLateNotFound === 'true';\n    const pageShouldHydrate =\n      !lateNotFound &&\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 = !lateNotFound && window.__FARM_LAYOUT_SHOULD_HYDRATE__ === true;\n    const shouldHydrate =\n      !lateNotFound &&\n      (window.__FARM_SHOULD_HYDRATE__ === true || pageShouldHydrate || 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            // A navigation replaced this route before it hydrated. Like a superseded\n            // navigation, that is not a failure, so error hooks never see it.\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) return;\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            // A navigation replaced this route before it hydrated. Like a superseded\n            // navigation, that is not a failure, so error hooks never see it.\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) return;\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      farmServerOnlyEntriesPlugin(),\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 {\n  PluginLocalAPI,\n  PluginLocalAPIEndpoint,\n  PluginRoutes,\n  PluginRoutesFactory,\n  RouteDefinition,\n  RouteMethod,\n} from \"./api/route\";\nexport type { RouteSchema } from \"./api/route-schema\";\nexport type { EndpointMCPMetadata, EndpointMCPOptions } from \"./api/endpoint\";\n// Reachable from every route a plugin declares (each endpoint carries its\n// OpenAPI metadata), so it must be nameable from this entry the same way\n// RouteDefinition is. Otherwise a plugin package's declaration emit falls back to\n// a private dist chunk path.\nexport type { EndpointOpenAPIMetadata } from \"./openapi/types\";\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  copyRequestContext,\n  deleteRequestContext,\n  getRequestContext,\n  getRequestContextSnapshot,\n  hasRequestContext,\n  setRequestContext,\n} from \"./request-context\";\nimport { getFarmPluginIntegrationContext } from \"./plugin-integration-context\";\nimport type { FarmSchema } from \"./schema\";\nimport type { FarmSqlDialect } from \"./schema-sql\";\nimport { declareSchemaTables, readSchemaTables } from \"./schema-owner\";\nimport { pluginShortName } from \"./plugin-dependencies\";\nimport { collectSchemaExtensions } from \"./schema-extend\";\nimport { validateSchemaSteps, type FarmSchemaMigrationStep } from \"./schema-step-types\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\nimport {\n  isPluginOptionsSchema,\n  parsePluginOptions,\n  type FarmPluginFactory,\n  type FarmPluginOptionsSchema,\n  type InferPluginOptionsInput,\n  type InferPluginOptionsOutput,\n} from \"./plugin-options\";\nimport { normalizeFarmBasePath, stripFarmBasePath } from \"./base-path\";\nimport {\n  normalizeFarmPluginRuntimeEndpointPath,\n  normalizeRuntimeEndpointRequestPath,\n} from \"./plugin-runtime-endpoint\";\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  | \"endpoint\"\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 FarmPluginRuntimeEndpointEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBaseEvent<TState, TIntegrationInstance> {\n  /** Normalized application-relative path registered by the endpoint. */\n  path: string;\n}\n\nexport interface FarmPluginRuntimeEndpoint<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  /** Exact application-relative pathname, before Farm's configured basePath. */\n  path: string;\n  handler(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeEndpointEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<Response>;\n}\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  /** Exact request endpoints owned by this plugin. */\n  endpoints?: readonly FarmPluginRuntimeEndpoint<TState, TIntegrationInstance, TIntegrationBound>[];\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   * Tables this plugin stores data in. Farm creates them with\n   * `farm <name> migrate` (the part of the plugin name after its last `:` or\n   * `/`), includes them in `farm generate` and `farm schema check`, and\n   * reaches them through the app's `storage.client`. Mark tables the plugin\n   * only reads, such as the app's `user`, with `external: true`.\n   */\n  schema?: FarmSchema;\n  /** Where the `schema` tables live, when not in the app's `storage.client`. */\n  database?: FarmPluginDatabase;\n  /**\n   * Plugins this one needs, by name (`farm:teams` or `teams`) or integration\n   * key. The config fails to load when one is missing or they form a cycle,\n   * and migrations run dependencies first.\n   */\n  dependsOn?: readonly string[];\n  /**\n   * Ordered steps for what a release changes in its tables that Farm will not\n   * infer, such as a renamed column. Each runs once per database, through\n   * `farm <name> migrate`. Additions need no step.\n   */\n  migrations?: readonly FarmSchemaMigrationStep[];\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 runtimeEndpoints?: Array<{\n    plugin: FarmPlugin;\n    endpoint: FarmPluginRuntimeEndpoint;\n    path: string;\n  }>;\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          // Shutdown never waits for startup, because a plugin whose\n          // runtime.start() hangs still has to be able to stop. Setup can\n          // therefore finish after the runtime is already closed, and the only\n          // way not to leak what it just opened is to release it now. This is\n          // what the disposer would have done moments earlier.\n          if (this.runtimeClosed) {\n            void (async () => {\n              try {\n                await dispose();\n              } catch (error) {\n                console.error(\"Farm runtime cleanup registered after shutdown failed:\", error);\n              }\n            })();\n            return () => {};\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    copyRequestContext(source, target);\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 getRuntimeEndpoints(): Array<{\n    plugin: FarmPlugin;\n    endpoint: FarmPluginRuntimeEndpoint;\n    path: string;\n  }> {\n    if (this.runtimeEndpoints) return this.runtimeEndpoints;\n\n    const endpoints: Array<{\n      plugin: FarmPlugin;\n      endpoint: FarmPluginRuntimeEndpoint;\n      path: string;\n    }> = [];\n    const owners = new Map<string, string>();\n\n    for (const plugin of this.getSortedPlugins()) {\n      const configured = plugin.runtime?.endpoints;\n      if (configured === undefined) continue;\n      if (!Array.isArray(configured)) {\n        throw new TypeError(`Farm plugin \"${plugin.name}\" runtime.endpoints must be an array`);\n      }\n\n      for (const endpoint of configured) {\n        if (!endpoint || typeof endpoint !== \"object\") {\n          throw new TypeError(\n            `Farm plugin \"${plugin.name}\" runtime.endpoints must contain endpoint objects`,\n          );\n        }\n        const path = normalizeFarmPluginRuntimeEndpointPath(\n          endpoint.path,\n          `Farm plugin \"${plugin.name}\" runtime endpoint`,\n        );\n        if (typeof endpoint.handler !== \"function\") {\n          throw new TypeError(\n            `Farm plugin \"${plugin.name}\" runtime endpoint ${path} requires a handler`,\n          );\n        }\n        const owner = owners.get(path);\n        if (owner) {\n          throw new Error(\n            `Farm plugin runtime endpoint ${path} from \"${plugin.name}\" conflicts with \"${owner}\"`,\n          );\n        }\n        owners.set(path, plugin.name);\n        endpoints.push({ plugin, endpoint, path });\n      }\n    }\n\n    this.runtimeEndpoints = endpoints;\n    return endpoints;\n  }\n\n  private async runRuntimeEndpoint(\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n    onMatch: (options: FarmPluginRuntimeRequestOptions) => void,\n  ): Promise<Response | undefined> {\n    const endpoints = this.getRuntimeEndpoints();\n    if (endpoints.length === 0) return undefined;\n\n    const requestPathname = new URL(request.url).pathname;\n    const basePath = normalizeFarmBasePath(this.context.config.basePath);\n    if (basePath && requestPathname !== basePath && !requestPathname.startsWith(`${basePath}/`)) {\n      return undefined;\n    }\n    const pathname = normalizeRuntimeEndpointRequestPath(\n      stripFarmBasePath(requestPathname, basePath),\n    );\n    const match = endpoints.find((entry) => entry.path === pathname);\n    if (!match) return undefined;\n\n    const endpointOptions: FarmPluginRuntimeRequestOptions = {\n      ...options,\n      kind: \"endpoint\",\n      route: {\n        pathname: requestPathname,\n        pattern: match.path,\n        params: {},\n      },\n    };\n    onMatch(endpointOptions);\n    const response = await match.endpoint.handler({\n      ...this.createRuntimeBaseEvent(match.plugin, request, endpointOptions, waitUntil),\n      path: match.path,\n    });\n    if (!(response instanceof Response)) {\n      throw new TypeError(\n        `Farm plugin \"${match.plugin.name}\" runtime endpoint ${match.path} must return a Response`,\n      );\n    }\n    return response;\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    this.runtimeEndpoints = undefined;\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.getRuntimeEndpoints().length > 0 ||\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      // Validate endpoint ownership before setup can create resources or the\n      // production server begins accepting requests.\n      this.getRuntimeEndpoints();\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      // Shutdown deliberately does not wait for startup: a plugin whose\n      // runtime.start() never resolves still has to be able to stop. Setup can\n      // therefore finish while disposal is already running, so keep draining\n      // until nothing new is registered instead of splicing once and stranding\n      // whatever arrived late.\n      while (this.runtimeDisposers.length > 0) {\n        const batch = this.runtimeDisposers.splice(0).reverse();\n        for (const dispose of batch) {\n          try {\n            await dispose();\n          } catch (error) {\n            errors.push(error);\n          }\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 activeOptions = options;\n    let runtimeContext: Readonly<Record<string, unknown>> = Object.freeze({});\n\n    try {\n      const endpoint = await this.runRuntimeEndpoint(\n        activeRequest,\n        activeOptions,\n        waitUntil,\n        (nextOptions) => {\n          activeOptions = nextOptions;\n        },\n      );\n      if (endpoint) {\n        return {\n          request: activeRequest,\n          response: endpoint,\n          ctx: runtimeContext,\n          startedAt,\n          options: activeOptions,\n          waitUntil,\n        };\n      }\n\n      runtimeContext = await this.createRuntimeRequestContext(\n        activeRequest,\n        activeOptions,\n        waitUntil,\n      );\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, activeOptions, 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: activeOptions,\n        waitUntil,\n      };\n    } catch (error) {\n      await this.runRuntimeErrorHooks(\n        activeRequest,\n        error,\n        runtimeContext,\n        Date.now() - startedAt,\n        activeOptions,\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\ntype PluginOptionsSchemaInput = FarmPluginOptionsSchema<any, any>;\n\n/** Parsed options, available to `setup` and `configure` when a plugin declares `options`. */\ntype WithPluginOptions<TContext, TSchema> = TSchema extends PluginOptionsSchemaInput\n  ? TContext & { readonly options: InferPluginOptionsOutput<TSchema> }\n  : TContext;\n\n/**\n * A plugin's state. When it declares `options` and `setup` returns nothing (or\n * there is no `setup`), the parsed options are its state.\n */\ntype ResolvedPluginState<TState, TSchema> = TSchema extends PluginOptionsSchemaInput\n  ? [TState] extends [undefined | void]\n    ? InferPluginOptionsOutput<TSchema>\n    : TState\n  : TState;\n\n/** What `definePlugin` accepts: a plugin, optionally with an `options` schema. */\nexport type FarmPluginDefinition<\n  TState = undefined,\n  TRequestContext extends object = Record<string, never>,\n  TClientState = unknown,\n  TClientPublic = undefined,\n  TIntegrationInstance = unknown,\n  TRoutes extends PluginRoutes = PluginRoutes,\n  TSchema extends PluginOptionsSchemaInput | undefined = undefined,\n> = Omit<\n  FarmPlugin<\n    ResolvedPluginState<TState, TSchema>,\n    TRequestContext,\n    TClientState,\n    TClientPublic,\n    TIntegrationInstance,\n    false,\n    TRoutes\n  >,\n  \"configure\" | \"setup\"\n> & {\n  /**\n   * Describe the plugin's options with a Standard Schema (Zod, Valibot,\n   * ArkType, ...). `definePlugin` then returns a factory: the app passes typed\n   * options, invalid ones fail while the config loads, and the plugin receives\n   * the parsed result in `setup` and `configure`, and as its state.\n   */\n  options?: TSchema;\n  /** Transform Farm config before the development or production pipeline is created. */\n  configure?: (\n    config: FarmConfig,\n    context: WithPluginOptions<FarmPluginContextFor<TIntegrationInstance, false>, TSchema>,\n  ) => MaybePromise<FarmConfig | void>;\n  /** Initialize private plugin state once for this plugin manager. */\n  setup?: (\n    context: WithPluginOptions<FarmPluginSetupContextFor<TIntegrationInstance, false>, TSchema>,\n  ) => MaybePromise<TState>;\n};\n\ntype DefinedPlugin<\n  TState,\n  TRequestContext extends object,\n  TClientState,\n  TClientPublic,\n  TIntegrationInstance,\n  TRoutes extends PluginRoutes,\n  TSchema,\n> = FarmPlugin<\n  ResolvedPluginState<TState, TSchema>,\n  TRequestContext,\n  TClientState,\n  TClientPublic,\n  TIntegrationInstance,\n  false,\n  TRoutes\n>;\n\n/**\n * Define a plugin. Declaring `options` turns the result into a factory:\n *\n * ```ts\n * export const security = definePlugin({\n *   name: \"acme:security\",\n *   options: z.object({ frameAncestors: z.string().default(\"'none'\") }),\n *   runtime: {\n *     after({ state, response }) {\n *       // state.frameAncestors: string\n *       return response;\n *     },\n *   },\n * });\n *\n * // farm.config.ts\n * plugins: [security({ frameAncestors: \"'self'\" })]\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  TSchema extends PluginOptionsSchemaInput | undefined = undefined,\n>(\n  plugin: FarmPluginDefinition<\n    TState,\n    TRequestContext,\n    TClientState,\n    TClientPublic,\n    TIntegrationInstance,\n    TRoutes,\n    TSchema\n  >,\n): TSchema extends PluginOptionsSchemaInput\n  ? FarmPluginFactory<\n      InferPluginOptionsInput<TSchema>,\n      DefinedPlugin<\n        TState,\n        TRequestContext,\n        TClientState,\n        TClientPublic,\n        TIntegrationInstance,\n        TRoutes,\n        TSchema\n      >\n    >\n  : DefinedPlugin<\n      TState,\n      TRequestContext,\n      TClientState,\n      TClientPublic,\n      TIntegrationInstance,\n      TRoutes,\n      TSchema\n    > {\n  // Only a schema turns the plugin into a factory. An untyped plugin that\n  // already carries some other `options` value keeps working as before.\n  if (!isPluginOptionsSchema(plugin.options)) return declarePluginSchema(plugin) as never;\n  return createPluginFactory(\n    plugin as FarmPluginDefinition<any, any, any, any, any, any, any>,\n  ) as never;\n}\n\nfunction createPluginFactory(\n  definition: FarmPluginDefinition<any, any, any, any, any, any, PluginOptionsSchemaInput>,\n) {\n  const { options: schema, configure, setup, ...plugin } = definition;\n  return (input?: unknown): FarmPlugin => {\n    const options = parsePluginOptions(schema!, input);\n    // When setup returns nothing, the parsed options are the plugin's state.\n    const resolveState = (state: unknown) => (state === undefined ? options : state);\n    return declarePluginSchema({\n      ...plugin,\n      ...(configure\n        ? {\n            configure: (config: FarmConfig, context: FarmPluginContextFor<unknown, false>) =>\n              configure(config, { ...context, options }),\n          }\n        : {}),\n      setup(context: FarmPluginSetupContextFor<unknown, false>) {\n        const state = setup?.({ ...context, options });\n        return state instanceof Promise ? state.then(resolveState) : resolveState(state);\n      },\n    } as FarmPlugin);\n  };\n}\n\n/** The database a plugin's `schema` tables live in, when not `storage.client`. */\nexport interface FarmPluginDatabase {\n  /**\n   * A pg, mysql2, or sqlite connection the app chose for this plugin, or a\n   * function returning one. Left undefined, the app's `storage.client` is used,\n   * so a plugin can forward an optional app setting as is.\n   */\n  client?: unknown;\n  /** Only when the dialect cannot be detected from the connection. */\n  dialect?: FarmSqlDialect;\n}\n\n/** The `farm <name> migrate` namespace for a plugin: `farm:teams` → `teams`. */\nfunction pluginSchemaName(pluginName: string): string {\n  const name = pluginShortName(pluginName);\n  if (!/^[a-z0-9][a-z0-9_-]*$/iu.test(name)) {\n    throw new Error(\n      `Plugin \"${pluginName}\" declares a schema, so its name must end in a word made of letters, numbers, \"-\" or \"_\": that word becomes \\`farm <name> migrate\\`.`,\n    );\n  }\n  return name;\n}\n\n/**\n * Record the tables a plugin's `schema` describes, so migrate, generate, and\n * check find them. Farm's own packages that record ownership themselves keep\n * their declaration.\n */\nfunction declarePluginSchema<\n  TPlugin extends {\n    name: string;\n    version?: string;\n    schema?: FarmSchema;\n    database?: FarmPluginDatabase;\n    dependsOn?: readonly string[];\n    migrations?: readonly FarmSchemaMigrationStep[];\n  },\n>(plugin: TPlugin): TPlugin {\n  if (plugin.migrations && !plugin.schema) {\n    throw new Error(\n      `Plugin \"${plugin.name}\" sets \\`migrations\\` without a \\`schema\\`: its steps change the schema's tables.`,\n    );\n  }\n  if (plugin.database && !plugin.schema) {\n    throw new Error(\n      `Plugin \"${plugin.name}\" sets \\`database\\` without a \\`schema\\`: it only says where the schema's tables live.`,\n    );\n  }\n  if (!plugin.schema || readSchemaTables(plugin)) return plugin;\n  const name = pluginSchemaName(plugin.name);\n  // Fail while the config loads, not at the first migrate or query.\n  const models = resolveSchemaModels(name, plugin.schema);\n  collectSchemaExtensions(name, plugin.schema);\n  validateSchemaSteps(name, plugin.schema, plugin.migrations);\n  const database = plugin.database;\n  return declareSchemaTables(plugin, {\n    name,\n    schema: plugin.schema,\n    // Also listed by key, which tooling from before `external` existed reads.\n    models: Object.keys(models).filter((key) => !models[key]!.external),\n    ...(plugin.dependsOn ? { dependsOn: plugin.dependsOn.map(pluginShortName) } : {}),\n    ...(plugin.version ? { version: plugin.version } : {}),\n    ...(plugin.migrations?.length ? { migrations: plugin.migrations } : {}),\n    dialect: database?.dialect,\n    resolveClient: async (config) => {\n      if (database?.client !== undefined && database.client !== null) {\n        const client =\n          typeof database.client === \"function\"\n            ? await (database.client as () => unknown)()\n            : database.client;\n        if (client === undefined || client === null) {\n          throw new Error(`The ${name} plugin's \\`database.client\\` returned no connection.`);\n        }\n        return client;\n      }\n      const { resolveIntegrationOrmRuntimeClient } = await import(\"./integration-orm\");\n      const client = await resolveIntegrationOrmRuntimeClient({ config: config as never });\n      if (client === undefined || client === null) {\n        throw new Error(\n          `The ${name} plugin keeps its tables in the app's database: set \\`storage.client\\` in farm.config.`,\n        );\n      }\n      return client;\n    },\n  });\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 declarePluginSchema(plugin);\n    };\n  }\n}\nexport { farmPlugin } from \"./vite\";\n","import type { NitroConfig } from \"nitro/types\";\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    // serverDir should point to where source files are (for scanning)\n    // But we're using scanDirs to point to our server directory\n    serverDir: 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    // 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      \"/**\": {\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    rollupConfig: {\n      external: [\"react\", \"react-dom\"],\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    },\n    wasm: false, // Disable for now to avoid issues\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 type { FarmAgentCrawlers, FarmCrawlerPolicy } from \"./agent-crawlers\";\nexport { defineRenderer, REACT_RENDERER } from \"./renderer\";\nexport type {\n  FarmRenderer,\n  FarmRendererCapabilities,\n  FarmRendererCapabilitiesInput,\n  FarmRendererRuntime,\n  FarmRendererStreamingCapabilities,\n  FarmRendererStreamingPrimitives,\n} from \"./renderer\";\nexport * from \"./utils\";\nexport * from \"./storage\";\nexport * from \"./schema\";\nexport * from \"./schema-sql\";\nexport * from \"./schema-migrate\";\nexport * from \"./schema-tables\";\nexport { collectSchemaDependencies, orderSchemaOwners } from \"./schema-dependencies\";\nexport type { FarmCrossOwnerReference } from \"./schema-foreign-keys\";\nexport { FARM_SCHEMA_STEPS_TABLE, type FarmSchemaStepPlan } from \"./schema-steps\";\nexport type { FarmSchemaMigrationStep } from \"./schema-step-types\";\nexport {\n  FARM_SCHEMA_STATE_TABLE,\n  type FarmSchemaChanges,\n  type FarmSchemaSnapshot,\n  type FarmSchemaState,\n} from \"./schema-state\";\nexport {\n  collectSchemaExtensions,\n  isSchemaExtensionAllowed,\n  type FarmSchemaExtension,\n} from \"./schema-extend\";\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 { renameSchema, type FarmSchemaRenames } from \"./schema-rename\";\nexport {\n  checkSchema,\n  collectSchemaOwners,\n  formatSchemaCheck,\n  type FarmSchemaCheckCode,\n  type FarmSchemaCheckConfig,\n  type FarmSchemaCheckIssue,\n  type FarmSchemaCheckOwner,\n  type FarmSchemaCheckOptions,\n  type FarmSchemaCheckReport,\n  type FarmSchemaCheckSeverity,\n} from \"./schema-check\";\nexport {\n  definePlugin,\n  FarmRuntimeShutdownError,\n  PluginManager,\n  type FarmPluginDatabase,\n  type FarmPluginDefinition,\n} from \"./plugin\";\nexport {\n  FarmPluginOptionsError,\n  type FarmPluginFactory,\n  type FarmPluginOptionsIssue,\n  type FarmPluginOptionsSchema,\n  type InferPluginOptionsInput,\n  type InferPluginOptionsOutput,\n} from \"./plugin-options\";\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 type {\n  FarmMCPAuthorization,\n  FarmMCPEndpoint,\n  FarmMCPToolDefinition,\n  FarmMCPStandaloneTool,\n  FarmMCPExecuteContext,\n  FarmMCPTool,\n  FarmMCPServer,\n  FarmMCPAuthorizeContext,\n  FarmMCPConfig,\n  FarmMCPUserConfig,\n  ResolvedFarmMCPConfig,\n} from \"./mcp-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  FarmPluginRuntimeEndpoint,\n  FarmPluginRuntimeEndpointEvent,\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 type { FarmSchema } from \"./schema\";\nimport { collectSchemaExtensions } from \"./schema-extend\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\nimport { collectSchemaModels } from \"./schema-sql\";\n\ntype DependencyOwner = {\n  name: string;\n  schema: FarmSchema;\n  models?: readonly string[];\n  dependsOn?: readonly string[];\n};\n\n/**\n * Which owners need which, by owner name: what they declare in `dependsOn`,\n * plus what their schemas imply. A reference to, or columns added to, a\n * table another owner creates makes that owner a dependency. An owner whose\n * schema cannot be resolved contributes only what it declares.\n */\nexport function collectSchemaDependencies(\n  owners: readonly DependencyOwner[],\n): Map<string, Set<string>> {\n  const names = new Set(owners.map((owner) => owner.name));\n  const known = new Map<string, ReturnType<typeof resolveSchemaModels>>();\n  const creators = new Map<string, string>();\n  const claimedKeys = new Map<string, string>();\n  for (const owner of owners) {\n    try {\n      known.set(owner.name, resolveSchemaModels(owner.name, owner.schema));\n      for (const model of collectSchemaModels([[owner.name, owner.schema, owner.models]])) {\n        creators.set(model.modelName.toLowerCase(), owner.name);\n        claimedKeys.set(model.modelKey, owner.name);\n      }\n    } catch {\n      // Reported by the check; it implies nothing here.\n    }\n  }\n\n  // The table a reference points at, resolved the way the check resolves it:\n  // the owner's own description first, then a model another owner creates.\n  const referencedTable = (owner: string, model: string) => {\n    const own = known.get(owner)?.[model];\n    if (own && Object.prototype.hasOwnProperty.call(known.get(owner), model)) return own.name;\n    const creator = claimedKeys.get(model);\n    return (creator && known.get(creator)?.[model]?.name) || model;\n  };\n\n  const dependencies = new Map<string, Set<string>>();\n  for (const owner of owners) {\n    const needs = new Set(\n      (owner.dependsOn ?? []).filter((name) => names.has(name) && name !== owner.name),\n    );\n    dependencies.set(owner.name, needs);\n    const add = (table: string) => {\n      const creator = creators.get(table.toLowerCase());\n      if (creator && creator !== owner.name) needs.add(creator);\n    };\n\n    try {\n      for (const model of collectSchemaModels([[owner.name, owner.schema, owner.models]])) {\n        for (const field of Object.values(model.model.fields)) {\n          if (field.reference) add(referencedTable(owner.name, field.reference.model));\n        }\n      }\n      for (const extension of collectSchemaExtensions(owner.name, owner.schema, owner.models)) {\n        add(extension.table);\n      }\n    } catch {\n      // As above.\n    }\n  }\n  return dependencies;\n}\n\n/**\n * Owners with their dependencies first, otherwise in the order given. When\n * owners only refer to each other, every one is still listed exactly once:\n * without foreign keys between them, either can be created first.\n */\nexport function orderSchemaOwners<TOwner extends DependencyOwner>(\n  owners: readonly TOwner[],\n  dependencies: ReadonlyMap<string, ReadonlySet<string>> = collectSchemaDependencies(owners),\n): TOwner[] {\n  const byName = new Map(owners.map((owner) => [owner.name, owner]));\n  const ordered: TOwner[] = [];\n  const state = new Map<string, \"visiting\" | \"done\">();\n  const visit = (owner: TOwner) => {\n    if (state.has(owner.name)) return;\n    state.set(owner.name, \"visiting\");\n    for (const name of dependencies.get(owner.name) ?? []) {\n      const dependency = byName.get(name);\n      if (dependency && state.get(name) !== \"visiting\") visit(dependency);\n    }\n    state.set(owner.name, \"done\");\n    ordered.push(owner);\n  };\n  for (const owner of owners) visit(owner);\n  return ordered;\n}\n","import React, { createContext, useContext, type ReactNode } from \"react\";\nimport type { FarmConfig } from \"./types\";\nimport { normalizeFarmBasePath } from \"./base-path\";\n\ninterface FarmContextValue {\n  config: FarmConfig;\n  basePath: string;\n}\n\nconst FarmContext = createContext<FarmContextValue | null>(null);\n\ninterface FarmProviderProps {\n  children: ReactNode;\n  config: FarmConfig;\n}\n\n/**\n * Farm.js context provider for client-side components\n */\nexport function FarmProvider({ children, config }: FarmProviderProps) {\n  const value: FarmContextValue = {\n    config,\n    basePath: normalizeFarmBasePath(config.basePath),\n  };\n\n  return <FarmContext.Provider value={value}>{children}</FarmContext.Provider>;\n}\n\n/**\n * Hook to access Farm.js configuration and utilities\n */\nexport function useFarm(): FarmContextValue {\n  const context = useContext(FarmContext);\n\n  if (!context) {\n    throw new Error(\"useFarm must be used within a FarmProvider\");\n  }\n\n  return context;\n}\n\n/** @internal Read Farm context when a component can also use a runtime fallback. */\nexport function useOptionalFarm(): FarmContextValue | null {\n  return useContext(FarmContext);\n}\n\n/**\n * Hook to get the current base path\n */\nexport function useBasePath(): string {\n  const { basePath } = useFarm();\n  return basePath;\n}\n","import type { FarmSchema, FarmSchemaModelOverride } from \"./schema\";\nimport { resolveSchemaModels } from \"./schema-resolve\";\n\n/**\n * Real table and column names for a schema's models, keyed by the names the\n * schema uses. An app passes these to a plugin to point it at its own tables:\n *\n * ```ts\n * teams({\n *   schema: {\n *     user: { name: \"members_auth\", fields: { id: \"user_id\" } },\n *     member: { name: \"team_members\" },\n *   },\n * });\n * ```\n */\nexport type FarmSchemaRenames<TSchema extends FarmSchema = FarmSchema> = {\n  [TModel in keyof TSchema[\"models\"] & string]?: {\n    /** The table's real name. */\n    name?: string;\n    /** Real column names, keyed by the schema's field names. */\n    fields?: { [TField in keyof TSchema[\"models\"][TModel][\"fields\"] & string]?: string };\n  };\n};\n\nconst hasOwn = (target: object, key: string) => Object.prototype.hasOwnProperty.call(target, key);\n\nfunction assertName(value: unknown, where: string): asserts value is string {\n  if (typeof value !== \"string\" || value.trim() === \"\") {\n    throw new TypeError(`${where} must be a non-empty string.`);\n  }\n}\n\n/**\n * Apply an app's renames to a schema. Only names change: the plugin keeps\n * using its own model and field names in code, and every consumer of the\n * schema (migrate, `farm generate`, `farm schema check`, and the runtime ORM)\n * reads the real ones.\n *\n * A rename for a model or field the schema does not have is an error, so a\n * typo fails while the config loads instead of pointing at a missing table.\n */\nexport function renameSchema<TSchema extends FarmSchema>(\n  schema: TSchema,\n  renames: FarmSchemaRenames<TSchema> | undefined,\n): TSchema {\n  if (!renames) return schema;\n  if (typeof renames !== \"object\" || Array.isArray(renames)) {\n    throw new TypeError(\"Schema renames must be an object keyed by model name.\");\n  }\n\n  const resolved = resolveSchemaModels(\"schema\", schema);\n  const override: Record<string, FarmSchemaModelOverride> = { ...schema.override };\n\n  for (const [modelKey, rename] of Object.entries(renames) as Array<\n    [string, { name?: unknown; fields?: Record<string, unknown> } | undefined]\n  >) {\n    if (rename === undefined) continue;\n    const model = hasOwn(resolved, modelKey) ? resolved[modelKey] : undefined;\n    if (!model) {\n      throw new Error(\n        `Cannot rename model \"${modelKey}\": the schema has no such model. Models: ${Object.keys(resolved).join(\", \") || \"(none)\"}.`,\n      );\n    }\n\n    const fields: Record<string, { name: string }> = {};\n    for (const [fieldKey, column] of Object.entries(rename.fields ?? {})) {\n      if (column === undefined) continue;\n      if (!hasOwn(model.fields, fieldKey)) {\n        throw new Error(\n          `Cannot rename \"${modelKey}.${fieldKey}\": the model has no such field. Fields: ${Object.keys(model.fields).join(\", \")}.`,\n        );\n      }\n      assertName(column, `The new name for \"${modelKey}.${fieldKey}\"`);\n      fields[fieldKey] = { name: column };\n    }\n    if (rename.name !== undefined) assertName(rename.name, `The new name for \"${modelKey}\"`);\n\n    const previous = override[modelKey];\n    override[modelKey] = {\n      ...previous,\n      ...(rename.name !== undefined ? { name: rename.name as string } : {}),\n      fields: { ...previous?.fields, ...withExistingField(previous?.fields, fields) },\n    };\n  }\n\n  const renamed = { ...schema, override };\n  // Resolving again catches two fields renamed to one column; tables are\n  // compared here because only owned tables are checked for collisions later.\n  const tables = new Map<string, string>();\n  for (const [modelKey, model] of Object.entries(resolveSchemaModels(\"schema\", renamed))) {\n    const key = model.name.toLowerCase();\n    const other = tables.get(key);\n    if (other) {\n      throw new Error(\n        `Models \"${other}\" and \"${modelKey}\" would both use the table \"${model.name}\".`,\n      );\n    }\n    tables.set(key, modelKey);\n  }\n  return renamed;\n}\n\n/** Keep an existing field override's other settings when only its name changes. */\nfunction withExistingField(\n  previous: FarmSchemaModelOverride[\"fields\"],\n  renamed: Record<string, { name: string }>,\n) {\n  return Object.fromEntries(\n    Object.entries(renamed).map(([fieldKey, value]) => [\n      fieldKey,\n      { ...previous?.[fieldKey], ...value },\n    ]),\n  );\n}\n","import type { FarmSchema, FarmSchemaConfig } from \"./schema\";\nimport { collectSchemaDependencies, orderSchemaOwners } from \"./schema-dependencies\";\nimport { describeForeignKeyApproval, planCrossOwnerReferences } from \"./schema-foreign-keys\";\nimport type { FarmSchemaMigrationStep } from \"./schema-step-types\";\nimport {\n  planOwnerSchemaSteps,\n  withoutRenameTargets,\n  type FarmSchemaStepPlan,\n} from \"./schema-steps\";\nimport {\n  createSchemaSnapshot,\n  diffSchemaSnapshots,\n  hasSchemaChanges,\n  readSchemaState,\n} from \"./schema-state\";\nimport {\n  collectSchemaExtensions,\n  describeSchemaExtensionApproval,\n  isSchemaExtensionAllowed,\n  type FarmSchemaExtension,\n} from \"./schema-extend\";\nimport { getIntegrationSchemas } from \"./integrations\";\nimport { resolveIntegrationOrmRuntimeClient } from \"./integration-orm\";\nimport { resolveSchemaModels, type ResolvedSchemaField } from \"./schema-resolve\";\nimport {\n  columnTypeFamily,\n  createSchemaExecutor,\n  describeSchemaTable,\n  planSchemaMigration,\n  type FarmSchemaExecutor,\n  type FarmSchemaTableDescription,\n} from \"./schema-migrate\";\nimport {\n  collectSchemaModels,\n  getSqlColumnType,\n  type CollectedSchemaModel,\n  type FarmSqlDialect,\n} from \"./schema-sql\";\nimport {\n  findSchemaTableOwners,\n  readSchemaTables,\n  type FarmSchemaOwnerConfig,\n} from \"./schema-tables\";\n\n/**\n * Read-only checks of every schema owner against the real database.\n *\n * Owners are integrations that declare a `schema` and plugins that declare\n * tables. Their tables are compared with what the database holds, and every\n * reference to a table someone else owns (the app's ORM, an auth library,\n * another plugin) is checked too: the table must exist and the referenced\n * column must have a type a foreign key can use. Nothing is written.\n */\n\nexport type FarmSchemaCheckSeverity = \"error\" | \"warning\";\n\nexport type FarmSchemaCheckCode =\n  | \"schema-invalid\"\n  | \"owner-conflict\"\n  | \"table-conflict\"\n  | \"client-missing\"\n  | \"client-unavailable\"\n  | \"client-unsupported\"\n  | \"table-missing\"\n  | \"column-missing\"\n  | \"column-type\"\n  | \"column-definition\"\n  | \"index-missing\"\n  | \"foreign-key-missing\"\n  | \"reference-table-missing\"\n  | \"reference-column-missing\"\n  | \"reference-type\"\n  | \"extend-invalid\"\n  | \"extend-table-missing\"\n  | \"extend-column-missing\"\n  | \"extend-column-type\"\n  | \"extend-column-shared\"\n  | \"schema-upgrade\"\n  | \"migration-step-pending\"\n  | \"migration-step-blocked\"\n  | \"migration-step-edited\";\n\nexport interface FarmSchemaCheckIssue {\n  severity: FarmSchemaCheckSeverity;\n  code: FarmSchemaCheckCode;\n  /** The integration key or plugin name that declares the schema. */\n  owner: string;\n  table?: string;\n  column?: string;\n  message: string;\n  /** What to do about it. */\n  hint?: string;\n}\n\nexport interface FarmSchemaCheckOwner {\n  name: string;\n  kind: \"integration\" | \"plugin\";\n  dialect?: FarmSqlDialect;\n  /** False when the owner stores data in a key/value mount, which has no tables. */\n  relational: boolean;\n  tables: string[];\n  /** Owners whose tables this one needs, declared or implied by its schema. */\n  dependsOn: string[];\n}\n\nexport interface FarmSchemaCheckReport {\n  owners: FarmSchemaCheckOwner[];\n  issues: FarmSchemaCheckIssue[];\n  /** True when there are no errors. Warnings do not fail a check. */\n  ok: boolean;\n}\n\nexport type FarmSchemaCheckConfig = FarmSchemaOwnerConfig & {\n  plugins?: readonly unknown[];\n};\n\nexport interface FarmSchemaCheckOptions {\n  /**\n   * How long connecting, and each query, may take before the owner is\n   * reported unreachable. A pg client has no connect timeout of its own, so\n   * an unreachable host would otherwise hang the check. Default 10 seconds.\n   */\n  timeoutMs?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Reject when `work` has not settled in time. The work itself is abandoned. */\nasync function withTimeout<T>(work: () => Promise<T>, timeoutMs: number): Promise<T> {\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  const timeout = new Promise<never>((_, reject) => {\n    timer = setTimeout(\n      () => reject(new Error(`no answer within ${formatSeconds(timeoutMs)}`)),\n      timeoutMs,\n    );\n    // An abandoned connection attempt must not keep the process alive.\n    (timer as { unref?: () => void }).unref?.();\n  });\n  try {\n    return await Promise.race([Promise.resolve().then(work), timeout]);\n  } finally {\n    clearTimeout(timer);\n  }\n}\n\nconst formatSeconds = (ms: number) =>\n  ms < 1000 ? `${ms}ms` : `${Number((ms / 1000).toFixed(1))}s`;\n\ntype SchemaOwner = {\n  name: string;\n  kind: \"integration\" | \"plugin\";\n  schema: FarmSchema;\n  models?: readonly string[];\n  dialect?: FarmSqlDialect;\n  dependsOn?: readonly string[];\n  version?: string;\n  migrations?: readonly FarmSchemaMigrationStep[];\n  resolveClient(config: FarmSchemaCheckConfig): Promise<unknown>;\n};\n\n/**\n * Every owner of database tables in an app: integrations that declare a\n * `schema` and plugins that declare tables. An integration that also\n * contributes a table-owning plugin under the same name is listed once.\n */\nexport function collectSchemaOwners(config: FarmSchemaCheckConfig): SchemaOwner[] {\n  const owners: SchemaOwner[] = [];\n  const integrationSchemas = getIntegrationSchemas(config.integrations as never);\n  // Every integration reads `storage.client`. A factory there would open a\n  // new connection per integration, so it is resolved once and shared.\n  let integrationClient: Promise<unknown> | undefined;\n  for (const [name, schema] of Object.entries(integrationSchemas)) {\n    owners.push({\n      name,\n      kind: \"integration\",\n      schema: schema as FarmSchema,\n      resolveClient: (resolved) =>\n        (integrationClient ??= resolveIntegrationOrmRuntimeClient({ config: resolved as never })),\n    });\n  }\n  for (const declaration of findSchemaTableOwners(config)) {\n    if (owners.some((owner) => owner.name === declaration.name)) continue;\n    owners.push({\n      name: declaration.name,\n      kind: \"plugin\",\n      schema: declaration.schema,\n      models: declaration.models,\n      dialect: declaration.dialect,\n      dependsOn: declaration.dependsOn,\n      version: declaration.version,\n      migrations: declaration.migrations,\n      resolveClient: (resolved) => declaration.resolveClient(resolved),\n    });\n  }\n  return owners;\n}\n\n/** Driver errors can echo a connection string; never print its password. */\nconst errorMessage = (error: unknown) =>\n  (error instanceof Error ? error.message : String(error)).replace(\n    /(\\/\\/[^/\\s:@]+):[^@\\s]+@/gu,\n    \"$1:***@\",\n  );\n\nfunction migrateHint(owner: SchemaOwner): string {\n  return owner.kind === \"plugin\"\n    ? `Run \\`farm ${owner.name} migrate\\` to see the SQL, then \\`--apply\\` it.`\n    : \"Create it with your migration tool: `farm generate` writes the integration's tables into your Prisma or Drizzle schema.\";\n}\n\n/** Where an owner's tables live. */\ntype OwnerDatabase = {\n  /** The driver connection, to tell owners sharing one database apart. */\n  client: unknown;\n  executor: FarmSchemaExecutor;\n  dialect: FarmSqlDialect;\n};\n\n/**\n * A SQL executor for a client, null for a key/value mount, or undefined for a\n * client Farm cannot read, such as a Prisma client. A Drizzle database keeps\n * its driver on `$client`, which is used instead.\n */\nfunction resolveSchemaExecutor(\n  client: unknown,\n  owner: string,\n  timeoutMs: number,\n): (ReturnType<typeof createSchemaExecutor> & { client: unknown }) | null | undefined {\n  for (const candidate of [client, (client as { $client?: unknown }).$client]) {\n    if (candidate === undefined || candidate === null) continue;\n    let adapter: ReturnType<typeof createSchemaExecutor>;\n    try {\n      adapter = createSchemaExecutor(candidate, owner);\n    } catch {\n      continue; // Not a driver Farm can read; try the next shape.\n    }\n    if (!adapter) return null;\n    const { executor } = adapter;\n    return {\n      ...adapter,\n      client: candidate,\n      // Each query is bounded, not the whole check, so a large schema on a\n      // slow link still finishes while a dead connection fails fast.\n      executor: {\n        execute: (sql) => withTimeout(() => executor.execute(sql), timeoutMs),\n        query: (sql, params) => withTimeout(() => executor.query(sql, params), timeoutMs),\n      },\n    };\n  }\n  return undefined;\n}\n\nconst describeReferencedTable = (database: OwnerDatabase, table: string) =>\n  describeSchemaTable(database.executor, database.dialect, table);\n\n/** Physical table and column a reference points at, and who owns them. */\ntype ReferenceTarget = {\n  table: string;\n  column: string;\n  /** Another Farm owner, or undefined for tables Farm does not manage. */\n  owner?: string;\n};\n\nexport async function checkSchema(\n  config: FarmSchemaCheckConfig,\n  options: FarmSchemaCheckOptions = {},\n): Promise<FarmSchemaCheckReport> {\n  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n    throw new TypeError(\"timeoutMs must be a positive number of milliseconds.\");\n  }\n  const timeoutHint = `Check that the database is reachable from here, or allow longer than ${formatSeconds(timeoutMs)} with \\`--timeout <ms>\\`.`;\n  // Dependencies first, so the report reads in the order things get created.\n  const dependencies = collectSchemaDependencies(collectSchemaOwners(config));\n  const owners = orderSchemaOwners(collectSchemaOwners(config), dependencies);\n  const issues: FarmSchemaCheckIssue[] = [];\n\n  // Owners are found by name, so a second plugin declaring tables under a\n  // name already taken is invisible to migrate and to this check.\n  const declared = new Map<string, unknown[]>();\n  for (const candidate of config.plugins ?? []) {\n    const declaration = readSchemaTables(candidate);\n    if (!declaration) continue;\n    const schemas = declared.get(declaration.name) ?? [];\n    if (!schemas.includes(declaration.schema)) schemas.push(declaration.schema);\n    declared.set(declaration.name, schemas);\n  }\n  for (const [name, schemas] of declared) {\n    if (schemas.length < 2) continue;\n    issues.push({\n      severity: \"error\",\n      code: \"owner-conflict\",\n      owner: name,\n      message: `${schemas.length} plugins declare tables under the name \"${name}\", so \\`farm ${name} migrate\\` and this check only see the first.`,\n      hint: \"Rename one of the plugins: the part of its name after the last `:` or `/` is its migrate command.\",\n    });\n  }\n  const summaries: FarmSchemaCheckOwner[] = [];\n\n  // Every model key each owner knows about, claimed or not, with its\n  // physical names, so a reference can be resolved to a real table.\n  const knownModels = new Map<string, ReturnType<typeof resolveSchemaModels>>();\n  const ownedModels = new Map<string, CollectedSchemaModel[]>();\n  for (const owner of owners) {\n    try {\n      knownModels.set(owner.name, resolveSchemaModels(owner.name, owner.schema));\n      ownedModels.set(owner.name, collectSchemaModels([[owner.name, owner.schema, owner.models]]));\n    } catch (error) {\n      issues.push({\n        severity: \"error\",\n        code: \"schema-invalid\",\n        owner: owner.name,\n        message: errorMessage(error),\n      });\n    }\n  }\n\n  const resolveTarget = (\n    ownerName: string,\n    field: ResolvedSchemaField,\n  ): ReferenceTarget | undefined => {\n    const reference = field.reference;\n    if (!reference) return undefined;\n    // The owner's own schema first, claimed or not: it describes the tables\n    // this owner works with. Then a model another owner creates. Another\n    // owner's unclaimed models are only its description of someone else's\n    // table, so they are not used to reinterpret this owner's reference.\n    const own = knownModels.get(ownerName)?.[reference.model];\n    const other = own\n      ? undefined\n      : owners.find(\n          (owner) =>\n            owner.name !== ownerName &&\n            (ownedModels.get(owner.name) ?? []).some((entry) => entry.modelKey === reference.model),\n        );\n    const model = own ?? (other && knownModels.get(other.name)?.[reference.model]);\n    if (model) {\n      const claimedBy = [...ownedModels].find(([, models]) =>\n        models.some((entry) => entry.modelName === model.name),\n      )?.[0];\n      return {\n        table: model.name,\n        column: model.fields[reference.field]?.name ?? reference.field,\n        owner: claimedBy,\n      };\n    }\n    // A table Farm does not manage: the app's ORM, an auth library, a migration.\n    return { table: reference.model, column: reference.field };\n  };\n\n  // Each owner's database, resolved before any check so a reference into\n  // another owner's table is looked up where that owner keeps it.\n  const databases = new Map<string, OwnerDatabase>();\n  for (const owner of owners) {\n    const models = ownedModels.get(owner.name);\n    if (!models) continue;\n    const summary: FarmSchemaCheckOwner = {\n      name: owner.name,\n      kind: owner.kind,\n      relational: true,\n      tables: models.map((model) => model.modelName),\n      dependsOn: [...(dependencies.get(owner.name) ?? [])],\n    };\n    summaries.push(summary);\n\n    let client: unknown;\n    try {\n      client = await withTimeout(() => owner.resolveClient(config), timeoutMs);\n    } catch (error) {\n      issues.push({\n        severity: \"error\",\n        code: \"client-unavailable\",\n        owner: owner.name,\n        message: `Could not connect to ${owner.name}'s database: ${errorMessage(error)}`,\n        hint: timeoutHint,\n      });\n      continue;\n    }\n    if (client === undefined || client === null) {\n      issues.push({\n        severity: \"error\",\n        code: \"client-missing\",\n        owner: owner.name,\n        message: `${owner.name} declares tables but has no database client.`,\n        hint:\n          owner.kind === \"integration\"\n            ? \"Set `storage.client` in farm.config to your database client.\"\n            : `Pass a database client to the ${owner.name} plugin.`,\n      });\n      continue;\n    }\n\n    const adapter = resolveSchemaExecutor(client, owner.name, timeoutMs);\n    if (adapter === null) {\n      // A key/value mount has no tables to check.\n      summary.relational = false;\n      continue;\n    }\n    if (adapter === undefined) {\n      // Not a failure: an ORM client means that ORM's migrations own the\n      // tables, and the check must not block a deploy it cannot inspect.\n      issues.push({\n        severity: \"warning\",\n        code: \"client-unsupported\",\n        owner: owner.name,\n        message: `${owner.name}'s database client cannot be inspected, so its tables were not checked.`,\n        hint: \"Farm reads pg, mysql2, and sqlite connections, and Drizzle databases built on them. Check these tables with your ORM's migration status instead.\",\n      });\n      continue;\n    }\n    const dialect = owner.dialect ?? adapter.dialect;\n    summary.dialect = dialect;\n    databases.set(owner.name, { client: adapter.client, executor: adapter.executor, dialect });\n  }\n\n  // Two owners must not claim the same table in the same database.\n  const claims = new Map<string, string>();\n  for (const [ownerName, models] of ownedModels) {\n    for (const model of models) {\n      const key = model.modelName.toLowerCase();\n      const previous = claims.get(key);\n      if (!previous || previous === ownerName) {\n        claims.set(key, ownerName);\n        continue;\n      }\n      const mine = databases.get(ownerName);\n      const theirs = databases.get(previous);\n      // Different dialects are different databases. Different client objects\n      // may still be one database (a factory opens a new connection per call).\n      if (mine && theirs && mine.dialect !== theirs.dialect) continue;\n      if (\n        mine?.dialect === \"postgres\" &&\n        theirs?.dialect === \"postgres\" &&\n        !(ownedModels.get(previous) ?? []).some((entry) => entry.modelName === model.modelName)\n      ) {\n        continue; // Postgres names are case-sensitive: \"User\" and \"user\" are two tables.\n      }\n      const shared = Boolean(mine && theirs && mine.client === theirs.client);\n      issues.push({\n        severity: shared ? \"error\" : \"warning\",\n        code: \"table-conflict\",\n        owner: ownerName,\n        table: model.modelName,\n        message: shared\n          ? `\"${model.modelName}\" is claimed by both ${previous} and ${ownerName}.`\n          : `\"${model.modelName}\" is claimed by both ${previous} and ${ownerName}. If they share a database, they write to the same table.`,\n        hint: \"Give one of the models a different table name with `name`, or narrow one owner's `models`.\",\n      });\n    }\n  }\n\n  // Columns owners add to tables they do not own, and which database each\n  // table is in: the owner that creates it, or the extending owner's own.\n  const allowExtend = (config.schema as FarmSchemaConfig | undefined)?.allowExtend;\n  const extensions = new Map<string, FarmSchemaExtension[]>();\n  const addedColumns = new Map<string, string>();\n  for (const owner of owners) {\n    if (!ownedModels.has(owner.name)) continue;\n    try {\n      const owned = collectSchemaExtensions(owner.name, owner.schema, owner.models);\n      extensions.set(owner.name, owned);\n      for (const extension of owned) {\n        for (const { field } of extension.fields) {\n          const key = `${extension.table}.${field.name}`.toLowerCase();\n          const other = addedColumns.get(key);\n          if (other && other !== owner.name) {\n            issues.push({\n              severity: \"warning\",\n              code: \"extend-column-shared\",\n              owner: owner.name,\n              table: extension.table,\n              column: field.name,\n              message: `${other} and ${owner.name} both add \"${extension.table}.${field.name}\", so they will share one column.`,\n            });\n          } else {\n            addedColumns.set(key, owner.name);\n          }\n        }\n      }\n    } catch (error) {\n      issues.push({\n        severity: \"error\",\n        code: \"extend-invalid\",\n        owner: owner.name,\n        message: errorMessage(error),\n      });\n    }\n  }\n  const databaseForTable = (table: string): OwnerDatabase | undefined => {\n    const creator = [...ownedModels].find(([, models]) =>\n      models.some((model) => model.modelName === table),\n    )?.[0];\n    return creator ? databases.get(creator) : undefined;\n  };\n\n  for (const owner of owners) {\n    const models = ownedModels.get(owner.name);\n    const database = databases.get(owner.name);\n    if (!models || !database) continue;\n    try {\n      // The same foreign keys migrate would create, so a missing one can be named.\n      const crossOwner = await planCrossOwnerReferences(\n        owner,\n        findSchemaTableOwners(config),\n        database.dialect,\n        database.executor,\n      );\n      for (const reference of crossOwner.eligible) {\n        const model = models.find((candidate) => candidate.modelKey === reference.modelKey);\n        if (!model) continue;\n        (model.foreignKeys ??= {})[reference.fieldKey] = {\n          table: reference.referencedTable,\n          column: reference.referencedColumn,\n          onDelete: reference.onDelete,\n        };\n      }\n      // Migration steps, read the way migrate reads them.\n      const stepPlan = owner.migrations?.length\n        ? await planOwnerSchemaSteps({\n            owner: owner.name,\n            schema: owner.schema,\n            steps: owner.migrations,\n            tables: models.map((model) => model.modelName),\n            dialect: database.dialect,\n            executor: database.executor,\n            othersTables: new Set(\n              [...ownedModels]\n                .filter(([name]) => name !== owner.name)\n                .flatMap(([, entries]) => entries.map((entry) => entry.modelName)),\n            ),\n          })\n        : undefined;\n      checkSteps(owner, stepPlan, issues);\n      const plan = await checkOwnerTables(\n        owner,\n        // What a pending rename will produce is not missing yet.\n        withoutRenameTargets(models, stepPlan),\n        database.dialect,\n        database.executor,\n        issues,\n      );\n      // An installed version whose changes have not been applied here yet.\n      const pending = plan.statements.length + (plan.upgrades?.length ?? 0);\n      const state =\n        pending > 0\n          ? await readSchemaState(database.executor, database.dialect, owner.name)\n          : undefined;\n      const changes = state\n        ? diffSchemaSnapshots(state.snapshot, createSchemaSnapshot(models))\n        : undefined;\n      if (state && changes && hasSchemaChanges(changes)) {\n        const versions =\n          state.version && owner.version && state.version !== owner.version\n            ? `upgraded ${state.version} → ${owner.version}`\n            : \"changed since it was last migrated\";\n        issues.push({\n          severity: \"warning\",\n          code: \"schema-upgrade\",\n          owner: owner.name,\n          message: `${owner.name} ${versions}, and ${pending} change(s) are not applied yet.`,\n          hint:\n            owner.kind === \"plugin\"\n              ? `Run \\`farm ${owner.name} migrate\\` to review and apply them.`\n              : \"Apply them with your migration tool.\",\n        });\n      }\n      await checkReferences(owner, models, database, databases, resolveTarget, issues);\n      await checkExtensions(\n        owner,\n        extensions.get(owner.name) ?? [],\n        databaseForTable,\n        database,\n        allowExtend,\n        issues,\n      );\n    } catch (error) {\n      issues.push({\n        severity: \"error\",\n        code: \"client-unavailable\",\n        owner: owner.name,\n        message: `Could not read ${owner.name}'s tables: ${errorMessage(error)}`,\n        hint: timeoutHint,\n      });\n    }\n  }\n\n  return {\n    owners: summaries,\n    issues,\n    ok: !issues.some((issue) => issue.severity === \"error\"),\n  };\n}\n\nasync function checkOwnerTables(\n  owner: SchemaOwner,\n  models: readonly CollectedSchemaModel[],\n  dialect: FarmSqlDialect,\n  executor: FarmSchemaExecutor,\n  issues: FarmSchemaCheckIssue[],\n) {\n  const plan = await planSchemaMigration(models, dialect, executor);\n  const present = new Set([\n    ...plan.upToDate,\n    ...plan.drift.map((drift) => drift.table),\n    ...(plan.upgrades ?? []).map((upgrade) => upgrade.table),\n  ]);\n  const command =\n    owner.kind === \"plugin\" ? `\\`farm ${owner.name} migrate\\`` : \"your migration tool\";\n\n  // Additions migrate can make: still missing, so a missing column is an error.\n  for (const upgrade of plan.upgrades ?? []) {\n    const column =\n      upgrade.kind === \"column\" ? upgrade.target.slice(upgrade.table.length + 1) : undefined;\n    issues.push({\n      severity: column ? \"error\" : \"warning\",\n      code: column ? \"column-missing\" : \"index-missing\",\n      owner: owner.name,\n      table: upgrade.table,\n      ...(column ? { column } : {}),\n      message: column\n        ? `\"${upgrade.table}\" has no column \"${column}\".`\n        : `\"${upgrade.table}\" is missing the index ${upgrade.target}.`,\n      hint: `Add it with ${command}.`,\n    });\n  }\n\n  for (const model of models) {\n    if (present.has(model.modelName)) continue;\n    issues.push({\n      severity: \"error\",\n      code: \"table-missing\",\n      owner: owner.name,\n      table: model.modelName,\n      message: `Table \"${model.modelName}\" does not exist.`,\n      hint: migrateHint(owner),\n    });\n  }\n\n  for (const drift of plan.drift) {\n    for (const column of drift.missingColumns) {\n      issues.push({\n        severity: \"error\",\n        code: \"column-missing\",\n        owner: owner.name,\n        table: drift.table,\n        column,\n        message: `\"${drift.table}\" has no column \"${column}\".`,\n        hint: \"It is required with no default, so Farm cannot add it to a table that may have rows. Add it with a migration step or your migration tool.\",\n      });\n    }\n    for (const change of drift.changedColumns) {\n      const typeChanged = change.differences.includes(\"type\");\n      issues.push({\n        severity: typeChanged ? \"error\" : \"warning\",\n        code: typeChanged ? \"column-type\" : \"column-definition\",\n        owner: owner.name,\n        table: drift.table,\n        column: change.column,\n        message: typeChanged\n          ? `\"${drift.table}.${change.column}\" is ${change.actual.type}; the schema expects ${change.expected.type}.`\n          : `\"${drift.table}.${change.column}\" differs from the schema (${change.differences.join(\", \")}).`,\n      });\n    }\n    for (const index of drift.missingIndexes) {\n      issues.push({\n        severity: \"warning\",\n        code: \"index-missing\",\n        owner: owner.name,\n        table: drift.table,\n        message: `\"${drift.table}\" is missing the ${index.unique ? \"unique \" : \"\"}index on (${index.columns.join(\", \")}).`,\n      });\n    }\n    for (const reference of drift.missingReferences ?? []) {\n      issues.push({\n        severity: \"warning\",\n        code: \"foreign-key-missing\",\n        owner: owner.name,\n        table: drift.table,\n        column: reference.column,\n        message: `\"${drift.table}.${reference.column}\" has no foreign key to \"${reference.referencedTable}.${reference.referencedColumn}\".`,\n      });\n    }\n  }\n  for (const key of plan.addableForeignKeys ?? []) {\n    issues.push({\n      severity: \"warning\",\n      code: \"foreign-key-missing\",\n      owner: owner.name,\n      table: key.table,\n      column: key.column,\n      message: `\"${key.table}.${key.column}\" has no foreign key to \"${key.referencedTable}.${key.referencedColumn}\", which ${owner.name} could have.`,\n      hint:\n        dialect === \"sqlite\"\n          ? \"SQLite can only add a foreign key when it creates the table.\"\n          : `Allow it with \\`${describeForeignKeyApproval({ owner: owner.name, modelKey: key.modelKey })}\\` in farm.config, then run \\`farm ${owner.name} migrate --apply\\`. Rows that point at nothing are checked first.`,\n    });\n  }\n  return plan;\n}\n\nfunction checkSteps(\n  owner: SchemaOwner,\n  stepPlan: FarmSchemaStepPlan | undefined,\n  issues: FarmSchemaCheckIssue[],\n) {\n  if (!stepPlan) return;\n  const command = `\\`farm ${owner.name} migrate\\``;\n  const blockedAt = stepPlan.steps.findIndex((planned) => planned.state === \"blocked\");\n  const pending = stepPlan.steps\n    .slice(0, blockedAt === -1 ? undefined : blockedAt)\n    .filter((planned) => planned.state === \"run\");\n  if (pending.length > 0) {\n    issues.push({\n      severity: \"warning\",\n      code: \"migration-step-pending\",\n      owner: owner.name,\n      message: `${owner.name} has ${pending.length} migration step(s) not run yet: ${pending.map((planned) => `${planned.summary}${planned.destructive ? \" (deletes data)\" : \"\"}`).join(\"; \")}.`,\n      hint: `Run ${command} to review and apply them.`,\n    });\n  }\n  if (blockedAt !== -1) {\n    const blocked = stepPlan.steps[blockedAt]!;\n    issues.push({\n      severity: \"error\",\n      code: \"migration-step-blocked\",\n      owner: owner.name,\n      message: `${owner.name}'s migration step \"${blocked.step.id}\" (${blocked.summary}) cannot run: ${blocked.reason}`,\n      hint: \"Later steps wait for it. Fix the database, then run migrate again.\",\n    });\n  }\n  for (const id of stepPlan.edited) {\n    issues.push({\n      severity: \"warning\",\n      code: \"migration-step-edited\",\n      owner: owner.name,\n      message: `${owner.name}'s migration step \"${id}\" changed after it ran here; it will not run again.`,\n    });\n  }\n}\n\nasync function checkReferences(\n  owner: SchemaOwner,\n  models: readonly CollectedSchemaModel[],\n  database: OwnerDatabase,\n  databases: ReadonlyMap<string, OwnerDatabase>,\n  resolveTarget: (owner: string, field: ResolvedSchemaField) => ReferenceTarget | undefined,\n  issues: FarmSchemaCheckIssue[],\n) {\n  const ownTables = new Set(models.map((model) => model.modelName));\n  const described = new Map<string, FarmSchemaTableDescription | undefined>();\n\n  for (const model of models) {\n    for (const field of Object.values(model.model.fields)) {\n      const target = resolveTarget(owner.name, field);\n      // References inside the owner's own tables are covered by the table check.\n      if (!target || ownTables.has(target.table)) continue;\n\n      // Another owner's table lives in that owner's database. When it could\n      // not be reached or inspected, its own issue already says so.\n      const targetDatabase = target.owner ? databases.get(target.owner) : database;\n      if (!targetDatabase) continue;\n      const key = `${target.owner ?? \"\"}\\u0000${target.table}`;\n      if (!described.has(key)) {\n        described.set(key, await describeReferencedTable(targetDatabase, target.table));\n      }\n      const table = described.get(key);\n      const dialect = targetDatabase.dialect;\n      const where = `\"${model.modelName}.${field.name}\" references \"${target.table}.${target.column}\"`;\n\n      if (!table) {\n        issues.push({\n          severity: \"error\",\n          code: \"reference-table-missing\",\n          owner: owner.name,\n          table: model.modelName,\n          column: field.name,\n          message: `${where}, but \"${target.table}\" does not exist.`,\n          hint: target.owner\n            ? `It belongs to ${target.owner}; migrate it first.`\n            : \"Farm does not manage that table. Run the migration that creates it (your ORM's, or a library's such as Better Auth) first.\",\n        });\n        continue;\n      }\n\n      // Postgres column names are case-sensitive once quoted, as Farm quotes them.\n      const column = table.columns.find((candidate) =>\n        dialect === \"postgres\"\n          ? candidate.name === target.column\n          : candidate.name.toLowerCase() === target.column.toLowerCase(),\n      );\n      if (!column) {\n        issues.push({\n          severity: \"error\",\n          code: \"reference-column-missing\",\n          owner: owner.name,\n          table: model.modelName,\n          column: field.name,\n          message: `${where}, but \"${target.table}\" has no column \"${target.column}\".`,\n          hint: `Columns there: ${table.columns.map((candidate) => candidate.name).join(\", \")}.`,\n        });\n        continue;\n      }\n\n      // SQLite converts by affinity when it compares, so any pairing joins.\n      if (database.dialect === \"sqlite\" || dialect === \"sqlite\") continue;\n      const expected = getSqlColumnType(field, database.dialect);\n      const mine = columnTypeFamily(expected);\n      const theirs = columnTypeFamily(column.type);\n      if (mine && theirs && mine !== theirs) {\n        // A warning, not an error: lookups by value still work, and Farm only\n        // creates a foreign key across owners when the types match, so this\n        // reference simply stays without one. Joins in SQL need a cast.\n        issues.push({\n          severity: \"warning\",\n          code: \"reference-type\",\n          owner: owner.name,\n          table: model.modelName,\n          column: field.name,\n          message: `${where}, but the types differ: ${expected.toLowerCase()} here, ${column.type} there. Lookups by value work; a SQL join needs a cast and a foreign key is not possible.`,\n          hint:\n            theirs === \"uuid\" && mine === \"text\"\n              ? 'Farm stores \"uuid\" fields as text in Postgres. Cast in joins, for example \"users\".\"id\"::text.'\n              : `Change \"${field.name}\" to match \"${target.table}.${target.column}\" if you join on it.`,\n        });\n      }\n    }\n  }\n}\n\nasync function checkExtensions(\n  owner: SchemaOwner,\n  extensions: readonly FarmSchemaExtension[],\n  databaseForTable: (table: string) => OwnerDatabase | undefined,\n  ownDatabase: OwnerDatabase,\n  allowExtend: Record<string, readonly string[]> | undefined,\n  issues: FarmSchemaCheckIssue[],\n) {\n  for (const extension of extensions) {\n    const database = databaseForTable(extension.table) ?? ownDatabase;\n    const table = await describeSchemaTable(database.executor, database.dialect, extension.table);\n    const columns = extension.fields.map(({ field }) => field.name);\n    if (!table) {\n      issues.push({\n        severity: \"error\",\n        code: \"extend-table-missing\",\n        owner: owner.name,\n        table: extension.table,\n        message: `${owner.name} adds ${columns.map((column) => `\"${column}\"`).join(\", \")} to \"${extension.table}\", which does not exist.`,\n        hint: \"Run the migration that creates it (your ORM's, or a library's such as Better Auth) first.\",\n      });\n      continue;\n    }\n\n    const allowed = isSchemaExtensionAllowed(allowExtend, extension);\n    for (const { field } of extension.fields) {\n      const existing = table.columns.find((column) =>\n        database.dialect === \"postgres\"\n          ? column.name === field.name\n          : column.name.toLowerCase() === field.name.toLowerCase(),\n      );\n      if (!existing) {\n        const command =\n          owner.kind === \"plugin\"\n            ? `\\`farm ${owner.name} migrate --apply\\``\n            : \"your migration tool\";\n        issues.push({\n          severity: \"error\",\n          code: \"extend-column-missing\",\n          owner: owner.name,\n          table: extension.table,\n          column: field.name,\n          message: `${owner.name} needs \"${extension.table}.${field.name}\", which does not exist.`,\n          hint: allowed\n            ? `Add it with ${command}. If your ORM owns \"${extension.table}\", add the column to its schema instead.`\n            : `Allow it in farm.config with \\`${describeSchemaExtensionApproval(extension)}\\`, then add it with ${command}. If your ORM owns \"${extension.table}\", add the column to its schema instead.`,\n        });\n        continue;\n      }\n      if (database.dialect === \"sqlite\") continue;\n      const expected = getSqlColumnType(field, database.dialect);\n      const mine = columnTypeFamily(expected);\n      const theirs = columnTypeFamily(existing.type);\n      if (mine && theirs && mine !== theirs) {\n        issues.push({\n          severity: \"warning\",\n          code: \"extend-column-type\",\n          owner: owner.name,\n          table: extension.table,\n          column: field.name,\n          message: `\"${extension.table}.${field.name}\" is ${existing.type}; ${owner.name} expects ${expected.toLowerCase()}.`,\n        });\n      }\n    }\n  }\n}\n\n/** Human-readable report, grouped by owner. */\nexport function formatSchemaCheck(report: FarmSchemaCheckReport): string {\n  if (report.owners.length === 0) {\n    return \"No integration or plugin declares database tables.\";\n  }\n  const lines: string[] = [];\n  for (const owner of report.owners) {\n    const ownIssues = report.issues.filter((issue) => issue.owner === owner.name);\n    const details = [\n      owner.kind,\n      ...(owner.dialect ? [owner.dialect] : []),\n      ...(owner.dependsOn?.length ? [`needs ${owner.dependsOn.join(\", \")}`] : []),\n    ];\n    const label = `${owner.name} (${details.join(\", \")})`;\n    if (!owner.relational) {\n      lines.push(`- ${label}: stores data in a key/value mount, nothing to check`);\n      continue;\n    }\n    lines.push(\n      ownIssues.length === 0\n        ? `✓ ${label}: ${owner.tables.length} table(s) match`\n        : `${ownIssues.some((issue) => issue.severity === \"error\") ? \"✗\" : \"!\"} ${label}`,\n    );\n    for (const issue of ownIssues) {\n      lines.push(`    ${issue.severity === \"error\" ? \"error  \" : \"warning\"} ${issue.message}`);\n      if (issue.hint) lines.push(`            ${issue.hint}`);\n    }\n  }\n  for (const issue of report.issues.filter(\n    (candidate) => !report.owners.some((owner) => owner.name === candidate.owner),\n  )) {\n    lines.push(`✗ ${issue.owner}: ${issue.message}`);\n  }\n  const errors = report.issues.filter((issue) => issue.severity === \"error\").length;\n  const warnings = report.issues.length - errors;\n  lines.push(\"\", `${errors} error(s), ${warnings} warning(s)`);\n  return lines.join(\"\\n\");\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\n// Media types worth a compressor pass, listed the way nginx and CDN configs do\n// it: an allowlist. A denylist fails open, so a png, mp4, zip, xlsx or woff2\n// response was piped through brotli for a byte count it cannot improve, and any\n// newly minted binary type would keep doing that until someone remembered to\n// deny it. Everything here is either plain text or a container of uncompressed\n// bytes.\nconst COMPRESSIBLE_MEDIA_TYPES = new Set([\n  \"application/javascript\",\n  \"application/json\",\n  \"application/ndjson\",\n  \"application/wasm\",\n  \"application/x-ndjson\",\n  \"application/xml\",\n  // Font formats that store raw glyph tables. `font/woff` and `font/woff2` are\n  // deliberately absent: their payloads are already deflate and brotli streams.\n  \"application/vnd.ms-fontobject\",\n  \"font/otf\",\n  \"font/ttf\",\n]);\n\n// Structured syntax suffixes (RFC 6839), so `image/svg+xml`,\n// `application/atom+xml`, `application/manifest+json`,\n// `application/problem+json` and friends compress without being enumerated.\nconst COMPRESSIBLE_MEDIA_TYPE_SUFFIXES = [\"+json\", \"+xml\"];\n\nfunction isCompressibleMediaType(mediaType: string | undefined): boolean {\n  // A missing or empty content-type says nothing about the bytes, and an\n  // undeclared body is as likely to be an opaque download as it is to be text,\n  // so it stays untouched: guessing wrong spends a whole compressor pass on\n  // bytes that are already compressed. A route that wants its body compressed\n  // only has to declare what it returns.\n  if (!mediaType) return false;\n\n  // Kept as an explicit skip even though the allowlist already excludes it: an\n  // event stream is a long-lived pipe whose delivery unit is the event, not the\n  // chunk, so putting a compressor in front of it makes timely delivery depend\n  // on flush behavior for no size win. Leaving it out of the pipeline entirely\n  // is the honest contract, and naming it here keeps that reasoning attached to\n  // the decision if the allowlist ever grows a `text/*` exception.\n  if (mediaType === \"text/event-stream\") return false;\n\n  // text/html, text/css, text/plain, text/javascript, text/x-component, and the\n  // rest of text/* are all worth compressing.\n  if (mediaType.startsWith(\"text/\")) return true;\n  if (COMPRESSIBLE_MEDIA_TYPES.has(mediaType)) return true;\n  return COMPRESSIBLE_MEDIA_TYPE_SUFFIXES.some((suffix) => mediaType.endsWith(suffix));\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 isCompressibleMediaType(mediaType);\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  // Both compressors must flush per chunk. Without an explicit flush mode brotli\n  // buffers until its 4 MB window fills or the source ends, so a streaming SSR,\n  // RSC, or NDJSON response delivers nothing to the client until it completes -\n  // and `selectEncoding` prefers brotli on every tie, so that is the default\n  // path for an ordinary browser.\n  const compressor =\n    encoding === \"br\"\n      ? createBrotliCompress({\n          flush: constants.BROTLI_OPERATION_FLUSH,\n          // Dynamic responses need bounded compression work. Node defaults to\n          // quality 11, spending substantially more CPU for a small size gain.\n          params: { [constants.BROTLI_PARAM_QUALITY]: 5 },\n        })\n      : 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\n/** @internal Applies Farm's production response compression contract. */\nexport function compressFarmResponse(request: Request, response: Response): Response {\n  if (!isCompressionEligible(request, response)) return response;\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\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) return;\n        return compressFarmResponse(request, response);\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 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\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 aliasesByTarget = new Map<string, Set<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 pendingMetadataSweeps = new Set<string>();\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 = FarmClientDataCache.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.applyInvalidation(key, Date.now(), false),\n        );\n      }\n    }\n  }\n\n  // This closure must only capture a weak reference, never the cache itself.\n  private static subscribeWeakCache(reference: WeakRef<FarmClientDataCache>): () => void {\n    const unsubscribe = subscribeFarmCacheInvalidation((key) => {\n      const cache = reference.deref();\n      if (cache) cache.applyInvalidation(key, Date.now(), false);\n      else dispose();\n    });\n    function dispose() {\n      unsubscribe();\n      cacheFinalizer?.unregister(reference);\n    }\n    return dispose;\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      // Match the scheduled sweep: fetching entries still own live work and\n      // are replaced when that work settles. Do not return their expired data.\n      if (entry.fetching) return undefined;\n      this.entries.delete(resolved);\n      this.persistence?.onDelete(resolved);\n      this.sweepEntryMetadata(new Set([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    this.pendingMetadataSweeps.delete(resolved);\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    // Match expiry cleanup, retaining aliases/marks only while a live owner\n    // needs them. A no-op delete must preserve invalidation before first set.\n    if (deleted || this.pendingMetadataSweeps.has(resolved)) {\n      this.sweepEntryMetadata(new Set([resolved]));\n    }\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.aliasesByTarget.clear();\n    this.invalidatedAt.clear();\n    this.inflight.clear();\n    this.pendingMetadataSweeps.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    // Explicit invalidation can precede a set/alias; preserve that contract.\n    this.applyInvalidation(key, now, true);\n  }\n\n  private applyInvalidation(key: string, now: number, retainUnowned: boolean): void {\n    const resolved = this.resolveKey(key);\n    for (const keys of invalidationTrackers.get(this) ?? []) keys.add(resolved);\n    const entry = this.entries.get(resolved);\n    const alreadyRetained = this.invalidatedAt.has(resolved);\n    // Broadcasts reach every cache, including caches which have never used the\n    // key. Late-discovered response keys are already tracked per request above.\n    // Retain shared timestamps only while the cache actually owns the key.\n    if (retainUnowned || entry || alreadyRetained || this.hasMetadataOwner(resolved)) {\n      this.invalidatedAt.set(resolved, now);\n      if (!entry && !retainUnowned && !alreadyRetained) this.pendingMetadataSweeps.add(resolved);\n    }\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  private hasMetadataOwner(key: string): boolean {\n    const related = new Set([key]);\n    for (const target of related) {\n      if (this.listeners.has(target) || this.inflight.has(target)) return true;\n      for (const alias of this.aliasesByTarget.get(target) ?? []) related.add(alias);\n    }\n    return false;\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    if (this.pendingMetadataSweeps.delete(alias) && !this.entries.has(resolved)) {\n      this.pendingMetadataSweeps.add(resolved);\n    }\n    const previousTarget = this.aliases.get(alias);\n    if (previousTarget !== resolved) {\n      const previousResolved =\n        previousTarget !== undefined && this.pendingMetadataSweeps.size > 0\n          ? this.resolveKey(alias)\n          : undefined;\n      this.removeAlias(alias);\n      this.aliases.set(alias, resolved);\n      let aliases = this.aliasesByTarget.get(resolved);\n      if (!aliases) this.aliasesByTarget.set(resolved, (aliases = new Set()));\n      aliases.add(alias);\n      // Retargeting can release the last owner of a previously expired target.\n      if (previousResolved !== undefined) this.sweepPendingEntryMetadata(previousResolved);\n    }\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        this.sweepPendingEntryMetadata(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    const resolved = this.resolveKey(key);\n    if (this.inflight.delete(resolved)) this.sweepPendingEntryMetadata(resolved);\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    const protectedKeys = new Set<string>();\n    // A lazy read usually evicts one key. Do not rescan every unrelated live\n    // subscription/request for each expired entry; follow its reverse aliases.\n    for (const key of swept) if (this.hasMetadataOwner(key)) protectedKeys.add(key);\n\n    for (const key of swept) {\n      if (this.entries.has(key)) {\n        this.pendingMetadataSweeps.delete(key);\n      } else if (protectedKeys.has(key)) {\n        this.pendingMetadataSweeps.add(key);\n      } else {\n        this.pendingMetadataSweeps.delete(key);\n        this.invalidatedAt.delete(key);\n      }\n    }\n\n    // Walk only the reverse edges owned by swept targets, including aliases\n    // of aliases. Discover the complete chain before deleting any edge.\n    const related = new Set<string>();\n    const targets = new Set(swept);\n    for (const target of targets) {\n      for (const alias of this.aliasesByTarget.get(target) ?? []) {\n        related.add(alias);\n        targets.add(alias);\n      }\n    }\n    const removable: string[] = [];\n    for (const alias of related) {\n      // Keep any alias that is still addressable: one that has its own entry,\n      // that something is subscribed to, that owns in-flight work, or whose\n      // target is still live.\n      if (this.entries.has(alias) || this.listeners.has(alias) || this.inflight.has(alias))\n        continue;\n      const resolved = this.resolveKey(alias);\n      if (!swept.has(resolved)) continue;\n      if (this.entries.has(resolved) || protectedKeys.has(resolved)) continue;\n      removable.push(alias);\n    }\n    for (const alias of removable) {\n      this.removeAlias(alias);\n      this.invalidatedAt.delete(alias);\n    }\n  }\n\n  private removeAlias(alias: string): void {\n    const target = this.aliases.get(alias);\n    if (target === undefined) return;\n    this.aliases.delete(alias);\n    const aliases = this.aliasesByTarget.get(target);\n    aliases?.delete(alias);\n    if (aliases?.size === 0) this.aliasesByTarget.delete(target);\n  }\n\n  private sweepPendingEntryMetadata(key?: string): void {\n    if (this.pendingMetadataSweeps.size === 0) return;\n    // Owner releases affect one canonical key, not every pending eviction.\n    if (key !== undefined) {\n      const resolved = this.resolveKey(key);\n      if (this.pendingMetadataSweeps.has(resolved)) {\n        this.sweepEntryMetadata(new Set([resolved]));\n      }\n      return;\n    }\n    this.sweepEntryMetadata(new Set(this.pendingMetadataSweeps));\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 { resolveClientRetryCount, resolveClientRetryDelay } from \"../client-retry\";\nimport { resolveAPIRequestRuntime, type APIRequestRuntime } from \"./server-client-bridge\";\nexport type { APIRouteManifest } from \"./client-routes\";\nimport {\n  isFarmAPIStream,\n  isJSONStreamResponse,\n  readJSONStream,\n  type FarmAPIStream,\n} from \"./transport\";\n\nexport const FARM_API_ROUTE_REF_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-ref\") as any;\nexport const FARM_API_ROUTE_META_SYMBOL: unique symbol = Symbol.for(\"farm.api.route-meta\") as any;\n\nexport type APIRouteRefMetadata = {\n  path: string;\n  method: string;\n  baseURL: string;\n  sameOrigin: boolean;\n};\n\nexport type APIClientOptions = ClientLifecycleHooks & {\n  /** Generated path/method metadata required for dynamic shorthand and $params scopes. */\n  routes?: APIRouteManifest;\n  baseURL?: string;\n  headers?: ClientHeaders;\n  credentials?: RequestCredentials;\n  /** Whole-call deadline in milliseconds. 0 (default) disables it. */\n  timeoutMs?: number;\n  /** HTTP transport only; local server dispatch does not use it. */\n  fetch?: typeof globalThis.fetch;\n  cacheDefaults?: CacheOptions;\n  integrations?: IntegrationClientOptions;\n};\n\nexport type APIClientWithoutIntegrationsOptions = Omit<APIClientOptions, \"integrations\"> & {\n  integrations: false;\n};\n\nexport type ServerAPIClientOptions = {\n  integrations?: Omit<IntegrationServerClientOptions, \"isServer\">;\n};\n\nexport type ServerAPIClientWithoutIntegrationsOptions = Omit<\n  ServerAPIClientOptions,\n  \"integrations\"\n> & {\n  integrations: false;\n};\n\nexport type StatusPhase = \"idle\" | \"pending\" | \"success\" | \"error\" | \"revalidating\" | \"invalidated\";\n\nexport type StatusEvent<TData = unknown, TError = unknown> = {\n  phase: StatusPhase;\n  requestId: string;\n  method: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n  key: string;\n  input?: unknown;\n  data?: TData;\n  error?: TError;\n  isBackground?: boolean;\n  timestamp: number;\n};\n\nexport type CacheKey<TData = unknown> = string & {\n  readonly __farmCacheData?: TData;\n};\n\nexport type APIResult<TData = unknown, TError = Error> = {\n  data: TData | undefined;\n  error: TError | null;\n  key: CacheKey<TData>;\n};\n\nexport class APIClientError<\n  TCode extends string = string,\n  TData = unknown,\n  TStatus extends number = number,\n> extends Error {\n  readonly code: TCode;\n  readonly data: TData;\n  readonly status: TStatus;\n  readonly response?: Response;\n\n  constructor(\n    code: TCode,\n    data: TData,\n    options: {\n      status: TStatus;\n      message: string;\n      response?: Response;\n    },\n  ) {\n    super(options.message);\n    this.name = \"APIClientError\";\n    this.code = code;\n    this.data = data;\n    this.status = options.status;\n    this.response = options.response;\n  }\n}\n\nexport type APIClientSystemError =\n  | APIClientError<\"http_error\", unknown, number>\n  | APIClientError<\"aborted\" | \"timeout\", unknown, 0>\n  | APIClientError<\"network_error\", unknown, 0>;\n\nexport type RequestEvent = {\n  requestId: string;\n  method: StatusEvent[\"method\"];\n  key: string;\n  path: string;\n  input?: unknown;\n  attempt: number;\n  timestamp: number;\n};\n\nexport type ResponseEvent<TData = unknown, TError = Error> = {\n  requestId: string;\n  method: StatusEvent[\"method\"];\n  key: string;\n  path: string;\n  input?: unknown;\n  attempt: number;\n  timestamp: number;\n  response?: Response;\n  data?: TData;\n  error?: TError;\n  ok?: boolean;\n  status?: number;\n};\n\nexport type CachePolicy = \"cache-first\" | \"network-only\" | \"stale-while-revalidate\";\nexport type CacheScope = \"client\" | \"shared\";\n\nexport type CacheOptions = {\n  key?: FarmClientCacheKey;\n  policy?: CachePolicy;\n  /** Select client-local or public shared storage. Identity-carrying requests always stay local. */\n  scope?: CacheScope;\n  staleTime?: number;\n  gcTime?: number;\n  dedupeMs?: number;\n  /** Allow the configured client cache persistence adapter to store this read. */\n  persist?: boolean;\n};\n\nexport type RetryAttemptContext = {\n  /** Zero-based index of the attempt that just failed. */\n  attempt: number;\n  /** Upper-case HTTP method of the request. */\n  method: string;\n  /** Response status, or undefined when the request never produced a response. */\n  status?: number;\n  error: Error;\n};\n\nexport type RetryOptions = {\n  count?: number;\n  delay?: number | ((attempt: number) => number);\n  /**\n   * Decide whether a failed attempt should be retried.\n   *\n   * Defaults to transient failures of idempotent requests only: replaying a\n   * POST or PATCH whose response was lost duplicates the write it performed.\n   * Supply this to opt a specific call in or out.\n   */\n  shouldRetry?: (context: RetryAttemptContext) => boolean;\n};\n\n/**\n * Methods whose replay has the same effect as a single call, so a retry cannot\n * duplicate work: the idempotent set from RFC 9110, plus QUERY, which Farm\n * supports as a read that carries a body.\n */\nconst FARM_IDEMPOTENT_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\", \"PUT\", \"DELETE\", \"QUERY\"]);\n\n/** Statuses that represent a transient condition worth another attempt. */\nconst FARM_RETRYABLE_STATUSES = new Set([408, 425, 429]);\n\nfunction isFarmRetryableFailure(context: RetryAttemptContext): boolean {\n  // A non-idempotent request may already have been applied by the server even\n  // when the client never saw the response, so it is never retried by default.\n  if (!FARM_IDEMPOTENT_METHODS.has(context.method)) return false;\n  // No response at all: a transport failure, which is the transient case retries\n  // exist for.\n  if (context.status === undefined) return true;\n  return context.status >= 500 || FARM_RETRYABLE_STATUSES.has(context.status);\n}\n\nexport type InvalidateTarget =\n  | FarmClientCacheKey\n  | {\n      key: FarmClientCacheKey;\n    }\n  | {\n      path: string;\n      method?: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\";\n      input?: unknown;\n    }\n  | [CallableRouteRef<any>, unknown?];\n\nexport type InvalidateOptions =\n  | InvalidateTarget[]\n  | {\n      targets: InvalidateTarget[];\n      refetch?: boolean;\n    };\n\nexport type OptimisticUpdate =\n  | [CallableRouteRef<any>, unknown, (prev: any) => any]\n  | [CacheKey<any> | DefinedCacheKey<any> | string, (prev: any) => any];\n\nexport type OptimisticOptions<TUpdates extends readonly unknown[] = readonly OptimisticUpdate[]> = {\n  update: TUpdates & NormalizeOptimisticUpdates<TUpdates>;\n  rollbackOnError?: boolean;\n};\n\nexport type ClientOptions<\n  TData = unknown,\n  TError = unknown,\n  TUpdates extends readonly unknown[] = readonly OptimisticUpdate[],\n> = {\n  key?: CacheKey<TData> | FarmClientCacheKey;\n  signal?: AbortSignal;\n  /** Override the instance deadline; 0 disables it for this call. */\n  timeoutMs?: number;\n  cache?: CacheOptions;\n  retry?: RetryOptions;\n  invalidate?: InvalidateOptions;\n  optimistic?: OptimisticOptions<TUpdates>;\n  onRequest?: (event: RequestEvent) => void;\n  onResponse?: (\n    data: TData | undefined,\n    error: TError | null,\n    event: ResponseEvent<TData, TError>,\n  ) => void;\n  onSuccess?: (data: TData) => void;\n  onError?: (err: TError) => void;\n  onSettled?: (data?: TData, err?: TError | null) => void;\n  onStatus?: (event: StatusEvent<TData, TError>) => void;\n};\n\ntype AnyRouteRef = (...args: any[]) => any;\ntype RouteRef<TData = any, TInput = any> = {\n  readonly __farmRouteInput: TInput;\n  readonly __farmRouteData: TData;\n};\ntype CallableRouteRef<TData = any, TInput = any> = AnyRouteRef & RouteRef<TData, TInput>;\n\ntype InferRouteInput<TRoute> = TRoute extends { readonly __farmRouteInput: infer TInput }\n  ? TInput\n  : never;\ntype InferRouteData<TRoute> = TRoute extends { readonly __farmRouteData: infer TData }\n  ? TData\n  : never;\n\ntype NormalizeOptimisticUpdate<TUpdate> = TUpdate extends readonly [\n  infer TRoute,\n  unknown,\n  (prev: any) => any,\n]\n  ? TRoute extends RouteRef<any, any>\n    ? [\n        TRoute,\n        InferRouteInput<TRoute> | undefined,\n        (prev: InferRouteData<TRoute> | undefined) => InferRouteData<TRoute>,\n      ]\n    : never\n  : TUpdate extends readonly [infer TKey, (prev: any) => any]\n    ? TKey extends DefinedCacheKey<any, RouteDataCacheKey>\n      ? [TKey, (prev: InferCacheKeyData<TKey> | undefined) => InferCacheKeyData<TKey>]\n      : TKey extends CacheKey<infer TData>\n        ? [TKey, (prev: TData | undefined) => TData]\n        : TKey extends string\n          ? [TKey, (prev: unknown) => unknown]\n          : never\n    : never;\n\ntype NormalizeOptimisticUpdates<TUpdates extends readonly unknown[]> = {\n  [K in keyof TUpdates]: NormalizeOptimisticUpdate<TUpdates[K]>;\n};\n\ntype TypedEndpointLike = {\n  __types: {\n    body: any;\n    query: any;\n    response: any;\n    errors?: any;\n  };\n};\n\ntype Simplify<T> = {\n  [K in keyof T]: T[K];\n} & {};\n\ntype IsNever<T> = [T] extends [never] ? true : false;\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype RequiredKeys<T> = T extends object\n  ? {\n      [K in keyof T]-?: {} extends Pick<T, K> ? never : K;\n    }[keyof T]\n  : never;\n\ntype BodyInputProp<TValue> =\n  IsNever<TValue> extends true\n    ? {}\n    : IsAny<TValue> extends true\n      ? { body?: TValue }\n      : undefined extends TValue\n        ? { body?: TValue }\n        : { body: TValue };\n\nexport type APIQueryPrimitive = string | number | boolean | bigint;\nexport type APIQueryValue =\n  | APIQueryPrimitive\n  | null\n  | undefined\n  | readonly (APIQueryPrimitive | null | undefined)[];\n\ntype NormalizeAPIQueryValue<TValue> = TValue extends null | undefined\n  ? TValue\n  : TValue extends APIQueryPrimitive\n    ? TValue\n    : TValue extends readonly (infer TItem)[]\n      ? Exclude<TItem, null | undefined> extends APIQueryPrimitive\n        ? TValue\n        : never\n      : never;\n\ntype NormalizeAPIQueryInput<TValue> = TValue extends URLSearchParams\n  ? TValue\n  : TValue extends object\n    ? { [TKey in keyof TValue]: NormalizeAPIQueryValue<TValue[TKey]> }\n    : never;\n\ntype QueryInputProp<TValue> =\n  IsNever<TValue> extends true\n    ? {}\n    : IsAny<TValue> extends true\n      ? { query?: TValue }\n      : undefined extends TValue\n        ? { query?: NormalizeAPIQueryInput<TValue> }\n        : RequiredKeys<TValue> extends never\n          ? { query?: NormalizeAPIQueryInput<TValue> }\n          : { query: NormalizeAPIQueryInput<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      appendAPIQuery(url.searchParams, requestOptions.query);\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 maxRetries = resolveClientRetryCount(clientOptions?.retry?.count);\n    if (typeof clientOptions?.retry?.delay !== \"function\") {\n      resolveClientRetryDelay(clientOptions?.retry?.delay);\n    }\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        notifyClientObserver(\n          clientOptions?.onStatus,\n          [\n            {\n              phase,\n              requestId,\n              method: methodUpper,\n              key: cacheKey,\n              input,\n              timestamp: Date.now(),\n              ...payload,\n            },\n          ],\n          \"API client onStatus\",\n        );\n      };\n\n      const policy = cacheOptions?.policy ?? (cacheOptions ? \"cache-first\" : \"network-only\");\n      const staleTime = cacheOptions?.staleTime ?? 0;\n      const hasReliableDefaultCacheKey =\n        methodUpper !== \"QUERY\" || !isFormData(input?.body) || configuredCacheKey !== undefined;\n      const isCacheEnabled =\n        Boolean(cacheOptions) &&\n        (methodUpper === \"GET\" || methodUpper === \"QUERY\") &&\n        hasReliableDefaultCacheKey;\n      const needsCacheState =\n        isCacheEnabled ||\n        Boolean(clientOptions?.optimistic?.update?.length) ||\n        Boolean(clientOptions?.invalidate);\n      let requestCacheContext: string | undefined = undefined;\n      if (needsCacheState && !requestContextError) {\n        try {\n          requestCacheContext = getRequestCacheContext(\n            { headers: defaultHeaders, credentials: options.credentials },\n            input,\n            // Custom transports can inject an identity outside visible headers.\n            // Never share their cached data with other client instances.\n            httpFetch ? \"client\" : cacheOptions?.scope,\n          );\n        } catch (error) {\n          requestContextError = normalizeError(error);\n        }\n      }\n\n      let cacheState = sharedCacheState;\n      let inflightState = sharedInflightState;\n      let requestScopedState: ScopedRequestState | undefined;\n      if (requestCacheContext !== undefined) {\n        if (scopedRequestState && scopedRequestState.context !== requestCacheContext) {\n          scopedRequestState.retired = true;\n          if (scopedRequestState.inflight.size === 0) scopedRequestState.cache.dispose();\n          scopedRequestState = undefined;\n        }\n        scopedRequestState ??= {\n          context: requestCacheContext,\n          cache: new FarmClientDataCache({ subscribeToInvalidation: !transport }),\n          inflight: new Map(),\n          retired: false,\n        };\n        requestScopedState = scopedRequestState;\n        cacheState = requestScopedState.cache;\n        localCaches?.add(cacheState);\n        inflightState = requestScopedState.inflight;\n      }\n      const optimisticState = getOptimisticState(cacheState);\n\n      const entry = getValidCacheEntry(cacheState, cacheKey, now);\n      const isStale = entry ? isEntryStale(entry, now) : true;\n\n      const applyOptimisticUpdates = () => {\n        if (!clientOptions?.optimistic?.update?.length) return [] as OptimisticSnapshot[];\n\n        const snapshots = new Map<string, OptimisticSnapshot>();\n        for (const update of clientOptions.optimistic.update) {\n          const [target, targetInput, updater] =\n            update.length === 2\n              ? [update[0], undefined, update[1]]\n              : [update[0], update[1], update[2]];\n          const targetKey = resolveTargetKey(\n            routeMeta,\n            target,\n            targetInput,\n            baseURL,\n            defaultHeaders,\n            transport ? baseURL : undefined,\n          );\n          if (!targetKey) continue;\n\n          const targetEntry = getValidCacheEntry(cacheState, targetKey, now);\n          const currentEntry = cacheState.get(targetKey);\n          let stack = optimisticState.get(targetKey);\n          if (stack && !reconcileOptimisticInvalidation(cacheState, targetKey, stack)) {\n            stack = undefined;\n          }\n          if (!stack) {\n            stack = {\n              entry: targetEntry ? { ...targetEntry } : undefined,\n              layers: [],\n              renderedEntry: currentEntry,\n            };\n            optimisticState.set(targetKey, stack);\n          }\n\n          let snapshot = snapshots.get(targetKey);\n          if (!snapshot) {\n            const previousEntry = stack.layers.length === 0 ? stack.entry : stack.renderedEntry;\n            const layer: OptimisticLayer = {\n              updaters: [],\n              updatedAt: now,\n              staleAt:\n                targetEntry?.staleAt ??\n                now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),\n              gcAt:\n                targetEntry?.gcAt ??\n                getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime),\n            };\n            stack.layers.push(layer);\n            snapshot = {\n              key: targetKey,\n              stack,\n              layer,\n            };\n            snapshots.set(targetKey, snapshot);\n            snapshot.layer.updaters.push(updater);\n            const nextEntry = applyOptimisticLayer(previousEntry, {\n              ...snapshot.layer,\n              updaters: [updater],\n            });\n            storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n            continue;\n          }\n          snapshot.layer.updaters.push(updater);\n          const nextEntry = applyOptimisticLayer(stack.renderedEntry, {\n            ...snapshot.layer,\n            updaters: [updater],\n          });\n          storeOptimisticEntry(cacheState, targetKey, stack, nextEntry);\n        }\n\n        return Array.from(snapshots.values());\n      };\n\n      const rollbackOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n        if (!clientOptions?.optimistic?.rollbackOnError) return;\n        settleOptimisticUpdates(cacheState, optimisticState, snapshots, \"rollback\");\n      };\n\n      const invalidateUncommittedOptimisticUpdates = (snapshots: OptimisticSnapshot[]) => {\n        if (clientOptions?.optimistic?.rollbackOnError) return;\n        for (const key of settleOptimisticUpdates(\n          cacheState,\n          optimisticState,\n          snapshots,\n          \"invalidate\",\n        )) {\n          emitStatus(\"invalidated\", { key });\n        }\n      };\n\n      const executeNetwork = async (opts?: { isBackground?: boolean; callCallbacks?: boolean }) => {\n        const release = cancellation.hold();\n        let unsubscribeInvalidation: (() => void) | undefined;\n        let readOwners: Map<string, object> | undefined;\n        let readOwner: object | undefined;\n        const resolvedCacheKey = cacheState.resolveKey(cacheKey);\n        try {\n          const dedupeMs = cacheOptions?.dedupeMs ?? 0;\n          const inflight = inflightState.get(cacheKey);\n          const allowDedupe =\n            isCacheEnabled && dedupeMs > 0 && !cancellation.signal && !requestContextError;\n\n          if (\n            allowDedupe &&\n            inflight &&\n            !inflight.cancellable &&\n            now - inflight.startedAt < dedupeMs\n          ) {\n            emitStatus(\"pending\", { isBackground: opts?.isBackground, data: entry?.data });\n            const result = await inflight.promise;\n\n            if (result.error) {\n              emitStatus(\"error\", { error: result.error, isBackground: opts?.isBackground });\n              notifyClientObserver(options.onError, [result.error]);\n              if (opts?.callCallbacks !== false) {\n                notifyClientObserver(clientOptions?.onError, [result.error], \"API client onError\");\n              }\n            } else {\n              emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n              if (opts?.callCallbacks !== false) {\n                notifyClientObserver(\n                  clientOptions?.onSuccess,\n                  [result.data],\n                  \"API client onSuccess\",\n                );\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 shouldRetryFailure = clientOptions?.retry?.shouldRetry ?? isFarmRetryableFailure;\n            let attempt = 0;\n\n            // eslint-disable-next-line no-constant-condition\n            while (true) {\n              if (options.onRequest || clientOptions?.onRequest) {\n                const requestEvent: RequestEvent = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                };\n                notifyClientObserver(options.onRequest, [requestEvent]);\n                notifyClientObserver(\n                  clientOptions?.onRequest,\n                  [requestEvent],\n                  \"API client onRequest\",\n                );\n              }\n\n              try {\n                if (requestContextError) throw requestContextError;\n                const { response, data, decodeError } = await cancellation.run(() =>\n                  fetchClient(\n                    path,\n                    {\n                      ...input,\n                      method: methodUpper,\n                    },\n                    defaultHeaders,\n                    cancellation,\n                  ),\n                );\n\n                const error = response.ok ? null : createResponseError(response, data, decodeError);\n\n                const responseEvent: ResponseEvent<any, Error> = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                  response,\n                  data: response.ok ? data : undefined,\n                  error: error ?? undefined,\n                  ok: response.ok,\n                  status: response.status,\n                };\n\n                notifyClientObserver(options.onResponse, [\n                  response.ok ? data : undefined,\n                  error,\n                  responseEvent,\n                ]);\n                notifyResponseObserver(\n                  clientOptions?.onResponse,\n                  response.ok ? data : undefined,\n                  error,\n                  responseEvent,\n                );\n\n                if (!error) {\n                  return { data, error: null, key: cacheKey } as APIResult<any, Error>;\n                }\n\n                if (\n                  attempt >= maxRetries ||\n                  !shouldRetryFailure({\n                    attempt,\n                    method: methodUpper,\n                    status: response.status,\n                    error,\n                  })\n                ) {\n                  return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n                }\n              } catch (err: any) {\n                const error = normalizeCallError(err);\n                const responseEvent: ResponseEvent<any, Error> = {\n                  requestId,\n                  method: methodUpper,\n                  key: cacheKey,\n                  path,\n                  input,\n                  attempt,\n                  timestamp: Date.now(),\n                  error,\n                  ok: false,\n                };\n\n                notifyClientObserver(options.onResponse, [undefined, error, responseEvent]);\n                notifyResponseObserver(clientOptions?.onResponse, undefined, error, responseEvent);\n\n                if (\n                  attempt >= maxRetries ||\n                  requestContextError ||\n                  cancellation.signal?.aborted ||\n                  !shouldRetryFailure({ attempt, method: methodUpper, error })\n                ) {\n                  return { data: undefined, error, key: cacheKey } as APIResult<any, Error>;\n                }\n              }\n\n              attempt += 1;\n              const delay = resolveClientRetryDelay(\n                typeof clientOptions?.retry?.delay === \"function\"\n                  ? clientOptions.retry.delay(attempt)\n                  : clientOptions?.retry?.delay,\n              );\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                notifyClientObserver(clientOptions?.onError, [result.error], \"API client onError\");\n              }\n            } else {\n              emitStatus(\"success\", { data: result.data, isBackground: opts?.isBackground });\n              if (opts?.callCallbacks !== false) {\n                notifyClientObserver(\n                  clientOptions?.onSuccess,\n                  [result.data],\n                  \"API client onSuccess\",\n                );\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          notifyClientObserver(clientOptions?.onSuccess, [entry.data], \"API client onSuccess\");\n          notifyClientObserver(\n            clientOptions?.onSettled,\n            [entry.data, null],\n            \"API client onSettled\",\n          );\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          notifyClientObserver(clientOptions?.onSuccess, [entry.data], \"API client onSuccess\");\n          notifyClientObserver(\n            clientOptions?.onSettled,\n            [entry.data, null],\n            \"API client onSettled\",\n          );\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      notifyClientObserver(\n        clientOptions?.onSettled,\n        [result.data, result.error],\n        \"API client onSettled\",\n      );\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      // Promise resolution probes arbitrary values for a callable `then`.\n      // Route proxies are not promises; literal /then routes remain available\n      // through the leading-slash alias.\n      if (prop === \"then\") return undefined;\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 (\n        path.length === 0 &&\n        typeof prop === \"string\" &&\n        rootAliases &&\n        Object.prototype.hasOwnProperty.call(rootAliases, prop)\n      ) {\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 === \"bigint\") return `bigint:${value.toString()}`;\n  if (typeof value !== \"object\") return JSON.stringify(value);\n  if (Array.isArray(value)) {\n    return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n  }\n  if (value instanceof URLSearchParams) {\n    return `urlsearchparams:${stableStringify(Array.from(value.entries()))}`;\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 appendAPIQuery(searchParams: URLSearchParams, query: unknown): void {\n  if (query instanceof URLSearchParams) {\n    const keys = new Set(query.keys());\n    for (const key of keys) searchParams.delete(key);\n    query.forEach((value, key) => searchParams.append(key, value));\n    return;\n  }\n  if (!query || typeof query !== \"object\" || Array.isArray(query)) {\n    throw new TypeError(\"API query input must be an object or URLSearchParams.\");\n  }\n\n  for (const [key, value] of Object.entries(query)) {\n    if (value === undefined || value === null) continue;\n    searchParams.delete(key);\n    const values = Array.isArray(value) ? value : [value];\n    for (const item of values) {\n      if (item === undefined || item === null) continue;\n      if (!isAPIQueryPrimitive(item)) {\n        throw new TypeError(\n          `API query parameter \"${key}\" must be a string, number, boolean, bigint, or an array of those values.`,\n        );\n      }\n      searchParams.append(key, String(item));\n    }\n  }\n}\n\nfunction isAPIQueryPrimitive(value: unknown): value is APIQueryPrimitive {\n  return (\n    typeof value === \"string\" ||\n    typeof value === \"number\" ||\n    typeof value === \"boolean\" ||\n    typeof value === \"bigint\"\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  private readonly routes: Map<string, APIRouteManifest[number]>;\n  private readonly candidates = new Map<string, APIRouteManifest[number][]>();\n  private readonly nextSegments = new Map<string, Set<string>>();\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    // The API client owns this schema-free snapshot; app input is copied above\n    // and no mutable route table escapes the client factory.\n    const addCandidate = (path: string, route: APIRouteManifest[number]) => {\n      let candidates = this.candidates.get(path);\n      if (!candidates) this.candidates.set(path, (candidates = []));\n      candidates.push(route);\n    };\n    for (const route of this.routes.values()) {\n      addCandidate(route.path, route);\n      const segments = route.path.split(\"/\");\n      let parent = \"\";\n      for (let i = 0; i < segments.length; i++) {\n        const segment = segments[i]!;\n        if (i > 0 && parseDynamicSegment(segment)) {\n          let next = this.nextSegments.get(parent);\n          if (!next) this.nextSegments.set(parent, (next = new Set()));\n          next.add(segment);\n          if (i === segments.length - 1) addCandidate(parent, route);\n        }\n        parent = i === 0 ? segment : `${parent}/${segment}`;\n      }\n    }\n  }\n\n  bind(path: string, input: unknown): { segment: string; params: BoundRouteParams } {\n    const params = readParams(input);\n    const normalized = path.replace(/\\/$/, \"\");\n    const candidates = new Set(\n      [...(this.nextSegments.get(normalized) ?? [])].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.candidates.get(normalized) ?? []).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","const MAX_TIMER_DELAY = 2_147_483_647;\n\nexport function resolveClientRetryCount(value: number | undefined): number {\n  const count = value ?? 0;\n  if (!Number.isSafeInteger(count) || count < 0) {\n    throw new RangeError(\"retry.count must be a non-negative safe integer\");\n  }\n  return count;\n}\n\nexport function resolveClientRetryDelay(value: number | undefined): number {\n  const delay = value ?? 0;\n  if (!Number.isFinite(delay) || delay < 0 || delay > MAX_TIMER_DELAY) {\n    throw new RangeError(`retry.delay must be between 0 and ${MAX_TIMER_DELAY} milliseconds`);\n  }\n  return delay;\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          const result = _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          return Promise.resolve(result).catch((error) => {\n            console.error(\n              `[FARM] Unhandled API error while handling ${req.method || \"GET\"} ${req.url || \"/\"}:`,\n              error,\n            );\n            if (res.writableEnded) return;\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    },\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\";\nimport { SCALAR_API_REFERENCE_SCRIPT, SCALAR_API_REFERENCE_STYLES } from \"./scalar-assets\";\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  const scalar = React.useRef<{ destroy(): void } | null>(null);\n\n  React.useEffect(() => {\n    const cssLink = document.createElement(\"link\");\n    cssLink.rel = \"stylesheet\";\n    cssLink.href = SCALAR_API_REFERENCE_STYLES.url;\n    cssLink.integrity = SCALAR_API_REFERENCE_STYLES.integrity;\n    cssLink.crossOrigin = \"anonymous\";\n    document.head.appendChild(cssLink);\n\n    const script = document.createElement(\"script\");\n    script.src = SCALAR_API_REFERENCE_SCRIPT.url;\n    script.integrity = SCALAR_API_REFERENCE_SCRIPT.integrity;\n    script.crossOrigin = \"anonymous\";\n    script.onload = () => setIsLoaded(true);\n    script.onerror = () => console.error(\"Failed to load Scalar API Reference\");\n    document.head.appendChild(script);\n\n    return () => {\n      scalar.current?.destroy();\n      scalar.current = null;\n      script.remove();\n      cssLink.remove();\n    };\n  }, []);\n\n  React.useEffect(() => {\n    if (isLoaded && window.Scalar) {\n      // Initialize Scalar\n      const container = document.getElementById(\"scalar-api-reference\");\n      if (container) {\n        scalar.current?.destroy();\n        scalar.current = window.Scalar.createApiReference(container, {\n          content: 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\n    return () => {\n      scalar.current?.destroy();\n      scalar.current = null;\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    Scalar?: {\n      createApiReference(element: Element, config: Record<string, unknown>): { destroy(): void };\n    };\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","import type { Parser } from \"./parsers\";\n\nexport const PARSE_REPEATED_VALUES = Symbol(\"farm.query.parseRepeatedValues\");\n\nexport type RepeatedValueParser<T> = Parser<T> & {\n  [PARSE_REPEATED_VALUES]?: (values: readonly string[]) => T | null;\n};\n\nexport function parseQueryParameter<T>(parser: Parser<T>, values: readonly string[]): T | null {\n  const parseRepeated = (parser as RepeatedValueParser<T>)[PARSE_REPEATED_VALUES];\n  if (values.length > 1 && parseRepeated) return parseRepeated(values);\n  return parser.parse(values.length > 1 ? values.join(\",\") : (values[0] ?? \"\"));\n}\n","/**\n * Farm.js Query State Parsers\n *\n * Shared parsers that can be used in both client and server contexts\n */\n\nimport { PARSE_REPEATED_VALUES, type RepeatedValueParser } from \"./values\";\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  const parseRepeated = (values: readonly string[]) =>\n    values.map((item) => itemParser.parse(item)).filter((item) => item !== null) as T[];\n  const parser: RepeatedValueParser<T[]> = {\n    parse,\n    serialize,\n    withDefault: (defaultValue: T[]) => {\n      const parserWithDefault: RepeatedValueParser<T[]> = {\n        parse: (value: string) => parse(value) ?? defaultValue,\n        serialize,\n      };\n      if (structured) parserWithDefault[PARSE_REPEATED_VALUES] = parseRepeated;\n      return parserWithDefault;\n    },\n  };\n  if (structured) parser[PARSE_REPEATED_VALUES] = parseRepeated;\n  return parser;\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\";\nimport { parseQueryParameter } from \"./values\";\n\nexport type RouteParamsInput =\n  | Record<string, string | undefined>\n  | URLSearchParams\n  | Promise<Record<string, string | undefined> | URLSearchParams>;\n\nfunction parseParam<T>(\n  input: Record<string, string | undefined> | URLSearchParams,\n  key: string,\n  parser: Parser<T>,\n) {\n  const values = input instanceof URLSearchParams ? input.getAll(key) : [input[key] ?? \"\"];\n  return {\n    raw: values.length > 1 ? values.join(\",\") : (values[0] ?? \"\"),\n    parsed: parseQueryParameter(parser, values),\n  };\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 result = {} as { [K in keyof T]: ReturnType<T[K][\"parse\"]> };\n\n  for (const [key, parser] of Object.entries(parsers)) {\n    const { raw, parsed } = parseParam(resolved, key, parser);\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 result = {} as { [K in keyof T]: ReturnType<T[K][\"parse\"]> };\n\n  for (const [key, parser] of Object.entries(parsers)) {\n    const { raw, parsed } = parseParam(input, key, parser);\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  // A lower bound is sufficient: lazy deletion may leave it earlier than the\n  // next live expiry, which only causes an extra sweep, never a missed expiry.\n  let earliestExpiry = Infinity;\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    if (now < earliestExpiry) return;\n    earliestExpiry = Infinity;\n    for (const [key, record] of records) {\n      if (record.resetAt <= now) records.delete(key);\n      else earliestExpiry = Math.min(earliestExpiry, record.resetAt);\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        current.count++;\n        return { ...current };\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      earliestExpiry = Math.min(earliestExpiry, next.resetAt);\n      // Like get(), return a snapshot so caller mutation cannot change the\n      // stored counter or invalidate the expiration bound.\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      : `${requireRateLimitClientAddress(ctx)}:${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\n/**\n * The client address the default key generator buckets on.\n *\n * A web Request has no socket, so outside a Node server this is only known when\n * a trusted proxy supplied it. Bucketing every caller together would make one\n * client's traffic exhaust the window for everyone, so refuse instead: a rate\n * limiter that cannot tell callers apart is not enforcing anything, and failing\n * loudly is the only outcome that cannot be mistaken for working.\n */\nfunction requireRateLimitClientAddress(ctx: MiddlewareContext): string {\n  const address = ctx.request.socket?.remoteAddress;\n  if (address) return address;\n\n  throw new Error(\n    \"Rate limiting could not identify the caller: this runtime reports no client address. \" +\n      \"Set `server.trustProxy` so a proxy's x-forwarded-for is trusted, or pass a `keyGenerator` \" +\n      \"that derives the bucket from something you do have, such as a session or an API key.\",\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  matchesMiddlewareConfig,\n} from \"./production-runtime\";\n// The segments every route matcher compares against, for a runner outside core\n// that has to agree with the router about which route a request is for.\nexport { canonicalizeRequestPathSegments } from \"../utils/decode\";\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  MiddlewareModule,\n  MiddlewareResult,\n} from \"./types\";\nimport { emitFarmEvent } from \"../observability\";\nimport {\n  getFarmRedirectError,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n} from \"../navigation-errors\";\nimport { normalizeMiddlewareModule } from \"./module\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\nimport { stripFarmBasePath } from \"../base-path\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport type { ResolvedFarmServerConfig } from \"../server-http\";\nimport {\n  parseMiddlewareCookieHeader,\n  serializeMiddlewareCookie as serializeCookie,\n  serializeMiddlewareCookieDeletion,\n} from \"./cookie-header\";\nimport {\n  compileMiddlewareConfig,\n  compileMiddlewareRoute,\n  matchesMiddlewareRoute,\n  matchesMiddlewareConfig as matchesPreparedMiddlewareConfig,\n} from \"./matcher\";\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 ProductionMiddlewareRequestOptions {\n  /**\n   * The address of the peer that opened the connection, as the server adapter\n   * reports it. A web Request carries no socket, so this is the only way a\n   * built app's middleware learns the client address it already has in\n   * development. A trusted proxy's `x-forwarded-for` still takes precedence.\n   */\n  clientAddress?: string;\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  /** Middleware called notFound(): answer with the app's not-found page. */\n  notFound?: true;\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\ninterface WebResponseShimState {\n  response: Record<string, any>;\n  getResponse(method: string): 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\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, options: CookieOptions = {}): void {\n    delete this.cookies[name];\n    // Path and Domain must match the cookie that was set, or the tombstone\n    // addresses a different cookie and the original survives.\n    this.headers.appendSetCookie(serializeMiddlewareCookieDeletion(name, options));\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 findHeaderName(headers: WebResponseHeaderMap, name: string): string | undefined {\n  const normalizedName = name.toLowerCase();\n  return [...headers.keys()].find((key) => key.toLowerCase() === normalizedName);\n}\n\nfunction createResponseShim(headers: WebResponseHeaderMap): WebResponseShimState {\n  const bodyChunks: Uint8Array[] = [];\n  const encoder = new TextEncoder();\n\n  const response = {\n    headersSent: false,\n    writableEnded: false,\n    statusCode: 200,\n    statusMessage: \"\",\n    setHeader(name: string, value: string | number | readonly string[]) {\n      const existingName = findHeaderName(headers, name);\n      if (existingName) headers.delete(existingName);\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      return this;\n    },\n    getHeader(name: string) {\n      if (name.toLowerCase() === \"set-cookie\") {\n        const cookies = headers.getSetCookies();\n        return cookies.length > 0 ? [...cookies] : undefined;\n      }\n      const existingName = findHeaderName(headers, name);\n      return existingName ? headers.get(existingName) : undefined;\n    },\n    hasHeader(name: string) {\n      return name.toLowerCase() === \"set-cookie\"\n        ? headers.getSetCookies().length > 0\n        : findHeaderName(headers, name) !== undefined;\n    },\n    getHeaderNames() {\n      return [...headers.keys()].map((name) => name.toLowerCase());\n    },\n    getHeaders() {\n      return Object.fromEntries(\n        [...headers.keys()].map((name) => [name.toLowerCase(), this.getHeader(name)]),\n      );\n    },\n    removeHeader(name: string) {\n      const existingName = findHeaderName(headers, name);\n      if (existingName) headers.delete(existingName);\n    },\n    appendHeader(name: string, value: string | readonly string[]) {\n      const values = Array.isArray(value) ? value.map(String) : [String(value)];\n      if (name.toLowerCase() === \"set-cookie\") {\n        for (const item of values) headers.appendSetCookie(item);\n        return this;\n      }\n      const existing = this.getHeader(name);\n      return this.setHeader(name, existing ? `${String(existing)}, ${values.join(\", \")}` : values);\n    },\n    writeHead(\n      status: number,\n      statusMessageOrHeaders?: string | Record<string, string | number | readonly string[]>,\n      responseHeaders?: Record<string, string | number | readonly string[]>,\n    ) {\n      this.statusCode = status;\n      const nextHeaders =\n        typeof statusMessageOrHeaders === \"string\" ? responseHeaders : statusMessageOrHeaders;\n      if (typeof statusMessageOrHeaders === \"string\") {\n        this.statusMessage = statusMessageOrHeaders;\n      }\n      if (nextHeaders) {\n        for (const [key, value] of Object.entries(nextHeaders)) {\n          this.setHeader(key, value);\n        }\n      }\n      this.headersSent = true;\n      return this;\n    },\n    flushHeaders() {\n      this.headersSent = true;\n    },\n    write(\n      chunk: string | Uint8Array,\n      encodingOrCallback?: string | (() => void),\n      callback?: () => void,\n    ) {\n      bodyChunks.push(typeof chunk === \"string\" ? encoder.encode(chunk) : new Uint8Array(chunk));\n      this.headersSent = true;\n      const done = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n      done?.();\n      return true;\n    },\n    end(\n      chunk?: string | Uint8Array | (() => void),\n      encodingOrCallback?: string | (() => void),\n      callback?: () => void,\n    ) {\n      if (typeof chunk === \"string\" || chunk instanceof Uint8Array) {\n        bodyChunks.push(typeof chunk === \"string\" ? encoder.encode(chunk) : new Uint8Array(chunk));\n      }\n      this.headersSent = true;\n      this.writableEnded = true;\n      const done =\n        typeof chunk === \"function\"\n          ? chunk\n          : typeof encodingOrCallback === \"function\"\n            ? encodingOrCallback\n            : callback;\n      done?.();\n      return this;\n    },\n  };\n\n  return {\n    response,\n    getResponse(method: string) {\n      if (!response.headersSent && !response.writableEnded) return null;\n\n      const bodyLength = bodyChunks.reduce((total, chunk) => total + chunk.byteLength, 0);\n      const body = new Uint8Array(bodyLength);\n      let offset = 0;\n      for (const chunk of bodyChunks) {\n        body.set(chunk, offset);\n        offset += chunk.byteLength;\n      }\n\n      const bodyAllowed =\n        method.toUpperCase() !== \"HEAD\" &&\n        response.statusCode !== 204 &&\n        response.statusCode !== 205 &&\n        response.statusCode !== 304;\n      return new Response(bodyAllowed && bodyLength > 0 ? body : null, {\n        status: response.statusCode,\n        statusText: response.statusMessage || undefined,\n        headers: mapToHeaders(headers),\n      });\n    },\n  };\n}\n\nfunction withNodeRequestShape(\n  request: Request,\n  trustProxy: boolean,\n  clientAddress: string | undefined,\n): 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      // A web Request carries no socket, so the address comes from a trusted\n      // proxy or from the server adapter's own connection. Never invent one:\n      // reporting `127.0.0.1` used to make every visitor look like the same\n      // client, which collapsed per-client rate limiting into one shared\n      // bucket. Leave it undefined so a consumer can tell that it does not know.\n      requestWithShape.socket = { remoteAddress: forwardedFor || clientAddress || undefined };\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();\n  for (const [key, value] of headers) {\n    if (key.toLowerCase() === \"set-cookie\") continue;\n    responseHeaders.set(key, value);\n  }\n  for (const [key, value] of new Headers(init.headers)) {\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  clientAddress?: string,\n): WebMiddlewareContextState {\n  let currentRequest = withNodeRequestShape(request, trustProxy, clientAddress);\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  const responseShim = createResponseShim(headers);\n\n  const ctx = {\n    request: currentRequest as any,\n    response: responseShim.response 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(\n        new Request(nextUrl, currentRequest),\n        trustProxy,\n        clientAddress,\n      );\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 || responseShim.getResponse(currentRequest.method),\n  };\n}\n\n/**\n * Decide whether a middleware entry's `export const config` applies to a path.\n *\n * Exported so the standalone dev plugin matches exactly what the production\n * runner does instead of maintaining a parallel implementation.\n */\nexport function matchesMiddlewareConfig(\n  pathname: string,\n  config: MiddlewareConfig,\n  ctx: MiddlewareContext,\n): { matched: boolean; params?: Record<string, string> } {\n  return matchesPreparedMiddlewareConfig(pathname, config, ctx);\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    compileMiddlewareConfig(middlewareConfig);\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    if (normalized.config) compileMiddlewareConfig(normalized.config);\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  for (const entry of fileMiddleware) compileMiddlewareRoute(entry);\n  const entries = [...configMiddleware.entries, ...fileMiddleware];\n  const globalConfig = configMiddleware.globalConfig;\n  if (globalConfig) compileMiddlewareConfig(globalConfig);\n\n  return async function runProductionMiddleware(\n    request: Request,\n    requestOptions: ProductionMiddlewareRequestOptions = {},\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      requestOptions.clientAddress,\n    );\n    let ctx = contextState.ctx;\n    let currentRequest = contextState.getRequest();\n    // Match the app path page routing sees: without basePath (the locale step\n    // strips it too), so file and config middleware run beneath a basePath.\n    const initialPathname = options.i18n?.enabled\n      ? stripFarmLocaleFromPathname(ctx.pathname, options.i18n)\n      : stripFarmBasePath(ctx.pathname, options.i18n?.basePath ?? \"/\");\n    let parentData: MiddlewareContext[\"parent\"] | undefined;\n\n    if (globalConfig) {\n      const globalMatch = matchesPreparedMiddlewareConfig(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            : matchesMiddlewareRoute(initialPathname, entry),\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        ? matchesPreparedMiddlewareConfig(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          requestOptions.clientAddress,\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 || ctx.response.headersSent || ctx.response.writableEnded) {\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        // redirect() and notFound() are control flow, as they are in pages.\n        // A rewrite earlier in this middleware still decides the request.\n        currentRequest = contextState.getRequest();\n        if (isFarmRedirectError(error)) {\n          const redirect = getFarmRedirectError(error)!;\n          const response = applyProductionMiddlewareHeaders(\n            new Response(null, { status: redirect.status, headers: { Location: redirect.url } }),\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        if (isFarmNotFoundError(error)) {\n          emitFarmEvent({ type: \"middleware.shortCircuit\", ...middlewareEvent, status: 404 });\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: true,\n            notFound: true,\n          };\n        }\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 { resolveFarmI18nConfig } from \"../i18n/config\";\nimport { MiddlewareManager } from \"./manager\";\n\nexport interface FarmMiddlewarePluginOptions {\n  /** Source directory (default: `src`). */\n  srcDir?: string;\n  /** Application base path (default: `/`). */\n  basePath?: 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    const i18n = resolveFarmI18nConfig(false, {\n      root: server.config.root,\n      mode: server.config.mode === \"production\" ? \"production\" : \"development\",\n      basePath: options.basePath ?? \"/\",\n    });\n    manager = new MiddlewareManager(\n      getMiddlewareAppDirectory(server.config.root, srcDir),\n      server,\n      undefined,\n      i18n,\n    );\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  compareRouteSpecificity,\n  getRoutePatternShape,\n  type RouteSegmentSpecificity,\n} from \"./routing/specificity\";\nimport {\n  matchSegmentParts,\n  normalizePathname,\n  normalizeRoutePattern,\n  parseRoutePattern,\n  splitNormalizedPathname,\n  splitPathname,\n  type RouterSegment,\n} from \"./routing/matcher\";\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\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  const exactRoutes = new Map<string, NormalizedRouterRoute<TMeta>>();\n  for (const entry of normalizedRoutes) {\n    if (entry.segments.every((segment) => segment.type === \"static\")) {\n      const pathname = entry.segments.length\n        ? `/${entry.segments.map((segment) => encodePathSegment(segment.value)).join(\"/\")}`\n        : \"/\";\n      exactRoutes.set(pathname, entry);\n    }\n  }\n\n  return {\n    routes: normalizedRoutes.map((entry) => entry.route),\n    match(pathname) {\n      const normalizedPathname = normalizePathname(pathname);\n      const exactRoute = exactRoutes.get(normalizedPathname);\n      if (exactRoute) {\n        return {\n          route: exactRoute.route,\n          pathname: normalizedPathname,\n          params: {},\n        };\n      }\n\n      const parts = splitNormalizedPathname(normalizedPathname);\n\n      for (const entry of normalizedRoutes) {\n        const params = matchSegmentParts(entry.segments, parts);\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  const segments = parseRoutePattern(pattern);\n  const parts = splitNormalizedPathname(normalizedPathname);\n  if (matchSegmentParts(segments, parts)) return true;\n  if (options.exact !== false) return false;\n\n  if (segments.length === 0) return normalizedPathname === \"/\";\n  return matchSegmentParts(segments, parts, 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 segments = parseRoutePattern(route.path);\n  const path = normalizeRoutePattern(route.path);\n\n  return {\n    route: {\n      ...route,\n      path,\n    },\n    segments,\n    specificity: segments.map(getRouterSegmentSpecificity),\n    index,\n  };\n}\n\nfunction matchSegments(\n  segments: RouterSegment[],\n  pathname: string,\n  allowTrailingSegments = false,\n): FarmRouterParams | null {\n  return matchSegmentParts(segments, splitPathname(pathname), allowTrailingSegments);\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 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","// Shared by the public router and immutable production layout tables.\n// Keep URL normalization, validation and decoding identical across both paths.\nimport type { FarmRouterParams } from \"../router\";\nimport {\n  assertBrowserStableRoutePath,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n} from \"./specificity\";\n\nexport type RouterSegment =\n  | {\n      type: \"static\";\n      value: string;\n    }\n  | {\n      type: \"dynamic\";\n      name: string;\n      catchAll: boolean;\n      optional: boolean;\n    };\n\nexport function parseRoutePattern(pattern: string): RouterSegment[] {\n  assertBrowserStableRoutePath(pattern);\n  assertTerminalCatchAll(pattern, \"router\");\n  assertUniqueRouteParameters(pattern, \"router\");\n  return splitRoutePattern(pattern)\n    .filter((part) => !isRouteGroup(part))\n    .map((part) => {\n      const optionalCatchAll = part.match(/^\\[\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]\\]$/);\n      if (optionalCatchAll) {\n        return {\n          type: \"dynamic\",\n          name: optionalCatchAll[1],\n          catchAll: true,\n          optional: true,\n        };\n      }\n\n      const catchAll = part.match(/^\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]$/);\n      if (catchAll) {\n        return {\n          type: \"dynamic\",\n          name: catchAll[1],\n          catchAll: true,\n          optional: false,\n        };\n      }\n\n      const dynamic = part.match(/^\\[([A-Za-z0-9_$-]+)\\]$/) || part.match(/^:([A-Za-z0-9_$-]+)$/);\n      if (dynamic) {\n        return {\n          type: \"dynamic\",\n          name: dynamic[1],\n          catchAll: false,\n          optional: false,\n        };\n      }\n\n      const star = part.match(/^\\*([A-Za-z0-9_$-]+)(\\?)?$/);\n      if (star) {\n        return {\n          type: \"dynamic\",\n          name: star[1],\n          catchAll: true,\n          optional: !!star[2],\n        };\n      }\n\n      return {\n        type: \"static\",\n        value: decodePathSegment(part),\n      };\n    });\n}\n\nexport function matchSegmentParts(\n  segments: RouterSegment[],\n  parts: string[],\n  allowTrailingSegments = false,\n): FarmRouterParams | null {\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\nexport function 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\nexport function splitPathname(pathname: string) {\n  return splitNormalizedPathname(normalizePathname(pathname));\n}\n\nexport function splitNormalizedPathname(pathname: string) {\n  return pathname.split(\"/\").filter(Boolean);\n}\n\nexport function normalizeRoutePattern(value: string) {\n  let pathname = (value || \"/\").replace(/\\\\/g, \"/\").replace(/\\/+/g, \"/\");\n  if (!pathname.startsWith(\"/\")) pathname = `/${pathname}`;\n  if (pathname.length > 1) pathname = pathname.replace(/\\/+$/, \"\");\n  return pathname || \"/\";\n}\n\nfunction splitRoutePattern(pattern: string) {\n  return normalizeRoutePattern(pattern).split(\"/\").filter(Boolean);\n}\n\nfunction isRouteGroup(part: string) {\n  return part.startsWith(\"(\") && part.endsWith(\")\");\n}\n\nfunction decodePathSegment(value: string) {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return value;\n  }\n}\n","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 { RetryAttemptContext, RetryOptions } from \"./api/client\";\nimport { resolveClientRetryCount, resolveClientRetryDelay } from \"./client-retry\";\n\n/** Statuses that represent a transient condition worth another attempt. */\nconst TRANSIENT_STATUSES = new Set([408, 425, 429]);\n\n/**\n * The default filter for opted-in mutation retries. A mutation is a POST the\n * caller chose to retry despite the duplicate-write risk, so the method is\n * not the gate here - the failure class is: transport failures and transient\n * server statuses retry, while a 4xx is the server's final answer and\n * retrying it only repeats the rejection.\n */\nfunction isTransientMutationFailure(context: RetryAttemptContext): boolean {\n  if (context.status === undefined) return true;\n  return context.status >= 500 || TRANSIENT_STATUSES.has(context.status);\n}\n\nfunction readErrorStatus(error: unknown): number | undefined {\n  const status = (error as { status?: unknown })?.status;\n  return typeof status === \"number\" ? status : undefined;\n}\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, until the\n * retry filter declines the failure, or until `shouldContinue` reports that\n * the owning lifecycle was reset. `shouldRetry` receives the same attempt\n * context the API client provides; the default retries transient failures\n * only. The delay callback receives the upcoming attempt number starting at\n * 1, matching the API client. Defaults to zero retries so existing behavior\n * 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 = resolveClientRetryCount(retry?.count);\n  if (typeof retry?.delay !== \"function\") resolveClientRetryDelay(retry?.delay);\n  const shouldRetryFailure = retry?.shouldRetry ?? isTransientMutationFailure;\n  let attempt = 0;\n\n  while (true) {\n    try {\n      return await invoke();\n    } catch (error) {\n      const failure = error instanceof Error ? error : new Error(String(error));\n      if (\n        attempt >= maxRetries ||\n        !shouldContinue() ||\n        !shouldRetryFailure({\n          attempt,\n          method: \"POST\",\n          status: readErrorStatus(error),\n          error: failure,\n        })\n      ) {\n        throw error;\n      }\n\n      attempt += 1;\n      const delay = resolveClientRetryDelay(\n        typeof retry?.delay === \"function\" ? retry.delay(attempt) : retry?.delay,\n      );\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, farmServerOnlyEntriesPlugin } =\n    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      farmServerOnlyEntriesPlugin(),\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/builder\"),\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, ApplicationMetadataRouteEntry } from \"../routing/route-manager\";\nimport { compareRoutePatternSpecificity } from \"../routing/specificity\";\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 { findRequestBoundSourceBlockers, parseRouteRenderingDirective } from \"../ssg\";\nimport { fileURLToPath } from \"url\";\nimport { builtinModules, createRequire } from \"module\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { logger, toPosixPath, toViteModuleId } from \"../utils\";\nimport {\n  describeSuppressedAsyncHydration,\n  enforceFarmIsolatedHydrationRouteBudget,\n  getClientModuleHydrationPlan,\n  getClientModuleMetadata,\n  getFarmClientHydrationPlanOptions,\n  createMarkdownPageHydrationPlanner,\n  resolveFarmIsolatedClientHydrationMode,\n  type ClientModuleHydrationPlan,\n  type FarmClientHydrationPlanOptions,\n  type IsolatedClientBoundaryReference,\n} from \"../utils/client-component\";\nimport type { FarmIsolatedClientHydrationMode } from \"../types\";\nimport { isFarmMarkdownPageFile } from \"../app-markdown\";\nimport { resolveFarmMdxComponentsModulePath, resolveMdxConfig } from \"../app-markdown-config\";\nimport type { ProgrammaticRedirectRoute } from \"../routes\";\nimport type { NitroConfig } from \"nitro/types\";\nimport { applyFarmCspHashesToHtml } from \"../security\";\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 { generateFarmDocsAdapterClientRuntime } from \"../docs/adapter-client\";\nimport { resolveFarmDocsFontAssets, toFarmDocsPublicFontAssets } from \"../docs/fonts\";\nimport { compileFarmDocsManifest } from \"../docs/compiler\";\nimport { compileFarmDocsAdapterEdgeManifest } from \"../docs/adapter\";\nimport type { FarmDocsCompiledManifest } from \"../docs/precompiled-runtime\";\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 { getFarmPresetRuntime } from \"../deployment\";\nimport { isFarmPreviewDeploymentEnvironment } from \"../deployment-environment\";\nimport { resolveFarmInstrumentationRuntime } from \"../instrumentation-runtime\";\nimport {\n  getFarmRendererCapabilities,\n  getFarmRendererStreamingCapabilitiesForRuntime,\n  isReactRenderer,\n  loadFarmRendererVitePlugins,\n  REACT_RENDERER,\n} from \"../renderer\";\nimport { appendMiddlewareRoutePath } from \"../middleware/path\";\nimport type { FarmRenderer } from \"../renderer\";\nimport { farmPluginMayAffectRuntimePath } from \"../plugin-runtime-endpoint\";\n\n// Type alias for OutputBundle\ntype OutputBundle = Rollup.OutputBundle;\ntype FarmEsbuildOptions = TransformOptions & {\n  exclude?: unknown;\n  include?: unknown;\n  loaders?: unknown;\n  sourceMap?: unknown;\n};\ntype NitroOutputPackage = {\n  dependencies?: Record<string, string>;\n  [key: string]: unknown;\n};\ntype FarmNitroBuilder = typeof import(\"nitro/builder\");\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};\n// Derived from the route manager so new metadata route kinds cannot drift out of sync.\ntype UniversalApplicationMetadataRoute = Pick<\n  ApplicationMetadataRouteEntry,\n  \"pattern\" | \"kind\" | \"outputName\" | \"modulePath\"\n>;\ntype UniversalMiddlewareRoute = {\n  path: string;\n  filePath: string;\n};\n\nfunction preloadFarmNitroBuilder(): Promise<PromiseSettledResult<FarmNitroBuilder>> {\n  return import(\"nitro/builder\").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]);\n// Node presets trace these into the output's node_modules. A Cloudflare\n// module Worker has no node_modules, so it must bundle them instead.\nconst NITRO_REACT_RUNTIME_MODULES = new Set([\"react\", \"react-dom\", \"react-dom/server\"]);\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\nfunction resolveNitroInternalRuntimeAliases(root: string): Record<string, string> {\n  const runtimeDir = path.dirname(resolveNitroPackageEntry(root));\n  return Object.fromEntries(\n    [\"app\", \"error/hooks\", \"runtime-config\", \"shutdown\", \"task\"].map((moduleName) => [\n      `#nitro/runtime/${moduleName}`,\n      path.join(runtimeDir, \"internal\", `${moduleName}.mjs`).split(path.sep).join(\"/\"),\n    ]),\n  );\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    exportConditions: config.exportConditions,\n    inlineDynamicImports: config.inlineDynamicImports,\n    noExternals: config.noExternals,\n    node: config.node,\n    oxc: config.oxc,\n    plugins: config.plugins,\n    replace: config.replace,\n    rolldownConfig: config.rolldownConfig,\n    serverEntry: config.serverEntry,\n    sourcemap: config.sourcemap,\n    traceDeps: config.traceDeps,\n    traceOpts: config.traceOpts,\n    typescript: config.typescript,\n    unenv: config.unenv,\n    virtual: config.virtual,\n    wasm: config.wasm,\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\n/**\n * Alias that points React's server entry at a Web-stream build.\n *\n * React splits `react-dom/server` by export condition: the Node build exports\n * renderToPipeableStream, and only the Web builds export renderToReadableStream.\n * React 19 ships `./server.edge` for Workers and edge runtimes. Its\n * `./server.browser` build schedules work through a global MessageChannel,\n * which a Cloudflare Worker only exposes on recent compatibility dates, so it\n * can fail at module load. React 18 has no edge build, and its browser build\n * does not need MessageChannel.\n */\nexport function createFarmReactWebServerAlias(hasEdgeBuild: boolean) {\n  return {\n    find: /^react-dom\\/server$/,\n    replacement: hasEdgeBuild ? \"react-dom/server.edge\" : \"react-dom/server.browser\",\n  };\n}\n\n/** Whether the app's installed React DOM exports the dedicated edge server build. */\nexport function hasReactDomEdgeServerBuild(root: string): boolean {\n  try {\n    createRequire(path.join(root, \"package.json\")).resolve(\"react-dom/server.edge\");\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Whether the SSR graph must resolve React's server entry to the Web-stream\n * build instead of the Node one.\n *\n * Vite resolves the SSR graph with Node conditions, and React applications\n * bundle react-dom rather than externalizing it, so without this an edge\n * preset inlines the Node build. React 18's Node build has no\n * `renderToReadableStream`, so the edge renderer cannot stream at all; React\n * 19's Node build streams only through Node built-in polyfills.\n */\nexport function shouldAliasReactServerToWebBuild(\n  renderer: Pick<FarmRenderer, \"name\"> | undefined,\n  preset: string,\n): boolean {\n  return isReactRenderer(renderer) && getFarmPresetRuntime(preset) === \"edge\";\n}\n\nfunction isCloudflareImagePreset(preset: string): boolean {\n  return preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\";\n}\n\n/**\n * Whether the server output loads @vercel/og from node_modules. Its Node build\n * reads its wasm and default font from beside its own file, so Node presets\n * cannot inline it into a bundle, whether generated metadata images or app\n * server code imports it.\n */\nfunction shouldUseExternalMetadataImageRuntime(preset: string, usesImageRuntime: boolean): boolean {\n  return usesImageRuntime && 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: FarmEsbuildOptions,\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: FarmEsbuildOptions,\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\nfunction hasFarmPluginRoutes(config: ResolvedFarmConfig): boolean {\n  return (config.plugins || []).some((plugin) => Boolean(plugin.routes));\n}\n\nfunction farmServerRuntimePluginsMayHandlePath(\n  config: ResolvedFarmConfig,\n  pathname: string,\n): boolean {\n  return (config.plugins || []).some(\n    (plugin) =>\n      getFarmIntegrationPluginServerRuntime(plugin) !== false &&\n      farmPluginMayAffectRuntimePath(plugin, pathname),\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 */\n/** External docs adapters must explicitly publish the versioned compiler Farm\n * uses to turn their Node-backed build runtime into an edge-safe snapshot. */\nexport function assertFarmDocsRuntimeSupported(\n  config: Pick<ResolvedFarmConfig, \"docs\">,\n  preset: string,\n): void {\n  if (\n    !config.docs?.enabled ||\n    !config.docs.adapter?.server ||\n    getFarmPresetRuntime(preset) !== \"edge\" ||\n    Boolean(config.docs.adapter.edgeCompiler)\n  ) {\n    return;\n  }\n  throw new Error(\n    `The configured docs adapter (${config.docs.adapter.id}) has not declared an edge compiler, ` +\n      `but the \"${preset}\" preset deploys to an edge runtime. Set docs.adapter = false ` +\n      \"to use Farm's precompiled embedded renderer, choose a Node target, or disable docs for \" +\n      \"this deployment.\",\n  );\n}\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  assertFarmDocsRuntimeSupported(config, preset);\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 nitroBuilderResultPromise = preloadFarmNitroBuilder();\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      try {\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      } catch (retryError) {\n        if (!(retryError instanceof IncompleteClientBuildOutputError)) throw retryError;\n\n        // A second Rolldown pass can observe the same incomplete graph when a\n        // renderer or build plugin leaves process-global state behind. Keep\n        // the server/SSR bundle on the selected builder, but use Vite's\n        // compatibility Rollup path for the client rather than shipping a\n        // missing browser entry.\n        logger.warn(\"Client bundle remained incomplete; falling back to Rollup...\");\n        const rollupVite = await loadFarmProductionVite(\"rollup\");\n        await buildClient(\n          rollupVite,\n          config,\n          root,\n          srcDir,\n          clientOutputDir,\n          pageRoutes,\n          layoutRoutes,\n          routeSlots,\n          isolatedClientBoundaryModules,\n          hydrationPlanCache,\n        );\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      nitroBuilderResultPromise,\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  options: FarmClientHydrationPlanOptions = {},\n): ClientModuleHydrationPlan {\n  const key = `${path.resolve(root)}\\0${mode}\\0${options.asyncOwnerIslands === true}\\0${path.resolve(modulePath)}`;\n  let plan = cache.get(key);\n  if (!plan) {\n    plan = getClientModuleHydrationPlan(modulePath, root, mode, options);\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, farmServerOnlyEntriesPlugin } = 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  const planOptions = getFarmClientHydrationPlanOptions(\n    config.renderer,\n    Boolean(unsupportedIntegrationProvider),\n  );\n\n  const clientLayouts = layoutRoutes.map((layout) => {\n    try {\n      const metadata = getCachedClientModuleHydrationPlan(\n        layout.modulePath,\n        root,\n        isolatedMode,\n        hydrationPlanCache,\n        planOptions,\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        asyncOwnerIslands: metadata.asyncOwnerIslands,\n        suppressedAsyncHydration: metadata.suppressedAsyncHydration,\n        fallbackReason: metadata.fallbackReason,\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        asyncOwnerIslands: undefined,\n        suppressedAsyncHydration: undefined,\n        fallbackReason: undefined,\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  const syntheticDocsEntry =\n    config.docs?.enabled && !adapterOwnsDocsRuntime ? adapterDocsEntry : null;\n  const syntheticDocsPatterns = syntheticDocsEntry\n    ? syntheticDocsEntry === \"/\"\n      ? [\"/\", \"/[...slug]\"]\n      : [syntheticDocsEntry, `${syntheticDocsEntry}/[...slug]`]\n    : [];\n\n  const markdownPagePlan = createMarkdownPageHydrationPlanner(\n    resolveFarmMdxComponentsModulePath(resolveMdxConfig(config.mdx), root),\n    root,\n    isolatedMode,\n    planOptions,\n  );\n  const routePlans = pageRoutes.map((route) => ({\n    route,\n    metadata: isFarmMarkdownPageFile(route.modulePath)\n      ? markdownPagePlan()\n      : getCachedClientModuleHydrationPlan(\n          route.modulePath,\n          root,\n          isolatedMode,\n          hydrationPlanCache,\n          planOptions,\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    [\n      ...routePlans.map(({ route, metadata }) => ({\n        pattern: route.pattern,\n        depth: route.pattern.split(\"/\").filter(Boolean).length,\n        metadata,\n      })),\n      ...syntheticDocsPatterns.map((pattern) => ({\n        pattern,\n        depth: pattern.split(\"/\").filter(Boolean).length,\n        metadata: {\n          mode: isolatedMode,\n          shouldHydrate: false,\n          islandStrategy: null,\n          legacyShouldHydrate: false,\n          legacyIslandStrategy: null,\n          estimatedIsolatedRootCount: 0,\n          hasIsolatedClientBoundaries: false,\n          isolatedBoundaries: [] as IsolatedClientBoundaryReference[],\n        },\n      })),\n    ],\n    layoutAppliesToRoute,\n  );\n\n  for (const layout of clientLayouts) {\n    const matchesBuiltRoute =\n      pageRoutes.some((route) => layoutAppliesToRoute(layout.pattern, route.pattern)) ||\n      Boolean(adapterDocsEntry && layoutAppliesToRoute(layout.pattern, adapterDocsEntry));\n    if (matchesBuiltRoute && layout.suppressedAsyncHydration) {\n      logger.warn(`⚠️  ${describeSuppressedAsyncHydration(layout.pattern, layout.fallbackReason)}`);\n    }\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          `⚠️  ${describeSuppressedAsyncHydration(route.pattern, metadata.fallbackReason)}`,\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 (syntheticDocsEntry) {\n    const docsEntry = syntheticDocsEntry;\n    const applicableClientLayouts = clientLayouts.filter(\n      (layout) =>\n        (layout.shouldHydrate || layout.hasIsolatedClientBoundaries) &&\n        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 docsClientRoutes = syntheticDocsPatterns.map((pattern) => ({\n        pattern,\n        modulePath: \"\",\n        relativePath: \"\",\n        pageShouldHydrate: false,\n        islandStrategy,\n        hasIsolatedClientBoundaries: applicableClientLayouts.some(\n          (layout) => layout.hasIsolatedClientBoundaries,\n        ),\n        isolatedBoundaries: applicableClientLayouts\n          .filter((layout) => layout.hasIsolatedClientBoundaries)\n          .flatMap((layout) => layout.isolatedBoundaries),\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 || layout.hasIsolatedClientBoundaries).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        farmServerOnlyEntriesPlugin(),\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                // A page that hydrates ships to the browser with its notFound()/redirect() calls.\n                'export { getFarmRedirectError, isFarmNotFoundError, isFarmRedirectError, notFound, permanentRedirect, redirect } 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 */\n/**\n * The X-Farm-Markdown-Source header is a diagnostic, not a filesystem\n * disclosure: production output must never bake the build machine's absolute\n * paths into every markdown response. Bake the project-relative path with\n * POSIX separators; a path outside the root falls back to its basename.\n */\nexport function toBakedMarkdownSourcePath(root: string, filePath: string | undefined): string {\n  if (!filePath) return \"\";\n  if (!path.isAbsolute(filePath)) return filePath.split(path.sep).join(\"/\");\n  const relative = path.relative(root, filePath);\n  if (!relative || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n    return path.basename(filePath);\n  }\n  return relative.split(path.sep).join(\"/\");\n}\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    redirect: \"manual\",\n  });\n  // Let a document navigation follow redirects, including cross-origin chains\n  // and fragment inheritance. Never cache/swap their HTML under the source URL.\n  if (response.type === \"opaqueredirect\" || response.redirected) {\n    const error = new Error(\"Farm navigation requires a document redirect\");\n    error.name = \"FarmNavigationRedirect\";\n    throw error;\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  // Only an HTML page can be swapped in. A feed, JSON, file, or other API\n  // response belongs to the browser, so it takes the redirect path: a document\n  // navigation that is never cached or reported as a failed navigation.\n  const contentType = (response.headers.get(\"Content-Type\") || \"\").toLowerCase();\n  if (response.ok && !contentType.includes(\"text/html\")) {\n    response.body?.cancel().catch(() => {});\n    const error = new Error(\"Farm navigation requires a document load\");\n    error.name = \"FarmNavigationRedirect\";\n    throw error;\n  }\n  return response;\n}\n\nfunction clearFarmPrefetchCacheOnDeploymentMismatch(router, error) {\n  if (error?.name === \"FarmDeploymentMismatchError\") {\n    router.clearCache();\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 prepareRuntimePageSegments(segments) {\n  const prepared = [];\n  for (const segment of segments) {\n    // Only fixed-length patterns use this path. Leave all wildcard/catch-all\n    // forms (including ambiguous spellings) to the complete backtracking matcher.\n    if (segment.includes(\"*\") || segment.startsWith(\"[...\") || segment.startsWith(\"[[...\")) {\n      return null;\n    }\n    const dynamic = segment.match(/^\\\\[(.+)\\\\]$/) || segment.match(/^:([^/]+)$/);\n    prepared.push({ literal: segment, param: dynamic ? dynamic[1] : null });\n  }\n  return prepared;\n}\n\nfunction matchPreparedRuntimePageSegments(prepared, pathnameSegments) {\n  if (prepared.length !== pathnameSegments.length) return null;\n  const params = {};\n  for (let i = 0; i < prepared.length; i++) {\n    const segment = prepared[i];\n    if (segment.param !== null) params[segment.param] = pathnameSegments[i];\n    else if (segment.literal !== pathnameSegments[i]) return null;\n  }\n  Object.defineProperty(params, farmCatchAllParamSegments, { value: {} });\n  return params;\n}\n\nfunction matchRuntimePathPattern(pattern, pathname) {\n  const patternSegments = splitRuntimePath(pattern);\n  const pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n  return matchRuntimePathSegments(patternSegments, pathnameSegments);\n}\n\nfunction matchRuntimePathSegments(patternSegments, pathnameSegments) {\n  const failedStates = new Set();\n\n  function matchFrom(patternIndex, pathIndex, params, catchAllParamSegments) {\n    const stateKey = patternIndex + \":\" + pathIndex;\n    if (failedStates.has(stateKey)) return null;\n    const matched = matchFromUncached(patternIndex, pathIndex, params, catchAllParamSegments);\n    if (!matched) failedStates.add(stateKey);\n    return matched;\n  }\n\n  function matchFromUncached(patternIndex, pathIndex, params, catchAllParamSegments) {\n    while (patternIndex < patternSegments.length) {\n      const segment = patternSegments[patternIndex];\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 required = !!(catchAll || (starCatchAll && !starCatchAll[2]));\n\n        if (patternIndex === patternSegments.length - 1) {\n          const remainingSegments = pathnameSegments.slice(pathIndex);\n          const remaining = remainingSegments.join(\"/\");\n          if (!remaining && required) return null;\n          params[name] = remaining;\n          catchAllParamSegments[name] = remainingSegments;\n          pathIndex = pathnameSegments.length;\n          patternIndex += 1;\n          continue;\n        }\n\n        const maxConsume = pathnameSegments.length - pathIndex;\n        const minConsume = required ? 1 : 0;\n        for (let consume = maxConsume; consume >= minConsume; consume--) {\n          const trialParams = Object.assign({}, params);\n          const trialCatchAll = Object.assign({}, catchAllParamSegments);\n          // Downstream matching only needs path indexes. Defer constructing the\n          // catch-all value until a split actually matches; otherwise a long\n          // failing path repeatedly slices, decodes, and joins the same prefix.\n          trialParams[name] = \"\";\n          const matched = matchFrom(\n            patternIndex + 1,\n            pathIndex + consume,\n            trialParams,\n            trialCatchAll,\n          );\n          if (matched) {\n            const consumedSegments = pathnameSegments.slice(pathIndex, pathIndex + consume);\n            matched[name] = consumedSegments.join(\"/\");\n            matched[farmCatchAllParamSegments][name] = consumedSegments;\n            return matched;\n          }\n        }\n        return null;\n      }\n\n      const pathnameSegment = pathnameSegments[pathIndex];\n      if (pathnameSegment === undefined) return null;\n\n      if (dynamic || namedDynamic) {\n        // Segments were already decoded once at entry; decoding again here\n        // turns a literal \"%2541BC\" request into \"ABC\" and diverges from dev.\n        params[(dynamic || namedDynamic)[1]] = pathnameSegment;\n        pathIndex += 1;\n        patternIndex += 1;\n        continue;\n      }\n\n      if (segment !== pathnameSegment) return null;\n      pathIndex += 1;\n      patternIndex += 1;\n    }\n\n    if (pathIndex !== pathnameSegments.length) return null;\n    Object.defineProperty(params, farmCatchAllParamSegments, {\n      value: catchAllParamSegments,\n    });\n    return params;\n  }\n\n  return matchFrom(0, 0, {}, {});\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  pendingPrefetches: new Map(),\n  prefetchGeneration: 0,\n  prefetchObserver: null,\n  observedPrefetchLinks: new Map(),\n  viewportPrefetchQueue: [],\n  viewportPrefetchTasksByHref: new Map(),\n  viewportPrefetchTasksByElement: new Map(),\n  activeViewportPrefetches: 0,\n  scrollElements: new Map(),\n  currentPath: window.location.pathname + window.location.search,\n  currentHistoryIndex: null,\n  currentHistoryState: null,\n\n  getPrefetchObserver: function(rootMargin) {\n    if (this.prefetchObserver) return this.prefetchObserver;\n    const router = this;\n    this.prefetchObserver = new IntersectionObserver(function(entries) {\n      for (const entry of entries) {\n        if (!entry.isIntersecting) continue;\n        const element = entry.target;\n        const href = router.observedPrefetchLinks.get(element);\n        if (!href) continue;\n        router.prefetchObserver.unobserve(element);\n        router.observedPrefetchLinks.delete(element);\n        router.enqueueViewportPrefetch(element, href);\n      }\n    }, { rootMargin: rootMargin });\n    return this.prefetchObserver;\n  },\n\n  enqueueViewportPrefetch: function(element, href) {\n    let task = this.viewportPrefetchTasksByHref.get(href);\n    if (!task) {\n      task = { href: href, elements: new Set(), cancelled: false, started: false };\n      this.viewportPrefetchTasksByHref.set(href, task);\n      this.viewportPrefetchQueue.push(task);\n    }\n    task.elements.add(element);\n    this.viewportPrefetchTasksByElement.set(element, task);\n    this.drainViewportPrefetchQueue();\n  },\n\n  cancelViewportPrefetch: function(element) {\n    const task = this.viewportPrefetchTasksByElement.get(element);\n    if (!task) return;\n    this.viewportPrefetchTasksByElement.delete(element);\n    task.elements.delete(element);\n    if (task.elements.size > 0) return;\n    if (task.started) return;\n    task.cancelled = true;\n    if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n      this.viewportPrefetchTasksByHref.delete(task.href);\n    }\n  },\n\n  drainViewportPrefetchQueue: function() {\n    while (this.activeViewportPrefetches < 4 && this.viewportPrefetchQueue.length > 0) {\n      const task = this.viewportPrefetchQueue.shift();\n      if (task.cancelled || task.elements.size === 0) {\n        if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n          this.viewportPrefetchTasksByHref.delete(task.href);\n        }\n        continue;\n      }\n\n      task.started = true;\n      this.activeViewportPrefetches += 1;\n      let prefetchResult;\n      try {\n        prefetchResult = this.prefetch(task.href);\n      } catch {\n        prefetchResult = undefined;\n      }\n      Promise.resolve(prefetchResult)\n        .catch(() => undefined)\n        .finally(() => {\n          if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n            this.viewportPrefetchTasksByHref.delete(task.href);\n          }\n          for (const element of task.elements) {\n            if (this.viewportPrefetchTasksByElement.get(element) === task) {\n              this.viewportPrefetchTasksByElement.delete(element);\n            }\n          }\n          this.activeViewportPrefetches -= 1;\n          this.drainViewportPrefetchQueue();\n        });\n    }\n  },\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    for (const [key, pending] of this.pendingPrefetches) {\n      if (key === url || key.startsWith(interceptionPrefix)) {\n        pending.valid = false;\n        this.pendingPrefetches.delete(key);\n      }\n    }\n  },\n\n  clearCache: function() {\n    this.prefetchGeneration++;\n    this.prefetchCache.clear();\n    for (const pending of this.pendingPrefetches.values()) pending.valid = false;\n    this.pendingPrefetches.clear();\n  },\n\n  fetchPrefetchedDocument: async function(url, interceptFrom, fresh, recover, signal, cacheResult = true) {\n    signal?.throwIfAborted();\n    const cacheKey = interceptFrom ? url + \"\\\\nintercept:\" + interceptFrom : url;\n    if (fresh) this.clearPrefetchedPath(url);\n    const cached = fresh ? undefined : this.readFreshPrefetch(cacheKey);\n    if (cached !== undefined) return cached;\n    const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n    const pending = this.pendingPrefetches.get(cacheKey);\n    if (!fresh && pending && pending.deploymentId === deploymentId) {\n      const cancellation = createClientCancellation(signal);\n      try {\n        const html = await cancellation.run(() => pending.promise);\n        if (pending.valid && deploymentId === window.__FARM_DEPLOYMENT_ID__) return html;\n      } catch (error) {\n        if (signal?.aborted || !recover) throw error;\n        if (error?.name === \"FarmNavigationRedirect\") throw error;\n        if (error?.name === \"FarmDeploymentMismatchError\") {\n          window.location.assign(url);\n          throw error;\n        }\n        // A speculative failure must not poison a real navigation: retry it.\n      } finally {\n        cancellation.dispose();\n      }\n    }\n\n    const generation = this.prefetchGeneration;\n    // Only speculative requests have shared ownership. Ordinary navigations\n    // keep their own abort signal and cannot cancel another caller's work.\n    const record = recover ? null : { valid: true, deploymentId, promise: null };\n    const request = async () => {\n      const response = await fetchFarmNavigationDocument(url, {\n        \"Accept\": \"text/html\",\n        ...(interceptFrom ? { \"X-Farm-Intercept-From\": interceptFrom } : {}),\n      }, recover, signal);\n      if (!response.ok) throw new Error(\"Failed to fetch page\");\n      const html = await response.text();\n      if (cacheResult && !signal?.aborted && generation === this.prefetchGeneration &&\n          deploymentId === window.__FARM_DEPLOYMENT_ID__ && (!record || record.valid)) {\n        this.storePrefetchedHtml(cacheKey, html);\n      }\n      return html;\n    };\n    if (!record) return request();\n    record.promise = request().finally(() => {\n      if (this.pendingPrefetches.get(cacheKey) === record) this.pendingPrefetches.delete(cacheKey);\n    });\n    this.pendingPrefetches.set(cacheKey, record);\n    return record.promise;\n  },\n\n  // Cached documents go stale the moment a mutation lands, and a long-lived\n  // tab prefetching on hover accumulates full HTML forever - so entries have\n  // the same 30 second lifetime the development router uses, and the cache\n  // keeps at most 25 documents, evicting the oldest first.\n  readFreshPrefetch: function(cacheKey) {\n    const entry = this.prefetchCache.get(cacheKey);\n    if (!entry) return undefined;\n    if (Date.now() - entry.at > 30000) {\n      this.prefetchCache.delete(cacheKey);\n      return undefined;\n    }\n    return entry.html;\n  },\n  storePrefetchedHtml: function(cacheKey, html) {\n    this.prefetchCache.delete(cacheKey);\n    this.prefetchCache.set(cacheKey, { html: html, at: Date.now() });\n    while (this.prefetchCache.size > 25) {\n      const oldest = this.prefetchCache.keys().next().value;\n      if (oldest === undefined) break;\n      this.prefetchCache.delete(oldest);\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.href);\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.href);\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(\n    integrationProviders,\n    root,\n    renderer.componentExtensions ?? [],\n  );\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 = generateFarmDocsAdapterClientRuntime(docsAdapterReact);\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 { createClientCancellation, 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.href);\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 (error?.name === \"FarmNavigationRedirect\") {\n        this.cancelActiveNavigation();\n        if (action === \"pop\") window.location.reload();\n        else if (action === \"replace\") window.location.replace(url.href);\n        else window.location.assign(url.href);\n        return;\n      }\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    return this.fetchPrefetchedDocument(url, undefined, fresh, recover, signal, !recover);\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.href);\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.readFreshPrefetch(pathname) !== undefined) return;\n    \n    return this.fetchPage(pathname, false, false)\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    this.unobserveForPrefetch(element);\n    const observer = this.getPrefetchObserver(\"50px\");\n    this.observedPrefetchLinks.set(element, href);\n    observer.observe(element);\n  },\n\n  unobserveForPrefetch: function(element) {\n    if (this.observedPrefetchLinks.delete(element)) {\n      this.prefetchObserver?.unobserve(element);\n    }\n    this.cancelViewportPrefetch(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, createFarmServerPageBoundary, 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\n// A hydrating layout keeps a non-hydrating page as server HTML; this wrapper runs its islands.\nconst FarmServerPage = createFarmServerPageBoundary(React, 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  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 { createClientCancellation, 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 { createFarmRouter, 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];\nconst clientRouteMatcher = createFarmRouter(clientRoutes.map(function(route) {\n  return { path: route.pattern, meta: route };\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    // Same attributes as the server's page boundary, or React reports a mismatch.\n    \"data-farm-segment\": \"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(${isolatedHydrationEnabled ? \"FarmServerPage\" : '\"div\"'}, props);\n  }\n  return React.createElement(\"div\", props, pageElement);\n}\n\n// Match pathname to client route\nfunction matchRoute(pathname) {\n  const matched = clientRouteMatcher.match(getFarmRoutePathname(pathname));\n  return matched\n    ? { route: matched.route.meta, params: matched.params }\n    : 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 createMatchedHydrationRoute(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) return createFarmRouteState(pageElement, pathname, params, false);\n  if (matched.route.pageShouldHydrate) {\n    pageElement = createLayoutPageBoundary(matched.route, pageElement);\n  }\n  return createFarmRouteState(pageElement, pathname, params, true);\n}\n\nfunction createFarmRouteState(page, pathname, params, includeLayouts) {\n  const layouts = includeLayouts ? getApplicableLayouts(pathname).filter(function(layout) {\n    return Boolean(layout.Component);\n  }) : [];\n  const wrap = function(element) {\n    return wrapFarmRouteClientGraph(wrapWithIntegrationProviders(element));\n  };\n  return {\n    element: wrap(includeLayouts ? wrapWithLayouts(page, pathname, params) : page),\n    layouts,\n    page,\n    params,\n    wrap,\n  };\n}\n\nfunction hydrateFarmRoute(container, route) {\n  ${\n    isReactRenderer(renderer)\n      ? \"return hydrateRoot(container, route.element);\"\n      : \"return route.layouts.length > 0 ? hydrateRoot(container, route.element, route) : hydrateRoot(container, route.element);\"\n  }\n}\n\nfunction renderFarmRoute(root, route) {\n  if (route.layouts.length > 0 && typeof root.renderRoute === \"function\") root.renderRoute(route);\n  else root.render(route.element);\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 window.__FARM_PPR_REFRESH_PROMISE__;\n  // A PPR refresh that is still retrying must not replace DOM once hydration starts.\n  window.__FARM_PPR_HYDRATING__ = true;\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 routeState = await createMatchedHydrationRoute(\n          matched,\n          pathname,\n          searchParams,\n        );\n        if (!routeState) 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          // A navigation replaced this route before it hydrated. Like a superseded\n          // navigation, that is not a failure, so error hooks never see it.\n          if (hydrationController.signal.aborted || !container.isConnected) return;\n          if (shouldHydrate) {\n            reactRoot = hydrateFarmRoute(container, routeState);\n            reactRootContainer = container;\n            isHydrated = true;\n          } else {\n            if (!reactRoot) {\n              reactRoot = createRoot(container);\n              reactRootContainer = container;\n            }\n            renderFarmRoute(reactRoot, routeState);\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.href);\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 routeState = createFarmRouteState(\n          pageElement,\n          pathname,\n          params,\n          hasHydratableLayout(pathname),\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            renderFarmRoute(reactRoot, routeState);\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 (error?.name === \"FarmNavigationRedirect\") {\n        this.cancelActiveNavigation();\n        if (action === \"pop\") window.location.reload();\n        else if (action === \"replace\") window.location.replace(url.href);\n        else window.location.assign(url.href);\n        return;\n      }\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    return this.fetchPrefetchedDocument(url, interceptFrom, fresh, recover, signal);\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    // A full-document app owns <html>/<body> directly and therefore has no\n    // synthetic #root container. Treat each body as the navigation root so\n    // shared layout boundaries can still be reconciled without replacing the\n    // whole document (and remounting every isolated client boundary).\n    const newRoot = doc.getElementById(\"root\") || doc.body;\n    const currentRoot = document.getElementById(\"root\") || document.body;\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 routeState = await createMatchedHydrationRoute(\n        matched,\n        newPathname,\n        searchParams,\n        nextPage ? nextPage.innerHTML : \"\",\n      );\n      if (!isNavigationCurrent()) return false;\n      if (routeState) {\n        renderFarmRoute(reactRoot, routeState);\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 routeState = await createMatchedHydrationRoute(\n        matched,\n        newPathname,\n        searchParams,\n      );\n      if (!isNavigationCurrent()) return false;\n      if (routeState) {\n        reactRoot = hydrateFarmRoute(pageContainer, routeState);\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.href);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) return;\n    if (isFarmDocsPath(url.pathname)) return;\n    \n    // A prefetch warms an ordinary future navigation, which reads the bare\n    // URL key. Carrying the intercept identity here both missed every real\n    // navigation (double fetch per prefetched link) and sent\n    // X-Farm-Intercept-From, which bypasses the shared cache server-side.\n    const pathname = url.pathname + url.search;\n    if (this.readFreshPrefetch(pathname) !== undefined) return;\n    \n    return this.fetchPage(pathname, undefined, false, false)\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    this.unobserveForPrefetch(element);\n    const observer = this.getPrefetchObserver(\"50px\");\n    this.observedPrefetchLinks.set(element, href);\n    observer.observe(element);\n  },\n\n  unobserveForPrefetch: function(element) {\n    if (this.observedPrefetchLinks.delete(element)) {\n      this.prefetchObserver?.unobserve(element);\n    }\n    this.cancelViewportPrefetch(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      mode: \"production\",\n      apiBaseURL: config.api.baseURL,\n    });\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 hasPluginRoutes = hasFarmPluginRoutes(config);\n  const configModulePath =\n    hasServerRuntimeIntegrations ||\n    hasObservabilityHandler ||\n    hasMdxComponentConfig ||\n    hasMiddlewareConfig ||\n    hasRouteContextConfig ||\n    hasServerRuntimePlugins ||\n    hasPluginRoutes ||\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  const farmDocsPrecompiledManifest =\n    config.docs?.enabled && getFarmPresetRuntime(preset) === \"edge\"\n      ? config.docs.adapter?.server\n        ? await compileFarmDocsAdapterEdgeManifest(config.docs, {\n            root,\n            srcDir: config.srcDir,\n            clientEntry: FARM_CLIENT_JS_SRC_PLACEHOLDER,\n            fontStylesheetHref: \"/farm-fonts.css\",\n            globalStylesheetHref: \"/assets/globals.css\",\n          })\n        : await compileFarmDocsManifest(config.docs, {\n            root,\n            srcDir: config.srcDir,\n            clientEntry: FARM_CLIENT_JS_SRC_PLACEHOLDER,\n            fontAssets: toFarmDocsPublicFontAssets(resolveFarmDocsFontAssets(root)),\n            fontStylesheetHref: \"/farm-fonts.css\",\n            globalStylesheetHref: \"/assets/globals.css\",\n          })\n      : null;\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    farmDocsPrecompiledManifest,\n    configModulePath,\n    hasServerRuntimeIntegrations,\n    hasRuntimeIntegrationConfig,\n    hasConfiguredRuntimePlugins,\n    hasServerRuntimePlugins,\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  // Any server module may import @vercel/og, which is only known once this\n  // graph is built. Keep it external on Node presets regardless: an unused\n  // external costs nothing, and Nitro copies the package only when the bundle\n  // imports it.\n  const useExternalMetadataImageRuntime = shouldUseExternalMetadataImageRuntime(preset, true);\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: [\n          ...(shouldAliasReactServerToWebBuild(config.renderer, preset)\n            ? [createFarmReactWebServerAlias(hasReactDomEdgeServerBuild(root))]\n            : []),\n          ...Object.entries(createFarmSourceAlias(root, config.srcDir)).map(\n            ([find, replacement]) => ({ find, replacement }),\n          ),\n        ],\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 * Root paths the docs engine answers that the app serves itself, so the\n * production server leaves them to the app: /llms.txt and /llms-full.txt\n * (agent.llmsTxt, llms.ts, llms-full.ts), /sitemap.xml (sitemap.ts), and\n * /robots.txt (agent.crawlers, robots.ts). A public file needs no entry, since\n * the platform serves it before any route.\n */\nexport function getFarmAppOwnedDocsEnginePaths(\n  agent:\n    | (Pick<ResolvedFarmConfig[\"agent\"], \"llmsTxt\"> &\n        Partial<Pick<ResolvedFarmConfig[\"agent\"], \"crawlers\">>)\n    | undefined,\n  applicationMetadataRoutes: ReadonlyArray<\n    Pick<UniversalApplicationMetadataRoute, \"kind\" | \"pattern\">\n  >,\n): string[] {\n  const llmsTxt = agent?.llmsTxt;\n  const ownedByFile = (kind: UniversalApplicationMetadataRoute[\"kind\"]) =>\n    applicationMetadataRoutes.some(\n      (metadata) => metadata.kind === kind && metadata.pattern === \"/\",\n    );\n  return [\n    ...(llmsTxt?.enabled || ownedByFile(\"llms\") ? [\"/llms.txt\"] : []),\n    ...((llmsTxt?.enabled && llmsTxt.full) || ownedByFile(\"llms-full\") ? [\"/llms-full.txt\"] : []),\n    ...(ownedByFile(\"sitemap\") ? [\"/sitemap.xml\"] : []),\n    ...(agent?.crawlers?.enabled || ownedByFile(\"robots\") ? [\"/robots.txt\"] : []),\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(\n  docs: ResolvedFarmConfig[\"docs\"],\n  precompiled = false,\n): string {\n  if (!docs.enabled) return \"null\";\n\n  const baseConfig = {\n    ...docs,\n    contentDir: undefined,\n    ...(precompiled ? { configPath: undefined } : {}),\n    config: undefined,\n  };\n  const nestedConfig = {\n    ...docs.config,\n    contentDir: undefined,\n  };\n\n  if (precompiled) {\n    return JSON.stringify({\n      ...baseConfig,\n      config: nestedConfig,\n    });\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\n/**\n * Runtime source that remounts the native `auth` integration in a built server.\n *\n * `resolveConfig` turns a top-level `auth` config into `integrations.auth`, but\n * the generated production entry never calls `resolveConfig`: it rebuilds its\n * integration map by re-evaluating the raw user config module, where auth only\n * exists as `auth: true`. Without this the auth routes are absent from every\n * production build and each one 404s while dev serves them.\n *\n * The import is literal so the bundler traces `@farm.js/auth` into the server\n * output, and both pieces are empty when auth is disabled so nothing is pulled\n * in for apps that do not use it.\n */\nexport function generateNativeAuthIntegrationSource(auth: ResolvedFarmConfig[\"auth\"] | undefined): {\n  importSource: string;\n  registerSource: string;\n} {\n  if (auth?.enabled !== true) {\n    return { importSource: \"\", registerSource: \"\" };\n  }\n\n  return {\n    importSource: `import { createFarmAuthIntegration as __farmCreateAuthIntegration } from \"@farm.js/auth/internal\";`,\n    // resolveConfig rejects configuring both `auth` and `integrations.auth`,\n    // so this never overwrites a user-supplied integration.\n    registerSource: `configuredIntegrations.auth = __farmCreateAuthIntegration(${JSON.stringify(auth)}, {\n  root: process.cwd(),\n  mode: \"production\",\n});`,\n  };\n}\n\n/**\n * Runtime source that remounts the top-level `mcp` configuration in a built server.\n *\n * Production re-evaluates raw layer and application config modules instead of\n * calling `resolveConfig`, so the internal plugin created during the build is\n * not otherwise present in the runtime plugin list. The literal import keeps\n * the optional MCP package traceable for server and edge bundles while disabled\n * applications carry no import or runtime code.\n */\nexport function generateNativeMCPPluginSource(mcp: ResolvedFarmConfig[\"mcp\"] | undefined): {\n  importSource: string;\n  registerSource: string;\n  pluginSource: string;\n} {\n  if (mcp?.enabled !== true) {\n    return { importSource: \"\", registerSource: \"\", pluginSource: \"\" };\n  }\n\n  return {\n    importSource: `import { createFarmMCPPlugin as __farmCreateMCPPlugin } from \"@farm.js/mcp/internal\";`,\n    registerSource: `function __farmMCPIsPlainObject(value) {\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 __farmMergeMCPConfig(base, override) {\n  const output = { ...base };\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined) continue;\n    output[key] =\n      __farmMCPIsPlainObject(output[key]) && __farmMCPIsPlainObject(value)\n        ? __farmMergeMCPConfig(output[key], value)\n        : value;\n  }\n  return output;\n}\n\nconst farmNativeMCPConfig = farmRuntimeConfigs.reduce((merged, runtimeConfig) => {\n  const value = runtimeConfig?.mcp;\n  if (value === undefined) return merged;\n  if (value === false) return false;\n  return __farmMergeMCPConfig(merged && merged !== false ? merged : {}, value);\n}, undefined);\nconst farmNativeMCPPlugin =\n  farmNativeMCPConfig && farmNativeMCPConfig.enabled !== false\n    ? __farmCreateMCPPlugin(farmNativeMCPConfig)\n    : null;`,\n    pluginSource: `...(farmNativeMCPPlugin ? [farmNativeMCPPlugin] : []),`,\n  };\n}\n\n/**\n * Runtime source for the production entry's integration request dispatch.\n *\n * `matchLocalIntegrationRequest` stays route-only: it answers \"does this URL\n * belong to an emitted integration route\", which is what configured-rewrite\n * precedence needs. Request dispatch deliberately does not go through it.\n * Integration middleware is not route scoped (it is how `protectedRoutes`\n * guards and provider session refresh are mounted), so gating dispatch on a\n * route match let anonymous requests reach protected pages. Every request is\n * dispatched instead, exactly like the dev server runs the same middleware.\n */\nexport function generateIntegrationRequestRuntimeSource(options: {\n  hasServerRuntimeIntegrations: boolean;\n}): string {\n  return `\nfunction matchLocalIntegrationRequest(request) {\n  ${\n    options.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  ${\n    options.hasServerRuntimeIntegrations\n      ? `return dispatchIntegrationRequests(\n    serverRuntimeIntegrations,\n    {\n      config: integrationRuntimeConfig,\n      isDev: false,\n      isProd: true,\n    },\n    request,\n  );`\n      : `return { response: null, setCookies: [] };`\n  }\n}\n\n// Merge Set-Cookie values forwarded by a passthrough integration middleware\n// into the deferred header bag that every downstream response already applies.\nfunction withFarmIntegrationSetCookies(headers, cookies) {\n  if (!cookies || cookies.length === 0) return headers;\n  const merged = new Headers(headers || undefined);\n  for (const cookie of cookies) {\n    merged.append(\"set-cookie\", cookie);\n  }\n  return merged;\n}\n`;\n}\n\nexport function generateConfiguredResponseHeadersRuntimeSource(): string {\n  return `\n// Configured patterns are immutable build output. Reuse the page matcher's\n// fixed-segment preparation, retaining the complete matcher for catch-alls.\nconst preparedHeaderRoutes = configuredHeaderRoutes.map(function(route) {\n  const segments = splitRuntimePath(route.source);\n  return { headers: route.headers, segments, prepared: prepareRuntimePageSegments(segments) };\n});\n\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  if (preparedHeaderRoutes.length === 0) return response;\n  const pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n  let headers;\n  for (const headerRoute of preparedHeaderRoutes) {\n    const matched = headerRoute.prepared\n      ? matchPreparedRuntimePageSegments(headerRoute.prepared, pathnameSegments)\n      : matchRuntimePathSegments(headerRoute.segments, pathnameSegments);\n    if (!matched) 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 parseRouteRenderingDirectiveFromDisk(modulePath: string) {\n  try {\n    const source = readFileSync(modulePath, \"utf8\");\n    const directive = parseRouteRenderingDirective(source);\n    // The runtime only sees module exports, so whether this route reads request\n    // state has to be decided here and ride the registration. Without it the\n    // runtime merge happily resolves ssg for a route the build already demoted\n    // to per-request rendering, and stamps a shared cache-control on it.\n    if (findRequestBoundSourceBlockers(source).length === 0) return directive;\n    return { ...(directive ?? { ssg: false, ppr: false, directive: \"\" }), requestBound: true };\n  } catch {\n    return undefined;\n  }\n}\n\nexport function generatePreloadResponseRuntimeSource(): string {\n  return `\n// Farm builds buffered HTML responses from strings it already holds. Remember\n// that string per body stream so the budget step can scan it without draining\n// and re-encoding the body. Header-only rebuilds (middleware and configured\n// headers) pass the same stream through and keep the entry; anything that\n// changes the body (plugins, CSP nonces, clone/tee) creates a new stream and\n// falls back to reading it, so a changed body is never paired with a stale string.\nconst farmBufferedHtml = new WeakMap();\n\nfunction rememberFarmBufferedHtml(response, html) {\n  // Only candidate-bearing documents are read back; Response.text() strips a\n  // leading BOM, so those keep the body read to preserve that behavior.\n  if (\n    typeof html === \"string\" &&\n    html.charCodeAt(0) !== 0xfeff &&\n    response.body &&\n    response.headers.get(\"x-farm-preload-buffered\") === \"1\"\n  ) {\n    farmBufferedHtml.set(response.body, html);\n  }\n  return response;\n}\n\nfunction getFarmOwnedBufferedHtml(response) {\n  const body = response.body;\n  if (!body || response.bodyUsed || body.locked) return undefined;\n  return farmBufferedHtml.get(body);\n}\n\nfunction getFarmBufferedPreloadMarker(html) {\n  // Prove eligibility while Farm still owns the complete document string.\n  // Candidate-bearing or unknown bodies must retain the full parser path.\n  // Response.text() strips a leading UTF-8 BOM; retain that legacy behavior.\n  return typeof html === \"string\" && html.charCodeAt(0) !== 0xfeff && !/\\\\bpreload\\\\b/i.test(html) ? \"none\" : \"1\";\n}\n\nasync function applyFarmPreloadBudget(response, pathname, request) {\n  let 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 bufferedMarker = headers.get(\"x-farm-preload-buffered\");\n  const hasNoHtmlPreloads = bufferedMarker === \"none\";\n  const isBuffered = bufferedMarker === \"1\" || hasNoHtmlPreloads;\n  if (!isHtml) {\n    if (!isStreaming && !isBuffered) return response;\n    headers = new Headers(headers);\n    headers.delete(\"x-farm-preload-streaming\");\n    headers.delete(\"x-farm-preload-buffered\");\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    reportFarmPreloadWarnings(managed.warnings, managed.warnings.length > 0\n      ? \"route \" + (pathname ?? getFarmRoutePathname(new URL(request.url).pathname))\n      : undefined);\n    // Unknown streams retain their body and ownership when no headers change.\n    // Empty Link values and even unrecognized internal markers still need cleanup.\n    if (!headers.has(\"x-farm-preload-streaming\") &&\n        !headers.has(\"x-farm-preload-buffered\") &&\n        (managed.value || null) === headers.get(\"Link\")) return response;\n    headers = new Headers(headers);\n    headers.delete(\"x-farm-preload-streaming\");\n    headers.delete(\"x-farm-preload-buffered\");\n    if (managed.value) headers.set(\"Link\", managed.value);\n    else headers.delete(\"Link\");\n    return new Response(response.body, {\n      status: response.status,\n      statusText: response.statusText,\n      headers,\n    });\n  }\n\n  // Keep the document/header budget semantics (including unchanged Link\n  // formatting), but do not consume and re-encode a proven preload-free body.\n  headers = new Headers(headers);\n  headers.delete(\"x-farm-preload-streaming\");\n  headers.delete(\"x-farm-preload-buffered\");\n  const ownedHtml = hasNoHtmlPreloads ? undefined : getFarmOwnedBufferedHtml(response);\n  const html = hasNoHtmlPreloads ? \"\" : (ownedHtml ?? await response.text());\n  const managed = manageFarmDocumentPreloads(html, linkHeader, farmPreloadConfig);\n  // A remembered document the budget left unchanged keeps its unread body.\n  const reusesBody = hasNoHtmlPreloads || (ownedHtml !== undefined && managed.html === html);\n  if (ownedHtml !== undefined && !reusesBody) response.body?.cancel().catch(() => {});\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, managed.warnings.length > 0\n    ? \"route \" + (pathname ?? getFarmRoutePathname(new URL(request.url).pathname))\n    : undefined);\n  return new Response(reusesBody ? response.body : managed.html, {\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  farmDocsPrecompiledManifest: FarmDocsCompiledManifest | null,\n  configModulePath: string | null,\n  hasServerRuntimeIntegrations: boolean,\n  hasRuntimeIntegrationConfig: boolean,\n  hasConfiguredRuntimePlugins: boolean,\n  hasServerRuntimePlugins: boolean,\n  preset: string,\n  i18nCatalogs: FarmI18nCatalogs,\n  isolatedClientBoundaryModules: ReadonlySet<string>,\n  hydrationPlanCache: Map<string, ClientModuleHydrationPlan>,\n): string {\n  const hasCompressionRuntime =\n    config.compress && resolveFarmInstrumentationRuntime(preset) === \"nodejs\";\n  // agent.crawlers serves /robots.txt unless a root robots.ts owns it.\n  const servesAgentRobotsTxt =\n    Boolean(config.agent?.crawlers?.enabled) &&\n    !applicationMetadataRoutes.some(\n      (metadata) => metadata.kind === \"robots\" && metadata.pattern === \"/\",\n    );\n  const hasPluginRuntime = hasRuntimeIntegrationConfig || hasServerRuntimePlugins;\n  const hasPrecompiledDocs = Boolean(farmDocsPrecompiledManifest);\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 rendererStreamingCapabilities = getFarmRendererStreamingCapabilitiesForRuntime(\n    config.renderer,\n    getFarmPresetRuntime(preset),\n  );\n  const rendererServerImports = isReactRenderer(config.renderer)\n    ? `import * as React from \"react\";\\nimport * as ReactDOMServer from \"react-dom/server\";${\n        hasIsolatedClientGraphRuntime\n          ? '\\nimport { isolateFarmServerPageGraph, 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\n// A hydrating layout keeps a page that does not hydrate as server HTML, so the page's client\n// components render as their own islands instead of joining the layout's React tree.\nfunction isolateFarmRouteServerPage(element) {\n  return isolateFarmServerPageGraph(React, element);\n}`\n    : `function wrapFarmRouteClientGraph(element) { return element; }\n\nfunction isolateFarmRouteServerPage(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 (\n    renderedIntegrationProviders.length > 0 &&\n    !getFarmRendererCapabilities(config.renderer).functionComponents\n  ) {\n    throw new Error(\n      `Integration provider components are not supported by the \"${config.renderer.name}\" renderer.`,\n    );\n  }\n  const providerServerModules = generateFarmIntegrationProviderServerModules(\n    renderedIntegrationProviders,\n    config.root,\n    config.renderer.componentExtensions ?? [],\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 hydrationPlanOptions = getFarmClientHydrationPlanOptions(\n    config.renderer,\n    Boolean(unsupportedIntegrationProvider),\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      hydrationPlanOptions,\n    ),\n  }));\n  const markdownPagePlan = createMarkdownPageHydrationPlanner(\n    resolveFarmMdxComponentsModulePath(resolveMdxConfig(config.mdx), config.root),\n    config.root,\n    isolatedHydrationMode,\n    hydrationPlanOptions,\n  );\n  const pageHydrationPlans = new Map(\n    pageRoutes.map((route) => [\n      route.modulePath,\n      isFarmMarkdownPageFile(route.modulePath)\n        ? markdownPagePlan()\n        : getCachedClientModuleHydrationPlan(\n            route.modulePath,\n            config.root,\n            isolatedHydrationMode,\n            hydrationPlanCache,\n            hydrationPlanOptions,\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.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  // Order with the shared route-specificity contract, not a local score. An\n  // additive per-segment score is not equivalent to the segment-wise comparison\n  // the route manager and the generated client matcher use, so the two ranked\n  // some patterns differently and the same build could serve one page on first\n  // load and another after a client navigation.\n  const orderedPageRoutes = pageRoutes\n    .map((route, index) => ({ route, index }))\n    .sort((left, right) => {\n      const order = compareRoutePatternSpecificity(left.route.pattern, right.route.pattern);\n      return order || 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(toBakedMarkdownSourcePath(config.root, route.modulePath))},\n      components: farmMdxComponents,\n      config: farmMdxConfig,\n    }),\n    markdownSource: {\n      source: ${JSON.stringify(route.source ?? \"\")},\n      filePath: ${JSON.stringify(\n        toBakedMarkdownSourcePath(config.root, route.markdownSourcePath ?? route.modulePath),\n      )},\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    // Directives are parsed from source at build time; the runtime only sees\n    // module exports, so the parsed form must ride the registration for\n    // \\\"use ssg; 60\\\" routes to keep their ISR cache headers in production.\n    const renderingDirective = parseRouteRenderingDirectiveFromDisk(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      renderingDirective ? `\\n    rendering: ${JSON.stringify(renderingDirective)},` : \"\"\n    }\n    ${\n      route.source !== undefined\n        ? `markdownSource: {\n      source: ${JSON.stringify(route.source)},\n      filePath: ${JSON.stringify(toBakedMarkdownSourcePath(config.root, 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  // Prepare shared slot owners at build time. Root owners already have a\n  // constant-time check. Do not emit caching for empty or unique-owner manifests.\n  const slotOwnerCounts = new Map(routeSlots.map((slot) => [slot.ownerPattern, 0]));\n  for (const slot of routeSlots) {\n    slotOwnerCounts.set(slot.ownerPattern, (slotOwnerCounts.get(slot.ownerPattern) ?? 0) + 1);\n  }\n  const sharedSlotOwners = new Set(\n    [...slotOwnerCounts]\n      .filter(([owner, count]) => owner !== \"/\" && count > 1)\n      .map(([owner]) => owner),\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, createStaticAPIRouteMatcherAtBasePath, 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  addMetadataMarkdownAlternate,\n  appendFarmRedirectQuery,\n  applyFarmBasePath,\n  applyFarmCspNonceToResponse,\n  applyFarmPreviewRobotsTag,\n  applyFarmThemeDocument,\n  appendFarmLinkHeader,\n  applyProductionMiddlewareHeaders,\n  configureFarmCache,\n  configureFarmObservability,\n  cloneFarmRequestWithContext,\n  createDefaultErrorMarkup,\n  createFarmInstrumentationLifecycle,\n  createFarmLayoutSelector,\n  createFarmCacheKey,\n  createFarmMetadataRouteResponse,\n  createFarmAgentRobots,\n  collectFarmLlmsTxtPages,\n  createFarmDefaultLlmsTxt,\n  createFarmLlmsMarkdownReader,\n  renderFarmLlmsFullTxt,\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  manageFarmDocumentPreloads,\n  mergeRouteRenderingDirectiveConfig,\n  manageFarmLinkHeaderPreloads,\n  mergeMetadata,\n  matchesFarmIfNoneMatch,\n  normalizeRevalidatePath,\n  reportFarmPreloadWarnings,\n  renderFarmLocaleAlternateLinks,\n  renderMetadataHead,\n  resolveFarmRouteContext,\n  resolveFarmTrailingSlashRedirect,\n  resolveDefaultErrorStatus,\n  resolveFarmSecurityConfig,\n  resolveFarmInstrumentationRuntime,\n  resolveFarmPreviewDeployment,\n  resolveFarmWebRequestOrigin,\n  runWithFarmRequestSpan,\n  searchParamsToObject,\n  setFarmBasePath,\n  setFarmTrailingSlashPreference,\n  stripFarmBasePath,\n  stripFarmLocaleFromPathname,\n  withFarmRouteContext,\n  createLateNotFoundRecovery,\n  createLateRedirectRecovery,\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 compressionRuntimeImport = hasCompressionRuntime\n    ? `import { compressFarmResponse${hasPluginRuntime ? \", createCompressionPlugin\" : \"\"} } from \"@farm.js/core/internal/compression-runtime\";`\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    ? hasPrecompiledDocs\n      ? `import { createFarmDocsPrecompiledRuntime } from \"@farm.js/core/internal/docs-precompiled-runtime\";\nconst isFarmDocsAPIRequest = (requestOrPathname) => {\n  const pathname = typeof requestOrPathname === \"string\"\n    ? requestOrPathname\n    : new URL(requestOrPathname.url).pathname;\n  const apiPath = ${JSON.stringify(farmDocsPrecompiledManifest?.apiPath || \"/api/docs\")};\n  return pathname === apiPath || pathname.startsWith(apiPath + \"/\");\n};`\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 =\n    config.docs?.enabled && !hasPrecompiledDocs\n      ? `import { resolveFarmLayoutFonts } from \"@farm.js/core/font\";`\n      : \"\";\n  const docsRuntimeImport =\n    config.docs?.enabled && !hasPrecompiledDocs\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, getFarmMarkdownAlternatePath } from \"@farm.js/core/markdown\";`\n    : \"\";\n  const appMarkdownImport = hasMarkdownPages\n    ? `import { createFarmMarkdownRouteModule, createFarmMarkdownSourceResponse } from \"@farm.js/core/internal/app-markdown-runtime\";`\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  // Use the response-only module so TSX apps do not bundle the MDX compiler.\n  const markdownErrorImport = `import { FARM_MARKDOWN_CONTENT_TYPE, createFarmMarkdownErrorBody, farmRequestWantsMarkdown } from \"@farm.js/core/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        ? [\"dispatchIntegrationRequests\", \"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 nativeAuth = generateNativeAuthIntegrationSource(config.auth);\n  const nativeMCP = generateNativeMCPPluginSource(config.mcp);\n  const integrationImports = `\n${configModulePath ? `import * as FarmUserConfigModule from ${toVirtualEntryImportSpecifier(configModulePath)};` : \"\"}\n${layerConfigImports}\n${integrationRuntimeImport}\n${nativeAuth.importSource}\n${nativeMCP.importSource}\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 matchBuiltAPIRoute = createStaticAPIRouteMatcherAtBasePath(apiRoutes, farmLocalAPIBasePath);\n\nfunction matchLocalAPIRequest(request) {\n  return matchBuiltAPIRoute(new URL(request.url).pathname);\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${compressionRuntimeImport}\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 farmRendererStreamingCapabilities = ${JSON.stringify(rendererStreamingCapabilities)};\nconst farmRendererName = ${JSON.stringify(config.renderer.name)};\nconst farmRendererRuntime = ${JSON.stringify(getFarmPresetRuntime(preset))};\nconst farmRendererRuntimeStreamingCapabilities = ReactDOMServer.capabilities &&\n  ReactDOMServer.capabilities.streaming;\nif (farmRendererRuntimeStreamingCapabilities &&\n    ((farmRendererStreamingCapabilities.node && !farmRendererRuntimeStreamingCapabilities.node) ||\n     (farmRendererStreamingCapabilities.web && !farmRendererRuntimeStreamingCapabilities.web))) {\n  throw new Error(\n    \"Renderer \" + farmRendererName +\n    \" server module streaming capabilities do not satisfy the descriptor for the \" +\n    farmRendererRuntime + \" runtime.\"\n  );\n}\nif (farmRendererStreamingCapabilities.node &&\n    typeof ReactDOMServer.renderToPipeableStream !== \"function\") {\n  throw new Error(\n    \"Renderer \" + farmRendererName + \" advertises Node streaming for the \" +\n    farmRendererRuntime + \" runtime but its server module does not export \" +\n    \"renderToPipeableStream().\"\n  );\n}\nif (farmRendererStreamingCapabilities.web &&\n    typeof ReactDOMServer.renderToReadableStream !== \"function\") {\n  throw new Error(\n    \"Renderer \" + farmRendererName + \" advertises Web streaming for the \" +\n    farmRendererRuntime + \" runtime but its server module does not export \" +\n    \"renderToReadableStream().\"\n  );\n}\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);\n\nfunction FarmDefault404Page() {\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: applyFarmBasePath(\"/\", farmResolvedRuntimeConfig.basePath),\n        }, \"GO HOME\")\n      )\n    )\n  );\n}\n\n/** The app's not-found page, or Farm's, without layouts. */\nfunction createFarmNotFoundElement(pathname) {\n  const NotFoundPage = hasCustomNotFound && CustomNotFoundComponent ? CustomNotFoundComponent : FarmDefault404Page;\n  return React.createElement(NotFoundPage, { pathname: pathname });\n}\n${nativeMCP.registerSource}\n// Config middleware from layers is appended in layer order ahead of the\n// project's, the same merge development applies (mergeFarmLayerConfig).\n// Object.assign above would keep only the last config's middleware.\nconst farmMiddlewareConfig = farmRuntimeConfigs.reduce((merged, runtimeConfig) => {\n  const value = runtimeConfig?.middleware;\n  if (value === undefined) return merged;\n  if (merged === undefined) return value;\n  const toList = (entry) => (entry == null ? [] : Array.isArray(entry) ? entry : [entry]);\n  return [...toList(merged), ...toList(value)];\n}, undefined);\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}\n${nativeAuth.registerSource}\n${providerServerModules.helpers}\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  ${hasCompressionRuntime && hasPluginRuntime ? \"createCompressionPlugin(),\" : \"\"}\n  ${hasRuntimeIntegrationConfig ? \"...resolveIntegrationPlugins(serverRuntimeIntegrations),\" : \"\"}\n  ${nativeMCP.pluginSource}\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 || {}), basePath: ${JSON.stringify(config.basePath)} },\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 farmLlmsTxtConfig = ${JSON.stringify(config.agent?.llmsTxt ?? { enabled: false, include: [], exclude: [] })};\n${servesAgentRobotsTxt ? `const farmAgentCrawlers = ${JSON.stringify(config.agent.crawlers)};` : \"\"}\nconst farmMdxConfig = ${JSON.stringify({\n    ...config.mdx,\n    components: typeof config.mdx?.components === \"string\" ? config.mdx.components : undefined,\n  })};\nconst configuredFarmMdxComponents = farmUserConfig?.mdx?.components;\n${\n  config.agent?.noindexPreviews\n    ? `// agent.noindexPreviews: the runtime environment decides, falling back to the\n// environment this was built in, since Netlify exposes its deploy context only\n// to the build.\nconst farmNoindexPreview = resolveFarmPreviewDeployment(\n  globalThis.process?.env,\n  ${JSON.stringify(isFarmPreviewDeploymentEnvironment(process.env))},\n);`\n    : \"\"\n}\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)};\nconst farmSecurityConfig = resolveFarmSecurityConfig(${JSON.stringify(config.security)});\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 && !hasPrecompiledDocs\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, hasPrecompiledDocs)};\nconst farmDocsRuntimeRoot = ${hasPrecompiledDocs ? '\".\"' : `farmDocsBundledContentDir || ${JSON.stringify(config.root)}`};\nglobalThis.__FARM_DOCS_RUNTIME_CONFIG__ = {\n  root: farmDocsRuntimeRoot,\n  srcDir: ${JSON.stringify(config.srcDir)},\n  docs: farmDocsResolvedConfig,\n};\nconst farmDocsPrecompiledRuntime = ${\n    hasPrecompiledDocs\n      ? `createFarmDocsPrecompiledRuntime(${JSON.stringify(farmDocsPrecompiledManifest)})`\n      : \"null\"\n  };\nconst farmDocsHandler = ${\n    config.docs?.enabled\n      ? hasPrecompiledDocs\n        ? \"farmDocsPrecompiledRuntime.handleDocsRequest\"\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      ? hasPrecompiledDocs\n        ? \"farmDocsPrecompiledRuntime.handleAPIRequest\"\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]${\n    apiRoutes.length > 0\n      ? `, configuredPlugins, ${JSON.stringify(apiRoutes.map(({ path, methods }) => ({ path, methods })))}, { bodySizeLimit: ${JSON.stringify(config.server.bodySizeLimit)} })`\n      : \"\"\n  };\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    const segments = splitRuntimePath(route.pattern);\n    patternPageRoutes.push({ route, segments, prepared: prepareRuntimePageSegments(segments) });\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];\nconst selectApplicableLayouts = createFarmLayoutSelector(layoutRoutes);\n\nconst routeSlots = [${routeSlotRegistrations.join(\",\")}\n];\n// The slot manifest is immutable. Share the page matcher's preparation without\n// changing descriptors, owner-prefix checks, grouping, or candidate precedence.\nconst preparedRouteSlots = new Map();\nfor (const entry of routeSlots) {\n  if (entry.fallback) continue;\n  const segments = splitRuntimePath(entry.pattern);\n  preparedRouteSlots.set(entry, {\n    segments: segments,\n    prepared: prepareRuntimePageSegments(segments),\n    specificity: routeSlotSpecificity(entry),\n  });\n}\n${sharedSlotOwners.size > 0 ? `const sharedRouteSlotOwners = new Set(${JSON.stringify([...sharedSlotOwners])});` : \"\"}\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  let encoder;\n  const normalizeChunk = function(chunk) {\n    if (typeof chunk === \"string\") return (encoder ||= new TextEncoder()).encode(chunk);\n    if (chunk instanceof Uint8Array) return chunk;\n    return new Uint8Array(chunk);\n  };\n  const decodeChunks = function(chunks) {\n    const decoder = new TextDecoder();\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  // redirect()/notFound() reported while React rendered the shell (a\n  // synchronous page under a loading boundary) still decide the response:\n  // nothing has been sent, so stop instead of streaming an empty boundary.\n  const takeNavigationError = function() {\n    return streamErrors.find(function(error) {\n      return isFarmRedirectError(error) || isFarmNotFoundError(error);\n    });\n  };\n\n  if (farmRendererStreamingCapabilities.web &&\n      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    const earlyNavigationError = takeNavigationError();\n    if (earlyNavigationError) {\n      reader.cancel(earlyNavigationError).catch(function() {});\n      throw earlyNavigationError;\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 (farmRendererStreamingCapabilities.node &&\n      typeof ReactDOMServer.renderToPipeableStream === \"function\") {\n    let pipeableStream;\n    let stream;\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 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            // A synchronous render returns buffered HTML. Only allocate the\n            // bridge when streaming, before exposing that decision to callers.\n            if (decisionState === \"stream\") {\n              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            }\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    const earlyNavigationError = takeNavigationError();\n    if (earlyNavigationError) {\n      if (typeof pipeableStream.abort === \"function\") pipeableStream.abort(earlyNavigationError);\n      throw earlyNavigationError;\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          const tail = typeof suffix === \"function\" ? await suffix() : suffix;\n          controller.enqueue(encoder.encode(tail));\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 stripFarmDocumentWrappers(markup) {\n  let output = markup.replace(/^\\\\s+/, \"\");\n  const wrapper = /^<div\\\\b[^>]*style=[\"']display\\\\s*:\\\\s*contents[\"'][^>]*>/i;\n  let match;\n  while ((match = wrapper.exec(output))) {\n    output = output.slice(match[0].length).replace(/^\\\\s+/, \"\");\n  }\n  return output;\n}\n\nfunction opensFarmFullDocument(markup) {\n  const inner = stripFarmDocumentWrappers(markup);\n  return /^<!doctype/i.test(inner) || /^<html[\\\\s>]/i.test(inner);\n}\n\nfunction extractFarmFullDocument(markup) {\n  if (!opensFarmFullDocument(markup)) 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  const closeEnd = closeIndex + \"</html>\".length;\n  let document = markup.slice(start, closeEnd);\n  // Farm's segment wrappers sit outside an app-authored <html>. When React\n  // streams a suspended descendant, it closes those wrappers after </html>\n  // and then emits the reveal payload. Keep that payload inside <body> instead\n  // of discarding it with the wrapper suffix.\n  const streamedTail = markup\n    .slice(closeEnd)\n    .replace(/^(?:\\\\s*<\\\\/div>)+/i, \"\")\n    .trim();\n  if (streamedTail) {\n    document = document.replace(/<\\\\/body>/i, function() {\n      return streamedTail + \"</body>\";\n    });\n  }\n  return document;\n}\n\nfunction ensureFarmDocumentHead(markup) {\n  if (/<head[\\\\s>]/i.test(markup)) return markup;\n  return markup.replace(/<html([^>]*)>/i, function(_match, attributes) {\n    return \"<html\" + attributes + \"><head></head>\";\n  });\n}\n\nfunction createFarmErrorDocument(html, title) {\n  const escapedTitle = escapeFarmHtmlAttribute(title || \"Application Error\");\n  const fullDocument = extractFarmFullDocument(html);\n  const hasFullDocument = fullDocument !== null;\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 = ensureFarmDocumentHead(fullDocument);\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\n// The origin hreflang alternates resolve against when the route sets no\n// metadataBase. Forwarded authority counts only under server.trustProxy, the\n// same rule the development server applies.\nfunction resolveFarmI18nAlternateOrigin(request) {\n  return resolveFarmWebRequestOrigin(request, {\n    trustProxy: farmServerConfig.trustProxy === true,\n  });\n}\n\nfunction renderFarmI18nAlternateLinks(requestPath, snapshot, request, metadata) {\n  if (!snapshot || snapshot.routing === \"none\") return \"\";\n  const url = new URL(requestPath, \"http://farm.local\");\n  const routePathname = stripFarmLocaleFromPathname(url.pathname, snapshot);\n  return renderFarmLocaleAlternateLinks(routePathname, snapshot, {\n    metadataBase: metadata ? metadata.metadataBase : undefined,\n    origin: request ? resolveFarmI18nAlternateOrigin(request) : undefined,\n  });\n}\n\nfunction applyFarmI18nDocument(html, requestPath, snapshot, request, metadata) {\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, request, metadata) +\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\n${\n  servesAgentRobotsTxt\n    ? `// robots.txt from agent.crawlers, built the same way as in development.\nfunction createFarmAgentRobotsResponse(request) {\n  const rootLayout = layoutRoutes.find((layout) => layout.pattern === \"/\");\n  return createFarmMetadataRouteResponse(\n    \"robots\",\n    createFarmAgentRobots({\n      crawlers: farmAgentCrawlers,\n      sitemapPath: ${\n        applicationMetadataRoutes.some(\n          (metadata) => metadata.kind === \"sitemap\" && metadata.pattern === \"/\",\n        )\n          ? JSON.stringify(\"/sitemap.xml\")\n          : \"undefined\"\n      },\n      metadataBase: rootLayout && rootLayout.module && rootLayout.module.metadata\n        ? rootLayout.module.metadata.metadataBase\n        : undefined,\n      basePath: ${JSON.stringify(config.basePath)},\n    }),\n    {},\n    { method: request.method },\n  );\n}\n`\n    : \"\"\n}\n// Static pages and root metadata for llms.txt, built the same way as in development.\nfunction createFarmLlmsTxtContext(request, full) {\n  const origin = new URL(request.url).origin;\n  const pages = collectFarmLlmsTxtPages(\n    pageRoutes.map((route) => ({ pattern: route.pattern, metadata: route.module && route.module.metadata })),\n    {\n      origin,\n      markdown: farmMarkdownConfig,\n      include: farmLlmsTxtConfig.include,\n      exclude: farmLlmsTxtConfig.exclude,\n    },\n  );\n  const rootLayout = layoutRoutes.find((layout) => layout.pattern === \"/\");\n  return {\n    pages,\n    defaults: createFarmDefaultLlmsTxt({\n      origin,\n      pages,\n      config: farmLlmsTxtConfig,\n      rootMetadata: rootLayout && rootLayout.module && rootLayout.module.metadata,\n    }),\n    // llms-full.txt reads each page's .md mirror through this same handler,\n    // with a fresh request so the caller's cookies never shape its content.\n    // HEAD discards the body, so it reads nothing.\n    ...(full\n      ? {\n          markdown: request.method.toUpperCase() === \"HEAD\"\n            ? async () => null\n            : createFarmLlmsMarkdownReader((page) => handleFarmRequest(page)),\n        }\n      : {}),\n  };\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 isLlmsFull = match.metadata.kind === \"llms-full\";\n    const llmsContext = match.metadata.kind === \"llms\" || isLlmsFull\n      ? createFarmLlmsTxtContext(request, isLlmsFull)\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          ...llmsContext,\n        })\n      : routeModule.default;\n    const body = isLlmsFull && !(value instanceof Response)\n      ? await renderFarmLlmsFullTxt(value, { origin: url.origin, readMarkdown: llmsContext.markdown })\n      : value;\n    return createFarmMetadataRouteResponse(match.metadata.kind, body, 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: farmMiddlewareConfig,\n  modules: fileMiddlewareModules,\n  i18n: farmI18nConfig,\n  server: farmServerConfig,\n})`\n      : \"null\"\n  };\n\n${apiHandlerCode}\n\n${generateIntegrationRequestRuntimeSource({ hasServerRuntimeIntegrations })}\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  if (patternPageRoutes.length === 0) return null;\n  // The page manifest is immutable. Reuse its pattern parts and decode this\n  // request once, while each match retains its own params and backtracking state.\n  const pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n  for (const { route, segments, prepared } of patternPageRoutes) {\n    const params = prepared\n      ? matchPreparedRuntimePageSegments(prepared, pathnameSegments)\n      : matchRuntimePathSegments(segments, pathnameSegments);\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    sharedSlotOwners.size > 0\n      ? `\n  // Incoming-owner results belong only to this request. Interception checks\n  // still use their own background pathname and the complete prefix matcher.\n  const ownerMatches = new Map();\n  function matchesSlotOwner(pattern) {\n    if (!sharedRouteSlotOwners.has(pattern)) return matchesRoutePrefix(pathname, pattern);\n    let matched = ownerMatches.get(pattern);\n    if (matched === undefined) {\n      matched = matchesRoutePrefix(pathname, pattern);\n      ownerMatches.set(pattern, matched);\n    }\n    return matched;\n  }`\n      : \"\"\n  }\n  for (const slot of routeSlots) {\n    if (!${sharedSlotOwners.size > 0 ? \"matchesSlotOwner(slot.ownerPattern)\" : \"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  // Leave empty, fallback-only and ineligible requests unparsed.\n  let pathnameSegments;\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        const slot = preparedRouteSlots.get(entry);\n        if (!pathnameSegments) pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n        return {\n          entry: entry,\n          specificity: slot.specificity,\n          params: slot.prepared\n            ? matchPreparedRuntimePageSegments(slot.prepared, pathnameSegments)\n            : matchRuntimePathSegments(slot.segments, pathnameSegments),\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 right.specificity - left.specificity;\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 = selectApplicableLayouts(pathname);\n  // buildSSRInMemory already emits these immutable descriptors in stable depth\n  // order. Filtering preserves that order, including equal-depth ties.\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 resolveRouteRenderingView(route) {\n  // The same merge development uses: baked directive config under the\n  // module's explicit exports. Routes registered without either stay dynamic.\n  return mergeRouteRenderingDirectiveConfig(route && route.rendering, route && route.module, {\n    experimentalPPR: experimentalPPREnabled,\n  });\n}\n\nfunction resolvePPRConfig(route) {\n  if (!experimentalPPREnabled || !route || !route.module) {\n    return { enabled: false };\n  }\n\n  const view = resolveRouteRenderingView(route);\n  return { enabled: view.ppr, revalidate: view.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\n// origin is set when the shell carries hreflang alternates (i18n prefix\n// routing), so one host never serves a shell holding another host's URLs.\nfunction getPPRShellCacheKey(url, locale, origin) {\n  const key = [\n    \"ppr\",\n    locale || \"\",\n    normalizeRevalidatePath(url.pathname),\n    url.search,\n  ];\n  return createFarmCacheKey(origin ? key.concat(origin) : key);\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(route, pprCanCache) {\n  if (!route || !route.module) {\n    return null;\n  }\n\n  const view = resolveRouteRenderingView(route);\n  if (view.dynamic === \"force-dynamic\") {\n    return null;\n  }\n  if (!view.ssg && !pprCanCache) {\n    return null;\n  }\n\n  const revalidate =\n    typeof view.revalidate === \"number\" && view.revalidate > 0 ? view.revalidate : 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, adapterContext) {\n  // Share only this request's parse. Rewrites and middleware replacements keep\n  // their own URL, while response negotiation retains the original pathname.\n  const requestUrl = new URL(request.url);\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(\n        request,\n        farmLocaleResolution,\n        false,\n        Date.now(),\n        adapterContext,\n        requestUrl,\n      );\n      return applyFarmI18nResponse(response, farmLocaleResolution);\n    },\n    { redirect: !isFarmLocalAPIPathname(requestUrl.pathname) }\n  )`\n      : \"handleFarmRequestInContext(request, null, false, Date.now(), adapterContext, requestUrl)\"\n  };\n  ${\n    config.md?.enabled\n      ? `const pathname = getFarmRoutePathname(requestUrl.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  adapterContext,\n  requestUrl = new URL(request.url),\n) {\n  let url = requestUrl;\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            adapterContext,\n          )\n        );\n      }\n    }\n  }\n\n  if (farmImageHandler && pathname === ${JSON.stringify(config.images.path)}) {\n    const imageResponse = await farmImageHandler(request, {\n      trustedLocalOrigin: adapterContext?.trustedLocalOrigin,\n    });\n    if (imageResponse) {\n      return imageResponse;\n    }\n  }\n\n  ${\n    hasServerRuntimeIntegrations\n      ? `\n  const integrationDispatch = await handleIntegrationRequest(cloneFarmRequestWithContext(request));\n  if (integrationDispatch.response) {\n    return integrationDispatch.response;\n  }\n  // A middleware that refreshed a session and let the request continue handed\n  // its rotated Set-Cookie values back here. They belong on whatever response\n  // the page or API handler produces, so they ride the same deferred-header\n  // channel the file middleware runner already uses.\n  const farmIntegrationSetCookies = integrationDispatch.setCookies;\n  `\n      : \"\"\n  }\n\n  ${\n    hasMiddlewareRuntime\n      ? `\n  const requestBeforeMiddleware = request;\n  const middlewareResult = await farmMiddlewareRunner(request, {\n    clientAddress: adapterContext?.clientAddress,\n  });\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 = ${\n    hasServerRuntimeIntegrations\n      ? \"withFarmIntegrationSetCookies(middlewareResult.headers, farmIntegrationSetCookies)\"\n      : \"middlewareResult.headers\"\n  };\n  // A Request's url is already serialized, so an unchanged href means middleware\n  // kept the URL and the pre-middleware parse still describes it.\n  if (request.url !== url.href) {\n    url = new URL(request.url);\n    pathname = url.pathname;\n    routePathname = getFarmRoutePathname(pathname);\n  }\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    if (middlewareResult.notFound) return renderFarmNotFoundResponse();\n  `\n      : `\n  const middlewareData = undefined;\n  const middlewareContext = undefined;\n  const middlewareHeaders = ${\n    hasServerRuntimeIntegrations\n      ? \"withFarmIntegrationSetCookies(undefined, farmIntegrationSetCookies)\"\n      : \"undefined\"\n  };\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  // An app's own llms.txt, llms-full.txt, sitemap.xml, and robots.txt take\n  // those paths from the docs engine.\n  if (farmDocsHandler${(() => {\n    const owned = getFarmAppOwnedDocsEnginePaths(config.agent, applicationMetadataRoutes);\n    return owned.length\n      ? ` && !${JSON.stringify(owned)}.includes(normalizeRuntimePath(routePathname))`\n      : \"\";\n  })()}) {\n    const docsResponse = await farmDocsHandler(cloneFarmRequestWithContext(request));\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: cloneFarmRequestWithContext(request),\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      // The mirror helper only reads metadata and creates its own GET request.\n      // Cloning here needlessly tees bodies even when negotiation rejects them.\n      request,\n      // Middleware and configured rewrites have already resolved this URL.\n      requestUrl: url,\n      config: farmMarkdownConfig,\n      routeExists: (targetPathname) =>\n        Boolean(matchPageRoute(getFarmRoutePathname(targetPathname))),\n      renderPage: (targetRequest) => handleFarmRequest(targetRequest, adapterContext),\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(cloneFarmRequestWithContext(request));\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    cloneFarmRequestWithContext(request),\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    cloneFarmRequestWithContext(request),\n    routePathname\n  );\n  if (applicationMetadataResponse) {\n    return applyProductionMiddlewareHeaders(applicationMetadataResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n  ${\n    servesAgentRobotsTxt\n      ? `\n  // agent.crawlers with no robots.ts: serve the generated file.\n  if (normalizeRuntimePath(routePathname) === \"/robots.txt\") {\n    return applyProductionMiddlewareHeaders(\n      createFarmAgentRobotsResponse(request),\n      middlewareHeaders,\n    );\n  }\n  `\n      : \"\"\n  }\n  ${\n    config.agent?.llmsTxt?.enabled\n      ? `\n  // agent.llmsTxt with no llms.ts or llms-full.ts: serve the generated files.\n  const farmGeneratedLlmsKind = normalizeRuntimePath(routePathname) === \"/llms.txt\"\n    ? \"llms\"\n    : ${config.agent?.llmsTxt?.full ? `normalizeRuntimePath(routePathname) === \"/llms-full.txt\" ? \"llms-full\" : ` : \"\"}null;\n  if (farmGeneratedLlmsKind) {\n    const llmsContext = createFarmLlmsTxtContext(request, farmGeneratedLlmsKind === \"llms-full\");\n    const llmsBody = farmGeneratedLlmsKind === \"llms-full\"\n      ? await renderFarmLlmsFullTxt(llmsContext.defaults, {\n          origin: new URL(request.url).origin,\n          readMarkdown: llmsContext.markdown,\n        })\n      : llmsContext.defaults;\n    return applyProductionMiddlewareHeaders(\n      createFarmMetadataRouteResponse(\n        farmGeneratedLlmsKind,\n        llmsBody,\n        { revalidate: farmLlmsTxtConfig.revalidate },\n        { method: request.method },\n      ),\n      middlewareHeaders,\n    );\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    config.docs?.enabled\n      ? `if (farmDocsAPIHandler && isFarmDocsAPIRequest(pathname)) {\n    const docsAPIResponse = await farmDocsAPIHandler(cloneFarmRequestWithContext(request));\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);\n      const pprBypassReason = pprConfig.enabled\n        ? getPPRShellBypassReason(request, middlewareData, middlewareContext)\n        : undefined;\n      let pprCanCache = pprConfig.enabled && !pprBypassReason;\n      const pprCacheKey = pprCanCache\n        ? getPPRShellCacheKey(\n            url,\n            farmLocaleResolution?.locale,\n            farmLocaleResolution && farmI18nConfig.routing !== \"none\"\n              ? resolveFarmI18nAlternateOrigin(request)\n              : \"\"\n          )\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 rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(cachedPPRShell, {\n            status: 200,\n            headers: {\n              \"Content-Type\": \"text/html; charset=utf-8\",\n              \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(cachedPPRShell),\n              ...(farmFontPreloadHeader ? { \"Link\": farmFontPreloadHeader } : {}),\n              ...getPPRHeaders(\"hit\", pprConfig),\n            },\n          }), middlewareHeaders), cachedPPRShell);\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            } else if (shouldHydrateLayout && !route.shouldHydrate) {\n              pageElement = isolateFarmRouteServerPage(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          config.md?.enabled\n            ? `\n        // Advertise the Markdown mirror in the head as well as the Link header,\n        // using the public path the .md request will be resolved against.\n        mergedMetadata = addMetadataMarkdownAlternate(\n          mergedMetadata,\n          getFarmMarkdownAlternatePath(farmMarkdownConfig, pathname),\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, 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 initialHtml = html !== undefined ? html : renderedPage.shellHtml || \"\";\n        const hasFullDocument = opensFarmFullDocument(initialHtml);\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            async function() {\n              // A redirect()/notFound() after the 200 shell went out can only\n              // be recovered in the document.\n              const lateNavigationError = renderedPage.streamErrors.find(function(error) {\n                return isFarmRedirectError(error) || isFarmNotFoundError(error);\n              });\n              if (!lateNavigationError) return streamSuffix;\n              if (isFarmRedirectError(lateNavigationError)) {\n                return createLateRedirectRecovery(\n                  getFarmRedirectError(lateNavigationError).url\n                ) + streamSuffix;\n              }\n              try {\n                return createLateNotFoundRecovery(\n                  await ReactDOMServer.renderToString(\n                    wrapWithFarmIntegrationProviders(createFarmNotFoundElement(pathname))\n                  )\n                ) + streamSuffix;\n              } catch (error) {\n                // The layouts are already in the shell; a not-found page that\n                // needs their context cannot render alone, so use Farm's.\n                console.warn(\"not-found page could not render outside its layout, using Farm's:\", error);\n                return createLateNotFoundRecovery(\n                  await ReactDOMServer.renderToString(React.createElement(FarmDefault404Page))\n                ) + streamSuffix;\n              }\n            },\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        const rendererHasTitle = /<title[\\\\s>]/i.test(rendererHead);\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 && rendererHasTitle;\n        let fullHtml;\n        if (hasFullDocument) {\n          // Layout provides full HTML structure - inject CSS and client script\n          html = ensureFarmDocumentHead(extractFarmFullDocument(html) || html);\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            // Explicit metadata wins over renderer and layout titles. Without\n            // explicit metadata, a renderer title wins over the layout title.\n            .replace(/<head([^>]*)>([\\\\s\\\\S]*?)<\\\\/head>/i, (match, attrs, headContent) => {\n              const hasAuthoritativeTitle = renderedMetadata.hasExplicitTitle || rendererHasTitle;\n              let nextHeadContent = hasAuthoritativeTitle\n                ? headContent.replace(/<title\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/title>\\\\s*/gi, \"\")\n                : headContent;\n              if (renderedMetadata.hasExplicitTitle) {\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              const effectiveRendererHead = renderedMetadata.hasExplicitTitle\n                ? rendererHead.replace(/<title\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/title>\\\\s*/gi, \"\")\n                : rendererHead;\n              if (effectiveRendererHead) nextHeadContent += \"\\\\n  \" + effectiveRendererHead;\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(\n          fullHtml,\n          pathname,\n          farmI18nSnapshot,\n          request,\n          mergedMetadata\n        );\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 rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(\n          fullHtml,\n          { \n            status: pageStatus,\n            headers: { ...responseHeaders, \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(fullHtml) }\n          }\n        ), middlewareHeaders), fullHtml);\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        return renderFarmNotFoundResponse();\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              request\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 rememberFarmBufferedHtml(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\": getFarmBufferedPreloadMarker(errorDocument),\n            },\n          }), middlewareHeaders), errorDocument);\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          request\n        ),\n        farmThemeConfig,\n        farmResolvedRuntimeConfig.basePath,\n        getFarmTheme(request)\n      );\n      return rememberFarmBufferedHtml(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\": getFarmBufferedPreloadMarker(fallbackDocument),\n          },\n        }\n      ), middlewareHeaders), fallbackDocument);\n    }\n  }\n\n  // 404 fallback - render proper HTML page\n  return renderFarmNotFoundResponse();\n\n  // Hoisted: page and middleware notFound() answer with the same page.\n  async function renderFarmNotFoundResponse() {\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    // Wrap 404 page with root layout if available\n    let notFoundElement = createFarmNotFoundElement(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 fullDocument = extractFarmFullDocument(html);\n    const hasFullDocument = fullDocument !== null;\n    \n    let fullHtml;\n    if (hasFullDocument) {\n      fullHtml = ensureFarmDocumentHead(fullDocument)\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(), request);\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 rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(fullHtml, {\n      status: 404,\n      headers: {\n        \"Content-Type\": \"text/html; charset=utf-8\",\n        \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(fullHtml),\n      }\n    }), middlewareHeaders), fullHtml);\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 rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(\n      fallbackDocument,\n      {\n        status: 404,\n        headers: { \"Content-Type\": \"text/html\", \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(fallbackDocument) },\n      }\n    ), middlewareHeaders), fallbackDocument);\n  }\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, adapterContext) {\n  if (!farmPluginRuntime || runtimeOptions.kind !== \"page\") {\n    return handleFarmRequest(request, adapterContext);\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, adapterContext);\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\", getFarmBufferedPreloadMarker(html));\n  return rememberFarmBufferedHtml(new Response(html, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  }), html);\n}\n\n${generatePreloadResponseRuntimeSource()}\n\n// Export as Web Standard fetch API\nexport async function fetch(request, context) {\n  ${config.agent?.noindexPreviews ? \"const response = await\" : \"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    config.agent?.noindexPreviews\n      ? `\n  // Keep every response of a preview deployment out of search indexes.\n  return farmNoindexPreview ? applyFarmPreviewRobotsTag(response) : response;`\n      : \"\"\n  }\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 prepareResponse = async (runtimeRequest, responsePromise) => {\n          const response = await responsePromise;\n          // Headers need the path eagerly; preload reporting needs it only for\n          // actual warnings. Keep the current plugin request, not a render URL.\n          const routePathname = configuredHeaderRoutes.length > 0\n            ? getFarmRoutePathname(new URL(runtimeRequest.url).pathname)\n            : undefined;\n          return applyFarmPreloadBudget(\n            applyFarmCspNonceToResponse(\n              applyConfiguredResponseHeaders(response, routePathname),\n              farmSecurityConfig,\n            ),\n            routePathname,\n            runtimeRequest,\n          );\n        };\n        const runRequest = () => farmPluginRuntime\n          ? farmPluginRuntime.runRuntimeRequest(\n              request,\n              (runtimeRequest) =>\n                _runWithCurrentRequest(runtimeRequest, () =>\n                  prepareResponse(\n                    runtimeRequest,\n                    handleFarmPluginRequest(runtimeRequest, runtimeOptions, context),\n                  )\n                ),\n              {\n                ...runtimeOptions,\n                waitUntil: typeof context?.waitUntil === \"function\"\n                  ? context.waitUntil.bind(context)\n                  : undefined,\n              },\n            )\n          : prepareResponse(request, handleFarmRequest(request, context));\n\n        const response = await _runWithCurrentRequest(request, () =>\n          _runWithAfterRequest(request, runRequest, context),\n        );\n        return ${hasCompressionRuntime && !hasPluginRuntime ? \"compressFarmResponse(request, response)\" : \"response\"};\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\n/**\n * Rank a `routeRules` glob (`/blog/**`). This is config-pattern syntax, not file\n * route syntax, and is deliberately separate from the file-route ordering in\n * `compareRoutePatternSpecificity`.\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 (\n    manifest.routes\n      .filter((entry) => entry.kind === \"page\" && middlewarePatternMatches(entry.pattern, pathname))\n      // Page patterns, so this uses the shared file-route ordering contract too.\n      .sort((left, right) => compareRoutePatternSpecificity(left.pattern, right.pattern))[0]\n  );\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 (farmServerRuntimePluginsMayHandlePath(config, pathname)) 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  nitroBuilderResultPromise: Promise<PromiseSettledResult<FarmNitroBuilder>>,\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, nitroBuilderResult] = await Promise.all([\n    import(\"fs/promises\"),\n    nitroBuilderResultPromise,\n  ]);\n  if (nitroBuilderResult.status === \"rejected\") throw nitroBuilderResult.reason;\n  const nitroBuilder = nitroBuilderResult.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 runtimeServerOutputDir = isVercel\n    ? path.join(outputDir, \"functions\", \"__nitro.func\")\n    : path.join(outputDir, \"server\");\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 ssrExternalPackages = collectSSRExternalPackages(ssrBundle);\n  const useExternalMetadataImageRuntime = shouldUseExternalMetadataImageRuntime(\n    preset,\n    hasGeneratedMetadataImages || ssrExternalPackages.has(\"@vercel/og\"),\n  );\n  const nitroRollupExternal = (id: string) =>\n    (useExternalMetadataImageRuntime && id === \"@vercel/og\") ||\n    (isNitroRollupExternal(id) && !(isCloudflareWorker && NITRO_REACT_RUNTIME_MODULES.has(id)));\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 { useNitroHooks } from '#nitro/runtime/app'\nimport handler, { farmProductionLifecycle, createFarmNodeRequestAbortSignal } from './${ssrEntryFile}'\n\nexport { farmProductionLifecycle }\n\nlet farmCloseHookRegistered = false\nfunction registerFarmCloseHook() {\n  if (farmCloseHookRegistered) return\n  farmCloseHookRegistered = true\n  useNitroHooks().hook('close', () =>\n    farmProductionLifecycle.close('production-server-closed')\n  )\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// The peer address the server adapter already knows. The Request handed to\n// Farm is rebuilt below and has no socket, so without this a built app cannot\n// tell its visitors apart even though its development server can. Mirrors h3's\n// getRequestIP without the forwarded header, which only trustProxy may honor.\nfunction resolveFarmClientAddress(event) {\n  try {\n    return event.req?.context?.clientAddress || event.req?.ip ||\n      event.node?.req?.socket?.remoteAddress || undefined\n  } catch {\n    return undefined\n  }\n}\n\nfunction resolveTrustedLocalOrigin(event, request) {\n  const socket = event.node?.req?.socket\n  const port = socket?.localPort\n  let address = socket?.localAddress\n  if (!address || !Number.isInteger(port) || port <= 0) return undefined\n  if (address.startsWith('::ffff:')) address = address.slice('::ffff:'.length)\n  const hostname = address.includes(':') ? '[' + address + ']' : address\n  const protocol = socket.encrypted ? 'https:' : 'http:'\n  const requestURL = new URL(request.url)\n  let origin\n  try {\n    origin = new URL(protocol + '//' + hostname + ':' + port).origin\n  } catch {\n    return undefined\n  }\n  if (requestURL.origin === origin) return origin\n\n  const requestPort = Number(requestURL.port || (requestURL.protocol === 'https:' ? 443 : 80))\n  const normalizedRequestHostname =\n    requestURL.hostname.startsWith('[') && requestURL.hostname.endsWith(']')\n      ? requestURL.hostname.slice(1, -1)\n      : requestURL.hostname\n  const isLoopback = (value) =>\n    value === 'localhost' || value === '::1' || /^127(?:[.][0-9]{1,3}){3}$/.test(value)\n  return requestURL.protocol === protocol &&\n    requestPort === port &&\n    isLoopback(address) &&\n    isLoopback(normalizedRequestHostname)\n    ? requestURL.origin\n    : undefined\n}\n\n// Export the event handler for Nitro\nexport default async function farmNitroEventHandler(event) {\n  registerFarmCloseHook()\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 webRequest = event.req?._request || event.req\n  const request = node?.req && node?.res\n    ? new Request(webRequest, { signal: createFarmNodeRequestAbortSignal(node.req, node.res) })\n    : webRequest\n  const response = await handler.fetch(request, {\n    waitUntil: (promise) => event.waitUntil(promise),\n    onResponseFinished: createResponseFinishedHook(event),\n    trustedLocalOrigin: resolveTrustedLocalOrigin(event, request),\n    clientAddress: resolveFarmClientAddress(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        nodeAdapterModule: 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    serverDir: root,\n    buildDir: path.join(root, distDir, \".nitro\"),\n    alias: resolveNitroInternalRuntimeAliases(root),\n    compatibilityDate: \"2024-12-01\",\n    output: resolveFarmNitroOutputConfig(preset, outputDir),\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      \"/**\": {\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    rollupConfig: {\n      external: nitroRollupExternal,\n      plugins:\n        hasGeneratedMetadataImages && !useExternalMetadataImageRuntime\n          ? [createMetadataImageWasmPlugin()]\n          : [],\n    },\n    // Keep the public Nitro boolean intact for build hooks. Farm replaces\n    // Nitro's minifier only when no custom OXC transform was requested.\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 hasCustomOxcOptions = Boolean(nitroConfig.oxc && Object.keys(nitroConfig.oxc).length > 0);\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    !hasCustomOxcOptions &&\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: FarmEsbuildOptions = {};\n  const resolvedEsbuildOptions: FarmEsbuildOptions = {\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: !(config.docs?.enabled && config.docs.adapter?.server),\n    legalComments: \"none\",\n  };\n  const prebuiltSSREsbuildOptions =\n    config.docs?.enabled && config.docs.adapter?.server\n      ? resolvedEsbuildOptions\n      : configuredEsbuildOptions;\n  const useFarmEsbuildMinifier =\n    shouldMinify &&\n    nitroConfig.sourcemap === false &&\n    !hasCustomOxcOptions &&\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\n  // Build with Nitro\n  const nitroInstance = await nitroBuilder.createNitro(nitroConfig);\n  if (config.security.csp && config.security.csp.nonce) {\n    nitroInstance.hooks.hook(\"prerender:generate\", async (route) => {\n      if (!route.contents || !route.contentType?.toLowerCase().includes(\"html\")) return;\n      const staticCsp = await applyFarmCspHashesToHtml(route.contents, config.security);\n      if (!staticCsp) return;\n\n      route.contents = staticCsp.html;\n      const routeRule = nitroInstance.options.routeRules[route.route] || {};\n      const headers = { ...routeRule.headers };\n      for (const key of Object.keys(headers)) {\n        if (key.toLowerCase() === staticCsp.header.key.toLowerCase()) delete headers[key];\n      }\n      headers[staticCsp.header.key] = staticCsp.header.value;\n      nitroInstance.options.routeRules[route.route] = { ...routeRule, headers };\n    });\n    nitroInstance.hooks.hook(\"prerender:done\", () => {\n      // The final adapter build reads both the resolved options and Nitro's\n      // routing index. Refresh the latter after per-page policies are known.\n      nitroInstance.routing.sync();\n    });\n  }\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 nitroBuilder.prepare(nitroInstance);\n  await nitroBuilder.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 nitroBuilder.prerender(nitroInstance);\n  }\n  const sharpRuntimeStagePromise =\n    imageRuntime === \"node\"\n      ? stageSharpRuntime(config, root, distDir, fs)\n      : Promise.resolve<StagedSharpRuntime | null>(null);\n  const [nitroBuildResult, sharpRuntimeStageResult] = await Promise.allSettled([\n    nitroBuilder.build(nitroInstance),\n    sharpRuntimeStagePromise,\n  ]);\n  await nitroInstance.close();\n  if (nitroBuildResult.status === \"rejected\") {\n    if (sharpRuntimeStageResult.status === \"fulfilled\" && sharpRuntimeStageResult.value) {\n      await fs.rm(sharpRuntimeStageResult.value.stageDir, {\n        recursive: true,\n        force: true,\n      });\n    }\n    throw nitroBuildResult.reason;\n  }\n  if (sharpRuntimeStageResult.status === \"rejected\") {\n    throw sharpRuntimeStageResult.reason;\n  }\n  const stagedSharpRuntime =\n    sharpRuntimeStageResult.value ??\n    (imageRuntime === \"node\" ? await stageSharpRuntime(config, root, distDir, fs) : null);\n\n  const runtimeCopyPromise = (async () => {\n    if (stagedSharpRuntime) {\n      await installStagedSharpRuntime(stagedSharpRuntime, runtimeServerOutputDir, fs);\n    }\n    if (useExternalMetadataImageRuntime) {\n      await copyMetadataImageRuntime(root, runtimeServerOutputDir, fs);\n    }\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          shouldMinify,\n          fs,\n        )\n      : Promise.resolve(),\n    runtimeCopyPromise,\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\n/**\n * Keep Farm's conventional server/public split only for targets whose\n * post-processing and runtime adapters consume it. Platform presets such as\n * Cloudflare Pages and Netlify define their own output layout (for example\n * `_worker.js` or `.netlify/functions-internal`); supplying these directories\n * here overrides Nitro's preset defaults and produces an undeployable bundle.\n */\nexport function resolveFarmNitroOutputConfig(\n  preset: string,\n  outputDir: string,\n): NonNullable<NitroConfig[\"output\"]> {\n  const isVercel = preset === \"vercel\" || preset === \"vercel-edge\";\n\n  return {\n    dir: outputDir,\n    ...(preset === \"node-server\"\n      ? {\n          serverDir: path.join(outputDir, \"server\"),\n          publicDir: path.join(outputDir, \"public\"),\n        }\n      : isVercel\n        ? {\n            serverDir: path.join(outputDir, \"functions\", \"__nitro.func\"),\n            publicDir: path.join(outputDir, \"static\"),\n          }\n        : {}),\n  };\n}\n\nasync function copyPrebuiltSSRBundle(\n  ssrBundle: OutputBundle,\n  targetDir: string,\n  configuredEsbuildOptions: FarmEsbuildOptions,\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  // Patched Nitro v3 Vercel presets already write the function in its Build\n  // Output API directory. Retain migration support for older preset output.\n  await fs.mkdir(nitroFuncDir, { recursive: true });\n  const serverContents = await fs.readdir(serverDir).catch((error: NodeJS.ErrnoException) => {\n    if (error.code === \"ENOENT\") return [];\n    throw error;\n  });\n  for (const file of serverContents) {\n    await moveVercelOutputPath(path.join(serverDir, file), path.join(nitroFuncDir, file), fs);\n  }\n  if (serverContents.length > 0) 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    config.basePath,\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  });\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  // Nitro v3 emits the SSR entry at the function root. Its docs lookup searches\n  // beside the entry and its ancestors, not the old chunks/nitro directory.\n  const bundledContentDir = path.join(nitroFuncDir, \"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\ninterface StagedSharpRuntime {\n  stageDir: string;\n  dependencies: Record<string, string>;\n}\n\nasync function stageSharpRuntime(\n  config: ResolvedFarmConfig,\n  root: string,\n  distDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<StagedSharpRuntime> {\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 stageRoot = path.join(root, distDir, \"tmp\");\n  await fs.mkdir(stageRoot, { recursive: true });\n  const stageDir = await fs.mkdtemp(path.join(stageRoot, \"sharp-runtime-\"));\n  const targetNodeModules = path.join(stageDir, \"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  try {\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  } catch (error) {\n    await fs.rm(stageDir, { recursive: true, force: true });\n    throw error;\n  }\n\n  return {\n    stageDir,\n    dependencies: Object.fromEntries(\n      [...copiedPackages].sort(([left], [right]) => left.localeCompare(right)),\n    ),\n  };\n}\n\nasync function installStagedSharpRuntime(\n  staged: StagedSharpRuntime,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const stagedNodeModules = path.join(staged.stageDir, \"node_modules\");\n  const targetNodeModules = path.join(nitroFuncDir, \"node_modules\");\n\n  try {\n    await mergeStagedDirectory(stagedNodeModules, targetNodeModules, fs);\n\n    const functionPackage = await readNitroOutputPackage(nitroFuncDir, fs);\n    functionPackage.dependencies = {\n      ...functionPackage.dependencies,\n      ...staged.dependencies,\n    };\n    await writeNitroOutputPackage(nitroFuncDir, functionPackage, fs);\n  } finally {\n    await fs.rm(staged.stageDir, { recursive: true, force: true });\n  }\n\n  logger.info(\n    `🖼️  Bundled Sharp image runtime (${Object.keys(staged.dependencies).length} packages)`,\n  );\n}\n\nasync function mergeStagedDirectory(\n  sourceDir: string,\n  targetDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  await fs.mkdir(targetDir, { recursive: true });\n  const entries = await fs.readdir(sourceDir, { withFileTypes: true });\n\n  await Promise.all(\n    entries.map(async (entry) => {\n      const sourcePath = path.join(sourceDir, entry.name);\n      const targetPath = path.join(targetDir, entry.name);\n\n      try {\n        await fs.rename(sourcePath, targetPath);\n        return;\n      } catch (error) {\n        const code = (error as NodeJS.ErrnoException).code;\n        if (code !== \"EEXIST\" && code !== \"ENOTEMPTY\" && code !== \"EXDEV\") {\n          throw error;\n        }\n      }\n\n      if (entry.isDirectory()) {\n        await mergeStagedDirectory(sourcePath, targetPath, fs);\n        await fs.rm(sourcePath, { recursive: true, force: true });\n        return;\n      }\n\n      await fs.cp(sourcePath, targetPath, {\n        force: true,\n        dereference: true,\n        mode: fsConstants.COPYFILE_FICLONE,\n      });\n      await fs.rm(sourcePath, { force: true });\n    }),\n  );\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 functionPackage = await readNitroOutputPackage(nitroFuncDir, fs);\n  functionPackage.dependencies = {\n    ...functionPackage.dependencies,\n    \"@vercel/og\": String(packageJson.version || \"0.11.1\"),\n  };\n  await writeNitroOutputPackage(nitroFuncDir, functionPackage, fs);\n  logger.info(\"🖼️  Bundled generated metadata image runtime\");\n}\n\nasync function readNitroOutputPackage(\n  outputDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<NitroOutputPackage> {\n  const packagePath = path.join(outputDir, \"package.json\");\n  return fs\n    .readFile(packagePath, \"utf8\")\n    .then((contents) => JSON.parse(contents))\n    .catch((error: NodeJS.ErrnoException) => {\n      if (error.code === \"ENOENT\") return {};\n      throw error;\n    });\n}\n\nasync function writeNitroOutputPackage(\n  outputDir: string,\n  packageJson: NitroOutputPackage,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  await fs.mkdir(outputDir, { recursive: true });\n  await fs.writeFile(\n    path.join(outputDir, \"package.json\"),\n    `${JSON.stringify(packageJson, null, 2)}\\n`,\n  );\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\n  // Some modern packages, including Sharp 0.35+, do not export their\n  // package.json. Resolve their entry point and walk back to the package root\n  // so production staging keeps working without requiring a legacy export.\n  try {\n    let directory = path.dirname(parentRequire.resolve(packageName));\n    while (directory !== path.dirname(directory)) {\n      const candidate = path.join(directory, \"package.json\");\n      if (existsSync(candidate)) {\n        try {\n          const manifest = JSON.parse(readFileSync(candidate, \"utf8\")) as { name?: unknown };\n          if (manifest.name === packageName) return candidate;\n        } catch {\n          // Ignore unrelated or malformed metadata while walking upward.\n        }\n      }\n      if (path.basename(directory) === \"node_modules\") break;\n      directory = path.dirname(directory);\n    }\n  } catch {\n    // Keep the existing null result and caller diagnostics when resolution fails.\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 clientPackagePath = path.join(prismaClientDir, \"package.json\");\n  const [functionPackage, clientPackageContent] = await Promise.all([\n    readNitroOutputPackage(nitroFuncDir, fs),\n    fs.readFile(clientPackagePath, \"utf-8\"),\n  ]);\n  const clientPackage = JSON.parse(clientPackageContent);\n\n  functionPackage.dependencies = {\n    ...functionPackage.dependencies,\n    \"@prisma/client\": clientPackage.version,\n  };\n\n  await writeNitroOutputPackage(nitroFuncDir, functionPackage, fs);\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 \"node:path\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\nimport {\n  createFarmDocsHandler,\n  discoverFarmDocsPages,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n  toFarmDocsMarkdownPage,\n  type LoadedFarmDocsPage,\n} from \"./handler\";\nimport { createFarmDocsAPIHandler } from \"./api\";\nimport type { FarmDocsPublicFontAsset } from \"./fonts\";\nimport type { FarmDocsCompiledManifest, FarmDocsCompiledResponse } from \"./precompiled-runtime\";\n\nexport const FARM_DOCS_COMPILED_ORIGIN = \"https://farm-docs-build.invalid\";\n\nexport interface CompileFarmDocsManifestOptions {\n  root: string;\n  srcDir: string;\n  clientEntry: string;\n  fontAssets: readonly FarmDocsPublicFontAsset[];\n  fontStylesheetHref?: string;\n  globalStylesheetHref?: string;\n}\n\nfunction normalizePathname(pathname: string): string {\n  if (pathname === \"/\") return pathname;\n  return pathname.replace(/\\/+$/g, \"\") || \"/\";\n}\n\nfunction sanitizeCompiledValue(value: string, absolutePaths: readonly string[]): string {\n  let sanitized = value;\n  for (const absolutePath of absolutePaths) {\n    if (!absolutePath) continue;\n    sanitized = sanitized.split(absolutePath).join(\".\");\n    sanitized = sanitized.split(absolutePath.replace(/\\\\/g, \"/\")).join(\".\");\n    sanitized = sanitized.split(absolutePath.replace(/\\//g, \"\\\\\")).join(\".\");\n  }\n  return sanitized;\n}\n\nasync function compileResponse(\n  response: Response,\n  absolutePaths: readonly string[],\n): Promise<FarmDocsCompiledResponse> {\n  return {\n    status: response.status,\n    statusText: response.statusText,\n    headers: Array.from(response.headers.entries()).map(([key, value]) => [\n      key,\n      sanitizeCompiledValue(value, absolutePaths),\n    ]),\n    body: sanitizeCompiledValue(await response.text(), absolutePaths),\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 loadPages(contentDir: string, docs: FarmDocsResolvedConfig): LoadedFarmDocsPage[] {\n  return discoverFarmDocsPages(contentDir, docs)\n    .map((page) => loadFarmDocsPage(contentDir, docs, page.slug))\n    .filter((page): page is LoadedFarmDocsPage => Boolean(page))\n    .sort((a, b) => a.href.localeCompare(b.href));\n}\n\nfunction findSocialImagePath(html: string): string | null {\n  const match =\n    /<meta\\s+property=[\"']og:image[\"']\\s+content=[\"']([^\"']+)[\"']/i.exec(html) ||\n    /<meta\\s+content=[\"']([^\"']+)[\"']\\s+property=[\"']og:image[\"']/i.exec(html);\n  if (!match?.[1]) return null;\n  try {\n    return new URL(match[1], FARM_DOCS_COMPILED_ORIGIN).pathname;\n  } catch {\n    return null;\n  }\n}\n\nasync function addHandlerRoute(\n  routes: Record<string, FarmDocsCompiledResponse>,\n  pathname: string,\n  handler: (request: Request) => Promise<Response | null>,\n  absolutePaths: readonly string[],\n): Promise<Response | null> {\n  const response = await handler(new Request(`${FARM_DOCS_COMPILED_ORIGIN}${pathname}`));\n  if (!response) return null;\n  routes[normalizePathname(pathname)] = await compileResponse(response.clone(), absolutePaths);\n  return response;\n}\n\nexport async function compileFarmDocsManifest(\n  docs: FarmDocsResolvedConfig,\n  options: CompileFarmDocsManifestOptions,\n): Promise<FarmDocsCompiledManifest> {\n  const contentDir = resolveFarmDocsContentDir(docs, options);\n  const pages = loadPages(contentDir, docs);\n  const absolutePaths = [\n    path.resolve(options.root),\n    path.resolve(contentDir),\n    docs.configPath || \"\",\n  ];\n  const handler = createFarmDocsHandler(docs, {\n    root: options.root,\n    srcDir: options.srcDir,\n    clientEntry: options.clientEntry,\n    fontAssets: options.fontAssets,\n    fontStylesheetHref: options.fontStylesheetHref,\n    globalStylesheetHref: options.globalStylesheetHref,\n  });\n  const apiHandler = createFarmDocsAPIHandler({\n    rootDir: options.root,\n    srcDir: options.srcDir,\n    docs,\n  });\n  const routes: Record<string, FarmDocsCompiledResponse> = {};\n  const apiMarkdown: Record<string, FarmDocsCompiledResponse> = {};\n\n  for (const page of pages) {\n    const htmlResponse = await addHandlerRoute(routes, page.href, handler, absolutePaths);\n    const markdownPath = page.href === \"/\" ? \"/.md\" : `${page.href}.md`;\n    await addHandlerRoute(routes, markdownPath, handler, absolutePaths);\n\n    if (htmlResponse) {\n      const socialImagePath = findSocialImagePath(await htmlResponse.text());\n      if (socialImagePath && !routes[normalizePathname(socialImagePath)]) {\n        await addHandlerRoute(routes, socialImagePath, handler, absolutePaths);\n      }\n    }\n\n    const apiResponse = await apiHandler(\n      new Request(\n        `${FARM_DOCS_COMPILED_ORIGIN}/api/docs?format=markdown&path=${encodeURIComponent(page.slug)}`,\n      ),\n    );\n    if (apiResponse) {\n      apiMarkdown[page.slug] = await compileResponse(apiResponse, absolutePaths);\n    }\n  }\n\n  const publicCandidates = [\n    \"/llms.txt\",\n    \"/llms-full.txt\",\n    \"/.well-known/llms.txt\",\n    \"/.well-known/llms-full.txt\",\n    \"/AGENTS.md\",\n    \"/agent.md\",\n    \"/.well-known/AGENTS.md\",\n    \"/SKILL.md\",\n    \"/.well-known/SKILL.md\",\n    \"/.well-known/agent.json\",\n    \"/sitemap.xml\",\n    \"/sitemap.md\",\n    \"/robots.txt\",\n    `${docs.entry.replace(/\\/+$/g, \"\")}/sitemap.md`,\n  ];\n  for (const pathname of publicCandidates) {\n    if (!routes[normalizePathname(pathname)]) {\n      await addHandlerRoute(routes, pathname, handler, absolutePaths);\n    }\n  }\n\n  const staticFormats = [\n    \"config\",\n    \"skill\",\n    \"agents\",\n    \"agent-spec\",\n    \"diagnostics\",\n    \"llms\",\n    \"llms-full\",\n    \"sitemap-md\",\n    \"sitemap-xml\",\n    \"robots\",\n  ];\n  const apiStatic: Record<string, FarmDocsCompiledResponse> = {};\n  for (const format of staticFormats) {\n    const response = await apiHandler(\n      new Request(`${FARM_DOCS_COMPILED_ORIGIN}/api/docs?format=${format}`),\n    );\n    if (response) apiStatic[format] = await compileResponse(response, absolutePaths);\n  }\n\n  const emptyResponse = await apiHandler(new Request(`${FARM_DOCS_COMPILED_ORIGIN}/api/docs`));\n  const postResponse = await apiHandler(\n    new Request(`${FARM_DOCS_COMPILED_ORIGIN}/api/docs`, { method: \"POST\" }),\n  );\n  if (!emptyResponse || !postResponse) {\n    throw new Error(\"Farm docs compiler could not create the built-in API responses.\");\n  }\n\n  const searchConfig = docs.config.search;\n  if (\n    searchConfig &&\n    typeof searchConfig === \"object\" &&\n    \"provider\" in searchConfig &&\n    searchConfig.provider === \"custom\"\n  ) {\n    throw new Error(\n      \"Farm cannot serialize a custom docs search adapter into an edge deployment. \" +\n        'Use the built-in \"simple\" provider, a serializable hosted provider, or a Node target.',\n    );\n  }\n  const searchLimit =\n    searchConfig && typeof searchConfig === \"object\" && \"maxResults\" in searchConfig\n      ? Number((searchConfig as { maxResults?: unknown }).maxResults)\n      : undefined;\n\n  return {\n    protocol: 1,\n    originPlaceholder: FARM_DOCS_COMPILED_ORIGIN,\n    entry: docs.entry,\n    routes,\n    api: {\n      static: apiStatic,\n      markdown: apiMarkdown,\n      empty: await compileResponse(emptyResponse, absolutePaths),\n      post: await compileResponse(postResponse, absolutePaths),\n      search: {\n        pages: pages.map((page) => ({\n          ...toFarmDocsMarkdownPage(page),\n          sourcePath: `farm-docs:${page.slug || \"index\"}`,\n        })),\n        search: searchConfig ?? true,\n        siteTitle: getDocsTitle(docs),\n        ...(Number.isFinite(searchLimit) ? { limit: searchLimit } : {}),\n      },\n    },\n  };\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  basePath = \"/\",\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, basePath);\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, basePath = \"/\"): string {\n  const normalized = normalizePattern(pattern);\n  const normalizedBasePath = normalizeBasePath(basePath);\n  if (normalized === \"/\") return normalizedBasePath || \"/\";\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  if (!normalizedBasePath) return source || \"/\";\n  return source === \"/\" ? normalizedBasePath : `${normalizedBasePath}${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 normalizeBasePath(value: string): string {\n  const trimmed = value.trim();\n  if (!trimmed || trimmed === \"/\") return \"\";\n  const withSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n  return withSlash.replace(/\\/+$/g, \"\") || \"/\";\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}): FarmVercelRoute[] {\n  const { presetRoutes, runtimeRoutes } = 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    {\n      src: \"/(.*)\",\n      dest: \"/__nitro\",\n    },\n  ];\n}\n","import type { ResolvedFarmServerConfig } from \"../server-http\";\n\nexport interface FarmNodeServerEntryOptions {\n  nitroEntryFile: string;\n  nodeAdapterModule: 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/virtual/polyfills\";\nimport { NodeRequest, serve } from ${JSON.stringify(options.nodeAdapterModule)};\nimport wsAdapter from ${JSON.stringify(options.websocketAdapterModule)};\nimport { resolveWebsocketHooks, useNitroApp, useNitroHooks } from \"#nitro/runtime/app\";\nimport { useRuntimeConfig } from \"#nitro/runtime/runtime-config\";\nimport { trapUnhandledErrors } from \"#nitro/runtime/error/hooks\";\nimport { setupCloseHooks } from \"#nitro/runtime/shutdown\";\nimport { startScheduleRunner } from \"#nitro/runtime/task\";\nimport { tracingSrvxPlugins } from \"#nitro/virtual/tracing\";\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 = {\n  disabled: Boolean(process.env.NITRO_SHUTDOWN_DISABLED),\n  signals: (process.env.NITRO_SHUTDOWN_SIGNALS || \"SIGTERM SIGINT\")\n    .split(\" \")\n    .map((signal) => signal.trim())\n    .filter(Boolean),\n  timeout: Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || \"\", 10) || 30000,\n  forceExit: !process.env.NITRO_SHUTDOWN_NO_FORCE_EXIT,\n};\n\nconst nitroApp = useNitroApp();\nuseNitroHooks().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 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 server = serve({\n  manual: true,\n  silent: true,\n  gracefulShutdown: false,\n  port,\n  hostname: host,\n  node: socketPath ? { path: socketPath } : undefined,\n  tls: cert && key ? { cert, key } : undefined,\n  fetch: nitroApp.fetch,\n  plugins: [...tracingSrvxPlugins],\n});\nconst nodeServer = server.node?.server;\nif (!nodeServer) throw new Error(\"[Farm] Nitro did not create a Node server\");\n\nnodeServer.headersTimeout = farmServerConfig.headersTimeout;\nnodeServer.requestTimeout = farmServerConfig.requestTimeout;\nnodeServer.keepAliveTimeout = farmServerConfig.keepAliveTimeout;\n\nlet isShuttingDown = false;\nnodeServer.on(\"request\", (_request, response) => {\n  response.once(\"finish\", () => {\n    if (isShuttingDown) nodeServer.closeIdleConnections?.();\n  });\n});\n\nif (import.meta._websocket) {\n  const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks });\n  nodeServer.on(\"upgrade\", (request, socket, head) => {\n    handleUpgrade(\n      request,\n      socket,\n      head,\n      new NodeRequest({ req: request, upgrade: { socket, head } }),\n    );\n  });\n}\n\nsetupCloseHooks(server);\ntrapUnhandledErrors();\n\nlet shutdownPromise;\nasync function shutdown(signal) {\n  isShuttingDown = true;\n  farmProductionLifecycle.beginDrain(signal);\n\n  const gracefulClose = server.close().then(\n    () => true,\n    (error) => {\n      console.error(\"[Farm] Runtime shutdown failed:\", error);\n      process.exitCode = 1;\n      return true;\n    },\n  );\n  nodeServer.closeIdleConnections?.();\n  let gracefulTimer;\n  const gracefullyClosed = await Promise.race([\n    gracefulClose,\n    new Promise((resolve) => {\n      gracefulTimer = setTimeout(() => resolve(false), shutdownConfig.timeout);\n    }),\n  ]);\n  clearTimeout(gracefulTimer);\n\n  if (!gracefullyClosed) {\n    console.warn(\"[Farm] Graceful shutdown timed out; forcing cleanup\");\n    void server.close(true).catch((error) => {\n      console.error(\"[Farm] Forced server shutdown failed:\", error);\n      process.exitCode = 1;\n    });\n\n    let forceTimer;\n    const forceClosed = await Promise.race([\n      Promise.resolve()\n        .then(() => farmProductionLifecycle.forceClose(\"production-server-closed\"))\n        .then(\n          () => true,\n          (error) => {\n            console.error(\"[Farm] Forced runtime shutdown failed:\", error);\n            process.exitCode = 1;\n            return true;\n          },\n        ),\n      new Promise((resolve) => {\n        forceTimer = setTimeout(() => resolve(false), shutdownConfig.timeout);\n      }),\n    ]);\n    clearTimeout(forceTimer);\n    if (!forceClosed) {\n      console.error(\"[Farm] Forced runtime shutdown timed out\");\n      process.exitCode = 1;\n    }\n  }\n\n  if (shutdownConfig.forceExit) process.exit(process.exitCode || 0);\n}\n\nif (!shutdownConfig.disabled) {\n  for (const signal of shutdownConfig.signals) {\n    process.once(signal, (receivedSignal) => {\n      shutdownPromise ||= shutdown(receivedSignal);\n    });\n  }\n}\n\ntry {\n  await server.serve();\n  const protocol = cert && key ? \"https\" : \"http\";\n  const addressInfo = nodeServer.address();\n  if (typeof addressInfo === \"string\") {\n    console.log(\\`Listening on unix socket \\${addressInfo}\\`);\n  } else if (addressInfo) {\n    const configuredBaseURL = useRuntimeConfig().app.baseURL || \"\";\n    const baseURL = configuredBaseURL.endsWith(\"/\")\n      ? configuredBaseURL.slice(0, -1)\n      : configuredBaseURL;\n    const address = addressInfo.family === \"IPv6\"\n      ? \\`[\\${addressInfo.address}]\\`\n      : addressInfo.address;\n    console.log(\\`Listening on \\${protocol}://\\${address}:\\${addressInfo.port}\\${baseURL}\\`);\n  }\n} catch (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  throw error;\n}\n\nif (import.meta._tasks) {\n  startScheduleRunner({ waitUntil: server.waitUntil });\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(\n  preferredBuilder?: FarmProductionViteBuilder,\n): Promise<FarmProductionViteRuntime> {\n  const requested = preferredBuilder ?? 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","export type FarmInstrumentationRuntime = \"nodejs\" | \"edge\" | \"bun\";\nexport type FarmInstrumentationMode = \"development\" | \"production\" | \"test\";\n\nexport interface FarmInstrumentationContext {\n  root: string;\n  mode: FarmInstrumentationMode;\n  runtime: FarmInstrumentationRuntime;\n}\n\nexport type FarmInstrumentationCleanup =\n  | void\n  | (() => void | Promise<void>)\n  | { shutdown: () => void | Promise<void> };\n\nexport interface FarmInstrumentationModule {\n  register?: (\n    context: FarmInstrumentationContext,\n  ) => FarmInstrumentationCleanup | Promise<FarmInstrumentationCleanup>;\n  shutdown?: () => void | Promise<void>;\n}\n\nexport interface FarmInstrumentationLifecycle {\n  start(): Promise<void>;\n  shutdown(): Promise<void>;\n}\n\nexport function createFarmInstrumentationLifecycle(\n  module: FarmInstrumentationModule | null | undefined,\n  context: FarmInstrumentationContext,\n): FarmInstrumentationLifecycle {\n  let startPromise: Promise<void> | undefined;\n  let shutdownPromise: Promise<void> | undefined;\n  let cleanup: Exclude<FarmInstrumentationCleanup, void> | undefined;\n\n  return {\n    start() {\n      if (!startPromise) {\n        startPromise = Promise.resolve(module?.register?.(context)).then((result) => {\n          cleanup = result || undefined;\n        });\n      }\n      return startPromise;\n    },\n    shutdown() {\n      if (!shutdownPromise) {\n        shutdownPromise = (async () => {\n          try {\n            await startPromise;\n          } catch {\n            // A partially initialized module may still need its exported cleanup.\n          }\n          try {\n            if (typeof cleanup === \"function\") {\n              await cleanup();\n            } else if (cleanup?.shutdown) {\n              await cleanup.shutdown();\n            }\n          } finally {\n            if (module?.shutdown) {\n              await module.shutdown();\n            }\n          }\n        })();\n      }\n      return shutdownPromise;\n    },\n  };\n}\n\nexport function resolveFarmInstrumentationRuntime(preset?: string): FarmInstrumentationRuntime {\n  const normalized = preset?.toLowerCase() ?? \"\";\n  if (\n    normalized.includes(\"cloudflare\") ||\n    normalized.includes(\"worker\") ||\n    normalized.includes(\"edge\")\n  ) {\n    return \"edge\";\n  }\n  if (normalized.includes(\"bun\")) return \"bun\";\n  return \"nodejs\";\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 *because of connectivity* while offline\n            // pauses and rides the next reconnect. An application error (a\n            // typed business failure from a request that reached the server)\n            // must surface instead, or it would be swallowed and the payload\n            // silently re-submitted on reconnect, duplicating a non-idempotent\n            // write.\n            if (\n              currentOptions.networkMode === \"online\" &&\n              !isNavigatorOnline() &&\n              requestId >= lastResetIdRef.current &&\n              isConnectivityFailure(cause)\n            ) {\n              continue;\n            }\n            throw cause;\n          }\n        }\n\n        settleServerFnOptimisticUpdates(sharedSnapshots, \"commit\");\n        if (!isAPITarget && currentOptions.request?.invalidate) {\n          // Server-function invalidations travel the shared bus, matching\n          // server-declared `invalidates`, so every subscribed cache observes them.\n          for (const key of resolveServerFnInvalidateTargets(currentOptions.request.invalidate)) {\n            notifyFarmCacheInvalidation(key);\n          }\n        }\n\n        const isLatestRequest = requestId === requestIdRef.current;\n\n        setMutationState((current) => {\n          if (requestId < lastResetIdRef.current) return current;\n          const pendingCount = Math.max(0, current.pendingCount - 1);\n          if (!isLatestRequest) {\n            return {\n              ...current,\n              pendingCount,\n            };\n          }\n\n          return {\n            pendingCount,\n            pausedCount: current.pausedCount,\n            status: \"success\",\n            data,\n            error: null,\n            variables,\n          };\n        });\n\n        if (isLatestRequest) {\n          notifyClientObserver(currentOptions.onSuccess, [data, variables], \"Mutation onSuccess\");\n          if (requestId === requestIdRef.current) {\n            notifyClientObserver(\n              currentOptions.onSettled,\n              [data, null, variables],\n              \"Mutation onSettled\",\n            );\n          }\n        }\n\n        return data;\n      } catch (cause) {\n        settleServerFnOptimisticUpdates(\n          sharedSnapshots,\n          sharedOptimistic?.rollbackOnError ? \"rollback\" : \"invalidate\",\n        );\n        const error = normalizeMutationError(cause) as TError;\n        const isLatestRequest = requestId === requestIdRef.current;\n\n        setMutationState((current) => {\n          if (requestId < lastResetIdRef.current) return current;\n          const pendingCount = Math.max(0, current.pendingCount - 1);\n          if (!isLatestRequest) {\n            return {\n              ...current,\n              pendingCount,\n            };\n          }\n\n          return {\n            pendingCount,\n            pausedCount: current.pausedCount,\n            status: \"error\",\n            data:\n              hasOptimisticData && currentOptions.rollbackOnError\n                ? previousData\n                : currentOptions.resetOnMutate === false\n                  ? current.data\n                  : null,\n            error,\n            variables,\n          };\n        });\n\n        if (isLatestRequest) {\n          notifyClientObserver(currentOptions.onError, [error, variables], \"Mutation onError\");\n          if (requestId === requestIdRef.current) {\n            notifyClientObserver(\n              currentOptions.onSettled,\n              [null, error, variables],\n              \"Mutation onSettled\",\n            );\n          }\n        }\n\n        throw error;\n      }\n    },\n    [setMutationState, waitForReconnect],\n  );\n\n  const mutateAsync = useCallback(\n    (variables?: TVariables) => mutatePreparedAsync(() => variables),\n    [mutatePreparedAsync],\n  ) as MutationAsync<TTarget, TData>;\n\n  const mutate = useCallback(\n    (variables?: TVariables) => {\n      void mutateAsync(variables as never).catch(() => {});\n    },\n    [mutateAsync],\n  ) as MutationTrigger<TTarget>;\n\n  const reset = useCallback(() => {\n    // Pre-reset requests no longer own any of the current pending count.\n    lastResetIdRef.current = ++requestIdRef.current;\n    setMutationState({\n      pendingCount: 0,\n      pausedCount: 0,\n      status: \"idle\",\n      data: optionsRef.current.initialData ?? null,\n      error: null,\n      variables: undefined,\n    });\n    // Wake paused submissions so they reject instead of waiting for `online`.\n    const wakers = Array.from(resetWakersRef.current);\n    resetWakersRef.current.clear();\n    for (const wake of wakers) wake();\n  }, [setMutationState]);\n\n  const mutation: UseMutationReturn<TTarget, TData, TError> = useMemo(\n    () => ({\n      pending: state.pendingCount > 0,\n      paused: state.pausedCount > 0,\n      status: state.status,\n      data: state.data,\n      error: state.error,\n      variables: state.variables,\n      mutate,\n      mutateAsync,\n      reset,\n    }),\n    [\n      mutate,\n      mutateAsync,\n      reset,\n      state.data,\n      state.error,\n      state.pausedCount,\n      state.pendingCount,\n      state.status,\n      state.variables,\n    ],\n  );\n  return { mutation, mutatePreparedAsync };\n}\n\n/**\n * Whether a thrown value represents a connectivity failure (as opposed to an\n * application/business error). Only connectivity failures are safe to pause and\n * retry on reconnect; an application error means the request reached the server\n * and produced a real result. The client tags transport failures with an\n * `APIClientError` code of `network_error` or `timeout`; a raw fetch/transport\n * failure surfaces as a `TypeError`.\n */\nfunction isConnectivityFailure(error: unknown): boolean {\n  if (error instanceof TypeError) return true;\n  const code = (error as { code?: unknown } | null | undefined)?.code;\n  return code === \"network_error\" || code === \"timeout\";\n}\n\nfunction unwrapMutationResult<TData, TError>(result: unknown, apiRoute: boolean): TData {\n  if (!apiRoute) return result as TData;\n\n  const apiResult = result as APIResult<TData, TError>;\n  if (apiResult.error) {\n    throw apiResult.error;\n  }\n\n  return apiResult.data as TData;\n}\n\nfunction normalizeMutationError(error: unknown): Error {\n  if (error instanceof Error) return error;\n\n  const normalized = new Error(typeof error === \"string\" ? error : \"Mutation failed\");\n  (normalized as Error & { cause?: unknown }).cause = error;\n  return normalized;\n}\n","/**\n * Connectivity observation for the client data layer. Environments without a\n * navigator (server rendering, tests) report online so nothing ever pauses\n * there.\n */\nexport function isNavigatorOnline(): boolean {\n  if (typeof navigator === \"undefined\" || typeof navigator.onLine !== \"boolean\") return true;\n  return navigator.onLine;\n}\n\n/** Subscribe to the browser `online` event. Returns a disposer; no-op outside the browser. */\nexport function subscribeOnline(listener: () => void): () => void {\n  if (typeof window === \"undefined\") return () => {};\n  window.addEventListener(\"online\", listener);\n  return () => window.removeEventListener(\"online\", listener);\n}\n","\"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, source) => {\n    if (applyingRemote || source !== \"local\" || 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, \"broadcast\");\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 { applyFarmCacheInvalidations, decodeFarmCacheInvalidations } from \"./cache-invalidation\";\n\nexport interface LiveCacheInvalidationOptions {\n  /** App-owned SSE endpoint created with createFarmCacheInvalidationStream(). */\n  url: string | URL;\n  /** Include credentials for a cross-origin EventSource connection. */\n  withCredentials?: boolean;\n}\n\ntype ActiveLiveConnection = {\n  refCount: number;\n  source: EventSource;\n};\n\nconst FARM_LIVE_CACHE_INVALIDATION_CONNECTIONS = Symbol.for(\n  \"farm.liveCacheInvalidationConnections\",\n);\nconst connectionGlobal = globalThis as typeof globalThis & {\n  [FARM_LIVE_CACHE_INVALIDATION_CONNECTIONS]?: Map<string, ActiveLiveConnection>;\n};\n\nfunction getConnections(): Map<string, ActiveLiveConnection> {\n  return (connectionGlobal[FARM_LIVE_CACHE_INVALIDATION_CONNECTIONS] ??= new Map());\n}\n\n/**\n * Connect the browser cache to an app-owned invalidation event stream.\n * Native EventSource reconnection handles transient disconnects.\n */\nexport function enableLiveCacheInvalidation(options: LiveCacheInvalidationOptions): () => void {\n  if (typeof EventSource !== \"function\") return () => {};\n\n  const baseUrl = typeof location === \"object\" ? location.href : undefined;\n  const url = baseUrl ? new URL(String(options.url), baseUrl).href : String(options.url);\n  const key = `${url}\\0${options.withCredentials === true ? \"include\" : \"same-origin\"}`;\n  const connections = getConnections();\n  let connection = connections.get(key);\n\n  if (connection) {\n    connection.refCount += 1;\n  } else {\n    const source = new EventSource(url, {\n      withCredentials: options.withCredentials === true,\n    });\n    connection = { refCount: 1, source };\n    source.onmessage = (event) => {\n      const keys = decodeFarmCacheInvalidations(event.data);\n      applyFarmCacheInvalidations(keys, \"live\");\n    };\n    connections.set(key, connection);\n  }\n\n  const claimedConnection = connection;\n  let disposed = false;\n  return () => {\n    if (disposed) return;\n    disposed = true;\n    claimedConnection.refCount -= 1;\n    if (claimedConnection.refCount > 0) return;\n    claimedConnection.source.onmessage = null;\n    claimedConnection.source.close();\n    if (connections.get(key) === claimedConnection) connections.delete(key);\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  /** Invalidates adapter reads that began before the latest cache clear. */\n  hydrationGeneration: number;\n  disabled: boolean;\n  clearing: boolean;\n  /** The in-flight flush, so overlapping flushes serialize instead of racing. */\n  flushing: Promise<void> | undefined;\n};\n\nlet activeEngine: PersistenceEngine | undefined;\n\nfunction reportPersistenceFailure(error: unknown): void {\n  const report =\n    typeof reportError === \"function\" ? reportError : (console.error as (value: unknown) => void);\n  if (error instanceof Error) {\n    report(error);\n    return;\n  }\n  const normalized = new Error(\"Client cache persistence failed\");\n  (normalized as Error & { cause?: unknown }).cause = error;\n  report(normalized);\n}\n\nfunction disableEngine(engine: PersistenceEngine, error: unknown): void {\n  if (engine.disabled) return;\n  // The cache is disposable: on any adapter failure fall back to memory-only\n  // for the rest of the session instead of failing reads or writes.\n  engine.disabled = true;\n  engine.pendingSets.clear();\n  engine.pendingDeletes.clear();\n  if (engine.flushTimer !== undefined) {\n    clearTimeout(engine.flushTimer);\n    engine.flushTimer = undefined;\n  }\n  reportPersistenceFailure(error);\n}\n\nfunction scheduleFlush(engine: PersistenceEngine): void {\n  if (engine.disabled || engine.flushTimer !== undefined) return;\n  const timer = setTimeout(() => {\n    engine.flushTimer = undefined;\n    void flushEngine(engine);\n  }, engine.flushDelayMs);\n  (timer as unknown as { unref?: () => void }).unref?.();\n  engine.flushTimer = timer;\n}\n\nasync function flushEngine(engine: PersistenceEngine): Promise<void> {\n  // Serialize: a second flush scheduled while one is mid-await must not run its\n  // own adapter writes in parallel, or the two can resolve out of order and\n  // persist a stale value over a fresher one. Await the in-flight flush instead;\n  // its drain loop picks up whatever this caller queued.\n  if (engine.flushing) return engine.flushing;\n  if (engine.disabled || engine.clearing) return;\n  if (engine.pendingSets.size === 0 && engine.pendingDeletes.size === 0) return;\n\n  const run = (async () => {\n    // Drain until empty so entries queued during an await still flush, without a\n    // second concurrent loop. Re-check disabled/clearing after every await: a\n    // clear() that started mid-flush must stop further writes.\n    while (\n      !engine.disabled &&\n      !engine.clearing &&\n      (engine.pendingSets.size > 0 || engine.pendingDeletes.size > 0)\n    ) {\n      const sets = Array.from(engine.pendingSets.entries());\n      const deletes = Array.from(engine.pendingDeletes);\n      engine.pendingSets.clear();\n      engine.pendingDeletes.clear();\n      try {\n        if (sets.length > 0) {\n          if (engine.adapter.setMany) await engine.adapter.setMany(sets);\n          else for (const [key, entry] of sets) await engine.adapter.set(key, entry);\n        }\n        for (const key of deletes) await engine.adapter.delete(key);\n      } catch (error) {\n        disableEngine(engine, error);\n        return;\n      }\n    }\n  })();\n  engine.flushing = run;\n  try {\n    await run;\n  } finally {\n    engine.flushing = undefined;\n  }\n}\n\nasync function hydrateEngine(engine: PersistenceEngine): Promise<void> {\n  const generation = engine.hydrationGeneration;\n  const now = Date.now();\n  const keys = await engine.adapter.keys();\n  if (engine.disabled || generation !== engine.hydrationGeneration) return;\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  if (engine.disabled || generation !== engine.hydrationGeneration) return;\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 || generation !== engine.hydrationGeneration) 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.hydrationGeneration += 1;\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    hydrationGeneration: 0,\n    disabled: false,\n    clearing: false,\n    flushing: undefined,\n  };\n\n  activeEngine = engine;\n  engine.cache.attachPersistence(createSink(engine));\n  void hydrateEngine(engine).catch((error) => disableEngine(engine, error));\n\n  return () => {\n    if (activeEngine !== engine) return;\n    disposePersistedClientCache();\n  };\n}\n\n/**\n * @internal Entry point used by the generated client entries for the\n * `cache.client.adapter` configuration. Accepts the imported module namespace\n * and reports a misconfigured adapter without breaking application startup:\n * persistence is optional capability and must never block hydration.\n */\nexport function initConfiguredClientCachePersistence(\n  adapterModule: unknown,\n  options: ClientCachePersistenceOptions = {},\n): void {\n  try {\n    const adapter = (adapterModule as { default?: unknown } | null | undefined)?.default;\n    if (!adapter) {\n      throw new Error(\n        \"cache.client.adapter must default-export an adapter. \" +\n          \"Export defineClientCacheAdapter({ keys, get, set, delete, clear }) as the module default.\",\n      );\n    }\n    initPersistedClientCache(adapter as FarmClientCacheAdapter, options);\n  } catch (error) {\n    reportPersistenceFailure(error);\n  }\n}\n\n/** @internal Detach the active engine, flushing nothing further. */\nexport function disposePersistedClientCache(): void {\n  const engine = activeEngine;\n  if (!engine) return;\n  activeEngine = undefined;\n  // Hydration is asynchronous and may already be parked on an adapter read.\n  // Marking the engine disabled makes that in-flight pass stop before it writes,\n  // so a disposed engine cannot repopulate the shared cache after logout — or\n  // push the previous user's entries into whichever adapter is attached next.\n  engine.disabled = true;\n  engine.cache.attachPersistence(undefined);\n  if (engine.flushTimer !== undefined) {\n    clearTimeout(engine.flushTimer);\n    engine.flushTimer = undefined;\n  }\n  engine.pendingSets.clear();\n  engine.pendingDeletes.clear();\n}\n\n/**\n * Remove every persisted cache entry. Call on logout or any session change so\n * the next visitor on this device cannot warm-start into another user's data.\n * Safe to call when persistence is not configured.\n */\nexport async function clearPersistedCache(): Promise<void> {\n  const engine = activeEngine;\n  if (!engine) {\n    // Persistence is optional, but logout must mean the same thing with or\n    // without an adapter: the previous session's data stops being readable.\n    getFarmClientDataCache().clear();\n    return;\n  }\n  // Hold `clearing` for the whole operation. It both suppresses re-persist from\n  // the in-memory cache.clear() below and makes flushEngine bail, so no flush\n  // scheduled during the clear can write the signed-out user's data back.\n  engine.clearing = true;\n  // Adapter reads cannot be cancelled by the persistence contract. Establish\n  // a generation boundary before the first await so hydration that started\n  // under the previous user cannot commit after this clear completes.\n  engine.hydrationGeneration += 1;\n  try {\n    engine.pendingSets.clear();\n    engine.pendingDeletes.clear();\n    // Clearing the persisted copy alone leaves the in-memory cache holding the\n    // signed-out user's data, which a single-page app keeps serving to whoever\n    // uses the tab next. Drop both.\n    engine.cache.clear();\n    engine.pendingSets.clear();\n    engine.pendingDeletes.clear();\n    // Let an in-flight flush finish its current adapter write before wiping.\n    // Otherwise a write parked in `await adapter.set(...)` resolves after\n    // adapter.clear() and resurrects the data for the next visitor.\n    await engine.flushing;\n    engine.pendingSets.clear();\n    engine.pendingDeletes.clear();\n    await engine.adapter.clear();\n  } catch (error) {\n    disableEngine(engine, error);\n  } finally {\n    engine.clearing = false;\n  }\n}\n\n/** @internal Test hook: flush pending writes immediately. */\nexport async function flushPersistedClientCache(): Promise<void> {\n  const engine = activeEngine;\n  if (!engine) return;\n  if (engine.flushTimer !== undefined) {\n    clearTimeout(engine.flushTimer);\n    engine.flushTimer = undefined;\n  }\n  await flushEngine(engine);\n}\n","export {\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 { enableLiveCacheInvalidation } from \"./cache-invalidation-event-source\";\nexport type { LiveCacheInvalidationOptions } from \"./cache-invalidation-event-source\";\nexport {\n  clearPersistedCache,\n  defineClientCacheAdapter,\n  FARM_CLIENT_CACHE_PERSIST_VERSION,\n  // The generated client entry imports this by name when `cache.client.adapter`\n  // is configured, so it has to be reachable from this entry point.\n  initConfiguredClientCachePersistence,\n  initPersistedClientCache,\n  storageClientCacheAdapter,\n} from \"./client-cache-persistence\";\n// The shared browser store. Features that keep their own rows (for example\n// `@farm.js/sync`) persist through it rather than opening a second store.\nexport { getFarmClientDataCache, normalizeFarmClientCacheKey } from \"./client-cache\";\nexport type {\n  FarmClientCacheEntry,\n  FarmClientCacheKey,\n  FarmClientCacheStatus,\n} from \"./client-cache\";\nexport type {\n  ClientCachePersistenceOptions,\n  FarmClientCacheAdapter,\n  FarmClientCacheStorage,\n  PersistedEntry,\n} from \"./client-cache-persistence\";\nexport {\n  api,\n  endpoint,\n  defineIntegrationAPI,\n  defineIntegrationAPIOperation,\n} from \"./integration-api\";\nexport type {\n  FarmIntegrationAPI,\n  FarmIntegrationAPIBodyFormat,\n  FarmIntegrationAPIMethod,\n  FarmIntegrationAPIOperation,\n  FarmIntegrationAPIResponseFormat,\n} from \"./integration-api\";\nexport { createIntegrationClient, IntegrationClientError } from \"./integration-client\";\nexport {\n  createIntegrationApi,\n  createIntegrationClients,\n  createIntegrations,\n  createIntegrationServerClient,\n  getIntegrationAPIManifest,\n  integrationClients,\n  integrationsClient,\n  integrationsServer,\n} from \"./integration-client\";\nexport type {\n  IntegrationClient,\n  IntegrationClientAliases,\n  IntegrationClientRoot,\n  IntegrationClientOptions,\n  IntegrationClientRequestOptions,\n  IntegrationAPI,\n  IntegrationClients,\n  IntegrationClientData,\n  IntegrationOperationResult,\n  InferIntegrationOperationBody,\n  InferIntegrationOperationQuery,\n  InferIntegrationOperationResponse,\n  IntegrationServerClient,\n  IntegrationServerClientAliases,\n  IntegrationServerClientOptions,\n  IntegrationServerClientRequestOptions,\n  IntegrationServerClientRoot,\n  IntegrationServerRequestLike,\n} from \"./integration-client\";\nexport { createStore } from \"./store\";\nexport { getTheme, setTheme, toggleTheme, useTheme } from \"./theme/client\";\nexport type { UseThemeResult } from \"./theme/client\";\nexport type {\n  Store,\n  StoreApi,\n  StoreFields,\n  StoreListener,\n  StoreKeyListener,\n  StoreKeysListener,\n  StorePatch,\n  StoreState,\n  StoreValueUpdater,\n} from \"./store\";\n\n// SPA Navigation exports\nexport { Link } from \"./client/link\";\nexport {\n  useBlocker,\n  useNavigation,\n  usePageState,\n  useRouter,\n  useScrollRestoration,\n} from \"./client/router\";\nexport {\n  SPARouter,\n  getRouter,\n  navigateTo,\n  prefetch,\n  pushState,\n  readPageState,\n  replaceState,\n} from \"./client/spa-router\";\nexport { installChunkErrorRecovery, isChunkLoadError } from \"./client/chunk-recovery\";\nexport { createClientPluginManager, FarmClientPluginManager } from \"./client/plugin\";\nexport type {\n  LinkProps,\n  PrefetchBehavior,\n  LinkDefaultRoute,\n  DefaultRoutePath,\n  DefaultRoutePattern,\n  DefaultRouteHref,\n  ExternalHref,\n  LinkExternalUriSchemes,\n  RouteHref,\n  RouteParamValue,\n  RouteOptionalParamValue,\n  RouteParams,\n} from \"./client/link\";\nexport type { FarmChunkRecoveryOptions } from \"./client/chunk-recovery\";\nexport type {\n  FarmClientHydrationCompleteEvent,\n  FarmClientHydrationEvent,\n  FarmClientHydrationMode,\n  FarmClientHydrationSession,\n  FarmClientLocation,\n  FarmClientNavigationAction,\n  FarmClientNavigationErrorEvent,\n  FarmClientNavigationEvent,\n  FarmClientNavigationLoadedEvent,\n  FarmClientNavigationResolvedEvent,\n  FarmClientNavigationSession,\n  FarmClientPerformanceEvent,\n  FarmClientPlugin,\n  FarmClientPluginCloseEvent,\n  FarmClientPluginEnforce,\n  FarmClientPluginErrorEvent,\n  FarmClientPluginErrorPhase,\n  FarmClientPluginManagerOptions,\n  FarmClientPluginMetadata,\n  FarmClientPluginRegistration,\n  FarmClientPluginRouter,\n  FarmClientPluginSetupEvent,\n  FarmClientPluginStateEvent,\n} from \"./client/plugin\";\nexport type { UseBlockerOptions, UseBlockerReturn, UseRouterOptions } from \"./client/router\";\nexport type {\n  FarmNavigateOptions,\n  FarmNavigationBlocker,\n  FarmNavigationBlockerContext,\n  FarmNavigationListener,\n  FarmNavigationLocation,\n  FarmNavigationState,\n  FarmViewTransitionMode,\n} from \"./client/spa-router\";\n","import { 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 { resolveFarmNavigationURL } from \"./navigation-url\";\nimport type { FarmViewTransitionMode } from \"./spa-router\";\nimport { isFarmLocaleChangeHref, localizeActiveFarmHref } from \"../i18n/client-state\";\nimport type { FarmI18nLocale } from \"../i18n/types\";\nimport { getFarmTrailingSlashPreference } from \"../trailing-slash\";\nimport { applyFarmBasePath, getFarmBasePath } from \"../base-path\";\nimport { useOptionalFarm } from \"../provider\";\n\n/**\n * Prefetch strategy (TanStack Router–style):\n * - \"intent\": prefetch on hover and touchstart (with prefetchDelay)\n * - \"viewport\": prefetch when link enters viewport (IntersectionObserver)\n * - \"render\": prefetch as soon as the link is mounted\n * - \"none\" | false: no prefetch\n */\nexport type PrefetchBehavior = false | \"intent\" | \"viewport\" | \"render\" | \"none\";\n\n/** @internal Legacy prefetch mode for backward compatibility */\ntype PrefetchLegacy = boolean | \"hover\" | \"viewport\" | \"none\";\n\n/**\n * Augment this interface via the generated farm.d.ts so Link href is typed\n * without passing a generic. Defaults to string when not augmented.\n */\nexport interface LinkDefaultRoute {}\n\nexport type DefaultRoutePath = LinkDefaultRoute extends { _: infer TRoute extends string }\n  ? TRoute\n  : string;\n\nexport type DefaultRoutePattern = LinkDefaultRoute extends {\n  pattern: infer TRoute extends string;\n}\n  ? TRoute\n  : DefaultRoutePath;\n\nexport type DefaultRouteHref = DefaultRoutePath | DefaultRoutePattern;\n\nexport type RouteHref<TRoute extends string> =\n  | TRoute\n  | `${TRoute}?${string}`\n  | `${TRoute}#${string}`\n  | `${TRoute}?${string}#${string}`;\n\n/** A generated route with params already filled into its pathname. */\nexport type ResolvedRouteHref = RouteHref<DefaultRoutePath>;\n\nexport type RouteParamValue = Exclude<FarmRouterPathParam, null | undefined>;\nexport type RouteOptionalParamValue = FarmRouterPathParam;\nexport type RouteParams<TRoute extends string> = string extends TRoute\n  ? FarmRouterPathParams\n  : ExtractRouteParams<StripRouteSuffix<TRoute>>;\n\n/** URI schemes recognized as typed external Link targets. Apps may augment this interface. */\nexport interface LinkExternalUriSchemes {\n  about: true;\n  blob: true;\n  data: true;\n  file: true;\n  ftp: true;\n  ftps: true;\n  geo: true;\n  git: true;\n  http: true;\n  https: true;\n  im: true;\n  intent: true;\n  irc: true;\n  ircs: true;\n  magnet: true;\n  mailto: true;\n  market: true;\n  sms: true;\n  ssh: true;\n  tel: true;\n  urn: true;\n  vscode: true;\n  webcal: true;\n  ws: true;\n  wss: true;\n}\n\ntype ExternalUriScheme = Extract<keyof LinkExternalUriSchemes, string>;\n\ntype UriSchemeLetter =\n  | \"a\"\n  | \"b\"\n  | \"c\"\n  | \"d\"\n  | \"e\"\n  | \"f\"\n  | \"g\"\n  | \"h\"\n  | \"i\"\n  | \"j\"\n  | \"k\"\n  | \"l\"\n  | \"m\"\n  | \"n\"\n  | \"o\"\n  | \"p\"\n  | \"q\"\n  | \"r\"\n  | \"s\"\n  | \"t\"\n  | \"u\"\n  | \"v\"\n  | \"w\"\n  | \"x\"\n  | \"y\"\n  | \"z\";\ntype UriSchemeStart = UriSchemeLetter | Uppercase<UriSchemeLetter>;\ntype UriSchemeCharacter =\n  | UriSchemeStart\n  | \"0\"\n  | \"1\"\n  | \"2\"\n  | \"3\"\n  | \"4\"\n  | \"5\"\n  | \"6\"\n  | \"7\"\n  | \"8\"\n  | \"9\"\n  | \"+\"\n  | \"-\"\n  | \".\";\ntype IsUriSchemeTail<TValue extends string> = TValue extends \"\"\n  ? true\n  : TValue extends `${infer First}${infer Rest}`\n    ? First extends UriSchemeCharacter\n      ? IsUriSchemeTail<Rest>\n      : false\n    : false;\ntype IsUriScheme<TValue extends string> = TValue extends `${infer First}${infer Rest}`\n  ? First extends UriSchemeStart\n    ? IsUriSchemeTail<Rest>\n    : false\n  : false;\n\ntype KnownExternalHref = `//${string}` | `${ExternalUriScheme}:${string}`;\n\n/** External URLs; these are never type-checked as routes. */\nexport type ExternalHref<THref extends string = string> = string extends THref\n  ? KnownExternalHref\n  : THref extends `//${string}`\n    ? THref\n    : THref extends `${infer Scheme}:${string}`\n      ? IsUriScheme<Scheme> extends true\n        ? THref\n        : never\n      : never;\n\ntype StripRouteSuffix<TRoute extends string> = TRoute extends `${infer Path}?${string}`\n  ? StripRouteSuffix<Path>\n  : TRoute extends `${infer Path}#${string}`\n    ? StripRouteSuffix<Path>\n    : TRoute;\n\ntype ExtractRouteParams<TRoute extends string> = Simplify<\n  ExtractOptionalCatchAllParams<TRoute> &\n    ExtractCatchAllParams<TRoute> &\n    ExtractDynamicParams<TRoute>\n>;\n\ntype ExtractOptionalCatchAllParams<TRoute extends string> =\n  TRoute extends `${string}[[...${infer Param}]]${infer Rest}`\n    ? { [Key in Param]?: RouteOptionalParamValue } & ExtractOptionalCatchAllParams<Rest>\n    : {};\n\ntype ExtractCatchAllParams<TRoute extends string> =\n  TRoute extends `${string}[...${infer Param}]${infer Rest}`\n    ? Param extends `[...${string}`\n      ? ExtractCatchAllParams<Rest>\n      : { [Key in Param]: RouteParamValue } & ExtractCatchAllParams<Rest>\n    : {};\n\ntype ExtractDynamicParams<TRoute extends string> =\n  TRoute extends `${string}[${infer Param}]${infer Rest}`\n    ? Param extends `...${string}` | `[...${string}`\n      ? ExtractDynamicParams<Rest>\n      : { [Key in Param]: RouteParamValue } & ExtractDynamicParams<Rest>\n    : {};\n\ntype Simplify<T> = { [Key in keyof T]: T[Key] } & {};\n\ntype HasRouteParams<TRoute extends string> = keyof RouteParams<TRoute> extends never ? false : true;\n\ntype RoutesWithRequiredParams<TRoute extends string> = TRoute extends string\n  ? HasRouteParams<TRoute> extends true\n    ? TRoute\n    : never\n  : never;\n\ntype LinkRouteParamsProps<TRoute extends string> = string extends TRoute\n  ? { params?: FarmRouterPathParams }\n  : HasRouteParams<TRoute> extends true\n    ? { params: RouteParams<TRoute> }\n    : { params?: FarmRouterPathParams };\n\ntype LinkRouteTargetProps<TRoute extends string> = [RoutesWithRequiredParams<TRoute>] extends [\n  never,\n]\n  ? {\n      /** Internal route path with all params already resolved. */\n      href: RouteHref<TRoute>;\n      params?: FarmRouterPathParams;\n    }\n  : TRoute extends string\n    ? {\n        /** Internal route path or route pattern. */\n        href: RouteHref<TRoute>;\n      } & LinkRouteParamsProps<TRoute>\n    : never;\n\ntype LinkExternalTargetProps<THref extends string = string> = {\n  /** External URL; these are never type-checked as app routes. */\n  href: ExternalHref<THref>;\n  params?: never;\n};\n\ntype LinkTargetProps<TRoute extends string, THref extends string> =\n  | LinkExternalTargetProps<THref>\n  | LinkRouteTargetProps<TRoute>;\n\nexport type LinkProps<\n  TRoute extends string = DefaultRouteHref,\n  THref extends string = string,\n> = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> &\n  LinkTargetProps<TRoute, THref> & {\n    /**\n     * When to prefetch. TanStack-style: \"intent\" (hover+touch), \"viewport\", \"render\", or \"none\".\n     * Legacy: true (intent+viewport), \"hover\" (intent), \"viewport\", false/\"none\".\n     */\n    prefetch?: PrefetchBehavior | PrefetchLegacy;\n    /** Search params appended after route params are resolved. */\n    query?: FarmRouterBuildOptions[\"query\"];\n    /** Hash appended after route params and search params are resolved. */\n    hash?: string;\n    /** Add a trailing slash to the generated internal href. */\n    trailingSlash?: boolean;\n    /** Delay in ms before intent-based prefetch (hover/touch). Default 50. */\n    prefetchDelay?: number;\n    /** Replace current history entry instead of pushing */\n    replace?: boolean;\n    /** Scroll to top after navigation (default: true) */\n    scroll?: boolean;\n    /** Wrap this SPA navigation in a browser View Transition when supported. */\n    viewTransition?: FarmViewTransitionMode;\n    /** Preserve the active locale by default, or navigate using this locale. */\n    locale?: FarmI18nLocale;\n  };\n\nfunction isModifierEvent(e: React.MouseEvent): boolean {\n  return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);\n}\n\nfunction isExternalUrl(href: string): boolean {\n  return href.startsWith(\"//\") || /^[a-zA-Z][a-zA-Z\\d+.-]*:/.test(href);\n}\n\nfunction getRouter(): {\n  prefetch(href: string): Promise<void>;\n  observeForPrefetch(el: HTMLAnchorElement): void;\n  unobserveForPrefetch(el: HTMLAnchorElement): void;\n  navigate(\n    href: string,\n    opts: { replace?: boolean; scroll?: boolean; viewTransition?: FarmViewTransitionMode },\n  ): void;\n} | null {\n  if (typeof window !== \"undefined\" && (window as any).__FARM_SPA_ROUTER__) {\n    return (window as any).__FARM_SPA_ROUTER__;\n  }\n  return null;\n}\n\nfunction normalizePrefetch(prefetch: LinkProps[\"prefetch\"]): {\n  intent: boolean;\n  viewport: boolean;\n  render: boolean;\n} {\n  if (prefetch === false || prefetch === \"none\") {\n    return { intent: false, viewport: false, render: false };\n  }\n  if (prefetch === true) {\n    return { intent: true, viewport: true, render: false };\n  }\n  if (prefetch === \"hover\") {\n    return { intent: true, viewport: false, render: false };\n  }\n  if (prefetch === \"intent\") {\n    return { intent: true, viewport: false, render: false };\n  }\n  if (prefetch === \"viewport\") {\n    return { intent: false, viewport: true, render: false };\n  }\n  if (prefetch === \"render\") {\n    return { intent: false, viewport: false, render: true };\n  }\n  return { intent: false, viewport: false, render: false };\n}\n\nfunction LinkInner<TRoute extends string = DefaultRouteHref, THref extends string = string>(\n  {\n    href,\n    params,\n    query,\n    hash,\n    trailingSlash,\n    prefetch = true,\n    prefetchDelay = 50,\n    replace = false,\n    scroll = true,\n    viewTransition = false,\n    locale,\n    onClick,\n    target,\n    onMouseEnter,\n    onMouseLeave,\n    onFocus,\n    onBlur,\n    onTouchStart,\n    ...props\n  }: LinkProps<TRoute, THref>,\n  ref: React.ForwardedRef<HTMLAnchorElement>,\n) {\n  const elementRef = useRef<HTMLAnchorElement | null>(null);\n  const intentTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const activePrefetch = useRef<symbol | null>(null);\n  const farm = useOptionalFarm();\n\n  const { intent, viewport, render } = normalizePrefetch(prefetch);\n  const baseHref = resolveLinkHref(href, params, {\n    query,\n    hash,\n    trailingSlash: trailingSlash ?? getFarmTrailingSlashPreference(),\n  });\n  const localizedHref = localizeActiveFarmHref(baseHref, locale);\n  const resolvedHref = isExternalUrl(localizedHref)\n    ? localizedHref\n    : applyFarmBasePath(localizedHref, farm?.basePath ?? getFarmBasePath());\n  const isExternal = isExternalUrl(resolvedHref);\n\n  const doPrefetch = useCallback(() => {\n    if (isExternal || activePrefetch.current) return;\n    const router = getRouter();\n    if (!router) return;\n    const token = Symbol(resolvedHref);\n    activePrefetch.current = token;\n    const reset = () => {\n      if (activePrefetch.current === token) activePrefetch.current = null;\n    };\n    try {\n      void router.prefetch(resolvedHref).then(reset, reset);\n    } catch {\n      reset();\n    }\n  }, [resolvedHref, isExternal]);\n\n  useEffect(() => {\n    activePrefetch.current = null;\n  }, [resolvedHref]);\n\n  useEffect(() => {\n    const element = elementRef.current;\n    if (!element || isExternal) return;\n\n    const router = getRouter();\n    if (!router) return;\n\n    if (viewport) {\n      router.observeForPrefetch(element);\n      return () => router.unobserveForPrefetch(element);\n    }\n  }, [resolvedHref, viewport, isExternal]);\n\n  useEffect(() => {\n    if (!render || isExternal) return;\n\n    let cancelled = false;\n    let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n    const tryRenderPrefetch = () => {\n      if (cancelled || activePrefetch.current) return;\n\n      const router = getRouter();\n      if (!router) {\n        timeoutId = setTimeout(tryRenderPrefetch, 30);\n        return;\n      }\n\n      doPrefetch();\n    };\n\n    tryRenderPrefetch();\n\n    return () => {\n      cancelled = true;\n      if (timeoutId) {\n        clearTimeout(timeoutId);\n      }\n    };\n  }, [render, isExternal, resolvedHref, doPrefetch]);\n\n  useEffect(() => {\n    return () => {\n      if (intentTimeoutRef.current) {\n        clearTimeout(intentTimeoutRef.current);\n        intentTimeoutRef.current = null;\n      }\n    };\n  }, []);\n\n  const cancelIntent = useCallback(() => {\n    if (intentTimeoutRef.current) {\n      clearTimeout(intentTimeoutRef.current);\n      intentTimeoutRef.current = null;\n    }\n  }, []);\n\n  const scheduleIntentPrefetch = useCallback(() => {\n    if (isExternal || !intent || activePrefetch.current) return;\n    cancelIntent();\n    intentTimeoutRef.current = setTimeout(() => {\n      intentTimeoutRef.current = null;\n      doPrefetch();\n    }, prefetchDelay);\n  }, [intent, isExternal, prefetchDelay, doPrefetch, cancelIntent]);\n\n  const handleMouseEnter = useCallback(\n    (event: React.MouseEvent<HTMLAnchorElement>) => {\n      onMouseEnter?.(event);\n      scheduleIntentPrefetch();\n    },\n    [onMouseEnter, scheduleIntentPrefetch],\n  );\n\n  const handleMouseLeave = useCallback(\n    (event: React.MouseEvent<HTMLAnchorElement>) => {\n      onMouseLeave?.(event);\n      cancelIntent();\n    },\n    [onMouseLeave, cancelIntent],\n  );\n\n  const handleTouchStart = useCallback(\n    (event: React.TouchEvent<HTMLAnchorElement>) => {\n      onTouchStart?.(event);\n      scheduleIntentPrefetch();\n    },\n    [onTouchStart, scheduleIntentPrefetch],\n  );\n\n  const handleFocus = useCallback(\n    (event: React.FocusEvent<HTMLAnchorElement>) => {\n      onFocus?.(event);\n      scheduleIntentPrefetch();\n    },\n    [onFocus, scheduleIntentPrefetch],\n  );\n\n  const handleBlur = useCallback(\n    (event: React.FocusEvent<HTMLAnchorElement>) => {\n      onBlur?.(event);\n      cancelIntent();\n    },\n    [onBlur, cancelIntent],\n  );\n\n  const handleClick = useCallback(\n    (event: React.MouseEvent<HTMLAnchorElement>) => {\n      onClick?.(event);\n      if (event.defaultPrevented) return;\n      if (isExternal) return;\n      if (event.currentTarget.hasAttribute(\"download\")) return;\n      if (target && target !== \"_self\") return;\n      if (isModifierEvent(event)) return;\n      if (event.button !== 0) return;\n\n      if (typeof window !== \"undefined\") {\n        event.preventDefault();\n        if (isFarmLocaleChangeHref(localizedHref)) {\n          window.location.assign(resolvedHref);\n          return;\n        }\n        const router = getRouter();\n        if (router) {\n          router.navigate(resolvedHref, { replace, scroll, viewTransition });\n        } else {\n          if (replace) window.location.replace(resolvedHref);\n          else window.location.href = resolvedHref;\n        }\n      }\n    },\n    [localizedHref, resolvedHref, replace, scroll, viewTransition, target, isExternal, onClick],\n  );\n\n  const setRefs = useCallback(\n    (node: HTMLAnchorElement | null) => {\n      elementRef.current = node;\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) (ref as React.MutableRefObject<HTMLAnchorElement | null>).current = node;\n    },\n    [ref],\n  );\n\n  return (\n    <a\n      ref={setRefs}\n      href={resolvedHref}\n      target={target}\n      onClick={handleClick}\n      onMouseEnter={handleMouseEnter}\n      onMouseLeave={handleMouseLeave}\n      onFocus={handleFocus}\n      onBlur={handleBlur}\n      onTouchStart={handleTouchStart}\n      {...props}\n      data-farm-link=\"\"\n      data-replace={replace ? \"\" : undefined}\n      data-no-scroll={!scroll ? \"\" : undefined}\n      data-view-transition={\n        viewTransition === \"auto\" ? \"auto\" : viewTransition ? \"true\" : undefined\n      }\n    />\n  );\n}\n\nconst LinkWithRef = forwardRef(LinkInner);\nLinkWithRef.displayName = \"Link\";\n\ntype LinkComponentType = <TRoute extends string = DefaultRouteHref, THref extends string = string>(\n  props: LinkProps<TRoute, THref> & { ref?: React.ForwardedRef<HTMLAnchorElement> },\n) => React.ReactElement;\n\nexport const Link = LinkWithRef as unknown as LinkComponentType;\n\nfunction resolveLinkHref(\n  href: string,\n  params: FarmRouterPathParams | undefined,\n  options: FarmRouterBuildOptions,\n) {\n  if (isExternalUrl(href)) return href;\n\n  const { pathname, query, hash } = splitInternalHref(href);\n\n  const resolvedHref = buildFarmRoutePath(pathname, params, {\n    query: mergeQueryParams(query, options.query),\n    hash: options.hash ?? hash,\n    trailingSlash: options.trailingSlash,\n  });\n\n  return applyPreservedSearchParams(resolvedHref);\n}\n\nfunction splitInternalHref(href: string) {\n  try {\n    const url = new URL(href, \"http://farm.local\");\n    return {\n      pathname: url.pathname || \"/\",\n      query: url.searchParams,\n      hash: url.hash ? url.hash.slice(1) : undefined,\n    };\n  } catch {\n    const [withoutHash, rawHash] = href.split(\"#\", 2);\n    const [pathname, rawQuery] = withoutHash.split(\"?\", 2);\n    return {\n      pathname: pathname || \"/\",\n      query: new URLSearchParams(rawQuery || \"\"),\n      hash: rawHash,\n    };\n  }\n}\n\nfunction mergeQueryParams(\n  current: URLSearchParams,\n  next: FarmRouterBuildOptions[\"query\"],\n): URLSearchParams | undefined {\n  const merged = new URLSearchParams(current);\n\n  if (next instanceof URLSearchParams) {\n    for (const [key, value] of next.entries()) {\n      merged.append(key, value);\n    }\n  } else if (next) {\n    for (const [key, value] of Object.entries(next)) {\n      const values = Array.isArray(value) ? value : [value];\n      for (const item of values) {\n        if (item == null) continue;\n        merged.append(key, String(item));\n      }\n    }\n  }\n\n  return merged.toString() ? merged : undefined;\n}\n\nfunction applyPreservedSearchParams(href: string): string {\n  if (typeof window === \"undefined\") return href;\n\n  const manifest = (window as any).__FARM_MANIFEST__;\n  const routes =\n    manifest?.routes && typeof manifest.routes === \"object\" ? Object.values(manifest.routes) : [];\n  if (routes.length === 0) return href;\n\n  const url = resolveFarmNavigationURL(href, window.location.href);\n  const route = routes.find((candidate: any) => matchManifestRoute(url.pathname, candidate));\n  const preserve = Array.isArray((route as any)?.search?.preserve)\n    ? ((route as any).search.preserve as string[])\n    : [];\n  if (preserve.length === 0) return href;\n\n  const current = new URLSearchParams(window.location.search);\n  let changed = false;\n\n  for (const key of preserve) {\n    if (url.searchParams.has(key) || !current.has(key)) continue;\n    for (const value of current.getAll(key)) {\n      url.searchParams.append(key, value);\n      changed = true;\n    }\n  }\n\n  if (!changed) return href;\n  return `${url.pathname}${url.search}${url.hash}`;\n}\n\nfunction matchManifestRoute(pathname: string, route: any): boolean {\n  if (!route || !Array.isArray(route.segments)) return false;\n  const routeSegments = route.segments;\n  const normalized = pathname === \"/\" ? \"\" : pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  const pathSegments = normalized ? normalized.split(\"/\") : [];\n  const hasCatchAll = routeSegments.some((segment: any) => segment.isCatchAll);\n\n  if (!hasCatchAll && pathSegments.length !== routeSegments.length) {\n    return false;\n  }\n\n  for (let index = 0; index < routeSegments.length; index++) {\n    const routeSegment = routeSegments[index];\n    const pathSegment = pathSegments[index];\n\n    if (routeSegment.isCatchAll) {\n      return true;\n    }\n\n    if (pathSegment === undefined) {\n      if (routeSegment.isOptional) continue;\n      return false;\n    }\n\n    if (!routeSegment.isDynamic && routeSegment.segment !== pathSegment) {\n      return false;\n    }\n  }\n\n  return pathSegments.length === routeSegments.length || hasCatchAll;\n}\n","export function isFarmExternalNavigationURL(url: URL, currentOrigin: string): boolean {\n  return (url.protocol !== \"http:\" && url.protocol !== \"https:\") || url.origin !== currentOrigin;\n}\n\n/**\n * Resolve a navigation target the way the platform does.\n *\n * Relative references resolve against the *document's* URL, not the origin.\n * Basing on the origin turns `?tab=2` into `/?tab=2` and `details` into\n * `/details`, discarding the directory the user is actually on, so every\n * navigation entry point has to resolve through here.\n *\n * Absolute paths and absolute URLs are unaffected by the choice of base.\n */\nexport function resolveFarmNavigationURL(href: string, documentUrl: string): URL {\n  return new URL(href, documentUrl);\n}\n","import type IntlMessageFormat from \"intl-messageformat\";\nimport { resolveFarmNavigationURL } from \"../client/navigation-url\";\nimport { getActiveFarmI18nSnapshot } from \"./bridge\";\nimport { localizeFarmHref, resolveFarmLocalePath } from \"./routing\";\nimport type { FarmI18nClientSnapshot, FarmI18nLocale } from \"./types\";\n\ntype Listener = () => void;\n\nconst listeners = new Set<Listener>();\n// State owns invalidation so a locale change clears formatters before notifying\n// subscribers, even if they translate synchronously. The type-only import keeps\n// ICU parsing/formatting out of navigation-only bundles.\nexport const compiledFarmI18nMessages = 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) compiledFarmI18nMessages.clear();\n  for (const listener of listeners) listener();\n}\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 = resolveFarmNavigationURL(href, window.location.href);\n  const match = resolveFarmLocalePath(target.pathname, snapshot);\n  const targetLocale = match.locale || snapshot.defaultLocale;\n  return targetLocale !== snapshot.locale;\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-state\";\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 { createClientCancellation } from \"../client-cancellation\";\nimport { notifyHistoryChange, notifyRouterHistoryChange } from \"./history-sync\";\nimport {\n  createFarmDeploymentMismatchError,\n  createFarmDeploymentRequestHeaders,\n  isFarmDeploymentMismatchResponse,\n} from \"../deployment\";\nimport { getHashTargetElement } from \"./hash-target\";\nimport { isFarmExternalNavigationURL, resolveFarmNavigationURL } from \"./navigation-url\";\nimport { applyFarmMetadataToDocument, type NavigationMetadata } from \"./metadata-reconciler\";\nimport type { FarmClientNavigationSession, FarmClientPluginManager } from \"./plugin\";\nimport { _hydrateFarmI18n, isFarmLocaleChangeHref } from \"../i18n/client-state\";\nimport type { FarmI18nClientSnapshot } from \"../i18n/types\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport type { FarmRouteRenderPlan } from \"../navigation/render-plan\";\n\nexport { getHashTargetElement } from \"./hash-target\";\nexport { isFarmExternalNavigationURL } from \"./navigation-url\";\n\n/**\n * Farm.js SPA Router\n *\n * Provides client-side navigation without full page reloads.\n * Features:\n * - Prefetch on viewport intersection\n * - Prefetch on hover\n * - Page caching\n * - History API integration\n * - Scroll restoration\n */\n\ninterface PageData {\n  props: Record<string, any>;\n  modulePath: string;\n  loadingModulePath?: string | null;\n  canonicalPath?: string;\n  isClientComponent?: boolean;\n  shouldHydrate?: boolean;\n  islandStrategy?: FarmIslandStrategy | null;\n  renderPlan?: FarmRouteRenderPlan;\n  fragment?: {\n    html: string;\n    layoutPatterns: string[];\n  };\n  metadata?: NavigationMetadata;\n  layoutModules?: string[];\n  routeSlots?: RouteSlotPageData[];\n  interception?: {\n    from?: string;\n    slots: string[];\n  };\n  i18n?: FarmI18nClientSnapshot;\n}\n\ninterface RouteSlotPageData {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  interception: boolean;\n  fallback: boolean;\n  modulePath: string;\n  isClientComponent: boolean;\n  shouldHydrate: boolean;\n  props: Record<string, any>;\n}\n\nexport interface RouterOptions {\n  prefetchTimeout?: number;\n  cacheMaxAge?: number;\n  scrollRestoration?: boolean;\n  shouldUseDocumentNavigation?: (pathname: string) => boolean;\n  deploymentId?: string;\n}\n\ninterface CacheEntry {\n  data: PageData;\n  timestamp: number;\n}\n\ninterface PendingPrefetch {\n  data: Promise<PageData | undefined>;\n  resolve: (data: PageData | undefined) => void;\n  cacheable: boolean;\n}\n\ninterface ViewportPrefetchTask {\n  href: string;\n  elements: Set<HTMLAnchorElement>;\n  cancelled: boolean;\n  started: boolean;\n}\n\nconst MAX_CONCURRENT_VIEWPORT_PREFETCHES = 4;\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 pendingPrefetches: Map<string, PendingPrefetch> = new Map();\n  private cacheGeneration = 0;\n  private prefetchObserver?: IntersectionObserver;\n  private observedPrefetchLinks: Map<HTMLAnchorElement, string> = new Map();\n  private prefetchTimers: Map<Element, ReturnType<typeof setTimeout>> = new Map();\n  private viewportPrefetchQueue: ViewportPrefetchTask[] = [];\n  private viewportPrefetchTasksByHref: Map<string, ViewportPrefetchTask> = new Map();\n  private viewportPrefetchTasksByElement: Map<HTMLAnchorElement, ViewportPrefetchTask> = new Map();\n  private activeViewportPrefetches = 0;\n  private destroyed = false;\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 currentHistoryHash = \"\";\n  private currentInterceptFrom: unknown;\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      this.currentHistoryHash = window.location.hash;\n      this.currentInterceptFrom = window.history.state?.[FARM_INTERCEPT_FROM_KEY];\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.destroyed = true;\n    this.cancelActiveNavigation();\n    this.clearCache();\n    this.prefetchObserver?.disconnect();\n    this.prefetchObserver = undefined;\n    for (const timer of this.prefetchTimers.values()) clearTimeout(timer);\n    this.observedPrefetchLinks.clear();\n    this.prefetchTimers.clear();\n    for (const task of this.viewportPrefetchQueue) task.cancelled = true;\n    this.viewportPrefetchQueue.length = 0;\n    this.viewportPrefetchTasksByHref.clear();\n    this.viewportPrefetchTasksByElement.clear();\n    window.removeEventListener(\"popstate\", this.onPopState);\n    window.removeEventListener(\"beforeunload\", this.onBeforeUnload);\n  }\n\n  /**\n   * Set the navigation handler that updates React\n   */\n  setNavigationHandler(handler: (data: PageData) => Promise<void>) {\n    this.onNavigate = handler;\n  }\n\n  /**\n   * Connect Farm's browser plugin lifecycle to SPA navigation.\n   */\n  setClientPluginManager(manager: FarmClientPluginManager) {\n    this.clientPlugins = manager;\n  }\n\n  /**\n   * Navigate to a new URL\n   */\n  async navigate(href: string, options: FarmNavigateOptions = {}): Promise<void> {\n    const {\n      replace = false,\n      scroll = true,\n      state,\n      viewTransition = false,\n      refresh = false,\n    } = options;\n\n    // Relative targets resolve against the current document, not the origin.\n    const url = resolveFarmNavigationURL(href, window.location.href);\n    const pathname = url.pathname;\n    const search = url.search;\n    const fullPath = pathname + search;\n\n    if (\n      isFarmExternalNavigationURL(url, window.location.origin) ||\n      isFarmLocaleChangeHref(url.toString()) ||\n      this.options.shouldUseDocumentNavigation(pathname)\n    ) {\n      this.cancelActiveNavigation();\n      if (replace) window.location.replace(url.toString());\n      else window.location.assign(url.toString());\n      return;\n    }\n\n    // Same page navigation - update fragment history without fetching route data.\n    if (!refresh && pathname === window.location.pathname && search === window.location.search) {\n      this.cancelActiveNavigation();\n      if (url.hash === window.location.hash) return;\n\n      this.writePageState(\n        replace ? \"replace\" : \"push\",\n        state === undefined ? readPageState() : state,\n        url.toString(),\n      );\n      if (scroll) {\n        if (url.hash) {\n          getHashTargetElement(url.hash)?.scrollIntoView();\n        } else {\n          window.scrollTo(0, 0);\n        }\n      }\n      return;\n    }\n\n    const from = window.location.pathname + window.location.search;\n    if (\n      await this.shouldBlockNavigation({\n        from,\n        to: fullPath,\n        action: replace ? \"replace\" : \"push\",\n      })\n    ) {\n      return;\n    }\n\n    // Save current scroll position\n    if (this.options.scrollRestoration) {\n      this.saveScrollPosition(window.location.pathname + window.location.search);\n    }\n\n    const navigation = this.startNavigation({\n      from,\n      to: createNavigationLocation(url),\n      action: replace ? \"replace\" : \"push\",\n    });\n\n    let clientNavigation: FarmClientNavigationSession | undefined;\n    try {\n      clientNavigation = await this.clientPlugins?.beginNavigation({\n        from,\n        to: url,\n        action: replace ? \"replace\" : \"push\",\n      });\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      // Fetch page data (from cache or server)\n      const pageData = await this.fetchPageData(\n        fullPath,\n        true,\n        from,\n        refresh,\n        navigation.controller.signal,\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);\n      }\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      await this.runViewTransition(viewTransition, () =>\n        this.isCurrentNavigation(navigation, clientNavigation)\n          ? this.commitNavigation({\n              fullPath,\n              pageData,\n              pathname,\n              replace,\n              scroll,\n              state,\n              url,\n            })\n          : Promise.resolve(),\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      if (clientNavigation) {\n        await this.clientPlugins?.resolveNavigation(clientNavigation);\n        void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);\n      }\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      console.error(\"[Farm.js] Navigation error:\", error);\n      // Fall back to full page navigation\n      window.location.href = href;\n    }\n  }\n\n  /**\n   * Re-render the active route from the server while preserving the document,\n   * shared layouts, client runtime, and browser history entry.\n   */\n  refresh(options: Omit<FarmNavigateOptions, \"replace\" | \"refresh\"> = {}): Promise<void> {\n    return this.navigate(window.location.href, {\n      ...options,\n      replace: true,\n      refresh: true,\n      scroll: options.scroll ?? false,\n    });\n  }\n\n  /**\n   * Prefetch a URL\n   */\n  async prefetch(href: string): Promise<void> {\n    if (this.destroyed) return;\n    if (isFarmLocaleChangeHref(href)) return;\n    const url = resolveFarmNavigationURL(href, window.location.href);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) return;\n    if (this.options.shouldUseDocumentNavigation(url.pathname)) return;\n    const fullPath = url.pathname + url.search;\n    const interceptFrom = window.location.pathname + window.location.search;\n\n    // Skip if already prefetching or cached\n    if (this.prefetchingUrls.has(fullPath)) return;\n    if (this.isCached(fullPath, interceptFrom)) return;\n\n    this.prefetchingUrls.add(fullPath);\n\n    try {\n      await this.fetchPageData(fullPath, false, interceptFrom);\n    } catch (error) {\n      console.warn(\"[Farm.js] Prefetch failed:\", href, error);\n    } finally {\n      this.prefetchingUrls.delete(fullPath);\n    }\n  }\n\n  /**\n   * Observe an element for viewport intersection (prefetch when visible)\n   */\n  observeForPrefetch(element: HTMLAnchorElement): void {\n    if (this.destroyed || typeof IntersectionObserver === \"undefined\") return;\n\n    const href = element.getAttribute(\"href\");\n    if (!href || this.isExternalUrl(href)) return;\n    this.unobserveForPrefetch(element);\n    const observer = this.getPrefetchObserver();\n    this.observedPrefetchLinks.set(element, href);\n    observer.observe(element);\n  }\n\n  /**\n   * Stop observing an element\n   */\n  unobserveForPrefetch(element: HTMLAnchorElement): void {\n    if (this.observedPrefetchLinks.delete(element)) {\n      this.prefetchObserver?.unobserve(element);\n    }\n    const timer = this.prefetchTimers.get(element);\n    if (timer !== undefined) {\n      clearTimeout(timer);\n      this.prefetchTimers.delete(element);\n    }\n    this.cancelQueuedViewportPrefetch(element);\n  }\n\n  private getPrefetchObserver(): IntersectionObserver {\n    this.prefetchObserver ??= new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) {\n          if (!entry.isIntersecting) continue;\n          const element = entry.target as HTMLAnchorElement;\n          const href = this.observedPrefetchLinks.get(element);\n          if (!href) continue;\n\n          this.prefetchObserver?.unobserve(element);\n          this.observedPrefetchLinks.delete(element);\n          // Delay viewport work slightly so links passed during a scroll do not\n          // immediately compete with the active document for network slots.\n          const timer = setTimeout(() => {\n            if (this.prefetchTimers.get(element) !== timer) return;\n            this.prefetchTimers.delete(element);\n            this.enqueueViewportPrefetch(element, href);\n          }, this.options.prefetchTimeout);\n          this.prefetchTimers.set(element, timer);\n        }\n      },\n      { rootMargin: \"200px\" },\n    );\n    return this.prefetchObserver;\n  }\n\n  private enqueueViewportPrefetch(element: HTMLAnchorElement, href: string): void {\n    if (this.destroyed) return;\n    let task = this.viewportPrefetchTasksByHref.get(href);\n    if (!task) {\n      task = { href, elements: new Set(), cancelled: false, started: false };\n      this.viewportPrefetchTasksByHref.set(href, task);\n      this.viewportPrefetchQueue.push(task);\n    }\n    task.elements.add(element);\n    this.viewportPrefetchTasksByElement.set(element, task);\n    this.drainViewportPrefetchQueue();\n  }\n\n  private cancelQueuedViewportPrefetch(element: HTMLAnchorElement): void {\n    const task = this.viewportPrefetchTasksByElement.get(element);\n    if (!task) return;\n    this.viewportPrefetchTasksByElement.delete(element);\n    task.elements.delete(element);\n    if (task.elements.size > 0) return;\n    if (task.started) return;\n    task.cancelled = true;\n    if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n      this.viewportPrefetchTasksByHref.delete(task.href);\n    }\n  }\n\n  private drainViewportPrefetchQueue(): void {\n    while (\n      !this.destroyed &&\n      this.activeViewportPrefetches < MAX_CONCURRENT_VIEWPORT_PREFETCHES &&\n      this.viewportPrefetchQueue.length > 0\n    ) {\n      const task = this.viewportPrefetchQueue.shift()!;\n      if (task.cancelled || task.elements.size === 0) {\n        if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n          this.viewportPrefetchTasksByHref.delete(task.href);\n        }\n        continue;\n      }\n\n      task.started = true;\n      this.activeViewportPrefetches += 1;\n      let prefetchResult: Promise<void> | void;\n      try {\n        prefetchResult = this.prefetch(task.href);\n      } catch {\n        prefetchResult = undefined;\n      }\n      void Promise.resolve(prefetchResult)\n        .catch(() => undefined)\n        .finally(() => {\n          if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n            this.viewportPrefetchTasksByHref.delete(task.href);\n          }\n          for (const element of task.elements) {\n            if (this.viewportPrefetchTasksByElement.get(element) === task) {\n              this.viewportPrefetchTasksByElement.delete(element);\n            }\n          }\n          this.activeViewportPrefetches -= 1;\n          this.drainViewportPrefetchQueue();\n        });\n    }\n  }\n\n  addBlocker(blocker: FarmNavigationBlocker, shouldBlockUnload?: () => boolean): () => void {\n    this.blockers.add(blocker);\n    this.unloadBlockers.set(\n      blocker,\n      shouldBlockUnload ?? (() => this.evaluateBlockerForUnload(blocker)),\n    );\n    return () => {\n      this.blockers.delete(blocker);\n      this.unloadBlockers.delete(blocker);\n    };\n  }\n\n  getNavigationState(): FarmNavigationState {\n    return this.navigationState;\n  }\n\n  subscribeNavigation(listener: FarmNavigationListener): () => void {\n    this.navigationListeners.add(listener);\n    listener(this.navigationState);\n    return () => {\n      this.navigationListeners.delete(listener);\n    };\n  }\n\n  registerScrollElement(key: string, element: HTMLElement): () => void {\n    this.scrollElements.set(key, element);\n    this.restoreScrollElement(window.location.pathname + window.location.search, key, element);\n    return () => {\n      if (this.scrollElements.get(key) === element) {\n        this.scrollElements.delete(key);\n      }\n    };\n  }\n\n  pushState(state: unknown, href?: string): void {\n    this.writePageState(\"push\", state, href);\n  }\n\n  replaceState(state: unknown, href?: string): void {\n    this.writePageState(\"replace\", state, href);\n  }\n\n  /** @internal Keep shallow URL-search writes inside the router's history bookkeeping. */\n  writeURLSearch(action: \"push\" | \"replace\", href: string): void {\n    this.writePageState(action, readPageState(), href, false);\n  }\n\n  private async commitNavigation(options: {\n    fullPath: string;\n    pageData: PageData;\n    pathname: string;\n    replace: boolean;\n    scroll: boolean;\n    state: unknown;\n    url: URL;\n  }): Promise<void> {\n    const historyUrl = resolveFarmNavigationURL(\n      options.pageData.canonicalPath || options.fullPath,\n      window.location.href,\n    );\n    historyUrl.hash = options.url.hash;\n    const historyPath = historyUrl.pathname + historyUrl.search + historyUrl.hash;\n    const historyState = createHistoryState(\n      historyPath,\n      options.state,\n      options.replace ? window.history.state : undefined,\n      options.pageData.interception?.from ?? null,\n    ) as Record<string, unknown>;\n    const nextHistoryIndex =\n      this.currentHistoryIndex == null\n        ? null\n        : options.replace\n          ? this.currentHistoryIndex\n          : this.currentHistoryIndex + 1;\n    if (nextHistoryIndex != null) {\n      historyState[FARM_HISTORY_INDEX_KEY] = nextHistoryIndex;\n    }\n    if (options.replace) {\n      window.history.replaceState(historyState, \"\", historyPath);\n    } else {\n      window.history.pushState(historyState, \"\", historyPath);\n    }\n    this.currentHistoryIndex = nextHistoryIndex;\n    const resolvedHistoryUrl = resolveFarmNavigationURL(historyPath, window.location.href);\n    this.currentHistoryPath = resolvedHistoryUrl.pathname + resolvedHistoryUrl.search;\n    this.currentHistoryHash = resolvedHistoryUrl.hash;\n    this.currentInterceptFrom = historyState[FARM_INTERCEPT_FROM_KEY];\n    notifyRouterHistoryChange();\n\n    this.updateDocumentMetadata(options.pageData.metadata);\n\n    _hydrateFarmI18n(options.pageData.i18n);\n\n    if (this.onNavigate) {\n      await this.onNavigate(options.pageData);\n    }\n\n    if (options.scroll) {\n      if (options.url.hash) {\n        const element = getHashTargetElement(options.url.hash);\n        if (element) {\n          element.scrollIntoView();\n        }\n      } else {\n        window.scrollTo(0, 0);\n      }\n    } else if (this.options.scrollRestoration) {\n      const restorePath = this.currentHistoryPath ?? options.fullPath;\n      this.restoreWindowScroll(restorePath);\n      this.restoreScrollElements(restorePath);\n    }\n  }\n\n  private async runViewTransition(\n    mode: FarmViewTransitionMode,\n    callback: () => Promise<void>,\n  ): Promise<void> {\n    if (!mode || typeof document === \"undefined\") {\n      await callback();\n      return;\n    }\n\n    const startViewTransition = (document as any).startViewTransition;\n    if (typeof startViewTransition !== \"function\") {\n      await callback();\n      return;\n    }\n\n    const transition = startViewTransition.call(document, () => callback());\n    const updateDone = transition?.updateCallbackDone || transition?.ready;\n    if (updateDone && typeof updateDone.then === \"function\") {\n      await updateDone;\n    }\n    transition?.finished?.catch?.(() => undefined);\n  }\n\n  /**\n   * Fetch page data from cache or server\n   */\n  private async fetchPageData(\n    path: string,\n    recover = true,\n    interceptFrom?: string,\n    fresh = false,\n    signal?: AbortSignal,\n  ): Promise<PageData> {\n    const cacheKey = getPageDataCacheKey(path, interceptFrom);\n    // Check cache first\n    const cached = fresh ? undefined : this.cache.get(cacheKey);\n    if (cached && Date.now() - cached.timestamp < this.options.cacheMaxAge) {\n      return cached.data;\n    }\n\n    // Fetch from server. The active layout chain lets the server omit shared\n    // shell HTML from the fragment without inspecting component source.\n    const activeLayoutChain = getActiveLayoutChainHeader();\n    const prefetchKey = JSON.stringify([path, interceptFrom, activeLayoutChain]);\n    let generation = this.cacheGeneration;\n    const pending = this.pendingPrefetches.get(prefetchKey);\n    if (pending && recover) {\n      if (fresh) {\n        // An explicit refresh must not reuse, or later be overwritten by, old work.\n        pending.cacheable = false;\n        pending.resolve(undefined);\n        this.pendingPrefetches.delete(prefetchKey);\n      } else {\n        // Cancelling this navigation must not cancel the background prefetch.\n        const cancellation = createClientCancellation(signal);\n        try {\n          const data = await cancellation.run(() => pending.data);\n          cancellation.check();\n          if (data && pending.cacheable && generation === this.cacheGeneration) return data;\n        } finally {\n          cancellation.dispose();\n        }\n      }\n    }\n\n    // A cleared cache releases a waiter into a new, independently cacheable request.\n    generation = this.cacheGeneration;\n    let prefetch: PendingPrefetch | undefined;\n    if (!recover) {\n      let resolve!: PendingPrefetch[\"resolve\"];\n      const data = new Promise<PageData | undefined>((done) => {\n        resolve = done;\n      });\n      prefetch = { data, resolve, cacheable: true };\n      this.pendingPrefetches.set(prefetchKey, prefetch);\n    }\n    const cacheData = (data: PageData) => {\n      if (!this.destroyed && generation === this.cacheGeneration && prefetch?.cacheable !== false) {\n        this.cachePageData(cacheKey, data);\n      }\n    };\n    try {\n      return await this.requestPageData(\n        path,\n        recover,\n        interceptFrom,\n        activeLayoutChain,\n        signal,\n        cacheData,\n        prefetch?.resolve,\n      );\n    } finally {\n      // Release joiners on failure too: navigation retries through its own recovery path.\n      prefetch?.resolve(undefined);\n      if (prefetch && this.pendingPrefetches.get(prefetchKey) === prefetch) {\n        this.pendingPrefetches.delete(prefetchKey);\n      }\n    }\n  }\n\n  private async requestPageData(\n    path: string,\n    recover: boolean,\n    interceptFrom: string | undefined,\n    activeLayoutChain: string | undefined,\n    signal: AbortSignal | undefined,\n    cacheData: (data: PageData) => void,\n    resolvePrefetch?: PendingPrefetch[\"resolve\"],\n  ): Promise<PageData> {\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 isDeferredResponse = (response.headers.get(\"Content-Type\") || \"\")\n      .toLowerCase()\n      .startsWith(\"application/x-farm-deferred+json\");\n\n    if (!isDeferredResponse) {\n      const data = await readDeferredDataResponse<PageData>(response);\n      cacheData(data);\n      resolvePrefetch?.(data);\n      return data;\n    }\n\n    // Deferred streams keep independent ownership and abort behavior. Release\n    // navigation at the response headers; do not wait for deferred values.\n    resolvePrefetch?.(undefined);\n    // The first deferred stream line is available before its promises settle.\n    // Do not cache that object until the stream closes normally: an aborted\n    // navigation otherwise leaves rejected deferreds in the page-data cache.\n    let data: PageData | undefined;\n    let streamCompleted = false;\n    const markStreamComplete = () => {\n      streamCompleted = true;\n      if (data) cacheData(data);\n    };\n    data = await readDeferredDataResponse<PageData>(response, {\n      onComplete: markStreamComplete,\n    });\n    if (streamCompleted) cacheData(data);\n\n    return data;\n  }\n\n  private cachePageData(cacheKey: string, data: PageData): void {\n    // Expiry was previously only consulted on read, so a long-lived tab that\n    // navigates or prefetches many distinct routes grew this map without\n    // bound; sweeping on write bounds it to entries touched within the\n    // cacheMaxAge window.\n    const now = Date.now();\n    for (const [key, entry] of this.cache) {\n      if (now - entry.timestamp >= this.options.cacheMaxAge) this.cache.delete(key);\n    }\n    this.cache.set(cacheKey, { data, timestamp: now });\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    // Native fragment links and their Back/Forward entries also emit popstate.\n    // They stay in the current document: let the browser own anchor scrolling\n    // and history subscribers update local UI without refetching the route.\n    // A changed interception context still needs a route render.\n    if (\n      path === from &&\n      window.location.hash !== this.currentHistoryHash &&\n      event.state?.[FARM_INTERCEPT_FROM_KEY] === this.currentInterceptFrom\n    ) {\n      this.cancelActiveNavigation();\n      this.currentHistoryHash = window.location.hash;\n      this.currentHistoryIndex = readHistoryIndex(event.state);\n      return;\n    }\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.currentHistoryHash = window.location.hash;\n    this.currentInterceptFrom = event.state?.[FARM_INTERCEPT_FROM_KEY];\n    this.currentHistoryIndex = readHistoryIndex(event.state);\n\n    const navigation = this.startNavigation({\n      from,\n      to: createNavigationLocation(new URL(window.location.href)),\n      action: \"pop\",\n    });\n\n    let clientNavigation: FarmClientNavigationSession | undefined;\n    try {\n      clientNavigation = await this.clientPlugins?.beginNavigation({\n        from: null,\n        to: window.location.href,\n        action: \"pop\",\n      });\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      const interceptFrom =\n        typeof event.state?.[FARM_INTERCEPT_FROM_KEY] === \"string\"\n          ? event.state[FARM_INTERCEPT_FROM_KEY]\n          : undefined;\n      const pageData = await this.fetchPageData(\n        path,\n        true,\n        interceptFrom,\n        false,\n        navigation.controller.signal,\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);\n      }\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      this.updateDocumentMetadata(pageData.metadata);\n\n      _hydrateFarmI18n(pageData.i18n);\n\n      // Call the navigation handler to update React\n      if (this.onNavigate) {\n        await this.onNavigate(pageData);\n      }\n\n      // A fragment in the destination URL is an explicit scroll target for the\n      // window and takes precedence over the saved *window* scroll position,\n      // matching forward navigation and native browser back/forward. Element\n      // scroll positions are keyed without the hash (see\n      // getScrollElementStorageKey), so registered scroll containers are\n      // restored regardless of whether a fragment is present, even when the\n      // anchor resolves, so a persistent-layout scroll element is not left at\n      // the prior route's offset on a hash-destination popstate.\n      const destinationPath = window.location.pathname + window.location.search;\n      if (window.location.hash) {\n        const target = getHashTargetElement(window.location.hash);\n        if (target) {\n          target.scrollIntoView();\n        } else if (this.options.scrollRestoration) {\n          this.restoreWindowScroll(destinationPath);\n        }\n      } else if (this.options.scrollRestoration) {\n        this.restoreWindowScroll(destinationPath);\n      }\n      if (this.options.scrollRestoration) {\n        this.restoreScrollElements(destinationPath);\n      }\n\n      if (clientNavigation) {\n        await this.clientPlugins?.resolveNavigation(clientNavigation);\n        void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);\n      }\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (clientNavigation) {\n        await this.clientPlugins?.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      console.error(\"[Farm.js] Popstate navigation error:\", error);\n      // Reload the page as fallback\n      window.location.reload();\n    }\n  }\n\n  /**\n   * Check if URL is cached\n   */\n  private isCached(path: string, interceptFrom?: string): boolean {\n    const cached = this.cache.get(getPageDataCacheKey(path, interceptFrom));\n    return cached !== undefined && Date.now() - cached.timestamp < this.options.cacheMaxAge;\n  }\n\n  /**\n   * Check if URL is external\n   */\n  private isExternalUrl(href: string): boolean {\n    return href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\");\n  }\n\n  private async shouldBlockNavigation(context: FarmNavigationBlockerContext): Promise<boolean> {\n    for (const blocker of this.blockers) {\n      if (await blocker(context)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private evaluateBlockerForUnload(blocker: FarmNavigationBlocker): boolean {\n    const path = window.location.pathname + window.location.search;\n    const result = blocker({ from: path, to: path, action: \"replace\" });\n    if (result && typeof result !== \"boolean\") {\n      void result.catch(() => undefined);\n      return true;\n    }\n    return result === true;\n  }\n\n  private shouldBlockUnload(): boolean {\n    for (const blocker of this.blockers) {\n      try {\n        if (this.unloadBlockers.get(blocker)?.()) return true;\n      } catch {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private updateDocumentMetadata(metadata: PageData[\"metadata\"]): void {\n    // Both call sites run after the history entry is committed, so the current\n    // pathname is the navigated-to page and drives the default canonical.\n    applyFarmMetadataToDocument(metadata, window.location.pathname);\n  }\n\n  private startNavigation(options: {\n    from: string;\n    to: FarmNavigationLocation;\n    action: FarmNavigationBlockerContext[\"action\"];\n  }): { id: number; controller: AbortController } {\n    this.activeNavigation?.controller.abort(\"superseded\");\n    const navigation = {\n      id: ++this.navigationSequence,\n      controller: new AbortController(),\n    };\n    this.activeNavigation = navigation;\n    this.setNavigationState({\n      state: \"loading\",\n      pending: true,\n      from: options.from,\n      to: options.to,\n      action: options.action,\n      startedAt: Date.now(),\n    });\n    return navigation;\n  }\n\n  private isCurrentNavigation(\n    navigation: { id: number; controller: AbortController },\n    clientNavigation?: FarmClientNavigationSession,\n  ): boolean {\n    return (\n      this.activeNavigation?.id === navigation.id &&\n      !navigation.controller.signal.aborted &&\n      !clientNavigation?.signal.aborted\n    );\n  }\n\n  private finishNavigation(navigation: { id: number; controller: AbortController }): void {\n    if (this.activeNavigation?.id !== navigation.id) return;\n    this.activeNavigation = undefined;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  }\n\n  private cancelActiveNavigation(): void {\n    if (!this.activeNavigation) return;\n    this.activeNavigation.controller.abort(\"superseded\");\n    this.activeNavigation = undefined;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  }\n\n  private setNavigationState(state: FarmNavigationState): void {\n    this.navigationState = state;\n    for (const listener of this.navigationListeners) {\n      listener(state);\n    }\n  }\n\n  private writePageState(\n    action: \"push\" | \"replace\",\n    state: unknown,\n    href?: string,\n    notify = true,\n  ): void {\n    if (typeof window === \"undefined\") return;\n\n    const url = href\n      ? resolveFarmNavigationURL(href, window.location.href).toString()\n      : window.location.href;\n    const parsedUrl = new URL(url);\n    const nextPath = parsedUrl.pathname + parsedUrl.search;\n    const historyPath = nextPath + parsedUrl.hash;\n    const nextState = createHistoryState(historyPath, state, window.history.state) as Record<\n      string,\n      unknown\n    >;\n\n    if (action === \"replace\") {\n      window.history.replaceState(nextState, \"\", url);\n    } else {\n      if (this.currentHistoryIndex != null) {\n        nextState[FARM_HISTORY_INDEX_KEY] = this.currentHistoryIndex + 1;\n      }\n      window.history.pushState(nextState, \"\", url);\n      this.currentHistoryIndex =\n        this.currentHistoryIndex == null ? null : this.currentHistoryIndex + 1;\n    }\n    this.currentHistoryPath = nextPath;\n    this.currentHistoryHash = parsedUrl.hash;\n    this.currentInterceptFrom = nextState[FARM_INTERCEPT_FROM_KEY];\n\n    if (notify) notifyHistoryChange(\"page-state\");\n  }\n\n  /**\n   * Save scroll position for a path\n   */\n  private saveScrollPosition(path: string): void {\n    try {\n      sessionStorage.setItem(\n        `farm-scroll-${path}`,\n        JSON.stringify({ x: window.scrollX, y: window.scrollY }),\n      );\n      for (const [key, element] of this.scrollElements) {\n        sessionStorage.setItem(\n          getScrollElementStorageKey(path, key),\n          JSON.stringify({ x: element.scrollLeft, y: element.scrollTop }),\n        );\n      }\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  /**\n   * Restore the saved window scroll position for a path.\n   */\n  private restoreWindowScroll(path: string): void {\n    try {\n      const saved = sessionStorage.getItem(`farm-scroll-${path}`);\n      if (saved) {\n        const { x, y } = JSON.parse(saved);\n        setTimeout(() => window.scrollTo(x, y), 0);\n      }\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  /**\n   * Restore saved scroll positions for every registered scroll element. Keys\n   * are hash-stripped (see getScrollElementStorageKey), so this runs regardless\n   * of whether the destination URL carries a fragment.\n   */\n  private restoreScrollElements(path: string): void {\n    try {\n      for (const [key, element] of this.scrollElements) {\n        this.restoreScrollElement(path, key, element);\n      }\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  private restoreScrollElement(path: string, key: string, element: HTMLElement): void {\n    try {\n      const saved = sessionStorage.getItem(getScrollElementStorageKey(path, key));\n      if (!saved) return;\n      const { x, y } = JSON.parse(saved);\n      setTimeout(() => {\n        element.scrollLeft = x;\n        element.scrollTop = y;\n      }, 0);\n    } catch {\n      // Ignore storage errors\n    }\n  }\n\n  /**\n   * Clear the page cache\n   */\n  clearCache(): void {\n    this.cacheGeneration += 1;\n    this.cache.clear();\n    for (const pending of this.pendingPrefetches.values()) {\n      pending.cacheable = false;\n      pending.resolve(undefined);\n    }\n    this.pendingPrefetches.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","import { FARM_METADATA_ATTRIBUTE, renderMetadataHead, resolveMetadataTitle } from \"../metadata\";\nimport type { Metadata } from \"../types\";\n\nexport type NavigationMetadata = (Metadata & Record<string, any>) | undefined;\n\n/** Marks head elements this reconciler inserted, so they can be replaced. */\nconst MANAGED_ATTRIBUTE = FARM_METADATA_ATTRIBUTE;\n\n/**\n * Head tags the metadata system owns outright. These are swept on every\n * navigation whether or not they carry the managed marker, because the tags\n * rendered by the server for the first page have no marker and must not\n * survive into the next page's head.\n */\nconst OWNED_SELECTORS = [\n  'meta[name=\"description\"]',\n  'meta[name=\"keywords\"]',\n  'meta[name=\"author\"]',\n  'meta[name=\"google-site-verification\"]',\n  'meta[name=\"msvalidate.01\"]',\n  'meta[name=\"yandex-verification\"]',\n  'meta[name=\"creator\"]',\n  'meta[name=\"publisher\"]',\n  'meta[name=\"robots\"]',\n  'meta[name=\"googlebot\"]',\n  'link[rel=\"author\"]',\n  'link[rel=\"canonical\"]',\n  'link[rel=\"alternate\"]',\n  'meta[property^=\"og:\"]',\n  'meta[property^=\"article:\"]',\n  'meta[name^=\"twitter:\"]',\n  // Meta tags named by the app carry the marker, since no fixed name matches them.\n  `meta[${MANAGED_ATTRIBUTE}]`,\n].join(\", \");\n\n/**\n * Icons and the web-app manifest have document-level defaults that exist\n * outside page metadata (the default favicon, a discovered manifest route), so\n * an absent value means \"keep what the document has\", not \"remove it\". They\n * are only swept when the next page defines its own.\n */\nconst ICON_SELECTORS = [\n  'link[rel=\"icon\"]',\n  'link[rel=\"shortcut icon\"]',\n  'link[rel=\"apple-touch-icon\"]',\n].join(\", \");\nconst MANIFEST_SELECTOR = 'link[rel=\"manifest\"]';\nconst PAGE_JSON_LD_SELECTOR = `script[type=\"application/ld+json\"][${MANAGED_ATTRIBUTE}]`;\n\nfunction removeAll(selector: string): void {\n  for (const element of Array.from(document.head.querySelectorAll(selector))) {\n    element.remove();\n  }\n}\n\n/**\n * Make the document head for a client-side navigation match what a full-page\n * load of the target route renders: same title resolution and the same managed\n * tag set, produced by the same `renderMetadataHead` the server uses.\n *\n * Only page and layout JSON-LD (`metadata.jsonLd`) is swapped, matched by its\n * marker. The agent JSON-LD script is site identity rather than page metadata,\n * and ld+json scripts the application authored itself carry no marker, so\n * both stay untouched.\n */\nexport function applyFarmMetadataToDocument(metadata: NavigationMetadata, pathname: string): void {\n  document.title = resolveMetadataTitle(metadata?.title) || \"Farm.js App\";\n\n  const rendered = renderMetadataHead(metadata, { pathname });\n  const template = document.createElement(\"template\");\n  template.innerHTML = rendered.tags;\n\n  removeAll(OWNED_SELECTORS);\n  removeAll(PAGE_JSON_LD_SELECTOR);\n  if (metadata?.icons) removeAll(ICON_SELECTORS);\n  if (metadata?.manifest) removeAll(MANIFEST_SELECTOR);\n\n  for (const element of Array.from(template.content.children)) {\n    element.setAttribute(MANAGED_ATTRIBUTE, \"\");\n    document.head.appendChild(element);\n  }\n}\n","\"use client\";\n\nexport interface FarmChunkRecoveryOptions {\n  /**\n   * How long a page is considered already recovered before another chunk\n   * failure may trigger a reload. Defaults to 30 seconds.\n   */\n  maxAgeMs?: number;\n  /**\n   * Override the storage key. Mostly useful for tests and embedded runtimes.\n   */\n  storageKey?: string;\n  /**\n   * Called right before Farm reloads the page.\n   */\n  onRecover?: (error: unknown) => void;\n  /**\n   * Test hooks for browser globals.\n   */\n  reload?: () => void;\n  storage?: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | null;\n  location?: Pick<Location, \"pathname\" | \"search\" | \"reload\">;\n  now?: () => number;\n}\n\nconst DEFAULT_MAX_AGE_MS = 30_000;\nconst STORAGE_KEY_PREFIX = \"farm:chunk-recovery:\";\nconst CHUNK_ERROR_PATTERNS = [\n  /ChunkLoadError/i,\n  /Loading chunk [\\w-]+ failed/i,\n  /Loading CSS chunk [\\w-]+ failed/i,\n  /CSS_CHUNK_LOAD_FAILED/i,\n  /failed to fetch dynamically imported module/i,\n  /error loading dynamically imported module/i,\n  /importing a module script failed/i,\n  /unable to preload CSS/i,\n  /module script failed/i,\n];\n\nexport function isChunkLoadError(errorLike: unknown): boolean {\n  const values = collectErrorText(errorLike);\n  if (values.some((value) => CHUNK_ERROR_PATTERNS.some((pattern) => pattern.test(value)))) {\n    return true;\n  }\n\n  // Only treat same-origin script/style failures as chunk errors. A blocked\n  // or missing third-party asset (analytics, embeds) is not fixable by\n  // reloading, and reloading for it would loop for as long as it keeps\n  // failing.\n  const targetUrl = getEventTargetAssetUrl(errorLike);\n  return Boolean(\n    targetUrl && /\\.(?:m?js|css)(?:[?#].*)?$/i.test(targetUrl) && isSameOriginAssetUrl(targetUrl),\n  );\n}\n\nfunction isSameOriginAssetUrl(url: string): boolean {\n  if (typeof window === \"undefined\" || !window.location) {\n    return false;\n  }\n\n  try {\n    return new URL(url, window.location.href).origin === window.location.origin;\n  } catch {\n    return false;\n  }\n}\n\nexport function installChunkErrorRecovery(options: FarmChunkRecoveryOptions = {}): () => void {\n  if (typeof window === \"undefined\") {\n    return () => {};\n  }\n\n  const recover = (errorLike: unknown) => {\n    if (!isChunkLoadError(errorLike)) {\n      return;\n    }\n    if (!markRecovered(options)) {\n      return;\n    }\n\n    options.onRecover?.(errorLike);\n    getReload(options)();\n  };\n\n  const onError = (event: Event | ErrorEvent) => {\n    recover(getErrorEventPayload(event));\n  };\n  const onUnhandledRejection = (event: PromiseRejectionEvent) => {\n    recover(event.reason);\n  };\n\n  window.addEventListener(\"error\", onError, true);\n  window.addEventListener(\"unhandledrejection\", onUnhandledRejection);\n\n  return () => {\n    window.removeEventListener(\"error\", onError, true);\n    window.removeEventListener(\"unhandledrejection\", onUnhandledRejection);\n  };\n}\n\nfunction markRecovered(options: FarmChunkRecoveryOptions): boolean {\n  const now = getNow(options);\n  const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n  const storage = getStorage(options);\n  const key = getStorageKey(options);\n\n  if (!storage) {\n    return false;\n  }\n\n  try {\n    const previous = Number(storage.getItem(key));\n    if (Number.isFinite(previous) && previous > 0 && now - previous < maxAgeMs) {\n      return false;\n    }\n    storage.setItem(key, String(now));\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nfunction getErrorEventPayload(event: Event | ErrorEvent): unknown {\n  if (\"error\" in event && event.error) {\n    return event.error;\n  }\n  if (\"message\" in event && event.message) {\n    return event.message;\n  }\n  return event;\n}\n\nfunction collectErrorText(value: unknown, seen = new Set<unknown>()): string[] {\n  if (value == null || seen.has(value)) {\n    return [];\n  }\n  seen.add(value);\n\n  if (typeof value === \"string\") {\n    return [value];\n  }\n  if (typeof value === \"number\" || typeof value === \"boolean\") {\n    return [String(value)];\n  }\n  if (typeof value !== \"object\") {\n    return [];\n  }\n\n  const record = value as Record<string, unknown>;\n  const output: string[] = [];\n\n  for (const key of [\"name\", \"message\", \"code\", \"type\", \"request\", \"src\", \"href\"]) {\n    const candidate = record[key];\n    if (typeof candidate === \"string\") {\n      output.push(candidate);\n    }\n  }\n\n  if (\"reason\" in record) {\n    output.push(...collectErrorText(record.reason, seen));\n  }\n  if (\"error\" in record) {\n    output.push(...collectErrorText(record.error, seen));\n  }\n\n  return output;\n}\n\nfunction getEventTargetAssetUrl(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n\n  const target = (value as Event).target as\n    | (EventTarget & { src?: string; href?: string; tagName?: string })\n    | null\n    | undefined;\n  if (!target || typeof target !== \"object\") {\n    return undefined;\n  }\n\n  const tagName = typeof target.tagName === \"string\" ? target.tagName.toLowerCase() : \"\";\n  if (tagName !== \"script\" && tagName !== \"link\") {\n    return undefined;\n  }\n\n  return typeof target.src === \"string\" && target.src\n    ? target.src\n    : typeof target.href === \"string\" && target.href\n      ? target.href\n      : undefined;\n}\n\nfunction getStorage(options: FarmChunkRecoveryOptions) {\n  if (\"storage\" in options) {\n    return options.storage;\n  }\n\n  try {\n    return window.sessionStorage;\n  } catch {\n    return null;\n  }\n}\n\nfunction getStorageKey(options: FarmChunkRecoveryOptions): string {\n  if (options.storageKey) {\n    return options.storageKey;\n  }\n\n  const location = getLocation(options);\n  return `${STORAGE_KEY_PREFIX}${location.pathname}${location.search}`;\n}\n\nfunction getLocation(options: FarmChunkRecoveryOptions) {\n  return options.location ?? window.location;\n}\n\nfunction getReload(options: FarmChunkRecoveryOptions): () => void {\n  if (options.reload) {\n    return options.reload;\n  }\n\n  const location = getLocation(options);\n  return () => location.reload();\n}\n\nfunction getNow(options: FarmChunkRecoveryOptions): number {\n  return options.now ? options.now() : Date.now();\n}\n","\"use client\";\n\nimport type { FarmRuntimeErrorOverlay } 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 runtimeErrorOverlay?: FarmRuntimeErrorOverlay;\n\n  private readonly handleWindowError = (event: ErrorEvent) => {\n    const error = event.error ?? new Error(event.message || \"Unknown browser error\");\n    void this.reportError(error, \"window\", undefined, this.getLocation(), event);\n  };\n\n  private readonly handleUnhandledRejection = (event: PromiseRejectionEvent) => {\n    void this.reportError(\n      event.reason,\n      \"unhandled-rejection\",\n      undefined,\n      this.getLocation(),\n      event,\n    );\n  };\n\n  private readonly handlePageHide = (event: PageTransitionEvent) => {\n    // A persisted pagehide means the page is entering the back/forward cache and\n    // may be restored. close() is terminal — start() refuses to run again once\n    // closed — so tearing down here would hand the restored page dead scripts,\n    // PWA, and observability plugins with nothing able to revive them.\n    if (event.persisted) return;\n    void this.close(\"pagehide\");\n  };\n\n  constructor(\n    registrations: readonly FarmClientPluginRegistration[],\n    options: FarmClientPluginManagerOptions,\n  ) {\n    this.registrations = sortRegistrations(registrations);\n    this.options = {\n      ...options,\n      isDev: options.isDev ?? false,\n      isProd: options.isProd ?? !options.isDev,\n      window: options.window ?? (typeof window !== \"undefined\" ? window : undefined),\n    };\n  }\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    if (this.closed) return;\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\n    // Keep the entire diagnostics graph behind a build-time guard. A static\n    // import leaves the overlay and source-map helpers in published bundles,\n    // even when every production caller passes isDev: false.\n    if (process.env.NODE_ENV !== \"production\" && this.options.isDev && this.options.window) {\n      try {\n        const { createFarmRuntimeErrorOverlay } =\n          await import(\"@farm.js/core/internal/client-error-overlay\");\n        this.runtimeErrorOverlay = createFarmRuntimeErrorOverlay({ window: this.options.window });\n      } catch (error) {\n        // Diagnostics must not prevent hydration or application error hooks\n        // from starting when their development chunk cannot be loaded.\n        this.logHookError(\"farm:runtime-error-overlay\", \"load\", error);\n      }\n    }\n\n    // Errors reported while diagnostics load must await start(), whereas\n    // errors from a plugin's setup hook must not await their own start promise.\n    this.starting = true;\n\n    try {\n      for (const registration of this.registrations) {\n        try {\n          const definition = registration.definition;\n          if (!definition || typeof definition !== \"object\") {\n            throw new TypeError(\n              `Client plugin \"${registration.name}\" does not define a lifecycle object`,\n            );\n          }\n\n          const instance: FarmClientPluginInstance = {\n            registration,\n            plugin: definition,\n            state: undefined,\n          };\n          instance.state = await definition.setup?.(this.createSetupEvent(instance));\n          this.instances.push(instance);\n        } catch (error) {\n          this.logHookError(registration.name, \"setup\", error);\n          await this.runErrorHooks({\n            error,\n            phase: \"setup\",\n            location: this.getLocation(),\n          });\n        }\n      }\n\n      this.started = true;\n      this.installBrowserListeners();\n      this.installPerformanceObservers();\n    } finally {\n      this.starting = false;\n    }\n  }\n\n  private installBrowserListeners(): void {\n    const clientWindow = this.options.window;\n    if (!clientWindow) return;\n\n    if (this.runtimeErrorOverlay || this.instances.some(({ plugin }) => plugin.error)) {\n      clientWindow.addEventListener(\"error\", this.handleWindowError);\n      clientWindow.addEventListener(\"unhandledrejection\", this.handleUnhandledRejection);\n    }\n    // Not `once`: a persisted pagehide is ignored above, and the page can be\n    // restored and then genuinely unloaded later. close() is idempotent, so\n    // keeping the listener costs nothing and never disposes twice.\n    clientWindow.addEventListener(\"pagehide\", this.handlePageHide);\n  }\n\n  private installPerformanceObservers(): void {\n    if (!this.instances.some(({ plugin }) => plugin.performance)) return;\n    const Observer = typeof PerformanceObserver !== \"undefined\" ? PerformanceObserver : undefined;\n    if (!Observer) return;\n\n    const supported = new Set(Observer.supportedEntryTypes || []);\n    for (const type of PERFORMANCE_ENTRY_TYPES) {\n      if (!supported.has(type)) continue;\n      try {\n        const observer = new Observer((list: PerformanceObserverEntryList) => {\n          for (const entry of list.getEntries()) {\n            void this.runHook(\"performance\", (instance) =>\n              instance.plugin.performance?.({\n                ...this.createStateEvent(instance),\n                entry,\n                location: this.getLocation(),\n              }),\n            );\n          }\n        });\n        observer.observe({ type, buffered: true });\n        this.performanceObservers.push(observer);\n      } catch (error) {\n        void this.reportError(error, \"performance\");\n      }\n    }\n  }\n\n  private async closeInternal(reason: FarmClientPluginCloseEvent[\"reason\"]): Promise<void> {\n    if (this.closed) return;\n    if (this.startPromise) await this.startPromise;\n    this.closed = true;\n    this.currentNavigation?.controller.abort(reason);\n    this.currentNavigation = undefined;\n\n    const clientWindow = this.options.window;\n    clientWindow?.removeEventListener(\"error\", this.handleWindowError);\n    clientWindow?.removeEventListener(\"unhandledrejection\", this.handleUnhandledRejection);\n    clientWindow?.removeEventListener(\"pagehide\", this.handlePageHide);\n    for (const observer of this.performanceObservers) observer.disconnect();\n    this.performanceObservers.length = 0;\n    this.runtimeErrorOverlay?.destroy();\n\n    for (const instance of [...this.instances].reverse()) {\n      try {\n        await instance.plugin.close?.({\n          ...this.createStateEvent(instance),\n          reason,\n        });\n      } catch (error) {\n        this.logHookError(instance.registration.name, \"close\", error);\n      }\n    }\n  }\n\n  private async runHook(\n    hook: string,\n    invoke: (instance: FarmClientPluginInstance) => MaybePromise<void> | undefined,\n  ): Promise<void> {\n    for (const instance of this.instances) {\n      try {\n        await invoke(instance);\n      } catch (error) {\n        this.logHookError(instance.registration.name, hook, error);\n        await this.runErrorHooks(\n          {\n            error,\n            phase: `plugin:${hook}`,\n            location: this.getLocation(),\n          },\n          instance,\n        );\n      }\n    }\n  }\n\n  private async runErrorHooks(\n    event: Pick<FarmClientPluginErrorEvent, \"error\" | \"phase\" | \"location\" | \"navigation\">,\n    excluded?: FarmClientPluginInstance,\n    sourceEvent?: Event,\n  ): Promise<void> {\n    this.runtimeErrorOverlay?.show(event.error, {\n      phase: event.phase,\n      location: event.location,\n      sourceEvent,\n    });\n    for (const instance of this.instances) {\n      if (instance === excluded || !instance.plugin.error) continue;\n      try {\n        await instance.plugin.error({\n          ...this.createStateEvent(instance),\n          ...event,\n        });\n      } catch (error) {\n        this.logHookError(instance.registration.name, \"error\", error);\n      }\n    }\n  }\n\n  private createSetupEvent(\n    instance: Pick<FarmClientPluginInstance, \"registration\">,\n  ): FarmClientPluginSetupEvent<any> {\n    return {\n      plugin: {\n        name: instance.registration.name,\n        version: instance.registration.version,\n      },\n      public: readonlyPublicData(instance.registration.public),\n      router: this.options.router,\n      isDev: Boolean(this.options.isDev),\n      isProd: Boolean(this.options.isProd),\n      deploymentId: this.options.deploymentId,\n    };\n  }\n\n  private createStateEvent(\n    instance: FarmClientPluginInstance,\n  ): FarmClientPluginStateEvent<any, any> {\n    return {\n      ...this.createSetupEvent(instance),\n      state: instance.state,\n    };\n  }\n\n  private getLocation(): FarmClientLocation {\n    const href = this.options.window?.location.href ?? \"http://localhost/\";\n    return toClientLocation(href, href);\n  }\n\n  private getBaseUrl(): string {\n    return this.options.window?.location.href ?? \"http://localhost/\";\n  }\n\n  private logHookError(name: string, hook: string, error: unknown): void {\n    console.error(`[Farm.js] Client plugin \"${name}\" failed in ${hook}:`, error);\n  }\n}\n\nexport function createClientPluginManager(\n  registrations: readonly FarmClientPluginRegistration[],\n  options: FarmClientPluginManagerOptions,\n): FarmClientPluginManager {\n  return new FarmClientPluginManager(registrations, options);\n}\n\nfunction sortRegistrations(\n  registrations: readonly FarmClientPluginRegistration[],\n): FarmClientPluginRegistration[] {\n  const rank = (enforce?: FarmClientPluginEnforce) =>\n    enforce === \"pre\" ? 0 : enforce === \"post\" ? 2 : 1;\n  return registrations\n    .map((registration, index) => ({ registration, index }))\n    .sort(\n      (left, right) =>\n        rank(left.registration.enforce) - rank(right.registration.enforce) ||\n        left.index - right.index,\n    )\n    .map(({ registration }) => registration);\n}\n\nfunction toClientLocation(\n  input: string | URL | FarmClientLocation,\n  base: string,\n): FarmClientLocation {\n  if (typeof input === \"object\" && \"href\" in input && \"pathname\" in input) {\n    return {\n      href: input.href,\n      pathname: input.pathname,\n      search: input.search,\n      hash: input.hash,\n    };\n  }\n\n  const url = new URL(input, base);\n  return {\n    href: url.href,\n    pathname: url.pathname,\n    search: url.search,\n    hash: url.hash,\n  };\n}\n\nfunction readonlyPublicData<T>(value: T | undefined): Readonly<T> {\n  if (value && typeof value === \"object\") {\n    return Object.freeze(value);\n  }\n  return value as Readonly<T>;\n}\n\nfunction now(): number {\n  return typeof performance !== \"undefined\" ? performance.now() : Date.now();\n}\n\nfunction isObject(value: unknown): value is object {\n  return (typeof value === \"object\" && value !== null) || typeof value === \"function\";\n}\n","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\";\nimport { parseRequestCookieHeader } from \"./request-cookies\";\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 = parseRequestCookieHeader(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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2KO,SAAS,4BACd,UAC0B;AAC1B,QAAM,mBAAmB;AAAA,IACvB,MAAM,UAAU,cAAc,WAAW,QAAQ,8BAA8B,UAAU;AAAA,IACzF,KAAK,UAAU,cAAc,WAAW,OAAO,8BAA8B,UAAU;AAAA,EACzF;AACA,QAAM,WAAW,OAAO;AAAA,IACrB,CAAC,QAAQ,MAAM,EAAY,QAAQ,CAACA,aAAY;AAC/C,YAAM,WAAW,UAAU,cAAc,WAAW,WAAWA,QAAO;AACtE,UAAI,CAAC,SAAU,QAAO,CAAC;AACvB,aAAO;AAAA,QACL;AAAA,UACEA;AAAA,UACA;AAAA,YACE,MAAM,SAAS,QAAQ,iBAAiB;AAAA,YACxC,KAAK,SAAS,OAAO,iBAAiB;AAAA,UACxC;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,WAAW;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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;","names":["runtime","name","path","name","path","relativePath","fs","memoryDriver","storage","name","module","resolveDriver","base","location","name","name","name","literal","applied","mkdir","dirname","name","request","request","operation","api","path","route","globalState","listeners","resolve","cookies","headers","path","request","resolve","context","cookies","headers","path","globalState","endpoint","route","name","runtime","api","operation","env","request","middleware","response","text","resolveStorageRuntimeClient","createIntegrationOrm","path","import_node_path","route","headers","name","text","name","module","request","route","secretError","context","fs","path","isAbsolutePath","normalizePath","pathToFileURL","build","resolvePath","relativeFilePath","pathSeparator","text","import_node_path","name","fs","path","request","safeFileName","name","request","request","runtime","route","redirect","headers","request","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","after","text","name","storage","name","resolve","serialized","now","shared","context","PROGRAMMATIC_ROUTE_FILE_NAMES","api","createProgrammaticRouteModuleId","getProgrammaticRouteSearchClientOptions","isProgrammaticRoutesFileName","parseProgrammaticRouteModuleId","parseProgrammaticRoutePath","redirect","scanProgrammaticPagePaths","path","route","createElement","FarmProgrammaticPageContent","FarmProgrammaticPage","context","name","action","runtime","getProgrammaticRouteManifest","import_path","runtime","createElement","headers","path","import_promises","import_path","import_url","import_node_url","fs","path","literal","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","document","name","context","runtime","storage","headers","request","import_node_async_hooks","path","fs","import_node_fs","import_node_path","context","name","initialTagCount","icon","marked","context","headers","data","output","resolve","headers","request","path","name","path","normalizePositiveInteger","name","import_node_path","isPlainObject","name","import_promises","headers","request","redirect","readCookie","locale","name","request","IntlMessageFormat","getRequestStore","runtime","request","import_node_async_hooks","init_server","path","runtime","relative","name","escapeHtmlAttribute","import_node_crypto","import_node_fs","import_promises","import_node_path","import_node_module","import_node_url","context","bytes","createElement","headers","path","page","isRecord","index","isResponse","isRecord","resolveCacheControl","toArray","name","getFarmGlobalState","normalizeCookiePath","init_config","init_config","init_bridge","request","readCookie","name","init_server","init_bridge","init_config","path","import_node_path","relative","relativePath","location","fs","path","import_node_url","name","start","end","shared","context","init_server","React","reactRenderToString","reactRenderToPipeableStream","page","name","serializeInlineValue","escapeHtmlAttribute","toMiddlewareMap","request","resolve","headers","fs","path","import_node_url","init_renderer","init_server","runtime","renderToPipeableStream","layout","route","redirect","snapshot","context","relativePath","findStaticShellBoundary","error","html","normalizeBasePath","path","runtime","route","import_node_module","import_node_path","import_node_url","context","url","path","route","name","init_config","import_path","init_renderer","init_server","init_config","path","env","isRecord","name","path","path","isPromiseLike","runtime","endpoint","path","fs","location","import_node_fs","import_node_path","path","fs","import_node_fs","import_node_path","headers","path","middleware","endpoint","betterCallEndpoint","context","result","path","endpoint","context","route","init_config","normalizePathname","route","path","init_route_pattern","route","endpoint","request","response","searchParamsToObject","headers","isWebResponse","text","init_runtime","init_config","init_route_pattern","route","api","path","endpoint","request","init_runtime","fs","path","init_route_manager","init_server","init_runtime","route","relativePath","endpoint","getProgrammaticRouteManifest","request","cookies","name","createContext","headers","cookies","applyResponseHeaders","name","request","context","module","picocolors","path","name","fs","path","middleware","module","createContext","result","runtime","import_node_fs","import_fs","import_module","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","runtime","storage","reportError","resolve","context","request","import_node_async_hooks","runtime","import_node_async_hooks","headers","fs","path","import_promises","import_node_path","import_image_size","layout","request","context","throwIfAborted","text","name","location","resolve","headers","path","import_node_path","path","import_node_crypto","import_node_fs","import_node_path","init_config","context","env","context","path","relativePath","import_node_fs","import_node_path","path","import_node_fs","import_node_module","import_node_path","isFalse","page","escapeXml","name","route","import_node_crypto","trimSlashes","normalizeEntry","path","escapeAttribute","escapeHtml","relative","request","DOCS_FILE_EXTENSIONS","titleFromMarkdown","page","text","body","icon","renderedSections","headers","import_node_fs","import_node_path","path","import_node_module","import_node_path","import_node_url","path","runtime","import_node_module","import_node_path","import_node_url","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","request","getDocsDescription","getLoadedDocsPages","context","page","toDocsSitemapPage","toDocsLlmsPage","getDocsLlmsOptions","getDocsDiscoveryOptions","buildFarmingDocsDiagnostics","import_docs","import_server","init_config","context","route","path","operation","fs","init_manager","context","normalizePath","route","runtime","storage","env","middleware","path","import_node_path","init_config","name","escapeHtml","escapeAttribute","runtime","route","throwIfAborted","pipeline","request","Readable","headers","name","resolve","address","defineConfig","runtime","publicEnv","headers","request","middleware","name","isHtmlResponse","env","declaration","relative","context","createNodeImageFetcher","createNodeImageUrlValidator","createSharpImageTransformer","isStaticMetadataImageFile","route","createFarmWorkflowRequestHandler","discoverFarmWorkflows","OpenAPIManager","layout","now","handler","createFarmDevtoolsSnapshot","renderFarmDevtoolsHtml","pathname","startTime","duration","method","urlPath","routeManager","parseRouteModuleProps","options","page","React","renderToString","server","parseRouteModuleSchema","resolveFarmLayers","os","fs","path","import_node_url","init_vite","init_route_manager","init_config","init_runtime","init_server","context","name","client","resolveIntegrationOrmRuntimeClient","init_vite","request","endpoint","path","createContext","route","after","promises","definePlugin","path","mkdir","routePaths","clientManifestPath","readFile","import_path","asBoolean","build","createContext","createProgrammaticRouteModuleId","getRouter","getTheme","isProgrammaticRoutesFileName","isWebResponse","matchesMiddlewareConfig","parseProgrammaticRouteModuleId","parseProgrammaticRoutePath","scanProgrammaticPagePaths","name","import_react","name","shared","init_config","module","redirect","context","headers","context","env","context","import_node_stream","request","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","runtime","INTEGRATION_DATA_HEADER","INTEGRATION_DATA_HEADER_MAX_LENGTH","BLOCKED_INTEGRATION_DATA_KEYS","isPlainIntegrationDataObject","getIntegrationDataHeaderByteLength","headers","api","request","operation","dispatchIntegrationRequest","body","createClientSafeIntegrationAPI","now","listeners","init_config","init_route_pattern","route","path","segment","dynamic","delay","context","api","path","runtime","headers","name","request","now","nextEntry","result","createResponseError","delay","invalidate","route","init_config","init_route_manager","init_runtime","endpoint","route","request","fs","path","relativePath","getProgrammaticRouteManifest","duration","headers","init_manager","import_react","import_jsx_runtime","React","import_jsx_runtime","asBoolean","parse","now","window","storage","name","matchPattern","path","middleware","request","headers","name","isMiddlewareResponse","cookies","matchesMiddlewareConfig","runtime","result","redirect","import_node_fs","import_node_path","path","fs","module","splitRoutePattern","decodePathSegment","normalizePathname","normalizeRoutePattern","encodePathSegment","normalizePathname","value","route","path","normalizeRoutePattern","createSearchParams","init_config","api","middleware","isFormData","formDataToObject","request","context","result","isPromiseLike","import_react","context","delay","resolve","isFormData","context","request","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_node_path","normalizePathname","getDocsTitle","page","path","import_path","path","route","fs","runtime","relativePath","import_path","fs","route","path","normalizeBasePath","escapeRegExp","route","runtime","context","import_node_fs","import_node_path","import_node_url","path","fs","import_meta","import_meta","path","clone","trimSlashes","fs","route","layout","farmPlugin","farmServerOnlyEntriesPlugin","PluginManager","metadata","relativePath","relative","page","os","redirect","OpenAPIManager","renderOpenAPIReferenceHTML","name","headers","fsConstants","request","operation","build","buildClient","path","farmI18nClientBridgePlugin","farmPlugin","farmServerOnlyEntriesPlugin","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","runtime","getTheme","import_react","import_jsx_runtime","prefetch","route","import_react","shouldBlockUnload","path","prefetch","resolve","data","now","context","getRouter","path","context","route","pushState","getRouter","replaceState","request","now","storage","getStorage","location","resolve","location","name","name"]}