{"version":3,"sources":["../src/env.ts","../src/request-context.ts","../src/plugin-integration-context.ts","../src/app-markdown-config.ts","../src/markdown.ts","../src/routing/specificity.ts","../src/server-http.ts","../src/search-params.ts","../src/secret-compare.ts","../src/utils/runtime-env.ts","../src/utils/decode.ts","../src/utils.ts","../src/base-path.ts","../src/i18n/routing.ts","../src/plugins/route-pattern.ts","../src/workflows.ts","../src/cron.ts","../src/storage/index.ts","../src/tracing.ts","../src/observability.ts","../src/navigation-errors.ts","../src/route-runtime.ts","../src/route-rules.ts","../src/cache-invalidation.ts","../src/request-origin.ts","../src/server-fn-error.ts","../src/server-action-security.ts","../src/image-config.ts","../src/layers.ts","../src/route-call-scanner.ts","../src/routes-shared.ts","../src/i18n/bridge.ts","../src/cache.ts","../src/route-context.ts","../src/routes.ts","../src/schema.ts","../src/integration-request-security.ts","../src/integration-api.ts","../src/server/response.ts","../src/integration-orm.ts","../src/integrations.ts","../src/renderer.ts","../src/agent-config.ts","../src/deployment.ts","../src/i18n/config.ts","../src/theme/config.ts","../src/client/isolated-boundary.ts","../src/renderer/react/server.ts","../src/devtools-config.ts","../src/dev-indicators.ts","../src/auth-config.ts","../src/preload.ts","../src/security.ts","../src/api/config.ts","../src/api/route-shape.ts","../src/api/route-files.ts","../src/write-file-if-changed.ts","../src/type-generator.ts","../src/image-server.ts","../src/docs/fonts.ts","../src/client/document-head.ts","../src/docs/last-modified.ts","../src/docs/search-client.ts","../src/docs/social-image.ts","../src/docs/handler.ts","../src/docs/adapter.ts","../src/docs/framework-detect.ts","../src/config-entry.ts","../src/config.ts","../src/docs/api.ts","../src/docs/index.ts","../src/openapi/generator.ts","../src/openapi/manager.ts","../src/devtools.ts","../src/devtools-ui.ts","../src/devtools-client.ts","../src/image-sharp.ts","../src/plugin.ts","../src/app.ts","../src/routing/route-manager.ts","../src/ssg.ts","../src/routes.server.ts","../src/app-markdown.ts","../src/utils/client-component.ts","../src/island.ts","../src/navigation/render-plan.ts","../src/static-metadata-image.ts","../src/redirect-query.ts","../src/routing/route-slots.ts","../src/server/renderer.ts","../src/server/dev-styles.ts","../src/server/full-document.ts","../src/middleware/server.ts","../src/server/request.ts","../src/server/request-bridge.ts","../src/not-found.ts","../src/metadata.ts","../src/deferred.ts","../src/i18n/server.ts","../src/i18n/runtime.ts","../src/i18n/catalog.ts","../src/i18n/resolver.ts","../src/font-vite.ts","../src/response-body.ts","../src/metadata-image.ts","../src/metadata-route.ts","../src/trailing-slash.ts","../src/components/not-found-styles.ts","../src/components/error-styles.ts","../src/components/error-page.ts","../src/theme/server-runtime.ts","../src/theme/bridge.ts","../src/theme/server.ts","../package.json","../src/version.ts","../src/server/error-diagnostics.ts","../src/vite.ts","../src/default-styles.ts","../src/client-plugin-build.ts","../src/client-cache-persistence-build.ts","../src/api/endpoint.ts","../src/api/transport.ts","../src/api/route.ts","../src/api/plugin-route-runtime.ts","../src/api/route-manager.ts","../src/api/runtime.ts","../src/api/server-path.ts","../src/api/route-schema.ts","../src/api/route-pattern.ts","../src/middleware/manager.ts","../src/middleware/cookie-header.ts","../src/middleware/context.ts","../src/middleware/module.ts","../src/cli-colors.ts","../src/middleware/path.ts","../src/type-artifacts.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/after.ts","../src/api/server-context.ts","../src/api/server-client-bridge.ts","../src/dev-static.ts","../src/server-query-boundary.ts","../src/client-boundary-env.ts","../src/image-vite.ts","../src/font.ts","../src/server/vite-config.ts","../src/theme/vite.ts","../src/integration-provider-build.ts","../src/navigation/page-data-error.ts","../src/plugins/rewrites.ts","../src/openapi/dev-status.ts"],"sourcesContent":["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","type RequestContextCarrier = object;\n\nexport interface SetRequestContextOptions {\n  exposeToPage?: boolean;\n}\n\nexport interface RequestContextSnapshotOptions {\n  exposedOnly?: boolean;\n}\n\ninterface RequestContextBucket {\n  privateData: Map<string, any>;\n  exposedData: Map<string, any>;\n}\n\nconst REQUEST_CONTEXT_STORE_KEY = Symbol.for(\"farm.requestContextStore\");\n\ntype GlobalWithRequestContextStore = typeof globalThis & {\n  [REQUEST_CONTEXT_STORE_KEY]?: WeakMap<RequestContextCarrier, RequestContextBucket>;\n};\n\nfunction getRequestContextStore() {\n  const globalState = globalThis as GlobalWithRequestContextStore;\n  if (!globalState[REQUEST_CONTEXT_STORE_KEY]) {\n    globalState[REQUEST_CONTEXT_STORE_KEY] = new WeakMap<\n      RequestContextCarrier,\n      RequestContextBucket\n    >();\n  }\n\n  return globalState[REQUEST_CONTEXT_STORE_KEY]!;\n}\n\nfunction getBucket(target: RequestContextCarrier): RequestContextBucket {\n  const requestContextStore = getRequestContextStore();\n  let bucket = requestContextStore.get(target);\n  if (!bucket) {\n    bucket = {\n      privateData: new Map<string, any>(),\n      exposedData: new Map<string, any>(),\n    };\n    requestContextStore.set(target, bucket);\n  }\n  return bucket;\n}\n\nexport function setRequestContext(\n  target: RequestContextCarrier,\n  key: string,\n  value: any,\n  options: SetRequestContextOptions = {},\n): void {\n  const bucket = getBucket(target);\n  bucket.privateData.set(key, value);\n  if (options.exposeToPage) {\n    bucket.exposedData.set(key, value);\n  }\n}\n\nexport function getRequestContext<T = any>(\n  target: RequestContextCarrier,\n  key: string,\n): T | undefined {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  return bucket?.privateData.get(key) as T | undefined;\n}\n\nexport function hasRequestContext(target: RequestContextCarrier, key: string): boolean {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  return bucket?.privateData.has(key) ?? false;\n}\n\nexport function deleteRequestContext(target: RequestContextCarrier, key: string): boolean {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return false;\n  const removedPrivate = bucket.privateData.delete(key);\n  bucket.exposedData.delete(key);\n  return removedPrivate;\n}\n\nexport function clearRequestContext(target: RequestContextCarrier): void {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return;\n  bucket.privateData.clear();\n  bucket.exposedData.clear();\n}\n\nexport function getRequestContextSnapshot(\n  target: RequestContextCarrier,\n  options: RequestContextSnapshotOptions = {},\n): Map<string, any> {\n  const requestContextStore = getRequestContextStore();\n  const bucket = requestContextStore.get(target);\n  if (!bucket) return new Map<string, any>();\n  if (options.exposedOnly) {\n    return new Map(bucket.exposedData);\n  }\n  return new Map(bucket.privateData);\n}\n","import type { 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","import type React from \"react\";\n\nexport type FarmMdxComponent = React.ComponentType<any> | keyof React.JSX.IntrinsicElements;\nexport type FarmMdxComponents = Record<string, FarmMdxComponent>;\n\nexport interface FarmMdxUserConfig {\n  /**\n   * Component map or module path that exports `components` or a default component map.\n   * Relative paths resolve from the project root.\n   */\n  components?: string | FarmMdxComponents;\n  /**\n   * Serve source-authored markdown pages at `/route.md`.\n   * Enabled by default for `page.md` and `page.mdx`.\n   */\n  markdownRoutes?: boolean;\n  /** Class name used for the wrapper around rendered markdown content. */\n  className?: string;\n}\n\nexport interface FarmMdxResolvedConfig {\n  components?: string | FarmMdxComponents;\n  markdownRoutes: boolean;\n  className: string;\n}\n\nexport function resolveMdxConfig(config: FarmMdxUserConfig | undefined): FarmMdxResolvedConfig {\n  return {\n    components: config?.components,\n    markdownRoutes: config?.markdownRoutes ?? true,\n    className: config?.className ?? \"farm-markdown\",\n  };\n}\n","export type FarmMarkdownRouteInput =\n  | string\n  | {\n      route: string;\n      title?: string;\n      cache?: number | false;\n    };\n\nexport interface FarmMarkdownUserConfig {\n  /**\n   * Enable generated markdown representations for React pages.\n   * @default true\n   */\n  enabled?: boolean;\n  /**\n   * Routes that may expose generated markdown. Every page is exposed by default.\n   */\n  expose?: boolean | FarmMarkdownRouteInput[];\n  /** @deprecated Use `expose`. */\n  routes?: FarmMarkdownRouteInput[];\n  cache?: number | false;\n  includeMetadata?: boolean;\n}\n\nexport interface FarmMarkdownResolvedRoute {\n  route: string;\n  title?: string;\n  cache?: number | false;\n}\n\nexport interface FarmMarkdownResolvedConfig {\n  enabled: boolean;\n  expose: true | FarmMarkdownResolvedRoute[];\n  cache: number | false;\n  includeMetadata: boolean;\n}\n\nexport interface FarmMarkdownMirrorTarget {\n  pathname: string;\n  route: FarmMarkdownResolvedRoute | null;\n}\n\nexport interface ResolveMarkdownMirrorTargetOptions {\n  accept?: string | null;\n}\n\nexport interface CreateMarkdownMirrorResponseOptions {\n  request: Request;\n  config?: FarmMarkdownResolvedConfig;\n  routeExists?: (pathname: string) => boolean;\n  renderPage: (request: Request) => Response | Promise<Response>;\n}\n\nexport interface ApplyMarkdownNegotiationHeadersOptions {\n  config?: FarmMarkdownResolvedConfig;\n  pathname: string;\n}\n\nexport function resolveMarkdownConfig(\n  config: FarmMarkdownUserConfig | boolean | undefined,\n): FarmMarkdownResolvedConfig {\n  if (config === false) {\n    return {\n      enabled: false,\n      expose: [],\n      cache: false,\n      includeMetadata: true,\n    };\n  }\n\n  if (config === true || config === undefined) {\n    return {\n      enabled: true,\n      expose: true,\n      cache: false,\n      includeMetadata: true,\n    };\n  }\n\n  const exposeInput = config.expose ?? config.routes ?? true;\n  const expose =\n    exposeInput === true\n      ? true\n      : Array.isArray(exposeInput)\n        ? exposeInput.map(normalizeMarkdownRouteInput)\n        : [];\n\n  return {\n    enabled: config.enabled !== false && (expose === true || expose.length > 0),\n    expose,\n    cache: config.cache ?? false,\n    includeMetadata: config.includeMetadata ?? true,\n  };\n}\n\nexport function resolveMarkdownMirrorTarget(\n  config: FarmMarkdownResolvedConfig | undefined,\n  pathname: string,\n  options: ResolveMarkdownMirrorTargetOptions = {},\n): FarmMarkdownMirrorTarget | null {\n  const hasMarkdownExtension = pathname.toLowerCase().endsWith(\".md\");\n  if (!config?.enabled || (!hasMarkdownExtension && !requestAcceptsMarkdown(options.accept))) {\n    return null;\n  }\n\n  const targetPathname = normalizeMarkdownRoute(\n    hasMarkdownExtension ? pathname.slice(0, -\".md\".length) || \"/\" : pathname,\n  );\n  const route = findExposedMarkdownRoute(config, targetPathname);\n  if (!route && config.expose !== true) {\n    return null;\n  }\n\n  return {\n    pathname: targetPathname,\n    route,\n  };\n}\n\nexport async function createMarkdownMirrorResponse(\n  options: CreateMarkdownMirrorResponseOptions,\n): Promise<Response | null> {\n  if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n    return null;\n  }\n\n  const requestUrl = new URL(options.request.url);\n  const hasMarkdownExtension = requestUrl.pathname.toLowerCase().endsWith(\".md\");\n  const target = resolveMarkdownMirrorTarget(options.config, requestUrl.pathname, {\n    accept: options.request.headers.get(\"accept\"),\n  });\n  if (!target) {\n    return null;\n  }\n\n  if (options.routeExists && !options.routeExists(target.pathname)) {\n    return null;\n  }\n\n  const pageUrl = new URL(options.request.url);\n  pageUrl.pathname = target.pathname;\n  const headers = new Headers(options.request.headers);\n  headers.set(\"accept\", \"text/html\");\n\n  const pageResponse = await options.renderPage(\n    new Request(pageUrl, {\n      method: \"GET\",\n      headers,\n    }),\n  );\n\n  if (!isHtmlResponse(pageResponse)) {\n    return null;\n  }\n\n  const html = await pageResponse.text();\n  const markdown = htmlToMarkdown(html, {\n    title: target.route?.title,\n    includeMetadata: options.config?.includeMetadata ?? true,\n    sourcePath: target.pathname,\n  });\n  const headersOut = new Headers({\n    \"Content-Type\": \"text/markdown; charset=utf-8\",\n    \"Content-Location\": target.pathname === \"/\" ? \"/index.md\" : `${target.pathname}.md`,\n    \"X-Farm-Markdown-Route\": target.pathname,\n  });\n  if (!hasMarkdownExtension) {\n    headersOut.set(\"Vary\", \"Accept\");\n  }\n  const cache = target.route?.cache ?? options.config?.cache ?? false;\n  headersOut.set(\"Cache-Control\", createMarkdownCacheHeader(cache));\n\n  return new Response(options.request.method === \"HEAD\" ? null : markdown, {\n    status: pageResponse.status,\n    headers: headersOut,\n  });\n}\n\nexport function applyMarkdownNegotiationHeaders(\n  response: Response,\n  options: ApplyMarkdownNegotiationHeadersOptions,\n): Response {\n  if (!isHtmlResponse(response)) {\n    return response;\n  }\n\n  const target = resolveMarkdownMirrorTarget(options.config, options.pathname, {\n    accept: \"text/markdown\",\n  });\n  if (!target) {\n    return response;\n  }\n\n  const alternatePath = getMarkdownAlternatePath(target.pathname);\n  const headers = new Headers(response.headers);\n  appendHeaderToken(headers, \"Vary\", \"Accept\");\n  headers.append(\"Link\", `<${alternatePath}>; rel=\"alternate\"; type=\"text/markdown\"`);\n\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function htmlToMarkdown(\n  html: string,\n  options: {\n    title?: string;\n    sourcePath?: string;\n    includeMetadata?: boolean;\n  } = {},\n): string {\n  const title = options.title ?? extractHtmlTitle(html);\n  let source = extractHtmlBody(html)\n    .replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\")\n    .replace(/<style\\b[^>]*>[\\s\\S]*?<\\/style>/gi, \"\")\n    .replace(/<noscript\\b[^>]*>[\\s\\S]*?<\\/noscript>/gi, \"\")\n    .replace(/<!--[\\s\\S]*?-->/g, \"\");\n\n  source = source.replace(/<pre\\b[^>]*><code\\b[^>]*>([\\s\\S]*?)<\\/code><\\/pre>/gi, (_, code) => {\n    return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n  });\n  source = source.replace(/<pre\\b[^>]*>([\\s\\S]*?)<\\/pre>/gi, (_, code) => {\n    return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n  });\n  source = source.replace(/<h([1-6])\\b[^>]*>([\\s\\S]*?)<\\/h\\1>/gi, (_, level, content) => {\n    return `\\n\\n${\"#\".repeat(Number(level))} ${toInlineMarkdown(content).trim()}\\n\\n`;\n  });\n  source = source.replace(/<p\\b[^>]*>([\\s\\S]*?)<\\/p>/gi, (_, content) => {\n    return `\\n\\n${toInlineMarkdown(content).trim()}\\n\\n`;\n  });\n  source = source.replace(/<blockquote\\b[^>]*>([\\s\\S]*?)<\\/blockquote>/gi, (_, content) => {\n    const quote = htmlToMarkdown(content, { includeMetadata: false })\n      .split(\"\\n\")\n      .filter((line) => line.trim().length > 0)\n      .map((line) => `> ${line}`)\n      .join(\"\\n\");\n    return `\\n\\n${quote}\\n\\n`;\n  });\n  source = source.replace(/<li\\b[^>]*>([\\s\\S]*?)<\\/li>/gi, (_, content) => {\n    return `\\n- ${toInlineMarkdown(content).trim()}`;\n  });\n  source = source\n    .replace(/<\\/?(ul|ol|main|section|article|header|footer|nav|aside|div)\\b[^>]*>/gi, \"\\n\")\n    .replace(/<br\\s*\\/?>/gi, \"\\n\")\n    .replace(/<hr\\s*\\/?>/gi, \"\\n\\n---\\n\\n\");\n\n  let markdown = stripTags(source)\n    .split(\"\\n\")\n    .map((line) => line.replace(/[ \\t]+$/g, \"\"))\n    .join(\"\\n\")\n    .replace(/\\n{3,}/g, \"\\n\\n\")\n    .trim();\n\n  if (options.includeMetadata !== false) {\n    const metadata: string[] = [];\n    if (title && !markdown.startsWith(\"# \")) {\n      metadata.push(`# ${title}`);\n    }\n    if (options.sourcePath) {\n      metadata.push(`Source: ${options.sourcePath}`);\n    }\n    if (metadata.length) {\n      markdown = `${metadata.join(\"\\n\\n\")}${markdown ? `\\n\\n${markdown}` : \"\"}`;\n    }\n  }\n\n  return `${markdown}\\n`;\n}\n\nfunction normalizeMarkdownRouteInput(input: FarmMarkdownRouteInput): FarmMarkdownResolvedRoute {\n  if (typeof input === \"string\") {\n    return {\n      route: normalizeMarkdownRoute(input),\n    };\n  }\n\n  return {\n    ...input,\n    route: normalizeMarkdownRoute(input.route),\n  };\n}\n\nfunction normalizeMarkdownRoute(route: string): string {\n  const withoutMarkdownExtension = route.toLowerCase().endsWith(\".md\") ? route.slice(0, -3) : route;\n  const withSlash = withoutMarkdownExtension.startsWith(\"/\")\n    ? withoutMarkdownExtension\n    : `/${withoutMarkdownExtension}`;\n  const normalized = withSlash.replace(/\\/+/g, \"/\").replace(/\\/$/g, \"\");\n  return normalized === \"\" || normalized === \"/index\" ? \"/\" : normalized;\n}\n\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\nfunction appendHeaderToken(headers: Headers, name: string, token: string): void {\n  const current = headers.get(name);\n  if (!current) {\n    headers.set(name, token);\n    return;\n  }\n\n  const tokens = current.split(\",\").map((value) => value.trim().toLowerCase());\n  if (!tokens.includes(token.toLowerCase())) {\n    headers.set(name, `${current}, ${token}`);\n  }\n}\n\nfunction findExposedMarkdownRoute(\n  config: FarmMarkdownResolvedConfig,\n  pathname: string,\n): FarmMarkdownResolvedRoute | null {\n  if (config.expose === true) {\n    return null;\n  }\n\n  return config.expose.find((route) => routeMatches(route.route, pathname)) ?? null;\n}\n\nfunction routeMatches(pattern: string, pathname: string): boolean {\n  if (pattern === pathname) {\n    return true;\n  }\n\n  const escaped = pattern\n    .split(\"/\")\n    .map((segment) => {\n      if (/^\\[\\.\\.\\.[^\\]]+\\]$/.test(segment)) {\n        return \".*\";\n      }\n      if (/^\\[[^\\]]+\\]$/.test(segment)) {\n        return \"[^/]+\";\n      }\n      return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n    })\n    .join(\"/\");\n\n  return new RegExp(`^${escaped}$`).test(pathname);\n}\n\nfunction isHtmlResponse(response: Response): boolean {\n  const contentType = response.headers.get(\"content-type\") ?? \"\";\n  return contentType.includes(\"text/html\");\n}\n\nfunction createMarkdownCacheHeader(cache: number | false): string {\n  if (cache === false || cache <= 0) {\n    return \"no-store\";\n  }\n\n  return `public, max-age=${cache}, s-maxage=${cache}`;\n}\n\nfunction extractHtmlTitle(html: string): string | undefined {\n  const match = html.match(/<title\\b[^>]*>([\\s\\S]*?)<\\/title>/i);\n  return match ? decodeHtml(stripTags(match[1])).trim() : undefined;\n}\n\nfunction extractHtmlBody(html: string): string {\n  const rootMatch = html.match(\n    /<div\\b[^>]*id=[\"']root[\"'][^>]*>([\\s\\S]*?)<\\/div>\\s*(?:<script|<\\/body>|$)/i,\n  );\n  const bodyMatch = html.match(/<body\\b[^>]*>([\\s\\S]*?)<\\/body>/i);\n  const body = rootMatch ? rootMatch[1] : bodyMatch ? bodyMatch[1] : html;\n  return extractFirstElementContent(body, [\"main\", \"article\"]) ?? body;\n}\n\nfunction extractFirstElementContent(html: string, tagNames: string[]): string | undefined {\n  for (const tagName of tagNames) {\n    const match = html.match(new RegExp(`<${tagName}\\\\b[^>]*>([\\\\s\\\\S]*?)<\\\\/${tagName}>`, \"i\"));\n    if (match) {\n      return match[1];\n    }\n  }\n\n  return undefined;\n}\n\nfunction toInlineMarkdown(html: string): string {\n  let source = html\n    .replace(/<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>([\\s\\S]*?)<\\/a>/gi, (_, href, text) => {\n      const label: string = toInlineMarkdown(text).trim() || href;\n      return `[${label}](${decodeHtml(href)})`;\n    })\n    .replace(\n      /<img\\b[^>]*src=[\"']([^\"']+)[\"'][^>]*alt=[\"']([^\"']*)[\"'][^>]*\\/?>/gi,\n      (_, src, alt) => {\n        return `![${decodeHtml(alt)}](${decodeHtml(src)})`;\n      },\n    )\n    .replace(/<strong\\b[^>]*>([\\s\\S]*?)<\\/strong>/gi, (_, content) => {\n      return `**${toInlineMarkdown(content).trim()}**`;\n    })\n    .replace(/<b\\b[^>]*>([\\s\\S]*?)<\\/b>/gi, (_, content) => {\n      return `**${toInlineMarkdown(content).trim()}**`;\n    })\n    .replace(/<em\\b[^>]*>([\\s\\S]*?)<\\/em>/gi, (_, content) => {\n      return `_${toInlineMarkdown(content).trim()}_`;\n    })\n    .replace(/<i\\b[^>]*>([\\s\\S]*?)<\\/i>/gi, (_, content) => {\n      return `_${toInlineMarkdown(content).trim()}_`;\n    })\n    .replace(/<code\\b[^>]*>([\\s\\S]*?)<\\/code>/gi, (_, content) => {\n      return `\\`${decodeHtml(stripTags(content)).trim()}\\``;\n    })\n    .replace(/<br\\s*\\/?>/gi, \"\\n\");\n\n  source = stripTags(source);\n  return decodeHtml(source).replace(/\\s+/g, \" \");\n}\n\nfunction stripTags(input: string): string {\n  return input.replace(/<[^>]+>/g, \"\");\n}\n\nfunction decodeHtml(input: string): string {\n  return input.replace(/&(?:nbsp|amp|lt|gt|quot|#39|#(?:x|X)[0-9a-fA-F]+|#[0-9]+);/g, (entity) => {\n    switch (entity) {\n      case \"&nbsp;\":\n        return \" \";\n      case \"&amp;\":\n        return \"&\";\n      case \"&lt;\":\n        return \"<\";\n      case \"&gt;\":\n        return \">\";\n      case \"&quot;\":\n        return '\"';\n      case \"&#39;\":\n        return \"'\";\n    }\n\n    const hexadecimal = entity[2] === \"x\" || entity[2] === \"X\";\n    const codePoint = Number.parseInt(entity.slice(hexadecimal ? 3 : 2, -1), hexadecimal ? 16 : 10);\n    return codePoint === 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)\n      ? \"\\uFFFD\"\n      : String.fromCodePoint(codePoint);\n  });\n}\n","export type RouteSegmentSpecificity = \"static\" | \"dynamic\" | \"catch-all\" | \"optional-catch-all\";\n\nexport class AmbiguousRouteError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"AmbiguousRouteError\";\n  }\n}\n\nexport class NonTerminalCatchAllRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"NonTerminalCatchAllRouteError\";\n  }\n}\n\nexport class DuplicateRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"DuplicateRouteParameterError\";\n  }\n}\n\nexport class ReservedRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"ReservedRouteParameterError\";\n  }\n}\n\nexport class BrowserUnstableRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"BrowserUnstableRouteError\";\n  }\n}\n\nconst SEGMENT_RANK: Record<RouteSegmentSpecificity, number> = {\n  static: 4,\n  dynamic: 3,\n  \"catch-all\": 1,\n  \"optional-catch-all\": 0,\n};\n\n// Ending a route is more specific than consuming the same path through a\n// catch-all, while a following static or dynamic segment remains more specific.\nconst ROUTE_END_RANK = 2;\n\n/** Sort route patterns from the most specific segment sequence to the least specific. */\nexport function compareRouteSpecificity(\n  left: readonly RouteSegmentSpecificity[],\n  right: readonly RouteSegmentSpecificity[],\n): number {\n  const length = Math.max(left.length, right.length);\n\n  for (let index = 0; index < length; index++) {\n    const leftRank = index < left.length ? SEGMENT_RANK[left[index]!] : ROUTE_END_RANK;\n    const rightRank = index < right.length ? SEGMENT_RANK[right[index]!] : ROUTE_END_RANK;\n    if (leftRank !== rightRank) return rightRank - leftRank;\n  }\n\n  return 0;\n}\n\nexport type RoutePatternSyntax = \"page\" | \"router\" | \"api\";\n\nconst ROUTER_PARAMETER_NAME = \"[A-Za-z0-9_$-]+\";\nconst PAGE_PARAMETER_PATTERN = /^(?:\\[\\[\\.\\.\\.(.+)\\]\\]|\\[\\.\\.\\.(.+)\\]|\\[(.+)\\])$/;\nconst ROUTER_PARAMETER_PATTERN =\n  /^(?:\\[\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]\\]|\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]|\\[([A-Za-z0-9_$-]+)\\]|:([A-Za-z0-9_$-]+)|\\*([A-Za-z0-9_$-]+)\\??)$/;\nconst RESERVED_PARAMETER_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function assertBrowserStableRoutePath(pattern: string): void {\n  if (pattern.includes(\"\\\\\") || hasControlCharacter(pattern)) {\n    throw new BrowserUnstableRouteError(\n      `Route path \"${pattern}\" cannot contain backslashes or control characters.`,\n    );\n  }\n\n  for (const segment of pattern.split(\"/\").filter(Boolean)) {\n    if (\n      (segment.startsWith(\"(\") && segment.endsWith(\")\")) ||\n      (segment.startsWith(\"[\") && segment.endsWith(\"]\"))\n    ) {\n      continue;\n    }\n\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes stay literal in browser pathnames.\n    }\n    if (\n      decoded === \".\" ||\n      decoded === \"..\" ||\n      decoded.includes(\"/\") ||\n      decoded.includes(\"\\\\\") ||\n      hasControlCharacter(decoded)\n    ) {\n      throw new BrowserUnstableRouteError(\n        `Route path \"${pattern}\" contains browser-unstable segment \"${segment}\".`,\n      );\n    }\n  }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n  return Array.from(value).some((character) => {\n    const code = character.charCodeAt(0);\n    return code <= 31 || (code >= 127 && code <= 159);\n  });\n}\n\nexport function assertUniqueRouteParameters(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): void {\n  const parameterPattern = syntax === \"router\" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;\n  const names = new Set<string>();\n\n  for (const segment of splitRoutePattern(pattern, syntax)) {\n    const match = parameterPattern.exec(segment);\n    const name = match?.slice(1).find(Boolean);\n    if (!name) continue;\n    if (RESERVED_PARAMETER_NAMES.has(name)) {\n      throw new ReservedRouteParameterError(\n        `Route parameter \"${name}\" in route \"${pattern}\" is reserved. Use a different parameter name.`,\n      );\n    }\n    if (names.has(name)) {\n      throw new DuplicateRouteParameterError(\n        `Duplicate route parameter \"${name}\" in route \"${pattern}\". Each dynamic segment must use a unique name.`,\n      );\n    }\n    names.add(name);\n  }\n}\n\nfunction splitRoutePattern(pattern: string, syntax: RoutePatternSyntax): string[] {\n  return pattern\n    .replace(/\\\\/g, \"/\")\n    .split(\"/\")\n    .filter(Boolean)\n    .filter((segment) =>\n      syntax === \"api\" ? true : !(segment.startsWith(\"(\") && segment.endsWith(\")\")),\n    );\n}\n\nexport function assertTerminalCatchAll(pattern: string, syntax: RoutePatternSyntax = \"page\"): void {\n  const segments = splitRoutePattern(pattern, syntax);\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const catchAllPattern = new RegExp(\n    syntax === \"router\"\n      ? `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]|\\\\*${parameterName}\\\\??)$`\n      : `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\])$`,\n  );\n  const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));\n  if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {\n    throw new NonTerminalCatchAllRouteError(\n      `Catch-all segment \"${segments[catchAllIndex]}\" must be the final segment in route \"${pattern}\".`,\n    );\n  }\n}\n\n/** Return the URL-matching shape of a route without its parameter names. */\nexport function getRoutePatternShape(pattern: string, syntax: RoutePatternSyntax = \"page\"): string {\n  assertTerminalCatchAll(pattern, syntax);\n  const segments = splitRoutePattern(pattern, syntax).map((segment) => {\n    const specificity = getPatternSegmentSpecificity(segment, syntax);\n    if (specificity !== \"static\") return specificity;\n\n    try {\n      return `static:${decodeURIComponent(segment)}`;\n    } catch {\n      return `static:${segment}`;\n    }\n  });\n\n  return segments.length === 0 ? \"/\" : JSON.stringify(segments);\n}\n\n/** Return the specificity of every URL-consuming segment in a route pattern. */\nexport function getRoutePatternSpecificity(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): RouteSegmentSpecificity[] {\n  assertTerminalCatchAll(pattern, syntax);\n  return splitRoutePattern(pattern, syntax).map((segment) =>\n    getPatternSegmentSpecificity(segment, syntax),\n  );\n}\n\nfunction getPatternSegmentSpecificity(\n  segment: string,\n  syntax: RoutePatternSyntax,\n): RouteSegmentSpecificity {\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const supportsColonAndStar = syntax === \"router\";\n  if (\n    new RegExp(`^\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}\\\\?$`).test(segment))\n  ) {\n    return \"optional-catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}$`).test(segment))\n  ) {\n    return \"catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment))\n  ) {\n    return \"dynamic\";\n  }\n\n  return \"static\";\n}\n","import { assertBrowserStableRoutePath } from \"./routing/specificity\";\n\ninterface FarmNodeAbortRequest {\n  aborted?: boolean;\n  once(event: \"aborted\", listener: () => void): unknown;\n  off(event: \"aborted\", listener: () => void): unknown;\n}\n\ninterface FarmNodeAbortResponse {\n  writableEnded: boolean;\n  once(event: \"close\" | \"finish\", listener: () => void): unknown;\n  off(event: \"close\" | \"finish\", listener: () => void): unknown;\n}\n\n/** Share disconnect semantics between development and production Node requests. */\nexport function createFarmNodeRequestAbortSignal(\n  req: FarmNodeAbortRequest,\n  res: FarmNodeAbortResponse,\n): AbortSignal {\n  const controller = new AbortController();\n  let disposed = false;\n  const dispose = () => {\n    if (disposed) return;\n    disposed = true;\n    req.off(\"aborted\", abort);\n    res.off(\"close\", abortOnEarlyClose);\n    res.off(\"finish\", dispose);\n    controller.signal.removeEventListener(\"abort\", dispose);\n  };\n  const abort = () => controller.abort();\n  const abortOnEarlyClose = () => {\n    if (!res.writableEnded) abort();\n    dispose();\n  };\n\n  if (req.aborted) {\n    controller.abort();\n    return controller.signal;\n  }\n\n  req.once(\"aborted\", abort);\n  res.once(\"close\", abortOnEarlyClose);\n  res.once(\"finish\", dispose);\n  controller.signal.addEventListener(\"abort\", dispose, { once: true });\n  return controller.signal;\n}\n\nexport const DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 10_000_000;\nexport const DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 60_000;\nexport const DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 300_000;\nexport const DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5_000;\nexport const DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 30_000;\nconst MAX_FARM_SERVER_TIMEOUT = 2_147_483_647;\n\nexport type FarmServerDuration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport interface FarmServerHealthConfig {\n  /** Liveness endpoint. It remains healthy while a production process drains. */\n  livenessPath?: string;\n  /** Readiness endpoint. It returns 503 until startup completes and while draining. */\n  readinessPath?: string;\n}\n\nexport interface ResolvedFarmServerHealthConfig {\n  enabled: boolean;\n  livenessPath: string;\n  readinessPath: string;\n}\n\nexport interface FarmServerConfig {\n  /** Maximum request body size for API routes, integrations, workflows, and uploads. */\n  bodySizeLimit?: number | string;\n  /** Trust proxy-provided client address and request authority headers. Enable only behind a trusted proxy. */\n  trustProxy?: boolean;\n  /** Maximum time for a Node client to send complete request headers. */\n  headersTimeout?: FarmServerDuration;\n  /** Maximum time for a Node client to send the complete request. */\n  requestTimeout?: FarmServerDuration;\n  /** How long an idle Node keep-alive connection remains open after a response. */\n  keepAliveTimeout?: FarmServerDuration;\n  /** Maximum time the Node adapter drains traffic before forcing shutdown. */\n  gracefulShutdownTimeout?: FarmServerDuration;\n  /** Production liveness and readiness endpoints. Set to false to disable them. */\n  health?: false | FarmServerHealthConfig;\n}\n\nexport interface ResolvedFarmServerConfig {\n  bodySizeLimit: number;\n  trustProxy: boolean;\n  headersTimeout: number;\n  requestTimeout: number;\n  keepAliveTimeout: number;\n  gracefulShutdownTimeout: number;\n  health: ResolvedFarmServerHealthConfig;\n}\n\nexport type FarmRequestBodyErrorCode = \"BODY_TOO_LARGE\" | \"INVALID_CONTENT_LENGTH\";\n\n/** Apply the weak entity-tag comparison required by If-None-Match. */\nexport function matchesFarmIfNoneMatch(\n  value: string | readonly string[] | null | undefined,\n  etag: string,\n): boolean {\n  const expected = parseEntityTag(trimOptionalWhitespace(etag));\n  if (!expected) return false;\n\n  const values = Array.isArray(value) ? value : [value];\n  const combined = values\n    .filter((header): header is string => typeof header === \"string\")\n    .join(\",\");\n  const fieldValue = trimOptionalWhitespace(combined);\n  if (!fieldValue) return false;\n  if (fieldValue === \"*\") return true;\n\n  let matched = false;\n  let hasEntityTag = false;\n  for (const candidate of splitEntityTags(fieldValue)) {\n    const token = trimOptionalWhitespace(candidate);\n    if (!token) continue;\n\n    const parsed = parseEntityTag(token);\n    if (!parsed) return false;\n    hasEntityTag = true;\n    if (parsed === expected) matched = true;\n  }\n\n  return hasEntityTag && matched;\n}\n\nfunction trimOptionalWhitespace(value: string): string {\n  return value.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n}\n\nfunction parseEntityTag(value: string): string | null {\n  const opaqueTag = value.startsWith(\"W/\") ? value.slice(2) : value;\n  if (opaqueTag.length < 2 || opaqueTag[0] !== '\"' || opaqueTag.at(-1) !== '\"') return null;\n\n  for (let index = 1; index < opaqueTag.length - 1; index++) {\n    const code = opaqueTag.charCodeAt(index);\n    if (code === 0x21 || (code >= 0x23 && code <= 0x7e) || code >= 0x80) continue;\n    return null;\n  }\n\n  return opaqueTag;\n}\n\nfunction splitEntityTags(value: string): string[] {\n  const tags: string[] = [];\n  let start = 0;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index++) {\n    const character = value[index];\n    if (character === '\"') {\n      quoted = !quoted;\n    } else if (character === \",\" && !quoted) {\n      tags.push(value.slice(start, index));\n      start = index + 1;\n    }\n  }\n\n  tags.push(value.slice(start));\n  return tags;\n}\n\nexport class FarmRequestBodyError extends Error {\n  readonly code: FarmRequestBodyErrorCode;\n  readonly status: number;\n\n  constructor(code: FarmRequestBodyErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"FarmRequestBodyError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\nexport function resolveFarmServerConfig(\n  config: FarmServerConfig | ResolvedFarmServerConfig | undefined,\n): ResolvedFarmServerConfig {\n  const headersTimeout = parseFarmServerDuration(\n    config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,\n    \"server.headersTimeout\",\n  );\n  const requestTimeout = parseFarmServerDuration(\n    config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,\n    \"server.requestTimeout\",\n  );\n  if (headersTimeout > requestTimeout) {\n    throw new TypeError(\"server.headersTimeout must not exceed server.requestTimeout\");\n  }\n\n  return Object.freeze({\n    bodySizeLimit: parseBodySizeLimit(\n      config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n      \"server.bodySizeLimit\",\n    ),\n    trustProxy: config?.trustProxy === true,\n    headersTimeout,\n    requestTimeout,\n    keepAliveTimeout: parseFarmServerDuration(\n      config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,\n      \"server.keepAliveTimeout\",\n    ),\n    gracefulShutdownTimeout: parseFarmServerDuration(\n      config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,\n      \"server.gracefulShutdownTimeout\",\n    ),\n    health: resolveFarmServerHealthConfig(config?.health),\n  });\n}\n\nexport function parseFarmServerDuration(\n  value: FarmServerDuration,\n  optionName = \"duration\",\n): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    if (value > MAX_FARM_SERVER_TIMEOUT) {\n      throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be milliseconds or a duration such as \"30s\" or \"2m\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2];\n  const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n  const milliseconds = Math.floor(amount * multiplier);\n  if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n  if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {\n    throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n  }\n  return milliseconds;\n}\n\nfunction resolveFarmServerHealthConfig(\n  config: false | FarmServerHealthConfig | ResolvedFarmServerHealthConfig | undefined,\n): ResolvedFarmServerHealthConfig {\n  if (config === false || (config && \"enabled\" in config && config.enabled === false)) {\n    return Object.freeze({\n      enabled: false,\n      livenessPath: \"/_farm/health/live\",\n      readinessPath: \"/_farm/health/ready\",\n    });\n  }\n\n  const livenessPath = normalizeHealthPath(\n    config?.livenessPath ?? \"/_farm/health/live\",\n    \"server.health.livenessPath\",\n  );\n  const readinessPath = normalizeHealthPath(\n    config?.readinessPath ?? \"/_farm/health/ready\",\n    \"server.health.readinessPath\",\n  );\n  if (livenessPath === readinessPath) {\n    throw new TypeError(\"server.health livenessPath and readinessPath must be different\");\n  }\n\n  return Object.freeze({ enabled: true, livenessPath, readinessPath });\n}\n\nfunction normalizeHealthPath(value: string, optionName: string): string {\n  const path = value.trim();\n  if (!path.startsWith(\"/\") || path.includes(\"?\") || path.includes(\"#\") || path.includes(\"*\")) {\n    throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);\n  }\n  const normalized = path.length > 1 ? path.replace(/\\/+$/, \"\") || \"/\" : path;\n  assertBrowserStableRoutePath(normalized);\n  return normalized;\n}\n\nexport function parseBodySizeLimit(value: number | string, optionName = \"bodySizeLimit\"): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)?$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be bytes or a size string such as \"500kb\" or \"10mb\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2] ?? \"b\";\n  const multiplier: Record<string, number> = {\n    b: 1,\n    kb: 1_000,\n    mb: 1_000_000,\n    gb: 1_000_000_000,\n    kib: 1_024,\n    mib: 1_048_576,\n    gib: 1_073_741_824,\n  };\n  const bytes = Math.floor(amount * multiplier[unit]);\n\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n\n  return bytes;\n}\n\nexport async function bufferFarmRequestBody(request: Request, limit: number): Promise<Request> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || request.body === null) {\n    return request;\n  }\n\n  const bytes = await readFarmRequestBody(request, limit);\n  const body = new Uint8Array(bytes.byteLength);\n  body.set(bytes);\n  return new Request(request, {\n    // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.\n    body: body.buffer,\n  });\n}\n\nexport async function readFarmRequestBody(request: Request, limit: number): Promise<Uint8Array> {\n  try {\n    validateContentLength(request.headers.get(\"content-length\"), limit);\n  } catch (error) {\n    // A cloned Request is a tee branch: its cancellation may wait for the\n    // untouched branch. Rejection must not wait for producer-owned cleanup.\n    void request.body?.cancel(error).catch(() => {});\n    throw error;\n  }\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      // Cancellation resolves a pending read as EOF, not necessarily an error.\n      throwIfAborted(request.signal);\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nexport async function readNodeRequestBody(\n  request: {\n    headers: Record<string, string | string[] | undefined>;\n    on(event: \"data\", listener: (chunk: unknown) => void): unknown;\n    on(event: \"end\", listener: () => void): unknown;\n    on(event: \"error\", listener: (error: Error) => void): unknown;\n    removeListener?(event: string, listener: (...args: any[]) => void): unknown;\n    resume?(): unknown;\n  },\n  limit: number,\n): Promise<Buffer> {\n  const rawContentLength = request.headers[\"content-length\"];\n  const contentLength = Array.isArray(rawContentLength) ? rawContentLength[0] : rawContentLength;\n  try {\n    validateContentLength(contentLength, limit);\n  } catch (error) {\n    request.resume?.();\n    throw error;\n  }\n\n  return await new Promise<Buffer>((resolve, reject) => {\n    const chunks: Buffer[] = [];\n    let total = 0;\n    let settled = false;\n\n    const cleanup = () => {\n      request.removeListener?.(\"data\", onData);\n      request.removeListener?.(\"end\", onEnd);\n      request.removeListener?.(\"error\", onError);\n    };\n    const rejectOnce = (error: Error) => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      request.resume?.();\n      reject(error);\n    };\n    const onData = (chunk: unknown) => {\n      const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as any);\n      total += bytes.byteLength;\n      if (total > limit) {\n        rejectOnce(new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\"));\n        return;\n      }\n      chunks.push(bytes);\n    };\n    const onEnd = () => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      resolve(Buffer.concat(chunks, total));\n    };\n    const onError = (error: Error) => rejectOnce(error);\n\n    request.on(\"data\", onData);\n    request.on(\"end\", onEnd);\n    request.on(\"error\", onError);\n  });\n}\n\nexport function createFarmRequestBodyErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof FarmRequestBodyError)) return null;\n\n  return new Response(error.status === 413 ? \"Payload Too Large\" : \"Bad Request\", {\n    status: error.status,\n    headers: {\n      \"cache-control\": \"no-store\",\n      \"content-type\": \"text/plain; charset=utf-8\",\n      \"x-content-type-options\": \"nosniff\",\n    },\n  });\n}\n\nfunction validateContentLength(value: string | null | undefined, limit: number): void {\n  const contentLength = value?.trim();\n  if (!contentLength) return;\n  if (!/^\\d+$/.test(contentLength)) {\n    throw new FarmRequestBodyError(\"INVALID_CONTENT_LENGTH\", 400, \"Invalid content-length header\");\n  }\n  if (Number(contentLength) > limit) {\n    throw new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","/**\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 * 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","/**\n * Decode a percent-encoded path segment, falling back to the raw value.\n *\n * Request paths are not guaranteed to be validly percent-encoded, so\n * `decodeURIComponent` can throw on input that is still a legal URL: a\n * latin-1 escape such as `caf%E9` from an old link, or a truncated `%ZZ`\n * from a crawler. A malformed segment simply will not match a known route,\n * which is a 404, so it must not throw out of route matching.\n */\nexport function decodeRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n","import type { RouteSegment, ParsedRoute } from \"./types\";\nimport path from \"path\";\nimport {\n  assertBrowserStableRoutePath,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n} from \"./routing/specificity\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { decodeRouteSegment } from \"./utils/decode\";\n\nexport function parseRoutePath(filePath: string): ParsedRoute {\n  const segments: RouteSegment[] = [];\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  const pathParts = normalizedPath.split(\"/\").filter(Boolean);\n\n  const fileName = pathParts.pop() || \"\";\n  const fileType = getRouteType(fileName);\n  const routePath = `/${pathParts.join(\"/\")}`;\n  assertBrowserStableRoutePath(routePath);\n  assertTerminalCatchAll(routePath);\n  assertUniqueRouteParameters(routePath);\n\n  for (const part of pathParts) {\n    // Route groups like `(marketing)` organize files without adding URL\n    // segments. Mirrors isRouteGroup in router.ts for programmatic routes.\n    if (part.startsWith(\"(\") && part.endsWith(\")\")) continue;\n    if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n      let segment = part.slice(1, -1);\n      const isDynamic = true;\n      let isOptional = false;\n      let isCatchAll = false;\n\n      if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n        isOptional = true;\n        segment = segment.slice(1, -1);\n        if (segment.startsWith(\"...\")) {\n          segment = segment.slice(3);\n          isCatchAll = true;\n        }\n      } else if (segment.startsWith(\"...\")) {\n        segment = segment.slice(3);\n        isCatchAll = true;\n      }\n\n      segments.push({ segment, isDynamic, isOptional, isCatchAll });\n    } else {\n      segments.push({\n        segment: part,\n        isDynamic: false,\n        isOptional: false,\n        isCatchAll: false,\n      });\n    }\n  }\n\n  return {\n    segments,\n    filePath: normalizedPath,\n    type: fileType,\n  };\n}\n\nfunction getRouteType(fileName: string): ParsedRoute[\"type\"] {\n  const baseName = fileName.replace(/\\.(tsx?|jsx?|vue|svelte|mdx?|markdown)$/, \"\");\n\n  switch (baseName) {\n    case \"page\":\n      return \"page\";\n    case \"layout\":\n      return \"layout\";\n    case \"loading\":\n      return \"loading\";\n    case \"error\":\n      return \"error\";\n    case \"not-found\":\n      return \"not-found\";\n    default:\n      return \"page\";\n  }\n}\n\nexport function segmentsToPattern(segments: RouteSegment[]): string {\n  if (segments.length === 0) return \"/\";\n\n  return (\n    \"/\" +\n    segments\n      .map((segment) => {\n        if (!segment.isDynamic) return segment.segment;\n\n        if (segment.isCatchAll) {\n          return segment.isOptional ? `*${segment.segment}?` : `*${segment.segment}`;\n        }\n\n        return `:${segment.segment}`;\n      })\n      .join(\"/\")\n  );\n}\n\nexport function matchRoute(\n  url: string,\n  segments: RouteSegment[],\n): { params: Record<string, string>; matches: boolean } {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  const params: Record<string, string> = {};\n  if (segments.length === 0) {\n    return { params, matches: urlParts.length === 0 };\n  }\n\n  let urlIndex = 0;\n  let segmentIndex = 0;\n\n  while (segmentIndex < segments.length && urlIndex <= urlParts.length) {\n    const segment = segments[segmentIndex];\n\n    if (!segment.isDynamic) {\n      if (urlParts[urlIndex] !== segment.segment) {\n        return { params: {}, matches: false };\n      }\n      urlIndex++;\n      segmentIndex++;\n    } else if (segment.isCatchAll) {\n      const remainingParts = urlParts.slice(urlIndex);\n\n      if (remainingParts.length === 0 && !segment.isOptional) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = remainingParts.join(\"/\");\n      urlIndex = urlParts.length;\n      segmentIndex++;\n    } else {\n      if (urlIndex >= urlParts.length) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = urlParts[urlIndex];\n      urlIndex++;\n      segmentIndex++;\n    }\n  }\n\n  const matches = segmentIndex === segments.length && urlIndex === urlParts.length;\n\n  return { params, matches };\n}\n\n/** Match a route segment chain as an owner of the pathname or one of its descendants. */\nexport function matchRoutePrefix(url: string, segments: RouteSegment[]): boolean {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  let urlIndex = 0;\n\n  for (const segment of segments) {\n    if (segment.isCatchAll) {\n      return segment.isOptional || urlIndex < urlParts.length;\n    }\n\n    const urlPart = urlParts[urlIndex];\n    if (urlPart === undefined) return false;\n    if (!segment.isDynamic && segment.segment !== urlPart) return false;\n    urlIndex++;\n  }\n\n  return true;\n}\n\nexport function resolveAppPath(root: string, ...paths: string[]): string {\n  return path.resolve(root, ...paths);\n}\n\n/**\n * Convert an absolute module path inside the project root to a root-relative\n * URL path with forward slashes (e.g. `/src/app/page.tsx`), for values the\n * client passes to dynamic `import()`. On Windows the naive root-prefix slice\n * yields `\\src\\app\\page.tsx`, which is not a valid module specifier. Returns\n * undefined for paths outside the root so callers keep their own fallbacks.\n */\nexport function toRootRelativeUrlPath(\n  absolutePath: string,\n  projectRoot: string,\n): string | undefined {\n  if (absolutePath === projectRoot) return \"\";\n  if (absolutePath.startsWith(`${projectRoot}/`) || absolutePath.startsWith(`${projectRoot}\\\\`)) {\n    return absolutePath.slice(projectRoot.length).replace(/\\\\/g, \"/\");\n  }\n  return undefined;\n}\n\n/**\n * Normalize a filesystem path to forward slashes. Node's fs accepts these on\n * every platform, and module ids handed to bundlers (e.g. Nitro handler and\n * task entries) must not contain backslashes.\n */\nexport function toPosixPath(filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\");\n}\n\nexport function toViteModuleId(filePath: string, root: string): string {\n  if (!path.isAbsolute(filePath)) return filePath;\n\n  const relativePath = path.relative(root, filePath);\n  if (relativePath && !relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n    return `/${relativePath.split(path.sep).join(\"/\")}`;\n  }\n\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  return normalizedPath.startsWith(\"/\") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n  try {\n    const fs = await import(\"fs/promises\");\n    await fs.access(filePath);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function globFiles(pattern: string, cwd: string): Promise<string[]> {\n  const glob = await import(\"fast-glob\");\n  return glob.default(pattern, { cwd, absolute: false });\n}\n\nexport function parseSearchParams(\n  searchParams: URLSearchParams,\n): Record<string, string | string[]> {\n  return searchParamsToObject(searchParams) as Record<string, string | string[]>;\n}\n\nexport const logger = {\n  info: (message: string) => console.log(`[info] ${message}`),\n  success: (message: string) => console.log(`[success] ${message}`),\n  warn: (message: string) => console.warn(`⚠️  ${message}`),\n  error: (message: string) => console.error(`❌ ${message}`),\n  ready: (message: string) => console.log(`${message}`),\n  event: (message: string) => console.log(`  ${message}`),\n};\n","const FARM_BASE_PATH = Symbol.for(\"farm.basePath\");\n\nfunction getFarmGlobalState(): Record<PropertyKey, unknown> {\n  return globalThis as unknown as Record<PropertyKey, unknown>;\n}\n\n/** @internal Configure the app-wide base path for framework link rendering. */\nexport function setFarmBasePath(basePath: string | undefined): void {\n  getFarmGlobalState()[FARM_BASE_PATH] = normalizeFarmBasePath(basePath);\n}\n\n/** @internal Read the app-wide base path used by framework links. */\nexport function getFarmBasePath(): string {\n  return (getFarmGlobalState()[FARM_BASE_PATH] as string | undefined) ?? \"\";\n}\n\nexport function applyFarmBasePath(href: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath || !href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n  const canonicalHref = canonicalizeAppRelativeHref(href);\n  if (\n    canonicalHref === normalizedBasePath ||\n    canonicalHref.startsWith(`${normalizedBasePath}/`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}?`) ||\n    canonicalHref.startsWith(`${normalizedBasePath}#`)\n  ) {\n    return canonicalHref;\n  }\n  return `${normalizedBasePath}${canonicalHref}`;\n}\n\nfunction canonicalizeAppRelativeHref(href: string): string {\n  const origin = \"http://farm.local\";\n  const resolved = new URL(href, origin);\n  if (resolved.origin !== origin) {\n    throw new Error(\"Farm app-relative href cannot change the URL origin.\");\n  }\n  return `${resolved.pathname}${resolved.search}${resolved.hash}`;\n}\n\nexport function stripFarmBasePath(pathname: string, basePath = getFarmBasePath()): string {\n  const normalizedBasePath = normalizeFarmBasePath(basePath);\n  if (!normalizedBasePath) return pathname || \"/\";\n  if (pathname === normalizedBasePath) return \"/\";\n  if (!pathname.startsWith(`${normalizedBasePath}/`)) return pathname || \"/\";\n  return pathname.slice(normalizedBasePath.length) || \"/\";\n}\n\nexport function normalizeFarmBasePath(basePath: string | undefined): string {\n  if (!basePath || basePath === \"/\") return \"\";\n\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(basePath)) {\n    throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n  }\n\n  const pathname = basePath.trim();\n  if (!pathname || pathname === \"/\") return \"\";\n  if (pathname.includes(\"?\") || pathname.includes(\"#\")) {\n    throw new Error(\"Farm basePath cannot contain a query string or hash.\");\n  }\n  if (pathname.startsWith(\"//\") || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(pathname)) {\n    throw new Error('Farm basePath must be a pathname such as \"/docs\", not a URL.');\n  }\n\n  for (const segment of pathname.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal in URL pathnames and cannot be dot segments.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"Farm basePath cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"Farm basePath cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('Farm basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  return `/${pathname}`.replace(/\\/{2,}/g, \"/\").replace(/\\/+$/, \"\");\n}\n\n/** Normalize a configured application base path while preserving `/` for root. */\nexport function normalizeFarmConfigBasePath(basePath: string | undefined): string {\n  return normalizeFarmBasePath(basePath) || \"/\";\n}\n","import { applyFarmBasePath, stripFarmBasePath } from \"../base-path\";\nimport type { FarmI18nDirection, FarmI18nRouting, ResolvedFarmI18nConfig } from \"./types\";\n\nexport interface FarmLocalePathConfig {\n  locales: readonly string[];\n  defaultLocale: string;\n  routing: FarmI18nRouting;\n  basePath?: string;\n}\n\nexport interface FarmLocalePathMatch {\n  locale?: string;\n  pathname: string;\n  explicit: boolean;\n}\n\nconst RTL_LANGUAGES = new Set([\n  \"ar\",\n  \"arc\",\n  \"ckb\",\n  \"dv\",\n  \"fa\",\n  \"he\",\n  \"ku\",\n  \"nqo\",\n  \"ps\",\n  \"sd\",\n  \"syr\",\n  \"ug\",\n  \"ur\",\n  \"yi\",\n]);\n\nexport function resolveFarmLocalePath(\n  pathname: string,\n  config: FarmLocalePathConfig,\n): FarmLocalePathMatch {\n  const normalized = normalizePathname(stripFarmBasePath(pathname, config.basePath));\n  if (config.routing === \"none\") {\n    return { pathname: normalized, explicit: false };\n  }\n\n  const segments = normalized.split(\"/\").filter(Boolean);\n  const firstSegment = segments[0];\n  const locale = config.locales.find(\n    (candidate) => candidate.toLowerCase() === firstSegment?.toLowerCase(),\n  );\n  if (!locale) {\n    return { pathname: normalized, explicit: false };\n  }\n\n  const remaining = segments.slice(1);\n  return {\n    locale,\n    pathname: remaining.length > 0 ? `/${remaining.join(\"/\")}` : \"/\",\n    explicit: true,\n  };\n}\n\nexport function stripFarmLocaleFromPathname(\n  pathname: string,\n  config: FarmLocalePathConfig,\n): string {\n  return resolveFarmLocalePath(pathname, config).pathname;\n}\n\nexport function localizeFarmPathname(\n  pathname: string,\n  locale: string,\n  config: FarmLocalePathConfig,\n): string {\n  const internalPathname = resolveFarmLocalePath(pathname, config).pathname;\n  let localizedPathname = internalPathname;\n  if (config.routing === \"none\") {\n    return applyFarmBasePath(localizedPathname, config.basePath);\n  }\n  if (config.routing === \"prefix-except-default\" && locale === config.defaultLocale) {\n    return applyFarmBasePath(localizedPathname, config.basePath);\n  }\n  localizedPathname = internalPathname === \"/\" ? `/${locale}` : `/${locale}${internalPathname}`;\n  return applyFarmBasePath(localizedPathname, config.basePath);\n}\n\nexport function localizeFarmHref(\n  href: string,\n  locale: string,\n  config: FarmLocalePathConfig,\n): string {\n  if (!href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n  const url = new URL(href, \"http://farm.local\");\n  url.pathname = localizeFarmPathname(url.pathname, locale, config);\n  return `${url.pathname}${url.search}${url.hash}`;\n}\n\nexport function getFarmLocaleDirection(\n  locale: string,\n  direction: ResolvedFarmI18nConfig[\"direction\"] | undefined,\n): FarmI18nDirection {\n  const configured = direction?.[locale];\n  if (configured) return configured;\n  const language = locale.split(\"-\")[0]?.toLowerCase() || locale.toLowerCase();\n  return RTL_LANGUAGES.has(language) ? \"rtl\" : \"ltr\";\n}\n\nfunction normalizePathname(pathname: string): string {\n  const withLeadingSlash = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n  if (withLeadingSlash === \"/\") return \"/\";\n  return withLeadingSlash.replace(/\\/{2,}/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n}\n","import { localizeFarmHref, resolveFarmLocalePath } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { assertBrowserStableRoutePath } from \"../routing/specificity\";\n\ntype ConfigRoutePatternToken =\n  | { kind: \"param\"; name: string; captureIndex: number; catchAll: boolean }\n  | { kind: \"wildcard\"; captureIndex: number };\n\nexport interface CompiledConfigRoutePattern {\n  regex: RegExp;\n  tokens: ConfigRoutePatternToken[];\n}\n\nexport function validateConfigRouteSource(source: string, field = \"Config route source\"): string {\n  if (typeof source !== \"string\" || source.length === 0) {\n    throw new TypeError(`${field} must be a non-empty pathname pattern.`);\n  }\n  if (source.trim() !== source) {\n    throw new Error(`${field} cannot contain leading or trailing whitespace.`);\n  }\n  if (!source.startsWith(\"/\")) {\n    throw new Error(`${field} must start with \"/\".`);\n  }\n  if (source.includes(\"?\") || source.includes(\"#\")) {\n    throw new Error(`${field} must be a pathname without a query string or hash.`);\n  }\n  if (\n    source.includes(\"\\\\\") ||\n    Array.from(source).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  ) {\n    throw new Error(`${field} cannot contain backslashes or control characters.`);\n  }\n  assertBrowserStableRoutePath(source);\n  return source;\n}\n\nexport function resolveConfigRoutePathname(\n  pathname: string,\n  i18n?: ResolvedFarmI18nConfig,\n): { pathname: string; locale?: string } {\n  if (!i18n?.enabled) return { pathname: normalizeConfigRoutePathname(pathname) };\n  const match = resolveFarmLocalePath(pathname, i18n);\n  return { pathname: normalizeConfigRoutePathname(match.pathname), locale: match.locale };\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","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/runtime\";\nimport { runFarmWorkflowModule } from \"@farm.js/core/workflows\";\nimport * as workflowModule from ${JSON.stringify(normalizedPath)};\n\nexport default defineTask({\n  meta: {\n    description: ${JSON.stringify(workflow.description || `Farm workflow ${workflow.id}`)}\n  },\n  async run(event) {\n    const payload = event?.payload || {};\n    const env = event?.context?.cloudflare?.env || event?.context?.env || process.env;\n    return await runFarmWorkflowModule(workflowModule, {\n      id: ${JSON.stringify(workflow.id)},\n      name: event?.name || ${JSON.stringify(workflow.id)},\n      payload,\n      scheduledTime: payload.scheduledTime,\n      request: event?.context?.request,\n      event,\n      env\n    });\n  }\n});\n`.trim();\n}\n\nfunction createNitroWorkflowHTTPHandler(\n  config: FarmWorkflowsResolvedConfig,\n  workflows: FarmDiscoveredWorkflow[],\n  server: ResolvedFarmServerConfig,\n): string {\n  return `\nimport { H3 } from \"h3\";\nimport { runTask } from \"nitro/runtime\";\nimport {\n  createFarmRequestBodyErrorResponse,\n  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 { defineTask, useNitroApp } from \"nitro/runtime\";\n\nconst name = ${JSON.stringify(job.name)};\nconst path = ${JSON.stringify(job.path)};\nconst secretEnv = ${JSON.stringify(secretEnv)};\n\nfunction readSecret(event) {\n  const runtimeEnv = event?.context?.cloudflare?.env || event?.context?.env || {};\n  return runtimeEnv[secretEnv] || (typeof process !== \"undefined\" ? process.env?.[secretEnv] : \"\") || \"\";\n}\n\nexport default defineTask({\n  meta: {\n    name: ${JSON.stringify(getFarmCronTaskName(job.name))},\n    description: ${JSON.stringify(job.description || `Farm cron ${job.name}`)}\n  },\n  async run(event) {\n    const headers = new Headers({\n      \"x-farm-cron-name\": name,\n      \"x-farm-cron-scheduled-at\": String(event?.payload?.scheduledTime || Date.now())\n    });\n    const secret = readSecret(event);\n    if (secret) headers.set(\"authorization\", \"Bearer \" + secret);\n\n    const response = await useNitroApp().fetch(path, { method: \"GET\", headers });\n    const contentType = response.headers.get(\"content-type\") || \"\";\n    const body = response.status === 204\n      ? null\n      : contentType.includes(\"application/json\")\n        ? await response.json().catch(() => null)\n        : await response.text();\n\n    if (!response.ok) {\n      const detail = typeof body === \"string\" ? body : JSON.stringify(body);\n      throw new Error(\n        \"Farm cron \" + JSON.stringify(name) + \" received \" + response.status +\n        \" from \" + path + (detail ? \": \" + detail : \"\")\n      );\n    }\n\n    return { result: body };\n  }\n});\n`.trim();\n}\n\n/**\n * Wrapper file names for a set of cron job names.\n *\n * Cron names are case-sensitive and `Daily` and `daily` are both valid, distinct\n * jobs — but macOS and Windows use case-insensitive filesystems by default, so\n * their wrappers would overwrite one another and both jobs would run whichever\n * file was written last. Names are only disambiguated when they actually\n * collide case-insensitively, so ordinary names such as `dailyCleanup` keep a\n * readable wrapper; every name in a colliding group gets a digest of the exact\n * job name appended, which keeps the result independent of configuration order.\n */\nfunction resolveCronWrapperFileNames(names: readonly string[]): Map<string, string> {\n  const groups = new Map<string, number>();\n  for (const name of names) {\n    const key = safeFileName(name).toLowerCase();\n    groups.set(key, (groups.get(key) ?? 0) + 1);\n  }\n\n  const resolved = new Map<string, string>();\n  const claimed = new Map<string, string>();\n  for (const name of names) {\n    const base = safeFileName(name);\n    const key = base.toLowerCase();\n    const fileName = (groups.get(key) ?? 0) > 1 ? `${key}-${cronNameFingerprint(name)}` : base;\n    const claimedBy = claimed.get(fileName.toLowerCase());\n    if (claimedBy !== undefined) {\n      throw new Error(\n        `Farm cron jobs ${JSON.stringify(claimedBy)} and ${JSON.stringify(name)} generate the same wrapper file ${JSON.stringify(`${fileName}.mjs`)}. Rename one of them.`,\n      );\n    }\n    claimed.set(fileName.toLowerCase(), name);\n    resolved.set(name, fileName);\n  }\n  return resolved;\n}\n\n/**\n * FNV-1a. This module is bundled into server runtimes without node:crypto, and\n * the digest only needs to separate file names.\n */\nfunction cronNameFingerprint(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index += 1) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction safeFileName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"cron\";\n}\n","import { createStorage, prefixStorage, builtinDrivers, type BuiltinDriverName } from \"unstorage\";\nimport type { Driver, Storage, TransactionOptions } from \"unstorage\";\nimport type { Database } from \"db0\";\nimport memoryDriver from \"unstorage/drivers/memory\";\nimport type {\n  FarmStorageClient,\n  FarmStorageClientConfig,\n  FarmStorageConfigObject,\n  FarmStorageLocalDriverConfig,\n  FarmStorageDatabaseConfig,\n  FarmStorageDatabaseDriverMap,\n  FarmStorageDatabaseDriverName,\n  FarmStorageRuntimeClient,\n  FarmStorageMountConfig,\n  FarmStorageMounts,\n  FarmStorageUserConfig,\n} from \"./types\";\n\nexport type {\n  FarmStorageBuiltinDriverConfig,\n  FarmStorageClient,\n  FarmStorageClientConfig,\n  FarmStorageConfigObject,\n  FarmStorageCustomDriverConfig,\n  FarmStorageDatabaseConfig,\n  FarmStorageDatabaseDriverName,\n  FarmStorageLocalDriverConfig,\n  FarmStorageRuntimeClient,\n  FarmStorageMountConfig,\n  FarmStorageMounts,\n  FarmStorageUserConfig,\n} from \"./types\";\nexport type {\n  BuiltinDriverName,\n  BuiltinDriverOptions,\n  Driver,\n  Storage,\n  StorageMeta,\n  StorageValue,\n  TransactionOptions,\n} from \"unstorage\";\nexport type { ConnectorName, ConnectorOptions, Database } from \"db0\";\n\ntype DriverFactoryModule = {\n  default: (options?: Record<string, any>) => Driver;\n};\n\ntype DriverResolver = () => Driver | Promise<Driver>;\ntype ModuleLoader = <T = any>(specifier: string) => Promise<T>;\n\nconst loadModule: ModuleLoader = (specifier) => import(/* @vite-ignore */ specifier);\n\nconst DATABASE_CONNECTORS: {\n  [K in FarmStorageDatabaseDriverName]: {\n    connector: FarmStorageDatabaseDriverMap[K];\n    load: () => Promise<{ default: (options?: any) => any }>;\n  };\n} = {\n  sqlite: {\n    connector: \"node-sqlite\",\n    load: () => loadModule(\"db0/connectors/node-sqlite\"),\n  },\n  \"node-sqlite\": {\n    connector: \"node-sqlite\",\n    load: () => loadModule(\"db0/connectors/node-sqlite\"),\n  },\n  sqlite3: {\n    connector: \"sqlite3\",\n    load: () => loadModule(\"db0/connectors/sqlite3\"),\n  },\n  \"better-sqlite3\": {\n    connector: \"better-sqlite3\",\n    load: () => loadModule(\"db0/connectors/better-sqlite3\"),\n  },\n  postgres: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  postgresql: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  pg: {\n    connector: \"postgresql\",\n    load: () => loadModule(\"db0/connectors/postgresql\"),\n  },\n  mysql: {\n    connector: \"mysql2\",\n    load: () => loadModule(\"db0/connectors/mysql2\"),\n  },\n  mysql2: {\n    connector: \"mysql2\",\n    load: () => loadModule(\"db0/connectors/mysql2\"),\n  },\n  pglite: {\n    connector: \"pglite\",\n    load: () => loadModule(\"db0/connectors/pglite\"),\n  },\n  planetscale: {\n    connector: \"planetscale\",\n    load: () => loadModule(\"db0/connectors/planetscale\"),\n  },\n  libsql: {\n    connector: \"libsql\",\n    load: () => loadModule(\"db0/connectors/libsql/node\"),\n  },\n  \"libsql-node\": {\n    connector: \"libsql-node\",\n    load: () => loadModule(\"db0/connectors/libsql/node\"),\n  },\n  \"libsql-http\": {\n    connector: \"libsql-http\",\n    load: () => loadModule(\"db0/connectors/libsql/http\"),\n  },\n};\n\nfunction createMemoryStorage(): Storage {\n  return createStorage({\n    driver: memoryDriver(),\n  });\n}\n\nconst GLOBAL_STORAGE_KEY = Symbol.for(\"farmjs.storage.global\");\n\nfunction readGlobalStorage(): Storage | undefined {\n  return (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY];\n}\n\nfunction writeGlobalStorage(storage: Storage): Storage {\n  (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY] = storage;\n  return storage;\n}\n\nfunction getActiveGlobalStorage(): Storage {\n  const existing = readGlobalStorage();\n  if (existing) {\n    return existing;\n  }\n  return writeGlobalStorage(createMemoryStorage());\n}\n\nlet globalStorage = getActiveGlobalStorage();\n\nfunction normalizeMountKey(base?: string): string {\n  return (base || \"\")\n    .trim()\n    .replace(/^[:/\\\\]+|[:/\\\\]+$/g, \"\")\n    .replace(/[\\\\/]+/g, \":\");\n}\n\nfunction isDriverInstance(value: unknown): value is Driver {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as Driver).getItem === \"function\" &&\n    typeof (value as Driver).getKeys === \"function\"\n  );\n}\n\nfunction isStorageInstance(value: unknown): value is Storage {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    typeof (value as Storage).mount === \"function\" &&\n    typeof (value as Storage).getMount === \"function\"\n  );\n}\n\nfunction isStorageClient(value: unknown): value is FarmStorageClient {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (value as FarmStorageClient).kind === \"farm-storage-client\" &&\n    typeof (value as FarmStorageClient).resolveDriver === \"function\" &&\n    typeof (value as FarmStorageClient).createStorage === \"function\"\n  );\n}\n\nfunction isDatabaseDriverName(name: string): name is FarmStorageDatabaseDriverName {\n  return name in DATABASE_CONNECTORS;\n}\n\nfunction extractDriverOptions(config: FarmStorageClientConfig): Record<string, any> | undefined {\n  const source = config as Record<string, any>;\n  const {\n    client: _client,\n    driver: _driver,\n    mounts: _mounts,\n    options,\n    tableName: _tableName,\n    ...inlineOptions\n  } = source;\n  const hasInlineOptions = Object.keys(inlineOptions).length > 0;\n\n  if (options && typeof options === \"object\" && !Array.isArray(options)) {\n    return hasInlineOptions ? { ...inlineOptions, ...options } : options;\n  }\n\n  if (hasInlineOptions) {\n    return inlineOptions;\n  }\n\n  return options;\n}\n\nasync function loadBuiltinDriver(\n  name: BuiltinDriverName,\n  options?: Record<string, any>,\n): Promise<Driver> {\n  const modulePath = builtinDrivers[name];\n\n  if (!modulePath) {\n    throw new Error(`Unsupported storage driver \"${name}\".`);\n  }\n\n  const module = (await loadModule(modulePath)) as DriverFactoryModule;\n  return module.default(options);\n}\n\nasync function loadDatabaseDriver(config: FarmStorageDatabaseConfig): Promise<Driver> {\n  const connectorEntry = DATABASE_CONNECTORS[config.driver as FarmStorageDatabaseDriverName];\n  const [{ createDatabase }, connectorModule, db0DriverModule] = await Promise.all([\n    loadModule<typeof import(\"db0\")>(\"db0\"),\n    connectorEntry.load(),\n    loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\"),\n  ]);\n\n  const database = createDatabase(connectorModule.default(extractDriverOptions(config) || {}));\n  const driver = db0DriverModule.default({\n    database,\n    tableName: config.tableName,\n  });\n\n  // The db0 driver has no dispose, so this connection is Farm's to close. Databases\n  // handed to `databaseStorage` stay owned by the caller and are left open.\n  return {\n    ...driver,\n    async dispose() {\n      await driver.dispose?.();\n      await database.dispose();\n    },\n  };\n}\n\nasync function resolveDriver(config?: FarmStorageMountConfig): Promise<Driver> {\n  if (config && isStorageClient(config)) {\n    return config.resolveDriver();\n  }\n\n  const driverInput = config?.driver ?? \"memory\";\n\n  if (typeof driverInput === \"function\") {\n    return await driverInput();\n  }\n\n  if (isDriverInstance(driverInput)) {\n    return driverInput;\n  }\n\n  if (isDatabaseDriverName(driverInput)) {\n    return loadDatabaseDriver(config as FarmStorageDatabaseConfig);\n  }\n\n  if (driverInput === \"local\") {\n    return loadBuiltinDriver(\"fs-lite\", extractDriverOptions(config as FarmStorageMountConfig));\n  }\n\n  return loadBuiltinDriver(\n    driverInput as BuiltinDriverName,\n    extractDriverOptions(config as FarmStorageClientConfig),\n  );\n}\n\nfunction createStorageClientFromResolver(resolveDriver: DriverResolver): FarmStorageClient {\n  let driverPromise: Promise<Driver> | undefined;\n  let storagePromise: Promise<Storage> | undefined;\n\n  const ensureDriver = () => {\n    if (driverPromise) return driverPromise;\n\n    const pending = Promise.resolve().then(resolveDriver);\n    driverPromise = pending;\n    void pending.catch(() => {\n      if (driverPromise === pending) {\n        driverPromise = undefined;\n        storagePromise = undefined;\n      }\n    });\n    return pending;\n  };\n\n  const ensureStorage = () => {\n    if (storagePromise) return storagePromise;\n\n    const pending = ensureDriver().then((driver) =>\n      createStorage({\n        driver,\n      }),\n    );\n    storagePromise = pending;\n    void pending.catch(() => {\n      if (storagePromise === pending) storagePromise = undefined;\n    });\n    return pending;\n  };\n\n  const target = {\n    kind: \"farm-storage-client\" as const,\n    ready: ensureStorage,\n    createStorage: ensureStorage,\n    resolveDriver: ensureDriver,\n  };\n\n  return new Proxy(target as FarmStorageClient, {\n    get(currentTarget, prop, receiver) {\n      if (prop === \"then\") {\n        return undefined;\n      }\n\n      if (Reflect.has(currentTarget, prop)) {\n        return Reflect.get(currentTarget, prop, receiver);\n      }\n\n      return (...args: any[]) =>\n        ensureStorage().then(async (storage) => {\n          const member = Reflect.get(storage as object, prop);\n\n          if (typeof member !== \"function\") {\n            return member;\n          }\n\n          const result = Reflect.apply(member, storage, args);\n\n          if (prop === \"dispose\") {\n            return Promise.resolve(result).finally(() => {\n              // Disposing the storage also disposed the driver, so drop both\n              // cached promises: a later call must re-run the driver factory\n              // instead of rebuilding storage over the dead driver.\n              storagePromise = undefined;\n              driverPromise = undefined;\n            });\n          }\n\n          return result;\n        });\n    },\n  });\n}\n\nexport function defineStorageClient(resolveDriver: DriverResolver): FarmStorageClient {\n  return createStorageClientFromResolver(resolveDriver);\n}\n\nexport function createStorageClient(config: FarmStorageClientConfig): FarmStorageClient {\n  return defineStorageClient(() => resolveDriver(config));\n}\n\nexport function driverStorage(\n  driver: Driver | (() => Driver | Promise<Driver>),\n): FarmStorageClient {\n  return defineStorageClient(() => (typeof driver === \"function\" ? driver() : driver));\n}\n\nexport function databaseStorage(\n  database: Database,\n  options: { tableName?: string } = {},\n): FarmStorageClient {\n  return defineStorageClient(async () => {\n    const db0DriverModule =\n      await loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\");\n    return db0DriverModule.default({\n      database,\n      tableName: options.tableName,\n    });\n  });\n}\n\nexport function memoryStorage(): FarmStorageClient {\n  return createStorageClient({ driver: \"memory\" });\n}\n\nexport function localStorage(options: Omit<FarmStorageLocalDriverConfig, \"driver\"> = {}) {\n  return createStorageClient({\n    driver: \"local\",\n    ...options,\n  });\n}\n\nexport function sqliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"sqlite\",\n    ...options,\n  });\n}\n\nexport function mysqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"mysql\",\n    ...options,\n  });\n}\n\nexport function mysql2Storage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return mysqlStorage(options);\n}\n\nexport function postgresStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"postgres\",\n    ...options,\n  });\n}\n\nexport function pgStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return postgresStorage(options);\n}\n\nexport function pgliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"pglite\",\n    ...options,\n  });\n}\n\nexport function planetscaleStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"planetscale\",\n    ...options,\n  });\n}\n\nexport function libsqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n  return createStorageClient({\n    driver: \"libsql\",\n    ...options,\n  });\n}\n\nexport function redisStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"redis\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"redis\",\n    ...options,\n  });\n}\n\nexport function s3Storage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"s3\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"s3\",\n    ...options,\n  });\n}\n\nexport function mongodbStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"mongodb\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"mongodb\",\n    ...options,\n  });\n}\n\nexport function upstashStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"upstash\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"upstash\",\n    ...options,\n  });\n}\n\nexport function netlifyBlobsStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"netlify-blobs\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"netlify-blobs\",\n    ...options,\n  });\n}\n\nexport function vercelKVStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-kv\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"vercel-kv\",\n    ...options,\n  });\n}\n\nexport function vercelBlobStorage(\n  options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-blob\" }>, \"driver\">,\n) {\n  return createStorageClient({\n    driver: \"vercel-blob\",\n    ...options,\n  });\n}\n\nasync function mountNamespaces(storage: Storage, mounts?: FarmStorageMounts): Promise<void> {\n  if (!mounts) {\n    return;\n  }\n\n  for (const [base, config] of Object.entries(mounts)) {\n    storage.mount(normalizeMountKey(base), await resolveDriver(config));\n  }\n}\n\nexport async function createFarmStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n  if (isStorageInstance(config)) {\n    return config;\n  }\n\n  if (isStorageClient(config)) {\n    return config.createStorage();\n  }\n\n  const rootConfig = isStorageClient(config.client) ? config.client : config;\n  const storage = createStorage({\n    driver: await resolveDriver(rootConfig),\n  });\n\n  try {\n    await mountNamespaces(storage, config.mounts);\n  } catch (error) {\n    await storage.dispose().catch(() => {});\n    throw error;\n  }\n  return storage;\n}\n\nexport async function resolveStorageRuntimeClient(\n  config: FarmStorageUserConfig | undefined,\n): Promise<unknown | undefined> {\n  if (!config || isStorageInstance(config) || isStorageClient(config)) {\n    return undefined;\n  }\n\n  const client = config.client;\n  if (!client || isStorageInstance(client) || isStorageClient(client)) {\n    return undefined;\n  }\n\n  return typeof client === \"function\" ? await client() : client;\n}\n\nexport async function initStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n  globalStorage = getActiveGlobalStorage();\n  const nextStorage = await createFarmStorage(config);\n  const previousStorage = globalStorage;\n  globalStorage = writeGlobalStorage(nextStorage);\n\n  if (previousStorage !== nextStorage) {\n    await previousStorage.dispose().catch(() => {});\n  }\n\n  return globalStorage;\n}\n\nexport function getStorage(namespace?: string): Storage {\n  globalStorage = getActiveGlobalStorage();\n  const base = normalizeMountKey(namespace);\n  if (!base) {\n    return globalStorage;\n  }\n\n  const namespaced = prefixStorage(globalStorage, base);\n  // 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","import {\n  context,\n  createContextKey,\n  isSpanContextValid,\n  propagation,\n  SpanKind,\n  SpanStatusCode,\n  trace,\n  type Attributes,\n  type Context,\n  type Span,\n} from \"@opentelemetry/api\";\nimport type { FarmEvent } from \"./observability\";\n\nexport const FARM_TRACER_NAME = \"@farm.js/core\";\n\nexport type FarmTraceSpanKind =\n  | \"request\"\n  | \"render\"\n  | \"middleware\"\n  | \"api\"\n  | \"integration\"\n  | \"storage\"\n  | \"ppr\"\n  | \"build\"\n  | \"plugin\";\n\nexport interface FarmTracingConfig {\n  /** Enable Farm's OpenTelemetry spans. */\n  enabled?: boolean;\n  /** Span families to record. All families are enabled by default. */\n  spans?: readonly FarmTraceSpanKind[];\n  /** Add Farm lifecycle events to the active span. Defaults to true. */\n  recordEvents?: boolean;\n  /** Static attributes added to every Farm-created span. */\n  attributes?: Attributes;\n  /** Path prefixes that should not create request spans. */\n  ignorePaths?: readonly string[];\n}\n\nexport type FarmTracingUserConfig = boolean | FarmTracingConfig;\n\nexport interface FarmResolvedTracingConfig {\n  enabled: boolean;\n  spans: ReadonlySet<FarmTraceSpanKind>;\n  recordEvents: boolean;\n  attributes: Attributes;\n  ignorePaths: readonly string[];\n}\n\nexport interface FarmTraceContext {\n  traceId: string;\n  spanId: string;\n  traceSampled: boolean;\n}\n\nexport interface FarmRequestSpanOptions {\n  getStatusCode?: () => number | undefined;\n  onStart?: () => void;\n  onComplete?: (status: number, durationMs: number) => void;\n  onError?: (error: unknown, durationMs: number) => void;\n}\n\nexport interface FarmSpanOptions {\n  kind?: FarmTraceSpanKind;\n  attributes?: Attributes;\n  spanKind?: SpanKind;\n}\n\nconst ALL_SPAN_KINDS: readonly FarmTraceSpanKind[] = [\n  \"request\",\n  \"render\",\n  \"middleware\",\n  \"api\",\n  \"integration\",\n  \"storage\",\n  \"ppr\",\n  \"build\",\n  \"plugin\",\n];\n\nconst DEFAULT_IGNORED_PATHS = [\n  \"/@vite/\",\n  \"/@fs/\",\n  \"/@id/\",\n  \"/@react-refresh\",\n  \"/node_modules/\",\n  \"/__vite\",\n  \"/.well-known/appspecific/\",\n];\nconst FARM_REQUEST_METHOD_CONTEXT_KEY = createContextKey(\"@farm.js/core/request-method\");\n\nlet tracingState: FarmResolvedTracingConfig = normalizeFarmTracingConfig(false);\n\nexport function normalizeFarmTracingConfig(\n  config: FarmTracingUserConfig | undefined,\n): FarmResolvedTracingConfig {\n  if (!config) {\n    return {\n      enabled: false,\n      spans: new Set(ALL_SPAN_KINDS),\n      recordEvents: true,\n      attributes: {},\n      ignorePaths: DEFAULT_IGNORED_PATHS,\n    };\n  }\n\n  if (config === true) {\n    return {\n      enabled: true,\n      spans: new Set(ALL_SPAN_KINDS),\n      recordEvents: true,\n      attributes: {},\n      ignorePaths: DEFAULT_IGNORED_PATHS,\n    };\n  }\n\n  return {\n    enabled: config.enabled ?? true,\n    spans: new Set(config.spans ?? ALL_SPAN_KINDS),\n    recordEvents: config.recordEvents ?? true,\n    attributes: { ...config.attributes },\n    ignorePaths: [...DEFAULT_IGNORED_PATHS, ...(config.ignorePaths ?? [])],\n  };\n}\n\nexport function configureFarmTracing(\n  config: FarmTracingUserConfig | FarmResolvedTracingConfig | undefined,\n): void {\n  if (isResolvedFarmTracingConfig(config)) {\n    tracingState = {\n      ...config,\n      spans: new Set(config.spans),\n      attributes: { ...config.attributes },\n      ignorePaths: [...config.ignorePaths],\n    };\n    return;\n  }\n  tracingState = normalizeFarmTracingConfig(config as FarmTracingUserConfig | undefined);\n}\n\nfunction isResolvedFarmTracingConfig(\n  config: FarmTracingUserConfig | FarmResolvedTracingConfig | undefined,\n): config is FarmResolvedTracingConfig {\n  return (\n    !!config &&\n    typeof config === \"object\" &&\n    typeof config.enabled === \"boolean\" &&\n    config.spans instanceof Set &&\n    typeof config.recordEvents === \"boolean\" &&\n    Array.isArray(config.ignorePaths)\n  );\n}\n\nexport function getFarmTracingConfig(): FarmResolvedTracingConfig {\n  return tracingState;\n}\n\nexport function resetFarmTracing(): void {\n  tracingState = normalizeFarmTracingConfig(false);\n}\n\nexport function getFarmTraceContext(): FarmTraceContext | undefined {\n  return getSpanTraceContext(trace.getSpan(context.active()));\n}\n\nexport async function runWithFarmSpan<T>(\n  name: string,\n  handler: () => T | Promise<T>,\n  options: FarmSpanOptions = {},\n): Promise<T> {\n  const spanFamily = options.kind;\n  if (!tracingState.enabled || (spanFamily !== undefined && !tracingState.spans.has(spanFamily))) {\n    return await handler();\n  }\n\n  const tracer = trace.getTracer(FARM_TRACER_NAME);\n  return await tracer.startActiveSpan(\n    name,\n    {\n      kind: options.spanKind ?? SpanKind.INTERNAL,\n      attributes: {\n        ...tracingState.attributes,\n        ...options.attributes,\n      },\n    },\n    async (span) => {\n      try {\n        return await handler();\n      } catch (error) {\n        recordSpanError(span, error);\n        throw error;\n      } finally {\n        span.end();\n      }\n    },\n  );\n}\n\nexport async function _runWithFarmRequestSpan<T>(\n  request: Request,\n  handler: () => T | Promise<T>,\n  options: FarmRequestSpanOptions = {},\n): Promise<T> {\n  const startedAt = Date.now();\n  const url = new URL(request.url);\n  const shouldTrace =\n    tracingState.enabled &&\n    tracingState.spans.has(\"request\") &&\n    !tracingState.ignorePaths.some((prefix) => url.pathname.startsWith(prefix));\n\n  if (!shouldTrace) {\n    options.onStart?.();\n    try {\n      const result = await handler();\n      options.onComplete?.(resolveResultStatus(result, options), Date.now() - startedAt);\n      return result;\n    } catch (error) {\n      options.onError?.(error, Date.now() - startedAt);\n      throw error;\n    }\n  }\n\n  const extractedContext = propagation.extract(context.active(), request.headers, {\n    keys(carrier) {\n      return Array.from(carrier.keys());\n    },\n    get(carrier, key) {\n      return carrier.get(key) ?? undefined;\n    },\n  });\n  const requestContext = extractedContext.setValue(FARM_REQUEST_METHOD_CONTEXT_KEY, request.method);\n  const tracer = trace.getTracer(FARM_TRACER_NAME);\n  const attributes: Attributes = {\n    ...tracingState.attributes,\n    \"http.request.method\": request.method,\n    \"url.path\": url.pathname,\n    \"url.scheme\": url.protocol.replace(/:$/, \"\"),\n    \"server.address\": url.hostname,\n  };\n  if (url.port) attributes[\"server.port\"] = Number(url.port);\n\n  return await tracer.startActiveSpan(\n    `${request.method} ${url.pathname}`,\n    { kind: SpanKind.SERVER, attributes },\n    requestContext,\n    async (span) => {\n      options.onStart?.();\n      try {\n        const result = await handler();\n        const status = resolveResultStatus(result, options);\n        setResponseStatus(span, status);\n        options.onComplete?.(status, Date.now() - startedAt);\n        return result;\n      } catch (error) {\n        recordSpanError(span, error);\n        options.onError?.(error, Date.now() - startedAt);\n        throw error;\n      } finally {\n        span.end();\n      }\n    },\n  );\n}\n\nexport function recordFarmEventTrace(event: FarmEvent): FarmTraceContext | undefined {\n  if (!tracingState.enabled) return undefined;\n\n  const activeContext = context.active();\n  const activeSpan = trace.getSpan(activeContext);\n  const traceContext = getSpanTraceContext(activeSpan);\n  if (activeSpan && traceContext) {\n    if (event.type === \"route.matched\") {\n      const method =\n        (activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) as string | undefined) ?? \"HTTP\";\n      activeSpan.updateName(`${method} ${event.route}`);\n      activeSpan.setAttribute(\"http.route\", event.route);\n      activeSpan.setAttribute(\"farm.route\", event.route);\n    }\n\n    if (tracingState.recordEvents) {\n      activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);\n    }\n\n    const error = event.type === \"request.error\" ? undefined : getEventError(event);\n    if (error !== undefined) {\n      // A recoverable render error (caught by an error boundary) still fires\n      // React's onError while the request returns a valid response, so record\n      // the exception for visibility but let the actual response status\n      // (setResponseStatus) decide the span status instead of forcing the whole\n      // request trace to ERROR. A genuinely fatal render error surfaces through\n      // the request outcome (a thrown handler or a >= 500 status) and is marked\n      // there.\n      if (event.type === \"render.error\") {\n        recordSpanException(activeSpan, error);\n      } else {\n        recordSpanError(activeSpan, error);\n      }\n    }\n  }\n\n  const completedTraceContext = recordCompletedEventSpan(event, activeContext);\n  return traceContext ?? completedTraceContext;\n}\n\nfunction recordCompletedEventSpan(\n  event: FarmEvent,\n  parentContext: Context,\n): FarmTraceContext | undefined {\n  const descriptor = getCompletedSpanDescriptor(event);\n  if (!descriptor || !tracingState.spans.has(descriptor.kind)) return undefined;\n\n  const tracer = trace.getTracer(FARM_TRACER_NAME);\n  const span = tracer.startSpan(\n    descriptor.name,\n    {\n      kind: SpanKind.INTERNAL,\n      startTime: event.timestamp - descriptor.durationMs,\n      attributes: {\n        ...tracingState.attributes,\n        ...toEventAttributes(event),\n        \"farm.event.type\": event.type,\n      },\n    },\n    parentContext,\n  );\n\n  const status = \"status\" in event && typeof event.status === \"number\" ? event.status : undefined;\n  if (status !== undefined) setResponseStatus(span, status);\n  const error = getEventError(event);\n  if (error !== undefined) recordSpanError(span, error);\n  const traceContext = getSpanTraceContext(span);\n  span.end(event.timestamp);\n  return traceContext;\n}\n\nfunction getCompletedSpanDescriptor(\n  event: FarmEvent,\n): { kind: FarmTraceSpanKind; name: string; durationMs: number } | undefined {\n  if (!(\"durationMs\" in event) || typeof event.durationMs !== \"number\") return undefined;\n\n  switch (event.type) {\n    case \"render.complete\":\n      return { kind: \"render\", name: `farm.render ${event.route}`, durationMs: event.durationMs };\n    case \"render.stream.shellReady\":\n      return {\n        kind: \"render\",\n        name: `farm.render.shell ${event.route}`,\n        durationMs: event.durationMs,\n      };\n    case \"render.stream.complete\":\n      return {\n        kind: \"render\",\n        name: `farm.render.stream ${event.route}`,\n        durationMs: event.durationMs,\n      };\n    case \"middleware.complete\":\n      return {\n        kind: \"middleware\",\n        name: `farm.middleware ${event.name ?? event.route ?? \"anonymous\"}`,\n        durationMs: event.durationMs,\n      };\n    case \"api.request.complete\":\n    case \"api.error\":\n      return {\n        kind: \"api\",\n        name: `farm.api ${event.method} ${event.route}`,\n        durationMs: event.durationMs,\n      };\n    case \"integration.api.call.complete\":\n      return {\n        kind: \"integration\",\n        name: `farm.integration ${event.integration}.${event.operation}`,\n        durationMs: event.durationMs,\n      };\n    case \"storage.query.complete\":\n      return {\n        kind: \"storage\",\n        name: `farm.storage ${event.operation}`,\n        durationMs: event.durationMs,\n      };\n    case \"ppr.refresh.complete\":\n      return {\n        kind: \"ppr\",\n        name: `farm.ppr.refresh ${event.route}`,\n        durationMs: event.durationMs,\n      };\n    case \"build.complete\":\n      return {\n        kind: \"build\",\n        name: `farm.build${event.target ? ` ${event.target}` : \"\"}`,\n        durationMs: event.durationMs,\n      };\n    case \"plugin.hook.complete\":\n      return {\n        kind: \"plugin\",\n        name: `farm.plugin ${event.plugin}.${event.hook}`,\n        durationMs: event.durationMs,\n      };\n    default:\n      return undefined;\n  }\n}\n\n// A runtime-agnostic, non-cryptographic digest (FNV-1a). This module is bundled\n// into browser and edge runtimes, so it must not import node:crypto; the digest\n// only needs to redact the raw cache key while keeping cache events correlatable,\n// which does not require a cryptographic hash.\nfunction hashFarmCacheKey(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index++) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction toEventAttributes(event: FarmEvent): Attributes {\n  const attributes: Attributes = {};\n  // A cache event's `key` embeds the serialized arguments of the cached call\n  // (e.g. `unstable_cache(getUser)(email)` serializes the email into the key),\n  // so it must never be exported verbatim to a tracing backend. Emit a stable\n  // digest under `farm.key_hash` instead, preserving cross-event correlation\n  // without shipping the sensitive payload.\n  const redactKey = typeof event.type === \"string\" && event.type.startsWith(\"cache.\");\n  for (const [key, value] of Object.entries(event)) {\n    if (\n      key === \"timestamp\" ||\n      key === \"level\" ||\n      key === \"error\" ||\n      key === \"traceId\" ||\n      key === \"spanId\" ||\n      key === \"traceSampled\" ||\n      value === undefined\n    ) {\n      continue;\n    }\n    if (redactKey && key === \"key\" && typeof value === \"string\") {\n      attributes[\"farm.key_hash\"] = hashFarmCacheKey(value);\n      continue;\n    }\n    if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n      attributes[`farm.${key}`] = value;\n    } else if (Array.isArray(value)) {\n      if (value.every((entry) => typeof entry === \"string\")) {\n        attributes[`farm.${key}`] = value as string[];\n      } else if (value.every((entry) => typeof entry === \"number\")) {\n        attributes[`farm.${key}`] = value as number[];\n      } else if (value.every((entry) => typeof entry === \"boolean\")) {\n        attributes[`farm.${key}`] = value as boolean[];\n      }\n    }\n  }\n  return attributes;\n}\n\nfunction getEventError(event: FarmEvent): unknown {\n  return \"error\" in event ? event.error : undefined;\n}\n\nfunction recordSpanException(span: Span, error: unknown): Error {\n  const normalized = error instanceof Error ? error : new Error(String(error));\n  span.recordException(normalized);\n  return normalized;\n}\n\nfunction recordSpanError(span: Span, error: unknown): void {\n  const normalized = recordSpanException(span, error);\n  span.setStatus({ code: SpanStatusCode.ERROR, message: normalized.message });\n}\n\nfunction setResponseStatus(span: Span, status: number): void {\n  span.setAttribute(\"http.response.status_code\", status);\n  if (status >= 500) {\n    span.setStatus({ code: SpanStatusCode.ERROR });\n  }\n}\n\nfunction resolveResultStatus<T>(result: T, options: FarmRequestSpanOptions): number {\n  if (result instanceof Response) return result.status;\n  return options.getStatusCode?.() ?? 200;\n}\n\nfunction getSpanTraceContext(span: Span | undefined): FarmTraceContext | undefined {\n  if (!span) return undefined;\n  const spanContext = span.spanContext();\n  if (!isSpanContextValid(spanContext)) return undefined;\n  return {\n    traceId: spanContext.traceId,\n    spanId: spanContext.spanId,\n    traceSampled: (spanContext.traceFlags & 0x01) === 0x01,\n  };\n}\n","import {\n  _runWithFarmRequestSpan,\n  configureFarmTracing,\n  getFarmTraceContext,\n  normalizeFarmTracingConfig,\n  recordFarmEventTrace,\n  resetFarmTracing,\n  runWithFarmSpan,\n  type FarmRequestSpanOptions,\n  type FarmResolvedTracingConfig,\n  type FarmSpanOptions,\n  type FarmTraceContext,\n  type FarmTraceSpanKind,\n  type FarmTracingConfig,\n  type FarmTracingUserConfig,\n} from \"./tracing\";\n\nexport type FarmEventLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface FarmEventBase {\n  type: string;\n  timestamp: number;\n  level: FarmEventLevel;\n  requestId?: string;\n  traceId?: string;\n  spanId?: string;\n  traceSampled?: boolean;\n  route?: string;\n  pathname?: string;\n}\n\nexport type FarmRequestEvent =\n  | (FarmEventBase & { type: \"request.start\"; method: string; pathname: string })\n  | (FarmEventBase & {\n      type: \"request.complete\";\n      method: string;\n      pathname: string;\n      status: number;\n      durationMs: number;\n    })\n  | (FarmEventBase & {\n      type: \"request.error\";\n      method: string;\n      pathname: string;\n      durationMs: number;\n      error: unknown;\n    });\n\nexport type FarmServerEvent =\n  | (FarmEventBase & {\n      type: \"server.start\";\n      mode: \"dev\" | \"preview\" | \"production\";\n      port?: number;\n    })\n  | (FarmEventBase & { type: \"server.ready\"; url?: string })\n  | (FarmEventBase & { type: \"server.shutdown\"; reason?: string });\n\nexport type FarmRouteEvent =\n  | (FarmEventBase & { type: \"route.discovered\"; route: string; filePath: string })\n  | (FarmEventBase & {\n      type: \"route.matched\";\n      pathname: string;\n      route: string;\n      params?: Record<string, string>;\n    })\n  | (FarmEventBase & { type: \"route.notFound\"; pathname: string })\n  | (FarmEventBase & { type: \"route.redirect\"; from: string; to: string; status?: number })\n  | (FarmEventBase & { type: \"route.rewrite\"; from: string; to: string });\n\nexport type FarmRenderEvent =\n  | (FarmEventBase & { type: \"render.start\"; route: string; pathname?: string })\n  | (FarmEventBase & {\n      type: \"render.complete\";\n      route: string;\n      durationMs: number;\n      status?: number;\n    })\n  | (FarmEventBase & { type: \"render.error\"; route?: string; error: unknown })\n  | (FarmEventBase & { type: \"render.stream.start\"; route: string })\n  | (FarmEventBase & { type: \"render.stream.shellReady\"; route: string; durationMs: number })\n  | (FarmEventBase & { type: \"render.stream.complete\"; route: string; durationMs: number });\n\nexport type FarmCacheEvent =\n  | (FarmEventBase & {\n      type: \"cache.hit\";\n      key: string;\n      route?: string;\n      tags?: readonly string[];\n      revalidate?: number | false;\n      stale?: boolean;\n    })\n  | (FarmEventBase & { type: \"cache.miss\"; key: string; route?: string; reason?: string })\n  | (FarmEventBase & {\n      type: \"cache.set\";\n      key: string;\n      route?: string;\n      tags?: readonly string[];\n      revalidate?: number | false;\n    })\n  | (FarmEventBase & { type: \"cache.dedupe\"; key: string })\n  | (FarmEventBase & { type: \"cache.bypass\"; key?: string; route?: string; reason: string })\n  | (FarmEventBase & {\n      type: \"cache.stale\";\n      key: string;\n      route?: string;\n      tags?: readonly string[];\n      revalidate?: number | false;\n    })\n  | (FarmEventBase & { type: \"cache.revalidatePath\"; path: string; count: number })\n  | (FarmEventBase & {\n      type: \"cache.revalidateTag\";\n      tag: string;\n      profile?: unknown;\n      count: number;\n    })\n  | (FarmEventBase & { type: \"cache.updateTag\"; tag: string; count: number })\n  | (FarmEventBase & {\n      type: \"cache.invalidated\";\n      key?: string;\n      route?: string;\n      tag?: string;\n      reason?: string;\n      count?: number;\n    })\n  | (FarmEventBase & { type: \"cache.delete\"; key: string; deleted: boolean })\n  | (FarmEventBase & { type: \"cache.clear\"; count: number })\n  | (FarmEventBase & {\n      type: \"cache.error\";\n      key?: string;\n      operation: \"get\" | \"set\" | \"delete\" | \"revalidate\";\n      error: unknown;\n    });\n\nexport type FarmPPREvent =\n  | (FarmEventBase & { type: \"ppr.shell.hit\"; route: string; key: string })\n  | (FarmEventBase & { type: \"ppr.shell.miss\"; route: string; key: string })\n  | (FarmEventBase & {\n      type: \"ppr.shell.cached\";\n      route: string;\n      key: string;\n      revalidate?: number;\n    })\n  | (FarmEventBase & { type: \"ppr.shell.bypass\"; route: string; reason: string })\n  | (FarmEventBase & {\n      type: \"ppr.shell.invalidated\";\n      route: string;\n      reason?: string;\n      count?: number;\n    })\n  | (FarmEventBase & { type: \"ppr.suspense.holeDetected\"; route: string })\n  | (FarmEventBase & { type: \"ppr.refresh.start\"; route: string })\n  | (FarmEventBase & { type: \"ppr.refresh.complete\"; route: string; durationMs: number })\n  | (FarmEventBase & { type: \"ppr.refresh.error\"; route: string; error: unknown });\n\nexport type FarmAPIEvent =\n  | (FarmEventBase & { type: \"api.request.start\"; route: string; method: string })\n  | (FarmEventBase & {\n      type: \"api.request.complete\";\n      route: string;\n      method: string;\n      status: number;\n      durationMs: number;\n    })\n  | (FarmEventBase & {\n      type: \"api.validation.failed\";\n      route: string;\n      method: string;\n      issues?: unknown;\n    })\n  | (FarmEventBase & {\n      type: \"api.error\";\n      route: string;\n      method: string;\n      durationMs: number;\n      error: unknown;\n    });\n\nexport type FarmIntegrationEvent =\n  | (FarmEventBase & { type: \"integration.registered\"; name: string })\n  | (FarmEventBase & { type: \"integration.config.validated\"; name: string })\n  | (FarmEventBase & { type: \"integration.ready\"; name: string })\n  | (FarmEventBase & { type: \"integration.disposed\"; name: string })\n  | (FarmEventBase & {\n      type: \"integration.api.call.start\";\n      integration: string;\n      operation: string;\n    })\n  | (FarmEventBase & {\n      type: \"integration.api.call.complete\";\n      integration: string;\n      operation: string;\n      durationMs: number;\n    })\n  | (FarmEventBase & {\n      type: \"integration.api.call.error\";\n      integration: string;\n      operation: string;\n      error: unknown;\n    })\n  | (FarmEventBase & { type: \"integration.webhook.received\"; integration: string; event?: string })\n  | (FarmEventBase & { type: \"integration.webhook.verified\"; integration: string; event?: string })\n  | (FarmEventBase & { type: \"integration.webhook.failed\"; integration: string; reason: string });\n\nexport type FarmMiddlewareEvent =\n  | (FarmEventBase & { type: \"middleware.start\"; route?: string; name?: string })\n  | (FarmEventBase & {\n      type: \"middleware.complete\";\n      route?: string;\n      name?: string;\n      durationMs: number;\n    })\n  | (FarmEventBase & {\n      type: \"middleware.shortCircuit\";\n      route?: string;\n      name?: string;\n      status?: number;\n    })\n  | (FarmEventBase & { type: \"middleware.error\"; route?: string; name?: string; error: unknown });\n\nexport type FarmStorageEvent =\n  | (FarmEventBase & { type: \"storage.query.start\"; integration?: string; operation: string })\n  | (FarmEventBase & {\n      type: \"storage.query.complete\";\n      integration?: string;\n      operation: string;\n      durationMs: number;\n    })\n  | (FarmEventBase & {\n      type: \"storage.query.error\";\n      integration?: string;\n      operation: string;\n      error: unknown;\n    })\n  | (FarmEventBase & { type: \"storage.schema.ready\"; integration?: string })\n  | (FarmEventBase & { type: \"storage.schema.error\"; integration?: string; error: unknown });\n\nexport type FarmBuildEvent =\n  | (FarmEventBase & { type: \"build.start\"; target?: string })\n  | (FarmEventBase & { type: \"build.complete\"; target?: string; durationMs: number })\n  | (FarmEventBase & { type: \"build.error\"; target?: string; error: unknown })\n  | (FarmEventBase & { type: \"routes.generated\"; pageCount: number; apiCount?: number })\n  | (FarmEventBase & { type: \"types.generated\"; filePath: string })\n  | (FarmEventBase & { type: \"manifest.generated\"; routeCount: number });\n\nexport type FarmPluginEvent =\n  | (FarmEventBase & { type: \"plugin.hook.start\"; plugin: string; hook: string })\n  | (FarmEventBase & {\n      type: \"plugin.hook.complete\";\n      plugin: string;\n      hook: string;\n      durationMs: number;\n    })\n  | (FarmEventBase & { type: \"plugin.hook.error\"; plugin: string; hook: string; error: unknown });\n\nexport type FarmErrorEvent = FarmEventBase & {\n  type: \"error\";\n  source: string;\n  error: unknown;\n  route?: string;\n};\n\nexport type FarmEvent =\n  | FarmRequestEvent\n  | FarmServerEvent\n  | FarmRouteEvent\n  | FarmRenderEvent\n  | FarmCacheEvent\n  | FarmPPREvent\n  | FarmAPIEvent\n  | FarmIntegrationEvent\n  | FarmMiddlewareEvent\n  | FarmStorageEvent\n  | FarmBuildEvent\n  | FarmPluginEvent\n  | FarmErrorEvent;\n\nexport type FarmEventType = FarmEvent[\"type\"];\nexport type FarmEventHandler = (event: FarmEvent) => void | Promise<void>;\n\nexport type FarmEventInput = FarmEvent extends infer T\n  ? T extends FarmEvent\n    ? Omit<T, \"timestamp\" | \"level\"> & Partial<Pick<T, \"timestamp\" | \"level\">>\n    : never\n  : never;\n\nexport type FarmObservabilityUserConfig =\n  | boolean\n  | {\n      logs?: boolean;\n      onEvent?: FarmEventHandler | readonly FarmEventHandler[];\n      events?: readonly FarmEventType[];\n      tracing?: FarmTracingUserConfig;\n    };\n\nexport interface FarmResolvedObservabilityConfig {\n  logs: boolean;\n  handlers: FarmEventHandler[];\n  events?: Set<FarmEventType>;\n  tracing: FarmResolvedTracingConfig;\n}\n\nexport interface FarmEventSubscriptionOptions {\n  /** Receive events even when they are excluded by `observability.events`. */\n  unfiltered?: boolean;\n}\n\nconst runtimeHandlers = new Set<FarmEventHandler>();\nconst unfilteredRuntimeHandlers = new Set<FarmEventHandler>();\nlet observabilityState: FarmResolvedObservabilityConfig = {\n  logs: false,\n  handlers: [],\n  tracing: normalizeFarmTracingConfig(false),\n};\n\nexport function configureFarmObservability(config: FarmObservabilityUserConfig | undefined): void {\n  observabilityState = normalizeFarmObservabilityConfig(config);\n  configureFarmTracing(observabilityState.tracing);\n}\n\nexport function normalizeFarmObservabilityConfig(\n  config: FarmObservabilityUserConfig | undefined,\n): FarmResolvedObservabilityConfig {\n  if (config === undefined || config === false) {\n    return { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) };\n  }\n\n  if (config === true) {\n    return { logs: true, handlers: [], tracing: normalizeFarmTracingConfig(false) };\n  }\n\n  const handlers = config.onEvent\n    ? Array.isArray(config.onEvent)\n      ? [...config.onEvent]\n      : [config.onEvent]\n    : [];\n\n  return {\n    logs: config.logs ?? false,\n    handlers,\n    events: config.events ? new Set(config.events) : undefined,\n    tracing: normalizeFarmTracingConfig(config.tracing),\n  };\n}\n\nexport function onFarmEvent(\n  handler: FarmEventHandler,\n  options: FarmEventSubscriptionOptions = {},\n): () => void {\n  const handlers = options.unfiltered ? unfilteredRuntimeHandlers : runtimeHandlers;\n  handlers.add(handler);\n  return () => {\n    handlers.delete(handler);\n  };\n}\n\nexport function resetFarmObservability(): void {\n  runtimeHandlers.clear();\n  unfilteredRuntimeHandlers.clear();\n  observabilityState = {\n    logs: false,\n    handlers: [],\n    tracing: normalizeFarmTracingConfig(false),\n  };\n  resetFarmTracing();\n}\n\nexport function emitFarmEvent(input: FarmEventInput): FarmEvent {\n  const event = {\n    timestamp: Date.now(),\n    level: inferFarmEventLevel(input.type),\n    ...input,\n  } as FarmEvent;\n\n  const traceContext = recordFarmEventTrace(event);\n  if (traceContext) {\n    event.traceId = traceContext.traceId;\n    event.spanId = traceContext.spanId;\n    event.traceSampled = traceContext.traceSampled;\n  }\n\n  notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);\n\n  if (!shouldEmitFarmEvent(event)) return event;\n\n  if (observabilityState.logs) {\n    logFarmEvent(event);\n  }\n\n  notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);\n\n  return event;\n}\n\nfunction notifyFarmEventHandlers(event: FarmEvent, handlers: Iterable<FarmEventHandler>): void {\n  for (const handler of handlers) {\n    try {\n      Promise.resolve(handler(event)).catch((error) => {\n        console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);\n      });\n    } catch (error) {\n      console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);\n    }\n  }\n}\n\nexport async function runWithFarmRequestSpan<T>(\n  request: Request,\n  handler: () => T | Promise<T>,\n  options: FarmRequestSpanOptions = {},\n): Promise<T> {\n  const url = new URL(request.url);\n  const method = request.method || \"GET\";\n  return await _runWithFarmRequestSpan(request, handler, {\n    ...options,\n    onStart() {\n      emitFarmEvent({ type: \"request.start\", method, pathname: url.pathname });\n      options.onStart?.();\n    },\n    onComplete(status, durationMs) {\n      emitFarmEvent({\n        type: \"request.complete\",\n        method,\n        pathname: url.pathname,\n        status,\n        durationMs,\n      });\n      options.onComplete?.(status, durationMs);\n    },\n    onError(error, durationMs) {\n      emitFarmEvent({\n        type: \"request.error\",\n        method,\n        pathname: url.pathname,\n        durationMs,\n        error,\n      });\n      options.onError?.(error, durationMs);\n    },\n  });\n}\n\nexport { configureFarmTracing, getFarmTraceContext, normalizeFarmTracingConfig, runWithFarmSpan };\nexport type {\n  FarmRequestSpanOptions,\n  FarmResolvedTracingConfig,\n  FarmSpanOptions,\n  FarmTraceContext,\n  FarmTraceSpanKind,\n  FarmTracingConfig,\n  FarmTracingUserConfig,\n};\n\nfunction shouldEmitFarmEvent(event: FarmEvent): boolean {\n  if (\n    !observabilityState.logs &&\n    observabilityState.handlers.length === 0 &&\n    runtimeHandlers.size === 0\n  ) {\n    return false;\n  }\n\n  if (observabilityState.events && !observabilityState.events.has(event.type)) {\n    return false;\n  }\n\n  return true;\n}\n\nfunction inferFarmEventLevel(type: FarmEventType): FarmEventLevel {\n  if (type === \"error\" || type.endsWith(\".error\") || type.endsWith(\".failed\")) {\n    return \"error\";\n  }\n  if (\n    type.endsWith(\".bypass\") ||\n    type.endsWith(\".invalidated\") ||\n    type.endsWith(\".stale\") ||\n    type.endsWith(\".notFound\")\n  ) {\n    return \"warn\";\n  }\n  if (\n    type.endsWith(\".hit\") ||\n    type.endsWith(\".miss\") ||\n    type.endsWith(\".start\") ||\n    type.endsWith(\".shellReady\")\n  ) {\n    return \"debug\";\n  }\n  return \"info\";\n}\n\nfunction logFarmEvent(event: FarmEvent): void {\n  const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;\n  switch (event.level) {\n    case \"error\":\n      console.error(message);\n      break;\n    case \"warn\":\n      console.warn(message);\n      break;\n    default:\n      console.log(message);\n      break;\n  }\n}\n\nfunction formatFarmEventDetails(event: FarmEvent): string {\n  const details: string[] = [];\n  const record = event as unknown as Record<string, unknown>;\n\n  for (const key of [\n    \"route\",\n    \"pathname\",\n    \"method\",\n    \"status\",\n    \"key\",\n    \"tag\",\n    \"path\",\n    \"reason\",\n    \"durationMs\",\n    \"integration\",\n    \"operation\",\n    \"plugin\",\n    \"hook\",\n    \"target\",\n    \"count\",\n  ]) {\n    const value = record[key];\n    if (value !== undefined) {\n      details.push(`${key}=${formatDetailValue(value)}`);\n    }\n  }\n\n  return details.length > 0 ? ` ${details.join(\" \")}` : \"\";\n}\n\nfunction formatDetailValue(value: unknown): string {\n  if (typeof value === \"string\") {\n    return value;\n  }\n  if (typeof value === \"number\" || typeof value === \"boolean\") {\n    return String(value);\n  }\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n\nfunction formatError(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n","export type FarmRedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nexport interface FarmRedirectSignal {\n  url: string;\n  status: FarmRedirectStatus;\n}\n\nconst REDIRECT_ERROR_CODE = \"FARM_REDIRECT\";\nconst NOT_FOUND_ERROR_CODE = \"FARM_NOT_FOUND\";\nconst REDIRECT_ERROR_SYMBOL = Symbol.for(\"farm.navigation.redirect\");\nconst NOT_FOUND_ERROR_SYMBOL = Symbol.for(\"farm.navigation.notFound\");\n\ntype FarmNavigationError = Error & {\n  digest: string;\n  [REDIRECT_ERROR_SYMBOL]?: FarmRedirectSignal;\n  [NOT_FOUND_ERROR_SYMBOL]?: true;\n};\n\nexport function redirect(url: string, status: FarmRedirectStatus = 307): never {\n  throw createRedirectError(url, status);\n}\n\nexport function permanentRedirect(url: string): never {\n  redirect(url, 308);\n}\n\nexport function notFound(): never {\n  const error = new Error(NOT_FOUND_ERROR_CODE) as FarmNavigationError;\n  error.digest = NOT_FOUND_ERROR_CODE;\n  error[NOT_FOUND_ERROR_SYMBOL] = true;\n  throw error;\n}\n\nexport function isFarmRedirectError(error: unknown): boolean {\n  return Boolean(getFarmRedirectError(error));\n}\n\nexport function getFarmRedirectError(error: unknown): FarmRedirectSignal | null {\n  if (!error || typeof error !== \"object\") return null;\n  const candidate = error as Partial<FarmNavigationError>;\n  if (candidate[REDIRECT_ERROR_SYMBOL]) {\n    return candidate[REDIRECT_ERROR_SYMBOL] as FarmRedirectSignal;\n  }\n\n  if (\n    typeof candidate.digest === \"string\" &&\n    candidate.digest.startsWith(`${REDIRECT_ERROR_CODE};`)\n  ) {\n    const [, status, ...urlParts] = candidate.digest.split(\";\");\n    const parsedStatus = Number(status);\n    if (isFarmRedirectStatus(parsedStatus)) {\n      return {\n        status: parsedStatus,\n        url: urlParts.join(\";\"),\n      };\n    }\n  }\n\n  return null;\n}\n\nexport function isFarmNotFoundError(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n  const candidate = error as Partial<FarmNavigationError>;\n  return Boolean(candidate[NOT_FOUND_ERROR_SYMBOL] || candidate.digest === NOT_FOUND_ERROR_CODE);\n}\n\nfunction createRedirectError(url: string, status: FarmRedirectStatus): FarmNavigationError {\n  const error = new Error(`${REDIRECT_ERROR_CODE};${status};${url}`) as FarmNavigationError;\n  error.digest = `${REDIRECT_ERROR_CODE};${status};${url}`;\n  error[REDIRECT_ERROR_SYMBOL] = { url, status };\n  return error;\n}\n\nexport function isFarmRedirectStatus(status: unknown): status is FarmRedirectStatus {\n  return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n","export type FarmRouteRuntime = \"auto\" | \"node\" | \"edge\";\nexport type FarmRouteRegions = \"auto\" | readonly string[];\nexport type FarmRouteMaxDuration = \"auto\" | number;\n\n/** Portable execution controls shared by file, programmatic, and config routes. */\nexport interface FarmRouteRuntimeConfig {\n  runtime?: FarmRouteRuntime;\n  regions?: FarmRouteRegions;\n  maxDuration?: FarmRouteMaxDuration;\n}\n\nexport interface ResolvedFarmRouteRuntimeConfig {\n  runtime: FarmRouteRuntime;\n  regions?: string[];\n  maxDuration?: number;\n}\n\nexport type FarmRouteRuntimeEntryKind = \"page\" | \"api\" | \"metadata\" | \"rule\";\nexport type FarmRouteRenderingMode = \"static\" | \"dynamic\";\n\nexport interface FarmRouteRuntimeManifestEntry extends ResolvedFarmRouteRuntimeConfig {\n  kind: FarmRouteRuntimeEntryKind;\n  pattern: string;\n  rendering: FarmRouteRenderingMode;\n  source?: string;\n}\n\nexport interface FarmRouteRuntimeManifest {\n  version: 1;\n  routes: FarmRouteRuntimeManifestEntry[];\n}\n\nexport function normalizeFarmRouteRuntimeConfig(\n  value: FarmRouteRuntimeConfig | null | undefined,\n  source = \"Route configuration\",\n): FarmRouteRuntimeConfig {\n  if (!value) return {};\n\n  const normalized: FarmRouteRuntimeConfig = {};\n\n  if (value.runtime !== undefined) {\n    if (value.runtime !== \"auto\" && value.runtime !== \"node\" && value.runtime !== \"edge\") {\n      throw new TypeError(`${source} runtime must be \"auto\", \"node\", or \"edge\"`);\n    }\n    normalized.runtime = value.runtime;\n  }\n\n  if (value.regions !== undefined) {\n    if (value.regions === \"auto\") {\n      normalized.regions = \"auto\";\n    } else {\n      if (!Array.isArray(value.regions) || value.regions.length === 0) {\n        throw new TypeError(`${source} regions must be \"auto\" or a non-empty string array`);\n      }\n\n      const regions = Array.from(\n        new Set(\n          value.regions.map((region) => {\n            if (\n              typeof region !== \"string\" ||\n              !region.trim() ||\n              /[\\u0000-\\u001f\\u007f]/.test(region)\n            ) {\n              throw new TypeError(`${source} regions must contain non-empty region identifiers`);\n            }\n            return region.trim();\n          }),\n        ),\n      );\n\n      normalized.regions = regions;\n    }\n  }\n\n  if (value.maxDuration !== undefined) {\n    if (value.maxDuration === \"auto\") {\n      normalized.maxDuration = \"auto\";\n    } else if (\n      typeof value.maxDuration !== \"number\" ||\n      !Number.isInteger(value.maxDuration) ||\n      value.maxDuration <= 0\n    ) {\n      throw new TypeError(`${source} maxDuration must be \"auto\" or a positive integer in seconds`);\n    } else {\n      normalized.maxDuration = value.maxDuration;\n    }\n  }\n\n  return normalized;\n}\n\n/** Merge from lowest to highest precedence. Explicit \"auto\" values reset inherited hints. */\nexport function mergeFarmRouteRuntimeConfigs(\n  ...configs: Array<FarmRouteRuntimeConfig | null | undefined>\n): FarmRouteRuntimeConfig {\n  const merged: FarmRouteRuntimeConfig = {};\n\n  for (const config of configs) {\n    if (!config) continue;\n    if (config.runtime !== undefined) merged.runtime = config.runtime;\n    if (config.regions !== undefined) merged.regions = config.regions;\n    if (config.maxDuration !== undefined) merged.maxDuration = config.maxDuration;\n  }\n\n  return merged;\n}\n\nexport function resolveFarmRouteRuntimeConfig(\n  config: FarmRouteRuntimeConfig | null | undefined,\n  source?: string,\n): ResolvedFarmRouteRuntimeConfig {\n  const normalized = normalizeFarmRouteRuntimeConfig(config, source);\n\n  return {\n    runtime: normalized.runtime ?? \"auto\",\n    ...(normalized.regions && normalized.regions !== \"auto\"\n      ? { regions: [...normalized.regions] }\n      : {}),\n    ...(typeof normalized.maxDuration === \"number\" ? { maxDuration: normalized.maxDuration } : {}),\n  };\n}\n\nexport function hasFarmRouteRuntimeControls(\n  config: FarmRouteRuntimeConfig | null | undefined,\n): boolean {\n  return Boolean(\n    config &&\n    (config.runtime !== undefined ||\n      config.regions !== undefined ||\n      config.maxDuration !== undefined),\n  );\n}\n\nexport function getFarmRouteRuntimeConfig(value: unknown): FarmRouteRuntimeConfig {\n  if (!value || typeof value !== \"object\") return {};\n  const route = value as FarmRouteRuntimeConfig;\n  return {\n    ...(route.runtime !== undefined ? { runtime: route.runtime } : {}),\n    ...(route.regions !== undefined ? { regions: route.regions } : {}),\n    ...(route.maxDuration !== undefined ? { maxDuration: route.maxDuration } : {}),\n  };\n}\n\nexport function createFarmRouteRuntimeKey(config: ResolvedFarmRouteRuntimeConfig): string {\n  return JSON.stringify({\n    runtime: config.runtime,\n    regions: config.regions || null,\n    maxDuration: config.maxDuration || null,\n  });\n}\n\n/** Resolve matching route rules from broadest to most specific. */\nexport function resolveFarmRouteRuleRuntimeConfig(\n  pathname: string,\n  routeRules: Record<string, FarmRouteRuntimeConfig> | null | undefined,\n): FarmRouteRuntimeConfig {\n  if (!routeRules) return {};\n\n  const matches = Object.entries(routeRules)\n    .filter(\n      ([pattern, rule]) =>\n        hasFarmRouteRuntimeControls(rule) && farmRouteRuleMatches(pattern, pathname),\n    )\n    .sort(([left], [right]) => compareFarmRouteRuleSpecificity(left, right));\n\n  return mergeFarmRouteRuntimeConfigs(...matches.map(([, rule]) => rule));\n}\n\nexport function farmRouteRuleMatches(pattern: string, pathname: string): boolean {\n  const normalizedPattern = normalizeRoutePattern(pattern);\n  const normalizedPathname = normalizeRoutePattern(pathname);\n  if (normalizedPattern === normalizedPathname) return true;\n\n  const expression = normalizedPattern\n    .split(\"/\")\n    .filter(Boolean)\n    .map((segment) => {\n      if (segment === \"**\") return \".*\";\n      if (segment === \"*\") return \"[^/]+\";\n      if (/^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)) return \".*\";\n      if (/^\\[\\.\\.\\..+\\]$/.test(segment)) return \".+\";\n      if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return \"[^/]+\";\n      return escapeRegExp(segment);\n    })\n    .join(\"/\");\n\n  return new RegExp(`^/${expression}/?$`).test(normalizedPathname);\n}\n\nfunction compareFarmRouteRuleSpecificity(left: string, right: string): number {\n  const leftScore = getFarmRouteRuleSpecificity(left);\n  const rightScore = getFarmRouteRuleSpecificity(right);\n  return leftScore - rightScore || left.localeCompare(right);\n}\n\nfunction getFarmRouteRuleSpecificity(pattern: string): number {\n  return normalizeRoutePattern(pattern)\n    .split(\"/\")\n    .filter(Boolean)\n    .reduce((score, segment) => {\n      if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n      if (segment === \"*\" || segment.startsWith(\"[...\")) return score + 10;\n      if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return score + 50;\n      return score + 100;\n    }, 0);\n}\n\nfunction normalizeRoutePattern(value: string): string {\n  const withSlash = value.trim().startsWith(\"/\") ? value.trim() : `/${value.trim()}`;\n  return withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import type { HeaderConfig, RedirectConfig } from \"./config\";\nimport { isFarmRedirectStatus, type FarmRedirectStatus } from \"./navigation-errors\";\nimport type { FarmRouteRuntimeConfig } from \"./route-runtime\";\nimport { normalizeFarmRouteRuntimeConfig } from \"./route-runtime\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\n\nexport type FarmRouteRuleRenderMode = \"static\" | \"dynamic\";\n\nexport type FarmRouteRuleRedirect =\n  | string\n  | {\n      to: string;\n      statusCode?: FarmRedirectStatus;\n      permanent?: boolean;\n    };\n\nexport type FarmRouteRuleCors =\n  | boolean\n  | {\n      origin?: string;\n      methods?: string | readonly string[];\n      headers?: string | readonly string[];\n    };\n\nexport interface FarmRouteRule extends FarmRouteRuntimeConfig {\n  prerender?: boolean;\n  render?: FarmRouteRuleRenderMode;\n  ssr?: boolean;\n  swr?: boolean | number;\n  isr?: boolean | number;\n  cors?: FarmRouteRuleCors;\n  headers?: Record<string, string>;\n  redirect?: FarmRouteRuleRedirect;\n}\n\nexport type FarmRouteRules = Record<string, FarmRouteRule>;\n\nexport function normalizeRouteRules(routeRules: FarmRouteRules | undefined): FarmRouteRules {\n  if (!routeRules) return {};\n\n  const normalized: FarmRouteRules = {};\n  const normalizedSources = new Map<string, string>();\n  for (const [source, rule] of Object.entries(routeRules)) {\n    if (!rule) continue;\n    const normalizedSource = normalizeRuleSource(source);\n    validateConfigRouteSource(normalizedSource, `Route rule \"${source}\" source`);\n    const existingSource = normalizedSources.get(normalizedSource);\n    if (existingSource !== undefined) {\n      throw new Error(\n        `Route rules \"${existingSource}\" and \"${source}\" both normalize to \"${normalizedSource}\".`,\n      );\n    }\n    normalizedSources.set(normalizedSource, source);\n    if (\n      typeof rule.redirect === \"object\" &&\n      rule.redirect.statusCode !== undefined &&\n      !isFarmRedirectStatus(rule.redirect.statusCode)\n    ) {\n      throw new RangeError(\n        `Route rule \"${normalizedSource}\" redirect.statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n    normalized[normalizedSource] = {\n      ...rule,\n      ...normalizeFarmRouteRuntimeConfig(rule, `Route rule \"${normalizedSource}\"`),\n    };\n  }\n  return normalized;\n}\n\nexport function routeRulesToRedirects(routeRules: FarmRouteRules): RedirectConfig[] {\n  return Object.entries(routeRules)\n    .filter((entry): entry is [string, FarmRouteRule & { redirect: FarmRouteRuleRedirect }] =>\n      Boolean(entry[1].redirect),\n    )\n    .map(([source, rule]) => {\n      const redirect = typeof rule.redirect === \"string\" ? { to: rule.redirect } : rule.redirect;\n      return {\n        source,\n        destination: redirect.to,\n        permanent: redirect.permanent,\n        statusCode: redirect.statusCode ?? (redirect.permanent === true ? 308 : undefined),\n      };\n    });\n}\n\nexport function routeRulesToHeaders(routeRules: FarmRouteRules): HeaderConfig[] {\n  const configs: HeaderConfig[] = [];\n\n  for (const [source, rule] of Object.entries(routeRules)) {\n    const headers = {\n      ...normalizeCorsHeaders(rule.cors),\n      ...rule.headers,\n    };\n\n    const entries = Object.entries(headers);\n    if (entries.length === 0) continue;\n\n    configs.push({\n      source,\n      headers: entries.map(([key, value]) => ({ key, value })),\n    });\n  }\n\n  return configs;\n}\n\nexport function routeRulesToNitroRouteRules(routeRules: FarmRouteRules): Record<string, any> {\n  const nitroRules: Record<string, any> = {};\n\n  for (const [source, rule] of Object.entries(routeRules)) {\n    const nitroRule: Record<string, any> = { ...rule };\n\n    if (rule.render === \"static\") {\n      nitroRule.prerender = true;\n    } else if (rule.render === \"dynamic\") {\n      nitroRule.prerender = false;\n    }\n\n    if (rule.redirect) {\n      const redirect = typeof rule.redirect === \"string\" ? { to: rule.redirect } : rule.redirect;\n      if (hasExplicitQuery(redirect.to)) {\n        // Nitro merges the incoming query into redirect targets, including when\n        // the target already declares one. Farm's redirect contract replaces\n        // the incoming query in that case, so let the bundled Farm handler own\n        // these redirects instead of changing their meaning in production.\n        delete nitroRule.redirect;\n      } else {\n        nitroRule.redirect = {\n          to: redirect.to,\n          status: redirect.statusCode ?? (redirect.permanent === true ? 308 : 307),\n        };\n      }\n    }\n\n    if (rule.cors) {\n      nitroRule.cors = true;\n      nitroRule.headers = {\n        ...normalizeCorsHeaders(rule.cors),\n        ...rule.headers,\n      };\n    }\n\n    delete nitroRule.render;\n    delete nitroRule.runtime;\n    delete nitroRule.regions;\n    delete nitroRule.maxDuration;\n    nitroRules[source] = nitroRule;\n  }\n\n  return nitroRules;\n}\n\nfunction normalizeCorsHeaders(cors: FarmRouteRuleCors | undefined): Record<string, string> {\n  if (!cors) return {};\n\n  if (cors === true) {\n    return {\n      \"Access-Control-Allow-Origin\": \"*\",\n      \"Access-Control-Allow-Methods\": \"*\",\n      \"Access-Control-Allow-Headers\": \"*\",\n    };\n  }\n\n  return {\n    \"Access-Control-Allow-Origin\": cors.origin ?? \"*\",\n    \"Access-Control-Allow-Methods\": normalizeList(cors.methods) ?? \"*\",\n    \"Access-Control-Allow-Headers\": normalizeList(cors.headers) ?? \"*\",\n  };\n}\n\nfunction normalizeList(value: string | readonly string[] | undefined): string | undefined {\n  if (!value || typeof value === \"string\") return value;\n  return value.join(\", \");\n}\n\nfunction normalizeRuleSource(source: string): string {\n  const trimmed = source.trim();\n  if (!trimmed) {\n    throw new TypeError(\"Route rule source must be a non-empty pathname pattern.\");\n  }\n  return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n\nfunction hasExplicitQuery(destination: string): boolean {\n  const queryIndex = destination.indexOf(\"?\");\n  if (queryIndex === -1) return false;\n  const hashIndex = destination.indexOf(\"#\");\n  return hashIndex === -1 || queryIndex < hashIndex;\n}\n","export type FarmCacheInvalidationListener = (key: string) => void;\nexport type FarmCacheTaskListener = (task: Promise<void>) => void;\n\nexport const FARM_CACHE_INVALIDATION_HEADER = \"x-farm-cache-invalidations\";\n\ntype FarmCacheInvalidationState = {\n  listeners: Set<FarmCacheInvalidationListener>;\n  taskListeners: Set<FarmCacheTaskListener>;\n};\n\nconst FARM_CACHE_INVALIDATION_STATE = Symbol.for(\"farm.cacheInvalidationState\");\nconst globalState = globalThis as typeof globalThis & {\n  [FARM_CACHE_INVALIDATION_STATE]?: FarmCacheInvalidationState;\n};\n\nfunction getFarmCacheInvalidationState(): FarmCacheInvalidationState {\n  return (globalState[FARM_CACHE_INVALIDATION_STATE] ??= {\n    listeners: new Set(),\n    taskListeners: new Set(),\n  });\n}\n\nfunction warnFarmCacheListenerError(scope: string, error: unknown): void {\n  const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);\n  console.warn(`[farm:cache] ${scope} listener failed: ${detail}`);\n}\n\nexport function notifyFarmCacheInvalidation(key: string): void {\n  if (typeof key !== \"string\" || key.length === 0) return;\n\n  for (const listener of getFarmCacheInvalidationState().listeners) {\n    // Isolate listeners: one throwing observer must not abort the remaining\n    // listeners (or the rest of a multi-key batch in applyFarmCacheInvalidations)\n    // and must not surface as a 500 when invalidation runs inside a request.\n    try {\n      listener(key);\n    } catch (error) {\n      warnFarmCacheListenerError(\"invalidation\", error);\n    }\n  }\n}\n\nexport function notifyFarmCacheTask(task: Promise<void>): void {\n  for (const listener of getFarmCacheInvalidationState().taskListeners) {\n    try {\n      listener(task);\n    } catch (error) {\n      warnFarmCacheListenerError(\"task\", error);\n    }\n  }\n}\n\nexport function applyFarmCacheInvalidations(keys: unknown): void {\n  if (!Array.isArray(keys)) return;\n\n  for (const key of keys) {\n    if (typeof key === \"string\") {\n      notifyFarmCacheInvalidation(key);\n    }\n  }\n}\n\nexport function encodeFarmCacheInvalidations(keys: readonly string[]): string | null {\n  const normalized = Array.from(\n    new Set(keys.filter((key) => typeof key === \"string\" && key.length > 0)),\n  );\n  if (normalized.length === 0) return null;\n  return encodeURIComponent(JSON.stringify(normalized));\n}\n\nexport function decodeFarmCacheInvalidations(value: string | null | undefined): readonly string[] {\n  if (!value) return [];\n\n  try {\n    const parsed = JSON.parse(decodeURIComponent(value));\n    return Array.isArray(parsed)\n      ? Array.from(\n          new Set(parsed.filter((key): key is string => typeof key === \"string\" && key.length > 0)),\n        )\n      : [];\n  } catch {\n    return [];\n  }\n}\n\nexport function subscribeFarmCacheInvalidation(\n  listener: FarmCacheInvalidationListener,\n): () => void {\n  const state = getFarmCacheInvalidationState();\n  state.listeners.add(listener);\n  return () => state.listeners.delete(listener);\n}\n\nexport function subscribeFarmCacheTask(listener: FarmCacheTaskListener): () => void {\n  const state = getFarmCacheInvalidationState();\n  state.taskListeners.add(listener);\n  return () => state.taskListeners.delete(listener);\n}\n","/**\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","export const FARM_SERVER_FN_FAILURE_SYMBOL = Symbol.for(\"farm.server-fn.failure\");\n\nexport type SerializedServerFnFailure = {\n  name: \"ServerFnFailure\";\n  message: string;\n  code: string;\n  status: number;\n  data: unknown;\n};\n\nexport class ServerFnFailure<\n  TCode extends string = string,\n  TData = unknown,\n  TStatus extends number = number,\n> extends Error {\n  readonly name = \"ServerFnFailure\" as const;\n  readonly code: TCode;\n  readonly data: TData;\n  readonly status: TStatus;\n\n  constructor(\n    code: TCode,\n    data: TData,\n    options: {\n      status: TStatus;\n      message: string;\n    },\n  ) {\n    super(options.message);\n    this.code = code;\n    this.data = data;\n    this.status = options.status;\n\n    Object.defineProperty(this, FARM_SERVER_FN_FAILURE_SYMBOL, {\n      value: true,\n      enumerable: false,\n    });\n  }\n}\n\nexport class ServerActionError extends Error {\n  readonly name = \"ServerActionError\" as const;\n\n  constructor(message = \"Server function failed\") {\n    super(message);\n  }\n}\n\nexport function isServerFnFailure(value: unknown): value is ServerFnFailure {\n  if (!value || typeof value !== \"object\") return false;\n\n  const candidate = value as Partial<ServerFnFailure> & {\n    [FARM_SERVER_FN_FAILURE_SYMBOL]?: unknown;\n  };\n  return (\n    candidate[FARM_SERVER_FN_FAILURE_SYMBOL] === true &&\n    candidate.name === \"ServerFnFailure\" &&\n    typeof candidate.code === \"string\" &&\n    Number.isInteger(candidate.status) &&\n    (candidate.status ?? 0) >= 400 &&\n    (candidate.status ?? 0) <= 599\n  );\n}\n\nexport function serializeServerFnFailure(value: unknown): SerializedServerFnFailure | null {\n  if (!isServerFnFailure(value)) return null;\n\n  return {\n    name: \"ServerFnFailure\",\n    message: value.message,\n    code: value.code,\n    status: value.status,\n    data: value.data,\n  };\n}\n\nexport function createServerFnTransportError(value: unknown): ServerFnFailure | ServerActionError {\n  if (isSerializedServerFnFailure(value)) {\n    return new ServerFnFailure(value.code, value.data, {\n      status: value.status,\n      message: value.message,\n    });\n  }\n\n  const message =\n    value && typeof value === \"object\" && \"message\" in value && typeof value.message === \"string\"\n      ? value.message\n      : \"Server function failed\";\n  return new ServerActionError(message);\n}\n\nfunction isSerializedServerFnFailure(value: unknown): value is SerializedServerFnFailure {\n  if (!value || typeof value !== \"object\") return false;\n\n  const candidate = value as Partial<SerializedServerFnFailure>;\n  return (\n    candidate.name === \"ServerFnFailure\" &&\n    typeof candidate.message === \"string\" &&\n    typeof candidate.code === \"string\" &&\n    Number.isInteger(candidate.status) &&\n    (candidate.status ?? 0) >= 400 &&\n    (candidate.status ?? 0) <= 599 &&\n    \"data\" in candidate\n  );\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { subscribeFarmCacheInvalidation, subscribeFarmCacheTask } from \"./cache-invalidation\";\nimport {\n  getRequestSourceOrigin,\n  matchesAllowedOrigin,\n  matchesHostHeader,\n  normalizeAllowedOriginPattern,\n} from \"./request-origin\";\nimport { serializeServerFnFailure, type SerializedServerFnFailure } from \"./server-fn-error\";\nimport { parseBodySizeLimit } from \"./server-http\";\n\nconst SERVER_ACTION_ALLOWED_ORIGINS_LABEL = \"serverActions.allowedOrigins\";\n\nexport const DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT = 1_000_000;\n\nexport interface FarmServerActionsConfig {\n  /** Additional trusted origins or host patterns, such as https://app.example.com. */\n  allowedOrigins?: readonly string[];\n  /** Maximum encoded request body size in bytes or as a size string such as \"1mb\". */\n  bodySizeLimit?: number | string;\n}\n\nexport interface ResolvedFarmServerActionsConfig {\n  allowedOrigins: readonly string[];\n  bodySizeLimit: number;\n}\n\nexport type ServerActionRequestKind = \"javascript\" | \"form\";\n\nexport interface PreparedServerActionRequest {\n  body: string | FormData;\n  contentType: string;\n}\n\nexport type SanitizedServerActionError =\n  | {\n      name: \"ServerActionError\";\n      message: \"Server function failed\";\n    }\n  | SerializedServerFnFailure;\n\ntype ServerActionRequestErrorCode =\n  | \"BODY_TOO_LARGE\"\n  | \"INVALID_ACTION_ID\"\n  | \"INVALID_BODY\"\n  | \"INVALID_CONTENT_LENGTH\"\n  | \"INVALID_METHOD\"\n  | \"INVALID_ORIGIN\"\n  | \"MISSING_ORIGIN\"\n  | \"UNSUPPORTED_CONTENT_TYPE\";\n\nexport class ServerActionRequestError extends Error {\n  readonly code: ServerActionRequestErrorCode;\n  readonly status: number;\n\n  constructor(code: ServerActionRequestErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"ServerActionRequestError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\ntype ServerActionExecutionContext = {\n  request: Request;\n  signal: AbortSignal;\n  invalidations: Set<string>;\n  cacheTasks: Set<Promise<void>>;\n};\n\nconst SERVER_ACTION_STORAGE_KEY = Symbol.for(\"farm.serverActionStorage\");\nconst FALLBACK_ABORT_CONTROLLER_KEY = Symbol.for(\"farm.serverActionFallbackAbortController\");\nconst FORM_ACTION_CONTENT_TYPES = new Set([\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n]);\nconst JAVASCRIPT_ACTION_CONTENT_TYPES = new Set([\n  \"application/octet-stream\",\n  \"application/x-www-form-urlencoded\",\n  \"multipart/form-data\",\n  \"text/plain\",\n]);\n\ntype GlobalWithServerActionStorage = typeof globalThis & {\n  [SERVER_ACTION_STORAGE_KEY]?: AsyncLocalStorage<ServerActionExecutionContext>;\n  [FALLBACK_ABORT_CONTROLLER_KEY]?: AbortController;\n};\n\nexport function resolveServerActionsConfig(\n  config: FarmServerActionsConfig | undefined,\n): ResolvedFarmServerActionsConfig {\n  const allowedOrigins = (config?.allowedOrigins ?? []).map((value) =>\n    normalizeAllowedOriginPattern(value, SERVER_ACTION_ALLOWED_ORIGINS_LABEL),\n  );\n  const bodySizeLimit = parseBodySizeLimit(\n    config?.bodySizeLimit ?? DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT,\n    \"serverActions.bodySizeLimit\",\n  );\n\n  return Object.freeze({\n    allowedOrigins: Object.freeze(allowedOrigins),\n    bodySizeLimit,\n  });\n}\n\nexport function validateServerActionRequest(\n  request: Request,\n  config: ResolvedFarmServerActionsConfig,\n): void {\n  if (request.method.toUpperCase() !== \"POST\") {\n    throw new ServerActionRequestError(\n      \"INVALID_METHOD\",\n      405,\n      \"Server actions only accept POST requests\",\n    );\n  }\n\n  const requestUrl = new URL(request.url);\n  const sourceOrigin = resolveSourceOrigin(request);\n  const fetchSite = request.headers.get(\"sec-fetch-site\")?.trim().toLowerCase();\n\n  if (!sourceOrigin) {\n    if (fetchSite !== \"same-origin\") {\n      throw new ServerActionRequestError(\n        \"MISSING_ORIGIN\",\n        403,\n        \"Server action request is missing same-origin metadata\",\n      );\n    }\n    return;\n  }\n\n  const matchesRequest =\n    sourceOrigin === requestUrl.origin || matchesHostHeader(sourceOrigin, request);\n  const matchesConfiguredOrigin = config.allowedOrigins.some((pattern) =>\n    matchesAllowedOrigin(sourceOrigin, pattern),\n  );\n\n  if (!matchesRequest && !matchesConfiguredOrigin) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      \"Server action origin does not match the request origin\",\n    );\n  }\n\n  if (fetchSite === \"cross-site\" && !matchesConfiguredOrigin) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      \"Cross-site server action request was rejected\",\n    );\n  }\n}\n\nexport async function prepareServerActionRequest(\n  request: Request,\n  config: ResolvedFarmServerActionsConfig,\n  kind: ServerActionRequestKind,\n  actionId?: string | null,\n): Promise<PreparedServerActionRequest> {\n  validateServerActionRequest(request, config);\n\n  if (kind === \"javascript\") {\n    validateActionId(actionId);\n  }\n\n  const contentType = getSupportedContentType(request, kind);\n  const bytes = await readBodyWithLimit(request, config.bodySizeLimit);\n\n  if (kind === \"form\" || contentType === \"multipart/form-data\") {\n    return {\n      body: await parseFormData(request, bytes),\n      contentType,\n    };\n  }\n\n  return {\n    body: new TextDecoder().decode(bytes),\n    contentType,\n  };\n}\n\nexport function createServerActionRequestErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof ServerActionRequestError)) {\n    return null;\n  }\n\n  const headers = new Headers({\n    \"cache-control\": \"no-store\",\n    \"content-type\": \"text/plain; charset=utf-8\",\n    \"x-content-type-options\": \"nosniff\",\n  });\n  if (error.status === 405) {\n    headers.set(\"allow\", \"POST\");\n  }\n\n  return new Response(getPublicErrorMessage(error.status), {\n    status: error.status,\n    headers,\n  });\n}\n\nexport function sanitizeServerActionError(error: unknown): SanitizedServerActionError {\n  const declaredFailure = serializeServerFnFailure(error);\n  if (declaredFailure) return declaredFailure;\n\n  return {\n    name: \"ServerActionError\",\n    message: \"Server function failed\",\n  };\n}\n\nexport async function runWithServerActionRequest<T>(\n  request: Request,\n  callback: () => T | Promise<T>,\n): Promise<T> {\n  throwIfAborted(request.signal);\n  const context: ServerActionExecutionContext = {\n    request,\n    signal: request.signal,\n    invalidations: new Set(),\n    cacheTasks: new Set(),\n  };\n\n  return getServerActionStorage().run(context, async () => {\n    try {\n      const result = await callback();\n      await Promise.all(context.cacheTasks);\n      return result;\n    } catch (error) {\n      await Promise.allSettled(context.cacheTasks);\n      throw error;\n    }\n  });\n}\n\nexport function getServerActionExecutionContext(): ServerActionExecutionContext | undefined {\n  return getServerActionStorage().getStore();\n}\n\nexport function getServerActionSignal(): AbortSignal {\n  return getServerActionExecutionContext()?.signal ?? getFallbackAbortController().signal;\n}\n\nexport function getServerActionInvalidations(): readonly string[] {\n  return Array.from(getServerActionExecutionContext()?.invalidations ?? []);\n}\n\nsubscribeFarmCacheInvalidation((key) => {\n  getServerActionExecutionContext()?.invalidations.add(key);\n});\n\nsubscribeFarmCacheTask((task) => {\n  getServerActionExecutionContext()?.cacheTasks.add(task);\n});\n\nfunction getServerActionStorage(): AsyncLocalStorage<ServerActionExecutionContext> {\n  const globalState = globalThis as GlobalWithServerActionStorage;\n  if (!globalState[SERVER_ACTION_STORAGE_KEY]) {\n    globalState[SERVER_ACTION_STORAGE_KEY] = new AsyncLocalStorage<ServerActionExecutionContext>();\n  }\n  return globalState[SERVER_ACTION_STORAGE_KEY]!;\n}\n\nfunction getFallbackAbortController(): AbortController {\n  const globalState = globalThis as GlobalWithServerActionStorage;\n  if (!globalState[FALLBACK_ABORT_CONTROLLER_KEY]) {\n    globalState[FALLBACK_ABORT_CONTROLLER_KEY] = new AbortController();\n  }\n  return globalState[FALLBACK_ABORT_CONTROLLER_KEY]!;\n}\n\n/**\n * Adapt the shared origin resolution onto the server-action error contract:\n * an unusable Origin/Referer is a 403 here, while a request that simply\n * carried neither header returns null for the caller to judge.\n */\nfunction resolveSourceOrigin(request: Request): string | null {\n  const result = getRequestSourceOrigin(request);\n\n  if (!result.ok) {\n    throw new ServerActionRequestError(\n      \"INVALID_ORIGIN\",\n      403,\n      result.reason === \"opaque-origin\"\n        ? \"Opaque origins are not allowed\"\n        : \"Invalid request origin\",\n    );\n  }\n\n  return result.origin;\n}\n\nfunction validateActionId(actionId?: string | null): asserts actionId is string {\n  if (!actionId || actionId.length > 4096 || hasControlCharacters(actionId)) {\n    throw new ServerActionRequestError(\"INVALID_ACTION_ID\", 400, \"Invalid server action id\");\n  }\n}\n\nfunction hasControlCharacters(value: string): boolean {\n  for (let index = 0; index < value.length; index++) {\n    const code = value.charCodeAt(index);\n    if (code <= 31 || code === 127) return true;\n  }\n  return false;\n}\n\nfunction getSupportedContentType(request: Request, kind: ServerActionRequestKind): string {\n  const header = request.headers.get(\"content-type\")?.trim().toLowerCase();\n  const contentType = header?.split(\";\", 1)[0]?.trim() ?? \"\";\n  const supported = kind === \"form\" ? FORM_ACTION_CONTENT_TYPES : JAVASCRIPT_ACTION_CONTENT_TYPES;\n\n  if (!supported.has(contentType)) {\n    throw new ServerActionRequestError(\n      \"UNSUPPORTED_CONTENT_TYPE\",\n      415,\n      \"Unsupported server action content type\",\n    );\n  }\n\n  return contentType;\n}\n\nasync function readBodyWithLimit(request: Request, limit: number): Promise<Uint8Array> {\n  const contentLength = request.headers.get(\"content-length\")?.trim();\n  if (contentLength) {\n    if (!/^\\d+$/.test(contentLength)) {\n      throw new ServerActionRequestError(\n        \"INVALID_CONTENT_LENGTH\",\n        400,\n        \"Invalid content-length header\",\n      );\n    }\n    if (Number(contentLength) > limit) {\n      throw new ServerActionRequestError(\"BODY_TOO_LARGE\", 413, \"Server action body is too large\");\n    }\n  }\n\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new ServerActionRequestError(\n          \"BODY_TOO_LARGE\",\n          413,\n          \"Server action body is too large\",\n        );\n        // As with API bodies, a cloned stream may wait for its untouched tee\n        // branch. Cleanup must neither delay rejection nor replace its error.\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  throwIfAborted(request.signal);\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nasync function parseFormData(request: Request, bytes: Uint8Array): Promise<FormData> {\n  const body = new ArrayBuffer(bytes.byteLength);\n  new Uint8Array(body).set(bytes);\n  const copy = new Request(request.url, {\n    method: \"POST\",\n    headers: request.headers,\n    body,\n  });\n\n  try {\n    return await copy.formData();\n  } catch {\n    throw new ServerActionRequestError(\"INVALID_BODY\", 400, \"Invalid server action form body\");\n  }\n}\n\nfunction getPublicErrorMessage(status: number): string {\n  switch (status) {\n    case 400:\n      return \"Bad Request\";\n    case 403:\n      return \"Forbidden\";\n    case 405:\n      return \"Method Not Allowed\";\n    case 413:\n      return \"Payload Too Large\";\n    case 415:\n      return \"Unsupported Media Type\";\n    default:\n      return \"Server Action Request Failed\";\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","export const DEFAULT_FARM_IMAGE_PATH = \"/_farm/image\";\nexport const DEFAULT_FARM_IMAGE_DEVICE_SIZES = [\n  640, 750, 828, 1080, 1200, 1920, 2048, 3840,\n] as const;\nexport const DEFAULT_FARM_IMAGE_SIZES = [16, 32, 48, 64, 96, 128, 256, 384] as const;\nexport const DEFAULT_FARM_IMAGE_QUALITIES = [75] as const;\nexport const DEFAULT_FARM_IMAGE_FORMATS = [\"image/webp\"] as const;\n\nexport type FarmImageFormat = \"image/avif\" | \"image/webp\";\nexport type FarmImageProvider = \"auto\" | \"node\" | \"cloudflare\" | \"none\";\n\nexport interface FarmImageRemotePattern {\n  protocol?: \"http\" | \"https\";\n  hostname: string;\n  port?: string;\n  pathname?: string;\n  search?: string;\n}\n\nexport interface FarmImageLocalPattern {\n  pathname: string;\n  search?: string;\n}\n\nexport interface FarmImageConfig {\n  /** Runtime optimizer. Auto selects Cloudflare Images on Cloudflare and Sharp elsewhere. */\n  provider?: FarmImageProvider;\n  /** Public optimizer endpoint. */\n  path?: string;\n  /** @deprecated Prefer remotePatterns, which also restricts protocol, path, port, and query. */\n  domains?: readonly string[];\n  remotePatterns?: readonly FarmImageRemotePattern[];\n  localPatterns?: readonly FarmImageLocalPattern[];\n  deviceSizes?: readonly number[];\n  imageSizes?: readonly number[];\n  qualities?: readonly number[];\n  formats?: readonly FarmImageFormat[];\n  minimumCacheTTL?: number;\n  maximumResponseBody?: number | string;\n  maximumRedirects?: number;\n  dangerouslyAllowSVG?: boolean;\n  dangerouslyAllowLocalIP?: boolean;\n}\n\nexport interface ResolvedFarmImageConfig {\n  provider: FarmImageProvider;\n  path: string;\n  domains: readonly string[];\n  remotePatterns: readonly FarmImageRemotePattern[];\n  localPatterns: readonly FarmImageLocalPattern[];\n  deviceSizes: readonly number[];\n  imageSizes: readonly number[];\n  qualities: readonly number[];\n  formats: readonly FarmImageFormat[];\n  minimumCacheTTL: number;\n  maximumResponseBody: number;\n  maximumRedirects: number;\n  dangerouslyAllowSVG: boolean;\n  dangerouslyAllowLocalIP: boolean;\n}\n\nexport type PublicFarmImageConfig = Pick<\n  ResolvedFarmImageConfig,\n  \"provider\" | \"path\" | \"deviceSizes\" | \"imageSizes\" | \"qualities\" | \"formats\"\n>;\n\nconst SIZE_UNITS: Record<string, number> = {\n  b: 1,\n  kb: 1_000,\n  mb: 1_000_000,\n  gb: 1_000_000_000,\n  kib: 1_024,\n  mib: 1_048_576,\n  gib: 1_073_741_824,\n};\n\nexport function resolveFarmImageConfig(\n  config: FarmImageConfig | undefined,\n): ResolvedFarmImageConfig {\n  const path = normalizeImagePath(config?.path ?? DEFAULT_FARM_IMAGE_PATH);\n  const deviceSizes = normalizeIntegerList(\n    config?.deviceSizes ?? DEFAULT_FARM_IMAGE_DEVICE_SIZES,\n    \"images.deviceSizes\",\n  );\n  const imageSizes = normalizeIntegerList(\n    config?.imageSizes ?? DEFAULT_FARM_IMAGE_SIZES,\n    \"images.imageSizes\",\n  );\n  const qualities = normalizeIntegerList(\n    config?.qualities ?? DEFAULT_FARM_IMAGE_QUALITIES,\n    \"images.qualities\",\n    100,\n  );\n  const formats = [...new Set(config?.formats ?? DEFAULT_FARM_IMAGE_FORMATS)];\n\n  if (formats.some((format) => format !== \"image/avif\" && format !== \"image/webp\")) {\n    throw new TypeError('images.formats only supports \"image/avif\" and \"image/webp\"');\n  }\n\n  const minimumCacheTTL = normalizeNonNegativeInteger(\n    config?.minimumCacheTTL ?? 60,\n    \"images.minimumCacheTTL\",\n  );\n  const maximumRedirects = normalizeNonNegativeInteger(\n    config?.maximumRedirects ?? 3,\n    \"images.maximumRedirects\",\n  );\n\n  return Object.freeze({\n    provider: config?.provider ?? \"auto\",\n    path,\n    domains: Object.freeze([\n      ...new Set(\n        (config?.domains ?? []).map((domain) => domain.trim().toLowerCase()).filter(Boolean),\n      ),\n    ]),\n    remotePatterns: Object.freeze(\n      (config?.remotePatterns ?? []).map((pattern) => normalizeRemotePattern(pattern)),\n    ),\n    localPatterns: Object.freeze(\n      (config?.localPatterns ?? [{ pathname: \"/**\" }]).map((pattern) =>\n        normalizeLocalPattern(pattern),\n      ),\n    ),\n    deviceSizes: Object.freeze(deviceSizes),\n    imageSizes: Object.freeze(imageSizes),\n    qualities: Object.freeze(qualities),\n    formats: Object.freeze(formats),\n    minimumCacheTTL,\n    maximumResponseBody: parseSize(\n      config?.maximumResponseBody ?? \"10mb\",\n      \"images.maximumResponseBody\",\n    ),\n    maximumRedirects,\n    dangerouslyAllowSVG: config?.dangerouslyAllowSVG ?? false,\n    dangerouslyAllowLocalIP: config?.dangerouslyAllowLocalIP ?? false,\n  });\n}\n\nexport function getPublicFarmImageConfig(\n  config: Pick<ResolvedFarmImageConfig, keyof PublicFarmImageConfig>,\n): PublicFarmImageConfig {\n  return {\n    provider: config.provider,\n    path: config.path,\n    deviceSizes: config.deviceSizes,\n    imageSizes: config.imageSizes,\n    qualities: config.qualities,\n    formats: config.formats,\n  };\n}\n\nfunction normalizeImagePath(value: string): string {\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(value)) {\n    throw new TypeError(\"images.path cannot contain backslashes or control characters\");\n  }\n\n  const path = value.trim().replace(/\\/+$/, \"\") || \"/\";\n  if (!path.startsWith(\"/\") || path.startsWith(\"//\") || path.includes(\"?\") || path.includes(\"#\")) {\n    throw new TypeError(\"images.path must be an absolute pathname without a query or hash\");\n  }\n\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal and cannot conceal a path separator\n      // or dot segment.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new TypeError(\"images.path cannot contain backslashes or control characters\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new TypeError(\"images.path cannot contain percent-encoded path separators\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new TypeError('images.path cannot contain \".\" or \"..\" path segments');\n    }\n  }\n\n  return path;\n}\n\nfunction normalizeIntegerList(values: readonly number[], name: string, max?: number): number[] {\n  if (values.length === 0) {\n    throw new TypeError(`${name} must contain at least one value`);\n  }\n\n  const normalized = [...new Set(values)].sort((left, right) => left - right);\n  for (const value of normalized) {\n    if (!Number.isSafeInteger(value) || value <= 0 || (max !== undefined && value > max)) {\n      throw new TypeError(\n        `${name} must contain positive integers${max ? ` no greater than ${max}` : \"\"}`,\n      );\n    }\n  }\n  return normalized;\n}\n\nfunction normalizeNonNegativeInteger(value: number, name: string): number {\n  if (!Number.isSafeInteger(value) || value < 0) {\n    throw new TypeError(`${name} must be a non-negative safe integer`);\n  }\n  return value;\n}\n\nfunction parseSize(value: number | string, name: string): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${name} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)$/);\n  if (!match) {\n    throw new TypeError(`${name} must be bytes or a size string such as \"5mb\"`);\n  }\n\n  const bytes = Number(match[1]) * SIZE_UNITS[match[2]];\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${name} must resolve to a positive safe integer`);\n  }\n  return bytes;\n}\n\nfunction normalizeRemotePattern(pattern: FarmImageRemotePattern): FarmImageRemotePattern {\n  const hostname = pattern.hostname.trim().toLowerCase();\n  if (!hostname || hostname.includes(\"/\") || hostname.includes(\":\")) {\n    throw new TypeError(\"images.remotePatterns[].hostname must be a hostname or wildcard hostname\");\n  }\n  if (pattern.pathname && !pattern.pathname.startsWith(\"/\")) {\n    throw new TypeError(\"images.remotePatterns[].pathname must start with /\");\n  }\n  if (pattern.search && !pattern.search.startsWith(\"?\")) {\n    throw new TypeError(\"images.remotePatterns[].search must start with ?\");\n  }\n  return Object.freeze({ ...pattern, hostname });\n}\n\nfunction normalizeLocalPattern(pattern: FarmImageLocalPattern): FarmImageLocalPattern {\n  if (!pattern.pathname.startsWith(\"/\")) {\n    throw new TypeError(\"images.localPatterns[].pathname must start with /\");\n  }\n  if (pattern.search && !pattern.search.startsWith(\"?\")) {\n    throw new TypeError(\"images.localPatterns[].search must start with ?\");\n  }\n  return Object.freeze({ ...pattern });\n}\n","import { existsSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { mkdir, unlink } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\ntype EsbuildTransform = (typeof import(\"esbuild\"))[\"transform\"];\n\nexport type FarmLayerEntry = string;\n\nexport interface ResolvedFarmLayer {\n  /** The value used in `extends`. */\n  source: string;\n  /** Stable name used by the `#layers/<name>` alias. */\n  name: string;\n  /** Absolute layer package or directory root. */\n  root: string;\n  /** Source directory relative to the layer root. */\n  srcDir: string;\n  /** Resolved layer config file when one exists. */\n  configFile?: string;\n}\n\nexport interface FarmSourceRoot {\n  name: string;\n  root: string;\n  srcDir: string;\n  layer: boolean;\n}\n\nexport interface ResolveFarmLayersOptions {\n  root: string;\n  mode: \"development\" | \"production\";\n}\n\nexport interface FarmLayerResolution<TConfig extends Record<string, any>> {\n  config: TConfig & {\n    extends?: readonly FarmLayerEntry[];\n    layers: ResolvedFarmLayer[];\n  };\n  layers: ResolvedFarmLayer[];\n}\n\nconst FARM_CORE_PACKAGE = \"@farm.js/core\";\nconst FARM_CONFIG_ENTRY = \"@farm.js/core/config\";\nconst FARM_CORE_REFERENCE_RE = /([\"'])@farm.js\\/core\\1/g;\nconst FARM_CONFIG_HELPER_IMPORT_RE =\n  /(?:^|\\n)[\\t ]*import[\\t ]*\\{([^{}]*)\\}[\\t ]*from[\\t ]*([\"'])@farm.js\\/core\\2[\\t ]*;?[\\t ]*(?:\\n|$)/g;\nconst FARM_CONFIG_HELPER_SPECIFIER_RE =\n  /^(?:defineConfig|defineFarmConfig)(?:\\s+as\\s+[$A-Z_a-z][$\\w]*)?$/;\n\nconst CONFIG_FILENAMES = [\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n];\n\nconst LAYER_LOCAL_CONFIG_KEYS = new Set([\n  \"root\",\n  \"srcDir\",\n  \"outDir\",\n  \"distDir\",\n  \"deploy\",\n  \"output\",\n  \"preset\",\n  \"publicDir\",\n  \"generateBuildId\",\n]);\n\ntype LoadedLayer = ResolvedFarmLayer & {\n  config: Record<string, any>;\n};\n\nexport async function resolveFarmLayers<TConfig extends Record<string, any>>(\n  projectConfig: TConfig,\n  options: ResolveFarmLayersOptions,\n): Promise<FarmLayerResolution<TConfig>> {\n  const projectRoot = path.resolve(options.root);\n  const entries = normalizeLayerEntries(projectConfig.extends, \"project config\");\n\n  if (entries.length === 0) {\n    return {\n      config: {\n        ...projectConfig,\n        layers: [],\n      },\n      layers: [],\n    };\n  }\n\n  const loadedLayers: LoadedLayer[] = [];\n  const visited = new Set<string>();\n  const aliases = new Map<string, string>();\n\n  const visit = async (\n    source: string,\n    ownerRoot: string,\n    stack: Array<{ root: string; source: string }>,\n  ): Promise<void> => {\n    const resolvedSource = resolveLayerSource(source, ownerRoot);\n    const cycleIndex = stack.findIndex((entry) => entry.root === resolvedSource.root);\n    if (cycleIndex !== -1) {\n      const cycle = [...stack.slice(cycleIndex).map((entry) => entry.source), source];\n      throw new Error(`Farm layer cycle detected: ${cycle.join(\" -> \")}`);\n    }\n    if (visited.has(resolvedSource.root)) return;\n\n    const configFile = findFarmConfigFile(resolvedSource.root, resolvedSource.configFile);\n    const config = configFile\n      ? await loadFarmConfigFile(configFile, {\n          cacheRoot: projectRoot,\n          root: resolvedSource.root,\n        })\n      : {};\n    const nestedEntries = normalizeLayerEntries(config.extends, `layer ${JSON.stringify(source)}`);\n    const nextStack = [...stack, { root: resolvedSource.root, source }];\n\n    for (const nestedSource of nestedEntries) {\n      await visit(nestedSource, resolvedSource.root, nextStack);\n    }\n\n    if (visited.has(resolvedSource.root)) return;\n\n    const name = getLayerName(source, resolvedSource.root);\n    const conflictingRoot = aliases.get(name);\n    if (conflictingRoot && conflictingRoot !== resolvedSource.root) {\n      throw new Error(\n        `Farm layer alias \"#layers/${name}\" is ambiguous between ${conflictingRoot} and ${resolvedSource.root}`,\n      );\n    }\n    aliases.set(name, resolvedSource.root);\n\n    visited.add(resolvedSource.root);\n    loadedLayers.push({\n      source,\n      name,\n      root: resolvedSource.root,\n      srcDir: normalizeLayerSrcDir(config.srcDir),\n      configFile,\n      config,\n    });\n  };\n\n  for (const source of entries) {\n    await visit(source, projectRoot, []);\n  }\n\n  let mergedConfig: Record<string, any> = {};\n  for (const layer of loadedLayers) {\n    mergedConfig = mergeFarmLayerConfig(mergedConfig, getLayerDefaults(layer.config));\n  }\n  mergedConfig = mergeFarmLayerConfig(mergedConfig, projectConfig);\n\n  const layers = loadedLayers.map(({ config: _config, ...layer }) => layer);\n  return {\n    config: {\n      ...mergedConfig,\n      root: projectConfig.root,\n      srcDir: projectConfig.srcDir,\n      extends: projectConfig.extends,\n      layers,\n    } as unknown as FarmLayerResolution<TConfig>[\"config\"],\n    layers,\n  };\n}\n\nexport function getFarmSourceRoots(config: {\n  root?: string;\n  srcDir?: string;\n  layers?: readonly ResolvedFarmLayer[];\n}): FarmSourceRoot[] {\n  const roots: FarmSourceRoot[] = (config.layers ?? []).map((layer) => ({\n    name: layer.name,\n    root: layer.root,\n    srcDir: layer.srcDir,\n    layer: true,\n  }));\n\n  roots.push({\n    name: \"project\",\n    root: path.resolve(config.root || process.cwd()),\n    srcDir: config.srcDir || \"src\",\n    layer: false,\n  });\n\n  return roots;\n}\n\nexport function getFarmAppDirectories(config: {\n  root?: string;\n  srcDir?: string;\n  layers?: readonly ResolvedFarmLayer[];\n}): string[] {\n  return getFarmSourceRoots(config).map((source) => path.join(source.root, source.srcDir, \"app\"));\n}\n\nexport function getFarmLayerAliases(\n  layers: readonly ResolvedFarmLayer[] | undefined,\n): Record<string, string> {\n  return Object.fromEntries(\n    (layers ?? []).map((layer) => [`#layers/${layer.name}`, path.join(layer.root, layer.srcDir)]),\n  );\n}\n\n// Matches Windows drive-letter (`E:\\`, `E:/`) and UNC (`\\\\server\\share`) paths,\n// which would otherwise pass the \"bare specifier\" filter below. `path.isAbsolute`\n// only recognizes these on Windows, but esbuild can hand us such paths on any\n// platform (e.g. in cross-platform tests), and no valid package name contains\n// `:` or starts with `\\`.\nconst WINDOWS_ABSOLUTE_PATH_RE = /^(?:[A-Za-z]:[\\\\/]|\\\\\\\\)/;\n\n// External paths are written verbatim into the bundled config's import\n// statements. Node's ESM loader accepts `/abs/path` specifiers on POSIX, but a\n// raw Windows path like `E:\\...` is parsed as a URL with protocol `e:` and\n// rejected, so absolute paths must be emitted as file:// URLs.\nfunction toExternalSpecifier(resolvedPath: string): string {\n  return path.isAbsolute(resolvedPath) ? pathToFileURL(resolvedPath).href : resolvedPath;\n}\n\nexport function createFarmConfigResolutionPlugin(options: {\n  transform: EsbuildTransform;\n}): import(\"esbuild\").Plugin {\n  const configEntryChecks = new Map<string, Promise<boolean>>();\n\n  return {\n    name: \"farm-config-package-resolution\",\n    setup(pluginBuild) {\n      pluginBuild.onResolve({ filter: /^@farm\\.js\\/core$/ }, async (args) => {\n        if (\n          args.pluginData?.farmConfigExternal ||\n          args.kind !== \"import-statement\" ||\n          !args.importer\n        ) {\n          return;\n        }\n\n        let configEntryCheck = configEntryChecks.get(args.importer);\n        if (!configEntryCheck) {\n          configEntryCheck = onlyImportsFarmConfigHelpers(args.importer, options.transform);\n          configEntryChecks.set(args.importer, configEntryCheck);\n        }\n        if (!(await configEntryCheck)) return;\n\n        const resolved = await pluginBuild.resolve(FARM_CONFIG_ENTRY, {\n          importer: args.importer,\n          kind: args.kind,\n          namespace: args.namespace,\n          resolveDir: args.resolveDir,\n          pluginData: { farmConfigExternal: true },\n        });\n        if (resolved.errors.length > 0 || !resolved.path) return;\n\n        return {\n          path: toExternalSpecifier(resolved.path),\n          external: true,\n          warnings: resolved.warnings,\n        };\n      });\n\n      pluginBuild.onResolve({ filter: /^[^./]/ }, async (args) => {\n        // The filter is meant to catch bare package specifiers, but Windows\n        // absolute paths (`E:\\...`) match it too — including the entry point\n        // itself, which esbuild rejects when marked external.\n        if (\n          args.kind === \"entry-point\" ||\n          path.isAbsolute(args.path) ||\n          WINDOWS_ABSOLUTE_PATH_RE.test(args.path)\n        ) {\n          return;\n        }\n        if (args.pluginData?.farmConfigExternal) return;\n\n        const resolved = await pluginBuild.resolve(args.path, {\n          importer: args.importer,\n          kind: args.kind,\n          namespace: args.namespace,\n          resolveDir: args.resolveDir,\n          pluginData: { farmConfigExternal: true },\n        });\n\n        if (resolved.errors.length > 0 || !resolved.path) {\n          return { path: args.path, external: true };\n        }\n\n        return {\n          path: toExternalSpecifier(resolved.path),\n          external: true,\n          warnings: resolved.warnings,\n        };\n      });\n    },\n  };\n}\n\nexport async function loadFarmConfigFile<TConfig = Record<string, any>>(\n  configPath: string,\n  options: { root: string; cacheRoot?: string },\n): Promise<TConfig> {\n  const { build, transform } = await import(\"esbuild\");\n  const cacheRoot = path.resolve(options.cacheRoot || options.root);\n  const configCacheDir = path.join(cacheRoot, \".farm\", \".config-loader\");\n  await mkdir(configCacheDir, { recursive: true });\n\n  const modulePath = path.join(\n    configCacheDir,\n    `farm-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n  );\n\n  await build({\n    absWorkingDir: path.resolve(options.root),\n    entryPoints: [path.resolve(configPath)],\n    outfile: modulePath,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: `node${process.versions.node.split(\".\")[0]}`,\n    plugins: [createFarmConfigResolutionPlugin({ transform })],\n    jsx: \"automatic\",\n    logLevel: \"silent\",\n    sourcemap: \"inline\",\n  });\n\n  const moduleUrl = `${pathToFileURL(modulePath).href}?t=${Date.now()}`;\n  try {\n    const loaded = await import(/* @vite-ignore */ moduleUrl);\n    const config = loaded.default || loaded;\n    if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n      throw new TypeError(`Farm config ${configPath} must export an object`);\n    }\n    return config as TConfig;\n  } finally {\n    await unlink(modulePath).catch(() => undefined);\n  }\n}\n\nasync function onlyImportsFarmConfigHelpers(\n  importer: string,\n  transform: EsbuildTransform,\n): Promise<boolean> {\n  try {\n    const source = readFileSync(importer, \"utf8\");\n    if (!source.includes(FARM_CORE_PACKAGE)) return false;\n\n    const transformed = await transform(source, {\n      format: \"esm\",\n      jsx: \"automatic\",\n      loader: getEsbuildLoader(importer),\n      sourcefile: importer,\n    });\n    const references = [...transformed.code.matchAll(FARM_CORE_REFERENCE_RE)];\n    if (references.length === 0) return false;\n\n    const safeImportRanges: Array<{ start: number; end: number }> = [];\n    for (const match of transformed.code.matchAll(FARM_CONFIG_HELPER_IMPORT_RE)) {\n      const specifiers = match[1]\n        .split(\",\")\n        .map((specifier) => specifier.trim())\n        .filter(Boolean);\n      if (\n        specifiers.length === 0 ||\n        !specifiers.every((specifier) => FARM_CONFIG_HELPER_SPECIFIER_RE.test(specifier))\n      ) {\n        continue;\n      }\n\n      const start = match.index ?? 0;\n      safeImportRanges.push({ start, end: start + match[0].length });\n    }\n\n    return references.every((reference) => {\n      const index = reference.index ?? -1;\n      return safeImportRanges.some((range) => index >= range.start && index < range.end);\n    });\n  } catch {\n    // Unsupported syntax or non-file importers retain the existing package resolution path.\n    return false;\n  }\n}\n\nfunction getEsbuildLoader(file: string): \"js\" | \"jsx\" | \"ts\" | \"tsx\" {\n  switch (path.extname(file)) {\n    case \".ts\":\n    case \".mts\":\n    case \".cts\":\n      return \"ts\";\n    case \".tsx\":\n      return \"tsx\";\n    case \".jsx\":\n      return \"jsx\";\n    default:\n      return \"js\";\n  }\n}\n\nfunction normalizeLayerEntries(value: unknown, owner: string): string[] {\n  if (value === undefined) return [];\n  if (!Array.isArray(value)) {\n    throw new TypeError(`${owner} \"extends\" must be an array of layer paths or package names`);\n  }\n\n  return value.map((entry, index) => {\n    if (typeof entry !== \"string\" || entry.trim() === \"\") {\n      throw new TypeError(`${owner} \"extends\" entry ${index} must be a non-empty string`);\n    }\n    return entry.trim();\n  });\n}\n\nfunction resolveLayerSource(\n  source: string,\n  ownerRoot: string,\n): { root: string; configFile?: string } {\n  if (isPathLayerSource(source)) {\n    const target = source.startsWith(\"file:\")\n      ? path.resolve(ownerRoot, source.slice(\"file:\".length))\n      : path.resolve(ownerRoot, source);\n    if (!existsSync(target)) {\n      throw new Error(`Cannot resolve Farm layer ${JSON.stringify(source)} from ${ownerRoot}`);\n    }\n\n    const stats = statSync(target);\n    const root = stats.isDirectory() ? target : path.dirname(target);\n    return {\n      root: normalizeRealPath(root),\n      configFile: stats.isFile() ? normalizeRealPath(target) : undefined,\n    };\n  }\n\n  const requireFromOwner = createRequire(path.join(ownerRoot, \"package.json\"));\n  let packageJsonPath: string | undefined;\n  try {\n    packageJsonPath = requireFromOwner.resolve(`${source}/package.json`);\n  } catch {\n    // Packages with an exports map often hide package.json. Resolve their entry and walk upward.\n  }\n\n  if (packageJsonPath) {\n    return { root: normalizeRealPath(path.dirname(packageJsonPath)) };\n  }\n\n  try {\n    const entryPath = requireFromOwner.resolve(source);\n    const packageRoot = findNearestPackageRoot(entryPath);\n    if (packageRoot) return { root: normalizeRealPath(packageRoot) };\n  } catch {\n    // Use the common error below so local and package failures have the same shape.\n  }\n\n  throw new Error(`Cannot resolve Farm layer package ${JSON.stringify(source)} from ${ownerRoot}`);\n}\n\nfunction findNearestPackageRoot(entryPath: string): string | null {\n  let current = statSync(entryPath).isDirectory() ? entryPath : path.dirname(entryPath);\n  while (true) {\n    if (existsSync(path.join(current, \"package.json\"))) return current;\n    const parent = path.dirname(current);\n    if (parent === current) return null;\n    current = parent;\n  }\n}\n\nfunction findFarmConfigFile(root: string, explicitPath?: string): string | undefined {\n  if (explicitPath) return explicitPath;\n  for (const fileName of CONFIG_FILENAMES) {\n    const candidate = path.join(root, fileName);\n    if (existsSync(candidate)) return candidate;\n  }\n  return undefined;\n}\n\nfunction getLayerName(source: string, root: string): string {\n  if (!isPathLayerSource(source)) {\n    const packageName = source.split(\"/\").filter(Boolean).pop();\n    if (packageName) return sanitizeLayerName(packageName);\n  }\n\n  try {\n    const packageJson = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\"));\n    if (typeof packageJson.name === \"string\") {\n      return sanitizeLayerName(packageJson.name.split(\"/\").pop() || packageJson.name);\n    }\n  } catch {\n    // A local layer does not need package metadata.\n  }\n\n  return sanitizeLayerName(path.basename(root));\n}\n\nfunction sanitizeLayerName(value: string): string {\n  const name = value\n    .trim()\n    .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n  if (!name) throw new Error(`Cannot derive a name for Farm layer ${JSON.stringify(value)}`);\n  return name;\n}\n\nfunction normalizeLayerSrcDir(value: unknown): string {\n  if (value === undefined) return \"src\";\n  if (typeof value !== \"string\" || value.trim() === \"\" || path.isAbsolute(value)) {\n    throw new TypeError(\"A Farm layer srcDir must be a non-empty relative path\");\n  }\n  const normalized = path.normalize(value.trim());\n  if (normalized === \"..\" || normalized.startsWith(`..${path.sep}`)) {\n    throw new TypeError(\"A Farm layer srcDir cannot leave the layer root\");\n  }\n  return normalized;\n}\n\nfunction getLayerDefaults(config: Record<string, any>): Record<string, any> {\n  return Object.fromEntries(\n    Object.entries(config).filter(\n      ([key, value]) =>\n        key !== \"extends\" && value !== undefined && !LAYER_LOCAL_CONFIG_KEYS.has(key),\n    ),\n  );\n}\n\nfunction mergeFarmLayerConfig(\n  base: Record<string, any>,\n  override: Record<string, any>,\n): Record<string, any> {\n  const output: Record<string, any> = { ...base };\n\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined || key === \"layers\") continue;\n\n    if (key === \"plugins\") {\n      output[key] = [...toArray(output[key]), ...toArray(value)];\n      continue;\n    }\n\n    if (key === \"middleware\" && output[key] !== undefined) {\n      output[key] = [...toArray(output[key]), ...toArray(value)];\n      continue;\n    }\n\n    if ((key === \"redirects\" || key === \"rewrites\" || key === \"headers\") && output[key]) {\n      output[key] = mergeConfigListResolvers(output[key], value);\n      continue;\n    }\n\n    if (isPlainObject(output[key]) && isPlainObject(value)) {\n      output[key] = mergePlainObjects(output[key], value);\n      continue;\n    }\n\n    output[key] = value;\n  }\n\n  return output;\n}\n\nfunction mergePlainObjects(base: Record<string, any>, override: Record<string, any>) {\n  const output: Record<string, any> = { ...base };\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined) continue;\n    output[key] =\n      isPlainObject(output[key]) && isPlainObject(value)\n        ? mergePlainObjects(output[key], value)\n        : value;\n  }\n  return output;\n}\n\nfunction mergeConfigListResolvers(base: unknown, override: unknown) {\n  return async () => [...(await resolveConfigList(base)), ...(await resolveConfigList(override))];\n}\n\nasync function resolveConfigList(value: unknown): Promise<any[]> {\n  const resolved = typeof value === \"function\" ? await value() : value;\n  return toArray(resolved);\n}\n\nfunction toArray(value: unknown): any[] {\n  if (value === undefined || value === null) return [];\n  return Array.isArray(value) ? value : [value];\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, any> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPathLayerSource(source: string): boolean {\n  return (\n    source.startsWith(\".\") ||\n    source.startsWith(\"/\") ||\n    source.startsWith(\"file:\") ||\n    /^[a-zA-Z]:[\\\\/]/.test(source)\n  );\n}\n\nfunction normalizeRealPath(value: string): string {\n  return path.resolve(realpathSync(value));\n}\n","/**\n * 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  return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeProgrammaticRoutePath(routePath))}`;\n}\n\nexport function parseProgrammaticRouteModuleId(moduleId: string): {\n  filePath: string;\n  kind: \"page\" | \"layout\" | \"api\";\n  routePath: string;\n} | null {\n  const queryIndex = moduleId.indexOf(\"?\");\n  if (queryIndex === -1) return null;\n\n  const filePath = moduleId.slice(0, queryIndex);\n  const params = new URLSearchParams(moduleId.slice(queryIndex + 1));\n  const value = params.get(\"farm-route\");\n  if (!value) return null;\n\n  const separator = value.indexOf(\":\");\n  if (separator === -1) return null;\n\n  const kind = value.slice(0, separator);\n  if (kind !== \"page\" && kind !== \"layout\" && kind !== \"api\") return null;\n\n  return {\n    filePath,\n    kind,\n    routePath: normalizeProgrammaticRoutePath(value.slice(separator + 1)),\n  };\n}\n\nexport function parseProgrammaticRoutePath(\n  routePath: string,\n  type: ParsedRoute[\"type\"] = \"page\",\n): ParsedRoute {\n  const fileName = type === \"layout\" ? \"layout.tsx\" : \"page.tsx\";\n  const normalized = normalizeProgrammaticRoutePath(routePath);\n  assertTerminalCatchAll(normalized);\n  assertUniqueRouteParameters(normalized);\n  const filePath =\n    normalized === \"/\" ? fileName : `${normalized.slice(1).replace(/\\/+$/, \"\")}/${fileName}`;\n\n  return {\n    filePath,\n    segments: normalized\n      .split(\"/\")\n      .filter(Boolean)\n      .filter((segment) => !(segment.startsWith(\"(\") && segment.endsWith(\")\")))\n      .map(parseRouteSegment),\n    type,\n  };\n}\n\nexport function scanProgrammaticPagePaths(source: string): string[] {\n  const paths = new Set<string>();\n\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 { emitFarmEvent } from \"./observability\";\nimport { notifyFarmCacheInvalidation, notifyFarmCacheTask } from \"./cache-invalidation\";\nimport { getActiveFarmI18nSnapshot } from \"./i18n/bridge\";\n\nexport { applyFarmCacheInvalidations } from \"./cache-invalidation\";\n\nexport type RevalidateTagProfile =\n  | \"max\"\n  | \"default\"\n  | \"seconds\"\n  | \"minutes\"\n  | \"hours\"\n  | \"days\"\n  | \"weeks\"\n  | \"months\"\n  | { expire?: number };\n\nexport interface FarmCacheOptions {\n  /**\n   * Tag cached data so it can be invalidated with revalidateTag/updateTag.\n   */\n  tags?: readonly string[];\n  /**\n   * Path tags let revalidatePath invalidate data tied to a route.\n   */\n  paths?: readonly string[];\n  /**\n   * Time in seconds before the entry becomes stale. False means no TTL.\n   */\n  revalidate?: number | false;\n}\n\nexport interface FarmCacheSetOptions extends FarmCacheOptions {\n  createdAt?: number;\n}\n\nexport type RouteDataCacheKey = string | readonly unknown[];\n\nexport type FarmCacheInvalidationTarget =\n  | { key: RouteDataCacheKey }\n  | { path: string }\n  | { tag: string };\n\ndeclare const FARM_DEFINED_CACHE_KEY_DATA: unique symbol;\n\n/**\n * A regular Farm cache key carrying the data shape stored under that key.\n *\n * The brand exists only in TypeScript. At runtime the value remains the\n * original string or structured array, so all existing cache APIs continue to\n * accept untyped keys.\n */\nexport type DefinedCacheKey<TData, TKey extends RouteDataCacheKey = RouteDataCacheKey> = TKey & {\n  readonly [FARM_DEFINED_CACHE_KEY_DATA]: TData;\n};\n\nexport type CacheKeyFactory<\n  TData,\n  TArguments extends readonly unknown[],\n  TKey extends RouteDataCacheKey = RouteDataCacheKey,\n> = (...args: TArguments) => DefinedCacheKey<TData, TKey>;\n\nexport type InferCacheKeyData<TKey> =\n  TKey extends DefinedCacheKey<infer TData, RouteDataCacheKey> ? TData : unknown;\n\n/**\n * Optionally add a data type to an existing string/array cache-key factory.\n *\n * This helper does not introduce a new runtime key representation. Calling the\n * returned factory produces the exact key returned by `factory`.\n */\nexport function defineCacheKey<TData>() {\n  return <const TArguments extends readonly unknown[], const TKey extends RouteDataCacheKey>(\n    factory: (...args: TArguments) => TKey,\n  ): CacheKeyFactory<TData, TArguments, TKey> => {\n    if (typeof factory !== \"function\") {\n      throw new TypeError(\"defineCacheKey expects a key factory function.\");\n    }\n\n    return ((...args: TArguments) => {\n      const key = factory(...args);\n      if (typeof key !== \"string\" && !Array.isArray(key)) {\n        throw new TypeError(\n          \"A defined cache key factory must return a string or structured array.\",\n        );\n      }\n      return key as DefinedCacheKey<TData, TKey>;\n    }) as CacheKeyFactory<TData, TArguments, TKey>;\n  };\n}\n\nexport interface FarmCacheEntry<T = unknown> {\n  key: string;\n  value: T;\n  tags: readonly string[];\n  /**\n   * Adapter tag versions captured before the cached value was produced.\n   * A later version makes the entry stale across every server instance.\n   */\n  tagVersions?: Readonly<Record<string, number>>;\n  createdAt: number;\n  createdVersion?: number;\n  revalidate?: number | false;\n}\n\ninterface InternalFarmCacheEntry<T = unknown> {\n  key: string;\n  value: T;\n  tags: Set<string>;\n  tagVersions?: Readonly<Record<string, number>>;\n  createdAt: number;\n  createdVersion: number;\n  revalidate?: number | false;\n}\n\n/**\n * Asynchronous persistence contract used by distributed Farm caches.\n *\n * Implementations are responsible for serializing cache entries and making\n * tag version updates atomic when the backing service supports it.\n */\nexport interface FarmCacheAdapter {\n  readonly name?: string;\n  get<T = unknown>(key: string): Promise<FarmCacheEntry<T> | null | undefined>;\n  set<T = unknown>(key: string, entry: FarmCacheEntry<T>): Promise<void>;\n  delete(key: string): Promise<void>;\n  clear?(): Promise<void>;\n  getTagVersions?(tags: readonly string[]): Promise<Readonly<Record<string, number>>>;\n  invalidateTags?(tags: readonly string[]): Promise<void>;\n  /** Atomically acquire a short-lived regeneration lease. */\n  acquireLease?(key: string, ttlMs: number): Promise<string | null | undefined>;\n  /** Release the lease only when the supplied ownership token still matches. */\n  releaseLease?(key: string, token: string): Promise<void>;\n}\n\nexport interface FarmClientCacheUserConfig {\n  /**\n   * Module path, relative to the project root, whose default export is a\n   * client cache adapter (`defineClientCacheAdapter`). The module is bundled\n   * into the browser entry; the server never imports it.\n   */\n  adapter?: string;\n  /** Extra version salt, typically a build or deploy id; entries persisted under another salt are dropped. */\n  version?: string;\n  /** Debounce for persisted write-behind flushes, in milliseconds. */\n  flushDelayMs?: number;\n}\n\nexport interface FarmCacheUserConfig {\n  /** Shared cache implementation, for example a Redis-backed adapter. */\n  adapter?: FarmCacheAdapter;\n  /** Prefix isolating applications and deployments sharing one adapter. */\n  namespace?: string;\n  /** Browser cache persistence; see the client cache adapter documentation. */\n  client?: FarmClientCacheUserConfig;\n  /**\n   * Coordinate cache fills across processes when the adapter implements\n   * acquireLease/releaseLease. Set false to disable.\n   */\n  lease?:\n    | false\n    | {\n        ttlMs?: number;\n        waitTimeoutMs?: number;\n        pollIntervalMs?: number;\n      };\n}\n\nexport interface FarmCacheStorage {\n  getItem<T = unknown>(key: string): Promise<T | null>;\n  setItem<T = unknown>(key: string, value: T): Promise<unknown>;\n  removeItem(key: string): Promise<unknown>;\n  clear?(base?: string): Promise<unknown>;\n}\n\nexport interface StorageFarmCacheAdapterOptions {\n  /** Prefix used inside the supplied storage client. */\n  base?: string;\n}\n\n/**\n * Adapt a Farm/unstorage-compatible key-value client to the cache contract.\n *\n * This is a portable baseline adapter. Provider-specific adapters should use\n * their atomic increment/transaction primitives for tag invalidation.\n */\nexport function storageCacheAdapter(\n  storage: FarmCacheStorage,\n  options: StorageFarmCacheAdapterOptions = {},\n): FarmCacheAdapter {\n  if (!storage || typeof storage.getItem !== \"function\" || typeof storage.setItem !== \"function\") {\n    throw new TypeError(\"storageCacheAdapter expects a compatible storage client.\");\n  }\n\n  const base = normalizeCacheNamespace(options.base || \"farm-cache\");\n  const entryKey = (key: string) => `${base}:entry:${key}`;\n  const tagKey = (tag: string) => `${base}:tag:${tag}`;\n\n  return {\n    name: \"storage\",\n    get: <T>(key: string) => storage.getItem<FarmCacheEntry<T>>(entryKey(key)),\n    set: async <T>(key: string, entry: FarmCacheEntry<T>) => {\n      await storage.setItem(entryKey(key), entry);\n    },\n    delete: async (key: string) => {\n      await storage.removeItem(entryKey(key));\n    },\n    clear: storage.clear\n      ? async () => {\n          await storage.clear!(base);\n        }\n      : undefined,\n    getTagVersions: async (tags) => {\n      const versions = await Promise.all(\n        tags.map(async (tag) => {\n          const value = await storage.getItem<number>(tagKey(tag));\n          return [tag, normalizeAdapterVersion(value)] as const;\n        }),\n      );\n      return Object.fromEntries(versions);\n    },\n    invalidateTags: async (tags) => {\n      await Promise.all(\n        tags.map(async (tag) => {\n          const key = tagKey(tag);\n          const current = normalizeAdapterVersion(await storage.getItem<number>(key));\n          await storage.setItem(key, Math.max(Date.now(), current + 1));\n        }),\n      );\n    },\n  };\n}\n\nexport interface GetFarmCacheEntryOptions {\n  allowStale?: boolean;\n  now?: number;\n}\n\ninterface FarmCacheStaleEntry {\n  tags: Iterable<string>;\n  createdAt: number;\n  createdVersion?: number;\n  revalidate?: number | false;\n}\n\nexport class FarmDataCache {\n  private entries = new Map<string, InternalFarmCacheEntry>();\n  private inflight = new Map<string, Promise<unknown>>();\n  private invalidatedTagVersions = new Map<string, number>();\n  private version = 0;\n  private generation = 0;\n  private adapter?: FarmCacheAdapter;\n  private namespace = \"farm\";\n  private local = true;\n  private lease = {\n    enabled: true,\n    ttlMs: 10_000,\n    waitTimeoutMs: 10_000,\n    pollIntervalMs: 25,\n  };\n\n  constructor(config: FarmCacheUserConfig = {}) {\n    this.configure(config);\n  }\n\n  configure(config: FarmCacheUserConfig = {}): void {\n    this.generation++;\n    this.entries.clear();\n    this.inflight.clear();\n    this.invalidatedTagVersions.clear();\n    this.version = 0;\n    this.adapter = config.adapter;\n    this.namespace = normalizeCacheNamespace(config.namespace || \"farm\");\n    this.local = !config.adapter;\n    this.lease =\n      config.lease === false\n        ? { ...this.lease, enabled: false }\n        : {\n            enabled: true,\n            ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 10_000, \"cache.lease.ttlMs\"),\n            waitTimeoutMs: normalizePositiveDuration(\n              config.lease?.waitTimeoutMs,\n              10_000,\n              \"cache.lease.waitTimeoutMs\",\n            ),\n            pollIntervalMs: normalizePositiveDuration(\n              config.lease?.pollIntervalMs,\n              25,\n              \"cache.lease.pollIntervalMs\",\n            ),\n          };\n  }\n\n  get adapterName(): string {\n    return this.adapter?.name || (this.adapter ? \"custom\" : \"memory\");\n  }\n\n  get hasAdapter(): boolean {\n    return this.adapter !== undefined;\n  }\n\n  get size(): number {\n    return this.entries.size;\n  }\n\n  get<T>(key: string, options: GetFarmCacheEntryOptions = {}): T | undefined {\n    return this.getEntry<T>(key, options)?.value;\n  }\n\n  getEntry<T = unknown>(\n    key: string,\n    options: GetFarmCacheEntryOptions = {},\n  ): FarmCacheEntry<T> | undefined {\n    const entry = this.entries.get(key) as InternalFarmCacheEntry<T> | undefined;\n    if (!entry) {\n      emitFarmEvent({ type: \"cache.miss\", key });\n      return undefined;\n    }\n\n    const stale = this.isStale(entry, options.now);\n    if (stale) {\n      emitFarmEvent({\n        type: \"cache.stale\",\n        key,\n        tags: Array.from(entry.tags),\n        revalidate: entry.revalidate,\n      });\n    }\n\n    if (!options.allowStale && stale) {\n      emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n      return undefined;\n    }\n\n    emitFarmEvent({\n      type: \"cache.hit\",\n      key,\n      tags: Array.from(entry.tags),\n      revalidate: entry.revalidate,\n      stale,\n    });\n\n    return this.toPublicEntry(entry);\n  }\n\n  async getEntryAsync<T = unknown>(\n    key: string,\n    options: GetFarmCacheEntryOptions = {},\n  ): Promise<FarmCacheEntry<T> | undefined> {\n    if (this.local) {\n      const localEntry = this.getEntry<T>(key, options);\n      if (localEntry) return localEntry;\n    }\n\n    if (!this.adapter) {\n      return this.local ? undefined : this.getEntry<T>(key, options);\n    }\n\n    const generation = this.generation;\n    const adapter = this.adapter;\n    const namespace = this.namespace;\n    const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n    if (generation !== this.generation) return undefined;\n    if (!entry) {\n      emitFarmEvent({ type: \"cache.miss\", key });\n      return undefined;\n    }\n\n    assertFarmCacheEntry(entry, key);\n    const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);\n    if (generation !== this.generation) return undefined;\n    if (stale) {\n      emitFarmEvent({\n        type: \"cache.stale\",\n        key,\n        tags: [...entry.tags],\n        revalidate: entry.revalidate,\n      });\n      if (!options.allowStale) {\n        emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n        return undefined;\n      }\n    }\n\n    emitFarmEvent({\n      type: \"cache.hit\",\n      key,\n      tags: [...entry.tags],\n      revalidate: entry.revalidate,\n      stale,\n    });\n\n    if (this.local && !stale) {\n      this.hydrateLocalEntry(entry);\n    }\n    return { ...entry, key };\n  }\n\n  set<T>(key: string, value: T, options: FarmCacheSetOptions = {}): FarmCacheEntry<T> {\n    const tags = new Set<string>();\n    for (const tag of options.tags ?? []) {\n      tags.add(normalizeCacheTag(tag));\n    }\n    for (const routePath of options.paths ?? []) {\n      tags.add(createPathCacheTag(routePath));\n    }\n\n    const entry: InternalFarmCacheEntry<T> = {\n      key,\n      value,\n      tags,\n      tagVersions: undefined,\n      createdAt: options.createdAt ?? Date.now(),\n      createdVersion: ++this.version,\n      revalidate: normalizeRevalidate(options.revalidate),\n    };\n\n    this.entries.set(key, entry);\n    emitFarmEvent({\n      type: \"cache.set\",\n      key,\n      tags: Array.from(tags),\n      revalidate: entry.revalidate,\n    });\n    return this.toPublicEntry(entry);\n  }\n\n  async setAsync<T>(\n    key: string,\n    value: T,\n    options: FarmCacheSetOptions = {},\n    tagVersions?: Readonly<Record<string, number>>,\n  ): Promise<FarmCacheEntry<T>> {\n    return this.writeAsync(key, value, options, tagVersions);\n  }\n\n  private async writeAsync<T>(\n    key: string,\n    value: T,\n    options: FarmCacheSetOptions,\n    tagVersions?: Readonly<Record<string, number>>,\n    createdVersion?: number,\n  ): Promise<FarmCacheEntry<T>> {\n    const tags = normalizeCacheOptionsTags(options);\n    const capturedVersions =\n      tagVersions ?? (await this.getAdapterTagVersions(Array.from(tags.values())));\n    const entry: FarmCacheEntry<T> = {\n      key,\n      value,\n      tags: Array.from(tags),\n      tagVersions: capturedVersions,\n      createdAt: options.createdAt ?? Date.now(),\n      createdVersion: createdVersion ?? ++this.version,\n      revalidate: normalizeRevalidate(options.revalidate),\n    };\n\n    if (this.local) {\n      this.hydrateLocalEntry(entry);\n    }\n    if (this.adapter) {\n      await this.adapter.set(this.createAdapterKey(key), entry);\n    }\n\n    emitFarmEvent({\n      type: \"cache.set\",\n      key,\n      tags: [...entry.tags],\n      revalidate: entry.revalidate,\n    });\n    return entry;\n  }\n\n  delete(key: string): boolean {\n    const deleted = this.entries.delete(key);\n    emitFarmEvent({ type: \"cache.delete\", key, deleted });\n    return deleted;\n  }\n\n  async deleteAsync(key: string): Promise<boolean> {\n    const deleted = this.entries.delete(key);\n    if (this.adapter) {\n      await this.adapter.delete(this.createAdapterKey(key));\n    }\n    emitFarmEvent({ type: \"cache.delete\", key, deleted: this.adapter ? true : deleted });\n    return this.adapter ? true : deleted;\n  }\n\n  clear(): void {\n    const count = this.entries.size;\n    this.generation++;\n    this.entries.clear();\n    this.inflight.clear();\n    this.invalidatedTagVersions.clear();\n    this.version = 0;\n    emitFarmEvent({ type: \"cache.clear\", count });\n  }\n\n  async clearAsync(): Promise<void> {\n    this.clear();\n    await this.adapter?.clear?.();\n  }\n\n  isStale(entry: FarmCacheStaleEntry, now = Date.now()): boolean {\n    if (\n      typeof entry.revalidate === \"number\" &&\n      entry.revalidate >= 0 &&\n      now - entry.createdAt >= entry.revalidate * 1000\n    ) {\n      return true;\n    }\n\n    for (const tag of entry.tags) {\n      const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));\n      if (\n        typeof invalidatedVersion === \"number\" &&\n        typeof entry.createdVersion === \"number\" &&\n        invalidatedVersion > entry.createdVersion\n      ) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  async isStaleAsync(entry: FarmCacheEntry, now = Date.now()): Promise<boolean> {\n    if (this.adapter) {\n      return this.isAdapterEntryStale(entry, now);\n    }\n    return this.isStale(entry, now);\n  }\n\n  revalidateTag(\n    tag: string,\n    options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n  ): number {\n    const normalized = normalizeCacheTag(tag);\n    const count = this.invalidateTag(normalized);\n    emitFarmEvent(\n      options.source === \"updateTag\"\n        ? { type: \"cache.updateTag\", tag: normalized, count }\n        : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n    );\n    return count;\n  }\n\n  async revalidateTagAsync(\n    tag: string,\n    options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n  ): Promise<number> {\n    const normalized = normalizeCacheTag(tag);\n    const count = this.invalidateTag(normalized);\n    await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);\n    emitFarmEvent(\n      options.source === \"updateTag\"\n        ? { type: \"cache.updateTag\", tag: normalized, count }\n        : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n    );\n    return count;\n  }\n\n  revalidatePath(routePath: string): number {\n    const normalizedPath = normalizeRevalidatePath(routePath);\n    const pathTag = createPathCacheTag(normalizedPath);\n    const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n    const count = this.invalidateTag(pathTag);\n    emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n    if (pprCount > 0) {\n      emitFarmEvent({\n        type: \"ppr.shell.invalidated\",\n        route: normalizedPath,\n        reason: \"revalidatePath\",\n        count: pprCount,\n      });\n    }\n\n    return count;\n  }\n\n  async revalidatePathAsync(routePath: string): Promise<number> {\n    const normalizedPath = normalizeRevalidatePath(routePath);\n    const pathTag = createPathCacheTag(normalizedPath);\n    const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n    const count = this.invalidateTag(pathTag);\n    await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);\n    emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n    if (pprCount > 0) {\n      emitFarmEvent({\n        type: \"ppr.shell.invalidated\",\n        route: normalizedPath,\n        reason: \"revalidatePath\",\n        count: pprCount,\n      });\n    }\n\n    return count;\n  }\n\n  async getOrSet<T>(\n    key: string,\n    producer: () => Promise<T> | T,\n    options: FarmCacheOptions = {},\n  ): Promise<T> {\n    const cached = await this.getEntryAsync<T>(key);\n    if (cached) {\n      return cached.value;\n    }\n\n    const inflight = this.inflight.get(key) as Promise<T> | undefined;\n    if (inflight) {\n      emitFarmEvent({ type: \"cache.dedupe\", key });\n      return inflight;\n    }\n\n    const tags = Array.from(normalizeCacheOptionsTags(options));\n    const generation = this.generation;\n    const promise = this.fillCacheEntry(key, producer, options, tags, generation)\n      .catch((error) => {\n        emitFarmEvent({ type: \"cache.error\", key, operation: \"set\", error });\n        throw error;\n      })\n      .finally(() => {\n        if (this.inflight.get(key) === promise) {\n          this.inflight.delete(key);\n        }\n      });\n\n    this.inflight.set(key, promise);\n    return promise;\n  }\n\n  private async fillCacheEntry<T>(\n    key: string,\n    producer: () => Promise<T> | T,\n    options: FarmCacheOptions,\n    tags: readonly string[],\n    generation: number,\n  ): Promise<T> {\n    const adapter = this.adapter;\n    const namespace = this.namespace;\n    const lease = { ...this.lease };\n    const leaseKey = `${namespace}:lease:${key}`;\n    let leaseToken: string | null | undefined;\n\n    if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {\n      leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n      if (!leaseToken) {\n        const shared = await this.waitForAdapterEntry<T>(\n          key,\n          adapter,\n          namespace,\n          lease,\n          generation,\n        );\n        if (shared) {\n          emitFarmEvent({ type: \"cache.dedupe\", key });\n          return shared.value;\n        }\n        if (generation === this.generation) {\n          leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);\n        }\n      }\n    }\n\n    try {\n      const initialCreatedVersion = this.version;\n      const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);\n      const value = await producer();\n      if (generation === this.generation) {\n        await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);\n      }\n      return value;\n    } finally {\n      if (leaseToken && adapter?.releaseLease) {\n        await adapter.releaseLease(leaseKey, leaseToken);\n      }\n    }\n  }\n\n  private async waitForAdapterEntry<T>(\n    key: string,\n    adapter: FarmCacheAdapter,\n    namespace: string,\n    lease: typeof this.lease,\n    generation: number,\n  ): Promise<FarmCacheEntry<T> | undefined> {\n    const deadline = Date.now() + lease.waitTimeoutMs;\n    while (Date.now() < deadline) {\n      await delay(lease.pollIntervalMs);\n      if (generation !== this.generation) return undefined;\n      const entry = await adapter.get<T>(`${namespace}:entry:${key}`);\n      if (generation !== this.generation) return undefined;\n      if (!entry) {\n        emitFarmEvent({ type: \"cache.miss\", key });\n        continue;\n      }\n      assertFarmCacheEntry(entry, key);\n      const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);\n      if (generation !== this.generation) return undefined;\n      if (stale) {\n        emitFarmEvent({\n          type: \"cache.stale\",\n          key,\n          tags: [...entry.tags],\n          revalidate: entry.revalidate,\n        });\n        emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n      } else {\n        emitFarmEvent({\n          type: \"cache.hit\",\n          key,\n          tags: [...entry.tags],\n          revalidate: entry.revalidate,\n          stale: false,\n        });\n        return { ...entry, key };\n      }\n    }\n    return undefined;\n  }\n\n  private countEntriesForTag(tag: string): number {\n    let count = 0;\n    for (const entry of this.entries.values()) {\n      if (entry.tags.has(tag)) {\n        count++;\n      }\n    }\n    return count;\n  }\n\n  private countEntriesForTags(tags: readonly string[]): number {\n    let count = 0;\n    for (const entry of this.entries.values()) {\n      if (tags.every((tag) => entry.tags.has(tag))) {\n        count++;\n      }\n    }\n    return count;\n  }\n\n  private invalidateTag(normalizedTag: string): number {\n    this.invalidatedTagVersions.set(normalizedTag, ++this.version);\n    return this.countEntriesForTag(normalizedTag);\n  }\n\n  private toPublicEntry<T>(entry: InternalFarmCacheEntry<T>): FarmCacheEntry<T> {\n    return {\n      key: entry.key,\n      value: entry.value,\n      tags: Array.from(entry.tags),\n      tagVersions: entry.tagVersions,\n      createdAt: entry.createdAt,\n      createdVersion: entry.createdVersion,\n      revalidate: entry.revalidate,\n    };\n  }\n\n  private hydrateLocalEntry<T>(entry: FarmCacheEntry<T>): void {\n    this.entries.set(entry.key, {\n      key: entry.key,\n      value: entry.value,\n      tags: new Set(entry.tags.map(normalizeCacheTag)),\n      tagVersions: entry.tagVersions,\n      createdAt: entry.createdAt,\n      createdVersion: entry.createdVersion ?? ++this.version,\n      revalidate: normalizeRevalidate(entry.revalidate),\n    });\n  }\n\n  private createAdapterKey(key: string): string {\n    return `${this.namespace}:entry:${key}`;\n  }\n\n  private createAdapterTag(tag: string): string {\n    return `${this.namespace}:tag:${tag}`;\n  }\n\n  private async getAdapterTagVersions(\n    tags: readonly string[],\n    adapter = this.adapter,\n    namespace = this.namespace,\n  ): Promise<Readonly<Record<string, number>>> {\n    if (!adapter?.getTagVersions || tags.length === 0) return {};\n\n    const normalized = tags.map(normalizeCacheTag);\n    const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);\n    const versions = await adapter.getTagVersions(physicalTags);\n    return Object.fromEntries(\n      normalized.map((tag, index) => [\n        tag,\n        normalizeAdapterVersion(versions[physicalTags[index]!]),\n      ]),\n    );\n  }\n\n  private async isAdapterEntryStale(\n    entry: FarmCacheEntry,\n    now = Date.now(),\n    adapter = this.adapter,\n    namespace = this.namespace,\n  ): Promise<boolean> {\n    if (\n      typeof entry.revalidate === \"number\" &&\n      entry.revalidate >= 0 &&\n      now - entry.createdAt >= entry.revalidate * 1000\n    ) {\n      return true;\n    }\n\n    const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);\n    for (const tag of entry.tags) {\n      if (\n        normalizeAdapterVersion(currentVersions[tag]) >\n        normalizeAdapterVersion(entry.tagVersions?.[tag])\n      ) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n\nconst FARM_DATA_CACHE_SYMBOL = Symbol.for(\"farm.dataCache\");\nconst farmDataCacheGlobal = globalThis as typeof globalThis & {\n  [FARM_DATA_CACHE_SYMBOL]?: FarmDataCache;\n};\nconst sharedFarmDataCache = (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ??= new FarmDataCache());\n\nexport function getFarmDataCache(): FarmDataCache {\n  return sharedFarmDataCache;\n}\n\nexport function configureFarmCache(config: FarmCacheUserConfig | undefined): void {\n  sharedFarmDataCache.configure(config);\n}\n\n/**\n * Wrap an async function so its results are cached and shared across requests,\n * processes, and restarts.\n *\n * The cache key is built from the wrapped function's identity (its name and a\n * hash of its source), the active locale, `keyParts`, and the call arguments.\n * Deriving identity from the source — rather than the closure instance — is\n * deliberate: it keeps the key stable across processes and restarts so a\n * distributed cache adapter can share entries between server instances.\n *\n * The consequence is that two closures with **identical source text but\n * different captured variables** produce the same identity. Pass those captured\n * values in `keyParts` so they take part in the key; otherwise the closures\n * share a cache entry and return each other's data:\n *\n * ```ts\n * // Collides: both closures have identical source, and `table` is captured,\n * // not an argument, so it never reaches the key.\n * const makeLoader = (table: string) =>\n *   unstable_cache(async (id: number) => db.get(table, id));\n *\n * // Correct: the captured value disambiguates the two closures.\n * const makeLoader = (table: string) =>\n *   unstable_cache(async (id: number) => db.get(table, id), [table]);\n * ```\n *\n * Values passed as call arguments already participate in the key and do not\n * need to be repeated in `keyParts`.\n *\n * @param fn The async function to memoize.\n * @param keyParts Extra values that identify this call site. Include every\n *   variable the function closes over that is not one of its arguments.\n * @param options Tags, paths, and revalidation settings for the cached entry.\n */\nexport function unstable_cache<Args extends unknown[], Result>(\n  fn: (...args: Args) => Result | Promise<Result>,\n  keyParts: readonly unknown[] = [],\n  options: FarmCacheOptions = {},\n): (...args: Args) => Promise<Result> {\n  return async (...args: Args): Promise<Result> => {\n    const locale = getActiveFarmI18nSnapshot()?.locale;\n    const key = createFarmCacheKey([\n      \"unstable_cache\",\n      getFunctionCacheIdentity(fn),\n      locale ? [\"locale\", locale] : null,\n      keyParts,\n      args,\n    ]);\n    return getFarmDataCache().getOrSet<Result>(key, () => fn(...args), options);\n  };\n}\n\n/**\n * Invalidate every cache entry carrying `tag`.\n *\n * Observability note: the `count` on the emitted `cache.revalidateTag` event is\n * derived from Farm's process-local entry tracking. With a shared `cache.adapter`\n * configured, entries live in the adapter rather than in local memory, so the\n * count can read as `0` even though the invalidation is still propagated to the\n * adapter and applied. Treat it as a best-effort signal, not a distributed count.\n */\nexport function revalidateTag(_tag: string, _profile?: RevalidateTagProfile): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache\n      .revalidateTagAsync(_tag, {\n        source: \"revalidateTag\",\n        profile: _profile,\n      })\n      .then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidateTag(_tag, {\n    source: \"revalidateTag\",\n    profile: _profile,\n  });\n}\n\nexport function updateTag(tag: string): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache.revalidateTagAsync(tag, { source: \"updateTag\" }).then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidateTag(tag, { source: \"updateTag\" });\n}\n\n/**\n * Invalidate cached data for a route path (and its PPR shell, if any).\n *\n * Observability note: the `count` on the emitted `cache.revalidatePath` event and\n * the `ppr.shell.invalidated` event are derived from process-local entry tracking.\n * With a shared `cache.adapter`, PPR shells live in the adapter rather than in\n * local memory, so the count can read as `0` and `ppr.shell.invalidated` may not\n * be emitted even though the invalidation is still propagated to the adapter and\n * applied.\n */\nexport function revalidatePath(routePath: string): void | Promise<void> {\n  const cache = getFarmDataCache();\n  if (cache.hasAdapter) {\n    const task = cache.revalidatePathAsync(routePath).then(() => undefined);\n    notifyFarmCacheTask(task);\n    return task;\n  }\n  cache.revalidatePath(routePath);\n}\n\nexport function invalidate(key: RouteDataCacheKey): void | Promise<void> {\n  const clientKey = createRouteDataCacheKey(key);\n  const task = updateTag(createRouteDataCacheTag(key));\n  notifyFarmCacheInvalidation(clientKey);\n  return task;\n}\n\nexport function invalidateRouteData(key: RouteDataCacheKey): void | Promise<void> {\n  return invalidate(key);\n}\n\n/**\n * Apply a normalized set of invalidation targets and return browser cache keys\n * that should be carried with an action/endpoint response.\n */\nexport async function applyFarmCacheInvalidationTargets(\n  targets: readonly FarmCacheInvalidationTarget[],\n): Promise<readonly string[]> {\n  if (!Array.isArray(targets)) {\n    throw new TypeError(\"Cache invalidations must resolve to an array of targets.\");\n  }\n\n  const clientKeys: string[] = [];\n  for (const target of targets) {\n    assertFarmCacheInvalidationTarget(target);\n    if (\"key\" in target) {\n      await invalidate(target.key);\n      clientKeys.push(createRouteDataCacheKey(target.key));\n    } else if (\"path\" in target) {\n      await revalidatePath(target.path);\n    } else {\n      await updateTag(target.tag);\n    }\n  }\n  return Array.from(new Set(clientKeys));\n}\n\nexport function createPathCacheTag(routePath: string): string {\n  return `path:${normalizeRevalidatePath(routePath)}`;\n}\n\nexport function createRouteDataCacheTag(key: RouteDataCacheKey): string {\n  return `route-data:${createRouteDataCacheKey(key)}`;\n}\n\nexport function createRouteDataCacheKey(key: RouteDataCacheKey): string {\n  return createFarmCacheKey(Array.isArray(key) ? key : [key]);\n}\n\nexport function normalizeRevalidatePath(routePath: string): string {\n  if (typeof routePath !== \"string\") {\n    throw new TypeError(\"revalidatePath expects a path string.\");\n  }\n\n  let normalized = routePath.trim();\n  if (!normalized) {\n    throw new Error(\"revalidatePath expects a non-empty path.\");\n  }\n\n  try {\n    if (/^https?:\\/\\//i.test(normalized)) {\n      normalized = new URL(normalized).pathname;\n    }\n  } catch {\n    // Keep the original path if URL parsing fails.\n  }\n\n  normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;\n  normalized = normalized.startsWith(\"/\") ? normalized : `/${normalized}`;\n  normalized = normalized.replace(/\\/{2,}/g, \"/\");\n  if (normalized.length > 1) {\n    normalized = normalized.replace(/\\/+$/, \"\");\n  }\n  return normalized || \"/\";\n}\n\nexport function createFarmCacheKey(parts: readonly unknown[]): string {\n  return stableSerialize(parts);\n}\n\nfunction normalizeRevalidate(revalidate: number | false | undefined): number | false | undefined {\n  if (revalidate === false || revalidate === undefined) {\n    return revalidate;\n  }\n  if (!Number.isFinite(revalidate) || revalidate < 0) {\n    return undefined;\n  }\n  // 0 is meaningful: the entry is stale immediately, i.e. always re-produced.\n  return revalidate;\n}\n\nfunction normalizeCacheTag(tag: string): string {\n  if (typeof tag !== \"string\") {\n    throw new TypeError(\"Cache tags must be strings.\");\n  }\n  const normalized = tag.trim();\n  if (!normalized) {\n    throw new Error(\"Cache tags cannot be empty.\");\n  }\n  return normalized;\n}\n\nfunction normalizeCacheNamespace(namespace: string): string {\n  if (typeof namespace !== \"string\") {\n    throw new TypeError(\"Cache namespace must be a string.\");\n  }\n  const normalized = namespace.trim().replace(/:+$/g, \"\");\n  if (!normalized) {\n    throw new Error(\"Cache namespace cannot be empty.\");\n  }\n  return normalized;\n}\n\nfunction normalizeAdapterVersion(value: unknown): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\n}\n\nfunction normalizePositiveDuration(\n  value: number | undefined,\n  fallback: number,\n  name: string,\n): number {\n  if (value === undefined) return fallback;\n  if (!Number.isFinite(value) || value <= 0) {\n    throw new TypeError(`${name} must be a positive number of milliseconds.`);\n  }\n  return Math.floor(value);\n}\n\nfunction delay(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction normalizeCacheOptionsTags(options: FarmCacheOptions): Set<string> {\n  const tags = new Set<string>();\n  for (const tag of options.tags ?? []) {\n    tags.add(normalizeCacheTag(tag));\n  }\n  for (const routePath of options.paths ?? []) {\n    tags.add(createPathCacheTag(routePath));\n  }\n  return tags;\n}\n\nfunction assertFarmCacheEntry(\n  entry: FarmCacheEntry,\n  expectedKey: string,\n): asserts entry is FarmCacheEntry {\n  if (\n    !entry ||\n    typeof entry !== \"object\" ||\n    entry.key !== expectedKey ||\n    !Array.isArray(entry.tags) ||\n    typeof entry.createdAt !== \"number\"\n  ) {\n    throw new TypeError(\n      `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`,\n    );\n  }\n}\n\nfunction assertFarmCacheInvalidationTarget(\n  target: unknown,\n): asserts target is FarmCacheInvalidationTarget {\n  if (!target || typeof target !== \"object\") {\n    throw new TypeError(\"Cache invalidation targets must be { key }, { path }, or { tag }.\");\n  }\n\n  if (\"key\" in target) {\n    const key = (target as { key?: unknown }).key;\n    if (typeof key === \"string\" || Array.isArray(key)) return;\n  } else if (\"path\" in target && typeof (target as { path?: unknown }).path === \"string\") {\n    return;\n  } else if (\"tag\" in target && typeof (target as { tag?: unknown }).tag === \"string\") {\n    return;\n  }\n\n  throw new TypeError(\"Cache invalidation targets must contain a string/array key, path, or tag.\");\n}\n\nfunction getFunctionCacheIdentity(fn: Function): string {\n  // The name alone collides across modules — two different functions both\n  // named getUser would share cache entries. Include a hash of the source so\n  // only genuinely identical functions share, and the identity stays stable\n  // across processes and restarts.\n  const name = fn.name || \"anonymous\";\n  return `${name}:${hashFunctionSource(String(fn))}`;\n}\n\nfunction hashFunctionSource(source: string): string {\n  // FNV-1a, 32-bit.\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < source.length; index++) {\n    hash ^= source.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(36);\n}\n\nfunction compareCodepoint(a: string, b: string): number {\n  return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction serializeBinaryBytes(bytes: Uint8Array): string {\n  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction serializeCanonicalStringEntries(\n  entries: Iterable<readonly [string, string]>,\n  seen: WeakSet<object>,\n): string {\n  const valuesByKey = new Map<string, string[]>();\n  for (const [key, item] of entries) {\n    const values = valuesByKey.get(key);\n    if (values) values.push(item);\n    else valuesByKey.set(key, [item]);\n  }\n\n  return Array.from(valuesByKey.keys())\n    .sort(compareCodepoint)\n    .flatMap((key) =>\n      valuesByKey\n        .get(key)!\n        .map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`),\n    )\n    .join(\",\");\n}\n\nfunction stableSerialize(value: unknown, seen = new WeakSet<object>()): string {\n  if (value === null) return \"null\";\n  if (value === undefined) return \"undefined\";\n\n  const valueType = typeof value;\n  if (valueType === \"string\") return JSON.stringify(value);\n  if (valueType === \"number\" || valueType === \"boolean\" || valueType === \"bigint\") {\n    return `${valueType}:${String(value)}`;\n  }\n  if (valueType === \"symbol\") {\n    return `symbol:${String(value)}`;\n  }\n  if (valueType === \"function\") {\n    return `function:${getFunctionCacheIdentity(value as Function)}`;\n  }\n\n  if (value instanceof Date) {\n    // toISOString throws on an Invalid Date. Key building must not throw on a\n    // supported type, so all invalid dates share one stable marker and the\n    // caller's own validation decides what to do with the input.\n    return Number.isNaN(value.getTime()) ? \"date:invalid\" : `date:${value.toISOString()}`;\n  }\n  if (value instanceof URL) {\n    return `url:${value.toString()}`;\n  }\n  if (value instanceof RegExp) {\n    return `regexp:${value.toString()}`;\n  }\n  if (value instanceof ArrayBuffer) {\n    return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n  }\n  if (typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer) {\n    return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;\n  }\n  if (ArrayBuffer.isView(value)) {\n    const viewType = Object.prototype.toString.call(value).slice(8, -1);\n    const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n    return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;\n  }\n\n  if (value && typeof value === \"object\") {\n    if (seen.has(value)) {\n      return \"[Circular]\";\n    }\n    seen.add(value);\n\n    if (Array.isArray(value)) {\n      const items: string[] = [];\n      for (let index = 0; index < value.length; index++) {\n        items.push(\n          Object.prototype.hasOwnProperty.call(value, index)\n            ? stableSerialize(value[index], seen)\n            : \"[Hole]\",\n        );\n      }\n      seen.delete(value);\n      return `[${items.join(\",\")}]`;\n    }\n\n    // Set and Map keep their contents internally, so Object.entries is empty\n    // for both. Serialize the contents and sort them by codepoint so equal\n    // contents give the same key regardless of insertion order.\n    if (value instanceof Set) {\n      const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);\n      seen.delete(value);\n      return `set:[${items.join(\",\")}]`;\n    }\n    if (value instanceof Map) {\n      const items = Array.from(\n        value,\n        ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`,\n      ).sort(compareCodepoint);\n      seen.delete(value);\n      return `map:[${items.join(\",\")}]`;\n    }\n    // URLSearchParams and Headers keep their contents internally, so\n    // Object.entries is empty for both (same rationale as Set/Map above).\n    // Canonicalize key order while preserving the order of repeated values for\n    // each key. URLSearchParams treats `a=1&a=2` and `a=2&a=1` as observably\n    // different inputs, while `b=2&a=1` and `a=1&b=2` should still share a key.\n    if (value instanceof URLSearchParams) {\n      const serialized = serializeCanonicalStringEntries(value, seen);\n      seen.delete(value);\n      return `urlsearchparams:[${serialized}]`;\n    }\n    if (value instanceof Headers) {\n      const serialized = serializeCanonicalStringEntries(value, seen);\n      seen.delete(value);\n      return `headers:[${serialized}]`;\n    }\n\n    // Codepoint comparison, not localeCompare: the host locale must not\n    // change how a \"stable\" key serializes, or invalidations computed on one\n    // server can miss entries written by another.\n    const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>\n      compareCodepoint(a, b),\n    );\n    const serialized = entries\n      .map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`)\n      .join(\",\");\n\n    seen.delete(value);\n    return `{${serialized}}`;\n  }\n\n  return String(value);\n}\n","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  return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeRoutePath(routePath))}`;\n}\n\nexport function parseProgrammaticRouteModuleId(moduleId: string): {\n  filePath: string;\n  kind: \"page\" | \"layout\" | \"api\";\n  routePath: string;\n} | null {\n  const queryIndex = moduleId.indexOf(\"?\");\n  if (queryIndex === -1) {\n    return null;\n  }\n\n  const filePath = moduleId.slice(0, queryIndex);\n  const params = new URLSearchParams(moduleId.slice(queryIndex + 1));\n  const value = params.get(\"farm-route\");\n  if (!value) {\n    return null;\n  }\n\n  const separator = value.indexOf(\":\");\n  if (separator === -1) {\n    return null;\n  }\n\n  const kind = value.slice(0, separator);\n  if (kind !== \"page\" && kind !== \"layout\" && kind !== \"api\") {\n    return null;\n  }\n\n  return {\n    filePath,\n    kind,\n    routePath: normalizeRoutePath(value.slice(separator + 1)),\n  };\n}\n\nexport function parseProgrammaticRoutePath(\n  routePath: string,\n  type: ParsedRoute[\"type\"] = \"page\",\n): ParsedRoute {\n  return parseSharedProgrammaticRoutePath(routePath, type);\n}\n\nexport function createRouteModuleFromProgrammaticPage(\n  route: ProgrammaticPageRoute,\n  rendererRuntime?: Pick<FarmServerRendererRuntime, \"createElement\" | \"Suspense\">,\n): RouteModule {\n  const mod: RouteModule = {\n    default: createProgrammaticPageComponent(route, rendererRuntime),\n    ...normalizeFarmRouteRuntimeConfig(route, `Route \"${route.path}\"`),\n  };\n\n  if (route.params || route.search || route.guard || route.data) {\n    (mod as any).__farmRouteSchemas = {\n      params: route.params,\n      search: getProgrammaticRouteSearchSchema(route.search),\n    };\n    (mod as any).__farmRouteSearch = getProgrammaticRouteSearchClientOptions(route.search);\n    (mod as any).__farmRouteGuard = route.guard;\n    (mod as any).__farmRouteData = route.data;\n    (mod as any).__farmRouteParsesProps = true;\n    (mod as any).__farmResolveRouteProps = (props: PageProps) =>\n      resolveProgrammaticRouteProps(route, props);\n    (mod as any).__farmResolveRouteCanonicalPath = (\n      rawSearch: ProgrammaticRouteSearchFallback,\n      path: string,\n    ) => resolveProgrammaticRouteSearch(route.search, rawSearch, path, route.path).canonicalPath;\n  }\n\n  if (route.pending || route.error || route.notFound) {\n    (mod as any).__farmRouteComponents = {\n      pending: route.pending,\n      error: route.error,\n      notFound: route.notFound,\n    };\n  }\n\n  if (route.render === \"static\" || route.staticPaths) {\n    mod.ssg = true;\n    mod.dynamic = \"force-static\";\n  } else if (route.render === \"dynamic\") {\n    mod.ssg = false;\n    mod.dynamic = \"force-dynamic\";\n  }\n\n  if (typeof route.revalidate !== \"undefined\") {\n    mod.revalidate = route.revalidate;\n  }\n\n  if (route.ppr) {\n    mod.ppr = true;\n  }\n\n  if (route.metadata) {\n    mod.metadata = route.metadata;\n  }\n\n  if (route.generateMetadata) {\n    mod.generateMetadata = route.generateMetadata;\n  }\n\n  if (route.staticPaths) {\n    mod.getStaticPaths = async () => normalizeStaticPaths(route.path, await route.staticPaths!());\n  }\n\n  return mod;\n}\n\nexport function createLayoutModuleFromProgrammaticLayout(route: ProgrammaticLayoutRoute) {\n  return {\n    default: route.component,\n    ...normalizeFarmRouteRuntimeConfig(route, `Layout \"${route.path}\"`),\n    metadata: route.metadata,\n    generateMetadata: route.generateMetadata,\n  };\n}\n\nexport function scanProgrammaticPagePaths(source: string): string[] {\n  const paths = new Set<string>();\n\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","/**\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  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/**\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 {\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 { 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 type {\n  AnyFieldBuilder,\n  AnyModelDefinition,\n  FieldBuilder,\n  JsonValue,\n  ModelDefinition,\n  OrmClient,\n  SchemaDefinition,\n  SchemaModels,\n} from \"@farming-labs/orm\";\nimport type {\n  FarmIntegrationSchema,\n  FarmIntegrationSchemaField,\n  FarmIntegrationSchemaModel,\n} from \"./integrations\";\nimport { resolveStorageRuntimeClient } from \"./storage\";\nimport type { FarmStorageUserConfig } from \"./storage/types\";\nimport type { FarmConfig } from \"./types\";\n\ntype RuntimeClientFactory<TClient> = () => TClient | Promise<TClient>;\n\nexport type FarmIntegrationOrmSchema = SchemaDefinition<Record<string, AnyModelDefinition>>;\n\nexport type FarmIntegrationOrmClient<TSchema extends FarmIntegrationOrmSchema> = OrmClient<TSchema>;\n\ntype FarmIntegrationOrmFieldKind<TField extends FarmIntegrationSchemaField> = TField[\"type\"] extends\n  | \"id\"\n  | \"uuid\"\n  ? \"id\"\n  : TField[\"type\"] extends \"text\"\n    ? \"string\"\n    : TField[\"type\"] extends \"number\"\n      ? \"decimal\"\n      : Extract<TField[\"type\"], \"string\" | \"boolean\" | \"integer\" | \"datetime\" | \"json\" | \"enum\">;\n\ntype FarmIntegrationOrmFieldNullable<TField extends FarmIntegrationSchemaField> = TField extends {\n  nullable: true;\n}\n  ? true\n  : TField extends { required: false }\n    ? true\n    : false;\n\ntype FarmIntegrationOrmEnumValue<TField extends FarmIntegrationSchemaField> = TField extends {\n  values: readonly (infer TValue extends string)[];\n}\n  ? TValue\n  : string;\n\ntype FarmIntegrationOrmFieldValue<TField extends FarmIntegrationSchemaField> =\n  TField[\"type\"] extends \"id\" | \"uuid\" | \"string\" | \"text\"\n    ? string\n    : TField[\"type\"] extends \"boolean\"\n      ? boolean\n      : TField[\"type\"] extends \"integer\"\n        ? number\n        : TField[\"type\"] extends \"number\"\n          ? string\n          : TField[\"type\"] extends \"datetime\"\n            ? Date\n            : TField[\"type\"] extends \"json\"\n              ? JsonValue\n              : TField[\"type\"] extends \"enum\"\n                ? FarmIntegrationOrmEnumValue<TField>\n                : never;\n\nexport type InferFarmIntegrationOrmField<TField extends FarmIntegrationSchemaField> = FieldBuilder<\n  FarmIntegrationOrmFieldKind<TField>,\n  FarmIntegrationOrmFieldNullable<TField>,\n  FarmIntegrationOrmFieldValue<TField>\n>;\n\nexport type InferFarmIntegrationOrmFields<TModel extends FarmIntegrationSchemaModel> = {\n  [TFieldKey in keyof TModel[\"fields\"] & string]: InferFarmIntegrationOrmField<\n    Extract<TModel[\"fields\"][TFieldKey], FarmIntegrationSchemaField>\n  >;\n};\n\nexport type InferFarmIntegrationOrmSchema<TSchema extends FarmIntegrationSchema> =\n  SchemaDefinition<{\n    [TModelKey in keyof TSchema[\"models\"] & string]: ModelDefinition<\n      InferFarmIntegrationOrmFields<\n        Extract<TSchema[\"models\"][TModelKey], FarmIntegrationSchemaModel>\n      >,\n      {}\n    >;\n  }>;\n\nexport type InferFarmIntegrationOrmClient<TSchema extends FarmIntegrationSchema | undefined> =\n  TSchema extends FarmIntegrationSchema ? OrmClient<InferFarmIntegrationOrmSchema<TSchema>> : never;\n\nexport interface CreateIntegrationOrmOptions<\n  TClient = unknown,\n  TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n> {\n  schema: TSchema;\n  config?: Pick<FarmConfig, \"storage\">;\n  storage?: FarmStorageUserConfig;\n  client?: TClient | RuntimeClientFactory<TClient>;\n}\n\nexport async function createIntegrationOrm<\n  TClient = unknown,\n  TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n>(\n  options: CreateIntegrationOrmOptions<TClient, TSchema>,\n): Promise<InferFarmIntegrationOrmClient<TSchema>> {\n  const [schema, client] = await Promise.all([\n    farmIntegrationSchemaToOrmSchema(options.schema),\n    resolveIntegrationOrmRuntimeClient(options),\n  ]);\n\n  if (!client) {\n    throw new Error(\n      \"Schema-backed integration storage requires a runtime client at farm.config storage.client.\",\n    );\n  }\n\n  const { createOrmFromRuntime } = await import(\"@farming-labs/orm-runtime\");\n  return createOrmFromRuntime({\n    schema,\n    client,\n  }) as Promise<InferFarmIntegrationOrmClient<TSchema>>;\n}\n\nexport async function resolveIntegrationOrmRuntimeClient<TClient = unknown>(\n  options: Omit<CreateIntegrationOrmOptions<TClient>, \"schema\">,\n): Promise<TClient | unknown | undefined> {\n  if (options.client !== undefined) {\n    return typeof options.client === \"function\"\n      ? await (options.client as RuntimeClientFactory<TClient>)()\n      : options.client;\n  }\n\n  return resolveStorageRuntimeClient(options.storage ?? options.config?.storage);\n}\n\nexport async function farmIntegrationSchemaToOrmSchema(\n  schema: FarmIntegrationSchema,\n): Promise<FarmIntegrationOrmSchema> {\n  const orm = await import(\"@farming-labs/orm\");\n  const models: Record<string, AnyModelDefinition> = {};\n\n  for (const [modelKey, modelSchema] of Object.entries(schema.models)) {\n    models[modelKey] = orm.model({\n      table: modelSchema.name ?? modelKey,\n      fields: createOrmModelFields(orm, modelSchema),\n      constraints: createOrmModelConstraints(modelSchema),\n      description: modelSchema.description,\n    }) as AnyModelDefinition;\n  }\n\n  return orm.defineSchema(models) as FarmIntegrationOrmSchema;\n}\n\nfunction createOrmModelFields(\n  orm: typeof import(\"@farming-labs/orm\"),\n  modelSchema: FarmIntegrationSchemaModel,\n): Record<string, AnyFieldBuilder> {\n  return Object.fromEntries(\n    Object.entries(modelSchema.fields).map(([fieldKey, fieldSchema]) => [\n      fieldKey,\n      createOrmField(orm, fieldKey, fieldSchema),\n    ]),\n  );\n}\n\nfunction createOrmField(\n  orm: typeof import(\"@farming-labs/orm\"),\n  fieldKey: string,\n  field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n  let builder = createOrmFieldBuilder(orm, fieldKey, field) as AnyFieldBuilder;\n\n  if (field.unique) {\n    builder = builder.unique();\n  }\n\n  if (field.nullable || field.required === false) {\n    builder = builder.nullable();\n  }\n\n  if (field.default !== undefined) {\n    builder =\n      field.type === \"datetime\" && field.default === \"now\"\n        ? builder.defaultNow()\n        : builder.default(field.default as never);\n  }\n\n  if (field.reference) {\n    builder = builder.references(`${field.reference.model}.${field.reference.field}`);\n  }\n\n  if (field.name && field.name !== fieldKey) {\n    builder = builder.map(field.name);\n  }\n\n  if (field.description) {\n    builder = builder.describe(field.description);\n  }\n\n  return builder;\n}\n\nfunction createOrmFieldBuilder(\n  orm: typeof import(\"@farming-labs/orm\"),\n  fieldKey: string,\n  field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n  switch (field.type) {\n    case \"id\":\n    case \"uuid\":\n      return orm.id();\n    case \"string\":\n    case \"text\":\n      return orm.string();\n    case \"boolean\":\n      return orm.boolean();\n    case \"integer\":\n      return orm.integer();\n    case \"number\":\n      return orm.decimal();\n    case \"datetime\":\n      return orm.datetime();\n    case \"json\":\n      return orm.json();\n    case \"enum\": {\n      if (!field.values?.length) {\n        throw new Error(`Integration schema enum field \"${fieldKey}\" must define values.`);\n      }\n\n      return orm.enumeration(field.values as readonly [string, ...string[]]);\n    }\n    default:\n      throw new Error(\n        `Unsupported integration schema field type \"${field.type}\" for \"${fieldKey}\".`,\n      );\n  }\n}\n\nfunction createOrmModelConstraints(modelSchema: FarmIntegrationSchemaModel) {\n  const unique: Array<readonly [string, ...string[]]> = [];\n  const indexes: Array<readonly [string, ...string[]]> = [];\n\n  for (const constraint of modelSchema.constraints ?? []) {\n    if (!constraint.fields.length) {\n      continue;\n    }\n\n    const fields = constraint.fields as readonly [string, ...string[]];\n    if (constraint.type === \"unique\") {\n      unique.push(fields);\n    } else {\n      indexes.push(fields);\n    }\n  }\n\n  return {\n    unique,\n    indexes,\n  };\n}\n\nexport type IntegrationOrmModelNames<TSchema extends FarmIntegrationOrmSchema> =\n  keyof SchemaModels<TSchema> & string;\n","import { validateConfigRouteSource } from \"./plugins/route-pattern\";\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 { decodeRouteSegment } from \"./utils/decode\";\nimport {\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n  compareRouteSpecificity,\n  getRoutePatternSpecificity,\n} from \"./routing/specificity\";\nimport type {\n  FarmPlugin,\n  FarmPluginContext,\n  FarmPluginIntegrationContext,\n  FarmRequestStore,\n} from \"./plugin\";\nimport {\n  clearRequestContext,\n  deleteRequestContext,\n  getRequestContext,\n  getRequestContextSnapshot,\n  hasRequestContext,\n  setRequestContext,\n} from \"./request-context\";\nimport { 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  for (const [key, integration] of Object.entries(integrations)) {\n    if (!integration || !isFarmIntegration(integration)) {\n      continue;\n    }\n\n    const routes = normalizeIntegrationRoutes(integration.routes || []);\n\n    for (const route of routes) {\n      if (!matchesMethod(route.methods, input.method)) {\n        continue;\n      }\n\n      const params = extractPathParams(route.path, input.pathname);\n      if (!params) {\n        continue;\n      }\n\n      return {\n        key,\n        integration,\n        route: {\n          path: route.path,\n          methods: route.methods,\n        },\n        params,\n      };\n    }\n  }\n\n  return null;\n}\n\nexport function matchRegisteredIntegrationRoute(input: { pathname: string; method?: string }): {\n  key: string;\n  integration: FarmIntegration;\n  route: {\n    path: string;\n    methods: readonly string[];\n  };\n  params: FarmIntegrationRouteParams;\n} | null {\n  return matchIntegrationRoute(getRegisteredIntegrations(), input);\n}\n\nfunction createClientSafeIntegrationAPI(\n  api: FarmIntegrationAPI | undefined,\n): FarmIntegrationAPI | undefined {\n  if (!api) {\n    return undefined;\n  }\n\n  const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n    if (\n      value &&\n      typeof value === \"object\" &&\n      (value as FarmIntegrationAPIOperation<any, any, any, any, any>).kind ===\n        \"farm-integration-api-operation\"\n    ) {\n      const operation = value as FarmIntegrationAPIOperation<any, any, any, any, any>;\n      return [\n        key,\n        defineIntegrationAPIOperation({\n          path: operation.path,\n          method: operation.method,\n          bodyFormat: operation.bodyFormat,\n          responseFormat: operation.responseFormat,\n          credentials: operation.credentials,\n          isServer: operation.isServer,\n        }),\n      ];\n    }\n\n    if (value && typeof value === \"object\") {\n      return [key, createClientSafeIntegrationAPI(value as FarmIntegrationAPI)];\n    }\n\n    return [key, value];\n  });\n\n  return Object.fromEntries(entries) as FarmIntegrationAPI;\n}\n\nexport function getRegisteredIntegrationAPIManifest(): Record<string, FarmIntegrationAPI> {\n  const manifestEntries = Object.entries(getRegisteredIntegrations())\n    .map(([key, integration]) => {\n      const api = createClientSafeIntegrationAPI(integration.api);\n      return api ? ([key, api] as const) : null;\n    })\n    .filter((value): value is readonly [string, FarmIntegrationAPI] => value !== null);\n\n  return Object.fromEntries(manifestEntries);\n}\n\ntype IntegrationLifecycleCleanup = () => MaybePromise<void>;\n\nfunction getIntegrationRuntimeEnv(): Record<string, string | undefined> {\n  return typeof process !== \"undefined\" ? process.env : {};\n}\n\nfunction isIntegrationConfigDefinition(\n  value: unknown,\n): value is FarmIntegrationConfigDefinition<unknown> {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    (\"schema\" in value ||\n      \"env\" in value ||\n      \"defaults\" in value ||\n      \"input\" in value ||\n      \"resolve\" in value)\n  );\n}\n\nfunction mergeIntegrationConfigValue(current: unknown, next: unknown): unknown {\n  if (next === undefined) {\n    return current;\n  }\n\n  if (isPlainIntegrationConfigObject(current) && isPlainIntegrationConfigObject(next)) {\n    return {\n      ...current,\n      ...next,\n    };\n  }\n\n  return next;\n}\n\nfunction isPlainIntegrationConfigObject(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nasync function resolveIntegrationConfigPart<TValue>(\n  value: TValue | ((context: FarmIntegrationConfigContext) => MaybePromise<TValue>) | undefined,\n  context: FarmIntegrationConfigContext,\n): Promise<TValue | undefined> {\n  if (typeof value === \"function\") {\n    return (value as (context: FarmIntegrationConfigContext) => MaybePromise<TValue>)(context);\n  }\n\n  return value;\n}\n\nfunction resolveIntegrationEnvConfig(\n  env: Record<string, string | readonly string[]> | undefined,\n): Record<string, string> | undefined {\n  if (!env) {\n    return undefined;\n  }\n\n  const runtimeEnv = getIntegrationRuntimeEnv();\n  const config: Record<string, string> = {};\n\n  for (const [key, names] of Object.entries(env)) {\n    const envNames = Array.isArray(names) ? names : [names];\n    const value = envNames.map((name) => runtimeEnv[name]).find((entry) => entry !== undefined);\n    if (value !== undefined) {\n      config[key] = value;\n    }\n  }\n\n  return config;\n}\n\nasync function parseIntegrationConfigSchema<TConfig>(\n  integration: FarmIntegration<any, any>,\n  schema: FarmIntegrationInputSchema<TConfig>,\n  value: unknown,\n): Promise<TConfig> {\n  const parser = schema.safeParseAsync || schema.safeParse;\n  if (parser) {\n    const result = await parser.call(schema, value);\n    if (result.success) {\n      return result.data;\n    }\n\n    throw createIntegrationConfigValidationError(integration, result.error);\n  }\n\n  if (schema[\"~standard\"]?.validate) {\n    const result = await schema[\"~standard\"].validate(value);\n    if (\"value\" in result) {\n      return result.value;\n    }\n\n    throw createIntegrationConfigValidationError(integration, {\n      issues: result.issues,\n    });\n  }\n\n  if (schema.parse) {\n    try {\n      return await schema.parse(value);\n    } catch (error) {\n      throw createIntegrationConfigValidationError(\n        integration,\n        normalizeIntegrationValidationError(error),\n      );\n    }\n  }\n\n  throw new Error(\n    `Integration \"${integration.type}\" config schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.`,\n  );\n}\n\nfunction createIntegrationConfigValidationError(\n  integration: FarmIntegration<any, any>,\n  error: FarmIntegrationValidationErrorLike,\n) {\n  const issues =\n    Array.isArray(error.issues) && error.issues.length > 0\n      ? error.issues\n          .map((issue) => {\n            const normalizedPath = normalizeIntegrationValidationPath(issue.path);\n            const path = normalizedPath.length ? `${normalizedPath.join(\".\")}: ` : \"\";\n            return `${path}${issue.message || \"Invalid config\"}`;\n          })\n          .join(\"; \")\n      : error.message || \"Invalid config\";\n\n  return new Error(`Integration \"${integration.type}\" config validation failed: ${issues}`);\n}\n\nasync function resolveIntegrationConfig<TConfig>(\n  integration: FarmIntegration<any, TConfig>,\n  context: FarmIntegrationConfigContext,\n): Promise<TConfig> {\n  const config = integration.config;\n  if (!config) {\n    return undefined as TConfig;\n  }\n\n  if (!isIntegrationConfigDefinition(config)) {\n    return parseIntegrationConfigSchema(integration, config, {});\n  }\n\n  let value: unknown = {};\n  value = mergeIntegrationConfigValue(\n    value,\n    await resolveIntegrationConfigPart(config.defaults, context),\n  );\n  value = mergeIntegrationConfigValue(value, resolveIntegrationEnvConfig(config.env));\n  value = mergeIntegrationConfigValue(\n    value,\n    await resolveIntegrationConfigPart(config.input, context),\n  );\n  value = mergeIntegrationConfigValue(value, await config.resolve?.(context));\n\n  return config.schema\n    ? parseIntegrationConfigSchema(integration, config.schema, value)\n    : (value as TConfig);\n}\n\nfunction createIntegrationLifecycleLogger(\n  integration: FarmIntegration<any, any>,\n  phase: FarmIntegrationLogPhase,\n): FarmIntegrationLifecycleLogger {\n  const write = (\n    level: FarmIntegrationLifecycleLogLevel,\n    message: string,\n    meta?: Record<string, unknown>,\n  ) => {\n    if (!integration.log) {\n      return;\n    }\n\n    void Promise.resolve(\n      integration.log({\n        category: integration.category,\n        slot: integration.category,\n        type: integration.type,\n        phase,\n        level,\n        message,\n        meta,\n        context: new Map(),\n      }),\n    ).catch(() => {});\n  };\n\n  return {\n    info(message, meta) {\n      write(\"info\", message, meta);\n    },\n    warn(message, meta) {\n      write(\"warn\", message, meta);\n    },\n    error(message, meta) {\n      write(\"error\", message, meta);\n    },\n  };\n}\n\nasync function emitIntegrationLog(\n  integration: FarmIntegration,\n  event: FarmIntegrationLogEvent,\n): Promise<void> {\n  try {\n    await integration.log?.(event);\n  } catch {\n    // Integration logging is optional observability. A failed sink must not\n    // block lifecycle startup, request handlers, responses, or cleanup.\n  }\n}\n\nconst INTEGRATION_DATA_HEADER = \"x-farm-integration-data\";\nconst INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;\nconst BLOCKED_INTEGRATION_DATA_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isFarmIntegrationData(value: unknown): value is FarmIntegrationData {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isPlainIntegrationDataObject(value: unknown): value is Record<string, unknown> {\n  if (!isFarmIntegrationData(value)) {\n    return false;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction sanitizeIntegrationDataValue(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map((item) => sanitizeIntegrationDataValue(item));\n  }\n\n  if (!isPlainIntegrationDataObject(value)) {\n    return value;\n  }\n\n  const sanitized: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {\n      continue;\n    }\n\n    sanitized[key] = sanitizeIntegrationDataValue(item);\n  }\n\n  return sanitized;\n}\n\nfunction normalizeIntegrationData(value: FarmIntegrationData | undefined): FarmIntegrationData {\n  if (!isFarmIntegrationData(value)) {\n    return {};\n  }\n\n  const sanitized = sanitizeIntegrationDataValue(value);\n  return isFarmIntegrationData(sanitized) ? sanitized : {};\n}\n\nfunction getIntegrationDataHeaderByteLength(value: string): number {\n  return new TextEncoder().encode(value).byteLength;\n}\n\nfunction parseIntegrationDataHeader(request: Request): FarmIntegrationData {\n  const raw = request.headers.get(INTEGRATION_DATA_HEADER);\n  if (!raw) {\n    return {};\n  }\n\n  if (getIntegrationDataHeaderByteLength(raw) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {\n    return {};\n  }\n\n  try {\n    const value = JSON.parse(raw);\n    return normalizeIntegrationData(value);\n  } catch {\n    return {};\n  }\n}\n\nfunction resolveIntegrationData(request: Request, data?: FarmIntegrationData): FarmIntegrationData {\n  return {\n    ...parseIntegrationDataHeader(request),\n    ...normalizeIntegrationData(data),\n  };\n}\n\nfunction createIntegrationPlugin(integrationKey: string, integration: FarmIntegration): FarmPlugin {\n  const routes = normalizeIntegrationRoutes(integration.routes || []);\n  const middleware = [...(integration.middleware || [])];\n  const cleanupCallbacks: IntegrationLifecycleCleanup[] = [];\n  let integrationConfigPromise: Promise<unknown> | undefined;\n\n  const runCleanup = async () => {\n    const callbacks = cleanupCallbacks.splice(0).reverse();\n    for (const callback of callbacks) {\n      await callback();\n    }\n  };\n\n  const createLifecycleContext = async (\n    context: FarmPluginContext,\n    phase: FarmIntegrationLogPhase,\n    options: { reason?: string } = {},\n  ): Promise<FarmIntegrationLifecycleContext> => {\n    const args = createIntegrationRouteArgs({\n      integration,\n      config: context.config,\n    });\n    const configContext: FarmIntegrationConfigContext = {\n      key: integrationKey,\n      integration,\n      appConfig: context.config,\n      config: context.config,\n      args,\n      env: getIntegrationRuntimeEnv(),\n      isDev: context.isDev,\n      isProd: context.isProd,\n    };\n    integrationConfigPromise ??= resolveIntegrationConfig(integration, configContext);\n\n    return {\n      ...configContext,\n      integrationConfig: await integrationConfigPromise,\n      log: createIntegrationLifecycleLogger(integration, phase),\n      reason: options.reason,\n      async cleanup(callback) {\n        if (callback) {\n          cleanupCallbacks.push(callback);\n          return;\n        }\n\n        await runCleanup();\n      },\n    };\n  };\n\n  const plugin: FarmPlugin = {\n    name: `farm:integration:${integration.category}:${integration.type}`,\n    enforce: \"pre\",\n\n    async init(context) {\n      getIntegrationRuntimeRegistry().set(integrationKey, {\n        integration,\n        config: context.config,\n        isDev: context.isDev,\n        isProd: context.isProd,\n      });\n\n      await createLifecycleContext(context, \"validate\");\n\n      if (integration.validate) {\n        await integration.validate(await createLifecycleContext(context, \"validate\"));\n      }\n\n      if (integration.setup) {\n        await integration.setup(await createLifecycleContext(context, \"setup\"));\n      }\n\n      if (!integration.log) {\n        return;\n      }\n\n      for (const route of routes) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"registered\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          context: new Map(),\n        });\n      }\n\n      for (const entry of middleware) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"registered\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          context: new Map(),\n        });\n      }\n    },\n\n    async ready(context) {\n      if (integration.ready) {\n        await integration.ready(await createLifecycleContext(context, \"ready\"));\n      }\n    },\n\n    async shutdown(payload, context) {\n      try {\n        if (integration.dispose) {\n          await integration.dispose(\n            await createLifecycleContext(context, \"dispose\", {\n              reason: payload.reason,\n            }),\n          );\n        }\n      } finally {\n        await runCleanup();\n      }\n    },\n\n    async beforeRequest(req, res, context) {\n      const fullUrl = `http://${req.headers.host || \"localhost\"}${req.url || \"/\"}`;\n      const url = new URL(fullUrl);\n      const pathname = url.pathname;\n      const requestId = getRequestId(req);\n      let bodyLoaded = false;\n      let requestBody: Buffer | undefined;\n\n      const getRequestBody = async () => {\n        if (!bodyLoaded) {\n          bodyLoaded = true;\n          if (req.method && req.method !== \"GET\" && req.method !== \"HEAD\") {\n            requestBody = await readNodeRequestBody(\n              req,\n              resolveFarmServerConfig(context.config.server).bodySizeLimit,\n            );\n          }\n        }\n\n        return requestBody;\n      };\n\n      const createHandlerRequest = async (): Promise<Request | null> => {\n        try {\n          return createWebRequest(req, fullUrl, await getRequestBody());\n        } catch (error) {\n          const response = createFarmRequestBodyErrorResponse(error);\n          if (!response) throw error;\n          await sendWebResponse(res, response);\n          return null;\n        }\n      };\n\n      for (const entry of middleware) {\n        const params = resolveMatcherParams(entry.matcher, pathname);\n        if (!params) {\n          continue;\n        }\n\n        const request = await createHandlerRequest();\n        if (!request) return;\n        const handlerContext = createIntegrationHandlerContext({\n          integration,\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          rawRequest: req,\n          params,\n          pathname,\n          requestId,\n          pluginContext: context,\n        });\n        const startedAt = Date.now();\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:start\",\n          route: {\n            kind: \"middleware\",\n            path: normalizeMatcher(entry.matcher),\n            methods: [\"ALL\"],\n          },\n          request,\n          requestId,\n          context: handlerContext.req.snapshot(),\n        });\n\n        try {\n          const response = await entry.handler(request, handlerContext);\n\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 = matchesMethod(route.methods, req.method)\n          ? extractPathParams(route.path, pathname)\n          : null;\n        if (!params) {\n          continue;\n        }\n\n        const request = await createHandlerRequest();\n        if (!request) return;\n        const handlerContext = createIntegrationHandlerContext({\n          integration,\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          rawRequest: req,\n          params,\n          pathname,\n          requestId,\n          pluginContext: context,\n        });\n        const startedAt = Date.now();\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:start\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          requestId,\n          context: handlerContext.req.snapshot(),\n        });\n\n        try {\n          const validation = await validateIntegrationRouteInput(route, request, url);\n          if (!validation.success) {\n            await sendWebResponse(res, validation.response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"route\",\n                path: route.path,\n                methods: route.methods,\n              },\n              request,\n              response: validation.response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n          handlerContext.input = validation.input;\n\n          for (const middlewareEntry of route.middleware || []) {\n            const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n            if (middlewareResponse) {\n              await sendWebResponse(res, middlewareResponse);\n              await emitIntegrationLog(integration, {\n                category: integration.category,\n                slot: integration.category,\n                type: integration.type,\n                phase: \"request:end\",\n                route: {\n                  kind: \"route\",\n                  path: route.path,\n                  methods: route.methods,\n                },\n                request,\n                response: middlewareResponse,\n                requestId,\n                durationMs: Date.now() - startedAt,\n                context: handlerContext.req.snapshot(),\n              });\n              return;\n            }\n          }\n\n          const beforeResponse = await runIntegrationRouteBeforeHooks(\n            route,\n            request,\n            handlerContext,\n          );\n          if (beforeResponse) {\n            const response = await runIntegrationRouteAfterHooks(\n              route,\n              request,\n              handlerContext,\n              beforeResponse,\n            );\n            await sendWebResponse(res, response);\n            await emitIntegrationLog(integration, {\n              category: integration.category,\n              slot: integration.category,\n              type: integration.type,\n              phase: \"request:end\",\n              route: {\n                kind: \"route\",\n                path: route.path,\n                methods: route.methods,\n              },\n              request,\n              response,\n              requestId,\n              durationMs: Date.now() - startedAt,\n              context: handlerContext.req.snapshot(),\n            });\n            return;\n          }\n\n          const handlerResponse = await route.handler(request, handlerContext);\n          const response = await runIntegrationRouteAfterHooks(\n            route,\n            request,\n            handlerContext,\n            handlerResponse,\n          );\n          await sendWebResponse(res, response);\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:end\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            response,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            context: handlerContext.req.snapshot(),\n          });\n          return;\n        } catch (error) {\n          await emitIntegrationLog(integration, {\n            category: integration.category,\n            slot: integration.category,\n            type: integration.type,\n            phase: \"request:error\",\n            route: {\n              kind: \"route\",\n              path: route.path,\n              methods: route.methods,\n            },\n            request,\n            requestId,\n            durationMs: Date.now() - startedAt,\n            error,\n            context: handlerContext.req.snapshot(),\n          });\n          throw error;\n        }\n      }\n    },\n  };\n\n  Object.defineProperty(plugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {\n    value: integration.serverRuntime !== false,\n  });\n\n  return plugin;\n}\n\nfunction createIntegrationHandlerContext(input: {\n  integration: FarmIntegration;\n  route: FarmIntegrationHandlerContext[\"route\"];\n  request: Request;\n  rawRequest: FarmRequest;\n  params: FarmIntegrationRouteParams;\n  pathname: string;\n  requestId: string;\n  pluginContext: FarmPluginContext;\n}): FarmIntegrationHandlerContext {\n  const req = createIntegrationRequestContextStore(\n    input.rawRequest,\n    input.request,\n    input.pluginContext,\n  );\n\n  return {\n    request: input.request,\n    requestId: input.requestId,\n    url: new URL(input.request.url),\n    pathname: input.pathname,\n    method: input.request.method,\n    params: input.params,\n    input: {},\n    args: createIntegrationRouteArgs({\n      integration: input.integration,\n      config: input.pluginContext.config,\n    }),\n    data: resolveIntegrationData(input.request),\n    integration: {\n      category: input.integration.category,\n      slot: input.integration.category,\n      type: input.integration.type,\n      instance: input.integration.instance,\n    },\n    route: input.route,\n    req,\n    requestContext: req,\n    config: input.pluginContext.config,\n    isDev: input.pluginContext.isDev,\n    isProd: input.pluginContext.isProd,\n  };\n}\n\ntype NormalizedIntegrationRoute = Omit<FarmIntegrationRoute, \"method\" | \"methods\"> & {\n  methods: readonly string[];\n  __operation?: FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nfunction normalizeIntegrationRoutes(\n  routes: readonly FarmIntegrationRoute[],\n): NormalizedIntegrationRoute[] {\n  return routes\n    .map((route, index) => {\n      // Raw FarmIntegration objects and direct dispatch also pass through here.\n      assertUniqueRouteParameters(route.path, \"api\");\n      return {\n        index,\n        route: {\n          ...route,\n          methods: normalizeIntegrationRouteMethods(route),\n          input: normalizeIntegrationRouteInputSchemas(route),\n        },\n        specificity: getRoutePatternSpecificity(route.path, \"api\"),\n      };\n    })\n    .sort(\n      (left, right) =>\n        compareRouteSpecificity(left.specificity, right.specificity) || left.index - right.index,\n    )\n    .map(({ route }) => route);\n}\n\nfunction normalizeIntegrationRouteMethods(route: Pick<FarmIntegrationRoute, \"method\" | \"methods\">) {\n  const input =\n    route.methods && route.methods.length > 0\n      ? [...route.methods]\n      : route.method\n        ? [route.method]\n        : [\"ALL\"];\n\n  return input.map((method) => String(method).toUpperCase());\n}\n\nfunction normalizeIntegrationRouteInputSchemas<TBody, TQuery>(\n  route: Pick<FarmIntegrationRoute<TBody, TQuery>, \"body\" | \"query\" | \"input\">,\n): FarmIntegrationRouteInputSchemas<TBody, TQuery> | undefined {\n  const input: FarmIntegrationRouteInputSchemas<TBody, TQuery> = {\n    ...route.input,\n  };\n\n  if (route.body) {\n    input.body = route.body;\n  }\n\n  if (route.query) {\n    input.query = route.query;\n  }\n\n  return input.body || input.query ? input : undefined;\n}\n\ntype IntegrationRouteInputValidationResult =\n  | {\n      success: true;\n      input: FarmIntegrationRouteInput;\n    }\n  | {\n      success: false;\n      response: Response;\n    };\n\nasync function validateIntegrationRouteInput(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  url: URL,\n): Promise<IntegrationRouteInputValidationResult> {\n  if (request.method.toUpperCase() === \"QUERY\" && !request.headers.has(\"content-type\")) {\n    return {\n      success: false,\n      response: Response.json(\n        {\n          error: \"Invalid QUERY request\",\n          message: \"QUERY requests must include a Content-Type header.\",\n        },\n        { status: 400 },\n      ),\n    };\n  }\n\n  const schemas = route.input;\n  if (!schemas?.body && !schemas?.query) {\n    return {\n      success: true,\n      input: {},\n    };\n  }\n\n  const input: FarmIntegrationRouteInput = {};\n  const issues: FarmIntegrationValidationIssue[] = [];\n\n  if (schemas.query) {\n    const queryResult = await parseIntegrationInputSchema(\n      \"query\",\n      schemas.query,\n      createQueryInput(url.searchParams),\n    );\n    if (queryResult.success) {\n      input.query = queryResult.data;\n    } else {\n      issues.push(...queryResult.issues);\n    }\n  }\n\n  if (schemas.body) {\n    const bodyInput = await readIntegrationValidationBody(\n      request,\n      getIntegrationRouteBodyFormat(route),\n    );\n\n    if (bodyInput.success) {\n      const bodyResult = await parseIntegrationInputSchema(\"body\", schemas.body, bodyInput.data);\n      if (bodyResult.success) {\n        input.body = bodyResult.data;\n      } else {\n        issues.push(...bodyResult.issues);\n      }\n    } else {\n      issues.push(bodyInput.issue);\n    }\n  }\n\n  if (issues.length > 0) {\n    return {\n      success: false,\n      response: createIntegrationValidationResponse(issues),\n    };\n  }\n\n  return {\n    success: true,\n    input,\n  };\n}\n\nasync function parseIntegrationInputSchema<TValue>(\n  source: FarmIntegrationRouteInputSource,\n  schema: FarmIntegrationInputSchema<TValue>,\n  value: unknown,\n): Promise<\n  | {\n      success: true;\n      data: TValue;\n    }\n  | {\n      success: false;\n      issues: FarmIntegrationValidationIssue[];\n    }\n> {\n  const parser = schema.safeParseAsync || schema.safeParse;\n  if (parser) {\n    const result = await parser.call(schema, value);\n    if (result.success) {\n      return {\n        success: true,\n        data: result.data,\n      };\n    }\n\n    return {\n      success: false,\n      issues: normalizeIntegrationValidationIssues(source, result.error),\n    };\n  }\n\n  if (schema[\"~standard\"]?.validate) {\n    const result = await schema[\"~standard\"].validate(value);\n    if (\"value\" in result) {\n      return {\n        success: true,\n        data: result.value,\n      };\n    }\n\n    return {\n      success: false,\n      issues: normalizeIntegrationValidationIssues(source, {\n        issues: result.issues,\n      }),\n    };\n  }\n\n  if (schema.parse) {\n    try {\n      return {\n        success: true,\n        data: await schema.parse(value),\n      };\n    } catch (error) {\n      return {\n        success: false,\n        issues: normalizeIntegrationValidationIssues(\n          source,\n          normalizeIntegrationValidationError(error),\n        ),\n      };\n    }\n  }\n\n  return {\n    success: false,\n    issues: [\n      {\n        source,\n        message:\n          \"Input schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.\",\n      },\n    ],\n  };\n}\n\nfunction createIntegrationValidationResponse(issues: readonly FarmIntegrationValidationIssue[]) {\n  return Response.json(\n    {\n      error: \"Integration route input validation failed\",\n      issues,\n    },\n    {\n      status: 400,\n    },\n  );\n}\n\nfunction normalizeIntegrationValidationIssues(\n  source: FarmIntegrationRouteInputSource,\n  error: FarmIntegrationValidationErrorLike,\n): FarmIntegrationValidationIssue[] {\n  if (Array.isArray(error.issues) && error.issues.length > 0) {\n    return error.issues.map((issue) => ({\n      source,\n      path: normalizeIntegrationValidationPath(issue.path),\n      code: issue.code,\n      message: issue.message || \"Invalid input\",\n    }));\n  }\n\n  return [\n    {\n      source,\n      path: [],\n      message: error.message || \"Invalid input\",\n    },\n  ];\n}\n\nfunction normalizeIntegrationValidationPath(\n  path: readonly FarmIntegrationValidationPathSegment[] | undefined,\n): (string | number)[] {\n  return (path || []).map((segment) => {\n    const key =\n      typeof segment === \"object\" && segment !== null && \"key\" in segment ? segment.key : segment;\n    return typeof key === \"symbol\" ? key.description || key.toString() : key;\n  });\n}\n\nfunction normalizeIntegrationValidationError(error: unknown): FarmIntegrationValidationErrorLike {\n  if (error && typeof error === \"object\") {\n    return error as FarmIntegrationValidationErrorLike;\n  }\n\n  return {\n    message: error instanceof Error ? error.message : String(error || \"Invalid input\"),\n  };\n}\n\nasync function readIntegrationValidationBody(\n  request: Request,\n  format: FarmIntegrationAPIBodyFormat,\n): Promise<\n  | {\n      success: true;\n      data: unknown;\n    }\n  | {\n      success: false;\n      issue: FarmIntegrationValidationIssue;\n    }\n> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || format === \"none\") {\n    return {\n      success: true,\n      data: undefined,\n    };\n  }\n\n  try {\n    if (format === \"form\") {\n      return {\n        success: true,\n        data: createFormInput(await request.clone().formData()),\n      };\n    }\n\n    const text = await request.clone().text();\n    if (text.trim().length === 0) {\n      return {\n        success: true,\n        data: undefined,\n      };\n    }\n\n    return {\n      success: true,\n      data: JSON.parse(text),\n    };\n  } catch (error) {\n    return {\n      success: false,\n      issue: {\n        source: \"body\",\n        path: [],\n        message:\n          format === \"json\"\n            ? \"Expected a valid JSON request body.\"\n            : error instanceof Error && error.message\n              ? error.message\n              : \"Could not parse request body.\",\n      },\n    };\n  }\n}\n\nfunction getIntegrationRouteBodyFormat(route: NormalizedIntegrationRoute) {\n  return route.bodyFormat || route.__operation?.bodyFormat || \"json\";\n}\n\nfunction createIntegrationRouteArgs(input: {\n  integration: FarmIntegration;\n  config: FarmPluginContext[\"config\"];\n}): FarmIntegrationRouteArgs {\n  let clientPromise: Promise<unknown | undefined> | undefined;\n  let ormPromise: Promise<unknown> | undefined;\n\n  const getClient = () => {\n    clientPromise ??= import(\"./storage\").then(({ resolveStorageRuntimeClient }) =>\n      resolveStorageRuntimeClient(input.config.storage),\n    );\n    return clientPromise;\n  };\n\n  const getOrm = () => {\n    if (!input.integration.schema) {\n      throw new Error(\n        `Integration \"${input.integration.type}\" does not define a schema for ctx.args.db.`,\n      );\n    }\n\n    ormPromise ??= import(\"./integration-orm\").then(({ createIntegrationOrm }) =>\n      createIntegrationOrm({\n        schema: input.integration.schema!,\n        config: input.config,\n      }),\n    );\n    return ormPromise;\n  };\n\n  return {\n    db: createLazyIntegrationOrmClient(getOrm) as never,\n    getDb: getOrm as never,\n    storage: {\n      getClient,\n      getOrm: getOrm as never,\n    },\n  };\n}\n\nfunction createLazyIntegrationOrmClient(resolveOrm: () => Promise<unknown>) {\n  const modelProxyCache = new Map<PropertyKey, unknown>();\n\n  return new Proxy(\n    {},\n    {\n      get(_target, prop) {\n        if (prop === \"then\") {\n          return undefined;\n        }\n\n        if (prop === \"transaction\" || prop === \"batch\") {\n          return async (...args: unknown[]) => {\n            const orm = (await resolveOrm()) as Record<PropertyKey, unknown>;\n            const member = orm[prop];\n            if (typeof member !== \"function\") {\n              throw new Error(`Integration ORM does not expose \"${String(prop)}\".`);\n            }\n            return member.apply(orm, args);\n          };\n        }\n\n        if (prop === \"$driver\") {\n          return undefined;\n        }\n\n        if (!modelProxyCache.has(prop)) {\n          modelProxyCache.set(prop, createLazyIntegrationOrmModel(resolveOrm, prop));\n        }\n\n        return modelProxyCache.get(prop);\n      },\n    },\n  );\n}\n\nfunction createLazyIntegrationOrmModel(resolveOrm: () => Promise<unknown>, modelName: PropertyKey) {\n  return new Proxy(\n    {},\n    {\n      get(_target, prop) {\n        if (prop === \"then\") {\n          return undefined;\n        }\n\n        return async (...args: unknown[]) => {\n          const orm = (await resolveOrm()) as Record<PropertyKey, Record<PropertyKey, unknown>>;\n          const model = orm[modelName];\n          const member = model?.[prop];\n          if (typeof member !== \"function\") {\n            throw new Error(\n              `Integration ORM model \"${String(modelName)}\" does not expose \"${String(prop)}\".`,\n            );\n          }\n          return member.apply(model, args);\n        };\n      },\n    },\n  );\n}\n\nasync function runIntegrationRouteBeforeHooks(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  context: FarmIntegrationHandlerContext,\n): Promise<Response | undefined> {\n  const hookContext = context as FarmIntegrationRouteHookContext;\n  hookContext.response = undefined;\n\n  for (const hook of route.before || []) {\n    const response = await hook(request, hookContext);\n    if (response) {\n      hookContext.response = response;\n      return response;\n    }\n\n    if (hookContext.response) {\n      return hookContext.response;\n    }\n  }\n\n  return undefined;\n}\n\nasync function runIntegrationRouteAfterHooks(\n  route: NormalizedIntegrationRoute,\n  request: Request,\n  context: FarmIntegrationHandlerContext,\n  response: Response,\n): Promise<Response> {\n  const hookContext = context as FarmIntegrationRouteHookContext;\n  let currentResponse = response;\n\n  for (const hook of route.after || []) {\n    hookContext.response = currentResponse;\n    const nextResponse = await hook(request, hookContext);\n    currentResponse = nextResponse || hookContext.response || currentResponse;\n  }\n\n  hookContext.response = currentResponse;\n  return currentResponse;\n}\n\nfunction createQueryInput(searchParams: URLSearchParams): Record<string, string | string[]> {\n  const input: Record<string, string | string[]> = {};\n  searchParams.forEach((value, key) => {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n\n    const existing = input[key];\n    if (existing === undefined) {\n      input[key] = value;\n      return;\n    }\n\n    input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n  });\n  return input;\n}\n\nfunction createFormInput(\n  formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n  const input: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n  formData.forEach((value, key) => {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n\n    const existing = input[key];\n    if (existing === undefined) {\n      input[key] = value;\n      return;\n    }\n\n    input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n  });\n  return input;\n}\n\nexport async function dispatchIntegrationRequest(\n  runtime: RegisteredIntegrationRuntime,\n  request: Request,\n  options: {\n    currentRequest?: Request;\n    data?: FarmIntegrationData;\n    internal?: boolean;\n  } = {},\n): Promise<Response | null> {\n  try {\n    request = await bufferFarmRequestBody(\n      request,\n      resolveFarmServerConfig(runtime.config.server).bodySizeLimit,\n    );\n  } catch (error) {\n    const response = createFarmRequestBodyErrorResponse(error);\n    if (response) return response;\n    throw error;\n  }\n\n  const integration = runtime.integration;\n  const url = new URL(request.url);\n  const pathname = url.pathname;\n  const requestId =\n    request.headers.get(\"x-request-id\") ||\n    options.currentRequest?.headers.get(\"x-request-id\") ||\n    String(Date.now());\n  const routes = normalizeIntegrationRoutes(integration.routes || []);\n  const middleware = [...(integration.middleware || [])];\n\n  // 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 = matchesMethod(route.methods, request.method)\n      ? extractPathParams(route.path, pathname)\n      : null;\n    if (!params) {\n      continue;\n    }\n\n    const handlerContext = createServerIntegrationHandlerContext({\n      runtime,\n      route: {\n        kind: \"route\",\n        path: route.path,\n        methods: route.methods,\n      },\n      request,\n      params,\n      pathname,\n      requestId,\n      currentRequest: options.currentRequest,\n      data: options.data,\n      internal: options.internal === true,\n    });\n    const startedAt = Date.now();\n\n    await emitIntegrationLog(integration, {\n      category: integration.category,\n      slot: integration.category,\n      type: integration.type,\n      phase: \"request:start\",\n      route: {\n        kind: \"route\",\n        path: route.path,\n        methods: route.methods,\n      },\n      request,\n      requestId,\n      context: handlerContext.req.snapshot(),\n    });\n\n    try {\n      const validation = await validateIntegrationRouteInput(route, request, url);\n      if (!validation.success) {\n        await emitIntegrationLog(integration, {\n          category: integration.category,\n          slot: integration.category,\n          type: integration.type,\n          phase: \"request:end\",\n          route: {\n            kind: \"route\",\n            path: route.path,\n            methods: route.methods,\n          },\n          request,\n          response: validation.response,\n          requestId,\n          durationMs: Date.now() - startedAt,\n          context: handlerContext.req.snapshot(),\n        });\n        return 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  return null;\n}\n\n(globalThis as GlobalWithIntegrationRuntimeRegistry)[INTEGRATION_REQUEST_DISPATCHER_KEY] =\n  dispatchIntegrationRequest;\n\nfunction createIntegrationRequestContextStore(\n  rawRequest: FarmRequest,\n  request: Request,\n  pluginContext: FarmPluginContext,\n): FarmIntegrationRequestContextStore {\n  return {\n    get(key) {\n      const requestValue = pluginContext.requestContext.get(request, key);\n      if (requestValue !== undefined) {\n        return requestValue;\n      }\n\n      return pluginContext.requestContext.get(rawRequest, key);\n    },\n    set(key, value, options) {\n      pluginContext.requestContext.set(rawRequest, key, value, options);\n      pluginContext.requestContext.set(request, key, value, options);\n    },\n    has(key) {\n      return (\n        pluginContext.requestContext.has(request, key) ||\n        pluginContext.requestContext.has(rawRequest, key)\n      );\n    },\n    delete(key) {\n      const deletedRequest = pluginContext.requestContext.delete(request, key);\n      const deletedRaw = pluginContext.requestContext.delete(rawRequest, key);\n      return deletedRequest || deletedRaw;\n    },\n    clear() {\n      pluginContext.requestContext.clear(rawRequest);\n      pluginContext.requestContext.clear(request);\n    },\n    snapshot(options) {\n      const merged = pluginContext.requestContext.getAll(rawRequest, options);\n      const requestSnapshot = pluginContext.requestContext.getAll(request, options);\n      for (const [key, value] of requestSnapshot) {\n        merged.set(key, value);\n      }\n      return merged;\n    },\n  };\n}\n\nfunction createServerIntegrationHandlerContext(input: {\n  runtime: RegisteredIntegrationRuntime;\n  route: FarmIntegrationHandlerContext[\"route\"];\n  request: Request;\n  params: FarmIntegrationRouteParams;\n  pathname: string;\n  requestId: string;\n  currentRequest?: Request;\n  data?: FarmIntegrationData;\n  internal?: boolean;\n}): FarmIntegrationHandlerContext {\n  const req = createServerIntegrationRequestContextStore(input.request, input.currentRequest);\n\n  if (input.internal) {\n    req.set(FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY, true);\n  }\n\n  return {\n    request: input.request,\n    requestId: input.requestId,\n    url: new URL(input.request.url),\n    pathname: input.pathname,\n    method: input.request.method,\n    params: input.params,\n    input: {},\n    args: createIntegrationRouteArgs({\n      integration: input.runtime.integration,\n      config: input.runtime.config,\n    }),\n    data: resolveIntegrationData(input.request, input.data),\n    integration: {\n      category: input.runtime.integration.category,\n      slot: input.runtime.integration.category,\n      type: input.runtime.integration.type,\n      instance: input.runtime.integration.instance,\n    },\n    route: input.route,\n    req,\n    requestContext: req,\n    config: input.runtime.config,\n    isDev: input.runtime.isDev,\n    isProd: input.runtime.isProd,\n  };\n}\n\nfunction createServerIntegrationRequestContextStore(\n  request: Request,\n  currentRequest?: Request,\n): FarmIntegrationRequestContextStore {\n  return {\n    get(key) {\n      const requestValue = getRequestContext(request, key);\n      if (requestValue !== undefined) {\n        return requestValue;\n      }\n\n      if (currentRequest) {\n        return getRequestContext(currentRequest, key);\n      }\n\n      return undefined;\n    },\n    set(key, value, options) {\n      setRequestContext(request, key, value, options);\n      if (currentRequest) {\n        setRequestContext(currentRequest, key, value, options);\n      }\n    },\n    has(key) {\n      return (\n        hasRequestContext(request, key) ||\n        (!!currentRequest && hasRequestContext(currentRequest, key))\n      );\n    },\n    delete(key) {\n      const deletedRequest = deleteRequestContext(request, key);\n      const deletedCurrent = currentRequest ? deleteRequestContext(currentRequest, key) : false;\n      return deletedRequest || deletedCurrent;\n    },\n    clear() {\n      clearRequestContext(request);\n      if (currentRequest) {\n        clearRequestContext(currentRequest);\n      }\n    },\n    snapshot(options) {\n      const merged = currentRequest\n        ? getRequestContextSnapshot(currentRequest, options)\n        : new Map<string, unknown>();\n      const requestSnapshot = getRequestContextSnapshot(request, options);\n      for (const [key, value] of requestSnapshot) {\n        merged.set(key, value);\n      }\n      return merged;\n    },\n  };\n}\n\nfunction createWebRequest(req: FarmRequest, fullUrl: string, body?: Buffer): Request {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        headers.append(key, item);\n      }\n      continue;\n    }\n\n    headers.set(key, value);\n  }\n\n  return new Request(fullUrl, {\n    method: req.method,\n    headers,\n    body: body as BodyInit | undefined,\n  });\n}\n\nfunction matchesMethod(methods: readonly string[], method: string | undefined): boolean {\n  if (!method) {\n    return false;\n  }\n\n  const normalizedMethod = method.toUpperCase();\n  return methods.some((item) => {\n    const candidate = item.toUpperCase();\n    return candidate === \"ALL\" || candidate === normalizedMethod;\n  });\n}\n\nfunction matchesMatcher(\n  matcher: string | readonly string[] | undefined,\n  pathname: string,\n): boolean {\n  return resolveMatcherParams(matcher, pathname) !== null;\n}\n\nfunction resolveMatcherParams(\n  matcher: string | readonly string[] | undefined,\n  pathname: string,\n): FarmIntegrationRouteParams | null {\n  if (!matcher) {\n    return {};\n  }\n\n  const list = Array.isArray(matcher) ? matcher : [matcher];\n  for (const item of list) {\n    if (item === \"/(.*)\" || item === \"*\") {\n      return {};\n    }\n    if (item.endsWith(\"(.*)\")) {\n      const prefix = item.slice(0, -4);\n      if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n        return {};\n      }\n      continue;\n    }\n    const params = extractPathParams(item, pathname);\n    if (params) {\n      return params;\n    }\n  }\n\n  return null;\n}\n\nfunction matchesPath(pattern: string, pathname: string): boolean {\n  return extractPathParams(pattern, pathname) !== null;\n}\n\nfunction extractPathParams(pattern: string, pathname: string): FarmIntegrationRouteParams | null {\n  const routeSegments = splitPath(pattern);\n  const pathSegments = splitPath(pathname);\n  const params: FarmIntegrationRouteParams = {};\n\n  let routeIndex = 0;\n  let pathIndex = 0;\n\n  while (routeIndex < routeSegments.length && pathIndex < pathSegments.length) {\n    const routeSegment = routeSegments[routeIndex];\n    const pathSegment = pathSegments[pathIndex];\n\n    if (isCatchAllSegment(routeSegment)) {\n      params[getSegmentParamName(routeSegment)] = pathSegments\n        .slice(pathIndex)\n        .map((segment) => decodeRouteSegment(segment));\n      return params;\n    }\n\n    if (isDynamicSegment(routeSegment)) {\n      params[getSegmentParamName(routeSegment)] = decodeRouteSegment(pathSegment);\n      routeIndex += 1;\n      pathIndex += 1;\n      continue;\n    }\n\n    if (routeSegment !== pathSegment) {\n      return null;\n    }\n\n    routeIndex += 1;\n    pathIndex += 1;\n  }\n\n  if (routeIndex === routeSegments.length && pathIndex === pathSegments.length) {\n    return params;\n  }\n\n  if (routeIndex === routeSegments.length - 1 && isCatchAllSegment(routeSegments[routeIndex])) {\n    params[getSegmentParamName(routeSegments[routeIndex])] = [];\n    return params;\n  }\n\n  return null;\n}\n\nfunction splitPath(value: string): string[] {\n  return value.split(\"/\").filter(Boolean);\n}\n\nfunction isDynamicSegment(segment: string): boolean {\n  return segment.startsWith(\"[\") && segment.endsWith(\"]\");\n}\n\nfunction isCatchAllSegment(segment: string): boolean {\n  return segment.startsWith(\"[...\") && segment.endsWith(\"]\");\n}\n\nfunction getSegmentParamName(segment: string): string {\n  if (isCatchAllSegment(segment)) {\n    return segment.slice(4, -1);\n  }\n\n  return segment.slice(1, -1);\n}\n\nfunction getRequestId(req: FarmRequest): string {\n  const headerValue = req.headers[\"x-request-id\"];\n  if (Array.isArray(headerValue)) {\n    return headerValue[0] || String(Date.now());\n  }\n  return headerValue || String(Date.now());\n}\n\nfunction normalizeMatcher(matcher: string | readonly string[] | undefined): string {\n  if (!matcher) {\n    return \"/(.*)\";\n  }\n  return typeof matcher === \"string\" ? matcher : matcher.join(\", \");\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * A rendering-library integration used by Farm's compiler, server renderer,\n * and browser hydration runtime.\n *\n * Renderer descriptors intentionally contain module identifiers instead of\n * implementation functions. This keeps farm.config.ts serializable and lets\n * every module resolve from the application that selected the renderer.\n */\nexport interface FarmRenderer {\n  /** Stable public identifier used in diagnostics and generated manifests. */\n  name: string;\n  /** Module exporting the renderer's Vite plugin factory. */\n  vite: string;\n  /** Module exporting Farm's server-renderer compatibility contract. */\n  server: string;\n  /** Module exporting Farm's browser-renderer compatibility contract. */\n  client: string;\n  /** JSX import source written to generated TypeScript configuration. */\n  jsxImportSource?: string;\n  /** Additional file extensions used for renderer-owned route components. */\n  componentExtensions?: readonly string[];\n  /** Packages that must share one module instance in a Farm application. */\n  dedupe?: readonly string[];\n  /** Renderer packages seeded into Vite's dependency optimizer. */\n  optimizeDeps?: readonly string[];\n  /**\n   * Scheduling policy for the production client and SSR graphs.\n   *\n   * Most renderer plugins are safe to run in parallel. Renderers whose\n   * compiler plugins keep process-global mutable state can opt into serial\n   * builds so one graph cannot invalidate the other's transforms.\n   */\n  buildConcurrency?: \"parallel\" | \"serial\";\n  /** Runtime features this renderer intentionally supports. */\n  capabilities?: FarmRendererCapabilitiesInput;\n  /**\n   * Serializable options consumed by the renderer's Vite integration.\n   *\n   * Keeping renderer-owned configuration on the descriptor lets one rendering\n   * library expose multiple compiler modes without teaching Farm's core about\n   * each option.\n   */\n  options?: Readonly<Record<string, unknown>>;\n}\n\nexport interface FarmRendererStreamingCapabilities {\n  /** Supports Node.js writable streams through renderToPipeableStream(). */\n  node: boolean;\n  /** Supports WHATWG ReadableStream output through renderToReadableStream(). */\n  web: boolean;\n}\n\nexport interface FarmRendererCapabilities {\n  streaming: FarmRendererStreamingCapabilities;\n  /**\n   * 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\nexport interface FarmRendererCapabilitiesInput {\n  streaming?: Partial<FarmRendererStreamingCapabilities>;\n  reconcilesRerenders?: boolean;\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});\n\nexport function getFarmRendererCapabilities(\n  renderer?: Pick<FarmRenderer, \"capabilities\">,\n): FarmRendererCapabilities {\n  return {\n    streaming: {\n      node: renderer?.capabilities?.streaming?.node ?? DEFAULT_RENDERER_CAPABILITIES.streaming.node,\n      web: renderer?.capabilities?.streaming?.web ?? DEFAULT_RENDERER_CAPABILITIES.streaming.web,\n    },\n    reconcilesRerenders:\n      renderer?.capabilities?.reconcilesRerenders ??\n      DEFAULT_RENDERER_CAPABILITIES.reconcilesRerenders,\n  };\n}\n\nexport const FARM_COMPONENT_EXTENSIONS = [\".ts\", \".tsx\", \".js\", \".jsx\"] as const;\n\nexport function resolveFarmComponentExtensions(extensions: readonly string[] = []): string[] {\n  return Array.from(\n    new Set(\n      [...FARM_COMPONENT_EXTENSIONS, ...extensions].map((extension) => {\n        const normalized = extension.trim().toLowerCase();\n        return normalized.startsWith(\".\") ? normalized : `.${normalized}`;\n      }),\n    ),\n  ).filter((extension) => extension.length > 1);\n}\n\nexport function getFarmRendererComponentExtensions(\n  renderer?: Pick<FarmRenderer, \"componentExtensions\">,\n): string[] {\n  return resolveFarmComponentExtensions(renderer?.componentExtensions);\n}\n\nexport interface FarmRendererViteModule {\n  createFarmRendererPlugin(options?: {\n    ssr?: boolean;\n    rendererOptions?: Readonly<Record<string, unknown>>;\n  }): unknown | readonly unknown[] | Promise<unknown | readonly unknown[]>;\n}\n\nexport interface FarmServerRendererRuntime {\n  readonly name: string;\n  readonly Fragment: unknown;\n  readonly Suspense: unknown;\n  createElement(type: unknown, props?: unknown, ...children: unknown[]): unknown;\n  isValidElement(value: unknown): boolean;\n  /** Wraps a route-owned client tree so compiled leaf boundaries stay inside that React root. */\n  wrapClientGraph?(element: unknown): unknown;\n  /**\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?: FarmRendererCapabilities;\n  /** Optional bootstrap required before this renderer hydrates server markup. */\n  generateHydrationScript?: () => string;\n  /** Optional component used to render route-level failures. */\n  ErrorBoundary?: unknown;\n  /** Optional streaming primitive. Renderers without one use buffered SSR. */\n  renderToPipeableStream?: (\n    element: unknown,\n    callbacks: {\n      onShellReady(): void;\n      onShellError(error: unknown): void;\n      onError(error: unknown): void;\n    },\n  ) => { pipe(destination: NodeJS.WritableStream): void };\n  /** WHATWG streaming primitive used by Web-stream-capable renderers. */\n  renderToReadableStream?: (\n    element: unknown,\n  ) => ReadableStream<Uint8Array | string> | Promise<ReadableStream<Uint8Array | string>>;\n}\n\nexport const REACT_RENDERER: Readonly<FarmRenderer> = Object.freeze({\n  name: \"react\",\n  vite: \"@farm.js/core/renderer/react/vite\",\n  server: \"@farm.js/core/renderer/react/server\",\n  client: \"@farm.js/core/renderer/react/client\",\n  jsxImportSource: \"react\",\n  dedupe: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n  optimizeDeps: [\n    \"react\",\n    \"react-dom\",\n    \"react-dom/client\",\n    \"react/jsx-runtime\",\n    \"react/jsx-dev-runtime\",\n  ],\n  capabilities: {\n    streaming: { node: true, web: false },\n    reconcilesRerenders: 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","/**\n * Agent-readiness configuration: opt-in primitives that make a Farm site easier\n * for AI agents and crawlers to discover, resolve, and use. Off by default so\n * sites that do not want agent exposure (internal tools, private dashboards) are\n * unaffected.\n */\n\n/** schema.org JSON-LD emitted in the document head to identify the site. */\nexport interface FarmAgentJsonLd {\n  /**\n   * schema.org `@type`. Common values: `\"Organization\"` for a company or\n   * project, `\"SoftwareApplication\"` for a product, `\"WebSite\"`, `\"Person\"`.\n   *\n   * @default \"Organization\"\n   */\n  type?: string;\n  /** Entity name. Defaults to the site's Open Graph site name or page title. */\n  name?: string;\n  /** Canonical URL for the entity. Defaults to the configured `metadataBase`. */\n  url?: string;\n  /** Short description. Defaults to the page/site metadata description. */\n  description?: string;\n  /** Logo URL. */\n  logo?: string;\n  /** URLs that also represent this entity (social profiles, repos) — schema.org `sameAs`. */\n  sameAs?: string[];\n  /** Additional schema.org properties merged into the emitted object. */\n  properties?: Record<string, unknown>;\n}\n\nexport interface FarmAgentUserConfig {\n  /**\n   * Emit schema.org JSON-LD in the document head so agents and crawlers can\n   * resolve the site's identity. `true` emits an `Organization` built from the\n   * site's metadata; an object customizes the type and fields.\n   *\n   * @default false\n   */\n  jsonLd?: boolean | FarmAgentJsonLd;\n}\n\nexport interface ResolvedFarmAgentConfig {\n  jsonLd: FarmAgentJsonLd | false;\n}\n\nexport function resolveFarmAgentConfig(\n  input: FarmAgentUserConfig | undefined,\n): ResolvedFarmAgentConfig {\n  const jsonLd = input?.jsonLd;\n  if (!jsonLd) return { jsonLd: false };\n  return { jsonLd: jsonLd === true ? {} : jsonLd };\n}\n\nexport interface FarmAgentJsonLdContext {\n  metadataBase?: string;\n  siteName?: string;\n  title?: string;\n  description?: string;\n}\n\nfunction pruneUndefined(object: Record<string, unknown>): Record<string, unknown> {\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(object)) {\n    if (value !== undefined && value !== null && value !== \"\") result[key] = value;\n  }\n  return result;\n}\n\n/**\n * Serialize a JSON-LD object for inline `<script>` embedding, escaping `<` so a\n * value containing `</script>` cannot break out of the tag.\n */\nfunction serializeJsonLd(value: unknown): string {\n  return JSON.stringify(value).replace(/</g, \"\\\\u003c\");\n}\n\n/**\n * Build a JSON-LD `<script>` tag for the site identity, or an empty string when\n * there is not enough information to emit meaningful structured data.\n */\nexport function renderFarmAgentJsonLd(\n  config: FarmAgentJsonLd,\n  context: FarmAgentJsonLdContext,\n): string {\n  const base = pruneUndefined({\n    name: config.name ?? context.siteName ?? context.title,\n    url: config.url ?? context.metadataBase,\n    description: config.description ?? context.description,\n    logo: config.logo,\n    sameAs: config.sameAs && config.sameAs.length > 0 ? config.sameAs : undefined,\n  });\n\n  const object = {\n    \"@context\": \"https://schema.org\",\n    \"@type\": config.type || \"Organization\",\n    ...base,\n    ...(config.properties || {}),\n  };\n\n  // Nothing beyond @context/@type and no custom properties: not worth emitting.\n  if (Object.keys(object).length <= 2 && !config.properties) {\n    return \"\";\n  }\n\n  return `<script type=\"application/ld+json\">${serializeJsonLd(object)}</script>`;\n}\n","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 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 type React from \"react\";\nimport type { FarmIslandStrategy } from \"../island\";\n\nconst REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\");\nconst LEGACY_REACT_ELEMENT_TYPE = Symbol.for(\"react.element\");\nconst BOUNDARY_GRAPH_CONTEXT = Symbol.for(\"farm.isolated-hydration.client-graph-context\");\n\nfunction getBoundaryGraphContext(ReactRuntime: typeof React): React.Context<boolean> {\n  const shared = globalThis as typeof globalThis &\n    Record<symbol, WeakMap<object, React.Context<boolean>> | undefined>;\n  const contexts = shared[BOUNDARY_GRAPH_CONTEXT] ?? new WeakMap();\n  shared[BOUNDARY_GRAPH_CONTEXT] = contexts;\n  const runtimeIdentity = ReactRuntime.createElement;\n  const existing = contexts.get(runtimeIdentity);\n  if (existing) return existing;\n\n  const context = ReactRuntime.createContext(false);\n  contexts.set(runtimeIdentity, context);\n  return context;\n}\n\nfunction serializeBoundaryProps(value: unknown, seen = new Set<object>()): unknown {\n  if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n  if (typeof value === \"number\") {\n    if (!Number.isFinite(value)) throw new TypeError(\"non-finite numbers are not serializable\");\n    return value;\n  }\n  if (typeof value === \"undefined\") {\n    throw new TypeError(\"undefined values are not serializable\");\n  }\n  if (typeof value !== \"object\") {\n    throw new TypeError(`${typeof value} values are not serializable`);\n  }\n  if (\n    (value as { $$typeof?: symbol }).$$typeof === REACT_ELEMENT_TYPE ||\n    (value as { $$typeof?: symbol }).$$typeof === LEGACY_REACT_ELEMENT_TYPE\n  ) {\n    throw new TypeError(\"React elements cannot cross an isolated hydration boundary\");\n  }\n  if (seen.has(value)) throw new TypeError(\"circular props are not serializable\");\n  seen.add(value);\n  try {\n    if (Array.isArray(value)) return value.map((entry) => serializeBoundaryProps(entry, seen));\n    const prototype = Object.getPrototypeOf(value);\n    if (prototype !== Object.prototype && prototype !== null) {\n      throw new TypeError(\"class instances are not serializable\");\n    }\n    return Object.fromEntries(\n      Object.entries(value).map(([key, entry]) => [key, serializeBoundaryProps(entry, seen)]),\n    );\n  } finally {\n    seen.delete(value);\n  }\n}\n\nfunction serializeBoundaryPayload(value: unknown): string {\n  return JSON.stringify(serializeBoundaryProps(value))\n    .replace(/&/g, \"\\\\u0026\")\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/>/g, \"\\\\u003e\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\n/** @internal Keeps client-to-client imports inside one isolated React root. */\nexport function wrapFarmIsolatedClientGraph(\n  ReactRuntime: typeof React,\n  element: React.ReactNode,\n): React.ReactElement {\n  const Context = getBoundaryGraphContext(ReactRuntime);\n  return ReactRuntime.createElement(Context.Provider, { value: true }, element);\n}\n\n/** @internal Generated by Farm's experimental isolated-hydration transform. */\nexport function createFarmIsolatedClientBoundary(\n  ReactRuntime: typeof React,\n  Component: React.ComponentType<any>,\n  moduleReference: string,\n  exportName: string,\n  islandStrategy: FarmIslandStrategy,\n): React.ComponentType<any> {\n  function FarmIsolatedClientBoundary(props: Record<string, unknown>) {\n    const Context = getBoundaryGraphContext(ReactRuntime);\n    const belongsToParentClientGraph = ReactRuntime.useContext(Context);\n    const boundaryId = ReactRuntime.useId();\n\n    if (belongsToParentClientGraph) {\n      return ReactRuntime.createElement(Component, props);\n    }\n\n    let serializedProps: string;\n    try {\n      serializedProps = serializeBoundaryPayload(props);\n    } catch (error) {\n      if (typeof window === \"undefined\") {\n        console.warn(\n          `[Farm.js] Could not isolate ${moduleReference}#${exportName}: ${\n            error instanceof Error ? error.message : String(error)\n          }. The server-rendered component was preserved without client hydration.`,\n        );\n      }\n      return ReactRuntime.createElement(Component, props);\n    }\n\n    return ReactRuntime.createElement(\n      ReactRuntime.Fragment,\n      null,\n      ReactRuntime.createElement(\n        \"farm-client-boundary\",\n        {\n          \"data-farm-client-boundary\": moduleReference,\n          \"data-farm-client-id\": boundaryId,\n          \"data-farm-client-export\": exportName,\n          \"data-farm-island-strategy\": islandStrategy,\n          style: { display: \"contents\" },\n        },\n        ReactRuntime.createElement(\n          Context.Provider,\n          { value: true },\n          ReactRuntime.createElement(Component, props),\n        ),\n      ),\n      ReactRuntime.createElement(\"script\", {\n        type: \"application/json\",\n        \"data-farm-client-props\": boundaryId,\n        dangerouslySetInnerHTML: { __html: serializedProps },\n      }),\n    );\n  }\n\n  FarmIsolatedClientBoundary.displayName = `FarmIsolated(${\n    Component.displayName || Component.name || exportName\n  })`;\n  return FarmIsolatedClientBoundary;\n}\n\ntype FarmIsolatedRoot = {\n  render(element: React.ReactNode): void;\n  unmount(): void;\n};\n\ninterface FarmIsolatedRootRecord {\n  root: FarmIsolatedRoot;\n  reference: string;\n  exportName: string;\n  props: Record<string, unknown>;\n  serverHTML: string;\n  restore(error: unknown): void;\n}\n\ninterface FarmIsolatedHydrationRootOptions {\n  onUncaughtError?: (error: unknown) => void;\n}\n\nexport interface FarmIsolatedHydrationRuntimeOptions {\n  ReactRuntime: typeof React;\n  hydrateRoot(\n    container: Element,\n    element: React.ReactNode,\n    options?: FarmIsolatedHydrationRootOptions,\n  ): FarmIsolatedRoot;\n  load(reference: string): Promise<Record<string, unknown>>;\n  schedule(options: {\n    container: Element;\n    strategy: FarmIslandStrategy;\n    signal?: AbortSignal;\n    hydrate(): Promise<void>;\n  }): Promise<unknown>;\n  wrap?(element: React.ReactElement): React.ReactNode;\n  report?(message: string, error?: unknown): void;\n}\n\nfunction findBoundaryPayload(container: Element, boundaryId: string): HTMLScriptElement | null {\n  const sibling = container.nextElementSibling;\n  if (\n    sibling instanceof HTMLScriptElement &&\n    sibling.type === \"application/json\" &&\n    sibling.getAttribute(\"data-farm-client-props\") === boundaryId\n  ) {\n    return sibling;\n  }\n\n  for (const candidate of container.ownerDocument.querySelectorAll<HTMLScriptElement>(\n    'script[type=\"application/json\"][data-farm-client-props]',\n  )) {\n    if (candidate.getAttribute(\"data-farm-client-props\") === boundaryId) return candidate;\n  }\n  return null;\n}\n\n/** @internal Shared development and production runtime for isolated React roots. */\nexport function createFarmIsolatedHydrationRuntime(options: FarmIsolatedHydrationRuntimeOptions) {\n  const roots = new Map<Element, FarmIsolatedRootRecord>();\n  const pending = new Map<Element, AbortController>();\n  const report =\n    options.report ??\n    ((message: string, error?: unknown) => console.warn(`[Farm.js] ${message}`, error));\n\n  const failRoot = (\n    container: Element,\n    reference: string,\n    exportName: string,\n    serverHTML: string,\n    error: unknown,\n  ) => {\n    report(\n      `Could not hydrate isolated client boundary ${reference}#${exportName}. ` +\n        \"The server-rendered HTML was restored.\",\n      error,\n    );\n    queueMicrotask(() => {\n      try {\n        roots.get(container)?.root.unmount();\n      } catch {\n        // React may already have detached a root that failed during hydration.\n      }\n      roots.delete(container);\n      container.removeAttribute(\"data-farm-hydrated\");\n      container.removeAttribute(\"data-farm-island-hydrated\");\n      container.innerHTML = serverHTML;\n    });\n  };\n\n  class FarmIsolatedRootErrorBoundary extends options.ReactRuntime.Component<\n    { children?: React.ReactNode; onError(error: unknown): void },\n    { failed: boolean }\n  > {\n    state = { failed: false };\n\n    static getDerivedStateFromError() {\n      return { failed: true };\n    }\n\n    componentDidCatch(error: unknown) {\n      this.props.onError(error);\n    }\n\n    render() {\n      return this.state.failed ? null : this.props.children;\n    }\n  }\n\n  const createBoundaryGraph = (\n    Component: React.ComponentType<any>,\n    props: Record<string, unknown>,\n    restore: (error: unknown) => void,\n  ) => {\n    const componentElement = options.ReactRuntime.createElement(Component, props);\n    const wrappedElement = options.wrap ? options.wrap(componentElement) : componentElement;\n    return wrapFarmIsolatedClientGraph(\n      options.ReactRuntime,\n      options.ReactRuntime.createElement(\n        FarmIsolatedRootErrorBoundary,\n        { onError: restore },\n        wrappedElement,\n      ),\n    );\n  };\n\n  async function hydrate(scope: ParentNode = document, signal?: AbortSignal): Promise<void> {\n    const candidates = Array.from(\n      scope.querySelectorAll<Element>(\"farm-client-boundary[data-farm-client-boundary]\"),\n    );\n    if (\n      scope instanceof Element &&\n      scope.matches(\"farm-client-boundary[data-farm-client-boundary]\")\n    ) {\n      candidates.unshift(scope);\n    }\n    const boundaries = candidates.filter((container) => {\n      if (roots.has(container) || pending.has(container)) return false;\n      return !container.parentElement?.closest(\"farm-client-boundary[data-farm-client-boundary]\");\n    });\n\n    await Promise.all(\n      boundaries.map(async (container) => {\n        const reference = container.getAttribute(\"data-farm-client-boundary\");\n        const boundaryId = container.getAttribute(\"data-farm-client-id\");\n        const exportName = container.getAttribute(\"data-farm-client-export\") || \"default\";\n        const strategy =\n          (container.getAttribute(\"data-farm-island-strategy\") as FarmIslandStrategy | null) ??\n          \"load\";\n        if (!reference || !boundaryId) {\n          report(\"An isolated client boundary is missing its module reference or payload ID.\");\n          return;\n        }\n\n        const controller = new AbortController();\n        pending.set(container, controller);\n        const abort = () => controller.abort();\n        if (signal?.aborted) abort();\n        else signal?.addEventListener(\"abort\", abort, { once: true });\n        const cleanup = () => {\n          signal?.removeEventListener(\"abort\", abort);\n          if (pending.get(container) === controller) pending.delete(container);\n        };\n\n        let scheduled: Promise<unknown>;\n        try {\n          scheduled = options.schedule({\n            container,\n            strategy,\n            signal: controller.signal,\n            hydrate: async () => {\n              if (controller.signal.aborted || !container.isConnected) return;\n              const serverHTML = container.innerHTML;\n              try {\n                const module = await options.load(reference);\n                if (controller.signal.aborted || !container.isConnected) return;\n                const originals = module.__farm_client_boundary_originals__ as\n                  | Record<string, unknown>\n                  | undefined;\n                const Component = originals?.[exportName];\n                if (typeof Component !== \"function\" && typeof Component !== \"object\") {\n                  throw new Error(\"compiled original export was not found\");\n                }\n                const payload = findBoundaryPayload(container, boundaryId);\n                if (!payload) throw new Error(`serialized props ${boundaryId} were not found`);\n                const props = JSON.parse(payload.textContent || \"{}\");\n                if (!props || typeof props !== \"object\" || Array.isArray(props)) {\n                  throw new Error(\"serialized props must be an object\");\n                }\n\n                let rootFailure: unknown;\n                const restore = (error: unknown) => {\n                  if (rootFailure !== undefined) return;\n                  rootFailure = error;\n                  failRoot(container, reference, exportName, serverHTML, error);\n                  controller.abort();\n                };\n                const graphElement = createBoundaryGraph(\n                  Component as React.ComponentType<any>,\n                  props as Record<string, unknown>,\n                  restore,\n                );\n                const root = options.hydrateRoot(container, graphElement, {\n                  onUncaughtError: restore,\n                });\n                roots.set(container, {\n                  root,\n                  reference,\n                  exportName,\n                  props: props as Record<string, unknown>,\n                  serverHTML,\n                  restore,\n                });\n                container.setAttribute(\"data-farm-hydrated\", \"true\");\n              } catch (error) {\n                failRoot(container, reference, exportName, serverHTML, error);\n                controller.abort();\n              }\n            },\n          });\n        } catch (error) {\n          failRoot(container, reference, exportName, container.innerHTML, error);\n          controller.abort();\n          cleanup();\n          return;\n        }\n\n        const tracked = Promise.resolve(scheduled)\n          .catch((error) => {\n            if (!controller.signal.aborted) {\n              failRoot(container, reference, exportName, container.innerHTML, error);\n              controller.abort();\n            }\n          })\n          .finally(cleanup);\n        if (strategy === \"load\") await tracked;\n        else void tracked;\n      }),\n    );\n  }\n\n  function updateModule(reference: string, module: Record<string, unknown>): number {\n    const originals = module.__farm_client_boundary_originals__ as\n      | Record<string, unknown>\n      | undefined;\n    let updated = 0;\n\n    for (const [container, record] of roots) {\n      if (record.reference !== reference) continue;\n      const Component = originals?.[record.exportName];\n      if (typeof Component !== \"function\" && typeof Component !== \"object\") {\n        failRoot(\n          container,\n          record.reference,\n          record.exportName,\n          record.serverHTML,\n          new Error(\"updated compiled original export was not found\"),\n        );\n        continue;\n      }\n\n      try {\n        record.root.render(\n          createBoundaryGraph(Component as React.ComponentType<any>, record.props, record.restore),\n        );\n        updated++;\n      } catch (error) {\n        failRoot(container, record.reference, record.exportName, record.serverHTML, error);\n      }\n    }\n\n    return updated;\n  }\n\n  function dispose(scope: Node): void {\n    for (const [container, controller] of pending) {\n      if (container === scope || scope.contains(container)) {\n        controller.abort();\n        pending.delete(container);\n      }\n    }\n    for (const [container, record] of roots) {\n      if (container === scope || scope.contains(container)) {\n        try {\n          record.root.unmount();\n        } catch {\n          // The DOM owner may already have removed a failed root.\n        }\n        roots.delete(container);\n        container.removeAttribute(\"data-farm-hydrated\");\n        container.removeAttribute(\"data-farm-island-hydrated\");\n      }\n    }\n  }\n\n  return {\n    hydrate,\n    updateModule,\n    dispose,\n    rootCount: () => roots.size,\n  };\n}\n","import React from \"react\";\nimport {\n  renderToPipeableStream as reactRenderToPipeableStream,\n  renderToString as reactRenderToString,\n} from \"react-dom/server\";\nimport { wrapFarmIsolatedClientGraph } from \"../../client/isolated-boundary\";\n\nexport class ErrorBoundary extends React.Component<\n  {\n    Fallback: React.ComponentType<any>;\n    fallbackProps: Record<string, any>;\n    children: React.ReactNode;\n  },\n  { hasError: boolean; error: unknown }\n> {\n  constructor(props: any) {\n    super(props);\n    this.state = { hasError: false, error: null };\n  }\n\n  static getDerivedStateFromError(error: unknown) {\n    return { hasError: true, error };\n  }\n\n  render() {\n    if (this.state.hasError) {\n      const Fallback = this.props.Fallback;\n      return React.createElement(Fallback, {\n        ...this.props.fallbackProps,\n        error: this.state.error,\n        reset: () => this.setState({ hasError: false, error: null }),\n      });\n    }\n    return this.props.children as React.ReactElement;\n  }\n}\n\nexport const name = \"react\";\nexport const capabilities = {\n  streaming: { node: true, web: false },\n} as const;\nexport const Fragment = React.Fragment;\nexport const Suspense = React.Suspense;\nexport const createElement = React.createElement;\nexport const isValidElement = React.isValidElement;\nexport const wrapClientGraph = (element: React.ReactNode) =>\n  wrapFarmIsolatedClientGraph(React, element);\nexport const renderToString = reactRenderToString;\nexport const renderToPipeableStream = reactRenderToPipeableStream;\n\nexport default React;\n\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","export const DEFAULT_FARM_DEVTOOLS_SHORTCUT = \"mod+shift+.\";\nexport const FARM_DEVTOOLS_PATH = \"/__farm/devtools\";\nexport const FARM_DEVTOOLS_LAUNCH_PARAM = \"__farm_devtools\";\n\n/**\n * Configuration for the built-in DevTools dashboard. The dashboard is deprecated in favor\n * of the `@farm.js/devtools` plugin, which reuses this configuration for enablement and\n * the keyboard shortcut. Both options keep working while the built-in UI remains available.\n */\nexport interface FarmDevtoolsConfig {\n  /** Enable the development-only DevTools UI and runtime endpoints. */\n  enabled?: boolean;\n  /** Keyboard shortcut used to toggle DevTools, or false to disable the shortcut. */\n  shortcut?: string | false;\n}\n\nexport type FarmDevtoolsUserConfig = boolean | FarmDevtoolsConfig;\n\nexport interface ResolvedFarmDevtoolsConfig {\n  enabled: boolean;\n  shortcut: string | false;\n}\n\nexport function resolveFarmDevtoolsConfig(\n  config: FarmDevtoolsUserConfig | ResolvedFarmDevtoolsConfig | undefined,\n  mode: \"development\" | \"production\" = \"development\",\n): ResolvedFarmDevtoolsConfig {\n  if (mode !== \"development\" || config === false) {\n    return { enabled: false, shortcut: false };\n  }\n\n  const options = config === true || config === undefined ? {} : config;\n  const enabled = options.enabled ?? true;\n\n  if (!enabled) {\n    return { enabled: false, shortcut: false };\n  }\n\n  const shortcut =\n    typeof options.shortcut === \"string\" && options.shortcut.trim()\n      ? options.shortcut\n          .toLowerCase()\n          .split(\"+\")\n          .map((part) => part.trim())\n          .filter(Boolean)\n          .join(\"+\")\n      : options.shortcut === false\n        ? false\n        : DEFAULT_FARM_DEVTOOLS_SHORTCUT;\n\n  return { enabled: true, shortcut };\n}\n","export type FarmBuildActivityPosition = \"bottom-right\" | \"bottom-left\" | \"top-right\" | \"top-left\";\n\nexport interface FarmDevIndicatorsConfig {\n  /** Show build and HMR activity in the browser during development. */\n  buildActivity?: boolean;\n  /** Corner used by the build activity indicator. */\n  buildActivityPosition?: FarmBuildActivityPosition;\n}\n\nexport interface ResolvedFarmDevIndicatorsConfig {\n  buildActivity: boolean;\n  buildActivityPosition: FarmBuildActivityPosition;\n}\n\nexport function resolveFarmDevIndicatorsConfig(\n  config: FarmDevIndicatorsConfig | undefined,\n  mode: \"development\" | \"production\" = \"development\",\n): ResolvedFarmDevIndicatorsConfig {\n  return {\n    buildActivity: mode === \"development\" && (config?.buildActivity ?? true),\n    buildActivityPosition: config?.buildActivityPosition ?? \"bottom-right\",\n  };\n}\n\nexport function generateFarmDevIndicatorsClientRuntime(\n  config: ResolvedFarmDevIndicatorsConfig,\n): string {\n  if (!config.buildActivity) return \"\";\n\n  const position = {\n    \"bottom-right\": \"right: 16px; bottom: 16px;\",\n    \"bottom-left\": \"left: 16px; bottom: 16px;\",\n    \"top-right\": \"right: 16px; top: 16px;\",\n    \"top-left\": \"left: 16px; top: 16px;\",\n  }[config.buildActivityPosition];\n  const styles = `\n    #__farm_build_activity__ {\n      position: fixed;\n      ${position}\n      z-index: 2147483645;\n      display: inline-flex;\n      align-items: center;\n      gap: 7px;\n      min-height: 30px;\n      padding: 0 10px;\n      border: 1px solid rgb(255 255 255 / 0.16);\n      border-radius: 999px;\n      background: rgb(17 17 17 / 0.9);\n      box-shadow: 0 8px 24px rgb(0 0 0 / 0.2);\n      color: rgb(250 250 250);\n      font: 500 12px/1 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n      letter-spacing: -0.01em;\n      opacity: 0;\n      pointer-events: none;\n      transform: translateY(4px);\n      transition: opacity 120ms ease-out, transform 120ms ease-out;\n    }\n    #__farm_build_activity__[data-visible=\"true\"] {\n      opacity: 1;\n      transform: translateY(0);\n    }\n    #__farm_build_activity__::before {\n      width: 8px;\n      height: 8px;\n      border: 1.5px solid rgb(255 255 255 / 0.32);\n      border-top-color: currentColor;\n      border-radius: 50%;\n      content: \"\";\n      animation: farm-build-activity-spin 650ms linear infinite;\n    }\n    #__farm_build_activity__[data-state=\"ready\"]::before {\n      border-color: currentColor;\n      animation: none;\n    }\n    #__farm_build_activity__[data-state=\"error\"] {\n      border-color: rgb(248 113 113 / 0.55);\n      color: rgb(254 202 202);\n    }\n    #__farm_build_activity__[data-state=\"error\"]::before {\n      border-color: currentColor;\n      animation: none;\n    }\n    @keyframes farm-build-activity-spin { to { transform: rotate(360deg); } }\n    @media (prefers-reduced-motion: reduce) {\n      #__farm_build_activity__ { transition: none; }\n      #__farm_build_activity__::before { animation-duration: 1.4s; }\n    }\n  `;\n\n  return `\nif (import.meta.hot) {\n  (() => {\n    const hot = import.meta.hot;\n    const indicatorId = \"__farm_build_activity__\";\n    const styleId = \"__farm_build_activity_styles__\";\n    const runtimeKey = \"__FARM_BUILD_ACTIVITY_RUNTIME__\";\n    const reloadMarker = \"__FARM_BUILD_ACTIVITY_RELOADING__\";\n    let hideTimer;\n\n    const ensureIndicator = () => {\n      let style = document.getElementById(styleId);\n      if (!style) {\n        style = document.createElement(\"style\");\n        style.id = styleId;\n        style.textContent = ${JSON.stringify(styles)};\n        document.head.appendChild(style);\n      }\n\n      let indicator = document.getElementById(indicatorId);\n      if (!indicator) {\n        indicator = document.createElement(\"div\");\n        indicator.id = indicatorId;\n        indicator.setAttribute(\"role\", \"status\");\n        indicator.setAttribute(\"aria-live\", \"polite\");\n        document.body.appendChild(indicator);\n      }\n      return indicator;\n    };\n\n    const show = (state, label) => {\n      window.clearTimeout(hideTimer);\n      const indicator = ensureIndicator();\n      indicator.dataset.state = state;\n      indicator.dataset.visible = \"true\";\n      indicator.textContent = label;\n    };\n    const hide = () => {\n      const indicator = document.getElementById(indicatorId);\n      if (indicator) indicator.dataset.visible = \"false\";\n    };\n    const onBeforeUpdate = () => show(\"building\", \"Farm updating\");\n    const onAfterUpdate = () => {\n      show(\"ready\", \"Farm ready\");\n      hideTimer = window.setTimeout(hide, 500);\n    };\n    const onError = () => show(\"error\", \"Build failed\");\n    const onBeforeFullReload = () => {\n      try {\n        window.sessionStorage.setItem(reloadMarker, \"1\");\n      } catch {}\n      show(\"building\", \"Farm updating\");\n    };\n\n    window[runtimeKey]?.dispose?.();\n    ensureIndicator();\n    let completedReload = false;\n    try {\n      completedReload = window.sessionStorage.getItem(reloadMarker) === \"1\";\n      window.sessionStorage.removeItem(reloadMarker);\n    } catch {}\n    if (completedReload) onAfterUpdate();\n    else hide();\n    hot.on(\"vite:beforeUpdate\", onBeforeUpdate);\n    hot.on(\"vite:afterUpdate\", onAfterUpdate);\n    hot.on(\"vite:error\", onError);\n    hot.on(\"vite:beforeFullReload\", onBeforeFullReload);\n    window[runtimeKey] = {\n      dispose() {\n        window.clearTimeout(hideTimer);\n        hot.off(\"vite:beforeUpdate\", onBeforeUpdate);\n        hot.off(\"vite:afterUpdate\", onAfterUpdate);\n        hot.off(\"vite:error\", onError);\n        hot.off(\"vite:beforeFullReload\", onBeforeFullReload);\n        document.getElementById(indicatorId)?.remove();\n      },\n    };\n  })();\n}\n`;\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmIntegration } from \"./integrations\";\n\nexport interface FarmAuthEmailAndPasswordConfig {\n  /** Require a verified email before creating a session. @default false */\n  requireEmailVerification?: boolean;\n  /** Smallest accepted password length. @default 8 */\n  minPasswordLength?: number;\n  /** Largest accepted password length. @default 128 */\n  maxPasswordLength?: number;\n}\n\nexport interface FarmAuthSessionConfig {\n  /** Session lifetime in seconds. @default 604800 */\n  expiresIn?: number;\n  /** Session refresh interval in seconds. @default 86400 */\n  updateAge?: number;\n}\n\nexport interface FarmAuthDatabaseConfig {\n  /**\n   * Postgres connection string. Defaults to DATABASE_URL.\n   * Local development falls back to SQLite when no URL is present.\n   */\n  url?: string;\n  /** Local SQLite path. @default \".farm/auth.sqlite\" */\n  path?: string;\n  /** Automatically update the auth schema in development. @default true */\n  migrateInDevelopment?: boolean;\n}\n\nexport interface FarmAuthConfig {\n  /** Set false to disable auth without removing its configuration. @default true */\n  enabled?: boolean;\n  /** Display name used by authentication emails and metadata. */\n  appName?: string;\n  /** Route prefix for the auth endpoints. @default \"/api/auth\" */\n  basePath?: string;\n  /**\n   * Email/password authentication. It is enabled by default; set false to\n   * disable it when adding another sign-in method.\n   */\n  emailAndPassword?: boolean | FarmAuthEmailAndPasswordConfig;\n  session?: FarmAuthSessionConfig;\n  database?: FarmAuthDatabaseConfig;\n}\n\nexport type FarmAuthUserConfig = boolean | FarmAuthConfig;\n\nexport interface ResolvedFarmAuthConfig {\n  enabled: boolean;\n  appName?: string;\n  basePath: string;\n  emailAndPassword: {\n    enabled: boolean;\n    requireEmailVerification: boolean;\n    minPasswordLength: number;\n    maxPasswordLength: number;\n  };\n  session: {\n    expiresIn: number;\n    updateAge: number;\n  };\n  database: {\n    url?: string;\n    path: string;\n    migrateInDevelopment: boolean;\n  };\n}\n\ninterface FarmAuthRuntimeModule {\n  createFarmAuthIntegration(\n    config: ResolvedFarmAuthConfig,\n    options: {\n      root: string;\n      mode: \"development\" | \"production\";\n    },\n  ): FarmIntegration;\n}\n\nexport function resolveFarmAuthConfig(\n  input: FarmAuthUserConfig | undefined,\n): ResolvedFarmAuthConfig {\n  const config = input === true ? {} : input && typeof input === \"object\" ? input : {};\n  const passwordConfig = typeof config.emailAndPassword === \"object\" ? config.emailAndPassword : {};\n\n  const resolved: ResolvedFarmAuthConfig = {\n    enabled: input !== undefined && input !== false && config.enabled !== false,\n    appName: config.appName,\n    basePath: normalizeBasePath(config.basePath),\n    emailAndPassword: {\n      enabled: config.emailAndPassword !== false,\n      requireEmailVerification: passwordConfig.requireEmailVerification ?? false,\n      minPasswordLength: passwordConfig.minPasswordLength ?? 8,\n      maxPasswordLength: passwordConfig.maxPasswordLength ?? 128,\n    },\n    session: {\n      expiresIn: config.session?.expiresIn ?? 60 * 60 * 24 * 7,\n      updateAge: config.session?.updateAge ?? 60 * 60 * 24,\n    },\n    database: {\n      url: config.database?.url,\n      path: config.database?.path || \".farm/auth.sqlite\",\n      migrateInDevelopment: config.database?.migrateInDevelopment ?? true,\n    },\n  };\n\n  validateFarmAuthConfig(resolved);\n  return resolved;\n}\n\nexport async function resolveFarmAuthIntegration(\n  config: ResolvedFarmAuthConfig,\n  options: {\n    root: string;\n    mode: \"development\" | \"production\";\n  },\n): Promise<FarmIntegration | undefined> {\n  if (!config.enabled) return undefined;\n\n  const root = path.resolve(options.root);\n  let modulePath: string;\n  try {\n    const resolveFromApp = createRequire(path.join(root, \"package.json\"));\n    modulePath = resolveFromApp.resolve(\"@farm.js/auth/internal\");\n  } catch {\n    throw new Error(\n      \"The `auth` config requires @farm.js/auth. Install it with `pnpm add @farm.js/auth` and try again.\",\n    );\n  }\n\n  const runtime = (await import(\n    /* @vite-ignore */ pathToFileURL(modulePath).href\n  )) as FarmAuthRuntimeModule;\n  if (typeof runtime.createFarmAuthIntegration !== \"function\") {\n    throw new Error(\n      \"The installed @farm.js/auth package is incompatible with this version of @farm.js/core.\",\n    );\n  }\n\n  return runtime.createFarmAuthIntegration(config, {\n    ...options,\n    root,\n  });\n}\n\nfunction normalizeBasePath(value: string | undefined): string {\n  const route = (value || \"/api/auth\").trim();\n  if (!route) return \"/api/auth\";\n  assertStableBasePath(route);\n  const withLeadingSlash = route.startsWith(\"/\") ? route : `/${route}`;\n  const normalized = withLeadingSlash.replace(/\\/+/g, \"/\").replace(/\\/+$/, \"\");\n  return normalized || \"/api/auth\";\n}\n\nfunction assertStableBasePath(route: string): void {\n  if (route.includes(\"?\") || route.includes(\"#\")) {\n    throw new Error(\"auth.basePath cannot contain a query string or fragment.\");\n  }\n  if (route.startsWith(\"//\") || /^[a-z][a-z\\d+.-]*:\\/\\//i.test(route)) {\n    throw new Error('auth.basePath must be an application pathname such as \"/api/auth\".');\n  }\n  if (hasUnstablePathCharacters(route)) {\n    throw new Error(\"auth.basePath cannot contain backslashes or control characters.\");\n  }\n  for (const segment of route.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes remain literal URL pathname segments.\n    }\n    if (hasUnstablePathCharacters(decoded) || decoded.includes(\"/\")) {\n      throw new Error(\"auth.basePath cannot contain encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('auth.basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n}\n\nfunction hasUnstablePathCharacters(value: string): boolean {\n  return (\n    value.includes(\"\\\\\") ||\n    Array.from(value).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  );\n}\n\nfunction validateFarmAuthConfig(config: ResolvedFarmAuthConfig): void {\n  const { minPasswordLength, maxPasswordLength } = config.emailAndPassword;\n  if (!Number.isInteger(minPasswordLength) || minPasswordLength < 1) {\n    throw new Error(\"auth.emailAndPassword.minPasswordLength must be a positive integer.\");\n  }\n  if (!Number.isInteger(maxPasswordLength) || maxPasswordLength < minPasswordLength) {\n    throw new Error(\n      \"auth.emailAndPassword.maxPasswordLength must be an integer greater than or equal to minPasswordLength.\",\n    );\n  }\n  if (!Number.isInteger(config.session.expiresIn) || config.session.expiresIn < 1) {\n    throw new Error(\"auth.session.expiresIn must be a positive integer.\");\n  }\n  if (!Number.isInteger(config.session.updateAge) || config.session.updateAge < 0) {\n    throw new Error(\"auth.session.updateAge must be a non-negative integer.\");\n  }\n}\n","export type FarmPreloadMode = \"warn\" | \"enforce\";\n\nexport interface FarmPreloadUserConfig {\n  /** Report excess hints or remove the lower-priority hints. @default \"enforce\" */\n  mode?: FarmPreloadMode;\n  /** Maximum image preload hints per document. @default 1 */\n  maxImages?: number;\n  /** Maximum font preload hints per document. @default 2 */\n  maxFonts?: number;\n}\n\nexport interface ResolvedFarmPreloadConfig {\n  mode: FarmPreloadMode;\n  maxImages: number;\n  maxFonts: number;\n}\n\nexport interface FarmPerformanceConfig {\n  preload?: FarmPreloadUserConfig;\n}\n\nexport interface ResolvedFarmPerformanceConfig {\n  preload: ResolvedFarmPreloadConfig;\n}\n\nexport type FarmPreloadKind = \"image\" | \"font\";\n\nexport interface FarmPreloadBudgetWarning {\n  kind: FarmPreloadKind;\n  count: number;\n  budget: number;\n  removed: number;\n}\n\nexport interface FarmManagedPreloads {\n  value: string;\n  warnings: FarmPreloadBudgetWarning[];\n}\n\nexport interface FarmManagedDocumentPreloads {\n  html: string;\n  linkHeader: string;\n  warnings: FarmPreloadBudgetWarning[];\n}\n\nconst DEFAULT_PRELOAD_CONFIG: ResolvedFarmPreloadConfig = {\n  mode: \"enforce\",\n  maxImages: 1,\n  maxFonts: 2,\n};\n\nconst reportedWarnings = new Map<string, number>();\nconst PRELOAD_WARNING_TTL_MS = 60_000;\nconst MAX_REPORTED_PRELOAD_WARNINGS = 256;\n\nexport function resolveFarmPerformanceConfig(\n  config: FarmPerformanceConfig | undefined,\n): ResolvedFarmPerformanceConfig {\n  return {\n    preload: {\n      mode: config?.preload?.mode === \"warn\" ? \"warn\" : \"enforce\",\n      maxImages: normalizeBudget(config?.preload?.maxImages, DEFAULT_PRELOAD_CONFIG.maxImages),\n      maxFonts: normalizeBudget(config?.preload?.maxFonts, DEFAULT_PRELOAD_CONFIG.maxFonts),\n    },\n  };\n}\n\n/**\n * Apply image and font budgets to HTML preload elements. High-priority image\n * hints are retained before ordinary hints, making an explicitly preloaded LCP\n * image the winner when a document contains too many React-generated hints.\n */\nexport function manageFarmHtmlPreloads(\n  html: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedPreloads {\n  const elements = findHtmlLinkElements(html);\n  const candidates = elements.flatMap((element, index) => {\n    const kind = getHtmlPreloadKind(element.value);\n    return kind\n      ? [\n          {\n            index,\n            kind,\n            highPriority:\n              readHtmlAttribute(element.value, \"fetchpriority\")?.toLowerCase() === \"high\",\n          },\n        ]\n      : [];\n  });\n\n  const budget = selectPreloadsWithinBudget(candidates, config);\n  if (config.mode === \"warn\" || budget.removed.size === 0) {\n    return { value: html, warnings: budget.warnings };\n  }\n\n  return {\n    value: removeHtmlLinkElements(html, elements, budget.removed),\n    warnings: budget.warnings,\n  };\n}\n\n/** Apply the same budgets to HTTP Link preload hints, including Farm fonts. */\nexport function manageFarmLinkHeaderPreloads(\n  value: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedPreloads {\n  if (!value) return { value, warnings: [] };\n\n  const links = splitLinkHeader(value);\n  const candidates = links.flatMap((link, index) => {\n    const kind = getLinkHeaderPreloadKind(link);\n    return kind\n      ? [\n          {\n            index,\n            kind,\n            highPriority: getLinkHeaderParameter(link, \"fetchpriority\")?.toLowerCase() === \"high\",\n          },\n        ]\n      : [];\n  });\n  const budget = selectPreloadsWithinBudget(candidates, config);\n\n  return {\n    value:\n      config.mode === \"enforce\"\n        ? links.filter((_, index) => !budget.removed.has(index)).join(\", \")\n        : value,\n    warnings: budget.warnings,\n  };\n}\n\n/** Apply a single document budget across HTML and HTTP Link header hints. */\nexport function manageFarmDocumentPreloads(\n  html: string,\n  linkHeader: string,\n  config: ResolvedFarmPreloadConfig,\n): FarmManagedDocumentPreloads {\n  const elements = findHtmlLinkElements(html);\n  const links = linkHeader ? splitLinkHeader(linkHeader) : [];\n  const headerOffset = elements.length;\n  const candidates: PreloadCandidate[] = [];\n\n  for (const [index, element] of elements.entries()) {\n    const kind = getHtmlPreloadKind(element.value);\n    if (!kind) continue;\n    candidates.push({\n      index,\n      kind,\n      highPriority: readHtmlAttribute(element.value, \"fetchpriority\")?.toLowerCase() === \"high\",\n    });\n  }\n  for (const [index, link] of links.entries()) {\n    const kind = getLinkHeaderPreloadKind(link);\n    if (!kind) continue;\n    candidates.push({\n      index: headerOffset + index,\n      kind,\n      highPriority: getLinkHeaderParameter(link, \"fetchpriority\")?.toLowerCase() === \"high\",\n    });\n  }\n\n  const budget = selectPreloadsWithinBudget(candidates, config);\n  if (config.mode === \"warn\" || budget.removed.size === 0) {\n    return { html, linkHeader, warnings: budget.warnings };\n  }\n\n  return {\n    html: removeHtmlLinkElements(html, elements, budget.removed),\n    linkHeader: links.filter((_, index) => !budget.removed.has(headerOffset + index)).join(\", \"),\n    warnings: budget.warnings,\n  };\n}\n\n/** Rate-limit identical route-and-budget warnings within a server process. */\nexport function reportFarmPreloadWarnings(\n  warnings: FarmPreloadBudgetWarning[],\n  context = \"the rendered document\",\n): void {\n  const now = Date.now();\n  for (const [key, reportedAt] of reportedWarnings) {\n    if (now - reportedAt >= PRELOAD_WARNING_TTL_MS) reportedWarnings.delete(key);\n  }\n\n  for (const warning of warnings) {\n    const key = `${context}:${warning.kind}:${warning.count}:${warning.budget}:${warning.removed}`;\n    const reportedAt = reportedWarnings.get(key);\n    if (reportedAt !== undefined && now - reportedAt < PRELOAD_WARNING_TTL_MS) continue;\n    reportedWarnings.set(key, now);\n    while (reportedWarnings.size > MAX_REPORTED_PRELOAD_WARNINGS) {\n      const oldest = reportedWarnings.keys().next().value;\n      if (oldest === undefined) break;\n      reportedWarnings.delete(oldest);\n    }\n\n    const action = warning.removed > 0 ? ` Removed ${warning.removed} lower-priority hint(s).` : \"\";\n    const recommendation =\n      warning.kind === \"image\"\n        ? ' Mark only the LCP image with `preload` or `fetchPriority=\"high\"`.'\n        : \" Set `preload: false` on fonts that are not required above the fold.\";\n    console.warn(\n      `[Farm.js] ${context} emitted ${warning.count} ${warning.kind} preload hints ` +\n        `(budget: ${warning.budget}).${action}${recommendation}`,\n    );\n  }\n}\n\nexport function clearReportedFarmPreloadWarnings(): void {\n  reportedWarnings.clear();\n}\n\ninterface PreloadCandidate {\n  index: number;\n  kind: FarmPreloadKind;\n  highPriority: boolean;\n}\n\nfunction selectPreloadsWithinBudget(\n  candidates: PreloadCandidate[],\n  config: ResolvedFarmPreloadConfig,\n): { removed: Set<number>; warnings: FarmPreloadBudgetWarning[] } {\n  const removed = new Set<number>();\n  const warnings: FarmPreloadBudgetWarning[] = [];\n\n  for (const kind of [\"image\", \"font\"] as const) {\n    const matching = candidates.filter((candidate) => candidate.kind === kind);\n    const limit = kind === \"image\" ? config.maxImages : config.maxFonts;\n    if (matching.length <= limit) continue;\n\n    const retained = new Set(\n      [...matching]\n        .sort(\n          (left, right) =>\n            Number(right.highPriority) - Number(left.highPriority) || left.index - right.index,\n        )\n        .slice(0, limit)\n        .map((candidate) => candidate.index),\n    );\n\n    if (config.mode === \"enforce\") {\n      for (const candidate of matching) {\n        if (!retained.has(candidate.index)) removed.add(candidate.index);\n      }\n    }\n\n    warnings.push({\n      kind,\n      count: matching.length,\n      budget: limit,\n      removed: config.mode === \"enforce\" ? matching.length - retained.size : 0,\n    });\n  }\n\n  return { removed, warnings };\n}\n\nfunction getHtmlPreloadKind(link: string): FarmPreloadKind | undefined {\n  const rel = readHtmlAttribute(link, \"rel\")?.toLowerCase().split(/\\s+/) || [];\n  if (!rel.includes(\"preload\")) return undefined;\n  return normalizePreloadKind(readHtmlAttribute(link, \"as\"));\n}\n\nfunction getLinkHeaderPreloadKind(link: string): FarmPreloadKind | undefined {\n  const relations = getLinkHeaderParameter(link, \"rel\")?.toLowerCase().split(/\\s+/) ?? [];\n  if (!relations.includes(\"preload\")) return undefined;\n  return normalizePreloadKind(getLinkHeaderParameter(link, \"as\"));\n}\n\nfunction getLinkHeaderParameter(link: string, name: string): string | undefined {\n  const uriEnd = link.indexOf(\">\");\n  if (uriEnd === -1) return undefined;\n\n  for (const parameter of splitLinkParameters(link.slice(uriEnd + 1))) {\n    const separator = parameter.indexOf(\"=\");\n    const parameterName = (separator === -1 ? parameter : parameter.slice(0, separator))\n      .trim()\n      .toLowerCase();\n    if (parameterName !== name.toLowerCase() || separator === -1) continue;\n    const rawValue = parameter.slice(separator + 1).trim();\n    if (rawValue.startsWith('\"') && rawValue.endsWith('\"')) {\n      return rawValue.slice(1, -1).replace(/\\\\([\\\\\"])/g, \"$1\");\n    }\n    return rawValue;\n  }\n  return undefined;\n}\n\nfunction splitLinkParameters(value: string): string[] {\n  const parameters: string[] = [];\n  let start = 0;\n  let quoted = false;\n  for (let index = 0; index < value.length; index += 1) {\n    const character = value[index];\n    if (character === '\"' && !isEscaped(value, index)) quoted = !quoted;\n    else if (character === \";\" && !quoted) {\n      const parameter = value.slice(start, index).trim();\n      if (parameter) parameters.push(parameter);\n      start = index + 1;\n    }\n  }\n  const parameter = value.slice(start).trim();\n  if (parameter) parameters.push(parameter);\n  return parameters;\n}\n\nfunction normalizePreloadKind(value: string | undefined): FarmPreloadKind | undefined {\n  const normalized = value?.toLowerCase();\n  return normalized === \"image\" || normalized === \"font\" ? normalized : undefined;\n}\n\nfunction readHtmlAttribute(element: string, name: string): string | undefined {\n  const match = element.match(\n    new RegExp(`\\\\s${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\\\s>]+))`, \"i\"),\n  );\n  return match?.[1] ?? match?.[2] ?? match?.[3];\n}\n\ninterface HtmlLinkElement {\n  start: number;\n  end: number;\n  value: string;\n}\n\nfunction findHtmlLinkElements(html: string): HtmlLinkElement[] {\n  const elements: HtmlLinkElement[] = [];\n  const lowerHtml = html.toLowerCase();\n  let cursor = 0;\n\n  while (cursor < html.length) {\n    const start = html.indexOf(\"<\", cursor);\n    if (start === -1) break;\n\n    if (lowerHtml.startsWith(\"<!--\", start)) {\n      const commentEnd = lowerHtml.indexOf(\"-->\", start + 4);\n      cursor = commentEnd === -1 ? html.length : commentEnd + 3;\n      continue;\n    }\n\n    const rawText = lowerHtml\n      .slice(start)\n      .match(/^<(script|style|template|textarea|title|noscript|svg)(?=[\\s/>])/);\n    if (rawText?.[1]) {\n      const openingEnd = findHtmlTagEnd(html, start);\n      if (openingEnd === -1) break;\n      if (rawText[1] === \"svg\" && html[openingEnd - 2] === \"/\") {\n        cursor = openingEnd;\n        continue;\n      }\n      const closingStart = findHtmlClosingTag(lowerHtml, rawText[1], openingEnd);\n      if (closingStart === -1) {\n        cursor = html.length;\n        continue;\n      }\n      const closingEnd = findHtmlTagEnd(html, closingStart);\n      cursor = closingEnd === -1 ? html.length : closingEnd;\n      continue;\n    }\n\n    if (/^<link(?=[\\s/>])/i.test(html.slice(start))) {\n      const end = findHtmlTagEnd(html, start);\n      if (end === -1) break;\n      elements.push({ start, end, value: html.slice(start, end) });\n      cursor = end;\n      continue;\n    }\n\n    if (/^<\\/?[A-Za-z][\\w:-]*(?=[\\s/>])/.test(html.slice(start))) {\n      const end = findHtmlTagEnd(html, start);\n      cursor = end === -1 ? html.length : end;\n      continue;\n    }\n\n    cursor = start + 1;\n  }\n\n  return elements;\n}\n\nfunction findHtmlClosingTag(html: string, tagName: string, start: number): number {\n  const prefix = `</${tagName}`;\n  let candidate = html.indexOf(prefix, start);\n  while (candidate !== -1) {\n    const boundary = html[candidate + prefix.length];\n    if (boundary === \">\" || boundary === \"/\" || /\\s/.test(boundary ?? \"\")) return candidate;\n    candidate = html.indexOf(prefix, candidate + prefix.length);\n  }\n  return -1;\n}\n\nfunction findHtmlTagEnd(html: string, start: number): number {\n  let quote: '\"' | \"'\" | undefined;\n  for (let index = start + 1; index < html.length; index += 1) {\n    const character = html[index];\n    if (quote) {\n      if (character === quote) quote = undefined;\n    } else if (character === '\"' || character === \"'\") {\n      quote = character;\n    } else if (character === \">\") {\n      return index + 1;\n    }\n  }\n  return -1;\n}\n\nfunction removeHtmlLinkElements(\n  html: string,\n  elements: HtmlLinkElement[],\n  removed: ReadonlySet<number>,\n): string {\n  let cursor = 0;\n  let output = \"\";\n  for (const [index, element] of elements.entries()) {\n    if (!removed.has(index)) continue;\n    output += html.slice(cursor, element.start);\n    cursor = element.end;\n  }\n  return output + html.slice(cursor);\n}\n\nfunction splitLinkHeader(value: string): string[] {\n  const links: string[] = [];\n  let start = 0;\n  let insideAngleBrackets = false;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index += 1) {\n    const character = value[index];\n    if (quoted) {\n      if (character === '\"' && !isEscaped(value, index)) quoted = false;\n      continue;\n    }\n    if (character === '\"') {\n      quoted = true;\n    } else if (character === \"<\") {\n      insideAngleBrackets = true;\n    } else if (character === \">\") {\n      insideAngleBrackets = false;\n    } else if (character === \",\" && !insideAngleBrackets) {\n      links.push(value.slice(start, index).trim());\n      start = index + 1;\n    }\n  }\n\n  links.push(value.slice(start).trim());\n  return links.filter(Boolean);\n}\n\nfunction isEscaped(value: string, index: number): boolean {\n  let backslashes = 0;\n  for (let cursor = index - 1; cursor >= 0 && value[cursor] === \"\\\\\"; cursor -= 1) {\n    backslashes += 1;\n  }\n  return backslashes % 2 === 1;\n}\n\nfunction normalizeBudget(value: number | undefined, fallback: number): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value >= 0\n    ? Math.floor(value)\n    : fallback;\n}\n","export type FarmCspDirectiveValue = string | readonly string[] | boolean | null | undefined;\n\nexport type FarmCspDirectives = Readonly<Record<string, FarmCspDirectiveValue>>;\n\nexport interface FarmCspOptions {\n  /** A pre-serialized CSP value. Cannot be combined with directives. */\n  policy?: string;\n  /** CSP directives using camelCase or kebab-case names. */\n  directives?: FarmCspDirectives;\n  /** Emit Content-Security-Policy-Report-Only instead of enforcing the policy. */\n  reportOnly?: boolean;\n}\n\nexport type FarmCspConfig = string | FarmCspOptions;\n\nexport interface FarmSecurityConfig {\n  /** App-wide Content Security Policy applied to pages, APIs, and static output. */\n  csp?: FarmCspConfig | false;\n  /** @deprecated Use csp. */\n  contentSecurityPolicy?: never;\n}\n\nexport interface ResolvedFarmCspConfig {\n  value: string;\n  reportOnly: boolean;\n}\n\nexport interface ResolvedFarmSecurityConfig {\n  csp: ResolvedFarmCspConfig | false;\n}\n\nexport function resolveFarmSecurityConfig(\n  input: FarmSecurityConfig | ResolvedFarmSecurityConfig | undefined,\n): ResolvedFarmSecurityConfig {\n  if (input === undefined) return { csp: false };\n  if (!isPlainRecord(input)) {\n    throw new TypeError(\"security must be an object containing the csp option.\");\n  }\n  if (Object.prototype.hasOwnProperty.call(input, \"contentSecurityPolicy\")) {\n    throw new TypeError(\n      \"security.contentSecurityPolicy is not supported. Use security.csp instead.\",\n    );\n  }\n\n  const csp = input.csp;\n  if (csp === undefined || csp === false) return { csp: false };\n\n  if (typeof csp === \"string\") {\n    return {\n      csp: {\n        value: validateSerializedCsp(csp),\n        reportOnly: false,\n      },\n    };\n  }\n\n  if (!isPlainRecord(csp)) {\n    throw new TypeError(\"security.csp must be a policy string, false, or an options object.\");\n  }\n\n  const reportOnly = validateReportOnly(csp.reportOnly);\n  if (Object.prototype.hasOwnProperty.call(csp, \"value\")) {\n    if (\n      Object.prototype.hasOwnProperty.call(csp, \"policy\") ||\n      Object.prototype.hasOwnProperty.call(csp, \"directives\")\n    ) {\n      throw new TypeError(\n        \"Resolved security.csp values cannot include policy or directives options.\",\n      );\n    }\n    return {\n      csp: {\n        value: validateSerializedCsp(csp.value),\n        reportOnly,\n      },\n    };\n  }\n\n  const { policy, directives } = csp;\n  if (policy !== undefined && directives !== undefined) {\n    throw new TypeError(\"security.csp accepts either policy or directives, not both.\");\n  }\n  if (policy === undefined && directives === undefined) {\n    throw new TypeError(\"security.csp requires a policy string or directives object.\");\n  }\n\n  return {\n    csp: {\n      value:\n        policy !== undefined\n          ? validateSerializedCsp(policy)\n          : serializeFarmCspDirectives(directives as FarmCspDirectives),\n      reportOnly,\n    },\n  };\n}\n\nexport function serializeFarmCspDirectives(directives: FarmCspDirectives): string {\n  if (!isPlainRecord(directives)) {\n    throw new TypeError(\"security.csp.directives must be an object.\");\n  }\n  const serialized: string[] = [];\n  const normalizedNames = new Set<string>();\n\n  for (const [configuredName, configuredValue] of Object.entries(directives)) {\n    if (configuredValue === false || configuredValue === null || configuredValue === undefined) {\n      continue;\n    }\n\n    const name = normalizeDirectiveName(configuredName);\n    if (normalizedNames.has(name)) {\n      throw new TypeError(`security.csp contains the duplicate directive ${JSON.stringify(name)}.`);\n    }\n    normalizedNames.add(name);\n\n    const values =\n      configuredValue === true\n        ? []\n        : (Array.isArray(configuredValue) ? configuredValue : [configuredValue]).map(\n            validateDirectiveValue,\n          );\n    serialized.push(values.length > 0 ? `${name} ${values.join(\" \")}` : name);\n  }\n\n  if (serialized.length === 0) {\n    throw new TypeError(\"security.csp.directives must contain at least one enabled directive.\");\n  }\n  return serialized.join(\"; \");\n}\n\nexport function getFarmSecurityHeader(\n  security: ResolvedFarmSecurityConfig,\n): { key: string; value: string } | undefined {\n  if (!security.csp) return undefined;\n  return {\n    key: security.csp.reportOnly\n      ? \"Content-Security-Policy-Report-Only\"\n      : \"Content-Security-Policy\",\n    value: security.csp.value,\n  };\n}\n\n/**\n * Whether a resolved CSP would block the inline scripts the framework injects\n * into SSR documents (theme bootstrap, hydration bootstraps).\n *\n * The scripts carry no nonce or hash yet (see the CSP-nonce RFC), so they run\n * only when the governing directive — `script-src`, falling back to\n * `default-src` — permits inline script either via `'unsafe-inline'` or by\n * listing a nonce/hash source. A policy with no script-governing directive at\n * all does not restrict inline scripts, so it is not flagged. When a nonce or\n * hash is already present the app is assumed to be managing inline sources\n * deliberately and is left alone, to avoid nagging a correct-by-construction\n * setup.\n */\nexport function farmCspBlocksFrameworkInlineScripts(security: ResolvedFarmSecurityConfig): boolean {\n  if (!security.csp) return false;\n\n  const directives = parseCspDirectives(security.csp.value);\n  const governing = directives.get(\"script-src\") ?? directives.get(\"default-src\");\n  if (!governing) return false;\n\n  const allowsInline = governing.some((source) => {\n    const value = source.toLowerCase();\n    return (\n      value === \"'unsafe-inline'\" ||\n      value.startsWith(\"'nonce-\") ||\n      value.startsWith(\"'sha256-\") ||\n      value.startsWith(\"'sha384-\") ||\n      value.startsWith(\"'sha512-\")\n    );\n  });\n  return !allowsInline;\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 isPlainRecord(value: unknown): value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n","import type { ResolvedFarmEnv } from \"../env\";\n\nexport const DEFAULT_FARM_API_BASE_PATH = \"/api\";\n\nexport interface FarmAPIConfigResolverContext {\n  root: string;\n  mode: \"development\" | \"production\";\n  env: ResolvedFarmEnv;\n}\n\nexport type FarmAPIConfigValue =\n  | string\n  | undefined\n  | ((context: FarmAPIConfigResolverContext) => string | undefined | Promise<string | undefined>);\n\nexport interface FarmAPIConfig {\n  /**\n   * Public API root. An origin-only URL is joined with `basePath`; a URL that\n   * already has a path is used as-is. May be resolved from deployment context.\n   */\n  baseURL?: FarmAPIConfigValue;\n  /** Public API path and same-origin server mount used when `baseURL` has no path. @default \"/api\" */\n  basePath?: FarmAPIConfigValue;\n}\n\nexport interface ResolvedFarmAPIConfig {\n  /** Fully resolved public API root, either absolute or root-relative. */\n  baseURL: string;\n  /** Effective pathname of `baseURL`. */\n  basePath: string;\n}\n\ndeclare const __FARM_API_BASE_URL__: string | undefined;\n\nexport async function resolveFarmAPIConfig(\n  config: FarmAPIConfig | undefined,\n  context: FarmAPIConfigResolverContext,\n): Promise<ResolvedFarmAPIConfig> {\n  const configuredBasePath = await resolveConfigValue(config?.basePath, context, \"api.basePath\");\n  const basePath = normalizeFarmAPIBasePath(configuredBasePath ?? DEFAULT_FARM_API_BASE_PATH);\n  const configuredBaseURL = await resolveConfigValue(config?.baseURL, context, \"api.baseURL\");\n\n  return normalizeFarmAPIConfig({ baseURL: configuredBaseURL, basePath });\n}\n\n/** Normalize already-resolved API strings. */\nexport function normalizeFarmAPIConfig(\n  config: { baseURL?: string; basePath?: string } | undefined,\n): ResolvedFarmAPIConfig {\n  const basePath = normalizeFarmAPIBasePath(config?.basePath ?? DEFAULT_FARM_API_BASE_PATH);\n  const baseURL = config?.baseURL?.trim();\n\n  if (!baseURL) {\n    return { baseURL: basePath, basePath };\n  }\n\n  if (baseURL.startsWith(\"//\")) {\n    throw new Error(\n      'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\", not a network-path reference.',\n    );\n  }\n\n  if (baseURL.startsWith(\"/\")) {\n    const url = parseRootRelativeBaseURL(baseURL);\n    if (url.pathname !== \"/\") {\n      const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n      return { baseURL: effectivePath, basePath: effectivePath };\n    }\n    return { baseURL: basePath, basePath };\n  }\n\n  let url: URL;\n  try {\n    url = new URL(baseURL);\n  } catch {\n    throw new Error(\n      'Farm api.baseURL must be an absolute URL or a root-relative path such as \"/api\".',\n    );\n  }\n\n  if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n    throw new Error(\"Farm api.baseURL must use http or https.\");\n  }\n  if (url.search || url.hash) {\n    throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n  }\n\n  if (url.pathname !== \"/\") {\n    const effectivePath = normalizeFarmAPIBasePath(url.pathname);\n    return {\n      baseURL: `${url.origin}${effectivePath}`,\n      basePath: effectivePath,\n    };\n  }\n\n  return {\n    baseURL: basePath === \"/\" ? url.origin : `${url.origin}${basePath}`,\n    basePath,\n  };\n}\n\nexport function normalizeFarmAPIBasePath(value: string): string {\n  const hasUnstableCharacters = (candidate: string) =>\n    candidate.includes(\"\\\\\") ||\n    Array.from(candidate).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    });\n\n  if (hasUnstableCharacters(value)) {\n    throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n  }\n\n  const path = value.trim();\n  if (!path) {\n    throw new Error(\"Farm api.basePath cannot be empty.\");\n  }\n  if (path.includes(\"?\") || path.includes(\"#\")) {\n    throw new Error(\"Farm api.basePath cannot contain a query string or hash.\");\n  }\n  if (path.startsWith(\"//\")) {\n    throw new Error('Farm api.basePath must be a pathname such as \"/api\", not a URL.');\n  }\n  for (const segment of path.split(\"/\")) {\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // A malformed escape remains literal in a URL pathname. It cannot be a\n      // dot segment, so leave the ordinary URL parser to preserve it.\n    }\n    if (hasUnstableCharacters(decoded)) {\n      throw new Error(\"Farm api.basePath cannot contain backslashes or control characters.\");\n    }\n    if (decoded.includes(\"/\")) {\n      throw new Error(\"Farm api.basePath cannot contain percent-encoded path separators.\");\n    }\n    if (decoded === \".\" || decoded === \"..\") {\n      throw new Error('Farm api.basePath cannot contain \".\" or \"..\" path segments.');\n    }\n  }\n\n  const normalized = `/${path.replace(/^\\/+|\\/+$/g, \"\")}`;\n  return normalized === \"/\" ? \"/\" : normalized;\n}\n\n/** Read the API root embedded by Farm's Vite build. */\nexport function getFarmAPIBaseURL(): string {\n  if (typeof __FARM_API_BASE_URL__ !== \"undefined\" && __FARM_API_BASE_URL__) {\n    return __FARM_API_BASE_URL__;\n  }\n  return DEFAULT_FARM_API_BASE_PATH;\n}\n\n/** Resolve a canonical Farm route such as `/api/users` against an API root. */\nexport function resolveFarmAPIRequestURL(\n  routePath: string,\n  baseURL = getFarmAPIBaseURL(),\n  fallbackOrigin = getDefaultOrigin(),\n): URL {\n  const base = new URL(baseURL, fallbackOrigin);\n  if (base.pathname === \"/\") {\n    return new URL(routePath, base);\n  }\n\n  const route = new URL(routePath, fallbackOrigin);\n  const suffix = stripCanonicalAPIBasePath(route.pathname);\n  const joinedPath = joinURLPath(base.pathname, suffix);\n  base.pathname = joinedPath;\n  base.search = route.search;\n  base.hash = route.hash;\n  return base;\n}\n\nasync function resolveConfigValue(\n  value: FarmAPIConfigValue,\n  context: FarmAPIConfigResolverContext,\n  name: string,\n): Promise<string | undefined> {\n  const resolved = typeof value === \"function\" ? await value(context) : value;\n  if (resolved === undefined) return undefined;\n  if (typeof resolved !== \"string\") {\n    throw new Error(`Farm ${name} must resolve to a string or undefined.`);\n  }\n  if (!resolved.trim()) {\n    throw new Error(`Farm ${name} cannot be empty.`);\n  }\n  return resolved;\n}\n\nfunction parseRootRelativeBaseURL(value: string): URL {\n  const url = new URL(value, \"http://farm.local\");\n  if (url.search || url.hash) {\n    throw new Error(\"Farm api.baseURL cannot contain a query string or hash.\");\n  }\n  return url;\n}\n\nfunction stripCanonicalAPIBasePath(pathname: string): string {\n  if (pathname === DEFAULT_FARM_API_BASE_PATH) return \"\";\n  if (pathname.startsWith(`${DEFAULT_FARM_API_BASE_PATH}/`)) {\n    return pathname.slice(DEFAULT_FARM_API_BASE_PATH.length + 1);\n  }\n  return pathname.replace(/^\\/+/, \"\");\n}\n\nfunction joinURLPath(basePath: string, suffix: string): string {\n  const normalizedBase = basePath === \"/\" ? \"\" : basePath.replace(/\\/+$/, \"\");\n  const normalizedSuffix = suffix.replace(/^\\/+/, \"\");\n  if (!normalizedSuffix) return normalizedBase || \"/\";\n  return `${normalizedBase}/${normalizedSuffix}`;\n}\n\nfunction getDefaultOrigin(): string {\n  return typeof window !== \"undefined\" ? window.location.origin : \"http://localhost:3000\";\n}\n","import {\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","export function isFarmAPIRouteFileName(fileName: string): boolean {\n  return /^route\\.(?:ts|tsx|js|jsx)$/.test(fileName);\n}\n","import { readFileSync, writeFileSync } from \"node:fs\";\n\nexport function writeFileIfChanged(filePath: string, content: string): boolean {\n  try {\n    if (readFileSync(filePath, \"utf8\") === content) {\n      return false;\n    }\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n      throw error;\n    }\n  }\n\n  writeFileSync(filePath, content, \"utf8\");\n  return true;\n}\n","import { readFileSync, existsSync, readdirSync, mkdirSync } from \"fs\";\nimport { join, relative, dirname } from \"path\";\nimport { initSync, parse } from \"es-module-lexer\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\nimport { registerAPIRouteShape } from \"./api/route-shape\";\nimport { isFarmAPIRouteFileName } from \"./api/route-files\";\n\nlet moduleLexerInitialized = false;\n\nconst API_CLIENT_METHOD_SEGMENTS = new Set([\n  \"get\",\n  \"head\",\n  \"query\",\n  \"post\",\n  \"put\",\n  \"delete\",\n  \"patch\",\n  \"options\",\n]);\n\nexport interface APIRouteInfo {\n  path: string;\n  methods: string[];\n  filePath: string;\n  relativePath: string;\n}\n\nexport class APITypeGenerator {\n  private appDirs: string[];\n\n  constructor(appDir: string | readonly string[]) {\n    this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n  }\n\n  /**\n   * Scan all API route files and extract route information\n   */\n  scanAPIRoutes(): APIRouteInfo[] {\n    const methodSources = new Map<string, Map<string, APIRouteInfo>>();\n\n    for (const appDir of this.appDirs) {\n      const apiDir = join(appDir, \"api\");\n      if (!existsSync(apiDir)) continue;\n\n      const discovered: APIRouteInfo[] = [];\n      this.scanDirectory(apiDir, appDir, discovered);\n      for (const route of discovered) {\n        const routeMethods = methodSources.get(route.path) ?? new Map<string, APIRouteInfo>();\n        for (const method of route.methods) {\n          routeMethods.set(method, route);\n        }\n        methodSources.set(route.path, routeMethods);\n      }\n    }\n\n    const routes: APIRouteInfo[] = [];\n    for (const [routePath, methods] of methodSources) {\n      const routesByFile = new Map<string, APIRouteInfo>();\n      for (const [method, route] of methods) {\n        const existing = routesByFile.get(route.filePath);\n        if (existing) {\n          existing.methods.push(method);\n        } else {\n          routesByFile.set(route.filePath, {\n            ...route,\n            path: routePath,\n            methods: [method],\n          });\n        }\n      }\n      routes.push(...routesByFile.values());\n    }\n\n    return routes.sort(\n      (left, right) =>\n        left.path.localeCompare(right.path) || left.filePath.localeCompare(right.filePath),\n    );\n  }\n\n  private scanDirectory(dir: string, appDir: string, routes: APIRouteInfo[], basePath = \"\") {\n    const items = readdirSync(dir, { withFileTypes: true });\n\n    for (const item of items) {\n      const fullPath = join(dir, item.name);\n\n      if (item.isDirectory()) {\n        const newBasePath = basePath ? `${basePath}/${item.name}` : item.name;\n        this.scanDirectory(fullPath, appDir, routes, newBasePath);\n      } else if (isFarmAPIRouteFileName(item.name)) {\n        const routeInfo = this.extractRouteInfo(fullPath, appDir, basePath);\n        if (routeInfo) {\n          routes.push(routeInfo);\n        }\n      }\n    }\n  }\n\n  private extractRouteInfo(\n    filePath: string,\n    appDir: string,\n    basePath: string,\n  ): APIRouteInfo | null {\n    try {\n      const content = readFileSync(filePath, \"utf-8\");\n      const methods = this.extractExportedMethods(content);\n\n      if (methods.length === 0) {\n        return null;\n      }\n\n      const relativePath = relative(appDir, filePath);\n      const apiPath = basePath ? `/api/${basePath}` : \"/api\";\n\n      return {\n        path: apiPath,\n        methods,\n        filePath,\n        relativePath,\n      };\n    } catch (error) {\n      console.warn(`Failed to read route file ${filePath}:`, error);\n      return null;\n    }\n  }\n\n  private extractExportedMethods(content: string): string[] {\n    if (!moduleLexerInitialized) {\n      initSync();\n      moduleLexerInitialized = true;\n    }\n    const httpMethods = [\"GET\", \"HEAD\", \"QUERY\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"];\n    const [, exports] = parse(content);\n    const valueExports = new Set(\n      exports\n        .filter((specifier) => !this.isTypeOnlyExportSpecifier(content, specifier.s))\n        .map((specifier) => specifier.n),\n    );\n    return httpMethods.filter((method) => valueExports.has(method));\n  }\n\n  private isTypeOnlyExportSpecifier(content: string, exportNameStart: number): boolean {\n    let cursor = exportNameStart - 1;\n\n    while (cursor >= 0) {\n      while (cursor >= 0 && /\\s/.test(content[cursor])) cursor--;\n\n      if (content.slice(cursor - 1, cursor + 1) === \"*/\") {\n        const commentStart = content.lastIndexOf(\"/*\", cursor - 1);\n        if (commentStart >= 0) {\n          cursor = commentStart - 1;\n          continue;\n        }\n      }\n\n      const lineStart = content.lastIndexOf(\"\\n\", cursor) + 1;\n      const lineCommentStart = content.indexOf(\"//\", lineStart);\n      if (lineCommentStart >= 0 && lineCommentStart <= cursor) {\n        cursor = lineCommentStart - 1;\n        continue;\n      }\n\n      break;\n    }\n\n    const tokenEnd = cursor + 1;\n    while (cursor >= 0 && /[A-Za-z0-9_$]/.test(content[cursor])) cursor--;\n    return content.slice(cursor + 1, tokenEnd) === \"type\";\n  }\n\n  /**\n   * Generate TypeScript code for the API router\n   */\n  generateAPIRouter(\n    routes: APIRouteInfo[],\n    options: {\n      outFile?: string;\n      pluginConfigs?: readonly string[];\n      pluginRoutes?: readonly { path: string; method: string }[];\n    } = {},\n  ): string {\n    const imports: string[] = [];\n    const pluginTypes: string[] = [];\n    if (options.pluginConfigs?.length) {\n      imports.push('import type { PluginAPIRouter } from \"@farm.js/core/api\";');\n      options.pluginConfigs.forEach((filePath, index) => {\n        const importPath = this.getRouteImportPath({ filePath } as APIRouteInfo, options.outFile);\n        imports.push(`import type FarmPluginConfig${index} from ${JSON.stringify(importPath)};`);\n        pluginTypes.push(`PluginAPIRouter<typeof FarmPluginConfig${index}>`);\n      });\n    }\n\n    // Group routes by path to handle multiple methods\n    const routeGroups = new Map<string, APIRouteInfo[]>();\n\n    for (const route of routes) {\n      const key = route.path;\n      if (!routeGroups.has(key)) {\n        routeGroups.set(key, []);\n      }\n      routeGroups.get(key)!.push(route);\n    }\n\n    const routeMethodsByPath = new Map<string, Set<string>>();\n    for (const [routePath, routeList] of routeGroups) {\n      const cleanPath = routePath === \"/api\" ? \"\" : routePath.replace(/^\\/api\\//, \"\");\n      routeMethodsByPath.set(\n        cleanPath,\n        new Set(routeList.flatMap((route) => route.methods.map((method) => method.toLowerCase()))),\n      );\n    }\n    for (const route of options.pluginRoutes ?? []) {\n      const cleanPath = route.path === \"/api\" ? \"\" : route.path.replace(/^\\/api\\//, \"\");\n      const methods = routeMethodsByPath.get(cleanPath) ?? new Set<string>();\n      methods.add(route.method.toLowerCase());\n      routeMethodsByPath.set(cleanPath, methods);\n    }\n\n    // Build nested structure\n    const nestedStructure: any = {};\n    const usedRouteNames = new Map<string, number>();\n\n    for (const [path, routeList] of routeGroups) {\n      const routeName = this.uniqueRouteName(path, usedRouteNames);\n      const cleanPath = path === \"/api\" ? \"\" : path.replace(/^\\/api\\//, \"\");\n      const parts = cleanPath ? cleanPath.split(\"/\") : [];\n\n      // Keep the final source for each method, matching runtime layer precedence.\n      const methodSources = new Map<string, APIRouteInfo>();\n      for (const route of routeList) {\n        for (const method of route.methods) methodSources.set(method, route);\n      }\n      const allMethods = [...methodSources.keys()];\n\n      // Generate imports\n      for (const method of allMethods) {\n        const importPath = this.getRouteImportPath(methodSources.get(method)!, options.outFile);\n        const importName = `${method}_${routeName}`;\n        imports.push(\n          `import type { ${method} as ${importName} } from ${JSON.stringify(importPath)};`,\n        );\n      }\n\n      if (parts.length === 0) {\n        for (const method of allMethods) {\n          const importName = `${method}_${routeName}`;\n          const methodName = method.toLowerCase();\n          nestedStructure[methodName] = `typeof ${importName}`;\n        }\n      } else {\n        const hasMethodCollision = parts.some((part, index) => {\n          if (part === \"$params\" || (index === 0 && part === \"integrations\")) return true;\n          if (!API_CLIENT_METHOD_SEGMENTS.has(part)) return false;\n          const parentPath = parts.slice(0, index).join(\"/\");\n          return routeMethodsByPath.get(parentPath)?.has(part) === true;\n        });\n        const typePath = hasMethodCollision ? [`/${cleanPath}`] : parts;\n        // Build nested object\n        let current = nestedStructure;\n        for (let i = 0; i < typePath.length; i++) {\n          const part = typePath[i];\n          if (i === typePath.length - 1) {\n            // Last part - add methods\n            current[part] = {};\n            for (const method of allMethods) {\n              const importName = `${method}_${routeName}`;\n              const methodName = method.toLowerCase();\n              current[part][methodName] = `typeof ${importName}`;\n            }\n          } else {\n            // Intermediate part - create nested object\n            if (!current[part]) {\n              current[part] = {};\n            }\n            current = current[part];\n          }\n        }\n      }\n    }\n\n    // Convert nested structure to TypeScript code\n    const typeExports = this.structureToTypeString(nestedStructure, 1);\n    const manifest = new Map<string, Set<string>>();\n    const shapes = new Map();\n    for (const route of routes) {\n      registerAPIRouteShape(shapes, route.path, route.filePath, \"app\");\n      const methods = manifest.get(route.path) ?? new Set<string>();\n      for (const method of route.methods) methods.add(method);\n      manifest.set(route.path, methods);\n    }\n    for (const route of options.pluginRoutes ?? []) {\n      registerAPIRouteShape(shapes, route.path, `plugin:${route.path}`, \"app\");\n      const methods = manifest.get(route.path) ?? new Set<string>();\n      if (methods.has(route.method))\n        throw new Error(`Duplicate API route for ${route.method} ${route.path}`);\n      methods.add(route.method);\n      manifest.set(route.path, methods);\n    }\n    const routeManifest = [...manifest]\n      .sort(([a], [b]) => a.localeCompare(b))\n      .map(([path, methods]) => ({ path, methods: [...methods].sort() }));\n    const manifestSource = routeManifest.length\n      ? `[\\n${routeManifest\n          .map(\n            ({ path, methods }) =>\n              `  {\\n    path: ${JSON.stringify(path)},\\n    methods: [${methods.map((method) => JSON.stringify(method)).join(\", \")}],\\n  },`,\n          )\n          .join(\"\\n\")}\\n]`\n      : \"[]\";\n\n    return `/**\n * Auto-generated API router types\n * This file is automatically generated - do not edit manually\n *\n * Server modules are imported only as types. Runtime data contains paths and methods only.\n */\n\n${imports.join(\"\\n\")}\n\n// Type-only representation of your API routes\nexport type APIRouter = ${pluginTypes.length ? `${pluginTypes.join(\" & \")} & ` : \"\"}{\n${typeExports}\n};\n\n// Pass this schema-free manifest to createApiClients({ routes: apiRoutes }).\nexport const apiRoutes = ${manifestSource} as const;\n`;\n  }\n\n  private getRouteImportPath(route: APIRouteInfo, outFile?: string): string {\n    if (!outFile) {\n      return `../app/${route.relativePath.replace(/\\\\/g, \"/\").replace(/\\.(ts|tsx|js|jsx)$/, \"\")}`;\n    }\n\n    const relativeImport = relative(dirname(outFile), route.filePath)\n      .replace(/\\\\/g, \"/\")\n      .replace(/\\.(ts|tsx|js|jsx)$/, \"\");\n    return relativeImport.startsWith(\".\") ? relativeImport : `./${relativeImport}`;\n  }\n\n  private pathToRouteName(path: string): string {\n    // Replace (not strip) invalid identifier characters, so /api/id and\n    // /api/[id] do not normalize to the same name.\n    return (path === \"/api\" ? \"root\" : path.replace(/^\\/api\\//, \"\"))\n      .replace(/\\//g, \"_\")\n      .replace(/[^a-zA-Z0-9_]/g, \"_\");\n  }\n\n  private uniqueRouteName(path: string, usedNames: Map<string, number>): string {\n    const base = this.pathToRouteName(path);\n    const seen = usedNames.get(base);\n    usedNames.set(base, (seen ?? 0) + 1);\n    // Suffix any remaining collision so the generated import aliases are\n    // always distinct identifiers.\n    return seen ? `${base}_${seen + 1}` : base;\n  }\n\n  private structureToTypeString(obj: any, indent: number): string {\n    const spaces = \"  \".repeat(indent);\n    const lines: string[] = [];\n\n    for (const [key, value] of Object.entries(obj)) {\n      const propertyKey = this.toTypePropertyKey(key);\n\n      if (typeof value === \"string\") {\n        // It's a type reference\n        lines.push(`${spaces}${propertyKey}: ${value};`);\n      } else if (typeof value === \"object\") {\n        // It's a nested object\n        lines.push(`${spaces}${propertyKey}: {`);\n        lines.push(this.structureToTypeString(value, indent + 1));\n        lines.push(`${spaces}};`);\n      }\n    }\n\n    return lines.join(\"\\n\");\n  }\n\n  private toTypePropertyKey(key: string): string {\n    return /^[$A-Z_][0-9A-Z_$]*$/i.test(key) ? key : JSON.stringify(key);\n  }\n\n  private getBaseExportName(path: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n\n    if (cleanPath === \"\") {\n      return \"api\";\n    }\n\n    // Convert path to nested structure\n    // /api/auth/login -> ['auth', 'login']\n    return cleanPath;\n  }\n\n  private getExportName(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n\n    if (cleanPath === \"\") {\n      return method.toLowerCase();\n    }\n\n    const parts = cleanPath.split(\"/\");\n    if (parts.length === 1) {\n      // For single-level paths like /api/hello, just use the path name\n      return parts[0];\n    }\n\n    // For nested paths like /api/auth/login, create nested structure\n    // This matches the expected API client usage: api.auth.login()\n    return parts.join(\".\");\n  }\n\n  /**\n   * Generate the API index file\n   */\n  generateAPIIndex(outputPath: string): void {\n    const routes = this.scanAPIRoutes();\n    const content = this.generateAPIRouter(routes, { outFile: outputPath });\n\n    mkdirSync(dirname(outputPath), { recursive: true });\n    writeFileIfChanged(outputPath, content);\n    console.log(`✅ Generated API types for ${routes.length} routes`);\n  }\n}\n","import type {\n  FarmImageFormat,\n  FarmImageLocalPattern,\n  FarmImageRemotePattern,\n  ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { matchesFarmIfNoneMatch } from \"./server-http\";\n\nexport interface FarmImageTransformInput {\n  source: Uint8Array;\n  sourceUrl: URL;\n  sourceType: string;\n  width: number;\n  quality: number;\n  accept: string;\n  formats: readonly FarmImageFormat[];\n  signal: AbortSignal;\n  /**\n   * Byte ceiling for any source the transformer fetches itself. Supplied by the\n   * image handler; transformers that re-fetch the origin (Cloudflare) must\n   * enforce it, since they bypass the handler's bounded read.\n   */\n  maximumResponseBody?: number;\n}\n\nexport interface FarmImageTransformResult {\n  body: Uint8Array;\n  contentType: string;\n}\n\nexport type FarmImageTransformer = (\n  input: FarmImageTransformInput,\n) => Promise<FarmImageTransformResult>;\n\nexport interface CreateFarmImageHandlerOptions {\n  fetch?: typeof globalThis.fetch;\n  /** Node-only fetcher that validates the DNS result used for remote connections. @internal */\n  fetchRemote?: typeof globalThis.fetch;\n  transform: FarmImageTransformer;\n  validateRemoteUrl?: (url: URL) => void | Promise<void>;\n  onError?: (error: unknown, request: Request) => void;\n  cacheEntries?: number;\n}\n\nexport type FarmImageHandler = (request: Request) => Promise<Response | null>;\n\ntype OptimizedImage = FarmImageTransformResult & {\n  etag: string;\n  cacheControl: string;\n  expiresAt: number;\n};\n\ntype FarmImageRequestErrorCode =\n  | \"BODY_TOO_LARGE\"\n  | \"DISALLOWED_SOURCE\"\n  | \"INVALID_METHOD\"\n  | \"INVALID_PARAMETER\"\n  | \"PRIVATE_SOURCE\"\n  | \"TOO_MANY_REDIRECTS\"\n  | \"UNSUPPORTED_IMAGE\";\n\nexport class FarmImageRequestError extends Error {\n  readonly code: FarmImageRequestErrorCode;\n  readonly status: number;\n\n  constructor(code: FarmImageRequestErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"FarmImageRequestError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\nexport function createFarmImageHandler(\n  config: ResolvedFarmImageConfig,\n  options: CreateFarmImageHandlerOptions,\n): FarmImageHandler {\n  const fetcher = options.fetch ?? globalThis.fetch;\n  const cache = new FarmImageMemoryCache(options.cacheEntries ?? 100);\n  // Identical concurrent misses share one fetch + transform. Without this a\n  // burst for an uncached image (a new page going live, a CDN cold start)\n  // fetches the origin and runs the codec once per request.\n  const inflight = new Map<string, InflightOptimization>();\n  const allowedWidths = new Set([...config.deviceSizes, ...config.imageSizes]);\n  const allowedQualities = new Set(config.qualities);\n\n  return async function handleFarmImage(request): Promise<Response | null> {\n    const requestUrl = new URL(request.url);\n    if (requestUrl.pathname !== config.path) return null;\n\n    try {\n      if (config.provider === \"none\") {\n        throw new FarmImageRequestError(\n          \"DISALLOWED_SOURCE\",\n          404,\n          \"The Farm image optimizer is disabled\",\n        );\n      }\n      if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n        throw new FarmImageRequestError(\n          \"INVALID_METHOD\",\n          405,\n          \"The Farm image optimizer only accepts GET and HEAD\",\n        );\n      }\n\n      const sourceUrl = await resolveImageSourceUrl(requestUrl, config, options.validateRemoteUrl);\n      const width = parseAllowedInteger(requestUrl.searchParams.get(\"w\"), allowedWidths, \"width\");\n      const quality = parseAllowedInteger(\n        requestUrl.searchParams.get(\"q\"),\n        allowedQualities,\n        \"quality\",\n      );\n      const accept = request.headers.get(\"accept\") ?? \"\";\n      // Key on the format the Accept header negotiates to, not the header text.\n      // Both transformers derive their output from `selectOutputFormat(accept,\n      // formats)` alone, so every header that negotiates to the same format\n      // produces byte-identical output. Keying on the raw header let a caller\n      // vary it freely (`image/webp,*/*;q=0.8`, reordered lists, extra params)\n      // and force an uncached fetch and transform each time.\n      const negotiatedFormat = selectOutputFormat(accept, config.formats) ?? \"\";\n      const cacheKey = `${sourceUrl.href}\\n${width}\\n${quality}\\n${negotiatedFormat}`;\n      let optimized = cache.get(cacheKey);\n\n      if (!optimized) {\n        optimized = await runCoalesced(inflight, cacheKey, request.signal, async (signal) => {\n          const fetchedSource = await fetchImageSource(\n            sourceUrl,\n            requestUrl.origin,\n            config,\n            fetcher,\n            options.fetchRemote,\n            options.validateRemoteUrl,\n            signal,\n          );\n          const source = await readResponseWithLimit(\n            fetchedSource.response,\n            config.maximumResponseBody,\n          );\n          const sourceType = detectImageContentType(source);\n          validateSourceType(sourceType, config);\n          throwIfAborted(signal);\n\n          const result = await options.transform({\n            source,\n            sourceUrl: fetchedSource.url,\n            sourceType,\n            width,\n            quality,\n            accept,\n            formats: config.formats,\n            signal,\n            maximumResponseBody: config.maximumResponseBody,\n          });\n          throwIfAborted(signal);\n          validateTransformedResult(result, config);\n\n          const entry = {\n            ...result,\n            etag: createImageEtag(result.body),\n            cacheControl: `public, max-age=${config.minimumCacheTTL}, stale-while-revalidate=${Math.max(\n              config.minimumCacheTTL,\n              60,\n            )}`,\n            expiresAt: Date.now() + config.minimumCacheTTL * 1_000,\n          };\n          cache.set(cacheKey, entry);\n          return entry;\n        });\n      }\n\n      return createOptimizedImageResponse(request, optimized, config);\n    } catch (error) {\n      if (!(error instanceof FarmImageRequestError) && !isAbortError(error)) {\n        try {\n          options.onError?.(error, request);\n        } catch {\n          // Error reporting must not replace the optimizer's sanitized response.\n        }\n      }\n      return createFarmImageErrorResponse(error);\n    }\n  };\n}\n\n/** Mirrors the `images.maximumResponseBody` default (\"10mb\"). */\nconst DEFAULT_IMAGE_TRANSFORM_BODY_LIMIT = 10 * 1024 * 1024;\n\nexport function createCloudflareImageTransformer(\n  fetcher: typeof globalThis.fetch = globalThis.fetch,\n): FarmImageTransformer {\n  return async ({ sourceUrl, width, quality, accept, formats, signal, maximumResponseBody }) => {\n    const format = selectOutputFormat(accept, formats);\n    // Cloudflare resizing works by letting the edge fetch the origin, so this\n    // request cannot reuse the bytes the handler already read. It still must not\n    // be a weaker fetch than the validated one: `redirect: \"manual\"` keeps it\n    // from silently following a hop the handler never validated, and the body is\n    // read under the same ceiling as the handler's own read.\n    const response = await fetcher(sourceUrl, {\n      signal,\n      redirect: \"manual\",\n      headers: { accept: \"image/*\" },\n      cf: {\n        image: {\n          fit: \"scale-down\",\n          width,\n          quality,\n          ...(format ? { format: format === \"image/avif\" ? \"avif\" : \"webp\" } : {}),\n        },\n      },\n    } as RequestInit);\n\n    if (response.status >= 300 && response.status < 400) {\n      void cancelResponseBody(response);\n      throw new FarmImageRequestError(\n        \"UNSUPPORTED_IMAGE\",\n        502,\n        \"Source image redirected after validation\",\n      );\n    }\n\n    if (!response.ok) {\n      throw new FarmImageRequestError(\n        \"UNSUPPORTED_IMAGE\",\n        response.status === 404 ? 404 : 502,\n        \"Cloudflare could not transform the source image\",\n      );\n    }\n\n    const body = await readResponseWithLimit(\n      response,\n      maximumResponseBody ?? DEFAULT_IMAGE_TRANSFORM_BODY_LIMIT,\n    );\n    return {\n      body,\n      contentType:\n        normalizeImageContentType(response.headers.get(\"content-type\")) ||\n        detectImageContentType(body),\n    };\n  };\n}\n\nexport function selectOutputFormat(\n  accept: string,\n  formats: readonly FarmImageFormat[],\n): FarmImageFormat | undefined {\n  const qualityByFormat = new Map<string, number>();\n\n  for (const range of accept.split(\",\")) {\n    const [rawType, ...parameters] = range.split(\";\");\n    const type = rawType.trim().toLowerCase();\n    if (!type) continue;\n\n    let quality = 1;\n    for (const parameter of parameters) {\n      const [rawName, rawValue] = parameter.split(\"=\", 2);\n      if (rawName.trim().toLowerCase() !== \"q\") continue;\n      const parsed = Number(rawValue?.trim());\n      quality = Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? parsed : 0;\n      break;\n    }\n\n    qualityByFormat.set(type, Math.max(qualityByFormat.get(type) ?? 0, quality));\n  }\n\n  let selected: FarmImageFormat | undefined;\n  let selectedQuality = 0;\n  for (const format of formats) {\n    const quality = qualityByFormat.get(format) ?? 0;\n    if (quality > selectedQuality) {\n      selected = format;\n      selectedQuality = quality;\n    }\n  }\n  return selected;\n}\n\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  config: ResolvedFarmImageConfig,\n  validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n): Promise<URL> {\n  const raw = requestUrl.searchParams.get(\"url\");\n  if (!raw || raw.length > 4096 || raw.startsWith(\"//\")) {\n    throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, \"Invalid image source URL\");\n  }\n\n  let sourceUrl: URL;\n  try {\n    sourceUrl = raw.startsWith(\"/\") ? new URL(raw, requestUrl.origin) : new URL(raw);\n  } catch {\n    throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, \"Invalid image source URL\");\n  }\n\n  await validateImageSourceUrl(sourceUrl, requestUrl.origin, config, validateRemoteUrl);\n  return sourceUrl;\n}\n\nasync function validateImageSourceUrl(\n  sourceUrl: URL,\n  requestOrigin: string,\n  config: ResolvedFarmImageConfig,\n  validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n): Promise<void> {\n  if (sourceUrl.protocol !== \"http:\" && sourceUrl.protocol !== \"https:\") {\n    throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Unsupported image protocol\");\n  }\n  if (sourceUrl.username || sourceUrl.password || sourceUrl.hash) {\n    throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Unsafe image source URL\");\n  }\n\n  if (sourceUrl.origin === requestOrigin) {\n    if (\n      sourceUrl.pathname === config.path ||\n      !matchesLocalPatterns(sourceUrl, config.localPatterns)\n    ) {\n      throw new FarmImageRequestError(\n        \"DISALLOWED_SOURCE\",\n        400,\n        \"Local image source is not allowed\",\n      );\n    }\n    return;\n  }\n\n  if (!matchesRemoteSource(sourceUrl, config)) {\n    throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Remote image source is not allowed\");\n  }\n  if (!config.dangerouslyAllowLocalIP && isPrivateImageAddress(sourceUrl.hostname)) {\n    throw new FarmImageRequestError(\"PRIVATE_SOURCE\", 400, \"Private image source is not allowed\");\n  }\n  if (!config.dangerouslyAllowLocalIP) {\n    await validateRemoteUrl?.(sourceUrl);\n  }\n}\n\nasync function fetchImageSource(\n  initialUrl: URL,\n  requestOrigin: string,\n  config: ResolvedFarmImageConfig,\n  fetcher: typeof globalThis.fetch,\n  fetchRemote: typeof globalThis.fetch | undefined,\n  validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n  signal: AbortSignal,\n): Promise<{ response: Response; url: URL }> {\n  let currentUrl = initialUrl;\n\n  for (let redirectCount = 0; ; redirectCount += 1) {\n    throwIfAborted(signal);\n    const sourceFetcher = currentUrl.origin === requestOrigin ? fetcher : (fetchRemote ?? fetcher);\n    const response = await sourceFetcher(currentUrl, {\n      method: \"GET\",\n      redirect: \"manual\",\n      signal,\n      headers: {\n        accept: \"image/avif,image/webp,image/*,*/*;q=0.8\",\n        \"user-agent\": \"Farm.js Image Optimizer\",\n      },\n    });\n\n    if (![301, 302, 303, 307, 308].includes(response.status)) {\n      if (!response.ok) {\n        await cancelResponseBody(response);\n        throw new FarmImageRequestError(\n          \"UNSUPPORTED_IMAGE\",\n          response.status === 404 ? 404 : 502,\n          \"Could not fetch source image\",\n        );\n      }\n      return { response, url: currentUrl };\n    }\n\n    if (redirectCount >= config.maximumRedirects) {\n      await cancelResponseBody(response);\n      throw new FarmImageRequestError(\n        \"TOO_MANY_REDIRECTS\",\n        400,\n        \"Source image exceeded the redirect limit\",\n      );\n    }\n    const location = response.headers.get(\"location\");\n    if (!location) {\n      await cancelResponseBody(response);\n      throw new FarmImageRequestError(\"UNSUPPORTED_IMAGE\", 502, \"Invalid image redirect\");\n    }\n    await cancelResponseBody(response);\n    currentUrl = new URL(location, currentUrl);\n    await validateImageSourceUrl(currentUrl, requestOrigin, config, validateRemoteUrl);\n  }\n}\n\ntype InflightOptimization = {\n  promise: Promise<OptimizedImage>;\n  controller: AbortController;\n  waiters: number;\n};\n\n/**\n * Share one in-flight optimization between identical concurrent requests.\n *\n * The shared work runs under its own AbortController rather than any single\n * request's signal, so one caller going away cannot cancel the image everyone\n * else is waiting for. The controller is aborted only when the last waiter\n * leaves, so an abandoned burst still stops promptly.\n */\nasync function runCoalesced(\n  inflight: Map<string, InflightOptimization>,\n  key: string,\n  requestSignal: AbortSignal,\n  run: (signal: AbortSignal) => Promise<OptimizedImage>,\n): Promise<OptimizedImage> {\n  let entry = inflight.get(key);\n  if (!entry) {\n    const controller = new AbortController();\n    const created: InflightOptimization = {\n      controller,\n      waiters: 0,\n      promise: undefined as unknown as Promise<OptimizedImage>,\n    };\n    created.promise = run(controller.signal).finally(() => {\n      if (inflight.get(key) === created) inflight.delete(key);\n    });\n    // Every waiter can detach before the shared work settles: an already\n    // aborted request returns early without ever attaching to this promise,\n    // and the last waiter leaving aborts the controller. Keep one no-op\n    // handler so that rejection is never reported as unhandled. Waiters still\n    // observe it, because this does not replace the promise they await.\n    created.promise.catch(() => {});\n    inflight.set(key, created);\n    entry = created;\n  }\n\n  const pending = entry;\n  pending.waiters += 1;\n  try {\n    return await raceRequestAbort(pending.promise, requestSignal);\n  } finally {\n    pending.waiters -= 1;\n    if (pending.waiters === 0 && inflight.get(key) === pending) {\n      inflight.delete(key);\n      pending.controller.abort();\n    }\n  }\n}\n\nfunction raceRequestAbort(\n  promise: Promise<OptimizedImage>,\n  signal: AbortSignal,\n): Promise<OptimizedImage> {\n  if (!signal) return promise;\n  if (signal.aborted) return Promise.reject(signal.reason ?? new Error(\"Aborted\"));\n\n  return new Promise<OptimizedImage>((resolve, reject) => {\n    const onAbort = () => reject(signal.reason ?? new Error(\"Aborted\"));\n    signal.addEventListener(\"abort\", onAbort, { once: true });\n    promise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n  });\n}\n\nasync function readResponseWithLimit(response: Response, limit: number): Promise<Uint8Array> {\n  const contentLength = response.headers.get(\"content-length\");\n  if (contentLength && Number(contentLength) > limit) {\n    // Cleanup (including an unread tee branch) must not delay the size rejection.\n    void cancelResponseBody(response);\n    throw new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Source image is too large\");\n  }\n\n  if (!response.body) return new Uint8Array();\n  const reader = response.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let byteLength = 0;\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n      byteLength += value.byteLength;\n      if (byteLength > limit) {\n        const error = new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Source image is too large\");\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } finally {\n    reader.releaseLock();\n  }\n\n  const result = new Uint8Array(byteLength);\n  let offset = 0;\n  for (const chunk of chunks) {\n    result.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return result;\n}\n\nasync function cancelResponseBody(response: Response): Promise<void> {\n  try {\n    await response.body?.cancel();\n  } catch {\n    // Cleanup must not replace the request error or redirect result.\n  }\n}\n\nfunction detectImageContentType(bytes: Uint8Array): string {\n  if (\n    bytes.length >= 8 &&\n    bytes[0] === 0x89 &&\n    bytes[1] === 0x50 &&\n    bytes[2] === 0x4e &&\n    bytes[3] === 0x47\n  ) {\n    return \"image/png\";\n  }\n  if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n    return \"image/jpeg\";\n  }\n  if (bytes.length >= 6) {\n    const signature = new TextDecoder().decode(bytes.slice(0, 6));\n    if (signature === \"GIF87a\" || signature === \"GIF89a\") return \"image/gif\";\n  }\n  if (bytes.length >= 12) {\n    const riff = new TextDecoder().decode(bytes.slice(0, 4));\n    const webp = new TextDecoder().decode(bytes.slice(8, 12));\n    if (riff === \"RIFF\" && webp === \"WEBP\") return \"image/webp\";\n    const box = new TextDecoder().decode(bytes.slice(4, 12));\n    if (box.startsWith(\"ftypavif\") || box.startsWith(\"ftypavis\")) return \"image/avif\";\n  }\n\n  const prefix = new TextDecoder().decode(bytes.slice(0, 512)).trimStart().toLowerCase();\n  if (prefix.startsWith(\"<svg\") || (prefix.startsWith(\"<?xml\") && prefix.includes(\"<svg\"))) {\n    return \"image/svg+xml\";\n  }\n  return \"\";\n}\n\nfunction validateSourceType(type: string, config: ResolvedFarmImageConfig): void {\n  if (!type || (type === \"image/svg+xml\" && !config.dangerouslyAllowSVG)) {\n    throw new FarmImageRequestError(\"UNSUPPORTED_IMAGE\", 415, \"Unsupported source image\");\n  }\n}\n\nfunction validateTransformedResult(\n  result: FarmImageTransformResult,\n  config: ResolvedFarmImageConfig,\n): void {\n  if (!(result.body instanceof Uint8Array) || result.body.byteLength === 0) {\n    throw new Error(\"The image transformer returned an empty response\");\n  }\n  if (result.body.byteLength > config.maximumResponseBody) {\n    throw new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Optimized image is too large\");\n  }\n  const contentType = normalizeImageContentType(result.contentType);\n  if (!contentType || (contentType === \"image/svg+xml\" && !config.dangerouslyAllowSVG)) {\n    throw new Error(\"The image transformer returned an unsupported content type\");\n  }\n  result.contentType = contentType;\n}\n\nfunction normalizeImageContentType(value: string | null): string {\n  const type = value?.split(\";\", 1)[0].trim().toLowerCase() ?? \"\";\n  return type.startsWith(\"image/\") ? type : \"\";\n}\n\nfunction matchesRemoteSource(url: URL, config: ResolvedFarmImageConfig): boolean {\n  if (config.domains.includes(url.hostname.toLowerCase())) return true;\n  return config.remotePatterns.some((pattern) => matchesRemotePattern(url, pattern));\n}\n\nfunction matchesRemotePattern(url: URL, pattern: FarmImageRemotePattern): boolean {\n  return (\n    (!pattern.protocol || url.protocol === `${pattern.protocol}:`) &&\n    matchesHostname(url.hostname, pattern.hostname) &&\n    (pattern.port === undefined || url.port === pattern.port) &&\n    matchesGlob(url.pathname, pattern.pathname ?? \"/**\") &&\n    (pattern.search === undefined || url.search === pattern.search)\n  );\n}\n\nfunction matchesLocalPatterns(url: URL, patterns: readonly FarmImageLocalPattern[]): boolean {\n  return patterns.some(\n    (pattern) =>\n      matchesGlob(url.pathname, pattern.pathname) &&\n      (pattern.search === undefined || url.search === pattern.search),\n  );\n}\n\nfunction matchesHostname(hostname: string, pattern: string): boolean {\n  const normalizedHostname = hostname.toLowerCase();\n  const normalizedPattern = pattern.toLowerCase();\n  if (normalizedPattern.startsWith(\"**.\")) {\n    const suffix = normalizedPattern.slice(3);\n    return normalizedHostname === suffix || normalizedHostname.endsWith(`.${suffix}`);\n  }\n  if (normalizedPattern.startsWith(\"*.\")) {\n    const suffix = normalizedPattern.slice(2);\n    const prefix = normalizedHostname.slice(0, -(suffix.length + 1));\n    return normalizedHostname.endsWith(`.${suffix}`) && !!prefix && !prefix.includes(\".\");\n  }\n  return normalizedHostname === normalizedPattern;\n}\n\nfunction matchesGlob(value: string, pattern: string): boolean {\n  const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n  const source = escaped.replace(/\\*\\*/g, \"\\0\").replace(/\\*/g, \"[^/]*\").replace(/\\0/g, \".*\");\n  return new RegExp(`^${source}$`).test(value);\n}\n\nfunction createOptimizedImageResponse(\n  request: Request,\n  image: OptimizedImage,\n  config: ResolvedFarmImageConfig,\n): Response {\n  const headers = new Headers({\n    \"cache-control\": image.cacheControl,\n    \"content-type\": image.contentType,\n    \"content-length\": String(image.body.byteLength),\n    \"content-disposition\": \"inline\",\n    etag: image.etag,\n    vary: \"Accept\",\n    \"x-content-type-options\": \"nosniff\",\n  });\n  if (image.contentType === \"image/svg+xml\" && config.dangerouslyAllowSVG) {\n    headers.set(\"content-security-policy\", \"default-src 'none'; sandbox\");\n  }\n  if (matchesFarmIfNoneMatch(request.headers.get(\"if-none-match\"), image.etag)) {\n    headers.delete(\"content-length\");\n    return new Response(null, { status: 304, headers });\n  }\n  const body =\n    request.method === \"HEAD\"\n      ? null\n      : image.body.buffer.slice(\n          image.body.byteOffset,\n          image.body.byteOffset + image.body.byteLength,\n        );\n  return new Response(body as ArrayBuffer | null, { status: 200, headers });\n}\n\nfunction createFarmImageErrorResponse(error: unknown): Response {\n  const status =\n    error instanceof FarmImageRequestError ? error.status : isAbortError(error) ? 499 : 500;\n  const headers = new Headers({\n    \"cache-control\": \"no-store\",\n    \"content-type\": \"text/plain; charset=utf-8\",\n    \"x-content-type-options\": \"nosniff\",\n  });\n  if (status === 405) headers.set(\"allow\", \"GET, HEAD\");\n\n  const message =\n    status === 400\n      ? \"Invalid image request\"\n      : status === 404\n        ? \"Image not found\"\n        : status === 405\n          ? \"Method not allowed\"\n          : status === 413\n            ? \"Image is too large\"\n            : status === 415\n              ? \"Unsupported image\"\n              : status === 499\n                ? \"Image request cancelled\"\n                : \"Image optimization failed\";\n  return new Response(message, { status, headers });\n}\n\nfunction createImageEtag(bytes: Uint8Array): string {\n  let hash = 0x811c9dc5;\n  for (const byte of bytes) {\n    hash ^= byte;\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return `W/\"farm-${bytes.byteLength.toString(16)}-${(hash >>> 0).toString(16)}\"`;\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    throw signal.reason instanceof Error\n      ? signal.reason\n      : new DOMException(\"The image request was aborted\", \"AbortError\");\n  }\n}\n\nfunction isAbortError(error: unknown): boolean {\n  return error instanceof Error && error.name === \"AbortError\";\n}\n\nclass FarmImageMemoryCache {\n  private readonly entries = new Map<string, OptimizedImage>();\n\n  constructor(private readonly capacity: number) {}\n\n  get(key: string): OptimizedImage | undefined {\n    const value = this.entries.get(key);\n    if (!value) return undefined;\n    if (value.expiresAt <= Date.now()) {\n      this.entries.delete(key);\n      return undefined;\n    }\n    this.entries.delete(key);\n    this.entries.set(key, value);\n    return value;\n  }\n\n  set(key: string, value: OptimizedImage): void {\n    if (this.capacity <= 0) return;\n    this.entries.delete(key);\n    this.entries.set(key, value);\n    while (this.entries.size > this.capacity) {\n      const oldestKey = this.entries.keys().next().value as string | undefined;\n      if (oldestKey === undefined) break;\n      this.entries.delete(oldestKey);\n    }\n  }\n}\n","import { 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","export const FARM_NAVIGATION_HEAD_SELECTOR = [\n  \"meta[name]\",\n  \"meta[property]\",\n  \"meta[http-equiv]\",\n  \"meta[charset]\",\n  \"meta[itemprop]\",\n  'link[rel~=\"author\"]',\n  'link[rel~=\"canonical\"]',\n  'link[rel~=\"alternate\"]',\n  'link[rel~=\"icon\"]',\n  'link[rel~=\"apple-touch-icon\"]',\n  'link[rel~=\"manifest\"]',\n  'link[rel~=\"search\"]',\n  'link[rel~=\"next\"]',\n  'link[rel~=\"prev\"]',\n  'link[rel~=\"publisher\"]',\n  'link[rel~=\"license\"]',\n  'link[rel~=\"help\"]',\n  'link[rel~=\"me\"]',\n  'link[rel~=\"pingback\"]',\n  'link[rel~=\"privacy-policy\"]',\n  'link[rel~=\"terms-of-service\"]',\n].join(\",\");\n\nexport function reconcileFarmDocumentHead(nextDocument: Document): void {\n  const nextTitle = nextDocument.querySelector(\"title\");\n  document.title = nextTitle?.textContent || \"\";\n\n  document.head.querySelectorAll(FARM_NAVIGATION_HEAD_SELECTOR).forEach((node) => node.remove());\n  nextDocument.head\n    .querySelectorAll(FARM_NAVIGATION_HEAD_SELECTOR)\n    .forEach((node) => document.head.appendChild(document.importNode(node, true)));\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const FARM_DOCS_LAST_MODIFIED_MANIFEST = \".farm-docs-last-modified.json\";\n\nexport interface FarmDocsLastModifiedManifest {\n  version: 1;\n  pages: Record<string, string>;\n}\n\nexport interface CreateFarmDocsLastModifiedManifestOptions {\n  fallback?: \"mtime\" | \"now\";\n  now?: Date;\n}\n\nconst COMMIT_MARKER = \"__FARM_DOCS_COMMIT__\";\nconst DOCS_FILE_EXTENSIONS = new Set([\".md\", \".mdx\"]);\nconst manifestCache = new Map<\n  string,\n  {\n    signature: string;\n    manifest: FarmDocsLastModifiedManifest;\n  }\n>();\n\nfunction normalizeRelativePath(value: string): string {\n  return value.replace(/\\\\/g, \"/\").replace(/^\\.\\/+/, \"\");\n}\n\nfunction resolveExistingPath(filePath: string): string {\n  try {\n    return realpathSync(filePath);\n  } catch {\n    return path.resolve(filePath);\n  }\n}\n\nfunction isDocsSourceFile(filePath: string): boolean {\n  return DOCS_FILE_EXTENSIONS.has(path.extname(filePath).toLowerCase());\n}\n\nfunction discoverDocsSourceFiles(contentDir: string): string[] {\n  const files: string[] = [];\n\n  const visit = (dir: string) => {\n    for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>\n      a.name.localeCompare(b.name),\n    )) {\n      if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\n      const absolutePath = path.join(dir, entry.name);\n      if (entry.isDirectory()) {\n        visit(absolutePath);\n      } else if (entry.isFile() && isDocsSourceFile(absolutePath)) {\n        files.push(absolutePath);\n      }\n    }\n  };\n\n  if (existsSync(contentDir)) visit(contentDir);\n  return files;\n}\n\nfunction getGitLastModifiedDates(contentDir: string): Record<string, string> {\n  try {\n    const gitRoot = execFileSync(\"git\", [\"-C\", contentDir, \"rev-parse\", \"--show-toplevel\"], {\n      encoding: \"utf8\",\n      stdio: [\"ignore\", \"pipe\", \"ignore\"],\n    }).trim();\n    if (!gitRoot) return {};\n\n    const contentPathspec = normalizeRelativePath(path.relative(gitRoot, contentDir)) || \".\";\n    const contentPrefix = contentPathspec === \".\" ? \"\" : `${contentPathspec}/`;\n    const history = execFileSync(\n      \"git\",\n      [\n        \"-C\",\n        gitRoot,\n        \"-c\",\n        \"core.quotePath=false\",\n        \"log\",\n        `--format=${COMMIT_MARKER}%cI`,\n        \"--name-only\",\n        \"--\",\n        contentPathspec,\n      ],\n      {\n        encoding: \"utf8\",\n        stdio: [\"ignore\", \"pipe\", \"ignore\"],\n        maxBuffer: 32 * 1024 * 1024,\n      },\n    );\n\n    const pages: Record<string, string> = {};\n    let commitDate: string | undefined;\n\n    for (const rawLine of history.split(/\\r?\\n/)) {\n      const line = normalizeRelativePath(rawLine.trim());\n      if (!line) continue;\n\n      if (line.startsWith(COMMIT_MARKER)) {\n        commitDate = line.slice(COMMIT_MARKER.length);\n        continue;\n      }\n      if (!commitDate || (contentPrefix && !line.startsWith(contentPrefix))) continue;\n\n      const relativePath = contentPrefix ? line.slice(contentPrefix.length) : line;\n      if (isDocsSourceFile(relativePath) && !pages[relativePath]) {\n        pages[relativePath] = commitDate;\n      }\n    }\n\n    return pages;\n  } catch {\n    return {};\n  }\n}\n\nfunction readManifest(contentDir: string): FarmDocsLastModifiedManifest | null {\n  const manifestPath = path.join(contentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n  if (!existsSync(manifestPath)) return null;\n\n  try {\n    const parsed = JSON.parse(\n      readFileSync(manifestPath, \"utf8\"),\n    ) as Partial<FarmDocsLastModifiedManifest>;\n    if (parsed.version !== 1 || !parsed.pages || typeof parsed.pages !== \"object\") return null;\n\n    const pages = Object.fromEntries(\n      Object.entries(parsed.pages).filter(\n        (entry): entry is [string, string] => typeof entry[1] === \"string\" && entry[1].length > 0,\n      ),\n    );\n    return { version: 1, pages };\n  } catch {\n    return null;\n  }\n}\n\nexport function createFarmDocsLastModifiedManifest(\n  contentDir: string,\n  options: CreateFarmDocsLastModifiedManifestOptions = {},\n): FarmDocsLastModifiedManifest {\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const gitDates = getGitLastModifiedDates(resolvedContentDir);\n  const fallbackDate = (options.now ?? new Date()).toISOString();\n  const pages: Record<string, string> = {};\n\n  for (const sourcePath of discoverDocsSourceFiles(resolvedContentDir)) {\n    const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, sourcePath));\n    pages[relativePath] =\n      gitDates[relativePath] ||\n      (options.fallback === \"now\" ? fallbackDate : statSync(sourcePath).mtime.toISOString());\n  }\n\n  return { version: 1, pages };\n}\n\nfunction getLastModifiedManifest(contentDir: string): FarmDocsLastModifiedManifest {\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const manifestPath = path.join(resolvedContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n  const manifestStat = existsSync(manifestPath) ? statSync(manifestPath) : null;\n  const signature = manifestStat\n    ? `file:${manifestStat.mtimeMs}:${manifestStat.size}`\n    : \"generated\";\n  const cached = manifestCache.get(resolvedContentDir);\n  if (cached?.signature === signature) return cached.manifest;\n\n  const manifest =\n    readManifest(resolvedContentDir) ?? createFarmDocsLastModifiedManifest(resolvedContentDir);\n  manifestCache.set(resolvedContentDir, { signature, manifest });\n  return manifest;\n}\n\nexport function resolveFarmDocsPageLastModified(\n  contentDir: string,\n  sourcePath: string,\n  frontmatter: Record<string, string>,\n): string {\n  const configured =\n    frontmatter.lastModified ||\n    frontmatter.lastmod ||\n    frontmatter.lastUpdated ||\n    frontmatter.updatedAt;\n  if (configured) return configured;\n\n  const resolvedContentDir = resolveExistingPath(contentDir);\n  const resolvedSourcePath = resolveExistingPath(sourcePath);\n  const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, resolvedSourcePath));\n  const isInsideContentDir =\n    relativePath !== \"..\" && !relativePath.startsWith(\"../\") && !path.isAbsolute(relativePath);\n\n  if (isInsideContentDir) {\n    const generated = getLastModifiedManifest(resolvedContentDir).pages[relativePath];\n    if (generated) return generated;\n  }\n\n  return statSync(resolvedSourcePath).mtime.toISOString();\n}\n","import { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\nexport function isFarmDocsSearchEnabled(docs: FarmDocsResolvedConfig | undefined): boolean {\n  if (!docs?.enabled) return false;\n\n  const search = docs.config.search;\n  if (search === false) return false;\n  return !(search && typeof search === \"object\" && search.enabled === false);\n}\n\nexport function resolveFarmDocsSearchClientModule(root: string): string | undefined {\n  try {\n    const requireFromApp = createRequire(path.join(path.resolve(root), \"package.json\"));\n    const themeEntry = requireFromApp.resolve(\"@farming-labs/theme\");\n    const commandSearchModule = path.join(path.dirname(themeEntry), \"docs-command-search.mjs\");\n    if (existsSync(commandSearchModule)) return commandSearchModule;\n  } catch {\n    // The public package entry remains a compatible fallback.\n  }\n\n  return undefined;\n}\n\nexport function generateFarmDocsSearchBootstrapRuntime(): string {\n  return `(()=>{if(window.__farmDocsSearchBootstrap)return;window.__farmDocsSearchBootstrap=true;const queue=(trigger,event)=>{if(window.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__)return;event.preventDefault();event.stopPropagation();event.stopImmediatePropagation();window.__FARM_DOCS_SEARCH_PENDING__=trigger;window.__FARM_MOUNT_DOCS_SEARCH__?.()};document.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"[data-search-full]\"):null;if(target)queue(\"button\",event)},true);document.addEventListener(\"keydown\",(event)=>{if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()===\"k\")queue(\"keyboard\",event)},true)})();`;\n}\n\nexport function generateFarmDocsSearchClientRuntime(enabled: boolean, moduleId?: string): string {\n  if (!enabled || !moduleId) {\n    return `\nfunction isFarmDocsSearchPage() {\n  return false;\n}\n\nasync function mountFarmDocsSearch() {\n  return false;\n}\n`;\n  }\n\n  return `\nlet farmDocsSearchRoot = null;\nlet farmDocsSearchContainer = null;\nlet farmDocsSearchModulePromise = null;\nlet farmDocsSearchPendingTrigger = window.__FARM_DOCS_SEARCH_PENDING__ === 'keyboard'\n  ? 'keyboard'\n  : window.__FARM_DOCS_SEARCH_PENDING__\n    ? 'button'\n    : null;\nlet farmDocsSearchReady = false;\n\nfunction isFarmDocsSearchPage() {\n  return document.querySelector('[data-farm-docs-search-root]') instanceof HTMLElement;\n}\n\nfunction replayFarmDocsSearchOpen() {\n  const pendingTrigger = farmDocsSearchPendingTrigger;\n  farmDocsSearchPendingTrigger = null;\n  window.__FARM_DOCS_SEARCH_PENDING__ = null;\n  if (!pendingTrigger) return;\n\n  queueMicrotask(() => {\n    if (pendingTrigger === 'keyboard') {\n      document.dispatchEvent(\n        new KeyboardEvent('keydown', {\n          key: 'k',\n          metaKey: true,\n          bubbles: true,\n          cancelable: true,\n        }),\n      );\n    } else {\n      const trigger = document.querySelector('[data-search-full]');\n      if (trigger instanceof HTMLElement) trigger.click();\n    }\n  });\n}\n\nfunction FarmDocsSearchBridge({ component, api }) {\n  React.useEffect(() => {\n    farmDocsSearchReady = true;\n    replayFarmDocsSearchOpen();\n    return () => {\n      farmDocsSearchReady = false;\n    };\n  }, []);\n\n  return React.createElement(component, { api });\n}\n\nfunction queueFarmDocsSearchOpen(trigger, event) {\n  if (farmDocsSearchReady) return;\n  event.preventDefault();\n  event.stopPropagation();\n  event.stopImmediatePropagation();\n  farmDocsSearchPendingTrigger = trigger;\n  window.__FARM_DOCS_SEARCH_PENDING__ = trigger;\n  void mountFarmDocsSearch();\n}\n\ndocument.addEventListener(\n  'click',\n  (event) => {\n    const target = event.target instanceof Element\n      ? event.target.closest('[data-search-full]')\n      : null;\n    if (target) queueFarmDocsSearchOpen('button', event);\n  },\n  true,\n);\n\ndocument.addEventListener(\n  'keydown',\n  (event) => {\n    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {\n      queueFarmDocsSearchOpen('keyboard', event);\n    }\n  },\n  true,\n);\n\nwindow.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__ = true;\n\nasync function mountFarmDocsSearch() {\n  const container = document.querySelector('[data-farm-docs-search-root]');\n  if (!(container instanceof HTMLElement)) return false;\n  if (farmDocsSearchContainer === container && farmDocsSearchRoot) return true;\n\n  try {\n    farmDocsSearchModulePromise ||= import(${JSON.stringify(moduleId)});\n    const { DocsCommandSearch } = await farmDocsSearchModulePromise;\n    if (!container.isConnected) return false;\n\n    if (farmDocsSearchRoot) {\n      farmDocsSearchReady = false;\n      try {\n        farmDocsSearchRoot.unmount();\n      } catch {}\n    }\n\n    farmDocsSearchContainer = container;\n    farmDocsSearchRoot = createRoot(container);\n    farmDocsSearchRoot.render(\n      React.createElement(FarmDocsSearchBridge, {\n        component: DocsCommandSearch,\n        api: container.dataset.api || '/api/docs',\n      }),\n    );\n    return true;\n  } catch (error) {\n    farmDocsSearchModulePromise = null;\n    console.error('[Farm.js] Could not load docs search:', error);\n    return false;\n  }\n}\n\nwindow.__FARM_MOUNT_DOCS_SEARCH__ = mountFarmDocsSearch;\n`;\n}\n","import { createHash } from \"node:crypto\";\nimport type { LoadedFarmDocsPage } from \"./handler\";\nimport type {\n  FarmDocsResolvedConfig,\n  FarmDocsSocialImageConfig,\n  FarmDocsSocialImageFonts,\n} from \"./types\";\n\nexport const FARM_DOCS_SOCIAL_IMAGE_WIDTH = 1200;\nexport const FARM_DOCS_SOCIAL_IMAGE_HEIGHT = 630;\n\nexport interface FarmDocsSocialImageDescriptor {\n  title: string;\n  description: string;\n  section: string;\n  siteName: string;\n  brand: string;\n  pageHref: string;\n  pageUrl: string;\n  imagePath: string;\n  imageUrl: string;\n  imageAlt: string;\n  illustration: FarmDocsSocialImageIllustration;\n  fonts?: FarmDocsSocialImageFonts;\n  hash: string;\n}\n\nexport type FarmDocsSocialImageIllustration =\n  | \"auth\"\n  | \"cache\"\n  | \"cli\"\n  | \"integrations\"\n  | \"project\"\n  | \"routing\"\n  | \"runtime\";\n\nconst FARM_DOCS_SOCIAL_IMAGE_VERSION = 3;\n\nfunction normalizeEntry(entry: string): string {\n  if (!entry || entry === \"/\") return \"\";\n  return `/${entry.replace(/^\\/+|\\/+$/g, \"\")}`;\n}\n\nfunction encodeSlugPath(slug: string): string {\n  return slug\n    .split(\"/\")\n    .filter(Boolean)\n    .map((segment) => encodeURIComponent(segment))\n    .join(\"/\");\n}\n\nfunction getSocialImageConfig(docs: FarmDocsResolvedConfig): FarmDocsSocialImageConfig | undefined {\n  return typeof docs.config.socialImage === \"object\" && docs.config.socialImage\n    ? docs.config.socialImage\n    : undefined;\n}\n\nfunction getNavTitle(docs: FarmDocsResolvedConfig): string {\n  if (typeof docs.config.nav !== \"object\" || !docs.config.nav || !(\"title\" in docs.config.nav)) {\n    return \"Farm.js\";\n  }\n  return String((docs.config.nav as { title?: unknown }).title || \"Farm.js\");\n}\n\nfunction isFalse(value: string | undefined): boolean {\n  return value ? /^(false|no|none|off|disabled)$/i.test(value.trim()) : false;\n}\n\nfunction isExternalOrRootPath(value: string): boolean {\n  return /^(https?:)?\\/\\//i.test(value) || value.startsWith(\"/\");\n}\n\nexport function isFarmDocsSocialImageEnabled(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n): boolean {\n  if (docs.config.socialImage === false || getSocialImageConfig(docs)?.enabled === false) {\n    return false;\n  }\n  return !isFalse(page.frontmatter.socialImage);\n}\n\nexport function getFarmDocsCustomSocialImage(page: LoadedFarmDocsPage): string | undefined {\n  const value =\n    page.frontmatter.socialImage || page.frontmatter.openGraphImage || page.frontmatter.ogImage;\n  return value && !isFalse(value) && isExternalOrRootPath(value) ? value : undefined;\n}\n\nfunction resolveIllustration(page: LoadedFarmDocsPage): FarmDocsSocialImageIllustration {\n  const explicit = page.frontmatter.socialIllustration?.toLowerCase();\n  if (\n    explicit === \"auth\" ||\n    explicit === \"cache\" ||\n    explicit === \"cli\" ||\n    explicit === \"integrations\" ||\n    explicit === \"project\" ||\n    explicit === \"routing\" ||\n    explicit === \"runtime\"\n  ) {\n    return explicit;\n  }\n\n  const source = `${page.slug} ${page.title} ${page.section || \"\"}`.toLowerCase();\n  if (/auth|session|security|csrf/.test(source)) return \"auth\";\n  if (/cache|ppr|render|static|revalid|stream/.test(source)) return \"cache\";\n  if (/integration|stripe|prisma|better.auth|email|job|workflow/.test(source)) {\n    return \"integrations\";\n  }\n  if (/cli|test|deploy|preview|upgrade|migration|install/.test(source)) return \"cli\";\n  if (/project|structure|config|environment|markdown|docs.engine/.test(source)) {\n    return \"project\";\n  }\n  if (/rout|endpoint|middleware|navigation|server.function|server.action|api/.test(source)) {\n    return \"routing\";\n  }\n  return \"runtime\";\n}\n\nfunction createHashValue(value: unknown): string {\n  return createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\").slice(0, 16);\n}\n\nfunction resolveBaseUrl(requestUrl: URL, config: FarmDocsSocialImageConfig | undefined): URL {\n  return config?.baseUrl ? new URL(config.baseUrl) : new URL(requestUrl.origin);\n}\n\nexport function createFarmDocsSocialImageDescriptor(\n  page: LoadedFarmDocsPage,\n  docs: FarmDocsResolvedConfig,\n  requestUrl: URL,\n): FarmDocsSocialImageDescriptor {\n  const config = getSocialImageConfig(docs);\n  const siteName = config?.siteName || getNavTitle(docs);\n  const brand = config?.brand || siteName;\n  const title = page.frontmatter.socialTitle || page.title;\n  const description =\n    page.frontmatter.socialDescription ||\n    page.description ||\n    docs.config.metadata?.description ||\n    `Documentation for ${siteName}`;\n  const section = page.frontmatter.section || page.section || \"Documentation\";\n  const illustration = resolveIllustration(page);\n  const entry = normalizeEntry(docs.entry);\n  const slugPath = encodeSlugPath(page.slug) || \"index\";\n  const imagePath = `${entry}/_social/${slugPath}/opengraph-image.svg`;\n  const baseUrl = resolveBaseUrl(requestUrl, config);\n  const pageUrl = new URL(page.href, baseUrl).href;\n  const imageAlt = `${title} — ${siteName} documentation`;\n  const hash = createHashValue({\n    version: FARM_DOCS_SOCIAL_IMAGE_VERSION,\n    title,\n    description,\n    section,\n    siteName,\n    brand,\n    pageHref: page.href,\n    illustration,\n    fonts: config?.fonts,\n  });\n\n  return {\n    title,\n    description,\n    section,\n    siteName,\n    brand,\n    pageHref: page.href,\n    pageUrl,\n    imagePath,\n    imageUrl: new URL(`${imagePath}?v=${hash}`, baseUrl).href,\n    imageAlt,\n    illustration,\n    fonts: config?.fonts,\n    hash,\n  };\n}\n\nexport function getFarmDocsSocialImageSlug(\n  docs: FarmDocsResolvedConfig,\n  requestUrl: URL,\n): string | null {\n  const entry = normalizeEntry(docs.entry);\n  const prefix = `${entry}/_social/`;\n  const suffix = \"/opengraph-image.svg\";\n  if (!requestUrl.pathname.startsWith(prefix) || !requestUrl.pathname.endsWith(suffix)) {\n    return null;\n  }\n\n  const rawSlug = requestUrl.pathname.slice(prefix.length, -suffix.length);\n  if (!rawSlug) return null;\n  try {\n    const slug = rawSlug\n      .split(\"/\")\n      .map((segment) => decodeURIComponent(segment))\n      .join(\"/\");\n    if (slug.split(\"/\").some((segment) => !segment || segment === \"..\" || segment === \".\")) {\n      return null;\n    }\n    return slug === \"index\" ? \"\" : slug;\n  } catch {\n    return null;\n  }\n}\n\nfunction escapeXml(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&apos;\");\n}\n\nfunction truncate(value: string, length: number): string {\n  if (value.length <= length) return value;\n  return `${value.slice(0, Math.max(0, length - 1)).trimEnd()}…`;\n}\n\nfunction wrapText(value: string, maxCharacters: number, maxLines: number): string[] {\n  const words = value.trim().split(/\\s+/).filter(Boolean);\n  const lines: string[] = [];\n  let current = \"\";\n  let consumedWords = 0;\n\n  for (const word of words) {\n    const candidate = current ? `${current} ${word}` : word;\n    if (candidate.length <= maxCharacters || !current) {\n      current = candidate;\n      consumedWords += 1;\n      continue;\n    }\n    lines.push(current);\n    if (lines.length === maxLines) break;\n    current = word;\n    consumedWords += 1;\n  }\n\n  if (current && lines.length < maxLines) lines.push(current);\n  if (consumedWords < words.length && lines.length) {\n    lines[lines.length - 1] = truncate(`${lines[lines.length - 1]}…`, maxCharacters);\n  }\n  return lines;\n}\n\nfunction renderTextLines(\n  lines: string[],\n  x: number,\n  y: number,\n  lineHeight: number,\n  attributes: string,\n): string {\n  return lines\n    .map(\n      (line, index) =>\n        `<text x=\"${x}\" y=\"${y + index * lineHeight}\" ${attributes}>${escapeXml(line)}</text>`,\n    )\n    .join(\"\");\n}\n\nfunction renderEmbeddedFont(name: string, source: string | undefined, weight: string): string {\n  if (!source) return \"\";\n  return `@font-face{font-family:\"${name}\";src:url(\"${escapeXml(source)}\") format(\"woff2\");font-style:normal;font-weight:${weight};font-display:block;}`;\n}\n\nfunction renderArrow(x1: number, y: number, x2: number, color = \"#8b8b8b\"): string {\n  return `<path d=\"M${x1} ${y}H${x2 - 9}\" fill=\"none\" stroke=\"${color}\"/><path d=\"m${x2 - 9} ${y - 5} 9 5-9 5\" fill=\"none\" stroke=\"${color}\"/>`;\n}\n\nfunction renderPanelHeader(label: string, status: string): string {\n  return `<text x=\"819\" y=\"171\" class=\"label\">${escapeXml(label)}</text><text x=\"1134\" y=\"171\" class=\"label bright\" text-anchor=\"end\">${escapeXml(status)}</text>`;\n}\n\nfunction renderRoutingIllustration(): string {\n  return `${renderPanelHeader(\"ROUTE BLUEPRINT\", \"TYPED\")}\n    <rect x=\"819\" y=\"296\" width=\"92\" height=\"54\" fill=\"#a3a3a3\"/>\n    <text x=\"832\" y=\"327\" class=\"diagram-title ink\">src/app</text>\n    <path d=\"M911 323h41M952 232v181M952 232h44M952 323h44M952 413h44\" fill=\"none\" stroke=\"#696969\"/>\n    <rect x=\"996\" y=\"205\" width=\"138\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#414141\"/>\n    <text x=\"1010\" y=\"228\" class=\"diagram-title\">/</text><text x=\"1010\" y=\"246\" class=\"micro\">STATIC</text>\n    <rect x=\"996\" y=\"296\" width=\"138\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#414141\"/>\n    <text x=\"1010\" y=\"319\" class=\"diagram-title\">/blog/:slug</text><text x=\"1010\" y=\"337\" class=\"micro\">DYNAMIC</text>\n    <rect x=\"996\" y=\"386\" width=\"138\" height=\"55\" fill=\"#f0f0f0\"/>\n    <text x=\"1010\" y=\"410\" class=\"diagram-title ink\">/docs/:path*</text><text x=\"1010\" y=\"428\" class=\"micro ink-muted\">CATCH-ALL</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">FILE ROUTES</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">TYPES INCLUDED</text>`;\n}\n\nfunction renderAuthIllustration(): string {\n  return `${renderPanelHeader(\"REQUEST GUARD\", \"SERVER VERIFIED\")}\n    <rect x=\"819\" y=\"269\" width=\"86\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#454545\"/>\n    <text x=\"837\" y=\"292\" class=\"micro bright\">REQUEST</text><text x=\"837\" y=\"310\" class=\"diagram-title\">GET /app</text>\n    ${renderArrow(905, 296, 943)}\n    <rect x=\"943\" y=\"224\" width=\"104\" height=\"118\" fill=\"#f0f0f0\"/>\n    <path d=\"M974 271v-12a21 21 0 0 1 42 0v12M968 271h54v45h-54z\" fill=\"#050505\"/>\n    <circle cx=\"995\" cy=\"292\" r=\"4\" fill=\"#f0f0f0\"/><path d=\"M995 296v8\" stroke=\"#f0f0f0\" stroke-width=\"3\"/>\n    <text x=\"995\" y=\"332\" class=\"micro ink\" text-anchor=\"middle\">auth()</text>\n    ${renderArrow(1047, 296, 1071)}\n    <rect x=\"1071\" y=\"269\" width=\"63\" height=\"54\" fill=\"#0a0a0a\" stroke=\"#454545\"/>\n    <text x=\"1082\" y=\"292\" class=\"micro bright\">ALLOW</text><text x=\"1082\" y=\"310\" class=\"micro\">/app</text>\n    <rect x=\"819\" y=\"372\" width=\"315\" height=\"38\" fill=\"#090909\" stroke=\"#3d3d3d\"/>\n    <rect x=\"832\" y=\"385\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/>\n    <text x=\"856\" y=\"395\" class=\"code\">session.user / verified</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">SESSION TYPED</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">CSRF PROTECTED</text>`;\n}\n\nfunction renderCacheIllustration(): string {\n  return `${renderPanelHeader(\"PAGE / PRODUCT\", \"CACHE + PPR\")}\n    <rect x=\"819\" y=\"204\" width=\"315\" height=\"54\" fill=\"#f0f0f0\"/>\n    <text x=\"836\" y=\"235\" class=\"diagram-title ink\">STATIC SHELL</text><text x=\"1116\" y=\"235\" class=\"micro ink-muted\" text-anchor=\"end\">BUILD</text>\n    <rect x=\"819\" y=\"271\" width=\"198\" height=\"76\" fill=\"#a3a3a3\"/>\n    <text x=\"836\" y=\"301\" class=\"diagram-title ink\">CACHED DATA</text><text x=\"836\" y=\"326\" class=\"micro ink-muted\">tag: products</text>\n    <rect x=\"1029\" y=\"271\" width=\"105\" height=\"76\" fill=\"#0a0a0a\" stroke=\"#555\"/>\n    <text x=\"1045\" y=\"301\" class=\"diagram-title\">LIVE</text><text x=\"1045\" y=\"326\" class=\"micro\">stream</text>\n    <path d=\"M1081 347v43m-8-9 8 9 8-9\" fill=\"none\" stroke=\"#d4d4d4\"/>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">STATIC FIRST</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">DYNAMIC WHERE NEEDED</text>`;\n}\n\nfunction renderIntegrationsIllustration(): string {\n  return `${renderPanelHeader(\"INTEGRATION GRAPH\", \"ONE PRODUCT\")}\n    <path d=\"M976 309H879V247M976 309H879v87M1030 309h93V247M1030 309h93v87\" fill=\"none\" stroke=\"#4a4a4a\"/>\n    <rect x=\"819\" y=\"214\" width=\"120\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"839\" y=\"247\" class=\"diagram-title\">BETTER AUTH</text>\n    <rect x=\"819\" y=\"368\" width=\"120\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"851\" y=\"401\" class=\"diagram-title\">PRISMA</text>\n    <rect x=\"1061\" y=\"214\" width=\"73\" height=\"57\" fill=\"#0a0a0a\" stroke=\"#4b4b4b\"/><text x=\"1077\" y=\"247\" class=\"diagram-title\">STRIPE</text>\n    <rect x=\"1061\" y=\"368\" width=\"73\" height=\"57\" fill=\"#a3a3a3\"/><text x=\"1075\" y=\"401\" class=\"diagram-title ink\">VERCEL</text>\n    <rect x=\"976\" y=\"277\" width=\"94\" height=\"64\" fill=\"#f0f0f0\"/>\n    <text x=\"994\" y=\"304\" class=\"diagram-title ink\">FARM.JS</text><text x=\"994\" y=\"324\" class=\"micro ink-muted\">CORE</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">BRING YOUR STACK</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">CONNECTED ONCE</text>`;\n}\n\nfunction renderCliIllustration(): string {\n  return `${renderPanelHeader(\"TERMINAL\", \"PRODUCTION OUTPUT\")}\n    <rect x=\"819\" y=\"203\" width=\"315\" height=\"213\" fill=\"#050505\" stroke=\"#555\"/>\n    <line x1=\"819\" y1=\"236\" x2=\"1134\" y2=\"236\" stroke=\"#555\"/>\n    <circle cx=\"837\" cy=\"220\" r=\"4\" fill=\"#5d5d5d\"/><circle cx=\"850\" cy=\"220\" r=\"4\" fill=\"#7a7a7a\"/><circle cx=\"863\" cy=\"220\" r=\"4\" fill=\"#a3a3a3\"/>\n    <text x=\"837\" y=\"273\" class=\"code bright\"><tspan fill=\"#7a7a7a\">$</tspan> farm build</text>\n    <rect x=\"837\" y=\"293\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/><path d=\"m839 298 3 3 6-7\" fill=\"none\" stroke=\"#050505\" stroke-width=\"1.5\"/>\n    <text x=\"861\" y=\"303\" class=\"code\">64 routes discovered</text>\n    <rect x=\"837\" y=\"320\" width=\"11\" height=\"11\" fill=\"#a3a3a3\"/><path d=\"m839 325 3 3 6-7\" fill=\"none\" stroke=\"#050505\" stroke-width=\"1.5\"/>\n    <text x=\"861\" y=\"330\" class=\"code\">client + server bundles</text>\n    <rect x=\"837\" y=\"355\" width=\"126\" height=\"30\" fill=\"#f0f0f0\"/><text x=\"853\" y=\"374\" class=\"micro ink\">BUILD COMPLETE</text>\n    <text x=\"1115\" y=\"374\" class=\"micro\" text-anchor=\"end\">/dist</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">REAL COMMANDS</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">842MS</text>`;\n}\n\nfunction renderProjectIllustration(): string {\n  return `${renderPanelHeader(\"PROJECT MAP\", \"CONVENTION TYPED\")}\n    <rect x=\"819\" y=\"202\" width=\"315\" height=\"216\" fill=\"#050505\" stroke=\"#555\"/>\n    <text x=\"837\" y=\"227\" class=\"diagram-title bright\">my-app/</text>\n    <path d=\"M847 243v143M847 259h23M847 293h23M847 327h23M847 361h23\" fill=\"none\" stroke=\"#666\"/>\n    <rect x=\"870\" y=\"243\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"264\" class=\"code\">src/app</text><text x=\"1098\" y=\"264\" class=\"micro\" text-anchor=\"end\">ROUTES</text>\n    <rect x=\"870\" y=\"277\" width=\"246\" height=\"33\" fill=\"#f0f0f0\"/><text x=\"886\" y=\"298\" class=\"code ink\">src/app/page.tsx</text>\n    <rect x=\"870\" y=\"311\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"332\" class=\"code\">src/app/api/users/route.ts</text><text x=\"1098\" y=\"332\" class=\"micro\" text-anchor=\"end\">API</text>\n    <rect x=\"870\" y=\"345\" width=\"246\" height=\"33\" fill=\"#0a0a0a\" stroke=\"#444\"/><text x=\"886\" y=\"366\" class=\"code\">farm.config.ts</text><text x=\"1098\" y=\"366\" class=\"micro\" text-anchor=\"end\">CONFIG</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">FILES BECOME FEATURES</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">ONE CONFIG</text>`;\n}\n\nfunction renderRuntimeIllustration(): string {\n  return `${renderPanelHeader(\"PRODUCT ARCHITECTURE\", \"FULL STACK\")}\n    <rect x=\"819\" y=\"211\" width=\"315\" height=\"55\" fill=\"#f0f0f0\"/>\n    <text x=\"836\" y=\"244\" class=\"diagram-title ink\">PRODUCT SURFACE</text><text x=\"1116\" y=\"244\" class=\"micro ink-muted\" text-anchor=\"end\">UI + ROUTES</text>\n    <path d=\"M976 266v20m0 61v20\" stroke=\"#727272\"/>\n    <rect x=\"855\" y=\"286\" width=\"242\" height=\"61\" fill=\"#a3a3a3\"/>\n    <text x=\"874\" y=\"314\" class=\"diagram-title ink\">APPLICATION CORE</text><text x=\"874\" y=\"334\" class=\"micro ink-muted\">APIS · MIDDLEWARE</text>\n    <rect x=\"819\" y=\"367\" width=\"315\" height=\"55\" fill=\"#4c4c4c\"/>\n    <text x=\"836\" y=\"400\" class=\"diagram-title bright\">CONNECTED STACK</text><text x=\"1116\" y=\"400\" class=\"micro\" text-anchor=\"end\">DATA · AUTH · DEPLOY</text>\n    <line x1=\"819\" y1=\"450\" x2=\"1134\" y2=\"450\" stroke=\"#343434\"/>\n    <text x=\"819\" y=\"475\" class=\"label bright\">ONE FRAMEWORK</text><text x=\"1134\" y=\"475\" class=\"label\" text-anchor=\"end\">ONE DEPLOYMENT MODEL</text>`;\n}\n\nfunction renderIllustration(type: FarmDocsSocialImageIllustration): string {\n  switch (type) {\n    case \"auth\":\n      return renderAuthIllustration();\n    case \"cache\":\n      return renderCacheIllustration();\n    case \"cli\":\n      return renderCliIllustration();\n    case \"integrations\":\n      return renderIntegrationsIllustration();\n    case \"project\":\n      return renderProjectIllustration();\n    case \"routing\":\n      return renderRoutingIllustration();\n    default:\n      return renderRuntimeIllustration();\n  }\n}\n\nexport function renderFarmDocsSocialImageSvg(descriptor: FarmDocsSocialImageDescriptor): string {\n  const titleLines = wrapText(descriptor.title, 22, 2);\n  const longestTitleLine = Math.max(...titleLines.map((line) => line.length));\n  const titleSize = titleLines.length === 1 ? (longestTitleLine > 17 ? 62 : 74) : 56;\n  const titleLineHeight = Math.round(titleSize * 0.98);\n  const titleY = titleLines.length === 1 ? 294 : 266;\n  const descriptionY = titleY + (titleLines.length - 1) * titleLineHeight + 59;\n  const descriptionLines = wrapText(descriptor.description, 68, 2);\n  const routeY = Math.max(418, descriptionY + descriptionLines.length * 29 + 24);\n  const section = truncate(descriptor.section.toUpperCase(), 27);\n  const route = truncate(descriptor.pageHref, 42);\n  const footerUrl = truncate(descriptor.pageUrl.replace(/^https?:\\/\\//, \"\"), 70);\n  const brand = truncate(descriptor.brand.toUpperCase(), 25);\n  const titleId = `farm-docs-og-${descriptor.hash}`;\n\n  return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"${FARM_DOCS_SOCIAL_IMAGE_WIDTH}\" height=\"${FARM_DOCS_SOCIAL_IMAGE_HEIGHT}\" viewBox=\"0 0 ${FARM_DOCS_SOCIAL_IMAGE_WIDTH} ${FARM_DOCS_SOCIAL_IMAGE_HEIGHT}\" role=\"img\" aria-labelledby=\"${titleId}-title ${titleId}-description\">\n  <title id=\"${titleId}-title\">${escapeXml(descriptor.imageAlt)}</title>\n  <desc id=\"${titleId}-description\">${escapeXml(descriptor.description)}</desc>\n  <metadata>${escapeXml(JSON.stringify({ generator: \"Farm.js docs\", page: descriptor.pageUrl, illustration: descriptor.illustration }))}</metadata>\n  <style type=\"text/css\">\n    ${renderEmbeddedFont(\"Farm Sans\", descriptor.fonts?.sans, \"100 900\")}\n    ${renderEmbeddedFont(\"Farm Mono\", descriptor.fonts?.mono, \"100 900\")}\n    ${renderEmbeddedFont(\"Farm Pixel\", descriptor.fonts?.display, \"400 700\")}\n    .sans{font-family:\"Farm Sans\",\"Arial\",sans-serif}.mono,.label,.code,.diagram-title,.micro{font-family:\"Farm Mono\",\"Menlo\",\"DejaVu Sans Mono\",monospace}.pixel{font-family:\"Farm Pixel\",\"Farm Mono\",monospace}.label{fill:#8b8b8b;font-size:10px;font-weight:600;letter-spacing:1.2px}.code{fill:#8b8b8b;font-size:11px}.diagram-title{fill:#e7e7e7;font-size:11px;font-weight:650}.micro{fill:#777;font-size:8px;letter-spacing:.45px}.bright{fill:#f5f5f4}.ink{fill:#050505}.ink-muted{fill:#4c4c4c}\n  </style>\n  <defs>\n    <pattern id=\"canvas-grid\" width=\"40\" height=\"40\" patternUnits=\"userSpaceOnUse\"><path d=\"M40 0H0V40\" fill=\"none\" stroke=\"#151515\"/></pattern>\n    <pattern id=\"diagonal\" width=\"12\" height=\"12\" patternUnits=\"userSpaceOnUse\" patternTransform=\"rotate(45)\"><line x1=\"0\" y1=\"0\" x2=\"0\" y2=\"12\" stroke=\"#171717\" stroke-width=\"2\"/></pattern>\n    <clipPath id=\"frame-clip\"><rect x=\"28\" y=\"28\" width=\"1144\" height=\"574\"/></clipPath>\n  </defs>\n  <rect width=\"1200\" height=\"630\" fill=\"#050505\"/>\n  <rect width=\"1200\" height=\"630\" fill=\"url(#canvas-grid)\"/>\n  <g clip-path=\"url(#frame-clip)\">\n    <rect x=\"28\" y=\"28\" width=\"1144\" height=\"574\" fill=\"#020202\"/>\n    <rect x=\"782\" y=\"114\" width=\"390\" height=\"411\" fill=\"url(#diagonal)\"/>\n  </g>\n  <rect x=\"28.5\" y=\"28.5\" width=\"1143\" height=\"573\" fill=\"none\" stroke=\"#323232\"/>\n  <path d=\"M28 114.5h1144M28 525.5h1144M781.5 114v411\" fill=\"none\" stroke=\"#303030\"/>\n\n  <g transform=\"translate(71 51)\">\n    <rect width=\"11\" height=\"11\" rx=\"1\" fill=\"#f5f5f4\"/><rect x=\"15\" width=\"28\" height=\"11\" rx=\"1\" fill=\"#f5f5f4\"/>\n    <rect y=\"15\" width=\"11\" height=\"11\" rx=\"1\" fill=\"#9b9b9b\"/><rect x=\"15\" y=\"15\" width=\"28\" height=\"11\" rx=\"1\" fill=\"#9b9b9b\"/>\n    <rect y=\"30\" width=\"11\" height=\"11\" rx=\"1\" fill=\"#5f5f5f\"/><rect x=\"15\" y=\"30\" width=\"20\" height=\"11\" rx=\"1\" fill=\"#5f5f5f\"/>\n    <text x=\"61\" y=\"24\" class=\"mono bright\" font-size=\"24\" font-weight=\"550\">FARM<tspan fill=\"#777\">.JS</tspan></text>\n    <text x=\"61\" y=\"43\" class=\"label\">BY FARMING LABS</text>\n  </g>\n  <text x=\"1134\" y=\"72\" class=\"label\" text-anchor=\"end\">${escapeXml(brand)} · DOCUMENTATION</text>\n\n  <text x=\"71\" y=\"198\" class=\"mono bright\" font-size=\"13\" font-weight=\"650\">DOCS</text>\n  <line x1=\"117\" y1=\"193\" x2=\"155\" y2=\"193\" stroke=\"#696969\"/>\n  <text x=\"166\" y=\"198\" class=\"mono\" fill=\"#9b9b9b\" font-size=\"13\">${escapeXml(section)}</text>\n  ${renderTextLines(titleLines, 71, titleY, titleLineHeight, `class=\"pixel bright\" font-size=\"${titleSize}\" font-weight=\"500\" letter-spacing=\"-2.4\"`)}\n  ${renderTextLines(descriptionLines, 71, descriptionY, 29, 'class=\"sans\" fill=\"#a3a3a3\" font-size=\"20\" font-weight=\"430\" letter-spacing=\"-.3\"')}\n  <rect x=\"71\" y=\"${routeY}\" width=\"${Math.min(390, 56 + route.length * 8)}\" height=\"36\" fill=\"#050505\" stroke=\"#3c3c3c\"/>\n  <text x=\"85\" y=\"${routeY + 23}\" class=\"mono bright\" font-size=\"11\" font-weight=\"600\">GET</text>\n  <text x=\"119\" y=\"${routeY + 23}\" class=\"mono\" fill=\"#898989\" font-size=\"11\">${escapeXml(route)}</text>\n\n  ${renderIllustration(descriptor.illustration)}\n\n  <text x=\"71\" y=\"570\" class=\"mono bright\" font-size=\"13\" font-weight=\"550\">${escapeXml(footerUrl)}</text>\n  <text x=\"1134\" y=\"570\" class=\"mono\" fill=\"#9b9b9b\" font-size=\"12\" text-anchor=\"end\">FARM.JS DOCUMENTATION</text>\n  <path d=\"M20 20h10M20 20v10M1180 20h-10M1180 20v10M20 610h10M20 610v-10M1180 610h-10M1180 610v-10\" fill=\"none\" stroke=\"#9b9b9b\"/>\n</svg>`;\n}\n\nexport function renderFarmDocsSocialMetadata(\n  descriptor: FarmDocsSocialImageDescriptor,\n  customImage?: string,\n): string {\n  const imageUrl = customImage\n    ? new URL(customImage, descriptor.pageUrl).href\n    : descriptor.imageUrl;\n  const customExtension = customImage?.toLowerCase().split(/[?#]/, 1)[0];\n  const imageType = customExtension?.endsWith(\".webp\")\n    ? \"image/webp\"\n    : customExtension?.endsWith(\".png\")\n      ? \"image/png\"\n      : customExtension?.match(/\\.jpe?g$/)\n        ? \"image/jpeg\"\n        : \"image/svg+xml\";\n  const tag = (property: string, content: string, name = false) =>\n    `<meta ${name ? \"name\" : \"property\"}=\"${property}\" content=\"${escapeXml(content)}\">`;\n\n  return [\n    tag(\"og:type\", \"article\"),\n    tag(\"og:site_name\", descriptor.siteName),\n    tag(\"og:title\", descriptor.title),\n    tag(\"og:description\", descriptor.description),\n    tag(\"og:url\", descriptor.pageUrl),\n    tag(\"og:image\", imageUrl),\n    tag(\"og:image:type\", imageType),\n    ...(customImage\n      ? []\n      : [\n          tag(\"og:image:width\", String(FARM_DOCS_SOCIAL_IMAGE_WIDTH)),\n          tag(\"og:image:height\", String(FARM_DOCS_SOCIAL_IMAGE_HEIGHT)),\n        ]),\n    tag(\"og:image:alt\", descriptor.imageAlt),\n    tag(\"twitter:card\", \"summary_large_image\", true),\n    tag(\"twitter:title\", descriptor.title, true),\n    tag(\"twitter:description\", descriptor.description, true),\n    tag(\"twitter:image\", imageUrl, true),\n    tag(\"twitter:image:alt\", descriptor.imageAlt, true),\n  ].join(\"\\n  \");\n}\n","import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n  buildDocsAgentDiscoverySpec,\n  buildDocsSitemapManifest,\n  isDocsAgentDiscoveryRequest,\n  isDocsAgentsRequest,\n  isDocsSkillRequest,\n  renderDocsAgentsDocument,\n  renderDocsLlmsTxt,\n  renderDocsMarkdownDocument,\n  renderDocsRobotsTxt,\n  renderDocsSitemapMarkdown,\n  renderDocsSitemapXml,\n  renderDocsSkillDocument,\n  resolveDocsLlmsTxtFormat,\n  resolveDocsRobotsRequest,\n  resolveDocsSitemapRequest,\n  type DocsLlmsTxtPageInput,\n  type DocsMarkdownPage,\n  type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { marked, Renderer } from \"marked\";\nimport { highlight } from \"sugar-high\";\nimport { FARM_NAVIGATION_HEAD_SELECTOR } from \"../client/document-head\";\nimport { 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      },\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-copied=\"false\" aria-label=\"Copy code\" title=\"Copy code\" onclick=\"navigator.clipboard?.writeText(this.closest('figure').querySelector('code').innerText); this.dataset.copied='true'; this.setAttribute('aria-label','Copied'); this.title='Copied'; clearTimeout(this._copyTimer); this._copyTimer=setTimeout(() => { this.dataset.copied='false'; this.setAttribute('aria-label','Copy code'); this.title='Copy code'; }, 4500);\"><svg class=\"code-copy-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg><svg class=\"code-copy-check\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M20 6 9 17l-5-5\"></path></svg></button>`;\n}\n\nfunction 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))};document.addEventListener(\"click\",async(event)=>{const target=event.target instanceof Element?event.target.closest('[data-page-action=\"copy-markdown\"]'):null;if(!(target instanceof HTMLButtonElement))return;event.preventDefault();const format=target.dataset.copyMarkdownFormat===\"text\"?\"text\":\"markdown\";const includeTitle=target.dataset.copyMarkdownIncludeTitle===\"true\";let content=\"\";target.disabled=true;try{if(format===\"markdown\"&&target.dataset.markdownUrl){try{const response=await fetch(target.dataset.markdownUrl,{headers:{Accept:\"text/markdown\"}});if(response.ok)content=await response.text()}catch{}}if(!content)content=readArticleText();content=withTitle(content,format,includeTitle);if(content.trim()){await writeClipboard(content);markCopied(target)}}finally{target.disabled=false}})})();</script>`;\n}\n\nfunction renderDocsHashRuntimeScript(): string {\n  return `<script>(()=>{if(window.__farmDocsHashRuntime)return;window.__farmDocsHashRuntime=true;const scrollToHash=()=>{if(!location.hash)return;let id=location.hash.slice(1);try{id=decodeURIComponent(id)}catch{}document.getElementById(id)?.scrollIntoView({block:\"start\"})};const schedule=()=>requestAnimationFrame(()=>requestAnimationFrame(scrollToHash));if(document.readyState===\"loading\")document.addEventListener(\"DOMContentLoaded\",schedule,{once:true});else schedule();window.addEventListener(\"load\",schedule,{once:true});window.addEventListener(\"hashchange\",schedule)})();</script>`;\n}\n\nfunction renderDocsRuntimeScripts(docs: FarmDocsResolvedConfig): string {\n  return `${renderDocsRuntimeScript(docs)}\n${renderDocsHashRuntimeScript()}\n${renderDocsPageActionsRuntimeScript()}`;\n}\n\nfunction renderFarmDocsFontPreloads(fontAssets: readonly FarmDocsPublicFontAsset[]): string {\n  return fontAssets\n    .map(\n      ({ url }) =>\n        `<link rel=\"preload\" href=\"${escapeAttribute(url)}\" as=\"font\" type=\"font/woff2\" crossorigin>`,\n    )\n    .join(\"\\n  \");\n}\n\nfunction renderFarmDocsFontPreloadHeader(fontAssets: readonly FarmDocsPublicFontAsset[]): string {\n  return fontAssets\n    .map(({ url }) => `<${url}>; rel=preload; as=font; type=font/woff2; crossorigin`)\n    .join(\", \");\n}\n\nfunction getFarmLayoutFontPreloads(layoutFonts?: FarmLayoutFonts) {\n  const seen = new Set<string>();\n  return [layoutFonts?.body, layoutFonts?.code].flatMap((font) =>\n    (font?.preloads || []).filter(({ href }) => {\n      if (seen.has(href)) return false;\n      seen.add(href);\n      return true;\n    }),\n  );\n}\n\nfunction renderFarmLayoutFontPreloadHeader(layoutFonts?: FarmLayoutFonts): string {\n  return getFarmLayoutFontPreloads(layoutFonts)\n    .map(({ href, type }) => `<${href}>; rel=preload; as=font; type=${type}; crossorigin`)\n    .join(\", \");\n}\n\nfunction renderPixelDocsHtml(\n  page: LoadedFarmDocsPage,\n  pages: FarmDocsPage[],\n  docs: FarmDocsResolvedConfig,\n  clientEntry: string,\n  faviconHref: string,\n  requestUrl: URL,\n  fontAssets: readonly FarmDocsPublicFontAsset[],\n  fontStylesheetHref?: string,\n  globalStylesheetHref?: string,\n): string {\n  const navTitle =\n    typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n      ? String((docs.config.nav as { title?: unknown }).title || \"Docs\")\n      : \"Docs\";\n  const description = page.description || docs.config.metadata?.description || \"\";\n  // 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 type { FarmLayoutFonts } from \"../font\";\nimport { resolveFarmDocsContentDir } from \"./handler\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\ninterface FarmDocsAdapterServerModule {\n  createFarmDocsRuntimeHandler?: (\n    config: Record<string, unknown>,\n    options: {\n      rootDir: string;\n      clientEntry: string;\n      stylesheets: string[];\n      resolveLayoutFonts?: (\n        pathname: string,\n      ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n      loadReactModule?: () => Promise<any>;\n    },\n  ) => (request: Request) => Promise<Response | null>;\n}\n\nexport interface FarmDocsAdapterHandlerOptions {\n  root: string;\n  srcDir?: string;\n  clientEntry: string;\n  fontStylesheetHref?: string;\n  globalStylesheetHref?: string;\n  resolveLayoutFonts?: (\n    pathname: string,\n  ) => FarmLayoutFonts | undefined | Promise<FarmLayoutFonts | undefined>;\n  loadModule: (specifier: string) => Promise<any>;\n}\n\nexport function hasFarmDocsRuntimeAdapter(\n  docs: FarmDocsResolvedConfig | undefined,\n): docs is FarmDocsResolvedConfig & { adapter: NonNullable<FarmDocsResolvedConfig[\"adapter\"]> } {\n  return Boolean(docs?.enabled && docs.adapter?.server && docs.adapter.react);\n}\n\n/**\n * Load a documentation runtime through the versioned adapter descriptor.\n *\n * Core deliberately knows nothing about the adapter's DOM or theme. It only\n * supplies host assets and Vite's module loader; the adapter returns the final\n * Web Request handler.\n */\nexport async function createFarmDocsAdapterHandler(\n  docs: FarmDocsResolvedConfig,\n  options: FarmDocsAdapterHandlerOptions,\n): Promise<(request: Request) => Promise<Response | null>> {\n  if (!hasFarmDocsRuntimeAdapter(docs)) {\n    throw new Error(\"Farm docs adapter requires server and react runtime entrypoints.\");\n  }\n\n  const serverModule = (await options.loadModule(\n    docs.adapter.server,\n  )) as FarmDocsAdapterServerModule;\n  if (typeof serverModule.createFarmDocsRuntimeHandler !== \"function\") {\n    const adapterId = JSON.stringify(docs.adapter.id);\n    const serverEntry = JSON.stringify(docs.adapter.server);\n    throw new Error(\n      `Farm docs adapter ${adapterId} does not export createFarmDocsRuntimeHandler from ${serverEntry}. ` +\n        \"Upgrade the adapter to a runtime-enabled release.\",\n    );\n  }\n\n  const runtimeConfig = {\n    ...docs.config,\n    entry: docs.config.entry || docs.entry.replace(/^\\/+|\\/+$/g, \"\") || \"docs\",\n    docsPath: docs.entry,\n    contentDir: resolveFarmDocsContentDir(docs, {\n      root: options.root,\n      srcDir: options.srcDir,\n    }),\n  };\n\n  return serverModule.createFarmDocsRuntimeHandler(runtimeConfig as Record<string, unknown>, {\n    rootDir: options.root,\n    clientEntry: options.clientEntry,\n    stylesheets: [options.fontStylesheetHref, options.globalStylesheetHref].filter(\n      (value): value is string => typeof value === \"string\" && value.length > 0,\n    ),\n    resolveLayoutFonts: options.resolveLayoutFonts,\n    loadReactModule: () => options.loadModule(docs.adapter.react!),\n  });\n}\n","import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmDocsAdapterDescriptor, FarmDocsUserConfig } from \"./types\";\n\nconst FRAMEWORK_PACKAGE = \"@farming-labs/farmjs\";\nconst FRAMEWORK_CONFIG_ENTRY = \"@farming-labs/farmjs/config\";\n\n/**\n * The adapter descriptor protocol this core release knows how to drive.\n * Auto-detection must never wire up a descriptor from a future framework\n * release that this core cannot interpret; explicit withDocs() usage stays\n * the user's own call.\n */\nconst SUPPORTED_ADAPTER_PROTOCOL = 1;\n\nexport interface FarmDocsFrameworkDetectionOptions {\n  root: string;\n  log?: (message: string) => void;\n  warn?: (message: string) => void;\n}\n\n/**\n * Delegation triggers only for a dependency the app declared itself. A copy\n * that is merely resolvable through hoisting or a transitive dependency must\n * not silently change how the app's docs are served.\n */\nasync function frameworkDeclaredByApp(root: string): Promise<boolean> {\n  try {\n    const raw = await readFile(path.join(root, \"package.json\"), \"utf8\");\n    const manifest = JSON.parse(raw) as Record<string, unknown>;\n    for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"]) {\n      const section = manifest[field];\n      if (section && typeof section === \"object\" && FRAMEWORK_PACKAGE in section) {\n        return true;\n      }\n    }\n  } catch {\n    // Unreadable manifest: treat as not declared and keep the embedded renderer.\n  }\n  return false;\n}\n\nconst emittedNotices = new Set<string>();\n\n/** Test hook: notices are once-per-process so dev-server restarts stay quiet. */\nexport function resetFarmDocsFrameworkDetectionNotices(): void {\n  emittedNotices.clear();\n}\n\nfunction noticeOnce(key: string, emit: (message: string) => void, message: string): void {\n  if (emittedNotices.has(key)) return;\n  emittedNotices.add(key);\n  emit(message);\n}\n\nfunction docsWantsFrameworkDetection(docs: FarmDocsUserConfig | undefined): boolean {\n  if (docs === true) return true;\n  if (!docs || typeof docs !== \"object\") return false;\n  if (docs.enabled === false) return false;\n  // An explicit descriptor means the app already wired an adapter; an\n  // explicit `false` is the opt-out that pins the embedded renderer.\n  if (docs.adapter !== undefined) return false;\n  return true;\n}\n\nfunction isSupportedAdapterDescriptor(value: unknown): value is FarmDocsAdapterDescriptor {\n  if (!value || typeof value !== \"object\") return false;\n  const descriptor = value as Partial<FarmDocsAdapterDescriptor>;\n  return (\n    descriptor.protocol === SUPPORTED_ADAPTER_PROTOCOL &&\n    typeof descriptor.server === \"string\" &&\n    descriptor.server.length > 0 &&\n    typeof descriptor.react === \"string\" &&\n    descriptor.react.length > 0\n  );\n}\n\n/**\n * Delegate `docs: {}` to the @farming-labs/farmjs docs framework when the app\n * has it installed (#483 phase 1).\n *\n * Detection applies the framework's own withDocs() to the user config, so the\n * result is byte-for-byte what a manual `withDocs(defineConfig(...))` produces:\n * the MDX Vite plugin plus the versioned adapter descriptor. When the package\n * is absent the embedded renderer keeps serving, with a one-time migration\n * notice. Any failure falls back to the embedded renderer instead of breaking\n * a working app.\n */\nexport async function applyFarmDocsFrameworkAutoDetection<\n  T extends { docs?: FarmDocsUserConfig; vite?: unknown },\n>(userConfig: T, options: FarmDocsFrameworkDetectionOptions): Promise<T> {\n  if (!docsWantsFrameworkDetection(userConfig.docs)) return userConfig;\n\n  const log = options.log ?? ((message: string) => console.log(message));\n  const warn = options.warn ?? ((message: string) => console.warn(message));\n  const root = path.resolve(options.root || process.cwd());\n\n  if (!(await frameworkDeclaredByApp(root))) {\n    noticeOnce(\n      \"embedded-fallback\",\n      warn,\n      `[farm] docs is served by the embedded renderer, which is being replaced by the ${FRAMEWORK_PACKAGE} docs framework. ` +\n        `Install ${FRAMEWORK_PACKAGE} (with @farming-labs/docs and @farming-labs/theme) to migrate now, ` +\n        \"or set docs.adapter = false to keep the embedded renderer and silence this notice.\",\n    );\n    return userConfig;\n  }\n\n  let configEntryPath: string;\n  try {\n    const requireFromApp = createRequire(path.join(root, \"package.json\"));\n    configEntryPath = requireFromApp.resolve(FRAMEWORK_CONFIG_ENTRY);\n  } catch {\n    noticeOnce(\n      \"declared-not-installed\",\n      warn,\n      `[farm] ${FRAMEWORK_PACKAGE} is declared in package.json but could not be resolved; ` +\n        \"keeping the embedded docs renderer. Run your package manager's install to enable docs delegation.\",\n    );\n    return userConfig;\n  }\n\n  try {\n    const frameworkConfig = await import(/* @vite-ignore */ pathToFileURL(configEntryPath).href);\n    const withDocs = frameworkConfig?.withDocs;\n    if (typeof withDocs !== \"function\") {\n      noticeOnce(\n        \"missing-withdocs\",\n        warn,\n        `[farm] ${FRAMEWORK_CONFIG_ENTRY} does not export withDocs(); keeping the embedded docs renderer.`,\n      );\n      return userConfig;\n    }\n\n    const applied = withDocs(userConfig);\n    const adapter = (applied as { docs?: { adapter?: unknown } } | undefined)?.docs?.adapter;\n    if (!isSupportedAdapterDescriptor(adapter)) {\n      noticeOnce(\n        \"unsupported-descriptor\",\n        warn,\n        `[farm] The installed ${FRAMEWORK_PACKAGE} release publishes a docs adapter this Farm version cannot drive ` +\n          `(need protocol ${SUPPORTED_ADAPTER_PROTOCOL}); keeping the embedded docs renderer. ` +\n          \"Upgrading @farm.js/core usually resolves this.\",\n      );\n      return userConfig;\n    }\n\n    noticeOnce(\n      \"delegated\",\n      log,\n      `[farm] docs: delegated to ${FRAMEWORK_PACKAGE} (detected in this app). ` +\n        \"Set docs.adapter = false to keep the embedded renderer.\",\n    );\n    return applied as T;\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    noticeOnce(\n      \"detect-failed\",\n      warn,\n      `[farm] Failed to load ${FRAMEWORK_CONFIG_ENTRY} (${message}); keeping the embedded docs renderer.`,\n    );\n    return userConfig;\n  }\n}\n","import type { FarmUserConfig } from \"./config\";\n\n/** Define a Farm application config while preserving literal types. */\nexport function defineConfig<const TConfig extends FarmUserConfig>(config: TConfig): TConfig {\n  return config;\n}\n\n/** @deprecated Use {@link defineConfig}. */\nexport const defineFarmConfig = defineConfig;\n\nexport type { FarmUserConfig };\n","import type {\n  FarmConfig as BaseFarmConfig,\n  FarmMigrationCommand,\n  FarmMigrationsConfig,\n  FarmMigrationsUserConfig,\n  ResolvedFarmMigrationsConfig,\n} from \"./types\";\nimport type { DocsConfig } from \"@farming-labs/docs\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./docs/types\";\nimport type { FarmIntegrationsUserConfig } from \"./integrations\";\nimport type { FarmMarkdownResolvedConfig, FarmMarkdownUserConfig } from \"./markdown\";\nimport type { FarmObservabilityUserConfig } from \"./observability\";\nimport type { FarmMiddlewareConfig } from \"./middleware/types\";\nimport type { FarmPlugin } from \"./plugin\";\nimport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nimport type { FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nimport type { FarmEnvConfig, ResolvedFarmEnv } from \"./env\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport { resolveIntegrationPlugins } from \"./integrations\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig } from \"./workflows\";\nimport { resolveCronConfig } from \"./cron\";\nimport { resolveEnv, setEnv } from \"./env\";\nimport {\n  resolveMdxConfig,\n  type FarmMdxResolvedConfig,\n  type FarmMdxUserConfig,\n} from \"./app-markdown-config\";\nimport {\n  normalizeRouteRules,\n  routeRulesToHeaders,\n  routeRulesToRedirects,\n  type FarmRouteRules,\n} from \"./route-rules\";\nimport {\n  resolveServerActionsConfig,\n  type FarmServerActionsConfig,\n  type ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nimport {\n  resolveFarmServerConfig,\n  type FarmServerConfig,\n  type ResolvedFarmServerConfig,\n} from \"./server-http\";\nimport {\n  loadFarmConfigFile,\n  resolveFarmLayers,\n  type FarmLayerEntry,\n  type ResolvedFarmLayer,\n} from \"./layers\";\nimport path from \"path\";\nimport { logger } from \"./utils\";\nimport { normalizeFarmDeploymentId } from \"./deployment\";\nimport { normalizeFarmConfigBasePath } from \"./base-path\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n  resolveFarmDevIndicatorsConfig,\n  type FarmDevIndicatorsConfig,\n  type ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nimport {\n  resolveFarmImageConfig,\n  type FarmImageConfig,\n  type ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport type { FarmI18nUserConfig, ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport type { FarmCacheUserConfig } from \"./cache\";\nimport {\n  resolveFarmAuthConfig,\n  resolveFarmAuthIntegration,\n  type FarmAuthUserConfig,\n  type ResolvedFarmAuthConfig,\n} from \"./auth-config\";\nimport { resolveFarmPerformanceConfig, type ResolvedFarmPerformanceConfig } from \"./preload\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  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 { isReactRenderer, resolveFarmRenderer } from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { applyFarmDocsFrameworkAutoDetection } from \"./docs/framework-detect\";\nimport { resolveFarmAPIConfig, type ResolvedFarmAPIConfig } from \"./api/config\";\n\nconst FARM_RESOLVED_CUSTOM_CONTEXT = Symbol.for(\"farm.resolvedCustomContext\");\n\nexport type {\n  FarmDocsConfigInput,\n  FarmDocsNavigationConfig,\n  FarmDocsResolvedConfig,\n  FarmDocsSidebarItem,\n  FarmDocsUserConfig,\n} from \"./docs/types\";\nexport type {\n  FarmMarkdownResolvedConfig,\n  FarmMarkdownRouteInput,\n  FarmMarkdownUserConfig,\n} from \"./markdown\";\nexport type {\n  FarmMdxComponents,\n  FarmMdxResolvedConfig,\n  FarmMdxUserConfig,\n} from \"./app-markdown-config\";\nexport type {\n  FarmMigrationCommand,\n  FarmMigrationsConfig,\n  FarmMigrationsUserConfig,\n  ResolvedFarmMigrationsConfig,\n} from \"./types\";\nexport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nexport type { FarmCronJobConfig, FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nexport type {\n  FarmRouteRule,\n  FarmRouteRuleCors,\n  FarmRouteRuleRedirect,\n  FarmRouteRuleRenderMode,\n  FarmRouteRules,\n} from \"./route-rules\";\nexport type {\n  FarmServerActionsConfig,\n  ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nexport type {\n  FarmServerConfig,\n  FarmServerDuration,\n  FarmServerHealthConfig,\n  ResolvedFarmServerConfig,\n  ResolvedFarmServerHealthConfig,\n} from \"./server-http\";\nexport type { FarmLayerEntry, ResolvedFarmLayer } from \"./layers\";\nexport type {\n  FarmDevtoolsConfig,\n  FarmDevtoolsUserConfig,\n  ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\nexport type {\n  FarmBuildActivityPosition,\n  FarmDevIndicatorsConfig,\n  ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nexport type {\n  FarmPerformanceConfig,\n  FarmPreloadMode,\n  FarmPreloadUserConfig,\n  ResolvedFarmPerformanceConfig,\n  ResolvedFarmPreloadConfig,\n} from \"./preload\";\nexport type {\n  FarmImageConfig,\n  FarmImageFormat,\n  FarmImageLocalPattern,\n  FarmImageProvider,\n  FarmImageRemotePattern,\n  ResolvedFarmImageConfig,\n} from \"./image-config\";\nexport type {\n  FarmI18nCookieConfig,\n  FarmI18nDetectionSignal,\n  FarmI18nDirection,\n  FarmI18nRouting,\n  FarmI18nUserConfig,\n  ResolvedFarmI18nConfig,\n} from \"./i18n/types\";\nexport type {\n  FarmAuthConfig,\n  FarmAuthDatabaseConfig,\n  FarmAuthEmailAndPasswordConfig,\n  FarmAuthSessionConfig,\n  FarmAuthUserConfig,\n  ResolvedFarmAuthConfig,\n} from \"./auth-config\";\nexport type {\n  FarmCspConfig,\n  FarmCspDirectives,\n  FarmCspDirectiveValue,\n  FarmCspOptions,\n  FarmSecurityConfig,\n  ResolvedFarmCspConfig,\n  ResolvedFarmSecurityConfig,\n} from \"./security\";\nexport type {\n  FarmRenderer,\n  FarmRendererCapabilities,\n  FarmRendererCapabilitiesInput,\n  FarmRendererStreamingCapabilities,\n} from \"./renderer\";\nexport { defineRenderer } from \"./renderer\";\nexport type {\n  FarmAPIConfig,\n  FarmAPIConfigResolverContext,\n  FarmAPIConfigValue,\n  ResolvedFarmAPIConfig,\n} from \"./api/config\";\n\nexport interface RedirectConfig {\n  source: string;\n  destination: string;\n  permanent?: boolean;\n  statusCode?: import(\"./navigation-errors\").FarmRedirectStatus;\n}\n\nexport interface HeaderConfig {\n  source: string;\n  headers: Array<{\n    key: string;\n    value: string;\n  }>;\n}\n\nexport interface RewriteConfig {\n  source: string;\n  destination: string;\n}\n\n/** @deprecated Use FarmImageConfig. */\nexport type ImageConfig = FarmImageConfig;\n\n/** @deprecated Use FarmI18nUserConfig. */\nexport type I18nConfig = FarmI18nUserConfig;\n\nexport interface OpenAPIConfig {\n  enabled?: boolean;\n  route?: string;\n  /**\n   * Path where the raw OpenAPI spec is served as JSON, so agents and API tools\n   * can fetch it at a predictable URL. Set to `false` to disable.\n   *\n   * @default \"/openapi.json\"\n   */\n  specRoute?: string | false;\n  title?: string;\n  description?: string;\n  version?: string;\n  servers?: Array<{\n    url: string;\n    description?: string;\n  }>;\n  contact?: {\n    name?: string;\n    email?: string;\n    url?: string;\n  };\n  license?: {\n    name: string;\n    url?: string;\n  };\n}\n\nexport type MiddlewareConfig = FarmMiddlewareConfig;\n\nexport interface NotFoundConfig {\n  /** Path to a custom 404 page component (e.g., \"./src/app/not-found.tsx\") */\n  component?: string;\n}\n\nexport type FarmDeployTarget = \"vercel\" | \"cloudflare\" | \"netlify\" | \"node\" | string;\n\nexport interface FarmDeployConfig {\n  /**\n   * Deployment platform. When present, Farm picks the matching Nitro preset and\n   * output directory unless explicitly overridden.\n   */\n  target?: FarmDeployTarget;\n  /** Nitro preset override. Usually inferred from target. */\n  preset?: BaseFarmConfig[\"preset\"];\n  /** Deployable output directory, relative to project root unless absolute. */\n  outputDir?: string;\n  /** Alias for outputDir for terser config. */\n  output?: string;\n  /** Cloudflare Pages project name used by `farm deploy --cloudflare`. */\n  projectName?: string;\n  vercel?: {\n    outputDirectory?: string;\n    buildCommand?: string;\n    installCommand?: string;\n    framework?: string | null;\n  };\n  cloudflare?: {\n    outputDir?: string;\n    projectName?: string;\n  };\n  netlify?: {\n    outputDir?: string;\n    site?: string;\n  };\n}\n\nexport interface ResolvedFarmDeployConfig extends Omit<FarmDeployConfig, \"output\"> {\n  target?: FarmDeployTarget;\n  preset: BaseFarmConfig[\"preset\"];\n  outputDir: string;\n}\n\nexport interface FarmUserConfig extends Omit<BaseFarmConfig, \"vite\" | \"docs\" | \"env\" | \"layers\"> {\n  /** Reusable Farm directories or installed packages, applied from left to right. */\n  extends?: readonly FarmLayerEntry[];\n  /** Global plugins. Integration-bound plugins must be contributed through an integration. */\n  plugins?: FarmPlugin<any, any, any, any, unknown, false>[];\n  integrations?: FarmIntegrationsUserConfig;\n  /**\n   * Farm-native authentication. `true` enables email/password auth with\n   * server helpers from `@farm.js/auth/server` and React APIs from\n   * `@farm.js/auth/client`.\n   */\n  auth?: FarmAuthUserConfig;\n  /** Shared application data, route, ISR, and PPR cache. */\n  cache?: FarmCacheUserConfig;\n  migrations?: FarmMigrationsUserConfig;\n  /** Map portable cron schedules to ordinary GET API routes. */\n  cron?: FarmCronUserConfig | FarmCronResolvedConfig | false;\n  workflows?: FarmWorkflowsUserConfig | boolean;\n  preset?: BaseFarmConfig[\"preset\"];\n  deploy?: FarmDeployConfig;\n  docs?: FarmDocsUserConfig;\n  md?: FarmMarkdownUserConfig | boolean;\n  mdx?: FarmMdxUserConfig;\n  observability?: FarmObservabilityUserConfig;\n  trailingSlash?: boolean;\n  redirects?: () => Promise<RedirectConfig[]> | RedirectConfig[];\n  rewrites?: () => Promise<RewriteConfig[]> | RewriteConfig[];\n  headers?: () => Promise<HeaderConfig[]> | HeaderConfig[];\n\n  images?: ImageConfig;\n  publicDir?: string;\n\n  i18n?: FarmI18nUserConfig | false;\n  openapi?: OpenAPIConfig;\n\n  middleware?: FarmMiddlewareConfig;\n  routeRules?: FarmRouteRules;\n  context?: BaseFarmConfig[\"context\"];\n  /** Server ingress and trusted-proxy policy. */\n  server?: FarmServerConfig;\n  serverActions?: FarmServerActionsConfig;\n  /** Build identifier used to detect and recover from deployment version skew. */\n  deploymentId?: string;\n\n  notFound?: NotFoundConfig;\n\n  distDir?: string;\n  generateBuildId?: () => string | Promise<string>;\n  compress?: boolean;\n\n  devIndicators?: FarmDevIndicatorsConfig;\n\n  serverRuntimeConfig?: Record<string, any>;\n  publicRuntimeConfig?: Record<string, any>;\n\n  env?: FarmEnvConfig<any, any>;\n\n  vite?: ViteUserConfig | ((config: ViteUserConfig) => ViteUserConfig);\n\n  [key: string]: any;\n}\n\nexport interface ResolvedFarmConfig extends Required<\n  Omit<\n    FarmUserConfig,\n    | \"extends\"\n    | \"plugins\"\n    | \"vite\"\n    | \"deploy\"\n    | \"docs\"\n    | \"md\"\n    | \"mdx\"\n    | \"migrations\"\n    | \"cron\"\n    | \"workflows\"\n    | \"api\"\n    | \"env\"\n    | \"server\"\n    | \"serverActions\"\n    | \"devtools\"\n    | \"devIndicators\"\n    | \"images\"\n    | \"i18n\"\n    | \"auth\"\n    | \"performance\"\n    | \"security\"\n    | \"theme\"\n    | \"renderer\"\n    | \"agent\"\n  >\n> {\n  agent: ResolvedFarmAgentConfig;\n  /** @internal Tracks whether `context` came from user/layer config instead of the default noop. */\n  [FARM_RESOLVED_CUSTOM_CONTEXT]?: boolean;\n  root: string;\n  extends: readonly FarmLayerEntry[];\n  layers: ResolvedFarmLayer[];\n  plugins: FarmPlugin[];\n  vite: ViteUserConfig;\n  deploy: ResolvedFarmDeployConfig;\n  docs: FarmDocsResolvedConfig;\n  md: FarmMarkdownResolvedConfig;\n  mdx: FarmMdxResolvedConfig;\n  migrations: ResolvedFarmMigrationsConfig;\n  cron: FarmCronResolvedConfig;\n  workflows: FarmWorkflowsResolvedConfig;\n  api: ResolvedFarmAPIConfig;\n  env: ResolvedFarmEnv;\n  server: ResolvedFarmServerConfig;\n  serverActions: ResolvedFarmServerActionsConfig;\n  devtools: ResolvedFarmDevtoolsConfig;\n  devIndicators: ResolvedFarmDevIndicatorsConfig;\n  images: ResolvedFarmImageConfig;\n  i18n: ResolvedFarmI18nConfig;\n  auth: ResolvedFarmAuthConfig;\n  performance: ResolvedFarmPerformanceConfig;\n  security: ResolvedFarmSecurityConfig;\n  theme: ResolvedFarmThemeConfig;\n  renderer: FarmRenderer;\n  routeRules: FarmRouteRules;\n  notFound: NotFoundConfig;\n}\n\nexport function hasCustomFarmRouteContext(config: ResolvedFarmConfig): boolean {\n  return config[FARM_RESOLVED_CUSTOM_CONTEXT] === true;\n}\n\nexport type FarmLayerConfig = Omit<\n  FarmUserConfig,\n  | \"root\"\n  | \"outDir\"\n  | \"distDir\"\n  | \"deploy\"\n  | \"preset\"\n  | \"publicDir\"\n  | \"generateBuildId\"\n  | \"deploymentId\"\n>;\n\nexport { defineConfig, defineFarmConfig } from \"./config-entry\";\n\nexport function normalizeDeployTarget(target?: FarmDeployTarget): FarmDeployTarget | undefined {\n  if (!target) return undefined;\n  if (target === \"cloudflare-pages\" || target === \"cloudflare_pages\") return \"cloudflare\";\n  if (target === \"node-server\" || target === \"nitro\") return \"node\";\n  return target;\n}\n\nexport function getPresetForDeployTarget(\n  target?: FarmDeployTarget,\n): BaseFarmConfig[\"preset\"] | undefined {\n  switch (normalizeDeployTarget(target)) {\n    case \"vercel\":\n      return \"vercel\";\n    case \"cloudflare\":\n      return \"cloudflare-pages\";\n    case \"netlify\":\n      return \"netlify\";\n    case \"node\":\n      return \"node-server\";\n    default:\n      return undefined;\n  }\n}\n\nexport function getDeployTargetForPreset(preset?: string): FarmDeployTarget | undefined {\n  if (!preset) return undefined;\n  if (preset === \"vercel\" || preset === \"vercel-edge\") return \"vercel\";\n  if (preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\") {\n    return \"cloudflare\";\n  }\n  if (preset === \"netlify\" || preset === \"netlify-edge\") return \"netlify\";\n  if (preset === \"node-server\") return \"node\";\n  return undefined;\n}\n\nexport function getDefaultDeployOutputDir(\n  target: FarmDeployTarget | undefined,\n  preset: string | undefined,\n  distDir: string,\n): string {\n  const normalizedTarget = normalizeDeployTarget(target) || getDeployTargetForPreset(preset);\n  if (normalizedTarget === \"vercel\") return \".vercel/output\";\n  return `${distDir}/.output`;\n}\n\nexport function resolveDeployOutputPath(root: string, outputDir: string): string {\n  return path.isAbsolute(outputDir) ? outputDir : path.join(root, outputDir);\n}\n\nconst PLATFORM_BUILD_ENV_TARGETS: ReadonlyArray<[string, FarmDeployTarget]> = [\n  [\"VERCEL\", \"vercel\"],\n  [\"NETLIFY\", \"netlify\"],\n  [\"CF_PAGES\", \"cloudflare\"],\n];\n\n/**\n * Deploy target announced by the build environment (VERCEL=1, NETLIFY=true,\n * CF_PAGES=1), or undefined outside platform CI.\n */\nexport function detectPlatformDeployTarget(\n  env: NodeJS.ProcessEnv = process.env,\n): FarmDeployTarget | undefined {\n  for (const [key, target] of PLATFORM_BUILD_ENV_TARGETS) {\n    if (env[key]) return target;\n  }\n  return undefined;\n}\n\nconst warnedPlatformMismatches = new Set<string>();\n\nexport function resolveDeployConfig(\n  config: Pick<FarmUserConfig, \"deploy\" | \"preset\" | \"distDir\">,\n  overrides: {\n    target?: FarmDeployTarget;\n    preset?: BaseFarmConfig[\"preset\"];\n    outputDir?: string;\n    /** Build environment consulted for platform detection. Tests inject this. */\n    env?: NodeJS.ProcessEnv;\n  } = {},\n): ResolvedFarmDeployConfig {\n  const deploy = config.deploy || {};\n  const distDir = config.distDir || \".farm\";\n  // An explicit preset override replaces the deployment plan, so the\n  // configured platform target must not keep steering the output. Otherwise\n  // `farm build --preset node-server` on an app configured for Vercel writes\n  // a node server into .vercel/output — a directory Vercel will deploy as\n  // Build Output API content.\n  const overrideTarget = normalizeDeployTarget(overrides.target);\n  let target = overrideTarget\n    ? overrideTarget\n    : overrides.preset\n      ? getDeployTargetForPreset(overrides.preset)\n      : normalizeDeployTarget(deploy.target);\n\n  // A platform build environment (Vercel, Netlify, Cloudflare Pages) can only\n  // deploy its own output shape. When nothing selects a preset, the\n  // node-server fallback would build an artifact the platform cannot serve,\n  // so honor the detected platform instead. An explicit configuration always\n  // wins; it just gets a warning when it cannot run where it is being built.\n  const detectedTarget = detectPlatformDeployTarget(overrides.env);\n  if (detectedTarget) {\n    const hasExplicitSelection = Boolean(\n      target || overrides.preset || deploy.preset || config.preset,\n    );\n    if (!hasExplicitSelection) {\n      target = detectedTarget;\n      if (!warnedPlatformMismatches.has(`select:${detectedTarget}`)) {\n        warnedPlatformMismatches.add(`select:${detectedTarget}`);\n        logger.info(\n          `Detected ${detectedTarget} build environment; using the ${detectedTarget} preset. Set deploy.target in farm.config.ts to override.`,\n        );\n      }\n    }\n  }\n  // A CLI --target override governs the preset too: keep a configured preset\n  // only when it targets the same platform, otherwise derive the preset from\n  // the override target. Mirrors how a --preset override recomputes the target\n  // above, so `farm build --target netlify` never ships Vercel-shaped output.\n  const configuredPreset = deploy.preset || config.preset;\n  const overrideTargetPreset =\n    overrideTarget && getDeployTargetForPreset(configuredPreset) !== overrideTarget\n      ? getPresetForDeployTarget(overrideTarget)\n      : undefined;\n  const preset =\n    overrides.preset ||\n    overrideTargetPreset ||\n    configuredPreset ||\n    getPresetForDeployTarget(target) ||\n    \"node-server\";\n  const resolvedTarget = target || getDeployTargetForPreset(preset);\n  if (detectedTarget && resolvedTarget !== detectedTarget) {\n    const mismatchKey = `mismatch:${resolvedTarget}:${detectedTarget}`;\n    if (!warnedPlatformMismatches.has(mismatchKey)) {\n      warnedPlatformMismatches.add(mismatchKey);\n      logger.warn(\n        `The configured deploy target \"${resolvedTarget ?? preset}\" cannot be served by ${detectedTarget}, but this build is running in a ${detectedTarget} build environment. Set deploy.target: \"${detectedTarget}\" in farm.config.ts to deploy there.`,\n      );\n    }\n  }\n  const platformOutput =\n    resolvedTarget === \"vercel\"\n      ? deploy.vercel?.outputDirectory\n      : resolvedTarget === \"cloudflare\"\n        ? deploy.cloudflare?.outputDir\n        : resolvedTarget === \"netlify\"\n          ? deploy.netlify?.outputDir\n          : undefined;\n  const outputDir =\n    overrides.outputDir ||\n    deploy.outputDir ||\n    deploy.output ||\n    platformOutput ||\n    getDefaultDeployOutputDir(resolvedTarget, preset, distDir);\n\n  return {\n    ...deploy,\n    target: resolvedTarget,\n    preset,\n    outputDir,\n  };\n}\n\nexport function resolveMigrationsConfig(\n  migrations: FarmMigrationsUserConfig | undefined,\n): ResolvedFarmMigrationsConfig {\n  if (!migrations) return { commands: [] };\n  if (Array.isArray(migrations)) return { commands: migrations };\n  return { commands: migrations.commands || [] };\n}\n\nexport const DOCS_CONFIG_FILENAMES = [\n  \"docs.config.ts\",\n  \"docs.config.tsx\",\n  \"docs.config.mts\",\n  \"docs.config.cts\",\n  \"docs.config.js\",\n  \"docs.config.jsx\",\n  \"docs.config.mjs\",\n  \"docs.config.cjs\",\n  \"docs.json\",\n];\n\nfunction normalizeDocsRoute(value: string | undefined, fallback = \"/docs\"): string {\n  const raw = (value || fallback).trim();\n  if (!raw || raw === \"/\") return \"/\";\n  const normalized = raw\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\/+/g, \"/\")\n    .replace(/^\\/?/, \"/\")\n    .replace(/\\/+$/, \"\");\n  return normalized || \"/\";\n}\n\nfunction docsRouteToEntry(route: string): string {\n  const entry = route.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  return entry || \"docs\";\n}\n\nfunction normalizeDocsContentDir(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n  const normalized = value.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n  return normalized || undefined;\n}\n\nasync function inferDocsContentDir(\n  root: string,\n  srcDir: string,\n  entry: string,\n): Promise<string | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const contentDir = path.resolve(root, srcDir, \"app\", entry);\n  if (!existsSync(contentDir)) return undefined;\n\n  const relativeContentDir = path.relative(root, contentDir);\n  if (relativeContentDir.startsWith(\"..\") || path.isAbsolute(relativeContentDir)) return undefined;\n\n  return normalizeDocsContentDir(relativeContentDir);\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction cloneSerializable(value: unknown, seen = new WeakSet<object>()): any {\n  if (value === null) return null;\n\n  const valueType = typeof value;\n  if (valueType === \"string\" || valueType === \"number\" || valueType === \"boolean\") {\n    return value;\n  }\n  if (valueType === \"undefined\" || valueType === \"function\" || valueType === \"symbol\") {\n    return undefined;\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) => cloneSerializable(item, seen)).filter((item) => item !== undefined);\n  }\n  if (value instanceof Date) {\n    return value.toISOString();\n  }\n  if (isRecord(value)) {\n    if (seen.has(value)) return undefined;\n    seen.add(value);\n\n    const output: Record<string, any> = {};\n    for (const [key, nestedValue] of Object.entries(value)) {\n      const clonedValue = cloneSerializable(nestedValue, seen);\n      if (clonedValue !== undefined) {\n        output[key] = clonedValue;\n      }\n    }\n    return output;\n  }\n\n  return undefined;\n}\n\nfunction sanitizeDocsConfig(config: Partial<DocsConfig>): Partial<DocsConfig> {\n  return cloneSerializable(config) || {};\n}\n\nexport async function findDocsConfigPath(\n  rootDir: string,\n  configPath?: string,\n): Promise<string | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const root = path.resolve(rootDir || process.cwd());\n\n  if (configPath) {\n    const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n    if (!existsSync(resolvedPath)) {\n      throw new Error(`Could not find docs config at ${configPath}.`);\n    }\n    return path.resolve(resolvedPath);\n  }\n\n  for (const filename of DOCS_CONFIG_FILENAMES) {\n    const resolvedPath = path.join(root, filename);\n    if (existsSync(resolvedPath)) {\n      return resolvedPath;\n    }\n  }\n\n  return undefined;\n}\n\nexport async function loadDocsConfig(\n  rootDir: string,\n  configPath?: string,\n): Promise<{ config: Partial<DocsConfig>; configPath: string } | undefined> {\n  const fs = await import(\"fs/promises\");\n  const { pathToFileURL } = await import(\"url\");\n  const root = path.resolve(rootDir || process.cwd());\n  const resolvedPath = await findDocsConfigPath(root, configPath);\n\n  if (!resolvedPath) return undefined;\n\n  try {\n    if (resolvedPath.endsWith(\".json\")) {\n      const content = await fs.readFile(resolvedPath, \"utf8\");\n      return { config: JSON.parse(content), configPath: resolvedPath };\n    }\n\n    const { build } = await import(\"esbuild\");\n    const configCacheDir = path.join(root, \".farm\", \".config-loader\");\n    await fs.mkdir(configCacheDir, { recursive: true });\n    const modulePath = path.join(\n      configCacheDir,\n      `docs-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n    );\n\n    await build({\n      absWorkingDir: root,\n      entryPoints: [resolvedPath],\n      outfile: modulePath,\n      bundle: true,\n      format: \"esm\",\n      platform: \"node\",\n      target: `node${process.versions.node.split(\".\")[0]}`,\n      packages: \"external\",\n      jsx: \"automatic\",\n      logLevel: \"silent\",\n      sourcemap: \"inline\",\n    });\n\n    const moduleUrl = pathToFileURL(modulePath).href + `?t=${Date.now()}`;\n    let importedConfig: any;\n\n    try {\n      importedConfig = await import(/* @vite-ignore */ moduleUrl);\n    } finally {\n      await fs.unlink(modulePath).catch(() => undefined);\n    }\n\n    return {\n      config: importedConfig.default || importedConfig,\n      configPath: resolvedPath,\n    };\n  } catch (error: any) {\n    const relativePath = path.relative(root, resolvedPath) || resolvedPath;\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Failed to load docs config from ${relativePath}: ${message}`);\n  }\n}\n\nexport async function resolveDocsConfig(\n  userDocs: FarmDocsUserConfig | undefined,\n  options: {\n    root?: string;\n    srcDir?: string;\n  } = {},\n): Promise<FarmDocsResolvedConfig> {\n  const root = options.root || process.cwd();\n\n  if (userDocs === false) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const docsOptions = isRecord(userDocs) ? userDocs : {};\n  if (docsOptions.enabled === false) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const loadedConfig = await loadDocsConfig(root, docsOptions.configPath);\n  const hasExplicitDocsConfig = userDocs === true || isRecord(userDocs);\n\n  if (!hasExplicitDocsConfig && !loadedConfig) {\n    return {\n      enabled: false,\n      entry: \"/docs\",\n      config: { entry: \"docs\", docsPath: \"/docs\" },\n    };\n  }\n\n  const inlineDocsConfig = sanitizeDocsConfig(docsOptions.config || {});\n  const directDocsConfig = sanitizeDocsConfig({\n    ...docsOptions,\n    adapter: undefined,\n    enabled: undefined,\n    config: undefined,\n    configPath: undefined,\n  } as Partial<DocsConfig>);\n  const loadedDocsConfig = sanitizeDocsConfig(loadedConfig?.config || {});\n  const mergedDocsConfig: Partial<DocsConfig> = {\n    ...loadedDocsConfig,\n    ...inlineDocsConfig,\n    ...directDocsConfig,\n  };\n\n  const explicitRoute = typeof docsOptions.entry === \"string\" ? docsOptions.entry : undefined;\n  const configuredDocsPath =\n    typeof mergedDocsConfig.docsPath === \"string\" ? mergedDocsConfig.docsPath : undefined;\n  const configuredEntry =\n    typeof mergedDocsConfig.entry === \"string\" ? mergedDocsConfig.entry : undefined;\n  const entryRoute = normalizeDocsRoute(\n    configuredDocsPath || explicitRoute || (configuredEntry ? `/${configuredEntry}` : undefined),\n  );\n  const docsEntry =\n    explicitRoute && explicitRoute.startsWith(\"/\")\n      ? docsRouteToEntry(explicitRoute)\n      : docsRouteToEntry(configuredEntry || entryRoute);\n  const configuredContentDir = normalizeDocsContentDir(\n    docsOptions.contentDir || mergedDocsConfig.contentDir,\n  );\n  const contentDir =\n    configuredContentDir || (await inferDocsContentDir(root, options.srcDir || \"src\", docsEntry));\n\n  return {\n    enabled: true,\n    entry: entryRoute,\n    ...(docsOptions.adapter ? { adapter: docsOptions.adapter } : {}),\n    contentDir,\n    configPath: loadedConfig?.configPath,\n    config: {\n      ...mergedDocsConfig,\n      entry: docsEntry,\n      docsPath: entryRoute,\n      ...(contentDir ? { contentDir } : {}),\n    },\n  };\n}\n\nfunction validateRedirectConfigs(redirects: RedirectConfig[], field: string): RedirectConfig[] {\n  for (const [index, redirect] of redirects.entries()) {\n    validateConfigRouteSource(redirect.source, `${field}[${index}].source`);\n    if (redirect.statusCode !== undefined && !isFarmRedirectStatus(redirect.statusCode)) {\n      throw new RangeError(\n        `${field}[${index}].statusCode must be one of 301, 302, 303, 307, or 308.`,\n      );\n    }\n  }\n  return redirects;\n}\n\nfunction validateConfigRouteSources<T extends { source: string }>(routes: T[], field: string): T[] {\n  for (const [index, route] of routes.entries()) {\n    validateConfigRouteSource(route.source, `${field}[${index}].source`);\n  }\n  return routes;\n}\n\nexport async function resolveConfig(\n  userConfig: FarmUserConfig,\n  mode: \"development\" | \"production\",\n): Promise<ResolvedFarmConfig> {\n  const projectRoot = userConfig.root || process.cwd();\n  const layerResolution = await resolveFarmLayers(userConfig, {\n    root: projectRoot,\n    mode,\n  });\n  userConfig = layerResolution.config;\n\n  if ((userConfig as Record<string, unknown>).typescript !== undefined) {\n    logger.warn(\n      'The top-level \"typescript\" option is not supported and has no effect. Configure TypeScript in `tsconfig.json` and run `tsc --noEmit` separately when builds must enforce project type errors.',\n    );\n  }\n\n  if ((userConfig as Record<string, unknown>).output !== undefined) {\n    logger.warn(\n      'The top-level \"output\" option is not supported and has no effect. Configure `deploy.target`, `deploy.preset`, or `deploy.outputDir` for deployment output, and use route rendering configuration for static pages.',\n    );\n  }\n\n  // The docs adapter runtime is React-only today; other renderers keep the\n  // embedded docs handler without any migration notice.\n  if (isReactRenderer(resolveFarmRenderer(userConfig.renderer))) {\n    userConfig = await applyFarmDocsFrameworkAutoDetection(userConfig, {\n      root: userConfig.root || projectRoot,\n    });\n  }\n\n  const redirects = validateRedirectConfigs(\n    typeof userConfig.redirects === \"function\"\n      ? await userConfig.redirects()\n      : userConfig.redirects || [],\n    \"redirects\",\n  );\n\n  const rewrites =\n    typeof userConfig.rewrites === \"function\"\n      ? await userConfig.rewrites()\n      : userConfig.rewrites || [];\n  validateConfigRouteSources(rewrites, \"rewrites\");\n\n  const headers =\n    typeof userConfig.headers === \"function\"\n      ? await userConfig.headers()\n      : userConfig.headers || [];\n  validateConfigRouteSources(headers, \"headers\");\n  const routeRules = normalizeRouteRules(userConfig.routeRules);\n  const routeRuleRedirects = routeRulesToRedirects(routeRules);\n  const routeRuleHeaders = routeRulesToHeaders(routeRules);\n  const security = resolveFarmSecurityConfig(userConfig.security);\n  const securityHeader = getFarmSecurityHeader(security);\n  if (farmCspBlocksFrameworkInlineScripts(security)) {\n    logger.warn(\n      \"security.csp restricts inline scripts (no 'unsafe-inline', nonce, or hash in \" +\n        \"script-src/default-src), which blocks the inline scripts Farm injects for theming \" +\n        \"and hydration. Add 'unsafe-inline' or the scripts' hashes until nonce support lands \" +\n        \"(https://github.com/farming-labs/farm.js/issues/1275).\",\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  if (auth.enabled && userConfig.integrations?.auth) {\n    throw new Error(\n      \"Choose either the top-level `auth` config or `integrations.auth`; they cannot both own the auth route.\",\n    );\n  }\n  const nativeAuthIntegration = await resolveFarmAuthIntegration(auth, {\n    root,\n    mode,\n  });\n  const integrations = nativeAuthIntegration\n    ? { ...userConfig.integrations, auth: nativeAuthIntegration }\n    : userConfig.integrations || {};\n  const generateBuildId = userConfig.generateBuildId || (() => `build-${Date.now()}`);\n  const deploymentId = normalizeFarmDeploymentId(\n    userConfig.deploymentId ||\n      process.env.FARM_DEPLOYMENT_ID ||\n      process.env.VERCEL_GIT_COMMIT_SHA ||\n      process.env.CF_PAGES_COMMIT_SHA ||\n      (mode === \"production\" ? await generateBuildId() : \"development\"),\n  );\n  const basePath = normalizeFarmConfigBasePath(userConfig.basePath);\n  const openapi = {\n    enabled: false,\n    route: \"/docs/reference\",\n    specRoute: \"/openapi.json\" as string | false,\n    title: \"API Documentation\",\n    description: \"Auto-generated API documentation\",\n    version: \"1.0.0\",\n    servers: [{ url: \"http://localhost:3000\", description: \"Development server\" }],\n    ...userConfig.openapi,\n  };\n  if (openapi.route !== undefined) validateConfigRouteSource(openapi.route, \"openapi.route\");\n  if (openapi.specRoute) validateConfigRouteSource(openapi.specRoute, \"openapi.specRoute\");\n\n  const resolved: ResolvedFarmConfig = {\n    [FARM_RESOLVED_CUSTOM_CONTEXT]: typeof userConfig.context === \"function\",\n    root,\n    srcDir,\n    extends: userConfig.extends || [],\n    layers: layerResolution.layers,\n    outDir: userConfig.outDir || \"dist\",\n    basePath,\n    renderer: resolveFarmRenderer(userConfig.renderer),\n    preset: deploy.preset || \"node-server\",\n    deploy,\n    docs,\n    md,\n    mdx,\n    migrations: resolveMigrationsConfig(userConfig.migrations),\n    cron: resolveCronConfig(userConfig.cron),\n    workflows: resolveWorkflowsConfig(userConfig.workflows),\n    api,\n    observability: userConfig.observability ?? false,\n    telemetry: userConfig.telemetry !== false,\n    devtools: resolveFarmDevtoolsConfig(userConfig.devtools, mode),\n    storage: userConfig.storage || {},\n    cache: userConfig.cache || {},\n    auth,\n    suppressLintOnLink: userConfig.suppressLintOnLink ?? false,\n    experimental: {\n      serverComponents: false,\n      serverActions: false,\n      isolatedClientHydration: \"off\",\n      ppr: false,\n      ...userConfig.experimental,\n    },\n    agent: resolveFarmAgentConfig(userConfig.agent),\n    plugins: [...resolveIntegrationPlugins(integrations), ...(userConfig.plugins || [])],\n    integrations,\n    trailingSlash: userConfig.trailingSlash ?? false,\n    redirects: () => [...redirects, ...routeRuleRedirects],\n    rewrites: () => rewrites,\n    headers: () => [\n      ...headers,\n      ...routeRuleHeaders,\n      ...(securityHeader ? [{ source: \"/*\", headers: [securityHeader] }] : []),\n    ],\n    routeRules,\n    images: resolveFarmImageConfig(userConfig.images),\n    performance: resolveFarmPerformanceConfig(userConfig.performance),\n    theme: resolveFarmThemeConfig(userConfig.theme, basePath),\n    publicDir: userConfig.publicDir || \"public\",\n    i18n: resolveFarmI18nConfig(userConfig.i18n, { root, mode, basePath }),\n    openapi,\n    middleware: userConfig.middleware || {},\n    notFound: userConfig.notFound || {},\n    context: userConfig.context || (() => undefined),\n    server: resolveFarmServerConfig(userConfig.server),\n    serverActions: resolveServerActionsConfig(userConfig.serverActions),\n    security,\n    deploymentId,\n    distDir: userConfig.distDir || \".farm\",\n    generateBuildId,\n    compress: userConfig.compress ?? true,\n    devIndicators: resolveFarmDevIndicatorsConfig(userConfig.devIndicators, mode),\n    serverRuntimeConfig: userConfig.serverRuntimeConfig || {},\n    publicRuntimeConfig: userConfig.publicRuntimeConfig || {},\n    env,\n    vite: typeof userConfig.vite === \"function\" ? userConfig.vite({}) : userConfig.vite || {},\n  };\n\n  return resolved;\n}\n\nexport async function loadConfig(\n  rootDir?: string,\n  configPath?: string,\n  mode = process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n  loadEnvironment?: (typeof import(\"vite\"))[\"loadEnv\"],\n): Promise<FarmUserConfig | undefined> {\n  const { existsSync } = await import(\"fs\");\n  const loadEnv = loadEnvironment || (await import(\"vite\")).loadEnv;\n\n  const root = rootDir || process.cwd();\n  const loadedEnv = loadEnv(mode, root, \"\");\n  for (const [key, value] of Object.entries(loadedEnv)) {\n    if (process.env[key] === undefined) {\n      process.env[key] = value;\n    }\n  }\n  // An explicitly supplied config path must resolve — silently falling back\n  // to the default config would run against the wrong configuration.\n  if (configPath) {\n    const explicitPath = path.resolve(\n      path.isAbsolute(configPath) ? configPath : path.join(root, configPath),\n    );\n    if (!existsSync(explicitPath)) {\n      throw new Error(`Config file not found at ${configPath} (resolved to ${explicitPath}).`);\n    }\n  }\n\n  const searchPaths = [\n    configPath,\n    \"farm.config.ts\",\n    \"farm.config.mts\",\n    \"farm.config.js\",\n    \"farm.config.mjs\",\n    \"config.ts\",\n    \"config.mts\",\n    \"config.js\",\n    \"config.mjs\",\n  ].filter(Boolean) as string[];\n\n  for (const relativePath of searchPaths) {\n    try {\n      // Use path.join for proper path construction\n      const absolutePath = path.isAbsolute(relativePath)\n        ? relativePath\n        : path.join(root, relativePath);\n\n      // Normalize the path to handle any issues\n      const normalizedPath = path.resolve(absolutePath);\n\n      // Check if file exists before trying to import\n      if (!existsSync(normalizedPath)) {\n        continue;\n      }\n\n      const loadedConfig = await loadFarmConfigFile<FarmUserConfig>(normalizedPath, { root });\n      return loadedConfig.root === undefined ? { ...loadedConfig, root } : loadedConfig;\n    } catch (error: any) {\n      const message = error instanceof Error ? error.message : String(error);\n      throw new Error(`Failed to load config from ${relativePath}: ${message}`);\n    }\n  }\n  return undefined;\n}\n","import {\n  buildDocsAgentDiscoverySpec,\n  buildDocsConfigMap,\n  buildDocsDiagnostics as buildFarmingDocsDiagnostics,\n  buildDocsSitemapManifest,\n  performDocsSearch,\n  renderDocsAgentsDocument,\n  renderDocsLlmsTxt,\n  renderDocsMarkdownDocument,\n  renderDocsRobotsTxt,\n  renderDocsSitemapMarkdown,\n  renderDocsSitemapXml,\n  renderDocsSkillDocument,\n  type DocsConfig,\n  type DocsLlmsTxtPageInput,\n  type DocsSearchSourcePage,\n  type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { resolveDocsConfig } from \"../config\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./types\";\nimport {\n  discoverFarmDocsPages,\n  type LoadedFarmDocsPage,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n  toFarmDocsMarkdownPage,\n} from \"./handler\";\n\nexport interface FarmDocsAPIOptions {\n  rootDir?: string;\n  root?: string;\n  srcDir?: string;\n  docs?: FarmDocsUserConfig | FarmDocsResolvedConfig;\n  config?: Partial<DocsConfig>;\n  configPath?: string;\n  entry?: string;\n  docsPath?: string;\n  contentDir?: string;\n}\n\nexport interface FarmDocsCloudRouteOptions {\n  locale?: string;\n  publicBaseUrl?: string;\n}\n\nexport interface FarmDocsCloudServer {\n  handleRequest(request: Request, options?: FarmDocsCloudRouteOptions): Promise<Response>;\n}\n\nexport type FarmDocsCloudIntegration =\n  | FarmDocsCloudServer\n  | (FarmDocsCloudRouteOptions & { docsCloud?: FarmDocsCloudServer });\n\nexport interface FarmDocsAPIRouteHandlers {\n  GET(request: Request): Promise<Response>;\n  POST(request: Request): Promise<Response>;\n}\n\nexport type FarmDocsAPIHandler = (request: Request) => Promise<Response | null>;\n\ninterface FarmDocsAPIContext {\n  root: string;\n  srcDir: string;\n  docs: FarmDocsResolvedConfig;\n  contentDir: string;\n}\n\ntype JsonRecord = Record<string, unknown>;\ntype DocsAPIPathTarget = {\n  format?: string;\n  slug?: string;\n};\ntype FarmDocsRuntimeConfig = {\n  root?: string;\n  srcDir?: string;\n  docs?: FarmDocsResolvedConfig;\n};\n\ndeclare global {\n  // Injected by Farm's generated server entry so route wrappers can stay zero-config.\n  // eslint-disable-next-line no-var\n  var __FARM_DOCS_RUNTIME_CONFIG__: FarmDocsRuntimeConfig | undefined;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isResolvedDocsConfig(value: unknown): value is FarmDocsResolvedConfig {\n  return (\n    isRecord(value) &&\n    typeof value.enabled === \"boolean\" &&\n    typeof value.entry === \"string\" &&\n    isRecord(value.config)\n  );\n}\n\nexport function isFarmDocsAPIRequest(requestOrPathname: Request | string): boolean {\n  const pathname =\n    typeof requestOrPathname === \"string\"\n      ? requestOrPathname\n      : new URL(requestOrPathname.url).pathname;\n\n  return pathname === \"/api/docs\" || pathname.startsWith(\"/api/docs/\");\n}\n\nfunction json(data: unknown, init: ResponseInit = {}): Response {\n  const headers = new Headers(init.headers);\n  if (!headers.has(\"Content-Type\")) {\n    headers.set(\"Content-Type\", \"application/json\");\n  }\n  return new Response(JSON.stringify(data), { ...init, headers });\n}\n\nfunction text(content: string, contentType: string, init: ResponseInit = {}): Response {\n  const headers = new Headers(init.headers);\n  headers.set(\"Content-Type\", contentType);\n  return new Response(content, { ...init, headers });\n}\n\nfunction omitHeadBody(response: Response): Response {\n  return new Response(null, {\n    status: response.status,\n    statusText: response.statusText,\n    headers: response.headers,\n  });\n}\n\nfunction normalizeAction(value: string | null | undefined): string | undefined {\n  return value?.trim().toLowerCase().replace(/_/g, \"-\") || undefined;\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n  return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n    ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n    : \"Documentation\";\n}\n\nfunction isDocsCloudServer(value: unknown): value is FarmDocsCloudServer {\n  return isRecord(value) && typeof value.handleRequest === \"function\";\n}\n\nfunction resolveDocsCloudIntegration(\n  integration?: FarmDocsCloudIntegration,\n): { docsCloud: FarmDocsCloudServer; routeOptions: FarmDocsCloudRouteOptions } | undefined {\n  if (!integration) return undefined;\n\n  if (isDocsCloudServer(integration)) {\n    return { docsCloud: integration, routeOptions: {} };\n  }\n\n  if (!integration.docsCloud) return undefined;\n\n  return {\n    docsCloud: integration.docsCloud,\n    routeOptions: {\n      locale: integration.locale,\n      publicBaseUrl: integration.publicBaseUrl,\n    },\n  };\n}\n\nfunction isDocsCloudGetRequest(request: Request): boolean {\n  const url = new URL(request.url);\n  const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n  const action = normalizeAction(url.searchParams.get(\"action\"));\n  const format = normalizeAction(url.searchParams.get(\"format\"));\n\n  return (\n    cloud === \"config\" ||\n    cloud === \"public-config\" ||\n    action === \"cloud-config\" ||\n    action === \"docs-cloud-config\" ||\n    format === \"cloud-config\" ||\n    format === \"docs-cloud-config\"\n  );\n}\n\nfunction isDocsCloudAction(action: string | undefined): boolean {\n  return Boolean(\n    action &&\n    [\"analytics\", \"track\", \"track-event\", \"event\", \"ask-ai\", \"ai\", \"chat\", \"docs-cloud\"].includes(\n      action,\n    ),\n  );\n}\n\nasync function readJson(request: Request): Promise<unknown> {\n  try {\n    return await request.clone().json();\n  } catch {\n    return undefined;\n  }\n}\n\nasync function isDocsCloudPostRequest(request: Request): Promise<boolean> {\n  const url = new URL(request.url);\n  const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n  const action = normalizeAction(url.searchParams.get(\"action\"));\n\n  if (isDocsCloudAction(cloud) || isDocsCloudAction(action)) return true;\n\n  const body = await readJson(request);\n  if (!isRecord(body)) return false;\n\n  const bodyAction = normalizeAction(typeof body.action === \"string\" ? body.action : undefined);\n  if (isDocsCloudAction(bodyAction)) return true;\n\n  if (typeof body.type === \"string\") return true;\n  if (isRecord(body.event) && typeof body.event.type === \"string\") return true;\n  if (isRecord(body.payload) && typeof body.payload.type === \"string\") return true;\n\n  return false;\n}\n\nfunction normalizeDocsApiSlug(\n  value: string | null | undefined,\n  docs: FarmDocsResolvedConfig,\n): string {\n  const entry = docs.entry.replace(/^\\/+|\\/+$/g, \"\");\n  let slug = (value || \"\").trim().replace(/^\\/+|\\/+$/g, \"\");\n\n  if (entry && slug === entry) return \"\";\n  if (entry && slug.startsWith(`${entry}/`)) {\n    slug = slug.slice(entry.length + 1);\n  }\n\n  let decoded = slug;\n  try {\n    decoded = decodeURIComponent(slug);\n  } catch {\n    // Malformed percent-encoding resolves to a non-matching slug (404),\n    // not an exception out of the handler.\n  }\n  return decoded.replace(/\\.(mdx?|markdown)$/i, \"\");\n}\n\nfunction getDocsAPIPathTarget(request: Request): DocsAPIPathTarget {\n  const pathname = new URL(request.url).pathname.replace(/\\/+$/, \"\") || \"/\";\n  const prefix = \"/api/docs\";\n\n  if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return {};\n\n  const rawValue = pathname === prefix ? \"\" : pathname.slice(prefix.length + 1);\n  const value = rawValue.replace(/^\\/+|\\/+$/g, \"\");\n  const normalizedValue = normalizeAction(value);\n\n  if (!value) return {};\n  if (\n    normalizedValue === \"agent\" ||\n    normalizedValue === \"agent.json\" ||\n    normalizedValue === \"agent/spec\"\n  ) {\n    return { format: \"agent-spec\" };\n  }\n  if (\n    normalizedValue === \"agents\" ||\n    normalizedValue === \"agents.md\" ||\n    normalizedValue === \"agent.md\"\n  ) {\n    return { format: \"agents\" };\n  }\n  if (normalizedValue === \"skill\" || normalizedValue === \"skill.md\") return { format: \"skill\" };\n  if (normalizedValue === \"llms.txt\") return { format: \"llms\" };\n  if (normalizedValue === \"llms-full.txt\") return { format: \"llms-full\" };\n  if (normalizedValue === \"sitemap.md\") return { format: \"sitemap-md\" };\n  if (normalizedValue === \"sitemap.xml\") return { format: \"sitemap-xml\" };\n  if (normalizedValue === \"robots.txt\") return { format: \"robots\" };\n  if (/\\.(mdx?|markdown)$/i.test(value)) return { format: \"markdown\", slug: value };\n\n  return { slug: value };\n}\n\nfunction getDocsAPIFormat(request: Request): string | undefined {\n  const url = new URL(request.url);\n  return (\n    normalizeAction(url.searchParams.get(\"format\") || url.searchParams.get(\"type\")) ||\n    getDocsAPIPathTarget(request).format\n  );\n}\n\nfunction getDocsDescription(docs: FarmDocsResolvedConfig): string | undefined {\n  return docs.config.metadata?.description;\n}\n\nfunction getLoadedDocsPages(context: FarmDocsAPIContext): LoadedFarmDocsPage[] {\n  return discoverFarmDocsPages(context.contentDir, context.docs)\n    .map((page) => loadFarmDocsPage(context.contentDir, context.docs, page.slug))\n    .filter((page): page is LoadedFarmDocsPage => Boolean(page));\n}\n\nfunction toDocsSourcePage(page: LoadedFarmDocsPage): DocsSearchSourcePage {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\nfunction toDocsSitemapPage(page: LoadedFarmDocsPage): DocsSitemapPageInput {\n  return {\n    ...toFarmDocsMarkdownPage(page),\n    sourcePath: page.sourcePath,\n  };\n}\n\nfunction toDocsLlmsPage(page: LoadedFarmDocsPage): DocsLlmsTxtPageInput {\n  return toFarmDocsMarkdownPage(page);\n}\n\nfunction getDocsLlmsOptions(context: FarmDocsAPIContext, request: Request) {\n  const configured = isRecord(context.docs.config.llmsTxt) ? context.docs.config.llmsTxt : {};\n  return {\n    enabled: true,\n    baseUrl: new URL(request.url).origin,\n    siteTitle: getDocsTitle(context.docs),\n    siteDescription: getDocsDescription(context.docs),\n    ...configured,\n  };\n}\n\nfunction getDocsDiscoveryOptions(context: FarmDocsAPIContext, request: Request) {\n  const origin = new URL(request.url).origin;\n\n  return {\n    origin,\n    entry: context.docs.entry,\n    i18n: null,\n    search: context.docs.config.search ?? true,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(context.docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n    feedback: undefined,\n    llms: getDocsLlmsOptions(context, request),\n    sitemap: context.docs.config.sitemap ?? true,\n    robots: context.docs.config.robots ?? true,\n    openapi: context.docs.config.apiReference,\n    markdown: {\n      acceptHeader: true,\n      signatureAgentHeader: true,\n    },\n  };\n}\n\nfunction buildSitemapManifest(context: FarmDocsAPIContext, request: Request) {\n  const origin = new URL(request.url).origin;\n  return buildDocsSitemapManifest({\n    pages: getLoadedDocsPages(context).map(toDocsSitemapPage),\n    entry: context.docs.entry,\n    siteTitle: getDocsTitle(context.docs),\n    baseUrl: origin,\n  });\n}\n\nfunction renderLlmsTxt(context: FarmDocsAPIContext, request: Request, full: boolean): string {\n  const generated = renderDocsLlmsTxt(\n    getLoadedDocsPages(context).map(toDocsLlmsPage),\n    getDocsLlmsOptions(context, request),\n  );\n\n  return full ? generated.llmsFullTxt : generated.llmsTxt;\n}\n\nfunction renderSkillDocument(context: FarmDocsAPIContext, request: Request): string {\n  const farmAliases = [\n    \"## Farm API Route Aliases\",\n    \"\",\n    \"- Search JSON: /api/docs?query=<term>\",\n    \"- Config JSON: /api/docs?format=config\",\n    \"- Markdown by query: /api/docs?format=markdown&path=<slug>\",\n    \"- Markdown by path: /api/docs/<slug>.md\",\n    \"- LLM summary: /api/docs?format=llms\",\n    \"- Full LLM document: /api/docs?format=llms-full\",\n    \"- Sitemap XML: /api/docs?format=sitemap-xml\",\n    \"- Agent spec JSON: /api/docs/agent/spec\",\n  ].join(\"\\n\");\n\n  return `${renderDocsSkillDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n\\n${farmAliases}\\n`;\n}\n\nfunction renderAgentsDocument(context: FarmDocsAPIContext, request: Request): string {\n  return `${renderDocsAgentsDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n`;\n}\n\nfunction buildAgentSpec(context: FarmDocsAPIContext, request: Request) {\n  const url = new URL(request.url);\n  const origin = url.origin;\n  const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n  const spec = buildDocsAgentDiscoverySpec(getDocsDiscoveryOptions(context, request));\n  const title = getDocsTitle(context.docs);\n\n  return {\n    ...spec,\n    name: title,\n    site: {\n      ...spec.site,\n      title,\n      description: getDocsDescription(context.docs),\n      entry: context.docs.entry,\n    },\n    entry: context.docs.entry,\n    routes: {\n      docs: `${origin}${context.docs.entry}`,\n      config: `${origin}/api/docs?format=config`,\n      search: `${origin}/api/docs?query=<term>`,\n      markdown: `${origin}/api/docs/<slug>.md`,\n      markdownQuery: `${origin}/api/docs?format=markdown&path=<slug>`,\n      llms: `${origin}/api/docs?format=llms`,\n      llmsFull: `${origin}/api/docs?format=llms-full`,\n      sitemapXml: `${origin}/api/docs?format=sitemap-xml`,\n      sitemapMarkdown: `${origin}/api/docs?format=sitemap-md`,\n      robots: `${origin}/api/docs?format=robots`,\n      skill: `${origin}/api/docs?format=skill`,\n      agents: `${origin}/api/docs?format=agents`,\n      agentSpec: `${origin}/api/docs/agent/spec`,\n    },\n    capabilities: {\n      ...spec.capabilities,\n      search: spec.capabilities.search,\n      markdown: spec.capabilities.markdownRoutes,\n      llms: spec.capabilities.llms,\n      sitemap: spec.capabilities.sitemap,\n      robots: spec.capabilities.robots,\n      post: false,\n    },\n    pages,\n  };\n}\n\nfunction buildDiagnostics(context: FarmDocsAPIContext) {\n  const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n  const diagnostics = buildFarmingDocsDiagnostics(context.docs.config, {\n    entry: context.docs.entry,\n    mcp: {\n      enabled: false,\n      route: \"/api/docs/mcp\",\n      name: `${getDocsTitle(context.docs)} MCP`,\n      version: \"1\",\n      tools: {\n        listDocs: false,\n        listPages: false,\n        readPage: false,\n        searchDocs: false,\n        getNavigation: false,\n        getCodeExamples: false,\n        getConfigSchema: false,\n      },\n    },\n  });\n\n  return {\n    ...diagnostics,\n    enabled: context.docs.enabled,\n    entry: context.docs.entry,\n    root: context.root,\n    srcDir: context.srcDir,\n    contentDir: context.contentDir,\n    configPath: context.docs.configPath || null,\n    pageCount: pages.length,\n    pages,\n  };\n}\n\nasync function searchDocs(context: FarmDocsAPIContext, request: Request, query: string) {\n  const loadedPages = getLoadedDocsPages(context);\n  const sourcePages = loadedPages.map(toDocsSourcePage);\n  const sourcePageByUrl = new Map(sourcePages.map((page) => [page.url, page]));\n  const resultLimit =\n    isRecord(context.docs.config.search) &&\n    typeof context.docs.config.search.maxResults === \"number\"\n      ? context.docs.config.search.maxResults\n      : undefined;\n\n  const results = await performDocsSearch({\n    pages: sourcePages,\n    query,\n    search: context.docs.config.search ?? true,\n    pathname: new URL(request.url).pathname,\n    siteTitle: getDocsTitle(context.docs),\n    limit: resultLimit,\n  });\n\n  return results.map((result) => {\n    const pageUrl = result.url.split(\"#\")[0];\n    const page = sourcePageByUrl.get(pageUrl);\n    return {\n      ...result,\n      title: page?.title || result.content,\n      href: page?.url || pageUrl,\n      description: result.description || page?.description,\n    };\n  });\n}\n\nasync function resolveAPIContext(options: FarmDocsAPIOptions): Promise<FarmDocsAPIContext> {\n  const runtimeConfig = globalThis.__FARM_DOCS_RUNTIME_CONFIG__;\n  const root = options.rootDir || options.root || runtimeConfig?.root || process.cwd();\n  const srcDir = options.srcDir || runtimeConfig?.srcDir || \"src\";\n  const canUseRuntimeDocs =\n    options.docs === undefined &&\n    options.config === undefined &&\n    options.configPath === undefined &&\n    options.entry === undefined &&\n    options.docsPath === undefined &&\n    options.contentDir === undefined &&\n    options.root === undefined &&\n    options.rootDir === undefined &&\n    options.srcDir === undefined;\n  const docsInput =\n    options.docs ??\n    (canUseRuntimeDocs ? runtimeConfig?.docs : undefined) ??\n    ({\n      enabled: true,\n      entry: options.entry,\n      docsPath: options.docsPath,\n      contentDir: options.contentDir,\n      config: options.config,\n      configPath: options.configPath,\n    } satisfies Exclude<FarmDocsUserConfig, boolean>);\n  const docs = isResolvedDocsConfig(docsInput)\n    ? docsInput\n    : await resolveDocsConfig(docsInput, { root, srcDir });\n\n  return {\n    root,\n    srcDir,\n    docs,\n    contentDir: resolveFarmDocsContentDir(docs, { root, srcDir }),\n  };\n}\n\nasync function handleDocsAPIGet(request: Request, context: FarmDocsAPIContext): Promise<Response> {\n  if (!context.docs.enabled) {\n    return json({ error: \"Docs are disabled\" }, { status: 404 });\n  }\n\n  const url = new URL(request.url);\n  const format = getDocsAPIFormat(request);\n  const pathTarget = getDocsAPIPathTarget(request);\n\n  if (format === \"config\" || format === \"docs-config\") {\n    return json({\n      entry: context.docs.entry,\n      contentDir: context.docs.contentDir || context.docs.config.contentDir || null,\n      config: context.docs.config,\n      map: buildDocsConfigMap(context.docs.config, {\n        file: context.docs.configPath || \"farm.config.ts\",\n      }),\n    });\n  }\n\n  if (format === \"skill\")\n    return text(renderSkillDocument(context, request), \"text/markdown; charset=utf-8\");\n  if (format === \"agents\")\n    return text(renderAgentsDocument(context, request), \"text/markdown; charset=utf-8\");\n  if (format === \"agent\" || format === \"agent-spec\") return json(buildAgentSpec(context, request));\n  if (format === \"diagnostics\") return json(buildDiagnostics(context));\n  if (format === \"llms\")\n    return text(renderLlmsTxt(context, request, false), \"text/plain; charset=utf-8\");\n  if (format === \"llms-full\")\n    return text(renderLlmsTxt(context, request, true), \"text/plain; charset=utf-8\");\n  if (format === \"sitemap-md\") {\n    return text(\n      renderDocsSitemapMarkdown(buildSitemapManifest(context, request), {\n        includeDescriptions: true,\n      }),\n      \"text/markdown; charset=utf-8\",\n    );\n  }\n  if (format === \"sitemap-xml\" || format === \"sitemap\") {\n    const origin = new URL(request.url).origin;\n    return text(\n      renderDocsSitemapXml(buildSitemapManifest(context, request), {\n        baseUrl: origin,\n        includeLastmod: true,\n      }),\n      \"application/xml; charset=utf-8\",\n    );\n  }\n  if (format === \"robots\") {\n    return text(\n      renderDocsRobotsTxt({\n        entry: context.docs.entry,\n        sitemap: context.docs.config.sitemap ?? true,\n        robots: context.docs.config.robots ?? true,\n        baseUrl: new URL(request.url).origin,\n      }),\n      \"text/plain; charset=utf-8\",\n    );\n  }\n\n  if (format === \"markdown\" || url.pathname.endsWith(\".md\")) {\n    const pathParam = url.searchParams.get(\"path\") || url.searchParams.get(\"slug\");\n    const slug = normalizeDocsApiSlug(pathParam ?? pathTarget.slug ?? \"\", context.docs);\n    const page = loadFarmDocsPage(context.contentDir, context.docs, slug);\n    if (!page) return text(\"Docs page not found\\n\", \"text/plain; charset=utf-8\", { status: 404 });\n    return text(\n      renderDocsMarkdownDocument(toFarmDocsMarkdownPage(page), {\n        origin: new URL(request.url).origin,\n        llms: getDocsLlmsOptions(context, request),\n        sitemap: context.docs.config.sitemap,\n      }),\n      \"text/markdown; charset=utf-8\",\n    );\n  }\n\n  const query = url.searchParams.get(\"query\") || url.searchParams.get(\"q\") || \"\";\n  if (!query.trim()) return json([]);\n  return json(await searchDocs(context, request, query));\n}\n\nexport function createDocsAPI(\n  options: FarmDocsAPIOptions = {},\n  cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIRouteHandlers {\n  let contextPromise: Promise<FarmDocsAPIContext> | undefined;\n  const getContext = () => {\n    contextPromise ??= resolveAPIContext(options);\n    return contextPromise;\n  };\n  const integration = resolveDocsCloudIntegration(cloudIntegration);\n\n  return {\n    async GET(request: Request) {\n      if (integration && isDocsCloudGetRequest(request)) {\n        return integration.docsCloud.handleRequest(request, integration.routeOptions);\n      }\n\n      return handleDocsAPIGet(request, await getContext());\n    },\n    async POST(request: Request) {\n      if (integration && (await isDocsCloudPostRequest(request))) {\n        return integration.docsCloud.handleRequest(request, integration.routeOptions);\n      }\n\n      return json(\n        {\n          error: \"AI is not enabled for this Farm docs API route yet.\",\n        },\n        { status: 501 },\n      );\n    },\n  };\n}\n\nexport function createFarmDocsAPIHandler(\n  options: FarmDocsAPIOptions = {},\n  cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIHandler {\n  const handlers = createDocsAPI(options, cloudIntegration);\n\n  return async function handleFarmDocsAPIRequest(request: Request): Promise<Response | null> {\n    if (!isFarmDocsAPIRequest(request)) return null;\n\n    const method = request.method.toUpperCase();\n    if (method === \"GET\" || method === \"HEAD\") {\n      const response = await handlers.GET(request);\n      return method === \"HEAD\" ? omitHeadBody(response) : response;\n    }\n    if (method === \"POST\") {\n      return handlers.POST(request);\n    }\n\n    return json(\n      {\n        error: \"Method Not Allowed\",\n      },\n      {\n        status: 405,\n        headers: {\n          Allow: \"GET, HEAD, POST\",\n        },\n      },\n    );\n  };\n}\n","export {\n  createFarmDocsHandler,\n  discoverFarmDocsPages,\n  getFarmDocsDocumentNavigationMatchers,\n  getFarmDocsRouteTypeEntries,\n  isFarmDocsRequest,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n} from \"./handler\";\nexport {\n  createFarmDocsAdapterHandler,\n  hasFarmDocsRuntimeAdapter,\n  type FarmDocsAdapterHandlerOptions,\n} from \"./adapter\";\nexport { createDocsAPI, createFarmDocsAPIHandler, isFarmDocsAPIRequest } from \"./api\";\nexport type { FarmDocsHandlerOptions, FarmDocsPage, LoadedFarmDocsPage } from \"./handler\";\nexport type {\n  FarmDocsAPIHandler,\n  FarmDocsAPIOptions,\n  FarmDocsAPIRouteHandlers,\n  FarmDocsCloudIntegration,\n  FarmDocsCloudRouteOptions,\n  FarmDocsCloudServer,\n} from \"./api\";\nexport type {\n  FarmDocsConfigInput,\n  FarmDocsNavigationConfig,\n  FarmDocsResolvedConfig,\n  FarmDocsSocialImageConfig,\n  FarmDocsSocialImageFonts,\n  FarmDocsSidebarItem,\n  FarmDocsUserConfig,\n} from \"./types\";\n","import type { OpenAPIConfig } from \"../config\";\nimport type { APIRouteInfo } from \"../type-generator\";\nimport * as z from \"zod\";\n\nexport interface OpenAPISpec {\n  openapi: string;\n  info: {\n    title: string;\n    description?: string;\n    version: string;\n    contact?: {\n      name?: string;\n      email?: string;\n      url?: string;\n    };\n    license?: {\n      name: string;\n      url?: string;\n    };\n  };\n  servers?: Array<{\n    url: string;\n    description?: string;\n  }>;\n  paths: Record<string, any>;\n  components?: {\n    schemas?: Record<string, any>;\n    securitySchemes?: Record<string, any>;\n  };\n}\n\ntype AllowedType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\nconst allowedType = new Set([\"string\", \"number\", \"boolean\", \"array\", \"object\"]);\n\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\n  constructor(appDir: string, config: OpenAPIConfig) {\n    this.appDir = appDir;\n    this.config = config;\n  }\n\n  /**\n   * Get type from Zod type\n   */\n  private getTypeFromZodType(zodType: z.ZodType<any>): AllowedType {\n    const tag = (zodType as any)._def?.type;\n    return typeof tag === \"string\" && allowedType.has(tag) ? (tag as AllowedType) : \"string\";\n  }\n\n  /**\n   * 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: z.ZodType<any>): boolean {\n    return !(value instanceof z.ZodOptional) && !(value instanceof z.ZodDefault);\n  }\n\n  /**\n   * Process Zod type to OpenAPI schema\n   */\n  private processZodType(zodType: z.ZodType<any>): any {\n    // Handle ZodOptional and ZodNullable\n    if (zodType instanceof z.ZodOptional || zodType instanceof z.ZodNullable) {\n      const innerType = (zodType as any)._def.innerType;\n      const innerSchema = this.processZodType(innerType);\n      return {\n        ...innerSchema,\n        nullable: true,\n      };\n    }\n\n    // Handle ZodDefault. The value is always present after parsing, so the\n    // documented type is the wrapped one.\n    if (zodType instanceof z.ZodDefault) {\n      return this.processZodType((zodType as any)._def.innerType);\n    }\n\n    // Handle ZodObject\n    if (zodType instanceof z.ZodObject) {\n      const shape = (zodType as any).shape;\n      if (shape) {\n        const properties: Record<string, any> = {};\n        const required: string[] = [];\n        Object.entries(shape).forEach(([key, value]) => {\n          if (value instanceof z.ZodType) {\n            properties[key] = this.processZodType(value as z.ZodType<any>);\n            if (this.isRequiredField(value as z.ZodType<any>)) {\n              required.push(key);\n            }\n          }\n        });\n        return {\n          type: \"object\",\n          properties,\n          ...(required.length > 0 ? { required } : {}),\n          description: (zodType as any).description,\n        };\n      }\n    }\n\n    // Handle ZodArray\n    if (zodType instanceof z.ZodArray) {\n      return {\n        type: \"array\",\n        items: this.processZodType((zodType as any)._def.element),\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodEnum\n    if (zodType instanceof z.ZodEnum) {\n      return {\n        type: \"string\",\n        enum: (zodType as any).options,\n        description: (zodType as any).description,\n      };\n    }\n\n    // Handle ZodLiteral: emit the concrete value(s) as an enum rather than\n    // dropping the constraint and documenting a bare string.\n    if (zodType instanceof z.ZodLiteral) {\n      const values = ((zodType as any)._def.values as unknown[]) ?? [];\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 (zodType instanceof z.ZodUnion) {\n      const options = ((zodType as any)._def.options as z.ZodType<any>[]) ?? [];\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 (zodType instanceof z.ZodRecord) {\n      return {\n        type: \"object\",\n        additionalProperties: this.processZodType((zodType as any)._def.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 (zodType instanceof z.ZodTuple) {\n      const items = ((zodType as any)._def.items as z.ZodType<any>[]) ?? [];\n      const rest = (zodType as any)._def.rest;\n      const itemSchemas = items.map((item) => this.processZodType(item));\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 [key, value] of constraints) {\n      // Zod 4's .int() implies bounds of +/-Number.MAX_SAFE_INTEGER; those are\n      // implementation details of the safe-integer range, not author-declared\n      // constraints, and would otherwise stamp every integer field with\n      // maximum: 9007199254740991.\n      if (Number.isFinite(value) && Math.abs(value as number) !== Number.MAX_SAFE_INTEGER) {\n        baseSchema[key] = value;\n      }\n    }\n\n    return baseSchema;\n  }\n\n  /**\n   * Generate standard error responses\n   */\n  private getStandardResponses(): Record<string, any> {\n    return {\n      \"200\": {\n        description: \"Successful response\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              description: \"Response data\",\n            },\n          },\n        },\n      },\n      \"400\": {\n        description: \"Bad Request. Usually due to missing parameters, or invalid parameters.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n                error: { type: \"string\" },\n              },\n              required: [\"message\"],\n            },\n          },\n        },\n      },\n      \"401\": {\n        description: \"Unauthorized. Due to missing or invalid authentication.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n              required: [\"message\"],\n            },\n          },\n        },\n      },\n      \"403\": {\n        description:\n          \"Forbidden. You do not have permission to access this resource or to perform this action.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n      \"404\": {\n        description: \"Not Found. The requested resource was not found.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n      \"429\": {\n        description: \"Too Many Requests. You have exceeded the rate limit. Try again later.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n      \"500\": {\n        description:\n          \"Internal Server Error. This is a problem with the server that you cannot fix.\",\n        content: {\n          \"application/json\": {\n            schema: {\n              type: \"object\",\n              properties: {\n                message: { type: \"string\" },\n                error: { type: \"string\" },\n              },\n            },\n          },\n        },\n      },\n    };\n  }\n\n  /**\n   * Generate OpenAPI spec from API routes\n   */\n  async generateSpec(routes: APIRouteInfo[]): Promise<OpenAPISpec> {\n    const spec: OpenAPISpec = {\n      openapi: \"3.0.3\",\n      info: {\n        title: this.config.title || \"API Documentation\",\n        description: this.config.description || \"Auto-generated API documentation\",\n        version: this.config.version || \"1.0.0\",\n        ...(this.config.contact && { contact: this.config.contact }),\n        ...(this.config.license && { license: this.config.license }),\n      },\n      servers: this.config.servers || [\n        { url: \"http://localhost:3000\", description: \"Development server\" },\n      ],\n      paths: {},\n      components: {\n        schemas: {},\n        securitySchemes: {\n          bearerAuth: {\n            type: \"http\",\n            scheme: \"bearer\",\n            description: \"Bearer token authentication\",\n          },\n          apiKeyCookie: {\n            type: \"apiKey\",\n            in: \"cookie\",\n            name: \"session\",\n            description: \"API Key authentication via cookie\",\n          },\n        },\n      },\n    };\n\n    // Group routes by path\n    const routeGroups = new Map<string, APIRouteInfo[]>();\n    for (const route of routes) {\n      const key = route.path;\n      if (!routeGroups.has(key)) {\n        routeGroups.set(key, []);\n      }\n      routeGroups.get(key)!.push(route);\n    }\n\n    // Generate paths\n    for (const [path, routeList] of routeGroups) {\n      const openAPIPath = this.convertToOpenAPIPath(path);\n      spec.paths[openAPIPath] = {};\n\n      for (const route of routeList) {\n        for (const method of route.methods) {\n          const operation = await this.generateOperation(route, method);\n          if (method === \"QUERY\") {\n            const additionalOperations =\n              spec.paths[openAPIPath][\"x-oai-additionalOperations\"] ?? {};\n            additionalOperations.QUERY = operation;\n            spec.paths[openAPIPath][\"x-oai-additionalOperations\"] = additionalOperations;\n          } else {\n            spec.paths[openAPIPath][method.toLowerCase()] = operation;\n          }\n        }\n      }\n    }\n\n    return spec;\n  }\n\n  /**\n   * Convert 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    return path\n      .replace(/^\\/api/, \"\")\n      .replace(/\\[\\[\\.\\.\\.([^\\]]+)\\]\\]/g, \"{$1}\")\n      .replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \"{$1}\")\n      .replace(/\\[([^\\]]+)\\]/g, \"{$1}\");\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(path: string): any[] {\n    const openAPIPath = this.convertToOpenAPIPath(path);\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      // Check for Farm.js endpoint format: handler.__types.body\n      if (handler && handler.__types && handler.__types.body) {\n        const bodySchema = handler.__types.body;\n\n        if (bodySchema instanceof z.ZodObject || bodySchema instanceof z.ZodOptional) {\n          const shape = (bodySchema as any).shape || (bodySchema as any)._def?.innerType?.shape;\n          if (shape) {\n            const properties: Record<string, any> = {};\n            const required: string[] = [];\n\n            Object.entries(shape).forEach(([key, value]) => {\n              if (value instanceof z.ZodType) {\n                properties[key] = this.processZodType(value as z.ZodType<any>);\n                if (this.isRequiredField(value as z.ZodType<any>)) {\n                  required.push(key);\n                }\n              }\n            });\n            return {\n              required: bodySchema instanceof z.ZodOptional ? false : true,\n              content: {\n                \"application/json\": {\n                  schema: {\n                    type: \"object\",\n                    properties,\n                    ...(required.length > 0 ? { required } : {}),\n                  },\n                },\n              },\n            };\n          }\n        }\n      }\n\n      // Fallback: Check for better-call format: handler._type.body\n      if (handler && handler._type && handler._type.body) {\n        const bodySchema = handler._type.body;\n\n        if (bodySchema instanceof z.ZodObject || bodySchema instanceof z.ZodOptional) {\n          const shape = (bodySchema as any).shape || (bodySchema as any)._def?.innerType?.shape;\n          if (shape) {\n            const properties: Record<string, any> = {};\n            const required: string[] = [];\n\n            Object.entries(shape).forEach(([key, value]) => {\n              if (value instanceof z.ZodType) {\n                properties[key] = this.processZodType(value as z.ZodType<any>);\n                if (this.isRequiredField(value as z.ZodType<any>)) {\n                  required.push(key);\n                }\n              }\n            });\n\n            return {\n              required: bodySchema instanceof z.ZodOptional ? false : true,\n              content: {\n                \"application/json\": {\n                  schema: {\n                    type: \"object\",\n                    properties,\n                    ...(required.length > 0 ? { required } : {}),\n                  },\n                },\n              },\n            };\n          }\n        }\n      }\n    } catch (error) {\n      // If we can't load the module, return generic schema\n      console.warn(`Could not extract schema from ${route.filePath}:`, error);\n    }\n\n    // Fallback to generic schema\n    return {\n      required: true,\n      content: {\n        \"application/json\": {\n          schema: {\n            type: \"object\",\n            description: \"Request body\",\n          },\n        },\n      },\n    };\n  }\n\n  /**\n   * Extract query parameters from endpoint\n   */\n  private async getParameters(route: APIRouteInfo, method: string): Promise<any[]> {\n    const parameters: any[] = [];\n\n    try {\n      // Try to dynamically load the route module\n      const modulePath = route.filePath;\n      const routeModule = await import(/* @vite-ignore */ modulePath);\n\n      // Get the method handler\n      const handler = routeModule[method];\n\n      // Check for Farm.js endpoint format: handler.__types.query\n      if (handler && handler.__types && handler.__types.query) {\n        const querySchema = handler.__types.query;\n\n        if (querySchema instanceof z.ZodObject) {\n          Object.entries((querySchema as any).shape).forEach(([key, value]) => {\n            if (value instanceof z.ZodType) {\n              parameters.push({\n                name: key,\n                in: \"query\",\n                required: this.isRequiredField(value as z.ZodType<any>),\n                schema: this.processZodType(value as z.ZodType<any>),\n              });\n            }\n          });\n        }\n      }\n\n      // Fallback: Check for better-call format: handler._type.query\n      if (handler && handler._type && handler._type.query) {\n        const querySchema = handler._type.query;\n\n        if (querySchema instanceof z.ZodObject) {\n          Object.entries((querySchema as any).shape).forEach(([key, value]) => {\n            if (value instanceof z.ZodType) {\n              parameters.push({\n                name: key,\n                in: \"query\",\n                required: this.isRequiredField(value as z.ZodType<any>),\n                schema: this.processZodType(value as z.ZodType<any>),\n              });\n            }\n          });\n        }\n      }\n    } catch (error) {\n      console.warn(`Could not extract query params from ${route.filePath}:`, error);\n    }\n\n    return parameters;\n  }\n\n  /**\n   * Generate OpenAPI operation from route info\n   */\n  private async generateOperation(route: APIRouteInfo, method: string): Promise<any> {\n    const operation: any = {\n      summary: this.generateSummary(route.path, method),\n      description: this.generateDescription(route.path, method),\n      operationId: this.generateOperationId(route.path, method),\n      tags: this.generateTags(route.path),\n      security: [{ bearerAuth: [] }, { apiKeyCookie: [] }],\n      responses: this.getStandardResponses(),\n    };\n\n    // Path parameters (from dynamic route segments) precede query parameters.\n    const parameters = [\n      ...this.getPathParameters(route.path),\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      operation.requestBody = await this.getRequestBody(route, method);\n    }\n\n    return operation;\n  }\n\n  /**\n   * Generate operation summary\n   */\n  private generateSummary(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n    const pathParts = cleanPath.split(\"/\");\n    const lastPart = pathParts[pathParts.length - 1];\n\n    const action =\n      method === \"GET\"\n        ? \"Get\"\n        : method === \"QUERY\"\n          ? \"Query\"\n          : method === \"POST\"\n            ? \"Create\"\n            : method === \"PUT\"\n              ? \"Update\"\n              : method === \"DELETE\"\n                ? \"Delete\"\n                : method === \"PATCH\"\n                  ? \"Update\"\n                  : method;\n\n    return `${action} ${lastPart}`;\n  }\n\n  /**\n   * Generate operation description\n   */\n  private generateDescription(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n    return `${method} ${cleanPath} endpoint`;\n  }\n\n  /**\n   * Generate operation ID\n   */\n  private generateOperationId(path: string, method: string): string {\n    const cleanPath = path.replace(/^\\/api\\//, \"\").replace(/\\//g, \"_\");\n    return `${method.toLowerCase()}_${cleanPath}`;\n  }\n\n  /**\n   * Generate tags for grouping operations\n   */\n  private generateTags(path: string): string[] {\n    const cleanPath = path.replace(/^\\/api\\//, \"\");\n    const pathParts = cleanPath.split(\"/\");\n\n    if (pathParts.length > 1) {\n      return [pathParts[0]]; // Use first part as tag\n    }\n\n    return [\"default\"];\n  }\n\n  /**\n   * Generate OpenAPI spec file\n   */\n  async generateSpecFile(routes: APIRouteInfo[], outputPath: string): Promise<void> {\n    const spec = await this.generateSpec(routes);\n    const fs = require(\"fs\");\n    const path = require(\"path\");\n\n    // Ensure directory exists\n    const dir = path.dirname(outputPath);\n    if (!fs.existsSync(dir)) {\n      fs.mkdirSync(dir, { recursive: true });\n    }\n\n    // Write spec file\n    fs.writeFileSync(outputPath, JSON.stringify(spec, null, 2));\n  }\n}\n","import { OpenAPIGenerator, type OpenAPISpec } from \"./generator\";\nimport { APITypeGenerator } from \"../type-generator\";\nimport type { OpenAPIConfig } from \"../config\";\n\nfunction escapeHTML(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&#39;\");\n}\n\nexport function renderOpenAPIReferenceHTML(spec: OpenAPISpec, config: OpenAPIConfig): string {\n  return `\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>${escapeHTML(config.title || \"API Documentation\")}</title>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <link rel=\"icon\" href=\"data:,\" />\n  </head>\n  <body>\n    <script\n      id=\"api-reference\"\n      data-url=\"data:application/json;base64,${Buffer.from(JSON.stringify(spec)).toString(\"base64\")}\"\n    ></script>\n    <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n  </body>\n</html>\n    `;\n}\n\nexport class OpenAPIManager {\n  private generator: OpenAPIGenerator;\n  private apiTypeGenerator: APITypeGenerator;\n  private config: OpenAPIConfig;\n  private appDir: string;\n  private specCache: any = null;\n\n  constructor(appDir: string | readonly string[], config: OpenAPIConfig) {\n    const appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n    this.appDir = appDirs[appDirs.length - 1];\n    this.config = config;\n    this.generator = new OpenAPIGenerator(this.appDir, config);\n    this.apiTypeGenerator = new APITypeGenerator(appDirs);\n  }\n\n  /**\n   * Generate OpenAPI spec from API routes\n   */\n  async generateSpec(): Promise<any> {\n    try {\n      // Get API routes using the existing type generator\n      const routes = this.apiTypeGenerator.scanAPIRoutes();\n\n      // Generate OpenAPI spec (now async)\n      const spec = await this.generator.generateSpec(routes);\n\n      // Cache the spec\n      this.specCache = spec;\n\n      return spec;\n    } catch (error) {\n      console.error(\"Failed to generate OpenAPI spec:\", error);\n      return null;\n    }\n  }\n\n  /**\n   * Get cached spec or generate new one\n   */\n  async getSpec(): Promise<any> {\n    if (this.specCache) {\n      return this.specCache;\n    }\n\n    return await this.generateSpec();\n  }\n\n  /**\n   * Generate and save OpenAPI spec file\n   */\n  async generateSpecFile(): Promise<void> {\n    try {\n      const routes = this.apiTypeGenerator.scanAPIRoutes();\n      const outputPath = `${this.appDir}/lib/openapi.spec.json`;\n\n      await this.generator.generateSpecFile(routes, outputPath);\n      console.log(\"✅ OpenAPI spec generated at:\", outputPath);\n    } catch (error) {\n      console.error(\"Failed to generate OpenAPI spec file:\", error);\n    }\n  }\n\n  /**\n   * Invalidate cache and regenerate spec\n   */\n  async invalidateCache(): Promise<void> {\n    this.specCache = null;\n    await this.generateSpec();\n  }\n\n  /**\n   * Get the docs route handler\n   */\n  getDocsRouteHandler() {\n    return async (req: any, res: any) => {\n      try {\n        const method = String(req.method || \"GET\").toUpperCase();\n        if (method !== \"GET\" && method !== \"HEAD\") {\n          res.statusCode = 405;\n          res.setHeader(\"Allow\", \"GET, HEAD\");\n          res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n          res.end(\"Method Not Allowed\");\n          return;\n        }\n\n        const spec = await this.getSpec();\n\n        if (!spec) {\n          res.statusCode = 500;\n          res.setHeader(\"Content-Type\", \"text/html\");\n          res.end(`\n            <html>\n              <body>\n                <h1>Error</h1>\n                <p>Failed to generate OpenAPI specification</p>\n              </body>\n            </html>\n          `);\n          return;\n        }\n\n        // Set headers for HTML response\n        res.statusCode = 200;\n        res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n        res.setHeader(\"Cache-Control\", \"public, max-age=0, must-revalidate\");\n        res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n\n        // Generate HTML with Scalar\n        res.end(method === \"HEAD\" ? undefined : renderOpenAPIReferenceHTML(spec, this.config));\n      } catch (error) {\n        console.error(\"Error serving docs route:\", error);\n        res.statusCode = 500;\n        res.setHeader(\"Content-Type\", \"text/html\");\n        res.end(`\n          <html>\n            <body>\n              <h1>Error</h1>\n              <p>Failed to load API documentation</p>\n            </body>\n          </html>\n        `);\n      }\n    };\n  }\n}\n","import path from \"node:path\";\nimport { getDeployTargetForPreset } from \"./config\";\nimport { resolveCronConfig, type FarmCronJob } from \"./cron\";\nimport {\n  mergeFarmRouteRuntimeConfigs,\n  resolveFarmRouteRuleRuntimeConfig,\n  resolveFarmRouteRuntimeConfig,\n  type ResolvedFarmRouteRuntimeConfig,\n} from \"./route-runtime\";\nimport type { FarmConfig } from \"./types\";\nimport type { FarmDiscoveredWorkflow } from \"./workflows\";\n\ntype RouteMapEntry = {\n  pattern: string;\n  modulePath: string;\n};\n\ntype RouteManagerLike = {\n  getRoutes(): Map<string, RouteMapEntry>;\n  getLayouts(): Map<string, RouteMapEntry>;\n  getLoadings(): Map<string, RouteMapEntry>;\n  getErrors(): Map<string, RouteMapEntry>;\n  resolveRouteRuntimeConfig?(\n    pattern: string,\n  ): Promise<ResolvedFarmRouteRuntimeConfig> | ResolvedFarmRouteRuntimeConfig;\n};\n\ntype APIRouteManagerLike = {\n  getRoutes(): Map<\n    string,\n    {\n      path: string;\n      filePath: string;\n      methods: string[];\n      runtime?: \"auto\" | \"node\" | \"edge\";\n      regions?: \"auto\" | readonly string[];\n      maxDuration?: \"auto\" | number;\n    }\n  >;\n};\n\ntype MiddlewareManagerLike = {\n  getMiddlewares(): Array<{\n    path: string;\n    filePath: string;\n    handlers: unknown[];\n    source?: \"config\" | \"file\";\n  }>;\n};\n\ntype IntegrationLike = {\n  kind?: string;\n  type?: string;\n  category?: string;\n  serverRuntime?: boolean;\n  routes?: ReadonlyArray<{\n    path: string;\n    method?: string;\n    methods?: readonly string[];\n  }>;\n  middleware?: readonly unknown[];\n  providers?: readonly unknown[];\n  schema?: {\n    models?: Record<string, unknown>;\n  };\n};\n\nexport type FarmDevtoolsRuntime = {\n  runtime: \"auto\" | \"node\" | \"edge\";\n  regions?: string[];\n  maxDuration?: number;\n};\n\nexport type FarmDevtoolsDiagnostic = {\n  severity: \"error\" | \"warning\" | \"info\";\n  code: string;\n  title: string;\n  message: string;\n  action?: string;\n};\n\nexport type FarmDevtoolsSnapshot = {\n  generatedAt: string;\n  health: \"ready\" | \"attention\" | \"error\";\n  project: {\n    name: string;\n    root: string;\n    srcDir: string;\n    basePath: string;\n    deploymentId: string;\n  };\n  deployment: {\n    target: string;\n    preset: string;\n    outputDir?: string;\n  };\n  counts: {\n    pages: number;\n    layouts: number;\n    loadingBoundaries: number;\n    errorBoundaries: number;\n    apiRoutes: number;\n    middleware: number;\n    integrations: number;\n    storageMounts: number;\n    cronJobs: number;\n    workflows: number;\n    layers: number;\n    diagnostics: number;\n  };\n  routes: Array<{\n    kind: \"page\" | \"layout\" | \"loading\" | \"error\";\n    pattern: string;\n    filePath: string;\n    runtime?: FarmDevtoolsRuntime;\n  }>;\n  apiRoutes: Array<{\n    path: string;\n    methods: string[];\n    filePath: string;\n    runtime: FarmDevtoolsRuntime;\n  }>;\n  middleware: Array<{\n    path: string;\n    source: \"config\" | \"file\";\n    filePath: string;\n    handlerCount: number;\n  }>;\n  integrations: Array<{\n    key: string;\n    type: string;\n    category: string;\n    serverRuntime: boolean;\n    routes: Array<{ path: string; methods: string[] }>;\n    middlewareCount: number;\n    providerCount: number;\n    schemaModelCount: number;\n  }>;\n  storage: Array<{\n    mount: string;\n    driver: string;\n    default: boolean;\n  }>;\n  cron: FarmCronJob[];\n  workflows: Array<{\n    id: string;\n    filePath: string;\n    routePath: string;\n    schedule: string[];\n    timezone?: string;\n  }>;\n  layers: Array<{\n    name: string;\n    source: string;\n    srcDir: string;\n  }>;\n  environment: {\n    server: string[];\n    public: string[];\n  };\n  docs: {\n    enabled: boolean;\n    entry?: string;\n  };\n  features: {\n    openapi: boolean;\n    markdown: boolean;\n    serverComponents: boolean;\n    serverActions: boolean;\n    optimizedBoundary: boolean;\n    observability: boolean;\n  };\n  diagnostics: FarmDevtoolsDiagnostic[];\n};\n\nexport interface CreateFarmDevtoolsSnapshotInput {\n  root: string;\n  srcDir: string;\n  routeManager: RouteManagerLike;\n  apiRouteManager: APIRouteManagerLike;\n  middlewareManager: MiddlewareManagerLike;\n  config?: FarmConfig & { openapi?: { enabled?: boolean } };\n  workflows?: readonly FarmDiscoveredWorkflow[];\n  now?: () => Date;\n  env?: Record<string, string | undefined>;\n}\n\nfunction normalizePath(value: string): string {\n  return value.replace(/\\\\/g, \"/\");\n}\n\nfunction toProjectPath(root: string, filePath: string): string {\n  const normalizedRoot = normalizePath(root).replace(/\\/$/, \"\");\n  const normalizedFile = normalizePath(filePath);\n  if (normalizedFile.startsWith(normalizedRoot + \"/\")) {\n    return normalizedFile.slice(normalizedRoot.length + 1);\n  }\n  return normalizedFile;\n}\n\nfunction sortByPath<T extends { path?: string; pattern?: string }>(items: T[]): T[] {\n  return [...items].sort((a, b) =>\n    (a.path || a.pattern || \"\").localeCompare(b.path || b.pattern || \"\"),\n  );\n}\n\nfunction toRuntime(value: ResolvedFarmRouteRuntimeConfig): FarmDevtoolsRuntime {\n  return {\n    runtime: value.runtime,\n    ...(value.regions ? { regions: [...value.regions] } : {}),\n    ...(value.maxDuration ? { maxDuration: value.maxDuration } : {}),\n  };\n}\n\nasync function collectRoutes(\n  root: string,\n  kind: FarmDevtoolsSnapshot[\"routes\"][number][\"kind\"],\n  routes: Map<string, RouteMapEntry>,\n  routeManager: RouteManagerLike,\n  diagnostics: FarmDevtoolsDiagnostic[],\n): Promise<FarmDevtoolsSnapshot[\"routes\"]> {\n  return Promise.all(\n    Array.from(routes.values()).map(async (route) => {\n      let runtime: FarmDevtoolsRuntime | undefined;\n      if (kind === \"page\" && routeManager.resolveRouteRuntimeConfig) {\n        try {\n          runtime = toRuntime(await routeManager.resolveRouteRuntimeConfig(route.pattern));\n        } catch (error) {\n          diagnostics.push({\n            severity: \"warning\",\n            code: \"ROUTE_RUNTIME_UNRESOLVED\",\n            title: `Could not inspect ${route.pattern}`,\n            message: error instanceof Error ? error.message : String(error),\n            action: \"Check the route and inherited layout runtime exports.\",\n          });\n        }\n      }\n\n      return {\n        kind,\n        pattern: route.pattern,\n        filePath: toProjectPath(root, route.modulePath),\n        ...(runtime ? { runtime } : {}),\n      };\n    }),\n  );\n}\n\nfunction collectIntegrations(integrations: FarmConfig[\"integrations\"] | undefined) {\n  if (!integrations || typeof integrations !== \"object\") return [];\n\n  return Object.entries(integrations)\n    .filter((entry): entry is [string, NonNullable<(typeof entry)[1]>] => Boolean(entry[1]))\n    .map(([key, value]) => {\n      const integration = value as IntegrationLike;\n      const routes = (integration.routes || []).map((route) => ({\n        path: route.path,\n        methods: [...(route.methods || (route.method ? [route.method] : [\"ALL\"]))]\n          .map((method) => method.toUpperCase())\n          .sort(),\n      }));\n\n      return {\n        key,\n        type: integration.type || key,\n        category: integration.category || \"custom\",\n        serverRuntime: integration.serverRuntime !== false,\n        routes: sortByPath(routes),\n        middlewareCount: integration.middleware?.length || 0,\n        providerCount: integration.providers?.length || 0,\n        schemaModelCount: Object.keys(integration.schema?.models || {}).length,\n      };\n    })\n    .sort((a, b) => a.key.localeCompare(b.key));\n}\n\nfunction collectStorage(storage: FarmConfig[\"storage\"] | undefined): {\n  entries: FarmDevtoolsSnapshot[\"storage\"];\n  configured: boolean;\n} {\n  if (!storage || typeof storage !== \"object\") {\n    return {\n      entries: [{ mount: \"root\", driver: \"memory\", default: true }],\n      configured: false,\n    };\n  }\n\n  const value = storage as Record<string, any>;\n  if (value.kind === \"farm-storage-client\") {\n    return {\n      entries: [{ mount: \"root\", driver: \"storage client\", default: false }],\n      configured: true,\n    };\n  }\n\n  const configured = Object.keys(value).length > 0;\n  const rootDriver = value.client\n    ? describeStorageDriver(value.client)\n    : describeStorageDriver(value.driver);\n  const entries: FarmDevtoolsSnapshot[\"storage\"] = [\n    {\n      mount: \"root\",\n      driver: rootDriver,\n      default: !configured,\n    },\n  ];\n\n  if (value.mounts && typeof value.mounts === \"object\") {\n    for (const [mount, mountConfig] of Object.entries(value.mounts)) {\n      entries.push({\n        mount,\n        driver: describeStorageDriver(mountConfig),\n        default: false,\n      });\n    }\n  }\n\n  return {\n    entries: entries.sort((a, b) => {\n      if (a.mount === \"root\") return -1;\n      if (b.mount === \"root\") return 1;\n      return a.mount.localeCompare(b.mount);\n    }),\n    configured,\n  };\n}\n\nfunction describeStorageDriver(value: unknown): string {\n  if (!value) return \"memory\";\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"function\") return \"custom\";\n  if (typeof value !== \"object\") return \"custom\";\n\n  const record = value as Record<string, unknown>;\n  if (record.kind === \"farm-storage-client\") return \"storage client\";\n  if (typeof record.driver === \"string\") return record.driver;\n  if (typeof record.driver === \"function\") return \"custom\";\n  return \"custom\";\n}\n\nfunction featureEnabled(value: unknown): boolean {\n  if (!value) return false;\n  if (typeof value === \"object\" && \"enabled\" in value) {\n    return (value as { enabled?: boolean }).enabled !== false;\n  }\n  return value !== false;\n}\n\nfunction collectEnvironmentKeys(config: FarmConfig | undefined) {\n  const env = config?.env as\n    | { server?: Record<string, unknown>; public?: Record<string, unknown> }\n    | undefined;\n  return {\n    server: Object.keys(env?.server || {}).sort(),\n    public: Object.keys(env?.public || {}).sort(),\n  };\n}\n\nfunction resolveHealth(diagnostics: FarmDevtoolsDiagnostic[]): FarmDevtoolsSnapshot[\"health\"] {\n  if (diagnostics.some((diagnostic) => diagnostic.severity === \"error\")) return \"error\";\n  if (diagnostics.some((diagnostic) => diagnostic.severity === \"warning\")) return \"attention\";\n  return \"ready\";\n}\n\nexport async function createFarmDevtoolsSnapshot(\n  input: CreateFarmDevtoolsSnapshotInput,\n): Promise<FarmDevtoolsSnapshot> {\n  const config = input.config || {};\n  const diagnostics: FarmDevtoolsDiagnostic[] = [];\n  const pageRoutes = await collectRoutes(\n    input.root,\n    \"page\",\n    input.routeManager.getRoutes(),\n    input.routeManager,\n    diagnostics,\n  );\n  const layoutRoutes = await collectRoutes(\n    input.root,\n    \"layout\",\n    input.routeManager.getLayouts(),\n    input.routeManager,\n    diagnostics,\n  );\n  const loadingRoutes = await collectRoutes(\n    input.root,\n    \"loading\",\n    input.routeManager.getLoadings(),\n    input.routeManager,\n    diagnostics,\n  );\n  const errorRoutes = await collectRoutes(\n    input.root,\n    \"error\",\n    input.routeManager.getErrors(),\n    input.routeManager,\n    diagnostics,\n  );\n  const apiRoutes = sortByPath(\n    Array.from(input.apiRouteManager.getRoutes().values()).map((route) => {\n      const runtime = resolveFarmRouteRuntimeConfig(\n        mergeFarmRouteRuntimeConfigs(\n          resolveFarmRouteRuleRuntimeConfig(route.path, config.routeRules),\n          route,\n        ),\n        `API route \"${route.path}\"`,\n      );\n      return {\n        path: route.path,\n        methods: [...route.methods].sort(),\n        filePath: toProjectPath(input.root, route.filePath),\n        runtime: toRuntime(runtime),\n      };\n    }),\n  );\n  const middleware = sortByPath(\n    input.middlewareManager.getMiddlewares().map((entry) => ({\n      path: entry.path,\n      source: entry.source || \"file\",\n      filePath: toProjectPath(input.root, entry.filePath),\n      handlerCount: entry.handlers.length,\n    })),\n  );\n  const integrations = collectIntegrations(config.integrations);\n  const storage = collectStorage(config.storage);\n  const cron = resolveCronConfig(config.cron);\n  const workflows = (input.workflows || [])\n    .map((workflow) => ({\n      id: workflow.id,\n      filePath: toProjectPath(input.root, workflow.filePath),\n      routePath: workflow.routePath,\n      schedule: [...workflow.schedule],\n      ...(workflow.timezone ? { timezone: workflow.timezone } : {}),\n    }))\n    .sort((a, b) => a.id.localeCompare(b.id));\n  const layers = (config.layers || []).map((layer) => ({\n    name: layer.name,\n    source: layer.source,\n    srcDir: layer.srcDir,\n  }));\n  const deploymentPreset = String(config.deploy?.preset || config.preset || \"node-server\");\n  const deploymentTarget = String(\n    config.deploy?.target || getDeployTargetForPreset(deploymentPreset) || \"node\",\n  );\n  const env = input.env || process.env;\n\n  if (pageRoutes.length === 0) {\n    diagnostics.push({\n      severity: \"warning\",\n      code: \"NO_PAGE_ROUTES\",\n      title: \"No page routes found\",\n      message: `Farm did not discover a page under ${input.srcDir}/app.`,\n      action: `Add ${input.srcDir}/app/page.tsx or a programmatic page route.`,\n    });\n  }\n  if (layoutRoutes.length === 0) {\n    diagnostics.push({\n      severity: \"warning\",\n      code: \"ROOT_LAYOUT_MISSING\",\n      title: \"Root layout is missing\",\n      message: \"The application has no shared root layout.\",\n      action: `Add ${input.srcDir}/app/layout.tsx for shared metadata and application chrome.`,\n    });\n  }\n\n  const apiPaths = new Set(apiRoutes.map((route) => route.path));\n  for (const job of cron.jobs) {\n    if (!apiPaths.has(job.path)) {\n      diagnostics.push({\n        severity: \"warning\",\n        code: \"CRON_ROUTE_MISSING\",\n        title: `Cron route ${job.path} was not found`,\n        message: `${job.name} is scheduled, but its GET API route is not registered.`,\n        action: \"Add the target API route or update the cron path in farm.config.ts.\",\n      });\n    }\n  }\n  if (cron.jobs.length > 0 && !env[cron.secretEnv]) {\n    diagnostics.push({\n      severity: \"info\",\n      code: \"CRON_SECRET_NOT_SET\",\n      title: `${cron.secretEnv} is not set`,\n      message: \"Local manual runs remain available, but production cron routes fail closed.\",\n      action: `Set ${cron.secretEnv} in the deployment environment before production.`,\n    });\n  }\n  if (\n    storage.configured &&\n    storage.entries[0]?.driver === \"memory\" &&\n    [\"vercel\", \"cloudflare\", \"netlify\"].includes(deploymentTarget)\n  ) {\n    diagnostics.push({\n      severity: \"warning\",\n      code: \"EPHEMERAL_PRODUCTION_STORAGE\",\n      title: \"Production storage is in memory\",\n      message: `${deploymentTarget} instances do not preserve in-memory data across executions.`,\n      action: \"Configure a durable storage driver or mount for production state.\",\n    });\n  }\n\n  const environment = collectEnvironmentKeys(config);\n  const docs = config.docs;\n  const docsEnabled = featureEnabled(docs);\n  const allRoutes = sortByPath([...pageRoutes, ...layoutRoutes, ...loadingRoutes, ...errorRoutes]);\n\n  return {\n    generatedAt: (input.now?.() || new Date()).toISOString(),\n    health: resolveHealth(diagnostics),\n    project: {\n      name: path.basename(path.resolve(input.root)),\n      root: input.root,\n      srcDir: input.srcDir,\n      basePath: config.basePath || \"/\",\n      deploymentId: config.deploymentId || \"development\",\n    },\n    deployment: {\n      target: deploymentTarget,\n      preset: deploymentPreset,\n      ...(config.deploy?.outputDir ? { outputDir: config.deploy.outputDir } : {}),\n    },\n    counts: {\n      pages: pageRoutes.length,\n      layouts: layoutRoutes.length,\n      loadingBoundaries: loadingRoutes.length,\n      errorBoundaries: errorRoutes.length,\n      apiRoutes: apiRoutes.length,\n      middleware: middleware.length,\n      integrations: integrations.length,\n      storageMounts: storage.entries.length,\n      cronJobs: cron.jobs.length,\n      workflows: workflows.length,\n      layers: layers.length,\n      diagnostics: diagnostics.length,\n    },\n    routes: allRoutes,\n    apiRoutes,\n    middleware,\n    integrations,\n    storage: storage.entries,\n    cron: cron.jobs,\n    workflows,\n    layers,\n    environment,\n    docs: {\n      enabled: docsEnabled,\n      entry:\n        docsEnabled && docs && typeof docs === \"object\" && \"entry\" in docs\n          ? String(docs.entry)\n          : undefined,\n    },\n    features: {\n      openapi: Boolean(config.openapi?.enabled),\n      markdown: featureEnabled(config.md),\n      serverComponents: Boolean(config.experimental?.serverComponents),\n      serverActions: Boolean(config.experimental?.serverActions),\n      optimizedBoundary: Boolean(config.experimental?.optimizedBoundary),\n      observability: featureEnabled(config.observability),\n    },\n    diagnostics,\n  };\n}\n","import type { FarmDevtoolsDiagnostic, FarmDevtoolsRuntime, FarmDevtoolsSnapshot } from \"./devtools\";\n\ntype IconName =\n  | \"activity\"\n  | \"api\"\n  | \"app\"\n  | \"blocks\"\n  | \"book\"\n  | \"clock\"\n  | \"chevron\"\n  | \"close\"\n  | \"copy\"\n  | \"database\"\n  | \"external\"\n  | \"layers\"\n  | \"overview\"\n  | \"refresh\"\n  | \"route\"\n  | \"runtime\"\n  | \"search\"\n  | \"shield\"\n  | \"terminal\";\n\nconst ICON_PATHS: Record<IconName, string> = {\n  activity: '<path d=\"M22 12h-4l-3 9L9 3l-3 9H2\"/>',\n  api: '<path d=\"M8 3H7a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2 2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1\"/><path d=\"M16 3h1a2 2 0 0 1 2 2v4a2 2 0 0 0 2 2 2 2 0 0 0-2 2v4a2 2 0 0 1-2 2h-1\"/>',\n  app: '<path d=\"M15 3h6v6\"/><path d=\"M10 14 21 3\"/><path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"/>',\n  blocks:\n    '<rect width=\"7\" height=\"7\" x=\"3\" y=\"3\"/><rect width=\"7\" height=\"7\" x=\"14\" y=\"3\"/><rect width=\"7\" height=\"7\" x=\"14\" y=\"14\"/><rect width=\"7\" height=\"7\" x=\"3\" y=\"14\"/>',\n  book: '<path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\"/><path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\"/>',\n  clock: '<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M12 7v5l3 2\"/>',\n  chevron: '<path d=\"m9 18 6-6-6-6\"/>',\n  close: '<path d=\"M18 6 6 18M6 6l12 12\"/>',\n  copy: '<rect width=\"14\" height=\"14\" x=\"8\" y=\"8\"/><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"/>',\n  database:\n    '<ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\"/><path d=\"M3 5v14c0 1.7 4 3 9 3s9-1.3 9-3V5\"/><path d=\"M3 12c0 1.7 4 3 9 3s9-1.3 9-3\"/>',\n  external:\n    '<path d=\"M15 3h6v6\"/><path d=\"M10 14 21 3\"/><path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"/>',\n  layers:\n    '<path d=\"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z\"/><path d=\"m22 12.5-9.17 4.17a2 2 0 0 1-1.66 0L2 12.5\"/><path d=\"m22 17.5-9.17 4.17a2 2 0 0 1-1.66 0L2 17.5\"/>',\n  overview:\n    '<rect width=\"7\" height=\"9\" x=\"3\" y=\"3\"/><rect width=\"7\" height=\"5\" x=\"14\" y=\"3\"/><rect width=\"7\" height=\"9\" x=\"14\" y=\"12\"/><rect width=\"7\" height=\"5\" x=\"3\" y=\"16\"/>',\n  refresh:\n    '<path d=\"M20 11a8.1 8.1 0 0 0-15.5-2M4 4v5h5\"/><path d=\"M4 13a8.1 8.1 0 0 0 15.5 2M20 20v-5h-5\"/>',\n  route:\n    '<circle cx=\"6\" cy=\"19\" r=\"3\"/><path d=\"M9 19h5.5a3.5 3.5 0 0 0 0-7h-5a3.5 3.5 0 0 1 0-7H18\"/><circle cx=\"18\" cy=\"5\" r=\"3\"/>',\n  runtime:\n    '<rect width=\"20\" height=\"14\" x=\"2\" y=\"3\"/><line x1=\"8\" x2=\"16\" y1=\"21\" y2=\"21\"/><line x1=\"12\" x2=\"12\" y1=\"17\" y2=\"21\"/>',\n  search: '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/>',\n  shield: '<path d=\"M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3z\"/><path d=\"m9 12 2 2 4-4\"/>',\n  terminal: '<polyline points=\"4 17 10 11 4 5\"/><line x1=\"12\" x2=\"20\" y1=\"19\" y2=\"19\"/>',\n};\n\nfunction icon(name: IconName, className = \"\"): string {\n  return `<svg class=\"icon ${className}\" data-lucide=\"${name}\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${ICON_PATHS[name]}</svg>`;\n}\n\nfunction escapeHtml(value: unknown): string {\n  return String(value ?? \"\")\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&#39;\");\n}\n\nfunction escapeAttribute(value: unknown): string {\n  return escapeHtml(value).replace(/`/g, \"&#96;\");\n}\n\nfunction renderBadge(value: string, tone = \"neutral\"): string {\n  return `<span class=\"badge badge-${tone}\">${escapeHtml(value)}</span>`;\n}\n\nfunction renderRuntime(runtime: FarmDevtoolsRuntime | undefined): string {\n  if (!runtime) return '<span class=\"muted\">Inherited</span>';\n  const details = [\n    runtime.regions?.length ? runtime.regions.join(\", \") : null,\n    runtime.maxDuration ? `${runtime.maxDuration}s` : null,\n  ].filter(Boolean);\n  return `<span class=\"runtime-value\">${renderBadge(runtime.runtime, runtime.runtime)}${\n    details.length ? `<small>${escapeHtml(details.join(\" / \"))}</small>` : \"\"\n  }</span>`;\n}\n\nfunction renderEmpty(title: string, detail: string): string {\n  return `<div class=\"empty-state\">\n    ${icon(\"activity\")}\n    <strong>${escapeHtml(title)}</strong>\n    <span>${escapeHtml(detail)}</span>\n  </div>`;\n}\n\nfunction renderFilter(id: string, placeholder: string): string {\n  return `<label class=\"filter-control\">\n    ${icon(\"search\")}\n    <span class=\"sr-only\">${escapeHtml(placeholder)}</span>\n    <input type=\"search\" placeholder=\"${escapeAttribute(placeholder)}\" data-filter=\"${escapeAttribute(id)}\" autocomplete=\"off\">\n    <kbd>/</kbd>\n  </label>`;\n}\n\nfunction renderDiagnostics(diagnostics: FarmDevtoolsDiagnostic[]): string {\n  if (diagnostics.length === 0) {\n    return `<div class=\"diagnostic diagnostic-ready\">\n      <span class=\"diagnostic-mark\">${icon(\"shield\")}</span>\n      <div><strong>Framework checks passed</strong><p>Routes and configured systems are internally consistent.</p></div>\n      ${renderBadge(\"ready\", \"ready\")}\n    </div>`;\n  }\n\n  return diagnostics\n    .map(\n      (diagnostic) => `<article class=\"diagnostic diagnostic-${diagnostic.severity}\">\n        <span class=\"diagnostic-mark\">${icon(\n          diagnostic.severity === \"error\" ? \"activity\" : \"shield\",\n        )}</span>\n        <div>\n          <span class=\"diagnostic-code\">${escapeHtml(diagnostic.code)}</span>\n          <strong>${escapeHtml(diagnostic.title)}</strong>\n          <p>${escapeHtml(diagnostic.message)}</p>\n          ${diagnostic.action ? `<small>${escapeHtml(diagnostic.action)}</small>` : \"\"}\n        </div>\n        ${renderBadge(diagnostic.severity, diagnostic.severity)}\n      </article>`,\n    )\n    .join(\"\");\n}\n\nfunction renderSystemRows(snapshot: FarmDevtoolsSnapshot): string {\n  const rows = [\n    [\"Integrations\", snapshot.counts.integrations, \"Configured product adapters\", \"blocks\"],\n    [\"Storage\", snapshot.counts.storageMounts, \"Root driver and named mounts\", \"database\"],\n    [\"Cron\", snapshot.counts.cronJobs, \"Portable scheduled API routes\", \"clock\"],\n    [\"Workflows\", snapshot.counts.workflows, \"Discovered workflow modules\", \"activity\"],\n    [\"Docs\", snapshot.docs.enabled ? \"On\" : \"Off\", snapshot.docs.entry || \"No docs route\", \"book\"],\n  ] as const;\n\n  return rows\n    .map(\n      ([label, value, detail, rowIcon]) => `<div class=\"system-row\">\n        <span class=\"system-icon\">${icon(rowIcon)}</span>\n        <div><strong>${escapeHtml(label)}</strong><small>${escapeHtml(detail)}</small></div>\n        <span class=\"system-value\">${escapeHtml(value)}</span>\n      </div>`,\n    )\n    .join(\"\");\n}\n\nfunction renderIntegrations(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.integrations.length === 0) {\n    return renderEmpty(\n      \"No integrations configured\",\n      \"Register product systems through farm.config.ts when the app needs them.\",\n    );\n  }\n\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Registry key</th><th>Adapter</th><th>Routes</th><th>Runtime surface</th></tr></thead>\n    <tbody>${snapshot.integrations\n      .map(\n        (integration) => `<tr>\n          <td><code>${escapeHtml(integration.key)}</code><small class=\"cell-detail\">${escapeHtml(\n            integration.category,\n          )}</small></td>\n          <td>${escapeHtml(integration.type)}</td>\n          <td>${\n            integration.routes.length\n              ? integration.routes\n                  .map(\n                    (route) =>\n                      `<span class=\"route-operation\"><code>${escapeHtml(\n                        route.path,\n                      )}</code><small>${escapeHtml(route.methods.join(\", \"))}</small></span>`,\n                  )\n                  .join(\"\")\n              : '<span class=\"muted\">No HTTP routes</span>'\n          }</td>\n          <td><span class=\"runtime-facts\">${renderBadge(\n            integration.serverRuntime ? \"server\" : \"platform\",\n          )}<span>${integration.middlewareCount} middleware</span><span>${\n            integration.providerCount\n          } providers</span><span>${integration.schemaModelCount} models</span></span></td>\n        </tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderMiddleware(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.middleware.length === 0) {\n    return renderEmpty(\"No middleware configured\", \"Requests currently enter routes directly.\");\n  }\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Path</th><th>Source</th><th>Handlers</th><th>File</th></tr></thead>\n    <tbody>${snapshot.middleware\n      .map(\n        (entry) =>\n          `<tr><td><code>${escapeHtml(entry.path)}</code></td><td>${renderBadge(\n            entry.source,\n          )}</td><td>${entry.handlerCount}</td><td class=\"file-cell\">${escapeHtml(\n            entry.filePath,\n          )}</td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderStorage(snapshot: FarmDevtoolsSnapshot): string {\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Mount</th><th>Driver</th><th>State</th></tr></thead>\n    <tbody>${snapshot.storage\n      .map(\n        (entry) =>\n          `<tr><td><code>${escapeHtml(entry.mount)}</code></td><td>${escapeHtml(\n            entry.driver,\n          )}</td><td>${renderBadge(entry.default ? \"default\" : \"configured\")}</td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderCron(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.cron.length === 0) {\n    return renderEmpty(\n      \"No cron routes configured\",\n      \"Add named schedules under cron in farm.config.ts.\",\n    );\n  }\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Name</th><th>Schedule (UTC)</th><th>Target</th></tr></thead>\n    <tbody>${snapshot.cron\n      .map(\n        (job) =>\n          `<tr><td><code>${escapeHtml(job.name)}</code></td><td>${job.schedule\n            .map((schedule) => `<code class=\"schedule\">${escapeHtml(schedule)}</code>`)\n            .join(\"\")}</td><td><code>${escapeHtml(job.path)}</code></td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderWorkflows(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.workflows.length === 0) {\n    return renderEmpty(\n      \"No workflows discovered\",\n      \"Workflow directories are enabled but currently empty.\",\n    );\n  }\n  return `<div class=\"table-scroll\"><table>\n    <thead><tr><th>Workflow</th><th>Schedule</th><th>Endpoint</th><th>Source</th></tr></thead>\n    <tbody>${snapshot.workflows\n      .map(\n        (workflow) =>\n          `<tr><td><code>${escapeHtml(workflow.id)}</code></td><td>${\n            workflow.schedule.length\n              ? workflow.schedule.map((schedule) => `<code>${escapeHtml(schedule)}</code>`).join(\"\")\n              : '<span class=\"muted\">Manual</span>'\n          }</td><td><code>${escapeHtml(workflow.routePath)}</code></td><td class=\"file-cell\">${escapeHtml(\n            workflow.filePath,\n          )}</td></tr>`,\n      )\n      .join(\"\")}</tbody>\n  </table></div>`;\n}\n\nfunction renderFeatureMatrix(snapshot: FarmDevtoolsSnapshot): string {\n  const features = [\n    [\"OpenAPI\", snapshot.features.openapi],\n    [\"Markdown\", snapshot.features.markdown],\n    [\"Server components\", snapshot.features.serverComponents],\n    [\"Server actions\", snapshot.features.serverActions],\n    [\"Optimized boundary\", snapshot.features.optimizedBoundary],\n    [\"Observability\", snapshot.features.observability],\n  ] as const;\n  return `<div class=\"feature-matrix\">${features\n    .map(\n      ([label, enabled]) =>\n        `<div><span>${escapeHtml(label)}</span>${renderBadge(\n          enabled ? \"enabled\" : \"disabled\",\n          enabled ? \"ready\" : \"neutral\",\n        )}</div>`,\n    )\n    .join(\"\")}</div>`;\n}\n\nfunction renderEnvironment(snapshot: FarmDevtoolsSnapshot): string {\n  const renderKeys = (keys: string[]) =>\n    keys.length\n      ? `<div class=\"key-list\">${keys.map((key) => `<code>${escapeHtml(key)}</code>`).join(\"\")}</div>`\n      : '<span class=\"muted\">No validated keys</span>';\n  return `<div class=\"environment-grid\">\n    <div><span class=\"mini-label\">Server keys</span>${renderKeys(snapshot.environment.server)}</div>\n    <div><span class=\"mini-label\">Public keys</span>${renderKeys(snapshot.environment.public)}</div>\n  </div>`;\n}\n\nfunction renderLayers(snapshot: FarmDevtoolsSnapshot): string {\n  if (snapshot.layers.length === 0) {\n    return renderEmpty(\n      \"No layers extended\",\n      \"This project owns its complete route and config surface.\",\n    );\n  }\n  return `<div class=\"layer-list\">${snapshot.layers\n    .map(\n      (layer) =>\n        `<div><span>${icon(\"layers\")}<strong>${escapeHtml(\n          layer.name,\n        )}</strong></span><code>${escapeHtml(layer.source)}</code><small>${escapeHtml(\n          layer.srcDir,\n        )}</small></div>`,\n    )\n    .join(\"\")}</div>`;\n}\n\ntype InspectorEntry = {\n  id: string;\n  label: string;\n  description: string;\n  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 { PluginRoutes, PluginRoutesFactory } from \"./api/route\";\n// Plugin factories must emit declarations through public exports, never bundled\n// declaration chunk paths, even when they only import @farm.js/core/plugin.\nexport type { PluginRoutes, PluginRoutesFactory, RouteDefinition } from \"./api/route\";\nimport type { FarmConfig, FarmRequest, FarmResponse } from \"./types\";\nimport type { ViteDevServer } from \"vite\";\nimport type { FarmClientPlugin } from \"./client/plugin\";\nimport { getResolvedEnv, type ResolvedFarmEnv } from \"./env\";\nimport {\n  clearRequestContext,\n  deleteRequestContext,\n  getRequestContext,\n  getRequestContextSnapshot,\n  hasRequestContext,\n  setRequestContext,\n} from \"./request-context\";\nimport { getFarmPluginIntegrationContext } from \"./plugin-integration-context\";\n\ntype MaybePromise<T> = T | Promise<T>;\n/** @internal Marks a Node response whose intercepted end is awaiting response hooks. */\nexport const FARM_NODE_RESPONSE_END_PENDING = Symbol.for(\"farm.nodeResponseEndPending\");\ndeclare const FARM_PLUGIN_INTEGRATION_INSTANCE: unique symbol;\ndeclare const FARM_PLUGIN_INTEGRATION_BOUND: unique symbol;\n\nexport interface FarmPluginIntegrationContext<TInstance = unknown> {\n  /** Key used to register the integration in farm.config.ts. */\n  readonly key: string;\n  readonly category: string;\n  readonly type: string;\n  readonly instance: TInstance;\n  readonly serverRuntime: boolean;\n}\n\nexport class FarmRuntimeShutdownError extends Error {\n  readonly errors: readonly unknown[];\n\n  constructor(message: string, errors: readonly unknown[]) {\n    super(message);\n    this.name = \"FarmRuntimeShutdownError\";\n    this.errors = errors;\n  }\n}\n\nexport interface PluginRequestContext {\n  set: (\n    target: FarmRequest | Request,\n    key: string,\n    value: any,\n    options?: { exposeToPage?: boolean },\n  ) => void;\n  get: <T = any>(target: FarmRequest | Request, key: string) => T | undefined;\n  has: (target: FarmRequest | Request, key: string) => boolean;\n  delete: (target: FarmRequest | Request, key: string) => boolean;\n  clear: (target: FarmRequest | Request) => void;\n  getAll: (target: FarmRequest | Request, options?: { exposedOnly?: boolean }) => Map<string, any>;\n}\n\nexport interface FarmRequestStore {\n  set(key: string, value: unknown, options?: { exposeToPage?: boolean }): void;\n  get<T = unknown>(key: string): T | undefined;\n  has(key: string): boolean;\n  delete(key: string): boolean;\n  clear(): void;\n  snapshot(options?: { exposedOnly?: boolean }): Map<string, unknown>;\n}\n\nexport interface FarmPluginContext<TIntegrationInstance = unknown> {\n  config: FarmConfig;\n  viteServer?: ViteDevServer;\n  isDev: boolean;\n  isProd: boolean;\n  /** The owning integration when this plugin is contributed through `integration.plugins`. */\n  readonly integration?: Readonly<FarmPluginIntegrationContext<TIntegrationInstance>>;\n  /** Register resource cleanup that must run when the application runtime closes. */\n  lifecycle: FarmPluginLifecycle;\n  /** @deprecated Use `ctx.req` inside request hooks. */\n  requestContext: PluginRequestContext;\n}\n\ntype FarmPluginHookContext<\n  TContext,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = TIntegrationBound extends true\n  ? Omit<TContext, \"integration\"> & {\n      /** The owning integration bound by `definePlugin.forIntegration<T>()`. */\n      readonly integration: Readonly<FarmPluginIntegrationContext<TIntegrationInstance>>;\n    }\n  : TContext;\n\nexport interface FarmPluginLifecycle {\n  /**\n   * Register a database, storage, queue, or other resource disposer.\n   * Disposers run once in reverse registration order after plugin shutdown hooks.\n   */\n  onShutdown(dispose: () => void | Promise<void>): () => void;\n}\n\nexport interface FarmRequestPluginContext<\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  /** Request-scoped values for the current hook invocation. */\n  readonly req: FarmRequestStore;\n}\n\nexport interface RouteDiscoveredPayload {\n  kind: \"page\" | \"layout\";\n  pattern: string;\n  modulePath: string;\n}\n\nexport interface RoutesGeneratedPayload {\n  routes: RouteDiscoveredPayload[];\n  pageCount: number;\n  layoutCount: number;\n}\n\nexport interface MiddlewareDiscoveredPayload {\n  path: string;\n  filePath: string;\n  handlerCount: number;\n}\n\nexport interface APIRouteDiscoveredPayload {\n  path: string;\n  filePath: string;\n  methods: string[];\n}\n\nexport interface RouteMatchPayload {\n  pathname: string;\n  method?: string;\n}\n\nexport interface RouteMatchResultPayload {\n  pathname: string;\n  matched: boolean;\n  routePattern: string | null;\n  params: Record<string, string>;\n  layoutPatterns: string[];\n}\n\nexport interface RenderLifecyclePayload {\n  pathname: string;\n  method: string;\n  routePattern: string | null;\n  params: Record<string, string>;\n}\n\nexport interface APIHandlerLifecyclePayload {\n  pathname: string;\n  method: string;\n  routePath?: string;\n}\n\nexport interface ErrorLifecyclePayload {\n  phase: string;\n  error: unknown;\n  meta?: Record<string, unknown>;\n}\n\nexport interface HMRUpdatePayload {\n  file: string;\n  modules: string[];\n}\n\nexport interface BundleLifecyclePayload {\n  root: string;\n  preset: string;\n  universal: boolean;\n  distDir: string;\n  outputDir?: string;\n}\n\nexport interface BundleResultPayload extends BundleLifecyclePayload {\n  success: boolean;\n}\n\nexport interface NitroBuildLifecyclePayload {\n  root: string;\n  preset: string;\n  distDir: string;\n  outputDir: string;\n}\n\nexport interface ShutdownPayload {\n  reason: string;\n}\n\nexport type FarmPluginRuntimeKind =\n  | \"request\"\n  | \"page\"\n  | \"api\"\n  | \"action\"\n  | \"integration\"\n  | \"docs\"\n  | \"asset\"\n  | (string & {});\n\nexport interface FarmPluginRouteRuntimePayload {\n  pathname: string;\n  pattern?: string | null;\n  params?: Record<string, string>;\n}\n\nexport interface FarmPluginSetupContext<\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  env: ResolvedFarmEnv;\n}\n\nexport interface FarmPluginStateContext<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> extends FarmPluginContext<TIntegrationInstance> {\n  state: TState;\n}\n\nexport interface FarmPluginRuntimeBaseEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> extends FarmPluginStateContext<TState, TIntegrationInstance> {\n  request: Request;\n  /** Request-scoped values shared by plugin hooks. */\n  req: FarmRequestStore;\n  kind: FarmPluginRuntimeKind;\n  route?: FarmPluginRouteRuntimePayload;\n  signal: AbortSignal;\n  waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginRuntimeContextEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> = FarmPluginRuntimeBaseEvent<TState, TIntegrationInstance>;\n\nexport interface FarmPluginRuntimeBeforeEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBaseEvent<TState, TIntegrationInstance> {\n  ctx: Readonly<TRequestContext>;\n}\n\nexport interface FarmPluginRuntimeAfterEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance> {\n  response: Response;\n  durationMs: number;\n}\n\nexport interface FarmPluginRuntimeErrorEvent<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance> {\n  error: unknown;\n  durationMs: number;\n}\n\nexport type FarmPluginRuntimeStartEvent<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n> = FarmPluginStateContext<TState, TIntegrationInstance>;\n\nexport interface FarmPluginRuntimeCloseEvent<TState = unknown, TIntegrationInstance = unknown>\n  extends FarmPluginStateContext<TState, TIntegrationInstance>, ShutdownPayload {}\n\ntype FarmPluginContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmRequestPluginContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmRequestPluginContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginSetupContextFor<\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginSetupContext<TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginStateContextFor<\n  TState,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<\n  FarmPluginStateContext<TState, TIntegrationInstance>,\n  TIntegrationInstance,\n  TIntegrationBound\n>;\n\ntype FarmPluginRuntimeEventFor<\n  TEvent,\n  TIntegrationInstance,\n  TIntegrationBound extends boolean,\n> = FarmPluginHookContext<TEvent, TIntegrationInstance, TIntegrationBound>;\n\nexport interface FarmPluginRuntimeHooks<\n  TState = unknown,\n  TRequestContext extends object = Record<string, unknown>,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  start?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeStartEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n  context?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeContextEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<TRequestContext>;\n  before?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeBeforeEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<Request | Response | void>;\n  after?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeAfterEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<Response | void>;\n  error?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeErrorEvent<TState, TRequestContext, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n  close?(\n    event: FarmPluginRuntimeEventFor<\n      FarmPluginRuntimeCloseEvent<TState, TIntegrationInstance>,\n      TIntegrationInstance,\n      TIntegrationBound\n    >,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginRuntimeRequestOptions {\n  kind?: FarmPluginRuntimeKind;\n  route?: FarmPluginRouteRuntimePayload;\n  waitUntil?: (promise: Promise<unknown>) => void;\n}\n\nexport type FarmPluginRuntimeRequestHandler = (request: Request) => MaybePromise<Response>;\n\nexport interface FarmPluginRuntimeSession {\n  request: Request;\n  response?: Response;\n  ctx: Readonly<Record<string, unknown>>;\n  startedAt: number;\n  options: FarmPluginRuntimeRequestOptions;\n  waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginDiscoveredRoute =\n  | RouteDiscoveredPayload\n  | ({ kind: \"middleware\" } & MiddlewareDiscoveredPayload)\n  | ({ kind: \"api\" } & APIRouteDiscoveredPayload);\n\nexport interface FarmPluginRouterHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  discovered?(\n    route: FarmPluginDiscoveredRoute,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  generated?(\n    routes: RoutesGeneratedPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  before?(\n    route: RouteMatchPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  after?(\n    result: RouteMatchResultPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginRenderHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  before?(\n    render: RenderLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  html?(\n    html: string,\n    render: RenderLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<string | void>;\n}\n\nexport interface FarmPluginBuildHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  before?(\n    bundle: BundleLifecyclePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  configure?(\n    buildConfig: any,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<any>;\n  after?(\n    result: BundleResultPayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginDevHooks<\n  TState = unknown,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n> {\n  server?(\n    viteServer: ViteDevServer,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n  update?(\n    update: HMRUpdatePayload,\n    context: FarmPluginStateContextFor<TState, TIntegrationInstance, TIntegrationBound>,\n  ): MaybePromise<void>;\n}\n\nexport interface FarmPluginClientConfig<\n  TState = unknown,\n  TPublic = undefined,\n> extends FarmClientPlugin<TState, TPublic> {\n  /** Explicitly public, JSON-safe data embedded in the browser bundle. */\n  public?: TPublic;\n}\n\nexport interface FarmPlugin<\n  TState = any,\n  TRequestContext extends object = Record<string, unknown>,\n  TClientState = any,\n  TClientPublic = any,\n  TIntegrationInstance = unknown,\n  TIntegrationBound extends boolean = false,\n  TRoutes extends PluginRoutes = PluginRoutes,\n> {\n  name: string;\n  version?: string;\n  enforce?: \"pre\" | \"post\";\n  /** Declarative API routes, mounted through the normal dev and production API pipeline. */\n  routes?: PluginRoutesFactory<TRoutes>;\n\n  /** Transform Farm config before the development or production pipeline is created. */\n  configure?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => MaybePromise<FarmConfig | void>;\n  /** Initialize private plugin state once for this plugin manager. */\n  setup?: (\n    context: FarmPluginSetupContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => MaybePromise<TState>;\n\n  runtime?: FarmPluginRuntimeHooks<\n    TState,\n    TRequestContext,\n    TIntegrationInstance,\n    TIntegrationBound\n  >;\n  router?: FarmPluginRouterHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  render?: FarmPluginRenderHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  build?: FarmPluginBuildHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  dev?: FarmPluginDevHooks<TState, TIntegrationInstance, TIntegrationBound>;\n  /** Optional browser lifecycle for this logical plugin. */\n  client?: FarmPluginClientConfig<TClientState, TClientPublic>;\n\n  /** @internal Carries the expected integration instance type without runtime data. */\n  readonly [FARM_PLUGIN_INTEGRATION_INSTANCE]?: (instance: TIntegrationInstance) => void;\n  /** @internal Prevents integration-bound plugins from being registered globally. */\n  readonly [FARM_PLUGIN_INTEGRATION_BOUND]?: TIntegrationBound;\n\n  /** @deprecated Use `setup` instead. */\n  init?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `runtime.start` instead. */\n  ready?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `dev.server` instead. */\n  devServerCreated?: (\n    viteServer: ViteDevServer,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use `configure` instead. */\n  config?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => FarmConfig | Promise<FarmConfig>;\n  configResolved?: (\n    config: FarmConfig,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.before` instead. */\n  buildStart?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.after` instead. */\n  buildEnd?: (\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use `router.discovered` instead. */\n  routeDiscovered?: (\n    route: RouteDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.generated` instead. */\n  routesGenerated?: (\n    routes: RoutesGeneratedPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.discovered` instead. */\n  middlewareDiscovered?: (\n    middleware: MiddlewareDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.discovered` instead. */\n  apiRouteDiscovered?: (\n    route: APIRouteDiscoveredPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.before` instead. */\n  beforeRouteMatch?: (\n    route: RouteMatchPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `router.after` instead. */\n  afterRouteMatch?: (\n    result: RouteMatchResultPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `render.before` instead. */\n  beforeRender?: (\n    render: RenderLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `render.html` instead. */\n  afterRender?: (\n    html: string,\n    render: RenderLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => string | Promise<string> | void | Promise<void>;\n  /** @deprecated Use `runtime.before` instead. */\n  beforeApiHandler?: (\n    request: Request,\n    api: APIHandlerLifecyclePayload,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => Request | Promise<Request> | void | Promise<void>;\n  /** @deprecated Use `runtime.after` instead. */\n  afterApiHandler?: (\n    response: Response,\n    api: APIHandlerLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => Response | Promise<Response> | void | Promise<void>;\n  onError?: (\n    error: ErrorLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `dev.update` instead. */\n  hmrUpdate?: (\n    update: HMRUpdatePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.before` instead. */\n  beforeBundle?: (\n    bundle: BundleLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.after` instead. */\n  afterBundle?: (\n    result: BundleResultPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `build.configure` instead. */\n  beforeNitroBuild?: (\n    nitroConfig: any,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => any | Promise<any>;\n  afterNitroBuild?: (\n    payload: NitroBuildLifecyclePayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use `runtime.close` instead. */\n  shutdown?: (\n    payload: ShutdownPayload,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  /** @deprecated Use the Web Request based `runtime.before` hook instead. */\n  beforeRequest?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n  /** @deprecated Use the Web Response based `runtime.after` hook instead. */\n  afterResponse?: (\n    req: FarmRequest,\n    res: FarmResponse,\n    context: FarmRequestPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => void | Promise<void>;\n\n  // Transform hooks\n  /** @deprecated Use `render.html` instead. */\n  transformHTML?: (\n    html: string,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => string | Promise<string>;\n  /** @deprecated Use `render.before` or `render.html` instead. */\n  transformPage?: (\n    component: any,\n    context: FarmPluginContextFor<TIntegrationInstance, TIntegrationBound>,\n  ) => any | Promise<any>;\n}\n\nexport class PluginManager {\n  private plugins: FarmPlugin[] = [];\n  private hookPresence = new Map<keyof FarmPlugin, boolean>();\n  private runtimeHookPresence = new Map<\"context\" | \"before\" | \"after\" | \"error\", boolean>();\n  private context: FarmPluginContext;\n  private pluginStates = new Map<FarmPlugin, unknown>();\n  private setupComplete = false;\n  private initialized = false;\n  private runtimeReady = false;\n  private runtimeClosed = false;\n  private runtimeStartPromise?: Promise<void>;\n  private runtimeClosePromise?: Promise<void>;\n  private runtimeShutdownHooksRunning = false;\n  private runtimeDisposers: Array<() => void | Promise<void>> = [];\n  private runtimeRequestContexts = new WeakMap<Request, Readonly<Record<string, unknown>>>();\n  private failedRuntimeSessions = new WeakSet<FarmPluginRuntimeSession>();\n\n  constructor(context: Omit<FarmPluginContext, \"requestContext\" | \"lifecycle\">) {\n    this.context = {\n      ...context,\n      lifecycle: {\n        onShutdown: (dispose) => {\n          if (typeof dispose !== \"function\") {\n            throw new TypeError(\"Farm lifecycle.onShutdown requires a cleanup function\");\n          }\n          // 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    const requestContext = this.context.requestContext;\n    const values = requestContext.getAll(source);\n    const exposed = requestContext.getAll(source, { exposedOnly: true });\n\n    for (const [key, value] of values) {\n      requestContext.set(target, key, value, {\n        exposeToPage: exposed.has(key),\n      });\n    }\n  }\n\n  private copyRuntimeRequestContext(source: Request, target: Request): void {\n    const runtimeContext = this.runtimeRequestContexts.get(source);\n    if (runtimeContext) {\n      this.runtimeRequestContexts.set(target, runtimeContext);\n    }\n  }\n\n  private createRuntimeBaseEvent(\n    plugin: FarmPlugin,\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): FarmPluginRuntimeBaseEvent {\n    return {\n      ...this.createStateHookContext(plugin),\n      request,\n      req: this.createRequestHookContext(request, plugin).req,\n      kind: options.kind ?? \"request\",\n      route: options.route,\n      signal: request.signal,\n      waitUntil,\n    };\n  }\n\n  private async createRuntimeRequestContext(\n    request: Request,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): Promise<Readonly<Record<string, unknown>>> {\n    const values: Record<string, unknown> = {};\n    const owners = new Map<string, string>();\n\n    for (const plugin of this.getSortedPlugins()) {\n      const createContext = plugin.runtime?.context;\n      if (!createContext) continue;\n\n      const result = await createContext(\n        this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n      );\n      if (result === undefined) continue;\n      if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n        throw new TypeError(`Farm plugin \"${plugin.name}\" runtime.context must return an object`);\n      }\n\n      for (const [key, value] of Object.entries(result)) {\n        const owner = owners.get(key);\n        if (owner) {\n          throw new Error(\n            `Farm plugin context key \"${key}\" from \"${plugin.name}\" conflicts with \"${owner}\"`,\n          );\n        }\n        owners.set(key, plugin.name);\n        values[key] = value;\n      }\n    }\n\n    const runtimeContext = Object.freeze(values);\n    this.runtimeRequestContexts.set(request, runtimeContext);\n    return runtimeContext;\n  }\n\n  private async runRuntimeErrorHooks(\n    request: Request,\n    error: unknown,\n    ctx: Readonly<Record<string, unknown>>,\n    durationMs: number,\n    options: FarmPluginRuntimeRequestOptions,\n    waitUntil: (promise: Promise<unknown>) => void,\n  ): Promise<void> {\n    for (const plugin of this.getSortedPlugins()) {\n      const onError = plugin.runtime?.error;\n      if (!onError) continue;\n\n      try {\n        await onError({\n          ...this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n          ctx,\n          error,\n          durationMs,\n        });\n      } catch (hookError) {\n        console.error(`Farm plugin \"${plugin.name}\" runtime.error failed:`, hookError);\n      }\n    }\n\n    try {\n      await this.runHookParallel(\"onError\", {\n        phase: \"runtime\",\n        error,\n        meta: {\n          kind: options.kind ?? \"request\",\n          pathname: new URL(request.url).pathname,\n          durationMs,\n        },\n      });\n    } catch (hookError) {\n      console.error(\"Farm plugin onError hook failed:\", hookError);\n    }\n  }\n\n  private createStateHookContext(\n    plugin: FarmPlugin,\n    context: FarmPluginContext = this.context,\n  ): FarmPluginStateContext {\n    return {\n      ...this.createPluginHookContext(plugin, context),\n      state: this.pluginStates.get(plugin),\n    };\n  }\n\n  private getPluginHooks(\n    plugin: FarmPlugin,\n    hookName: keyof FarmPlugin,\n  ): Array<(...args: any[]) => any> {\n    const hooks: Array<(...args: any[]) => any> = [];\n    const legacyHook = plugin[hookName];\n    if (typeof legacyHook === \"function\") {\n      hooks.push(legacyHook);\n    }\n\n    const withState = (context: FarmPluginContext) => this.createStateHookContext(plugin, context);\n\n    switch (hookName) {\n      case \"config\":\n        if (plugin.configure) {\n          hooks.push((config: FarmConfig, context: FarmPluginContext) =>\n            plugin.configure?.(config, context),\n          );\n        }\n        break;\n      case \"ready\":\n        if (plugin.runtime?.start) {\n          hooks.push((context: FarmPluginContext) => plugin.runtime?.start?.(withState(context)));\n        }\n        break;\n      case \"shutdown\":\n        if (plugin.runtime?.close) {\n          hooks.push((payload: ShutdownPayload, context: FarmPluginContext) =>\n            plugin.runtime?.close?.({\n              ...withState(context),\n              reason: payload.reason,\n            }),\n          );\n        }\n        break;\n      case \"routeDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: RouteDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.(route, withState(context)),\n          );\n        }\n        break;\n      case \"middlewareDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: MiddlewareDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.({ kind: \"middleware\", ...route }, withState(context)),\n          );\n        }\n        break;\n      case \"apiRouteDiscovered\":\n        if (plugin.router?.discovered) {\n          hooks.push((route: APIRouteDiscoveredPayload, context: FarmPluginContext) =>\n            plugin.router?.discovered?.({ kind: \"api\", ...route }, withState(context)),\n          );\n        }\n        break;\n      case \"routesGenerated\":\n        if (plugin.router?.generated) {\n          hooks.push((routes: RoutesGeneratedPayload, context: FarmPluginContext) =>\n            plugin.router?.generated?.(routes, withState(context)),\n          );\n        }\n        break;\n      case \"beforeRouteMatch\":\n        if (plugin.router?.before) {\n          hooks.push((route: RouteMatchPayload, context: FarmPluginContext) =>\n            plugin.router?.before?.(route, withState(context)),\n          );\n        }\n        break;\n      case \"afterRouteMatch\":\n        if (plugin.router?.after) {\n          hooks.push((result: RouteMatchResultPayload, context: FarmPluginContext) =>\n            plugin.router?.after?.(result, withState(context)),\n          );\n        }\n        break;\n      case \"beforeRender\":\n        if (plugin.render?.before) {\n          hooks.push((render: RenderLifecyclePayload, context: FarmPluginContext) =>\n            plugin.render?.before?.(render, withState(context)),\n          );\n        }\n        break;\n      case \"afterRender\":\n        if (plugin.render?.html) {\n          hooks.push((html: string, render: RenderLifecyclePayload, context: FarmPluginContext) =>\n            plugin.render?.html?.(html, render, withState(context)),\n          );\n        }\n        break;\n      case \"beforeBundle\":\n        if (plugin.build?.before) {\n          hooks.push((bundle: BundleLifecyclePayload, context: FarmPluginContext) =>\n            plugin.build?.before?.(bundle, withState(context)),\n          );\n        }\n        break;\n      case \"beforeNitroBuild\":\n        if (plugin.build?.configure) {\n          hooks.push((buildConfig: any, context: FarmPluginContext) =>\n            plugin.build?.configure?.(buildConfig, withState(context)),\n          );\n        }\n        break;\n      case \"afterBundle\":\n        if (plugin.build?.after) {\n          hooks.push((result: BundleResultPayload, context: FarmPluginContext) =>\n            plugin.build?.after?.(result, withState(context)),\n          );\n        }\n        break;\n      case \"devServerCreated\":\n        if (plugin.dev?.server) {\n          hooks.push((server: ViteDevServer, context: FarmPluginContext) =>\n            plugin.dev?.server?.(server, withState(context)),\n          );\n        }\n        break;\n      case \"hmrUpdate\":\n        if (plugin.dev?.update) {\n          hooks.push((update: HMRUpdatePayload, context: FarmPluginContext) =>\n            plugin.dev?.update?.(update, withState(context)),\n          );\n        }\n        break;\n    }\n\n    return hooks;\n  }\n\n  private getHookContext(\n    plugin: FarmPlugin,\n    hookName: keyof FarmPlugin,\n    args: any[],\n  ): FarmPluginContext {\n    if (\n      hookName === \"beforeRequest\" ||\n      hookName === \"afterResponse\" ||\n      hookName === \"beforeApiHandler\"\n    ) {\n      const target = args[0];\n      if (target && typeof target === \"object\") {\n        return this.createRequestHookContext(target, plugin);\n      }\n    }\n\n    return this.createPluginHookContext(plugin);\n  }\n\n  addPlugin(plugin: FarmPlugin) {\n    this.plugins.push(plugin);\n    this.hookPresence.clear();\n    this.runtimeHookPresence.clear();\n  }\n\n  addPlugins(plugins: FarmPlugin[]) {\n    for (const plugin of plugins) {\n      this.addPlugin(plugin);\n    }\n  }\n\n  getPlugins(): FarmPlugin[] {\n    return [...this.plugins];\n  }\n\n  getSortedPlugins(): FarmPlugin[] {\n    const pre = this.plugins.filter((p) => p.enforce === \"pre\");\n    const normal = this.plugins.filter((p) => !p.enforce);\n    const post = this.plugins.filter((p) => p.enforce === \"post\");\n    return [...pre, ...normal, ...post];\n  }\n\n  hasHook(hookName: keyof FarmPlugin): boolean {\n    const cached = this.hookPresence.get(hookName);\n    if (cached !== undefined) return cached;\n\n    const present = this.plugins.some((plugin) => this.getPluginHooks(plugin, hookName).length > 0);\n    this.hookPresence.set(hookName, present);\n    return present;\n  }\n\n  hasRuntimeHook(hookName: \"context\" | \"before\" | \"after\" | \"error\"): boolean {\n    const cached = this.runtimeHookPresence.get(hookName);\n    if (cached !== undefined) return cached;\n\n    const present = this.plugins.some((plugin) => typeof plugin.runtime?.[hookName] === \"function\");\n    this.runtimeHookPresence.set(hookName, present);\n    return present;\n  }\n\n  hasRuntimeRequestHooks(): boolean {\n    return (\n      this.hasRuntimeHook(\"context\") ||\n      this.hasRuntimeHook(\"before\") ||\n      this.hasRuntimeHook(\"after\") ||\n      this.hasRuntimeHook(\"error\")\n    );\n  }\n\n  copyRequestContext(source: FarmRequest | Request, target: FarmRequest | Request): void {\n    this.copyRequestStore(source, target);\n    if (source instanceof Request && target instanceof Request) {\n      this.copyRuntimeRequestContext(source, target);\n    }\n  }\n\n  async setupPlugins(): Promise<void> {\n    if (this.setupComplete) return;\n\n    for (const plugin of this.getSortedPlugins()) {\n      if (!plugin.setup) continue;\n      const state = await plugin.setup({\n        ...this.createPluginHookContext(plugin),\n        env: getResolvedEnv(),\n      });\n      this.pluginStates.set(plugin, state);\n    }\n\n    this.setupComplete = true;\n  }\n\n  async startRuntime(): Promise<void> {\n    if (this.runtimeReady) return;\n    if (this.runtimeStartPromise) return this.runtimeStartPromise;\n\n    this.runtimeStartPromise = (async () => {\n      if (!this.initialized) {\n        await this.runHookParallel(\"init\");\n      }\n      await this.setupPlugins();\n      if (!this.runtimeReady) {\n        await this.runHookParallel(\"ready\");\n      }\n    })();\n\n    try {\n      await this.runtimeStartPromise;\n    } catch (error) {\n      this.runtimeStartPromise = undefined;\n      throw error;\n    }\n  }\n\n  async closeRuntime(reason = \"runtime-closed\"): Promise<void> {\n    if (this.runtimeClosePromise) return this.runtimeClosePromise;\n    if (this.runtimeClosed) return;\n\n    this.runtimeClosePromise = (async () => {\n      const errors: unknown[] = [];\n      this.runtimeShutdownHooksRunning = true;\n      try {\n        await this.runHookParallel(\"shutdown\", { reason });\n      } catch (error) {\n        if (error instanceof FarmRuntimeShutdownError) errors.push(...error.errors);\n        else errors.push(error);\n      } finally {\n        this.runtimeShutdownHooksRunning = false;\n      }\n\n      // 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 runtimeContext: Readonly<Record<string, unknown>> = Object.freeze({});\n\n    try {\n      runtimeContext = await this.createRuntimeRequestContext(activeRequest, options, waitUntil);\n\n      let response: Response | undefined;\n      for (const plugin of this.getSortedPlugins()) {\n        const before = plugin.runtime?.before;\n        if (!before) continue;\n\n        const result = await before({\n          ...this.createRuntimeBaseEvent(plugin, activeRequest, options, waitUntil),\n          ctx: runtimeContext,\n        });\n\n        if (result instanceof Request) {\n          this.copyRequestStore(activeRequest, result);\n          this.copyRuntimeRequestContext(activeRequest, result);\n          activeRequest = result;\n          continue;\n        }\n        if (result instanceof Response) {\n          response = result;\n          break;\n        }\n        if (result !== undefined) {\n          throw new TypeError(\n            `Farm plugin \"${plugin.name}\" runtime.before must return a Request, Response, or undefined`,\n          );\n        }\n      }\n\n      return {\n        request: activeRequest,\n        response,\n        ctx: runtimeContext,\n        startedAt,\n        options,\n        waitUntil,\n      };\n    } catch (error) {\n      await this.runRuntimeErrorHooks(\n        activeRequest,\n        error,\n        runtimeContext,\n        Date.now() - startedAt,\n        options,\n        waitUntil,\n      );\n      throw error;\n    }\n  }\n\n  async endRuntimeRequest(\n    session: FarmPluginRuntimeSession,\n    initialResponse: Response,\n  ): Promise<Response> {\n    let response = initialResponse;\n\n    try {\n      for (const plugin of this.getSortedPlugins()) {\n        const after = plugin.runtime?.after;\n        if (!after) continue;\n\n        const result = await after({\n          ...this.createRuntimeBaseEvent(\n            plugin,\n            session.request,\n            session.options,\n            session.waitUntil,\n          ),\n          ctx: session.ctx,\n          response,\n          durationMs: Date.now() - session.startedAt,\n        });\n        if (result !== undefined) {\n          if (!(result instanceof Response)) {\n            throw new TypeError(\n              `Farm plugin \"${plugin.name}\" runtime.after must return a Response or undefined`,\n            );\n          }\n          response = result;\n        }\n      }\n\n      return response;\n    } catch (error) {\n      await this.failRuntimeRequest(session, error);\n      throw error;\n    }\n  }\n\n  async failRuntimeRequest(session: FarmPluginRuntimeSession, error: unknown): Promise<void> {\n    if (this.failedRuntimeSessions.has(session)) return;\n    this.failedRuntimeSessions.add(session);\n    await this.runRuntimeErrorHooks(\n      session.request,\n      error,\n      session.ctx,\n      Date.now() - session.startedAt,\n      session.options,\n      session.waitUntil,\n    );\n  }\n\n  async runRuntimeRequest(\n    request: Request,\n    handler: FarmPluginRuntimeRequestHandler,\n    options: FarmPluginRuntimeRequestOptions = {},\n  ): Promise<Response> {\n    const session = await this.beginRuntimeRequest(request, options);\n    try {\n      const response = session.response ?? (await handler(session.request));\n      if (!(response instanceof Response)) {\n        throw new TypeError(\"Farm plugin runtime handlers must return a Response\");\n      }\n      return await this.endRuntimeRequest(session, response);\n    } catch (error) {\n      await this.failRuntimeRequest(session, error);\n      throw error;\n    }\n  }\n\n  async runHook<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<any> {\n    const plugins = this.getSortedPlugins();\n\n    for (const plugin of plugins) {\n      for (const hook of this.getPluginHooks(plugin, hookName)) {\n        const hookContext = this.getHookContext(plugin, hookName, args);\n        const result = await (hook as any).apply(plugin, [...args, hookContext]);\n        if (result !== undefined) {\n          return result;\n        }\n      }\n    }\n  }\n\n  async runHookSerial<K extends keyof FarmPlugin>(\n    hookName: K,\n    initialValue: any,\n    ...args: any[]\n  ): Promise<any> {\n    const plugins = this.getSortedPlugins();\n    let value = initialValue;\n\n    for (const plugin of plugins) {\n      for (const hook of this.getPluginHooks(plugin, hookName)) {\n        const hookArgs = [value, ...args];\n        const hookContext = this.getHookContext(plugin, hookName, hookArgs);\n        const result = await (hook as any).apply(plugin, [...hookArgs, hookContext]);\n        if (result !== undefined) {\n          if (\n            hookName === \"beforeApiHandler\" &&\n            result !== value &&\n            value &&\n            result &&\n            typeof value === \"object\" &&\n            typeof result === \"object\"\n          ) {\n            this.copyRequestStore(value as FarmRequest | Request, result as FarmRequest | Request);\n          }\n          value = result;\n        }\n      }\n    }\n\n    return value;\n  }\n\n  async runHookParallel<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<boolean> {\n    return this.runHookParallelFiltered(hookName, () => true, ...args);\n  }\n\n  /** @internal Runs hooks for only the plugins selected by the runtime adapter. */\n  async runHookParallelFiltered<K extends keyof FarmPlugin>(\n    hookName: K,\n    include: (plugin: FarmPlugin) => boolean,\n    ...args: any[]\n  ): Promise<boolean> {\n    if (hookName === \"shutdown\" && !this.runtimeShutdownHooksRunning) {\n      await this.closeRuntime(args[0]?.reason);\n      return false;\n    }\n\n    const plugins = this.getSortedPlugins().filter(include);\n\n    // Run selected hooks sequentially for deterministic execution and short-circuiting.\n    const sequentialHooks = new Set<keyof FarmPlugin>([\n      \"ready\",\n      \"shutdown\",\n      \"beforeRequest\",\n      \"afterResponse\",\n      \"beforeApiHandler\",\n      \"afterApiHandler\",\n      \"beforeRouteMatch\",\n      \"afterRouteMatch\",\n      \"beforeRender\",\n      \"afterRender\",\n    ]);\n\n    if (sequentialHooks.has(hookName)) {\n      const shutdownErrors: unknown[] = [];\n      for (const plugin of plugins) {\n        for (const hook of this.getPluginHooks(plugin, hookName)) {\n          // Check if response is already sent (only for beforeRequest)\n          if (hookName === \"beforeRequest\") {\n            const res = args[1];\n            if (res && (res.writableEnded || res[FARM_NODE_RESPONSE_END_PENDING])) {\n              return true;\n            }\n          }\n\n          const hookContext = this.getHookContext(plugin, hookName, args);\n          try {\n            await (hook as any).apply(plugin, [...args, hookContext]);\n          } catch (error) {\n            if (hookName !== \"shutdown\") throw error;\n            shutdownErrors.push(error);\n          }\n\n          // Check again after plugin execution (only for beforeRequest)\n          if (hookName === \"beforeRequest\") {\n            const res = args[1];\n            if (res && res.writableEnded) {\n              return true;\n            }\n          }\n        }\n      }\n      if (hookName === \"shutdown\" && shutdownErrors.length > 0) {\n        throw new FarmRuntimeShutdownError(\"Farm plugin shutdown hooks failed\", shutdownErrors);\n      }\n    } else {\n      // Run other hooks in parallel\n      const promises: Promise<any>[] = [];\n      for (const plugin of plugins) {\n        for (const hook of this.getPluginHooks(plugin, hookName)) {\n          const hookContext = this.getHookContext(plugin, hookName, args);\n          promises.push((hook as any).apply(plugin, [...args, hookContext]));\n        }\n      }\n      await Promise.all(promises);\n    }\n\n    if (hookName === \"init\") this.initialized = true;\n    if (hookName === \"ready\") this.runtimeReady = true;\n\n    return false;\n  }\n\n  updateContext(updates: Partial<FarmPluginContext>) {\n    this.context = {\n      ...this.context,\n      ...updates,\n      requestContext: this.context.requestContext,\n    };\n  }\n}\n\nexport function definePlugin<\n  TState = undefined,\n  TRequestContext extends object = Record<string, never>,\n  TClientState = unknown,\n  TClientPublic = undefined,\n  TIntegrationInstance = unknown,\n  const TRoutes extends PluginRoutes = PluginRoutes,\n>(\n  plugin: FarmPlugin<\n    TState,\n    TRequestContext,\n    TClientState,\n    TClientPublic,\n    TIntegrationInstance,\n    false,\n    TRoutes\n  >,\n): FarmPlugin<\n  TState,\n  TRequestContext,\n  TClientState,\n  TClientPublic,\n  TIntegrationInstance,\n  false,\n  TRoutes\n> {\n  return plugin;\n}\n\nexport namespace definePlugin {\n  /** Bind an integration instance type while preserving inference for plugin state and context. */\n  export function forIntegration<TIntegrationInstance>() {\n    return function defineBoundPlugin<\n      TState = undefined,\n      TRequestContext extends object = Record<string, never>,\n      TClientState = unknown,\n      TClientPublic = undefined,\n    >(\n      plugin: FarmPlugin<\n        TState,\n        TRequestContext,\n        TClientState,\n        TClientPublic,\n        TIntegrationInstance,\n        true\n      >,\n    ): FarmPlugin<\n      TState,\n      TRequestContext,\n      TClientState,\n      TClientPublic,\n      TIntegrationInstance,\n      true\n    > {\n      return plugin;\n    };\n  }\n}\nexport { farmPlugin } from \"./vite\";\n","import type { FarmConfig } from \"./types\";\nimport type { FarmDocsResolvedConfig } from \"./docs/types\";\nimport type { FarmMarkdownResolvedConfig } from \"./markdown\";\nimport { resolveMdxConfig, type FarmMdxResolvedConfig } from \"./app-markdown-config\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig, type FarmWorkflowsResolvedConfig } from \"./workflows\";\nimport { resolveCronConfig, type FarmCronResolvedConfig } from \"./cron\";\nimport { resolveAppPath, fileExists, logger } from \"./utils\";\nimport { initStorage } from \"./storage\";\nimport { configureFarmObservability } from \"./observability\";\nimport { normalizeRouteRules } from \"./route-rules\";\nimport { resolveServerActionsConfig } from \"./server-action-security\";\nimport { resolveFarmServerConfig } from \"./server-http\";\nimport { resolveFarmImageConfig, type ResolvedFarmImageConfig } from \"./image-config\";\nimport { getFarmAppDirectories, getFarmSourceRoots } from \"./layers\";\nimport { RouteManager } from \"./routing/route-manager\";\nimport { ServerRenderer } from \"./server/renderer\";\nimport { findProgrammaticRouteFiles } from \"./routes.server\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n  resolveFarmDevIndicatorsConfig,\n  type ResolvedFarmDevIndicatorsConfig,\n} from \"./dev-indicators\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport {\n  createFarmI18nRuntime,\n  _setDefaultFarmI18nRuntime,\n  type FarmI18nRuntime,\n} from \"./i18n/server\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport { configureFarmCache } from \"./cache\";\nimport { resolveFarmAuthConfig, type ResolvedFarmAuthConfig } from \"./auth-config\";\nimport { resolveFarmPerformanceConfig, type ResolvedFarmPerformanceConfig } from \"./preload\";\nimport { normalizeFarmConfigBasePath } from \"./base-path\";\nimport { resolveFarmSecurityConfig, type ResolvedFarmSecurityConfig } from \"./security\";\nimport { resolveFarmThemeConfig } from \"./theme/config\";\nimport { _setDefaultFarmThemeConfig } from \"./theme/server\";\nimport type { ResolvedFarmThemeConfig } from \"./theme/types\";\nimport { getFarmRendererComponentExtensions, resolveFarmRenderer } from \"./renderer\";\nimport type { FarmRenderer } from \"./renderer\";\nimport { normalizeFarmAPIConfig, type ResolvedFarmAPIConfig } from \"./api/config\";\n\ntype NormalizedFarmConfig = Omit<\n  Required<FarmConfig>,\n  \"api\" | \"devtools\" | \"devIndicators\" | \"images\" | \"i18n\" | \"performance\" | \"security\" | \"theme\"\n> & {\n  api: ResolvedFarmAPIConfig;\n  docs: FarmDocsResolvedConfig;\n  md: FarmMarkdownResolvedConfig;\n  mdx: FarmMdxResolvedConfig;\n  cron: FarmCronResolvedConfig;\n  workflows: FarmWorkflowsResolvedConfig;\n  devtools: ResolvedFarmDevtoolsConfig;\n  devIndicators: ResolvedFarmDevIndicatorsConfig;\n  images: ResolvedFarmImageConfig;\n  i18n: ResolvedFarmI18nConfig;\n  auth: ResolvedFarmAuthConfig;\n  performance: ResolvedFarmPerformanceConfig;\n  security: ResolvedFarmSecurityConfig;\n  theme: ResolvedFarmThemeConfig;\n  renderer: FarmRenderer;\n};\n\nconst defaultDocsConfig: FarmDocsResolvedConfig = {\n  enabled: false,\n  entry: \"/docs\",\n  config: { entry: \"docs\", docsPath: \"/docs\" },\n};\n\nfunction isResolvedDocsConfig(value: FarmConfig[\"docs\"]): value is FarmDocsResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    \"entry\" in value &&\n    \"config\" in value\n  );\n}\n\nexport class FarmApp {\n  private config: NormalizedFarmConfig;\n  private routeManager: RouteManager;\n  private serverRenderer: ServerRenderer;\n  private i18nRuntime: FarmI18nRuntime;\n  private viteServer?: ViteDevServer;\n\n  constructor(config: FarmConfig = {}, viteServer?: ViteDevServer) {\n    this.config = this.normalizeConfig(config);\n    configureFarmObservability(this.config.observability);\n    _setDefaultFarmThemeConfig(this.config.theme);\n    this.i18nRuntime = createFarmI18nRuntime(this.config.i18n);\n    _setDefaultFarmI18nRuntime(this.i18nRuntime);\n    this.viteServer = viteServer;\n    this.routeManager = new RouteManager(this.config, viteServer);\n    this.serverRenderer = new ServerRenderer(\n      this.config,\n      this.routeManager,\n      this.i18nRuntime,\n      this.viteServer,\n    );\n  }\n\n  async initialize(): Promise<void> {\n    // Silent initialization unless verbose mode\n    if (process.env.FARM_VERBOSE) {\n      logger.info(\"Initializing Farm.js application...\");\n    }\n\n    await initStorage(this.config.storage);\n    await configureFarmCache(this.config.cache);\n    await this.i18nRuntime.initialize();\n    await this.serverRenderer.initialize();\n\n    // Verify app directory structure\n    await this.verifyAppStructure();\n\n    // Discover and register routes\n    await this.routeManager.discoverRoutes();\n\n    // Compile hydration and island decisions once during startup. Navigation\n    // requests only read this manifest; HMR invalidates it when route code changes.\n    this.routeManager.generateClientManifest(this.config.root);\n\n    if (process.env.FARM_VERBOSE) {\n      logger.success(\"Farm.js application initialized successfully!\");\n    }\n  }\n\n  getRouteManager(): RouteManager {\n    return this.routeManager;\n  }\n\n  getServerRenderer(): ServerRenderer {\n    return this.serverRenderer;\n  }\n\n  getI18nRuntime(): FarmI18nRuntime {\n    return this.i18nRuntime;\n  }\n\n  getConfig(): NormalizedFarmConfig {\n    return this.config;\n  }\n\n  private normalizeConfig(config: FarmConfig): NormalizedFarmConfig {\n    const root = config.root || process.cwd();\n    const basePath = normalizeFarmConfigBasePath(config.basePath);\n\n    return {\n      root,\n      srcDir: config.srcDir || \"src\",\n      extends: config.extends || [],\n      layers: [...(config.layers || [])],\n      outDir: config.outDir || \"dist\",\n      basePath,\n      trailingSlash: config.trailingSlash ?? false,\n      renderer: resolveFarmRenderer(config.renderer),\n      preset: config.preset ?? \"node-server\",\n      deploy: config.deploy || {},\n      storage: config.storage || {},\n      cache: config.cache || {},\n      auth: isResolvedAuthConfig(config.auth) ? config.auth : resolveFarmAuthConfig(config.auth),\n      integrations: config.integrations || {},\n      plugins: config.plugins || [],\n      migrations: config.migrations || { commands: [] },\n      cron: resolveCronConfig(config.cron),\n      workflows: resolveWorkflowsConfig(config.workflows),\n      api: normalizeFarmAppAPIConfig(config.api),\n      middleware: config.middleware || {},\n      routeRules: normalizeRouteRules(config.routeRules),\n      context: config.context || (() => undefined),\n      server: resolveFarmServerConfig(config.server),\n      serverActions: resolveServerActionsConfig(config.serverActions),\n      security: resolveFarmSecurityConfig(config.security),\n      images: resolveFarmImageConfig(config.images),\n      performance: resolveFarmPerformanceConfig(config.performance),\n      theme: resolveFarmThemeConfig(config.theme, basePath),\n      i18n: isResolvedI18nConfig(config.i18n)\n        ? config.i18n\n        : resolveFarmI18nConfig(config.i18n, {\n            root,\n            mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n            basePath,\n          }),\n      deploymentId: config.deploymentId || \"development\",\n      notFound: config.notFound || {},\n      serverRuntimeConfig: config.serverRuntimeConfig || {},\n      publicRuntimeConfig: config.publicRuntimeConfig || {},\n      docs: isResolvedDocsConfig(config.docs) ? config.docs : defaultDocsConfig,\n      md: resolveMarkdownConfig(config.md),\n      mdx: resolveMdxConfig(config.mdx),\n      observability: config.observability ?? false,\n      telemetry: config.telemetry !== false,\n      devtools: resolveFarmDevtoolsConfig(\n        config.devtools,\n        process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      ),\n      devIndicators: resolveFarmDevIndicatorsConfig(\n        config.devIndicators,\n        process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      ),\n      env: config.env || { server: {}, public: {} },\n      suppressLintOnLink: config.suppressLintOnLink ?? false,\n      experimental: {\n        serverComponents: config.experimental?.serverComponents ?? false,\n        serverActions: config.experimental?.serverActions ?? false,\n        isolatedClientHydration: config.experimental?.isolatedClientHydration ?? \"off\",\n        ppr: config.experimental?.ppr ?? false,\n        ...config.experimental,\n      },\n      agent: config.agent ?? {},\n      vite: config.vite || {},\n    };\n  }\n\n  private async verifyAppStructure(): Promise<void> {\n    const appDirs = getFarmAppDirectories(this.config);\n\n    const hasAppDirectory = (await Promise.all(appDirs.map((appDir) => fileExists(appDir)))).some(\n      Boolean,\n    );\n\n    if (!hasAppDirectory) {\n      const routeFiles = getFarmSourceRoots(this.config).flatMap((source) =>\n        findProgrammaticRouteFiles(source.root, source.srcDir),\n      );\n      if (routeFiles.length > 0) {\n        return;\n      }\n\n      const appDir = resolveAppPath(this.config.root, this.config.srcDir, \"app\");\n      throw new Error(\n        `App directory not found at ${appDir}. ` +\n          \"Please create a src/app directory or extend a Farm layer containing routes.\",\n      );\n    }\n\n    const componentExtensions = getFarmRendererComponentExtensions(this.config.renderer);\n    const rootLayoutPaths = appDirs.flatMap((appDir) =>\n      componentExtensions.map((extension) => path.join(appDir, `layout${extension}`)),\n    );\n\n    const hasRootLayout = await Promise.all(rootLayoutPaths.map((p) => fileExists(p))).then(\n      (results) => results.some(Boolean),\n    );\n\n    if (!hasRootLayout) {\n      logger.warn(\n        `No root layout found. Consider creating src/app/layout${componentExtensions[0]} for consistent page structure.`,\n      );\n    }\n  }\n}\n\nfunction isResolvedI18nConfig(value: FarmConfig[\"i18n\"]): value is ResolvedFarmI18nConfig {\n  return Boolean(value && typeof value === \"object\" && \"enabled\" in value);\n}\n\nfunction isResolvedAuthConfig(value: FarmConfig[\"auth\"]): value is ResolvedFarmAuthConfig {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    \"enabled\" in value &&\n    \"emailAndPassword\" in value &&\n    \"database\" in value,\n  );\n}\n\nfunction normalizeFarmAppAPIConfig(config: FarmConfig[\"api\"]): ResolvedFarmAPIConfig {\n  if (typeof config?.baseURL === \"function\" || typeof config?.basePath === \"function\") {\n    throw new Error(\n      \"Farm API config resolver functions must be processed with resolveConfig() before creating a FarmApp.\",\n    );\n  }\n  return normalizeFarmAPIConfig(config as { baseURL?: string; basePath?: string } | undefined);\n}\n\nexport function createFarmApp(config?: FarmConfig, viteServer?: ViteDevServer): FarmApp {\n  return new FarmApp(config, viteServer);\n}\n","import type {\n  FarmConfig,\n  ParsedRoute,\n  RouteModule,\n  LayoutModule,\n  SSGCollectionResult,\n} from \"../types\";\nimport {\n  parseRoutePath,\n  matchRoute,\n  matchRoutePrefix,\n  resolveAppPath,\n  globFiles,\n  logger,\n  toRootRelativeUrlPath,\n  toViteModuleId,\n} from \"../utils\";\nimport { collectSSGPages, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport type {\n  ProgrammaticPageRoute,\n  ProgrammaticLayoutRoute,\n  ProgrammaticRedirectRoute,\n  ProgrammaticRouteSearchClientOptions,\n} from \"../routes\";\nimport {\n  createProgrammaticRouteModuleId,\n  getProgrammaticRouteSearchClientOptions,\n  parseProgrammaticRoutePath,\n} from \"../routes-shared\";\nimport { loadProgrammaticRouteManifests } from \"../routes.server\";\nimport {\n  createFarmMarkdownRouteModuleFromFile,\n  isFarmMarkdownPageFile,\n  loadFarmMdxComponents,\n  resolveMdxConfig,\n} from \"../app-markdown\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport {\n  enforceFarmIsolatedHydrationRouteBudget,\n  getClientModuleHydrationPlan,\n  getClientModuleMetadata,\n  resolveFarmIsolatedClientHydrationMode,\n  type IsolatedClientBoundaryReference,\n} from \"../utils/client-component\";\nimport { getIntegrationProviders } from \"../integrations\";\nimport type { MetadataImageKind } from \"../metadata\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport type { FarmServerRendererRuntime } from \"../renderer\";\nimport { createFarmRouteRenderPlan, type FarmRouteRenderPlan } from \"../navigation/render-plan\";\nimport { getFarmSourceRoots, type FarmSourceRoot } from \"../layers\";\nimport {\n  inspectStaticMetadataImage,\n  isStaticMetadataImageFile,\n  type StaticMetadataImageInfo,\n} from \"../static-metadata-image\";\nimport {\n  getFarmRouteRuntimeConfig,\n  mergeFarmRouteRuntimeConfigs,\n  normalizeFarmRouteRuntimeConfig,\n  resolveFarmRouteRuleRuntimeConfig,\n  resolveFarmRouteRuntimeConfig,\n  type ResolvedFarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport {\n  localizeFarmHref,\n  localizeFarmPathname,\n  resolveFarmLocalePath,\n  stripFarmLocaleFromPathname,\n} from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { appendFarmRedirectQuery } from \"../redirect-query\";\nimport { createRouteSlotContainerId, parseRouteSlotFile } from \"./route-slots\";\nimport { getFarmRendererComponentExtensions } from \"../renderer\";\nimport type { ApplicationMetadataRouteKind } from \"../metadata-route\";\nimport {\n  AmbiguousRouteError,\n  assertUniqueRouteParameters,\n  compareRouteSpecificity,\n  getRoutePatternShape,\n  type RouteSegmentSpecificity,\n} from \"./specificity\";\n\ninterface RouteEntry {\n  route: ParsedRoute;\n  modulePath: string;\n  markdownSourcePath?: string;\n  pattern: string;\n  source?: \"file\" | \"programmatic\";\n  sourceRoot: string;\n}\n\nexport interface RouteSlotEntry extends RouteEntry {\n  name: string;\n  ownerPattern: string;\n  interception: boolean;\n  fallback: boolean;\n  containerId: string;\n}\n\nexport interface MatchedRouteSlot {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  interception: boolean;\n  fallback: boolean;\n  route: RouteSlotEntry;\n  params: Record<string, string>;\n}\n\nexport interface FarmClientRouteManifest {\n  routes: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries?: true;\n    isolatedBoundaries?: IsolatedClientBoundaryReference[];\n    renderPlan: FarmRouteRenderPlan;\n    suppressedAsyncHydration?: true;\n    search?: ProgrammaticRouteSearchClientOptions;\n    segments: Array<{\n      segment: string;\n      isDynamic: boolean;\n      isCatchAll?: boolean;\n      isOptional?: boolean;\n    }>;\n  }>;\n  layouts: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries?: true;\n    isolatedBoundaries?: IsolatedClientBoundaryReference[];\n  }>;\n  slots: Array<{\n    name: string;\n    ownerPattern: string;\n    pattern: string;\n    modulePath: string;\n    containerId: string;\n    interception: boolean;\n    fallback: boolean;\n    shouldHydrate: boolean;\n    isClientComponent: boolean;\n    segments: RouteEntry[\"route\"][\"segments\"];\n  }>;\n}\n\nexport function shouldSuggestStaticRenderingForI18n(\n  i18n: Pick<ResolvedFarmI18nConfig, \"routing\" | \"detection\"> | undefined,\n): boolean {\n  return (\n    !i18n ||\n    i18n.routing === \"prefix-always\" ||\n    (i18n.routing === \"prefix-except-default\" && i18n.detection.every((signal) => signal === \"url\"))\n  );\n}\n\ninterface MetadataImageEntry extends RouteEntry {\n  kind: MetadataImageKind;\n  fileName: \"opengraph-image\" | \"twitter-image\";\n  sourceType: \"module\" | \"static\";\n  staticInfo?: StaticMetadataImageInfo;\n}\n\nexport interface ApplicationMetadataRouteEntry extends RouteEntry {\n  kind: ApplicationMetadataRouteKind;\n  fileName: \"sitemap\" | \"robots\" | \"manifest\";\n  outputName: \"sitemap.xml\" | \"robots.txt\" | \"manifest.webmanifest\";\n}\n\ninterface RedirectEntry {\n  route: ParsedRoute;\n  pattern: string;\n  definition: ProgrammaticRedirectRoute;\n}\n\nfunction getRouteSpecificity(entry: RouteEntry): RouteSegmentSpecificity[] {\n  return entry.route.segments.map((segment) => {\n    if (!segment.isDynamic) return \"static\";\n    if (!segment.isCatchAll) return \"dynamic\";\n    return segment.isOptional ? \"optional-catch-all\" : \"catch-all\";\n  });\n}\n\nfunction compareRouteEntries(left: RouteEntry, right: RouteEntry): number {\n  return compareRouteSpecificity(getRouteSpecificity(left), getRouteSpecificity(right));\n}\n\n/**\n * Manages route discovery and matching for the Farm.js application\n */\nexport class RouteManager {\n  private config: Required<FarmConfig>;\n  private routes: Map<string, RouteEntry> = new Map();\n  private pageRouteShapes: Map<string, RouteEntry> = new Map();\n  private layouts: Map<string, RouteEntry> = new Map();\n  private routeSlots: Map<string, RouteSlotEntry> = new Map();\n  private loadings: Map<string, RouteEntry> = new Map();\n  private errors: Map<string, RouteEntry> = new Map();\n  private metadataImages: Map<string, MetadataImageEntry> = new Map();\n  private metadataRoutes: Map<string, ApplicationMetadataRouteEntry> = new Map();\n  private redirects: Map<string, RedirectEntry> = new Map();\n  private programmaticPages: Map<string, ProgrammaticPageRoute> = new Map();\n  private programmaticLayouts: Map<string, ProgrammaticLayoutRoute> = new Map();\n  private rendererRuntime?: FarmServerRendererRuntime;\n  private viteServer?: ViteDevServer;\n  private clientManifestCache?: {\n    projectRoot: string;\n    manifest: FarmClientRouteManifest;\n    isolatedClientBoundaryModules: ReadonlySet<string>;\n  };\n\n  constructor(config: Required<FarmConfig>, viteServer?: ViteDevServer) {\n    this.config = config;\n    this.viteServer = viteServer;\n  }\n\n  setRendererRuntime(rendererRuntime: FarmServerRendererRuntime): void {\n    this.rendererRuntime = rendererRuntime;\n  }\n\n  /**\n   * Discover all routes in the app directory\n   */\n  async discoverRoutes(): Promise<void> {\n    this.invalidateClientManifest();\n    this.routes.clear();\n    this.pageRouteShapes.clear();\n    this.layouts.clear();\n    this.routeSlots.clear();\n    this.loadings.clear();\n    this.errors.clear();\n    this.metadataImages.clear();\n    this.metadataRoutes.clear();\n    this.redirects.clear();\n    this.programmaticPages.clear();\n    this.programmaticLayouts.clear();\n\n    for (const source of getFarmSourceRoots(this.config)) {\n      await this.discoverFileRoutes(source);\n      await this.discoverProgrammaticRoutes(source);\n    }\n\n    for (const slot of this.routeSlots.values()) {\n      if (slot.interception && !this.pageRouteShapes.has(getRoutePatternShape(slot.pattern))) {\n        throw new AmbiguousRouteError(\n          `Intercepting route slot \"${slot.name}\" targets \"${slot.pattern}\", but no canonical page exists for that URL`,\n        );\n      }\n    }\n\n    this.routes = new Map(\n      Array.from(this.routes.entries()).sort(([, left], [, right]) =>\n        compareRouteEntries(left, right),\n      ),\n    );\n    this.metadataRoutes = new Map(\n      Array.from(this.metadataRoutes.entries()).sort(([, left], [, right]) =>\n        compareRouteEntries(left, right),\n      ),\n    );\n\n    // Silent discovery - only log if verbose mode enabled\n    if (process.env.FARM_VERBOSE) {\n      logger.info(\n        `Discovered ${this.routes.size} pages, ${this.layouts.size} layouts, and ${this.metadataRoutes.size} metadata routes`,\n      );\n    }\n\n    if (process.env.FARM_VERBOSE) {\n      this.logRoutes();\n    }\n  }\n\n  /**\n   * Find matching route for a given URL path\n   */\n  matchRoute(\n    pathname: string,\n    options: {\n      interceptFrom?: string;\n    } = {},\n  ): {\n    route: RouteEntry | null;\n    params: Record<string, string>;\n    layouts: RouteEntry[];\n    slots: MatchedRouteSlot[];\n  } {\n    // Remove trailing slash except for root\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    // Find matching page route\n    let matchedRoute: RouteEntry | null = null;\n    let params: Record<string, string> = {};\n\n    for (const routeEntry of this.routes.values()) {\n      const match = matchRoute(normalizedPath, routeEntry.route.segments);\n      if (match.matches) {\n        matchedRoute = routeEntry;\n        params = match.params;\n        break;\n      }\n    }\n\n    // Find all matching layouts (from root to specific)\n    const layouts = this.findMatchingLayouts(normalizedPath);\n    const slots = this.findMatchingRouteSlots(normalizedPath, options.interceptFrom);\n\n    return {\n      route: matchedRoute,\n      params,\n      layouts,\n      slots,\n    };\n  }\n\n  /**\n   * Get all registered routes\n   */\n  getRoutes(): Map<string, RouteEntry> {\n    return new Map(this.routes);\n  }\n\n  /**\n   * Get all registered layouts\n   */\n  getLayouts(): Map<string, RouteEntry> {\n    return new Map(this.layouts);\n  }\n\n  getRouteSlots(): Map<string, RouteSlotEntry> {\n    return new Map(this.routeSlots);\n  }\n\n  /** Resolve route rules, inherited layouts, and the page export in precedence order. */\n  async resolveRouteRuntimeConfig(pattern: string): Promise<ResolvedFarmRouteRuntimeConfig> {\n    const routeEntry = this.routes.get(pattern);\n    if (!routeEntry) {\n      throw new Error(`Cannot resolve runtime configuration for unknown route \"${pattern}\"`);\n    }\n\n    const inherited = resolveFarmRouteRuleRuntimeConfig(pattern, this.config.routeRules);\n    const layouts = this.findMatchingLayouts(pattern);\n    const layoutConfigs = [];\n\n    for (const layout of layouts) {\n      const layoutModule = await this.loadLayoutModule(layout.modulePath);\n      layoutConfigs.push(\n        normalizeFarmRouteRuntimeConfig(\n          getFarmRouteRuntimeConfig(layoutModule),\n          `Layout \"${layout.pattern}\"`,\n        ),\n      );\n    }\n\n    const routeModule = await this.loadRouteModule(routeEntry.modulePath);\n    const routeConfig = normalizeFarmRouteRuntimeConfig(\n      getFarmRouteRuntimeConfig(routeModule),\n      `Route \"${pattern}\"`,\n    );\n\n    return resolveFarmRouteRuntimeConfig(\n      mergeFarmRouteRuntimeConfigs(inherited, ...layoutConfigs, routeConfig),\n      `Route \"${pattern}\"`,\n    );\n  }\n\n  /**\n   * Get all route-level loading boundaries.\n   */\n  getLoadings(): Map<string, RouteEntry> {\n    return new Map(this.loadings);\n  }\n\n  /**\n   * Get all route-level error boundaries.\n   */\n  getErrors(): Map<string, RouteEntry> {\n    return new Map(this.errors);\n  }\n\n  getMetadataImages(): Map<string, MetadataImageEntry> {\n    return new Map(this.metadataImages);\n  }\n\n  getMetadataRoutes(): Map<string, ApplicationMetadataRouteEntry> {\n    return new Map(this.metadataRoutes);\n  }\n\n  getRedirects(): ProgrammaticRedirectRoute[] {\n    return Array.from(this.redirects.values()).map((entry) => entry.definition);\n  }\n\n  matchRedirect(\n    pathname: string,\n    search = \"\",\n  ): {\n    redirect: ProgrammaticRedirectRoute;\n    destination: string;\n    statusCode: number;\n    params: Record<string, string>;\n  } | null {\n    const i18n = this.getI18nConfig();\n    const localeMatch = i18n ? resolveFarmLocalePath(pathname, i18n) : undefined;\n    const routePathname = localeMatch?.pathname || pathname;\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n\n    for (const redirectEntry of this.redirects.values()) {\n      const match = matchRoute(normalizedPath, redirectEntry.route.segments);\n      if (!match.matches) continue;\n\n      const statusCode =\n        redirectEntry.definition.statusCode || (redirectEntry.definition.permanent ? 308 : 307);\n\n      return {\n        redirect: redirectEntry.definition,\n        destination: appendFarmRedirectQuery(\n          this.localizeRedirectDestination(\n            interpolateRedirectDestination(redirectEntry.definition.destination, match.params),\n            localeMatch?.locale,\n          ),\n          search,\n        ),\n        statusCode,\n        params: match.params,\n      };\n    }\n\n    return null;\n  }\n\n  /**\n   * Return the nearest matching loading boundary for a pathname.\n   */\n  getMatchingLoading(pathname: string): RouteEntry | null {\n    return this.findNearestBoundary(this.toRoutePathname(pathname), this.loadings);\n  }\n\n  /**\n   * Return the nearest matching error boundary for a pathname.\n   */\n  getMatchingError(pathname: string): RouteEntry | null {\n    return this.findNearestBoundary(this.toRoutePathname(pathname), this.errors);\n  }\n\n  matchMetadataImage(pathname: string): {\n    image: MetadataImageEntry;\n    params: Record<string, string>;\n    pagePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const suffix = getMetadataImageSuffix(normalizedPath);\n    if (!suffix) return null;\n\n    const pagePath = normalizedPath.slice(0, -suffix.fileName.length - 1) || \"/\";\n\n    for (const imageEntry of this.metadataImages.values()) {\n      if (imageEntry.kind !== suffix.kind) continue;\n\n      const match = matchRoute(pagePath, imageEntry.route.segments);\n      if (!match.matches) continue;\n\n      return {\n        image: imageEntry,\n        params: match.params,\n        pagePath,\n      };\n    }\n\n    return null;\n  }\n\n  matchMetadataRoute(pathname: string): {\n    metadata: ApplicationMetadataRouteEntry;\n    params: Record<string, string>;\n    routePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const suffix = getApplicationMetadataRouteSuffix(normalizedPath);\n    if (!suffix) return null;\n\n    const routePath = normalizedPath.slice(0, -suffix.outputName.length - 1) || \"/\";\n    for (const metadata of this.metadataRoutes.values()) {\n      if (metadata.kind !== suffix.kind) continue;\n      const match = matchRoute(routePath, metadata.route.segments);\n      if (!match.matches) continue;\n      return { metadata, params: match.params, routePath };\n    }\n\n    return null;\n  }\n\n  getMatchingMetadataRoute(\n    pathname: string,\n    kind: ApplicationMetadataRouteKind,\n  ): {\n    metadata: ApplicationMetadataRouteEntry;\n    params: Record<string, string>;\n    routePath: string;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n    let bestMatch: {\n      metadata: ApplicationMetadataRouteEntry;\n      params: Record<string, string>;\n      routePath: string;\n    } | null = null;\n\n    for (const metadata of this.metadataRoutes.values()) {\n      if (metadata.kind !== kind || metadata.route.segments.length > pathSegments.length) continue;\n      const routePath =\n        metadata.route.segments.length === 0\n          ? \"/\"\n          : `/${pathSegments.slice(0, metadata.route.segments.length).join(\"/\")}`;\n      const match = matchRoute(routePath, metadata.route.segments);\n      if (!match.matches) continue;\n      if (!bestMatch || metadata.route.segments.length > bestMatch.metadata.route.segments.length) {\n        bestMatch = { metadata, params: match.params, routePath };\n      }\n    }\n\n    return bestMatch;\n  }\n\n  resolveMetadataRoutePath(\n    metadata: ApplicationMetadataRouteEntry,\n    params: Record<string, string> = {},\n  ): string {\n    const routePath = routeSegmentsToPath(metadata.route.segments, params);\n    return routePath === \"/\" ? `/${metadata.outputName}` : `${routePath}/${metadata.outputName}`;\n  }\n\n  getMatchingMetadataImage(\n    pathname: string,\n    kind: MetadataImageKind,\n  ): {\n    image: MetadataImageEntry;\n    params: Record<string, string>;\n  } | null {\n    const routePathname = this.toRoutePathname(pathname);\n    const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n    const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n    let bestMatch: {\n      image: MetadataImageEntry;\n      params: Record<string, string>;\n    } | null = null;\n\n    for (const imageEntry of this.metadataImages.values()) {\n      if (imageEntry.kind !== kind) continue;\n      if (imageEntry.route.segments.length > pathSegments.length) continue;\n\n      const candidatePath =\n        imageEntry.route.segments.length === 0\n          ? \"/\"\n          : `/${pathSegments.slice(0, imageEntry.route.segments.length).join(\"/\")}`;\n      const match = matchRoute(candidatePath, imageEntry.route.segments);\n      if (!match.matches) continue;\n\n      if (!bestMatch || imageEntry.route.segments.length > bestMatch.image.route.segments.length) {\n        bestMatch = {\n          image: imageEntry,\n          params: match.params,\n        };\n      }\n    }\n\n    return bestMatch;\n  }\n\n  resolveMetadataImagePath(image: MetadataImageEntry, params: Record<string, string> = {}): string {\n    const pagePath = routeSegmentsToPath(image.route.segments, params);\n    const imagePath = pagePath === \"/\" ? `/${image.fileName}` : `${pagePath}/${image.fileName}`;\n    return image.staticInfo ? `${imagePath}?v=${image.staticInfo.hash}` : imagePath;\n  }\n\n  /**\n   * Generate the compiled route decisions consumed by SPA navigation.\n   * Requests still fetch route data, but never inspect component source.\n   */\n  generateClientManifest(projectRoot: string = this.config.root): FarmClientRouteManifest {\n    const normalizedProjectRoot = path.resolve(projectRoot);\n    if (this.clientManifestCache?.projectRoot === normalizedProjectRoot) {\n      return this.clientManifestCache.manifest;\n    }\n\n    const toUrlPath = (absolutePath: string) => {\n      const rootRelative = toRootRelativeUrlPath(absolutePath, normalizedProjectRoot);\n      if (rootRelative !== undefined) return rootRelative;\n      if (path.isAbsolute(absolutePath)) {\n        const normalized = absolutePath.replace(/\\\\/g, \"/\");\n        return normalized.startsWith(\"/\") ? `/@fs${normalized}` : `/@fs/${normalized}`;\n      }\n      return absolutePath;\n    };\n\n    const integrationProviders = getIntegrationProviders(this.config.integrations).filter(\n      (provider) => provider.component || provider.type === \"clerk\",\n    );\n    const unsupportedIntegrationProvider = integrationProviders.find(\n      (provider) => provider.supportsIsolatedHydration !== true,\n    );\n    if (\n      this.config.experimental?.isolatedClientHydration === \"enabled\" &&\n      this.config.experimental?.serverComponents !== true &&\n      unsupportedIntegrationProvider\n    ) {\n      logger.warn(\n        `[Farm.js] isolated hydration kept route-wide because integration provider \"${unsupportedIntegrationProvider.name}\" does not declare supportsIsolatedHydration: true.`,\n      );\n    }\n    const isolatedMode = resolveFarmIsolatedClientHydrationMode(\n      this.config.experimental?.isolatedClientHydration,\n      {\n        serverComponents: this.config.experimental?.serverComponents === true,\n        hasUnsupportedIntegrationProvider: Boolean(unsupportedIntegrationProvider),\n      },\n    );\n    const layoutEntries = Array.from(this.layouts.values()).map((entry) => ({\n      entry,\n      metadata: getClientModuleHydrationPlan(entry.modulePath, normalizedProjectRoot, isolatedMode),\n    }));\n\n    const routeEntries = Array.from(this.routes.values()).map((entry) => ({\n      entry,\n      metadata: getClientModuleHydrationPlan(entry.modulePath, normalizedProjectRoot, isolatedMode),\n    }));\n\n    enforceFarmIsolatedHydrationRouteBudget(\n      layoutEntries.map(({ entry, metadata }) => ({\n        pattern: entry.pattern,\n        depth: entry.route.segments.length,\n        metadata,\n      })),\n      routeEntries.map(({ entry, metadata }) => ({\n        pattern: entry.pattern,\n        depth: entry.route.segments.length,\n        metadata,\n      })),\n      (layoutPattern, routePattern) =>\n        layoutPattern === \"/\" ||\n        routePattern === layoutPattern ||\n        routePattern.startsWith(`${layoutPattern.replace(/\\/$/, \"\")}/`),\n    );\n\n    for (const { entry, metadata } of [...layoutEntries, ...routeEntries]) {\n      if (!metadata.costGuardExceeded) continue;\n      logger.warn(\n        `[Farm.js] isolated hydration kept route-wide for ${entry.modulePath}: ${metadata.fallbackReason}.`,\n      );\n    }\n    if (isolatedMode === \"analyze\") {\n      for (const { entry, metadata } of [...layoutEntries, ...routeEntries]) {\n        if (!metadata.isolatedHydrationEligible) continue;\n        logger.info(\n          `[Farm.js] isolated hydration analysis: ${entry.modulePath} can keep ${metadata.isolatedBoundaries.length} client ${metadata.isolatedBoundaries.length === 1 ? \"boundary\" : \"boundaries\"} while excluding its server owner from the browser graph.`,\n        );\n      }\n    }\n\n    const routes = routeEntries.map(({ entry, metadata }) => {\n      const programmaticPage = this.programmaticPages.get(entry.modulePath);\n      const layoutShouldHydrate = layoutEntries.some(\n        ({ entry: layout, metadata: layoutMetadata }) =>\n          layoutMetadata.shouldHydrate &&\n          (layout.pattern === \"/\" ||\n            entry.pattern === layout.pattern ||\n            entry.pattern.startsWith(`${layout.pattern.replace(/\\/$/, \"\")}/`)),\n      );\n      return {\n        pattern: entry.pattern,\n        modulePath: toUrlPath(entry.modulePath),\n        shouldHydrate: metadata.shouldHydrate,\n        isClientComponent: metadata.isClientComponent,\n        islandStrategy: metadata.islandStrategy,\n        ...(metadata.hasIsolatedClientBoundaries\n          ? {\n              hasIsolatedClientBoundaries: true as const,\n              isolatedBoundaries: metadata.isolatedBoundaries.map((boundary) => ({\n                ...boundary,\n                modulePath: toUrlPath(boundary.modulePath),\n              })),\n            }\n          : {}),\n        renderPlan: createFarmRouteRenderPlan({\n          pageShouldHydrate: metadata.shouldHydrate,\n          layoutShouldHydrate,\n          islandStrategy: metadata.islandStrategy,\n        }),\n        suppressedAsyncHydration: metadata.suppressedAsyncHydration,\n        search: getProgrammaticRouteSearchClientOptions(programmaticPage?.search),\n        segments: entry.route.segments.map((seg) => ({\n          segment: seg.segment,\n          isDynamic: seg.isDynamic,\n          isCatchAll: seg.isCatchAll,\n          isOptional: seg.isOptional,\n        })),\n      };\n    });\n\n    const layouts = layoutEntries.map(({ entry, metadata }) => ({\n      pattern: entry.pattern,\n      modulePath: toUrlPath(entry.modulePath),\n      shouldHydrate: metadata.shouldHydrate,\n      isClientComponent: metadata.isClientComponent,\n      islandStrategy: metadata.islandStrategy,\n      ...(metadata.hasIsolatedClientBoundaries\n        ? {\n            hasIsolatedClientBoundaries: true as const,\n            isolatedBoundaries: metadata.isolatedBoundaries.map((boundary) => ({\n              ...boundary,\n              modulePath: toUrlPath(boundary.modulePath),\n            })),\n          }\n        : {}),\n    }));\n\n    const slots = Array.from(this.routeSlots.values()).map((entry) => {\n      const metadata = getClientModuleMetadata(entry.modulePath, normalizedProjectRoot);\n      return {\n        name: entry.name,\n        ownerPattern: entry.ownerPattern,\n        pattern: entry.pattern,\n        modulePath: toUrlPath(entry.modulePath),\n        containerId: entry.containerId,\n        interception: entry.interception,\n        fallback: entry.fallback,\n        shouldHydrate: metadata.shouldHydrate,\n        isClientComponent: metadata.isClientComponent,\n        segments: entry.route.segments,\n      };\n    });\n\n    const isolatedClientBoundaryModules = new Set<string>();\n    for (const { metadata } of [...layoutEntries, ...routeEntries]) {\n      if (!metadata.hasIsolatedClientBoundaries) continue;\n      for (const boundary of metadata.isolatedBoundaries) {\n        isolatedClientBoundaryModules.add(path.resolve(boundary.modulePath));\n      }\n    }\n\n    const manifest = { routes, layouts, slots };\n    this.clientManifestCache = {\n      projectRoot: normalizedProjectRoot,\n      manifest,\n      isolatedClientBoundaryModules,\n    };\n    return manifest;\n  }\n\n  /** @internal Client modules selected by the compiled hydration ownership plan. */\n  getIsolatedClientBoundaryModules(projectRoot: string = this.config.root): ReadonlySet<string> {\n    const normalizedProjectRoot = path.resolve(projectRoot);\n    this.generateClientManifest(normalizedProjectRoot);\n    return this.clientManifestCache?.isolatedClientBoundaryModules ?? new Set();\n  }\n\n  /**\n   * Invalidate build-time route metadata after a page or layout changes in dev.\n   * Navigation requests reuse the cached manifest and never inspect source files.\n   */\n  invalidateClientManifest(): void {\n    this.clientManifestCache = undefined;\n  }\n\n  /**\n   * Load a route module dynamically\n   */\n  async loadRouteModule(modulePath: string): Promise<RouteModule> {\n    try {\n      const programmaticPage = this.programmaticPages.get(modulePath);\n      if (programmaticPage) {\n        const { createRouteModuleFromProgrammaticPage } = await import(\"../routes\");\n        return createRouteModuleFromProgrammaticPage(programmaticPage, this.rendererRuntime);\n      }\n\n      if (isFarmMarkdownPageFile(modulePath)) {\n        const mdxConfig = resolveMdxConfig(this.config.mdx);\n        const components = await loadFarmMdxComponents(mdxConfig, {\n          root: this.config.root,\n          loadModule: this.viteServer\n            ? (componentModulePath) => this.viteServer!.ssrLoadModule(componentModulePath)\n            : undefined,\n        });\n        return await createFarmMarkdownRouteModuleFromFile(modulePath, {\n          components,\n          config: mdxConfig,\n        });\n      }\n\n      if (this.viteServer) {\n        const module = await this.viteServer.ssrLoadModule(modulePath);\n        return module as RouteModule;\n      } else {\n        const module = await import(/* @vite-ignore */ modulePath);\n        return module as RouteModule;\n      }\n    } catch (error) {\n      logger.error(`Failed to load route module: ${modulePath}`);\n      throw error;\n    }\n  }\n\n  /**\n   * Load a layout module dynamically\n   */\n  async loadLayoutModule(modulePath: string): Promise<LayoutModule> {\n    try {\n      const programmaticLayout = this.programmaticLayouts.get(modulePath);\n      if (programmaticLayout) {\n        const { createLayoutModuleFromProgrammaticLayout } = await import(\"../routes\");\n        return createLayoutModuleFromProgrammaticLayout(programmaticLayout) as LayoutModule;\n      }\n\n      if (this.viteServer) {\n        const module = await this.viteServer.ssrLoadModule(modulePath);\n        return module as LayoutModule;\n      } else {\n        const module = await import(/* @vite-ignore */ modulePath);\n        return module as LayoutModule;\n      }\n    } catch (error) {\n      logger.error(`Failed to load layout module: ${modulePath}`);\n      throw error;\n    }\n  }\n\n  /**\n   * Create a route pattern from parsed route\n   */\n  private createRoutePattern(route: ParsedRoute): string {\n    if (route.segments.length === 0) return \"/\";\n\n    return (\n      \"/\" +\n      route.segments\n        .map((segment) => {\n          if (!segment.isDynamic) return segment.segment;\n\n          if (segment.isCatchAll) {\n            return segment.isOptional ? `[[...${segment.segment}]]` : `[...${segment.segment}]`;\n          }\n\n          return `[${segment.segment}]`;\n        })\n        .join(\"/\")\n    );\n  }\n\n  private registerPageRoute(entry: RouteEntry): void {\n    assertUniqueRouteParameters(entry.pattern);\n    const shape = getRoutePatternShape(entry.pattern);\n    const existing = this.pageRouteShapes.get(shape);\n\n    if (existing && existing.pattern !== entry.pattern) {\n      if (existing.sourceRoot === entry.sourceRoot) {\n        throw new Error(\n          `Ambiguous page routes \"${existing.pattern}\" and \"${entry.pattern}\" match the same URLs. Found ${existing.modulePath} and ${entry.modulePath}. Keep only one route for this URL shape.`,\n        );\n      }\n      this.routes.delete(existing.pattern);\n    }\n\n    this.routes.set(entry.pattern, entry);\n    this.pageRouteShapes.set(shape, entry);\n  }\n\n  private async discoverFileRoutes(source: FarmSourceRoot): Promise<void> {\n    const appDir = resolveAppPath(source.root, source.srcDir, \"app\");\n    const componentExtensions = getFarmRendererComponentExtensions(this.config.renderer).map(\n      (extension) => extension.slice(1),\n    );\n    const componentGlob = componentExtensions.join(\",\");\n    const pageFiles = await safeGlobFiles(`**/page.{${componentGlob},md,mdx}`, appDir);\n    const slotDefaultFiles = await safeGlobFiles(`**/@*/**/default.{${componentGlob}}`, appDir);\n    const layoutFiles = await safeGlobFiles(`**/layout.{${componentGlob}}`, appDir);\n    const loadingFiles = await safeGlobFiles(`**/loading.{${componentGlob}}`, appDir);\n    const errorFiles = await safeGlobFiles(`**/error.{${componentGlob}}`, appDir);\n    const metadataImageFiles = await safeGlobFiles(\n      `**/{opengraph-image,twitter-image}.{${componentGlob},png,jpg,jpeg,gif,webp}`,\n      appDir,\n    );\n    const metadataRouteFiles = await safeGlobFiles(\"**/{sitemap,robots,manifest}.{ts,js}\", appDir);\n\n    const canonicalPageGroups = new Map<\n      string,\n      {\n        route: ParsedRoute;\n        files: string[];\n      }\n    >();\n    for (const file of pageFiles.filter((candidate) => parseRouteSlotFile(candidate) === null)) {\n      const route = parseRoutePath(file);\n      const pattern = this.createRoutePattern(route);\n      const group = canonicalPageGroups.get(pattern);\n      if (group) {\n        group.files.push(file);\n      } else {\n        canonicalPageGroups.set(pattern, {\n          route,\n          files: [file],\n        });\n      }\n    }\n\n    for (const [pattern, group] of canonicalPageGroups) {\n      const componentFiles = group.files.filter((file) => !isFarmMarkdownPageFile(file));\n      const markdownFiles = group.files.filter(isFarmMarkdownPageFile);\n      if (componentFiles.length > 1) {\n        throw new Error(\n          `Duplicate page route \"${pattern}\". Found ${componentFiles\n            .map((file) => path.join(appDir, file))\n            .join(\" and \")}.`,\n        );\n      }\n      if (markdownFiles.length > 1) {\n        throw new Error(\n          `Duplicate markdown representation for page route \"${pattern}\". Found ${markdownFiles\n            .map((file) => path.join(appDir, file))\n            .join(\" and \")}.`,\n        );\n      }\n\n      const componentFile = componentFiles[0];\n      const markdownFile = markdownFiles[0];\n      const primaryFile = componentFile || markdownFile;\n      if (!primaryFile) continue;\n\n      const modulePath = path.join(appDir, primaryFile);\n      const existing = this.routes.get(pattern);\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate page route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n        );\n      }\n      this.registerPageRoute({\n        route: group.route,\n        modulePath,\n        ...(markdownFile\n          ? {\n              markdownSourcePath: path.join(appDir, markdownFile),\n            }\n          : {}),\n        pattern,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n\n    for (const [kind, files, target] of [\n      [\"layout\", layoutFiles, this.layouts],\n      [\"loading\", loadingFiles, this.loadings],\n      [\"error\", errorFiles, this.errors],\n    ] as const) {\n      for (const file of files) {\n        const route = parseRoutePath(file);\n        const modulePath = path.join(appDir, file);\n        const pattern = this.createRoutePattern(route);\n        const existing = target.get(pattern);\n        if (existing?.sourceRoot === source.root) {\n          throw new Error(\n            `Duplicate ${kind} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n          );\n        }\n        target.set(pattern, {\n          route,\n          modulePath,\n          pattern,\n          source: \"file\",\n          sourceRoot: source.root,\n        });\n      }\n    }\n\n    for (const file of [...pageFiles, ...slotDefaultFiles]) {\n      const slot = parseRouteSlotFile(file);\n      if (!slot) continue;\n\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(slot.route);\n      const ownerPattern = this.createRoutePattern(slot.ownerRoute);\n      const key = `${ownerPattern}:${slot.name}:${slot.interception ? \"intercept\" : \"slot\"}:${\n        slot.fallback ? \"default\" : pattern\n      }`;\n      const existing = this.routeSlots.get(key);\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate route slot \"${slot.name}\" for \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n        );\n      }\n\n      this.routeSlots.set(key, {\n        route: slot.route,\n        modulePath,\n        pattern,\n        source: \"file\",\n        sourceRoot: source.root,\n        name: slot.name,\n        ownerPattern,\n        interception: slot.interception,\n        fallback: slot.fallback,\n        containerId: createRouteSlotContainerId(slot.name, ownerPattern),\n      });\n    }\n\n    for (const file of metadataImageFiles) {\n      const fileBase = path.basename(file, path.extname(file));\n      const kind: MetadataImageKind = fileBase === \"twitter-image\" ? \"twitter\" : \"opengraph\";\n      const fileName = kind === \"twitter\" ? \"twitter-image\" : \"opengraph-image\";\n      const route = parseRoutePath(file);\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(route);\n      const key = `${kind}:${pattern}`;\n      const existing = this.metadataImages.get(key);\n      const sourceType = isStaticMetadataImageFile(file) ? \"static\" : \"module\";\n\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate ${fileName} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}. Keep only one static image or module per route segment.`,\n        );\n      }\n\n      const staticInfo =\n        sourceType === \"static\" ? await inspectStaticMetadataImage(modulePath) : undefined;\n\n      this.metadataImages.set(key, {\n        route,\n        modulePath,\n        pattern,\n        kind,\n        fileName,\n        sourceType,\n        staticInfo,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n\n    for (const file of metadataRouteFiles) {\n      const descriptor = getApplicationMetadataRouteDescriptor(\n        path.basename(file, path.extname(file)),\n      );\n      if (!descriptor) continue;\n      const route = parseRoutePath(file);\n      const modulePath = path.join(appDir, file);\n      const pattern = this.createRoutePattern(route);\n      const key = `${descriptor.kind}:${pattern}`;\n      const existing = this.metadataRoutes.get(key);\n\n      if (existing?.sourceRoot === source.root) {\n        throw new Error(\n          `Duplicate ${descriptor.fileName} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}. Keep only one .ts or .js metadata route per segment.`,\n        );\n      }\n\n      this.metadataRoutes.set(key, {\n        route,\n        modulePath,\n        pattern,\n        ...descriptor,\n        source: \"file\",\n        sourceRoot: source.root,\n      });\n    }\n  }\n\n  private async discoverProgrammaticRoutes(source: FarmSourceRoot): Promise<void> {\n    const manifests = await loadProgrammaticRouteManifests({\n      root: source.root,\n      srcDir: source.srcDir,\n      loadModule: (filePath) => this.loadProgrammaticRoutesModule(filePath),\n    });\n\n    for (const { filePath, manifest } of manifests) {\n      for (const definition of manifest.routes) {\n        if (definition.kind === \"page\") {\n          const route = parseProgrammaticRoutePath(definition.path, \"page\");\n          const pattern = this.createRoutePattern(route);\n          const existing = this.routes.get(pattern);\n\n          if (existing?.sourceRoot === source.root) {\n            throw new Error(\n              `Duplicate page route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n            );\n          }\n\n          const modulePath = createProgrammaticRouteModuleId(filePath, \"page\", definition.path);\n          this.programmaticPages.set(modulePath, definition);\n          this.registerPageRoute({\n            route,\n            modulePath,\n            pattern,\n            source: \"programmatic\",\n            sourceRoot: source.root,\n          });\n        }\n\n        if (definition.kind === \"layout\") {\n          const route = parseProgrammaticRoutePath(definition.path, \"layout\");\n          const pattern = this.createRoutePattern(route);\n          const existing = this.layouts.get(pattern);\n          if (existing?.sourceRoot === source.root) {\n            throw new Error(\n              `Duplicate layout route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n            );\n          }\n          const modulePath = createProgrammaticRouteModuleId(filePath, \"layout\", definition.path);\n          this.programmaticLayouts.set(modulePath, definition);\n          this.layouts.set(pattern, {\n            route,\n            modulePath,\n            pattern,\n            source: \"programmatic\",\n            sourceRoot: source.root,\n          });\n        }\n\n        if (definition.kind === \"redirect\") {\n          const route = parseProgrammaticRoutePath(definition.source, \"page\");\n          const pattern = this.createRoutePattern(route);\n          this.redirects.set(pattern, {\n            route,\n            pattern,\n            definition,\n          });\n        }\n      }\n    }\n  }\n\n  private async loadProgrammaticRoutesModule(filePath: string): Promise<Record<string, any>> {\n    if (this.viteServer) {\n      const viteRoot = this.viteServer.config?.root || this.config.root || process.cwd();\n      return await this.viteServer.ssrLoadModule(toViteModuleId(filePath, viteRoot));\n    }\n\n    const fileUrl = `file://${filePath}`;\n    return await import(/* @vite-ignore */ fileUrl);\n  }\n\n  /**\n   * Find all layouts that should wrap a given path\n   */\n  private findMatchingLayouts(pathname: string): RouteEntry[] {\n    const matchingLayouts: RouteEntry[] = [];\n\n    const sortedLayouts = Array.from(this.layouts.values()).sort((a, b) => {\n      return a.route.segments.length - b.route.segments.length;\n    });\n\n    for (const layoutEntry of sortedLayouts) {\n      if (matchRoutePrefix(pathname, layoutEntry.route.segments)) {\n        matchingLayouts.push(layoutEntry);\n      }\n    }\n\n    return matchingLayouts;\n  }\n\n  private findMatchingRouteSlots(pathname: string, interceptFrom?: string): MatchedRouteSlot[] {\n    const groups = new Map<string, RouteSlotEntry[]>();\n    for (const entry of this.routeSlots.values()) {\n      if (!this.matchesRoutePrefix(pathname, entry.ownerPattern)) continue;\n      const key = `${entry.ownerPattern}:${entry.name}`;\n      const entries = groups.get(key) ?? [];\n      entries.push(entry);\n      groups.set(key, entries);\n    }\n\n    const normalizedFrom = interceptFrom\n      ? this.toRoutePathname(new URL(interceptFrom, \"http://farm.local\").pathname)\n      : undefined;\n    const matches: MatchedRouteSlot[] = [];\n\n    for (const entries of groups.values()) {\n      const candidates = entries\n        .filter((entry) => !entry.fallback)\n        .filter(\n          (entry) =>\n            !entry.interception ||\n            (normalizedFrom !== undefined &&\n              this.matchesRoutePrefix(normalizedFrom, entry.ownerPattern)),\n        )\n        .map((entry) => ({\n          entry,\n          match: matchRoute(pathname, entry.route.segments),\n        }))\n        .filter((candidate) => candidate.match.matches)\n        .sort((left, right) => {\n          if (left.entry.interception !== right.entry.interception) {\n            return left.entry.interception ? -1 : 1;\n          }\n          return compareRouteEntries(left.entry, right.entry);\n        });\n\n      const selected = candidates[0];\n      if (selected) {\n        matches.push({\n          name: selected.entry.name,\n          ownerPattern: selected.entry.ownerPattern,\n          containerId: selected.entry.containerId,\n          interception: selected.entry.interception,\n          fallback: false,\n          route: selected.entry,\n          params: selected.match.params,\n        });\n        continue;\n      }\n\n      const fallback = entries.find((entry) => entry.fallback);\n      if (fallback) {\n        matches.push({\n          name: fallback.name,\n          ownerPattern: fallback.ownerPattern,\n          containerId: fallback.containerId,\n          interception: false,\n          fallback: true,\n          route: fallback,\n          params: {},\n        });\n      }\n    }\n\n    return matches.sort((left, right) => {\n      const ownerDifference = left.route.route.segments.length - right.route.route.segments.length;\n      return ownerDifference || left.name.localeCompare(right.name);\n    });\n  }\n\n  private matchesRoutePrefix(pathname: string, pattern: string): boolean {\n    if (pattern === \"/\") return true;\n    const patternSegments = parseRoutePath(`${pattern}/page.tsx`).segments;\n    return matchRoutePrefix(pathname, patternSegments);\n  }\n\n  private findNearestBoundary(\n    pathname: string,\n    boundaries: Map<string, RouteEntry>,\n  ): RouteEntry | null {\n    const normalizedPath = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n    let bestMatch: RouteEntry | null = null;\n\n    for (const boundaryEntry of boundaries.values()) {\n      if (!matchRoutePrefix(normalizedPath, boundaryEntry.route.segments)) continue;\n\n      if (!bestMatch || boundaryEntry.route.segments.length > bestMatch.route.segments.length) {\n        bestMatch = boundaryEntry;\n      }\n    }\n\n    return bestMatch;\n  }\n\n  /**\n   * Log discovered routes for debugging\n   */\n  private logRoutes(): void {\n    if (this.routes.size > 0) {\n      logger.info(\"Registered routes:\");\n      for (const [pattern, entry] of this.routes) {\n        console.log(`  ${pattern} -> ${entry.modulePath}`);\n      }\n    }\n\n    if (this.layouts.size > 0) {\n      logger.info(\"Registered layouts:\");\n      for (const [pattern, entry] of this.layouts) {\n        console.log(`  ${pattern} -> ${entry.modulePath}`);\n      }\n    }\n  }\n\n  /**\n   * Collect SSG pages for static generation\n   *\n   * Returns all pages marked with `export const ssg = true` along with\n   * their pre-computed paths (for dynamic routes using getStaticPaths)\n   */\n  async collectSSGPages(): Promise<SSGCollectionResult> {\n    const routes = Array.from(this.routes.values()).map((entry) => ({\n      path: entry.pattern,\n      filePath: entry.modulePath,\n      isDynamic: entry.route.segments.some((seg) => seg.isDynamic),\n      pattern: entry.pattern,\n    }));\n\n    const i18n = this.getI18nConfig();\n    const result = await collectSSGPages(routes, (filePath) => this.loadRouteModule(filePath), {\n      suggestStaticRendering: shouldSuggestStaticRenderingForI18n(i18n),\n    });\n    if (!i18n) {\n      return result;\n    }\n\n    // A single static URL cannot safely vary by cookie or Accept-Language.\n    // Keep locale-without-prefix pages dynamic so caches never pin one language.\n    if (i18n.routing === \"none\") {\n      return {\n        ssg: [],\n        ssr: Array.from(new Set([...result.ssr, ...result.ssg.map((page) => page.urlPath)])),\n      };\n    }\n\n    return {\n      ssg: result.ssg.flatMap((page) =>\n        i18n.locales.map((locale) => ({\n          ...page,\n          urlPath: localizeFarmPathname(page.urlPath, locale, i18n),\n        })),\n      ),\n      ssr: result.ssr.flatMap((routePath) =>\n        i18n.locales.map((locale) => localizeFarmPathname(routePath, locale, i18n)),\n      ),\n    };\n  }\n\n  private toRoutePathname(pathname: string): string {\n    const i18n = this.getI18nConfig();\n    return i18n ? stripFarmLocaleFromPathname(pathname, i18n) : pathname;\n  }\n\n  private localizeRedirectDestination(destination: string, locale?: string): string {\n    if (!locale || !destination.startsWith(\"/\") || destination.startsWith(\"//\")) {\n      return destination;\n    }\n    const i18n = this.getI18nConfig();\n    return i18n ? localizeFarmHref(destination, locale, i18n) : destination;\n  }\n\n  private getI18nConfig(): ResolvedFarmI18nConfig | undefined {\n    const i18n = this.config.i18n;\n    return i18n && typeof i18n === \"object\" && \"enabled\" in i18n && i18n.enabled ? i18n : undefined;\n  }\n\n  /**\n   * Check if a route is SSG\n   */\n  async isRouteSSG(modulePath: string): Promise<boolean> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.ssg;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Check if a route has ISR (Incremental Static Regeneration)\n   */\n  async hasRouteISR(modulePath: string): Promise<boolean> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Get revalidation interval for a route\n   */\n  async getRouteRevalidateInterval(modulePath: string): Promise<number | undefined> {\n    try {\n      const mod = await this.loadRouteModule(modulePath);\n      const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n      return rendering.revalidate;\n    } catch {\n      return undefined;\n    }\n  }\n}\n\nexport function interpolateRedirectDestination(\n  destination: string,\n  params: Record<string, string>,\n): string {\n  let result = destination;\n\n  for (const [key, value] of Object.entries(params)) {\n    // Longest token first: [[...key]] contains [...key], which contains [key].\n    result = replaceAll(result, `[[...${key}]]`, value);\n    result = replaceAll(result, `[...${key}]`, value);\n    result = replaceAll(result, `[${key}]`, value);\n    result = replaceAll(result, `:${key}*`, value);\n    result = replaceAll(result, `:${key}`, value);\n  }\n\n  return result;\n}\n\nfunction getMetadataImageSuffix(pathname: string): {\n  kind: MetadataImageKind;\n  fileName: MetadataImageEntry[\"fileName\"];\n} | null {\n  if (pathname === \"/opengraph-image\" || pathname.endsWith(\"/opengraph-image\")) {\n    return { kind: \"opengraph\", fileName: \"opengraph-image\" };\n  }\n\n  if (pathname === \"/twitter-image\" || pathname.endsWith(\"/twitter-image\")) {\n    return { kind: \"twitter\", fileName: \"twitter-image\" };\n  }\n\n  return null;\n}\n\nfunction getApplicationMetadataRouteDescriptor(fileName: string): {\n  kind: ApplicationMetadataRouteKind;\n  fileName: ApplicationMetadataRouteEntry[\"fileName\"];\n  outputName: ApplicationMetadataRouteEntry[\"outputName\"];\n} | null {\n  if (fileName === \"sitemap\") {\n    return { kind: \"sitemap\", fileName: \"sitemap\", outputName: \"sitemap.xml\" };\n  }\n  if (fileName === \"robots\") {\n    return { kind: \"robots\", fileName: \"robots\", outputName: \"robots.txt\" };\n  }\n  if (fileName === \"manifest\") {\n    return { kind: \"manifest\", fileName: \"manifest\", outputName: \"manifest.webmanifest\" };\n  }\n  return null;\n}\n\nfunction getApplicationMetadataRouteSuffix(pathname: string): {\n  kind: ApplicationMetadataRouteKind;\n  outputName: ApplicationMetadataRouteEntry[\"outputName\"];\n} | null {\n  for (const fileName of [\"sitemap\", \"robots\", \"manifest\"] as const) {\n    const descriptor = getApplicationMetadataRouteDescriptor(fileName)!;\n    if (\n      pathname === `/${descriptor.outputName}` ||\n      pathname.endsWith(`/${descriptor.outputName}`)\n    ) {\n      return { kind: descriptor.kind, outputName: descriptor.outputName };\n    }\n  }\n  return null;\n}\n\nfunction routeSegmentsToPath(\n  segments: ParsedRoute[\"segments\"],\n  params: Record<string, string>,\n): string {\n  if (segments.length === 0) return \"/\";\n\n  const parts: string[] = [];\n  for (const segment of segments) {\n    if (!segment.isDynamic) {\n      parts.push(segment.segment);\n      continue;\n    }\n\n    const value = params[segment.segment];\n    if (!value && segment.isOptional) continue;\n    if (!value) {\n      parts.push(`[${segment.segment}]`);\n      continue;\n    }\n\n    parts.push(...value.split(\"/\").map((part) => encodeURIComponent(part)));\n  }\n\n  return `/${parts.join(\"/\")}`;\n}\n\nfunction replaceAll(input: string, search: string, replacement: string): string {\n  return input.split(search).join(replacement);\n}\n\nasync function safeGlobFiles(pattern: string, cwd: string): Promise<string[]> {\n  try {\n    return await globFiles(pattern, cwd);\n  } catch {\n    return [];\n  }\n}\n","/**\n * Farm.js SSG (Static Site Generation) Module\n *\n * Handles collection and pre-rendering of SSG pages at build time.\n *\n * SSR is the default - pages render on each request\n * SSG is opt-in via `export const ssg = true`, Next-compatible route\n * config exports, or a top-of-file rendering directive.\n *\n * @example\n * ```tsx\n * // SSG Page\n * export const ssg = true;\n * export default function AboutPage() {\n *   return <h1>About</h1>;\n * }\n *\n * // SSG with ISR\n * export const ssg = true;\n * export const revalidate = 60;\n * export default async function ProductsPage() {\n *   const products = await fetchProducts();\n *   return <ProductList products={products} />;\n * }\n *\n * // Dynamic SSG\n * export const ssg = true;\n * export async function getStaticPaths() {\n *   const posts = await fetchPosts();\n *   return posts.map(post => ({ slug: post.slug }));\n * }\n * export default async function BlogPost({ params }) {\n *   return <article>{params.slug}</article>;\n * }\n *\n * // Next-compatible route config\n * export const dynamic = \"force-static\";\n * export const revalidate = 60;\n *\n * // PPR/static-shell route\n * export const experimental_ppr = true;\n * export const revalidate = 60;\n *\n * // Directive config\n * \"use ssg; 60\";\n * export default function DocsPage() {\n *   return <h1>Docs</h1>;\n * }\n * ```\n */\n\nimport { readFile } from \"fs/promises\";\nimport type {\n  RouteModule,\n  SSGPage,\n  SSGCollectionResult,\n  StaticPathParams,\n  StaticPathPrimitive,\n} from \"./types\";\n\ninterface RouteEntry {\n  path: string;\n  filePath: string;\n  isDynamic: boolean;\n  pattern: string;\n}\n\nexport type RouteRenderingDynamic = NonNullable<RouteModule[\"dynamic\"]>;\n\nexport interface RouteRenderingConfig {\n  ssg: boolean;\n  ppr: boolean;\n  revalidate?: number;\n  dynamic?: RouteRenderingDynamic;\n  directive?: string;\n}\n\nexport interface RouteRenderingOptions {\n  /**\n   * Whether `experimental.ppr` is enabled in the app config. Route-level PPR\n   * opt-ins (`ppr`, `experimental_ppr`, `\"use ppr\"`) are inert without it.\n   */\n  experimentalPPR?: boolean;\n}\n\nexport interface StaticRouteCandidateAnalysis {\n  candidate: boolean;\n  blockers: string[];\n}\n\ninterface DirectiveRenderingConfig {\n  ssg: boolean;\n  ppr: boolean;\n  revalidate?: number;\n  dynamic?: RouteRenderingDynamic;\n  directive: string;\n}\n\nconst OPTIONAL_CATCH_ALL_SEGMENT = /^\\[\\[\\.\\.\\.([^\\]]+)\\]\\]$/;\nconst REQUIRED_CATCH_ALL_SEGMENT = /^\\[\\.\\.\\.([^\\]]+)\\]$/;\nconst REQUIRED_DYNAMIC_SEGMENT = /^\\[([^\\]]+)\\]$/;\n\nconst REQUEST_API_LABELS = new Map<string, string>([\n  [\"cookies\", \"request cookies\"],\n  [\"headers\", \"request headers\"],\n  [\"getCurrentRequest\", \"the current Request\"],\n  [\"useSearchParams\", \"URL search parameters\"],\n  [\"auth\", \"request authentication\"],\n  [\"getServerSession\", \"request authentication\"],\n  [\"getSession\", \"request authentication\"],\n  [\"currentUser\", \"request authentication\"],\n]);\n\nconst ROUTE_PROP_LABELS = new Map<string, string>([\n  [\"searchParams\", \"URL search parameters\"],\n  [\"middleware\", \"middleware request data\"],\n  [\"middlewareData\", \"middleware request data\"],\n  [\"context\", \"request context\"],\n]);\n\n/**\n * Resolve route rendering from Farm exports, Next-compatible exports, and\n * top-of-file directives such as `\"use ssg\";` or `\"use ssg; 60\";`.\n */\nfunction resolveConfiguredRouteRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source?: string,\n  options?: RouteRenderingOptions,\n): RouteRenderingConfig {\n  const pprEnabled = options?.experimentalPPR === true;\n  const directiveConfig = parseRouteRenderingDirective(source);\n  let ssg = directiveConfig?.ssg ?? false;\n  let requestedPPR = directiveConfig?.ppr ?? false;\n  let revalidate = directiveConfig?.revalidate;\n  const moduleDynamic = normalizeDynamicMode(mod?.dynamic);\n  const dynamic = moduleDynamic ?? directiveConfig?.dynamic;\n  const hasExplicitSsg = typeof mod?.ssg === \"boolean\";\n  const hasExplicitPPR =\n    typeof mod?.ppr === \"boolean\" || typeof mod?.experimental_ppr === \"boolean\";\n\n  if (hasExplicitSsg) {\n    ssg = mod!.ssg === true;\n  }\n\n  if (hasExplicitPPR) {\n    requestedPPR = mod?.ppr === true || mod?.experimental_ppr === true;\n  }\n\n  if (typeof mod?.revalidate === \"number\") {\n    if (mod.revalidate > 0) {\n      revalidate = mod.revalidate;\n      // A PPR opt-in keeps the route dynamic even while experimental.ppr is\n      // off: the page expects Suspense holes, so falling back to ISR would\n      // bake request-time content into a shared static artifact.\n      if (!hasExplicitSsg && !requestedPPR) {\n        ssg = true;\n      }\n    } else {\n      revalidate = undefined;\n      if (!hasExplicitSsg) {\n        ssg = false;\n      }\n    }\n  } else if (mod?.revalidate === false) {\n    revalidate = undefined;\n  }\n\n  if (moduleDynamic === \"force-static\" || moduleDynamic === \"error\") {\n    ssg = true;\n    requestedPPR = false;\n  } else if (moduleDynamic === \"force-dynamic\") {\n    ssg = false;\n    requestedPPR = false;\n    revalidate = undefined;\n  }\n\n  const ppr = pprEnabled && !ssg && requestedPPR;\n\n  return {\n    ssg,\n    ppr,\n    revalidate: ssg || ppr ? revalidate : undefined,\n    dynamic,\n    directive: directiveConfig?.directive,\n  };\n}\n\n/**\n * Resolve the effective rendering mode. Direct request reads make an explicitly\n * static route dynamic so request-specific HTML cannot enter a shared artifact.\n */\nexport function resolveRouteRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source?: string,\n  options?: RouteRenderingOptions,\n): RouteRenderingConfig {\n  const rendering = resolveConfiguredRouteRenderingConfig(mod, source, options);\n  if (!rendering.ssg || !source) {\n    return rendering;\n  }\n\n  const requestBlockers = findRequestBoundSourceBlockers(source);\n  if (requestBlockers.length === 0) {\n    return rendering;\n  }\n\n  return {\n    ...rendering,\n    ssg: false,\n    revalidate: undefined,\n  };\n}\n\nexport async function resolveRouteRenderingConfigFromFile(\n  mod: RouteModule | null | undefined,\n  filePath: string,\n  options?: RouteRenderingOptions,\n): Promise<RouteRenderingConfig> {\n  const source = await readFile(filePath, \"utf8\").catch(() => undefined);\n  return resolveRouteRenderingConfig(mod, source, options);\n}\n\n/**\n * Conservatively identify a route that may be safe to pre-render.\n *\n * This intentionally produces a suggestion rather than changing rendering:\n * request-bound work can live in a transitive import, which source inspection\n * of the route module cannot prove safe. Explicit route config always wins.\n */\nexport function analyzeStaticRouteCandidate(\n  mod: RouteModule | null | undefined,\n  source: string | undefined,\n  options: { isDynamic?: boolean } = {},\n): StaticRouteCandidateAnalysis {\n  const blockers: string[] = [];\n\n  if (!source) {\n    blockers.push(\"route source is unavailable\");\n  }\n\n  if (options.isDynamic) {\n    blockers.push(\"the route has dynamic path segments\");\n  }\n\n  if (hasExplicitRenderingConfig(mod, source)) {\n    blockers.push(\"the route already has explicit rendering config\");\n  }\n\n  if (source) {\n    blockers.push(...findRequestBoundSourceBlockers(source));\n  }\n\n  return {\n    candidate: blockers.length === 0,\n    blockers,\n  };\n}\n\nfunction findRequestBoundSourceBlockers(source: string): string[] {\n  const blockers = new Set<string>();\n  const code = stripCommentsAndLiteralContents(source);\n\n  const sourceWithoutComments = stripComments(source);\n  for (const binding of readRequestApiImportBindings(sourceWithoutComments)) {\n    if (new RegExp(`\\\\b${escapeRegExp(binding.local)}\\\\s*(?:\\\\?\\\\.\\\\s*)?\\\\(`).test(code)) {\n      blockers.add(`the route reads ${binding.label}`);\n    }\n  }\n\n  for (const namespace of readNamespaceImportBindings(sourceWithoutComments)) {\n    for (const [name, label] of REQUEST_API_LABELS) {\n      if (\n        new RegExp(\n          `\\\\b${escapeRegExp(namespace)}\\\\s*(?:\\\\?\\\\.\\\\s*|\\\\.\\\\s*)${name}\\\\s*(?:\\\\?\\\\.\\\\s*)?\\\\(`,\n        ).test(code)\n      ) {\n        blockers.add(`the route reads ${label}`);\n      }\n    }\n  }\n\n  const params = readDefaultRouteParameters(code);\n  if (params) {\n    for (const [name, label] of ROUTE_PROP_LABELS) {\n      if (new RegExp(`\\\\b${name}\\\\b`).test(params)) {\n        blockers.add(`the route reads ${label}`);\n      }\n    }\n\n    const propsName = params.match(/^\\s*([A-Za-z_$][\\w$]*)\\s*(?::|,|$)/)?.[1];\n    if (propsName) {\n      for (const [name, label] of ROUTE_PROP_LABELS) {\n        if (new RegExp(`\\\\b${escapeRegExp(propsName)}\\\\s*\\\\.\\\\s*${name}\\\\b`).test(code)) {\n          blockers.add(`the route reads ${label}`);\n        }\n        if (\n          new RegExp(`\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}\\\\s*=\\\\s*${escapeRegExp(propsName)}\\\\b`).test(\n            code,\n          )\n        ) {\n          blockers.add(`the route reads ${label}`);\n        }\n      }\n    }\n  }\n\n  return [...blockers];\n}\n\nfunction readRequestApiImportBindings(source: string): Array<{ local: string; label: string }> {\n  const bindings: Array<{ local: string; label: string }> = [];\n  for (const clause of readStaticImportClauses(source)) {\n    const namedGroup = clause.match(/\\{([\\s\\S]*?)\\}/)?.[1];\n    for (const rawSpecifier of (namedGroup ?? \"\").split(\",\")) {\n      const specifier = rawSpecifier.trim().replace(/^type\\s+/, \"\");\n      const imported = specifier.match(/^([A-Za-z_$][\\w$]*)(?:\\s+as\\s+([A-Za-z_$][\\w$]*))?$/);\n      if (!imported?.[1]) continue;\n      const label = REQUEST_API_LABELS.get(imported[1]);\n      if (label) bindings.push({ local: imported[2] ?? imported[1], label });\n    }\n\n    const local = clause.match(/^\\s*([A-Za-z_$][\\w$]*)\\s*(?:,|$)/)?.[1];\n    if (local) {\n      const label = REQUEST_API_LABELS.get(local);\n      if (label) bindings.push({ local, label });\n    }\n  }\n\n  return bindings;\n}\n\nfunction readNamespaceImportBindings(source: string): string[] {\n  return readStaticImportClauses(source)\n    .map((clause) => clause.match(/\\*\\s*as\\s*([A-Za-z_$][\\w$]*)/)?.[1])\n    .filter((binding): binding is string => Boolean(binding));\n}\n\nfunction readStaticImportClauses(source: string): string[] {\n  return [...source.matchAll(/\\bimport\\s+(?!\\()([\\s\\S]*?)\\s+from\\s*[\"'][^\"']+[\"']/g)]\n    .map((match) => match[1])\n    .filter((clause): clause is string => Boolean(clause));\n}\n\nfunction readDefaultRouteParameters(code: string): string | undefined {\n  const inlineParams =\n    code.match(/\\bexport\\s+default\\s+(?:async\\s+)?function\\b[^(]*\\(([^)]*)\\)/)?.[1] ??\n    code.match(/\\bexport\\s+default\\s+(?:async\\s+)?\\(([^)]*)\\)\\s*=>/)?.[1];\n  if (inlineParams !== undefined) return inlineParams;\n\n  const binding =\n    code.match(/\\bexport\\s+default\\s+([A-Za-z_$][\\w$]*)\\s*;?/)?.[1] ??\n    code.match(/\\bexport\\s*\\{\\s*([A-Za-z_$][\\w$]*)\\s+as\\s+default\\s*\\}/)?.[1];\n  if (!binding) return undefined;\n  const escapedBinding = escapeRegExp(binding);\n\n  return (\n    code.match(new RegExp(`\\\\bfunction\\\\s+${escapedBinding}\\\\s*\\\\(([^)]*)\\\\)`))?.[1] ??\n    code.match(\n      new RegExp(\n        `\\\\b(?:const|let|var)\\\\s+${escapedBinding}\\\\s*=\\\\s*(?:async\\\\s+)?\\\\(([^)]*)\\\\)\\\\s*=>`,\n      ),\n    )?.[1] ??\n    code.match(\n      new RegExp(`\\\\b(?:const|let|var)\\\\s+${escapedBinding}\\\\s*=\\\\s*function\\\\s*\\\\(([^)]*)\\\\)`),\n    )?.[1]\n  );\n}\n\nfunction stripCommentsAndLiteralContents(source: string): string {\n  return sanitizeSource(source, true);\n}\n\nfunction stripComments(source: string): string {\n  return sanitizeSource(source, false);\n}\n\nfunction sanitizeSource(source: string, maskLiterals: boolean): string {\n  const output = [...source];\n  const mask = (index: number) => {\n    if (output[index] !== \"\\n\" && output[index] !== \"\\r\") output[index] = \" \";\n  };\n\n  const scanQuoted = (start: number, quote: \"'\" | '\"'): number => {\n    let index = start;\n    if (maskLiterals) mask(index);\n    index += 1;\n    while (index < source.length) {\n      if (source[index] === \"\\\\\") {\n        if (maskLiterals) mask(index);\n        if (index + 1 < source.length && maskLiterals) mask(index + 1);\n        index += 2;\n        continue;\n      }\n      const character = source[index];\n      if (maskLiterals) mask(index);\n      index += 1;\n      if (character === quote) break;\n    }\n    return index;\n  };\n\n  const scanCode = (start: number, stopAtTemplateBrace: boolean): number => {\n    let index = start;\n    let braceDepth = 0;\n    while (index < source.length) {\n      const character = source[index];\n      const next = source[index + 1];\n      if (character === \"/\" && next === \"/\") {\n        while (index < source.length && source[index] !== \"\\n\" && source[index] !== \"\\r\") {\n          mask(index++);\n        }\n        continue;\n      }\n      if (character === \"/\" && next === \"*\") {\n        mask(index++);\n        mask(index++);\n        while (index < source.length) {\n          const closesComment = source[index] === \"*\" && source[index + 1] === \"/\";\n          mask(index++);\n          if (closesComment) {\n            mask(index++);\n            break;\n          }\n        }\n        continue;\n      }\n      if (character === \"'\" || character === '\"') {\n        index = scanQuoted(index, character);\n        continue;\n      }\n      if (character === \"`\") {\n        if (maskLiterals) mask(index);\n        index += 1;\n        while (index < source.length) {\n          if (source[index] === \"\\\\\") {\n            if (maskLiterals) mask(index);\n            if (index + 1 < source.length && maskLiterals) mask(index + 1);\n            index += 2;\n          } else if (source[index] === \"`\") {\n            if (maskLiterals) mask(index);\n            index += 1;\n            break;\n          } else if (source[index] === \"$\" && source[index + 1] === \"{\") {\n            if (maskLiterals) {\n              mask(index);\n              mask(index + 1);\n            }\n            index = scanCode(index + 2, true);\n          } else {\n            if (maskLiterals) mask(index);\n            index += 1;\n          }\n        }\n        continue;\n      }\n      if (character === \"{\") {\n        braceDepth += 1;\n      } else if (character === \"}\") {\n        if (stopAtTemplateBrace && braceDepth === 0) {\n          if (maskLiterals) mask(index);\n          return index + 1;\n        }\n        braceDepth = Math.max(0, braceDepth - 1);\n      }\n      index += 1;\n    }\n    return index;\n  };\n\n  scanCode(0, false);\n  return output.join(\"\");\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction hasExplicitRenderingConfig(\n  mod: RouteModule | null | undefined,\n  source: string | undefined,\n): boolean {\n  return (\n    typeof mod?.ssg === \"boolean\" ||\n    typeof mod?.ppr === \"boolean\" ||\n    typeof mod?.experimental_ppr === \"boolean\" ||\n    typeof mod?.revalidate !== \"undefined\" ||\n    typeof mod?.dynamic !== \"undefined\" ||\n    typeof parseRouteRenderingDirective(source) !== \"undefined\"\n  );\n}\n\nexport function parseRouteRenderingDirective(\n  source: string | undefined,\n): DirectiveRenderingConfig | undefined {\n  if (!source) {\n    return undefined;\n  }\n\n  for (const directive of readDirectivePrologue(source)) {\n    const config = parseKnownRenderingDirective(directive);\n    if (config) {\n      return config;\n    }\n  }\n\n  return undefined;\n}\n\nfunction parseKnownRenderingDirective(directive: string): DirectiveRenderingConfig | undefined {\n  const normalized = directive.trim().toLowerCase();\n  const match = normalized.match(\n    /^use\\s+(ssg|static|isr|ssr|dynamic|ppr)(?:\\s*[;:]\\s*(\\d+))?\\s*;?$/,\n  );\n\n  if (!match?.[1]) {\n    return undefined;\n  }\n\n  const mode = match[1];\n  const revalidate = match[2] ? Number(match[2]) : undefined;\n\n  if (mode === \"ssr\" || mode === \"dynamic\") {\n    return {\n      ssg: false,\n      ppr: false,\n      dynamic: \"force-dynamic\",\n      directive,\n    };\n  }\n\n  if (mode === \"ppr\") {\n    return {\n      ssg: false,\n      ppr: true,\n      revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n      directive,\n    };\n  }\n\n  return {\n    ssg: true,\n    ppr: false,\n    dynamic: \"force-static\",\n    revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n    directive,\n  };\n}\n\nfunction normalizeDynamicMode(value: unknown): RouteRenderingDynamic | undefined {\n  switch (value) {\n    case \"auto\":\n    case \"force-static\":\n    case \"force-dynamic\":\n    case \"error\":\n      return value;\n    default:\n      return undefined;\n  }\n}\n\nfunction readDirectivePrologue(source: string): string[] {\n  const directives: string[] = [];\n  let index = skipTrivia(source, 0);\n\n  while (index < source.length) {\n    const parsed = readStringStatement(source, index);\n    if (!parsed) {\n      break;\n    }\n\n    directives.push(parsed.value);\n    index = skipTrivia(source, parsed.end);\n  }\n\n  return directives;\n}\n\nfunction skipTrivia(source: string, start: number): number {\n  let index = start;\n\n  while (index < source.length) {\n    const char = source[index];\n\n    if (char && /\\s/.test(char)) {\n      index += 1;\n      continue;\n    }\n\n    if (source.startsWith(\"//\", index)) {\n      const nextLine = source.indexOf(\"\\n\", index + 2);\n      index = nextLine === -1 ? source.length : nextLine + 1;\n      continue;\n    }\n\n    if (source.startsWith(\"/*\", index)) {\n      const end = source.indexOf(\"*/\", index + 2);\n      index = end === -1 ? source.length : end + 2;\n      continue;\n    }\n\n    break;\n  }\n\n  return index;\n}\n\nfunction readStringStatement(\n  source: string,\n  start: number,\n): { value: string; end: number } | undefined {\n  const quote = source[start];\n  if (quote !== '\"' && quote !== \"'\") {\n    return undefined;\n  }\n\n  let value = \"\";\n  let index = start + 1;\n\n  while (index < source.length) {\n    const char = source[index];\n    if (char === \"\\\\\") {\n      value += source.slice(index, index + 2);\n      index += 2;\n      continue;\n    }\n\n    if (char === quote) {\n      index += 1;\n      const semicolonIndex = skipHorizontalWhitespace(source, index);\n      const end = source[semicolonIndex] === \";\" ? semicolonIndex + 1 : index;\n      return { value, end };\n    }\n\n    value += char ?? \"\";\n    index += 1;\n  }\n\n  return undefined;\n}\n\nfunction skipHorizontalWhitespace(source: string, start: number): number {\n  let index = start;\n  while (source[index] === \" \" || source[index] === \"\\t\" || source[index] === \"\\r\") {\n    index += 1;\n  }\n  return index;\n}\n\n/**\n * Collect SSG pages from route modules\n *\n * Scans all routes and categorizes them into:\n * - SSG pages: Pre-rendered at build time\n * - SSR routes: Rendered on each request\n *\n * @param routes - Array of route entries\n * @param loadModule - Function to load a route module\n * @returns SSG pages and SSR routes\n */\nexport async function collectSSGPages(\n  routes: RouteEntry[],\n  loadModule: (filePath: string) => Promise<RouteModule>,\n  options: { suggestStaticRendering?: boolean } = {},\n): Promise<SSGCollectionResult> {\n  const ssgPages: SSGPage[] = [];\n  const ssrRoutes: string[] = [];\n  const staticCandidateRoutes: string[] = [];\n\n  for (const route of routes) {\n    try {\n      const mod = await loadModule(route.filePath);\n\n      if (!mod) {\n        ssrRoutes.push(route.path);\n        continue;\n      }\n\n      const source = await readFile(route.filePath, \"utf8\").catch(() => undefined);\n      const configuredRendering = resolveConfiguredRouteRenderingConfig(mod, source);\n      const rendering = resolveRouteRenderingConfig(mod, source);\n\n      if (configuredRendering.ssg && !rendering.ssg && source) {\n        const blockers = findRequestBoundSourceBlockers(source);\n        console.warn(\n          `[Farm.js] Static rendering disabled for \"${route.path}\" because ${blockers.join(\n            \" and \",\n          )}. Farm will render this route on each request instead.`,\n        );\n      }\n\n      // Check if page is marked for SSG\n      if (rendering.ssg) {\n        if (route.isDynamic) {\n          // Dynamic SSG route requires getStaticPaths\n          const getStaticPaths = mod.getStaticPaths || mod.generateStaticParams;\n\n          if (!getStaticPaths) {\n            throw new Error(\n              `Dynamic SSG route \"${route.path}\" requires getStaticPaths export. ` +\n                `Add: export function getStaticPaths() { return [{ paramName: 'value' }]; }`,\n            );\n          }\n\n          // Get all paths to pre-render\n          const paths = await getStaticPaths();\n\n          // Materialize every path before adding any of them. If one entry is\n          // invalid, the outer error handler can safely fall the whole route\n          // back to SSR without leaving a partial SSG manifest behind.\n          const materializedPages = paths.map((params) => ({\n            urlPath: materializeSSGRoutePath(route.path, params),\n            filePath: route.filePath,\n            params: normalizeStaticPathParams(params),\n            revalidate: rendering.revalidate,\n          }));\n\n          ssgPages.push(...materializedPages);\n        } else {\n          // Static SSG page\n          ssgPages.push({\n            urlPath: route.path,\n            filePath: route.filePath,\n            params: {},\n            revalidate: rendering.revalidate,\n          });\n        }\n      } else {\n        // SSR route (default)\n        ssrRoutes.push(route.path);\n\n        if (\n          options.suggestStaticRendering !== false &&\n          analyzeStaticRouteCandidate(mod, source, { isDynamic: route.isDynamic }).candidate\n        ) {\n          staticCandidateRoutes.push(route.path);\n        }\n      }\n    } catch (error) {\n      console.error(`Error processing route ${route.path}:`, error);\n      // Fall back to SSR for problematic routes\n      ssrRoutes.push(route.path);\n    }\n  }\n\n  if (staticCandidateRoutes.length > 0) {\n    const visibleRoutes = staticCandidateRoutes.slice(0, 10);\n    const remainingCount = staticCandidateRoutes.length - visibleRoutes.length;\n    const remainingSuffix = remainingCount > 0 ? `\\n  …and ${remainingCount} more` : \"\";\n\n    console.warn(\n      `[Farm.js] ${staticCandidateRoutes.length} route${\n        staticCandidateRoutes.length === 1 ? \" appears\" : \"s appear\"\n      } eligible for static rendering:\\n  ${visibleRoutes.join(\"\\n  \")}${remainingSuffix}\\n` +\n        `Add \\`export const dynamic = \"force-static\";\\` after verifying that imported code ` +\n        `does not read cookies, headers, authentication, or other request data.`,\n    );\n  }\n\n  return { ssg: ssgPages, ssr: ssrRoutes };\n}\n\nfunction materializeSSGRoutePath(routePattern: string, params: StaticPathParams): string {\n  const outputSegments: string[] = [];\n\n  for (const segment of routePattern.split(\"/\")) {\n    if (!segment) {\n      continue;\n    }\n\n    const optionalCatchAll = segment.match(OPTIONAL_CATCH_ALL_SEGMENT);\n    if (optionalCatchAll) {\n      const parameterName = optionalCatchAll[1]!;\n      const value = params[parameterName];\n      const values = readCatchAllSegments(value, {\n        optional: true,\n        parameterName,\n        routePattern,\n      });\n      outputSegments.push(...values.map(encodePathSegment));\n      continue;\n    }\n\n    const requiredCatchAll = segment.match(REQUIRED_CATCH_ALL_SEGMENT);\n    if (requiredCatchAll) {\n      const parameterName = requiredCatchAll[1]!;\n      const value = params[parameterName];\n      const values = readCatchAllSegments(value, {\n        optional: false,\n        parameterName,\n        routePattern,\n      });\n      outputSegments.push(...values.map(encodePathSegment));\n      continue;\n    }\n\n    const requiredDynamic = segment.match(REQUIRED_DYNAMIC_SEGMENT);\n    if (requiredDynamic) {\n      const parameterName = requiredDynamic[1]!;\n      const value = params[parameterName];\n      if (isStaticPathArray(value)) {\n        throw new Error(\n          `Cannot materialize SSG route \"${routePattern}\": parameter \"${parameterName}\" ` +\n            \"must be a scalar value; arrays are only supported for catch-all segments.\",\n        );\n      }\n      if (isMissingPathValue(value)) {\n        throw missingRequiredParameterError(routePattern, parameterName);\n      }\n      outputSegments.push(encodePathSegment(value));\n      continue;\n    }\n\n    outputSegments.push(segment);\n  }\n\n  return outputSegments.length > 0 ? `/${outputSegments.join(\"/\")}` : \"/\";\n}\n\nfunction readCatchAllSegments(\n  value: StaticPathParams[string] | undefined,\n  options: {\n    optional: boolean;\n    parameterName: string;\n    routePattern: string;\n  },\n): StaticPathPrimitive[] {\n  if (isMissingPathValue(value) || (isStaticPathArray(value) && value.length === 0)) {\n    if (options.optional) {\n      return [];\n    }\n    throw missingRequiredParameterError(options.routePattern, options.parameterName);\n  }\n\n  const segments = isStaticPathArray(value) ? [...value] : [value as StaticPathPrimitive];\n  if (segments.some(isMissingPathValue)) {\n    throw new Error(\n      `Cannot materialize SSG route \"${options.routePattern}\": catch-all parameter ` +\n        `\"${options.parameterName}\" contains an empty path segment.`,\n    );\n  }\n\n  return segments;\n}\n\nfunction normalizeStaticPathParams(params: StaticPathParams): Record<string, string> {\n  return Object.fromEntries(\n    Object.entries(params).map(([key, value]) => [\n      key,\n      isStaticPathArray(value) ? value.map(String).join(\"/\") : String(value),\n    ]),\n  );\n}\n\nfunction isMissingPathValue(value: unknown): value is \"\" | null | undefined {\n  return value === \"\" || value === null || typeof value === \"undefined\";\n}\n\nfunction isStaticPathArray(\n  value: StaticPathParams[string] | undefined,\n): value is readonly StaticPathPrimitive[] {\n  return Array.isArray(value);\n}\n\nfunction missingRequiredParameterError(routePattern: string, parameterName: string): Error {\n  return new Error(\n    `Cannot materialize SSG route \"${routePattern}\": required parameter ` +\n      `\"${parameterName}\" is missing or empty.`,\n  );\n}\n\nfunction encodePathSegment(value: StaticPathPrimitive): string {\n  const encoded = encodeURIComponent(String(value)).replace(\n    /[!'()*]/g,\n    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n\n  // Dot-only URL segments are normalized as navigation by URL parsers and\n  // filesystem joins. Pre-rendering them could therefore escape the intended\n  // route directory or overwrite a parent artifact. They cannot faithfully be\n  // represented as a static URL segment, so keep the route server-rendered.\n  if (encoded === \".\" || encoded === \"..\") {\n    throw new Error(\n      `Cannot materialize SSG path segment \"${encoded}\": dot-only segments are unsafe to prerender.`,\n    );\n  }\n\n  return encoded;\n}\n\n/**\n * Check if a route module is SSG\n */\nexport function isSSGModule(mod: RouteModule | null | undefined): boolean {\n  return resolveRouteRenderingConfig(mod).ssg;\n}\n\n/**\n * Check if a route module has ISR (Incremental Static Regeneration)\n */\nexport function hasISR(mod: RouteModule | null | undefined): boolean {\n  const rendering = resolveRouteRenderingConfig(mod);\n  return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n}\n\n/**\n * Get revalidation interval for a module\n */\nexport function getRevalidateInterval(mod: RouteModule | null | undefined): number | undefined {\n  return resolveRouteRenderingConfig(mod).revalidate;\n}\n\n/**\n * Check if a route module has PPR/static-shell caching enabled.\n */\nexport function hasPPR(\n  mod: RouteModule | null | undefined,\n  options?: RouteRenderingOptions,\n): boolean {\n  return resolveRouteRenderingConfig(mod, undefined, options).ppr;\n}\n\n/**\n * Generate SSG manifest for production builds\n */\nexport function generateSSGManifest(pages: SSGPage[]): string {\n  return JSON.stringify(\n    pages.map((page) => ({\n      urlPath: page.urlPath,\n      params: page.params,\n      revalidate: page.revalidate,\n    })),\n    null,\n    2,\n  );\n}\n\n/**\n * Check if a URL path matches an SSG page\n */\nexport function matchSSGPage(urlPath: string, ssgPages: SSGPage[]): SSGPage | undefined {\n  const normalizedPath = urlPath === \"/\" ? \"/\" : urlPath.replace(/\\/$/, \"\");\n  return ssgPages.find((page) => page.urlPath === normalizedPath);\n}\n","import { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { PROGRAMMATIC_ROUTE_FILE_NAMES, scanProgrammaticPagePaths } from \"./routes-shared\";\nimport type { ProgrammaticRouteManifest } from \"./routes\";\n\nexport interface LoadedProgrammaticRouteManifest {\n  filePath: string;\n  manifest: ProgrammaticRouteManifest;\n}\n\nexport async function loadProgrammaticRouteManifests(options: {\n  root: string;\n  srcDir?: string;\n  loadModule: (filePath: string) => Promise<Record<string, any>>;\n}): Promise<LoadedProgrammaticRouteManifest[]> {\n  const manifests: LoadedProgrammaticRouteManifest[] = [];\n  const routeFiles = findProgrammaticRouteFiles(options.root, options.srcDir);\n  if (routeFiles.length === 0) return manifests;\n\n  const { getProgrammaticRouteManifest } = await import(\"./routes\");\n\n  for (const filePath of routeFiles) {\n    const mod = await options.loadModule(filePath);\n    const manifest = getProgrammaticRouteManifest(mod);\n    if (manifest) {\n      manifests.push({ filePath, manifest });\n    }\n  }\n\n  return manifests;\n}\n\nexport function findProgrammaticRouteFiles(root: string, srcDir = \"src\"): string[] {\n  return findProgrammaticRouteFilesInDir(join(root, srcDir));\n}\n\nexport function findProgrammaticRouteFilesInDir(srcRoot: string): string[] {\n  const files: string[] = [];\n\n  for (const fileName of PROGRAMMATIC_ROUTE_FILE_NAMES) {\n    const filePath = join(srcRoot, fileName);\n    if (existsSync(filePath)) {\n      files.push(filePath);\n    }\n  }\n\n  return files;\n}\n\nexport async function discoverProgrammaticRoutePaths(\n  root: string,\n  srcDir = \"src\",\n): Promise<string[]> {\n  const paths = new Set<string>();\n  const files = new Set([\n    ...findProgrammaticRouteFiles(root, srcDir),\n    ...(await findProgrammaticRouteSourceFiles(join(root, srcDir))),\n  ]);\n\n  for (const filePath of files) {\n    const source = readFileSync(filePath, \"utf8\");\n    for (const routePath of scanProgrammaticPagePaths(source)) {\n      paths.add(routePath);\n    }\n  }\n\n  return Array.from(paths).sort();\n}\n\nasync function findProgrammaticRouteSourceFiles(srcRoot: string): Promise<string[]> {\n  if (!existsSync(srcRoot)) {\n    return [];\n  }\n\n  try {\n    const glob = await import(\"fast-glob\");\n    return await glob.default(\"**/*.{ts,tsx,js,jsx}\", {\n      cwd: srcRoot,\n      absolute: true,\n      ignore: [\n        \"**/*.d.ts\",\n        \"**/node_modules/**\",\n        \"**/.*/**\",\n        \"farm-routes.d.ts\",\n        \"farm-env.d.ts\",\n        \"lib/api.generated.ts\",\n      ],\n    });\n  } catch {\n    return [];\n  }\n}\n","import { readFile } from \"fs/promises\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport type { Metadata, RouteModule } from \"./types\";\nimport type { ComponentType } from \"react\";\nimport { requestAcceptsMarkdown } from \"./markdown\";\nimport {\n  resolveMdxConfig,\n  type FarmMdxComponents,\n  type FarmMdxResolvedConfig,\n} from \"./app-markdown-config\";\nexport {\n  resolveMdxConfig,\n  type FarmMdxComponent,\n  type FarmMdxComponents,\n  type FarmMdxResolvedConfig,\n  type FarmMdxUserConfig,\n} from \"./app-markdown-config\";\n\nexport interface FarmMarkdownPageSource {\n  source: string;\n  filePath: string;\n}\n\nexport interface FarmMarkdownPageModuleInput extends FarmMarkdownPageSource {\n  components?: FarmMdxComponents;\n  config?: FarmMdxResolvedConfig;\n}\n\nexport function isFarmMarkdownPageFile(filePath: string): boolean {\n  return /(^|[/\\\\])page\\.mdx?$/i.test(filePath);\n}\n\n/** Content type for Markdown responses, including agent-facing error bodies. */\nexport const FARM_MARKDOWN_CONTENT_TYPE = \"text/markdown; charset=utf-8\";\n\n/**\n * True when the client asked for Markdown — either via a `.md` path or an\n * `Accept: text/markdown` header. Used to serve a Markdown error body to agents\n * that navigate in Markdown, instead of the HTML error shell.\n */\nexport function farmRequestWantsMarkdown(\n  pathname: string,\n  accept: string | null | undefined,\n): boolean {\n  return pathname.toLowerCase().endsWith(\".md\") || requestAcceptsMarkdown(accept);\n}\n\n/**\n * A Markdown error document for agents that requested Markdown but hit an error\n * (typically a 404). Includes a short explanation and a link back to the site so\n * an agent can recover, satisfying the \"Markdown error body\" agent-readiness\n * expectation.\n */\nexport function createFarmMarkdownErrorBody(\n  status: number,\n  pathname: string,\n  homeHref = \"/\",\n): string {\n  const heading = status === 404 ? \"Page not found\" : `Request failed (${status})`;\n  return (\n    `# ${heading}\\n\\n` +\n    `No page is available at \\`${pathname}\\`. The URL may be incorrect, ` +\n    `or the page has not been published.\\n\\n` +\n    `Browse [the site homepage](${homeHref}) to find available pages.\\n`\n  );\n}\n\nexport function normalizeFarmMarkdownRoutePath(pathname: string): string {\n  const withoutExtension = pathname.replace(/\\.md$/i, \"\");\n  const normalized = withoutExtension.startsWith(\"/\") ? withoutExtension : `/${withoutExtension}`;\n  return normalized === \"/index\" ? \"/\" : normalized.replace(/\\/+$/g, \"\") || \"/\";\n}\n\nexport function parseMarkdownFrontmatter(source: string): {\n  frontmatter: Record<string, string>;\n  body: string;\n} {\n  if (!source.startsWith(\"---\")) {\n    return { frontmatter: {}, body: source };\n  }\n\n  const endIndex = source.indexOf(\"\\n---\", 3);\n  if (endIndex === -1) {\n    return { frontmatter: {}, body: source };\n  }\n\n  const frontmatterSource = source.slice(3, endIndex).trim();\n  const closingFenceEnd = endIndex + \"\\n---\".length;\n  const bodyStart =\n    source.slice(closingFenceEnd, closingFenceEnd + 2) === \"\\r\\n\"\n      ? closingFenceEnd + 2\n      : source[closingFenceEnd] === \"\\n\"\n        ? closingFenceEnd + 1\n        : closingFenceEnd;\n  const body = source.slice(bodyStart);\n  const frontmatter: Record<string, string> = {};\n\n  for (const line of frontmatterSource.split(/\\r?\\n/)) {\n    const separator = line.indexOf(\":\");\n    if (separator === -1) continue;\n    const key = line.slice(0, separator).trim();\n    const value = line\n      .slice(separator + 1)\n      .trim()\n      .replace(/^[\"']|[\"']$/g, \"\");\n    if (key && value) frontmatter[key] = value;\n  }\n\n  return { frontmatter, body };\n}\n\nexport function titleFromMarkdown(body: string, fallback?: string): string | undefined {\n  return body.match(/^#\\s+(.+)$/m)?.[1]?.trim() || fallback;\n}\n\nexport function createMarkdownMetadata(\n  source: string,\n  filePath: string,\n): (Metadata & Record<string, any>) | undefined {\n  const { frontmatter, body } = parseMarkdownFrontmatter(source);\n  const routeTitle = titleFromMarkdown(body);\n  const title = frontmatter.title || routeTitle;\n  const description = frontmatter.description;\n\n  if (!title && !description) {\n    return undefined;\n  }\n\n  return {\n    ...(title ? { title } : {}),\n    ...(description ? { description } : {}),\n    source: filePath,\n  };\n}\n\nasync function evaluateMdxSource(source: string, filePath: string) {\n  const [{ evaluate }, runtime, remarkGfmModule] = await Promise.all([\n    import(\"@mdx-js/mdx\"),\n    import(\"react/jsx-runtime\"),\n    import(\"remark-gfm\"),\n  ]);\n  const remarkGfm = remarkGfmModule.default;\n\n  return evaluate(source, {\n    ...runtime,\n    baseUrl: pathToFileURL(filePath),\n    remarkPlugins: [remarkGfm],\n  });\n}\n\nexport function createFarmMarkdownRouteModule(\n  input: FarmMarkdownPageModuleInput,\n): RouteModule & { source: string } {\n  const { body } = parseMarkdownFrontmatter(input.source);\n  const components = input.components || {};\n  const className = input.config?.className || \"farm-markdown\";\n  let evaluatedPromise: Promise<{ default: ComponentType<any> }> | undefined;\n\n  const loadContent = async () => {\n    evaluatedPromise ??= evaluateMdxSource(body, input.filePath) as Promise<{\n      default: ComponentType<any>;\n    }>;\n    return evaluatedPromise;\n  };\n\n  async function FarmMarkdownPage(props: any) {\n    const { createElement } = await import(\"react\");\n    const evaluated = await loadContent();\n    const MDXContent = evaluated.default;\n    return createElement(\n      \"article\",\n      { className, \"data-farm-markdown-page\": \"\" },\n      createElement(MDXContent, {\n        ...props,\n        components: {\n          ...components,\n          ...props?.components,\n        },\n      }),\n    );\n  }\n\n  return {\n    default: FarmMarkdownPage as unknown as RouteModule[\"default\"],\n    metadata: createMarkdownMetadata(input.source, input.filePath),\n    source: input.source,\n  };\n}\n\nexport async function createFarmMarkdownRouteModuleFromFile(\n  filePath: string,\n  options: {\n    components?: FarmMdxComponents;\n    config?: FarmMdxResolvedConfig;\n  } = {},\n) {\n  const source = await readFile(filePath, \"utf8\");\n  return createFarmMarkdownRouteModule({\n    source,\n    filePath,\n    components: options.components,\n    config: options.config,\n  });\n}\n\nexport async function loadFarmMdxComponents(\n  config: FarmMdxResolvedConfig | undefined,\n  options: {\n    root: string;\n    loadModule?: (modulePath: string) => Promise<unknown>;\n  },\n): Promise<FarmMdxComponents> {\n  const configured = config?.components;\n  if (!configured) {\n    return {};\n  }\n\n  if (typeof configured !== \"string\") {\n    return configured;\n  }\n\n  const modulePath = path.isAbsolute(configured) ? configured : path.join(options.root, configured);\n  const mod = options.loadModule\n    ? await options.loadModule(modulePath)\n    : await import(pathToFileURL(modulePath).href);\n  const maybeModule = mod as {\n    components?: FarmMdxComponents;\n    default?: FarmMdxComponents;\n  };\n\n  return maybeModule.components || maybeModule.default || {};\n}\n\nexport async function createFarmMarkdownSourceResponse(options: {\n  request: Request;\n  config?: FarmMdxResolvedConfig;\n  resolveSource: (\n    pathname: string,\n  ) => Promise<FarmMarkdownPageSource | null> | FarmMarkdownPageSource | null;\n}): Promise<Response | null> {\n  if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n    return null;\n  }\n  if (options.config?.markdownRoutes === false) {\n    return null;\n  }\n\n  const url = new URL(options.request.url);\n  const hasMarkdownExtension = url.pathname.toLowerCase().endsWith(\".md\");\n  if (!hasMarkdownExtension && !requestAcceptsMarkdown(options.request.headers.get(\"accept\"))) {\n    return null;\n  }\n\n  const targetPathname = normalizeFarmMarkdownRoutePath(url.pathname);\n  const source = await options.resolveSource(targetPathname);\n  if (!source) {\n    return null;\n  }\n\n  const headers = new Headers({\n    \"Content-Type\": \"text/markdown; charset=utf-8\",\n    \"Content-Location\": targetPathname === \"/\" ? \"/index.md\" : `${targetPathname}.md`,\n    \"Cache-Control\": \"public, s-maxage=60, stale-while-revalidate=300\",\n    \"X-Farm-Markdown-Route\": targetPathname,\n    \"X-Farm-Markdown-Source\": source.filePath,\n  });\n  if (!hasMarkdownExtension) {\n    headers.set(\"Vary\", \"Accept\");\n  }\n\n  return new Response(options.request.method === \"HEAD\" ? null : source.source, {\n    status: 200,\n    headers,\n  });\n}\n","import fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { isFarmIslandStrategy, type FarmIslandStrategy } from \"../island\";\nimport type { FarmIsolatedClientHydrationMode } from \"../types\";\n\nfunction readIfExists(filePath: string): string | null {\n  try {\n    if (!filePath || !fs.existsSync(filePath)) {\n      return null;\n    }\n    return fs.readFileSync(filePath, \"utf-8\");\n  } catch {\n    return null;\n  }\n}\n\nexport function resolveModuleSourcePath(modulePath: string, root?: string): string | null {\n  const candidates = new Set<string>();\n  const withoutQuery = modulePath.split(\"?\")[0];\n\n  if (modulePath) {\n    candidates.add(modulePath);\n    candidates.add(withoutQuery);\n\n    if (modulePath.startsWith(\"file://\")) {\n      try {\n        candidates.add(fileURLToPath(modulePath));\n      } catch {\n        // ignore invalid file urls\n      }\n    }\n\n    if (modulePath.startsWith(\"/@fs/\")) {\n      // Vite emits /@fs/C:/... on Windows, where the leading slash is not part of the path.\n      const fsPath = withoutQuery.slice(\"/@fs/\".length);\n      candidates.add(path.normalize(/^[A-Za-z]:/.test(fsPath) ? fsPath : `/${fsPath}`));\n    }\n  }\n\n  if (root && modulePath) {\n    const normalized = withoutQuery.replace(/^\\/+/, \"\");\n    candidates.add(path.join(root, normalized));\n    candidates.add(path.resolve(root, normalized));\n  }\n\n  if (withoutQuery?.startsWith(\"/src/\")) {\n    const normalized = withoutQuery.replace(/^\\/+/, \"\");\n    candidates.add(path.join(process.cwd(), normalized));\n    candidates.add(path.resolve(process.cwd(), normalized));\n  }\n\n  for (const candidate of candidates) {\n    if (fs.existsSync(candidate)) {\n      return candidate;\n    }\n  }\n\n  return null;\n}\n\nexport interface ClientModuleMetadata {\n  isClientComponent: boolean;\n  shouldHydrate: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n  /**\n   * Set when the module would hydrate (client imports or an explicit hydrate\n   * export) but its default export is an async server component, which React\n   * cannot run in a client root. Hydration is suppressed so the\n   * server-rendered HTML stays intact instead of crashing to a blank page.\n   */\n  suppressedAsyncHydration?: true;\n}\n\nexport interface IsolatedClientBoundaryReference {\n  /** Absolute source path. Converted to a Vite URL only at the manifest edge. */\n  modulePath: string;\n  islandStrategy: FarmIslandStrategy;\n}\n\nexport interface ClientModuleHydrationPlan extends ClientModuleMetadata {\n  mode: FarmIsolatedClientHydrationMode;\n  legacyShouldHydrate: boolean;\n  legacyIslandStrategy: FarmIslandStrategy | null;\n  estimatedIsolatedRootCount: number;\n  isolatedHydrationEligible: boolean;\n  hasIsolatedClientBoundaries: boolean;\n  isolatedBoundaries: IsolatedClientBoundaryReference[];\n  costGuardExceeded?: true;\n  fallbackReason?: string;\n}\n\n/** @internal Largest measured statically bounded independent-root plan. */\nexport const FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES = 4;\n\nfunction isolatedHydrationBoundaryLimit(): number {\n  const benchmarkRoot = process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_ROOT;\n  const benchmarkLimit = Number(process.env.FARM_INTERNAL_ISOLATED_HYDRATION_BENCHMARK_LIMIT);\n  const resolvedBenchmarkRoot = benchmarkRoot ? path.resolve(benchmarkRoot) : null;\n  const isBenchmarkFixture =\n    process.env.FARM_INTERNAL_BENCHMARK === \"isolated-hydration\" &&\n    resolvedBenchmarkRoot !== null &&\n    (process.cwd() === resolvedBenchmarkRoot ||\n      process.cwd().startsWith(`${resolvedBenchmarkRoot}${path.sep}`));\n  return isBenchmarkFixture &&\n    Number.isSafeInteger(benchmarkLimit) &&\n    benchmarkLimit > FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES\n    ? benchmarkLimit\n    : FARM_ISOLATED_HYDRATION_MAX_BOUNDARIES;\n}\n\ninterface ParsedClientModuleMetadata {\n  isClientComponent: boolean;\n  hasHydrateExport: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n}\n\nconst RESOLVABLE_SOURCE_EXTENSIONS = [\n  \".svelte\",\n  \".vue\",\n  \".tsx\",\n  \".ts\",\n  \".jsx\",\n  \".js\",\n  \".mts\",\n  \".mjs\",\n  \".cts\",\n  \".cjs\",\n] as const;\n\nexport function resolveFarmIsolatedClientHydrationMode(\n  mode: FarmIsolatedClientHydrationMode | undefined,\n  options: {\n    serverComponents?: boolean;\n    hasUnsupportedIntegrationProvider?: boolean;\n  } = {},\n): FarmIsolatedClientHydrationMode {\n  if (options.serverComponents) return \"off\";\n  if (mode === \"enabled\" && options.hasUnsupportedIntegrationProvider) return \"off\";\n  return mode ?? \"off\";\n}\n\nexport function hasUseClientDirective(content: string | null): boolean {\n  if (!content) {\n    return false;\n  }\n\n  // Fast path: directive at the very start of the file.\n  const normalized = content.trimStart();\n  if (normalized.startsWith(\"'use client'\") || normalized.startsWith('\"use client\"')) {\n    return true;\n  }\n  if (!normalized.includes(\"use client\")) {\n    return false;\n  }\n\n  // Directive-prologue semantics allow comments and other directives (e.g.\n  // \"use strict\") before \"use client\". Scan the leading string-literal\n  // statements with the comment-aware tokenizer.\n  for (const token of tokenizeModuleSource(content)) {\n    if (token.kind === \"string\") {\n      if (token.value === \"use client\") {\n        return true;\n      }\n      continue;\n    }\n    if (token.kind === \"punctuation\" && token.value === \";\") {\n      continue;\n    }\n    return false;\n  }\n  return false;\n}\n\nexport function hasHydrateExport(content: string | null): boolean {\n  if (!content) {\n    return false;\n  }\n  if (/\\bexport\\s+const\\s+hydrate\\s*=\\s*true\\b/.test(content)) {\n    return true;\n  }\n  // Export lists may carry several specifiers and as-renames; the module\n  // opts in when any specifier's *exported* name is hydrate.\n  for (const match of content.matchAll(/\\bexport\\s*\\{([^}]*)\\}/g)) {\n    for (const specifier of match[1].split(\",\")) {\n      const parts = specifier.trim().split(/\\s+as\\s+/);\n      const exportedName = (parts[1] ?? parts[0])?.trim();\n      if (exportedName === \"hydrate\") {\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\ninterface ModuleSourceToken {\n  kind: \"identifier\" | \"string\" | \"punctuation\";\n  value: string;\n  line: number;\n}\n\nconst REGEXP_PREFIX_PUNCTUATION = new Set([\n  \"(\",\n  \"[\",\n  \"{\",\n  \",\",\n  \";\",\n  \":\",\n  \"=\",\n  \"!\",\n  \"?\",\n  \"&\",\n  \"|\",\n  \"+\",\n  \"-\",\n  \"*\",\n  \"%\",\n  \"^\",\n  \"~\",\n  \">\",\n]);\nconst REGEXP_PREFIX_KEYWORDS = new Set([\n  \"await\",\n  \"case\",\n  \"delete\",\n  \"do\",\n  \"else\",\n  \"in\",\n  \"instanceof\",\n  \"new\",\n  \"of\",\n  \"return\",\n  \"throw\",\n  \"typeof\",\n  \"void\",\n  \"yield\",\n]);\n\nfunction canStartRegularExpression(previous: ModuleSourceToken | undefined): boolean {\n  if (!previous) return true;\n  return previous.kind === \"identifier\"\n    ? REGEXP_PREFIX_KEYWORDS.has(previous.value)\n    : REGEXP_PREFIX_PUNCTUATION.has(previous.value);\n}\n\nfunction skipRegularExpression(content: string, startIndex: number): number | null {\n  let index = startIndex + 1;\n  let inCharacterClass = false;\n\n  while (index < content.length) {\n    const character = content[index];\n    if (character === \"\\n\" || character === \"\\r\") return null;\n    if (character === \"\\\\\") {\n      index += 2;\n      continue;\n    }\n    if (character === \"[\") {\n      inCharacterClass = true;\n      index++;\n      continue;\n    }\n    if (character === \"]\" && inCharacterClass) {\n      inCharacterClass = false;\n      index++;\n      continue;\n    }\n    if (character === \"/\" && !inCharacterClass) {\n      index++;\n      while (index < content.length && /[A-Za-z]/.test(content[index])) index++;\n      return index;\n    }\n    index++;\n  }\n\n  return null;\n}\n\nfunction tokenizeModuleSource(content: string): ModuleSourceToken[] {\n  const tokens: ModuleSourceToken[] = [];\n  let index = 0;\n  let line = 1;\n\n  while (index < content.length) {\n    const character = content[index];\n    if (/\\s/.test(character)) {\n      if (character === \"\\n\") line++;\n      index++;\n      continue;\n    }\n\n    if (character === \"/\" && content[index + 1] === \"/\") {\n      index += 2;\n      while (index < content.length && content[index] !== \"\\n\") index++;\n      continue;\n    }\n    if (character === \"/\" && content[index + 1] === \"*\") {\n      index += 2;\n      while (index < content.length) {\n        if (content[index] === \"\\n\") line++;\n        if (content[index] === \"*\" && content[index + 1] === \"/\") {\n          index += 2;\n          break;\n        }\n        index++;\n      }\n      continue;\n    }\n\n    if (character === \"/\" && canStartRegularExpression(tokens[tokens.length - 1])) {\n      const endIndex = skipRegularExpression(content, index);\n      if (endIndex !== null) {\n        index = endIndex;\n        continue;\n      }\n    }\n\n    if (character === '\"' || character === \"'\") {\n      const quote = character;\n      const tokenLine = line;\n      let value = \"\";\n      index++;\n      while (index < content.length) {\n        const next = content[index];\n        if (next === \"\\\\\") {\n          value += next;\n          if (index + 1 < content.length) value += content[index + 1];\n          index += 2;\n          continue;\n        }\n        if (next === quote) {\n          index++;\n          break;\n        }\n        if (next === \"\\n\") line++;\n        value += next;\n        index++;\n      }\n      tokens.push({ kind: \"string\", value, line: tokenLine });\n      continue;\n    }\n\n    if (character === \"`\") {\n      index++;\n      while (index < content.length) {\n        const next = content[index];\n        if (next === \"\\\\\") {\n          index += 2;\n          continue;\n        }\n        if (next === \"`\") {\n          index++;\n          break;\n        }\n        if (next === \"\\n\") line++;\n        index++;\n      }\n      continue;\n    }\n\n    if (/[A-Za-z_$]/.test(character)) {\n      const start = index++;\n      while (index < content.length && /[\\w$]/.test(content[index])) index++;\n      tokens.push({ kind: \"identifier\", value: content.slice(start, index), line });\n      continue;\n    }\n\n    tokens.push({ kind: \"punctuation\", value: character, line });\n    index++;\n  }\n\n  return tokens;\n}\n\nfunction isIslandExportStart(tokens: ModuleSourceToken[], index: number): boolean {\n  const token = tokens[index];\n  const previous = tokens[index - 1];\n  const startsStatement =\n    !previous ||\n    previous.value === \";\" ||\n    previous.value === \"{\" ||\n    previous.value === \"}\" ||\n    token.line > previous.line;\n  return (\n    startsStatement &&\n    token.value === \"export\" &&\n    tokens[index + 1]?.value === \"const\" &&\n    tokens[index + 2]?.value === \"island\"\n  );\n}\n\nexport function getIslandStrategyExport(content: string | null): FarmIslandStrategy | null {\n  if (!content) return null;\n\n  const tokens = tokenizeModuleSource(content);\n  for (let index = 0; index < tokens.length - 2; index++) {\n    if (!isIslandExportStart(tokens, index)) continue;\n\n    let valueIndex = index + 3;\n    if (tokens[valueIndex]?.value === \":\") {\n      while (valueIndex < tokens.length && tokens[valueIndex].value !== \"=\") valueIndex++;\n    }\n    if (tokens[valueIndex]?.value !== \"=\") break;\n    valueIndex++;\n\n    const literal = tokens[valueIndex];\n    if (!literal || literal.kind !== \"string\" || !isFarmIslandStrategy(literal.value)) break;\n\n    let trailingIndex = valueIndex + 1;\n    if (tokens[trailingIndex]?.value === \"as\" && tokens[trailingIndex + 1]?.value === \"const\") {\n      trailingIndex += 2;\n    }\n    const trailing = tokens[trailingIndex];\n    if (trailing && trailing.value !== \";\" && trailing.line === literal.line) break;\n    return literal.value;\n  }\n\n  if (tokens.some((_token, index) => isIslandExportStart(tokens, index))) {\n    throw new Error(\n      'Farm island configuration must be a static \"load\", \"interaction\", \"visible\", or \"idle\" string literal.',\n    );\n  }\n\n  return null;\n}\n\nexport function stripUseClientDirective(content: string): string {\n  // Comments (and other directives) may precede \"use client\"; keep them and\n  // remove only the directive itself.\n  return content.replace(\n    /^((?:\\s|\\/\\/[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/|(?:\"[^\"\\n]*\"|'[^'\\n]*')\\s*;?)*)([\"'])use client\\2\\s*;?\\s*/,\n    \"$1\",\n  );\n}\n\n/**\n * Best-effort static detection of an async default export, e.g.\n * `export default async function Page() {}`. Covers direct async\n * function/arrow default exports and `export default X` where `X` is a local\n * `async function X` or `X = async ...` declaration. Wrapped exports such as\n * `export default withAuth(Page)` cannot be resolved statically; the client\n * runtime guards against those at hydration time.\n */\nexport function hasAsyncDefaultExport(content: string | null): boolean {\n  if (!content) return false;\n\n  const tokens = tokenizeModuleSource(content);\n  for (let index = 0; index < tokens.length - 2; index++) {\n    const token = tokens[index];\n    if (token.kind !== \"identifier\" || token.value !== \"export\") continue;\n    if (tokens[index - 1]?.value === \".\") continue;\n    if (tokens[index + 1]?.value !== \"default\") continue;\n\n    const exported = tokens[index + 2];\n    if (exported.kind === \"identifier\" && exported.value === \"async\") {\n      return true;\n    }\n    if (\n      exported.kind === \"identifier\" &&\n      ![\"function\", \"class\"].includes(exported.value) &&\n      tokens[index + 3]?.value !== \"(\" &&\n      isAsyncLocalDeclaration(tokens, exported.value)\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction isAsyncLocalDeclaration(tokens: ModuleSourceToken[], name: string): boolean {\n  for (let index = 0; index < tokens.length - 2; index++) {\n    if (\n      tokens[index].value === \"async\" &&\n      tokens[index + 1]?.value === \"function\" &&\n      tokens[index + 2]?.value === name\n    ) {\n      return true;\n    }\n    if (\n      tokens[index].value === name &&\n      tokens[index + 1]?.value === \"=\" &&\n      tokens[index + 2]?.value === \"async\"\n    ) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction parseClientModuleMetadata(\n  content: string | null,\n  inspectIslandExport: boolean,\n): ParsedClientModuleMetadata {\n  if (!content) {\n    return {\n      isClientComponent: false,\n      hasHydrateExport: false,\n      islandStrategy: null,\n    };\n  }\n\n  const isClientComponent = hasUseClientDirective(content);\n  const hasHydrate = hasHydrateExport(content);\n  return {\n    isClientComponent,\n    hasHydrateExport: hasHydrate,\n    islandStrategy:\n      inspectIslandExport || isClientComponent || hasHydrate\n        ? getIslandStrategyExport(content)\n        : null,\n  };\n}\n\nexport function getClientModuleMetadata(modulePath: string, root?: string): ClientModuleMetadata {\n  const resolvedPath = resolveModuleSourcePath(modulePath, root);\n  return inspectClientModuleMetadata(resolvedPath, root, new Set(), true);\n}\n\n/**\n * Resolve hydration ownership without changing the legacy metadata contract.\n * The old metadata remains the conservative fallback; only an enabled and\n * completely supported graph moves ownership to leaf client modules.\n */\nexport function getClientModuleHydrationPlan(\n  modulePath: string,\n  root: string | undefined,\n  mode: FarmIsolatedClientHydrationMode = \"off\",\n): ClientModuleHydrationPlan {\n  const metadata = getClientModuleMetadata(modulePath, root);\n  const resolvedPath = resolveModuleSourcePath(modulePath, root);\n  const content = readIfExists(resolvedPath ?? \"\");\n  const parsed = parseClientModuleMetadata(content, true);\n  const emptyPlan = (\n    fallbackReason?: string,\n    costGuardExceeded = false,\n    estimatedIsolatedRootCount = 0,\n  ): ClientModuleHydrationPlan => ({\n    ...metadata,\n    mode,\n    legacyShouldHydrate: metadata.shouldHydrate,\n    legacyIslandStrategy: metadata.islandStrategy,\n    estimatedIsolatedRootCount,\n    isolatedHydrationEligible: false,\n    hasIsolatedClientBoundaries: false,\n    isolatedBoundaries: [],\n    ...(costGuardExceeded ? { costGuardExceeded: true as const } : {}),\n    ...(fallbackReason ? { fallbackReason } : {}),\n  });\n\n  if (mode === \"off\") return emptyPlan();\n  if (!resolvedPath) return emptyPlan(\"the owner source could not be resolved\");\n  if (parsed.isClientComponent) {\n    return emptyPlan(\"the owner is already a client component\");\n  }\n  if (parsed.hasHydrateExport) {\n    return emptyPlan(\"the owner explicitly exports `hydrate = true`\");\n  }\n\n  const inspection = collectIsolatedClientBoundaries(resolvedPath, root);\n  if (inspection.boundaries.length === 0) {\n    return emptyPlan(inspection.fallbackReason);\n  }\n  if (inspection.fallbackReason) {\n    return emptyPlan(\n      inspection.fallbackReason,\n      inspection.costGuardExceeded,\n      inspection.estimatedBoundaryCount,\n    );\n  }\n  const boundaryLimit = isolatedHydrationBoundaryLimit();\n  if (inspection.estimatedBoundaryCount > boundaryLimit) {\n    return emptyPlan(\n      `the client graph can create ${inspection.estimatedBoundaryCount} isolated roots, above the measured limit of ${boundaryLimit}`,\n      true,\n      inspection.estimatedBoundaryCount,\n    );\n  }\n\n  const enabled = mode === \"enabled\";\n  return {\n    ...metadata,\n    shouldHydrate: enabled ? false : metadata.shouldHydrate,\n    islandStrategy: enabled ? null : metadata.islandStrategy,\n    mode,\n    legacyShouldHydrate: metadata.shouldHydrate,\n    legacyIslandStrategy: metadata.islandStrategy,\n    estimatedIsolatedRootCount: inspection.estimatedBoundaryCount,\n    isolatedHydrationEligible: true,\n    hasIsolatedClientBoundaries: enabled,\n    isolatedBoundaries: inspection.boundaries,\n  };\n}\n\ninterface FarmIsolatedHydrationRoutePlan {\n  mode: FarmIsolatedClientHydrationMode;\n  shouldHydrate: boolean;\n  islandStrategy: FarmIslandStrategy | null;\n  legacyShouldHydrate: boolean;\n  legacyIslandStrategy: FarmIslandStrategy | null;\n  estimatedIsolatedRootCount: number;\n  hasIsolatedClientBoundaries: boolean;\n  isolatedBoundaries: IsolatedClientBoundaryReference[];\n  costGuardExceeded?: true;\n  fallbackReason?: string;\n}\n\ninterface FarmIsolatedHydrationRouteOwner {\n  pattern: string;\n  depth: number;\n  metadata: FarmIsolatedHydrationRoutePlan;\n}\n\nfunction restoreRouteWideHydration(\n  metadata: FarmIsolatedHydrationRoutePlan,\n  fallbackReason?: string,\n): void {\n  metadata.shouldHydrate = metadata.legacyShouldHydrate;\n  metadata.islandStrategy = metadata.legacyIslandStrategy;\n  metadata.hasIsolatedClientBoundaries = false;\n  metadata.isolatedBoundaries = [];\n  if (fallbackReason) {\n    metadata.costGuardExceeded = true;\n    metadata.fallbackReason = fallbackReason;\n  }\n}\n\n/** @internal Applies the measured root budget to each complete layout and page chain. */\nexport function enforceFarmIsolatedHydrationRouteBudget(\n  layouts: FarmIsolatedHydrationRouteOwner[],\n  routes: FarmIsolatedHydrationRouteOwner[],\n  layoutAppliesToRoute: (layoutPattern: string, routePattern: string) => boolean,\n): void {\n  const boundaryLimit = isolatedHydrationBoundaryLimit();\n  const sortedLayouts = [...layouts].sort((left, right) => left.depth - right.depth);\n\n  for (const route of routes) {\n    if (route.metadata.mode !== \"enabled\") continue;\n    const applicableLayouts = sortedLayouts.filter((layout) =>\n      layoutAppliesToRoute(layout.pattern, route.pattern),\n    );\n    if (applicableLayouts.some((layout) => layout.metadata.shouldHydrate)) continue;\n\n    const layoutRootCount = applicableLayouts.reduce(\n      (count, layout) =>\n        count +\n        (layout.metadata.hasIsolatedClientBoundaries\n          ? layout.metadata.estimatedIsolatedRootCount\n          : 0),\n      0,\n    );\n    const routeRootCount = route.metadata.hasIsolatedClientBoundaries\n      ? route.metadata.estimatedIsolatedRootCount\n      : 0;\n    const totalRootCount = layoutRootCount + routeRootCount;\n    if (totalRootCount <= boundaryLimit) continue;\n\n    let accumulatedLayoutRoots = 0;\n    const overflowingLayout = applicableLayouts.find((layout) => {\n      if (layout.metadata.hasIsolatedClientBoundaries) {\n        accumulatedLayoutRoots += layout.metadata.estimatedIsolatedRootCount;\n      }\n      return accumulatedLayoutRoots > boundaryLimit;\n    });\n    const fallbackReason = `the matched route ${route.pattern} can create ${totalRootCount} isolated roots, above the measured limit of ${boundaryLimit}`;\n\n    if (overflowingLayout) {\n      restoreRouteWideHydration(overflowingLayout.metadata, fallbackReason);\n    } else if (route.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(route.metadata, fallbackReason);\n    }\n  }\n\n  for (const layout of sortedLayouts) {\n    const hasRouteWideAncestor = sortedLayouts.some(\n      (ancestor) =>\n        ancestor !== layout &&\n        ancestor.depth < layout.depth &&\n        ancestor.metadata.shouldHydrate &&\n        layoutAppliesToRoute(ancestor.pattern, layout.pattern),\n    );\n    if (hasRouteWideAncestor && layout.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(layout.metadata);\n    }\n  }\n\n  for (const route of routes) {\n    const hasRouteWideLayout = sortedLayouts.some(\n      (layout) =>\n        layout.metadata.shouldHydrate && layoutAppliesToRoute(layout.pattern, route.pattern),\n    );\n    if (hasRouteWideLayout && route.metadata.hasIsolatedClientBoundaries) {\n      restoreRouteWideHydration(route.metadata);\n    }\n  }\n}\n\n/**\n * The first compiler pass intentionally accepts only statically named React\n * component exports. A rejected module retains route-wide hydration.\n */\nexport function isIsolatableClientBoundarySource(content: string | null): boolean {\n  if (!content || !hasUseClientDirective(content)) return false;\n  if (/\\bexport\\s*\\{/.test(content) || /\\bexport\\s*\\*/.test(content)) return false;\n  return (\n    /\\bexport\\s+default\\s+(?!(?:type|interface)\\b)/.test(content) ||\n    /\\bexport\\s+(?:async\\s+)?function\\s+[A-Z][$\\w]*/.test(content) ||\n    /\\bexport\\s+(?:const|let|var|class)\\s+[A-Z][$\\w]*/.test(content)\n  );\n}\n\nfunction getStaticImportBindings(content: string | null): Map<string, string[]> {\n  const bindings = new Map<string, string[]>();\n  if (!content) return bindings;\n  const tokens = tokenizeModuleSource(content);\n\n  for (let index = 0; index < tokens.length; index++) {\n    if (tokens[index].value !== \"import\" || tokens[index - 1]?.value === \".\") continue;\n    const first = tokens[index + 1];\n    if (!first || first.value === \"type\" || first.value === \"(\" || first.kind === \"string\") {\n      continue;\n    }\n\n    let fromIndex = -1;\n    for (let cursor = index + 1; cursor < tokens.length; cursor++) {\n      if (tokens[cursor].value === \";\") break;\n      if (tokens[cursor].value === \"from\" && tokens[cursor + 1]?.kind === \"string\") {\n        fromIndex = cursor;\n        break;\n      }\n    }\n    if (fromIndex === -1) continue;\n    const specifier = tokens[fromIndex + 1].value;\n    const clause = tokens.slice(index + 1, fromIndex);\n    const localNames: string[] = [];\n\n    if (clause[0]?.kind === \"identifier\" && clause[0].value !== \"type\") {\n      localNames.push(clause[0].value);\n    }\n    const namespaceAs = clause.findIndex(\n      (token, clauseIndex) => token.value === \"*\" && clause[clauseIndex + 1]?.value === \"as\",\n    );\n    if (namespaceAs !== -1 && clause[namespaceAs + 2]?.kind === \"identifier\") {\n      localNames.push(clause[namespaceAs + 2].value);\n    }\n\n    const openingBrace = clause.findIndex((token) => token.value === \"{\");\n    const closingBrace = clause.findIndex(\n      (token, clauseIndex) => clauseIndex > openingBrace && token.value === \"}\",\n    );\n    if (openingBrace !== -1 && closingBrace !== -1) {\n      let entryStart = openingBrace + 1;\n      for (let cursor = entryStart; cursor <= closingBrace; cursor++) {\n        if (cursor !== closingBrace && clause[cursor]?.value !== \",\") continue;\n        const entry = clause.slice(entryStart, cursor).filter((token) => token.value !== \"type\");\n        const asIndex = entry.findIndex((token) => token.value === \"as\");\n        const local = asIndex === -1 ? entry[0] : entry[asIndex + 1];\n        if (local?.kind === \"identifier\") localNames.push(local.value);\n        entryStart = cursor + 1;\n      }\n    }\n\n    bindings.set(\n      specifier,\n      Array.from(new Set([...(bindings.get(specifier) ?? []), ...localNames])),\n    );\n  }\n\n  return bindings;\n}\n\n/**\n * Elements whose content model the HTML parser enforces. A boundary marker\n * emitted inside one of these is relocated or ignored before any script runs:\n * in a table the marker and its row are foster-parented out of the table, in a\n * select the options stop being direct children and the control renders empty,\n * and inside svg the marker is created in the SVG namespace as an unknown\n * element whose children never render. RFC 0001 requires these to take the\n * route-wide fallback.\n */\nconst PARSER_SENSITIVE_JSX_CONTAINERS = new Set([\n  \"table\",\n  \"thead\",\n  \"tbody\",\n  \"tfoot\",\n  \"tr\",\n  \"select\",\n  \"optgroup\",\n  \"svg\",\n]);\n\n/**\n * Names a parser-sensitive element that encloses a use of one of the bindings,\n * or undefined when every use is in ordinary flow content.\n *\n * Ambiguity resolves toward reporting a container: the caller turns a hit into\n * the complete route-wide fallback, which is always correct, while a miss would\n * leave the silent DOM corruption in place.\n */\nfunction findParserSensitiveJsxContainer(\n  content: string | null,\n  localBindings: string[],\n): string | undefined {\n  if (!content || localBindings.length === 0) return undefined;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  const openDepth = new Map<string, number>();\n\n  const isSelfClosing = (openingIndex: number): boolean => {\n    for (let index = openingIndex; index < tokens.length; index++) {\n      if (tokens[index].value === \">\") return tokens[index - 1]?.value === \"/\";\n    }\n    return false;\n  };\n\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value !== \"<\") continue;\n\n    if (tokens[index + 1].value === \"/\") {\n      const closing = tokens[index + 2]?.value;\n      if (closing && openDepth.has(closing)) {\n        openDepth.set(closing, Math.max(0, (openDepth.get(closing) ?? 0) - 1));\n      }\n      continue;\n    }\n\n    const tag = tokens[index + 1].value;\n    if (names.has(tag)) {\n      for (const [container, depth] of openDepth) {\n        if (depth > 0) return container;\n      }\n      continue;\n    }\n    if (PARSER_SENSITIVE_JSX_CONTAINERS.has(tag) && !isSelfClosing(index)) {\n      openDepth.set(tag, (openDepth.get(tag) ?? 0) + 1);\n    }\n  }\n\n  return undefined;\n}\n\nfunction countStaticJsxUses(content: string | null, localBindings: string[]): number {\n  if (!content || localBindings.length === 0) return 0;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  let count = 0;\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value === \"<\" && names.has(tokens[index + 1].value)) count++;\n  }\n  return count;\n}\n\nfunction findMatchingToken(\n  tokens: ModuleSourceToken[],\n  openingIndex: number,\n  opening: string,\n  closing: string,\n): number {\n  let depth = 0;\n  for (let index = openingIndex; index < tokens.length; index++) {\n    if (tokens[index].value === opening) depth++;\n    if (tokens[index].value !== closing) continue;\n    depth--;\n    if (depth === 0) return index;\n  }\n  return tokens.length - 1;\n}\n\nfunction containsClientJsx(\n  tokens: ModuleSourceToken[],\n  start: number,\n  end: number,\n  clientBindings: Set<string>,\n): boolean {\n  for (let index = start; index < end; index++) {\n    if (tokens[index].value === \"<\" && clientBindings.has(tokens[index + 1]?.value)) return true;\n  }\n  return false;\n}\n\nfunction findStatementEnd(tokens: ModuleSourceToken[], start: number): number {\n  let parentheses = 0;\n  let brackets = 0;\n  let braces = 0;\n  const statementStarters = new Set([\n    \"class\",\n    \"const\",\n    \"export\",\n    \"function\",\n    \"import\",\n    \"let\",\n    \"var\",\n  ]);\n  for (let index = start; index < tokens.length; index++) {\n    const value = tokens[index].value;\n    if (\n      index > start &&\n      parentheses === 0 &&\n      brackets === 0 &&\n      braces === 0 &&\n      tokens[index].line > tokens[index - 1].line &&\n      statementStarters.has(value)\n    ) {\n      return index;\n    }\n    if (value === \";\" && parentheses === 0 && brackets === 0 && braces === 0) return index;\n    if (value === \"(\") parentheses++;\n    if (value === \")\") parentheses--;\n    if (value === \"[\") brackets++;\n    if (value === \"]\") brackets--;\n    if (value === \"{\") braces++;\n    if (value === \"}\") braces--;\n  }\n  return tokens.length;\n}\n\nfunction getClientRenderingHelpers(\n  tokens: ModuleSourceToken[],\n  clientBindings: Set<string>,\n): Set<string> {\n  const helperBodies = new Map<string, [start: number, end: number]>();\n  for (let index = 0; index < tokens.length; index++) {\n    let helperName: string | undefined;\n    let bodyStart = -1;\n    let bodyEnd = -1;\n\n    if (tokens[index].value === \"function\" && tokens[index + 1]?.kind === \"identifier\") {\n      helperName = tokens[index + 1].value;\n      const parametersStart = tokens.findIndex(\n        (token, tokenIndex) => tokenIndex > index + 1 && token.value === \"(\",\n      );\n      const parametersEnd =\n        parametersStart === -1 ? index + 1 : findMatchingToken(tokens, parametersStart, \"(\", \")\");\n      bodyStart = tokens.findIndex(\n        (token, tokenIndex) => tokenIndex > parametersEnd && token.value === \"{\",\n      );\n      if (bodyStart !== -1) bodyEnd = findMatchingToken(tokens, bodyStart, \"{\", \"}\");\n    } else if (\n      (tokens[index].value === \"const\" ||\n        tokens[index].value === \"let\" ||\n        tokens[index].value === \"var\") &&\n      tokens[index + 1]?.kind === \"identifier\"\n    ) {\n      helperName = tokens[index + 1].value;\n      let assignmentIndex = -1;\n      let arrowIndex = -1;\n      for (let cursor = index + 2; cursor < tokens.length; cursor++) {\n        if (tokens[cursor].value === \";\") break;\n        if (assignmentIndex === -1 && tokens[cursor].value === \"=\") assignmentIndex = cursor;\n        if (tokens[cursor].value === \"=\" && tokens[cursor + 1]?.value === \">\") {\n          arrowIndex = cursor;\n          break;\n        }\n      }\n      if (arrowIndex !== -1) {\n        bodyStart = arrowIndex + 2;\n        bodyEnd =\n          tokens[bodyStart]?.value === \"{\"\n            ? findMatchingToken(tokens, bodyStart, \"{\", \"}\")\n            : findStatementEnd(tokens, bodyStart);\n      } else if (assignmentIndex !== -1) {\n        bodyStart = assignmentIndex + 1;\n        bodyEnd = findStatementEnd(tokens, bodyStart);\n      }\n    }\n\n    if (helperName && bodyStart !== -1 && bodyEnd !== -1) {\n      helperBodies.set(helperName, [bodyStart, bodyEnd]);\n    }\n  }\n\n  const helpers = new Set<string>();\n  let addedHelper = true;\n  while (addedHelper) {\n    addedHelper = false;\n    for (const [helperName, [bodyStart, bodyEnd]] of helperBodies) {\n      if (helpers.has(helperName)) continue;\n      const rendersClientBoundary =\n        containsClientJsx(tokens, bodyStart, bodyEnd, clientBindings) ||\n        tokens.slice(bodyStart, bodyEnd).some((token) => helpers.has(token.value));\n      if (!rendersClientBoundary) continue;\n      helpers.add(helperName);\n      addedHelper = true;\n    }\n  }\n  return helpers;\n}\n\n/**\n * True when a boundary is handed a React element, as JSX children or as an\n * element-valued prop.\n *\n * Boundary props cross to the browser as JSON, and an element cannot be\n * serialized. Without this check the SSR wrapper drops the marker for that\n * boundary and the component renders as ordinary server markup that nothing\n * ever hydrates, leaving an interactive-looking widget permanently dead with\n * no browser-visible diagnostic. String and number children serialize fine and\n * are deliberately not flagged.\n */\nfunction passesElementValuedProps(content: string | null, localBindings: string[]): boolean {\n  if (!content || localBindings.length === 0) return false;\n  const names = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n\n  for (let index = 0; index < tokens.length - 1; index++) {\n    if (tokens[index].value !== \"<\" || !names.has(tokens[index + 1].value)) continue;\n    const name = tokens[index + 1].value;\n\n    // Walk the opening tag, watching for an element inside an attribute\n    // expression such as icon={<Icon />}.\n    let cursor = index + 2;\n    let braceDepth = 0;\n    let selfClosing = false;\n    for (; cursor < tokens.length; cursor++) {\n      const value = tokens[cursor].value;\n      if (value === \"{\") braceDepth++;\n      else if (value === \"}\") braceDepth--;\n      else if (value === \"<\" && braceDepth > 0) return true;\n      else if (value === \">\" && braceDepth === 0) {\n        selfClosing = tokens[cursor - 1]?.value === \"/\";\n        break;\n      }\n    }\n    if (selfClosing || cursor >= tokens.length) continue;\n\n    // The first tag after the opening one decides it: the boundary's own\n    // closing tag means no element children, anything else is an element child.\n    for (let child = cursor + 1; child < tokens.length; child++) {\n      if (tokens[child].value !== \"<\") continue;\n      const closesBoundary = tokens[child + 1]?.value === \"/\" && tokens[child + 2]?.value === name;\n      if (!closesBoundary) return true;\n      break;\n    }\n  }\n\n  return false;\n}\n\nfunction hasDynamicJsxCardinality(content: string | null, localBindings: string[]): boolean {\n  if (!content || localBindings.length === 0) return false;\n  const clientBindings = new Set(localBindings);\n  const tokens = tokenizeModuleSource(content);\n  const renderingHelpers = getClientRenderingHelpers(tokens, clientBindings);\n  const containsDynamicRenderer = (start: number, end: number) =>\n    containsClientJsx(tokens, start, end, clientBindings) ||\n    tokens.slice(start, end).some((token) => renderingHelpers.has(token.value));\n\n  for (let index = 0; index < tokens.length; index++) {\n    let callStart = -1;\n    if (\n      tokens[index].value === \".\" &&\n      (tokens[index + 1]?.value === \"map\" || tokens[index + 1]?.value === \"flatMap\") &&\n      tokens[index + 2]?.value === \"(\"\n    ) {\n      callStart = index + 2;\n    } else if (\n      tokens[index].value === \"Array\" &&\n      tokens[index + 1]?.value === \".\" &&\n      tokens[index + 2]?.value === \"from\" &&\n      tokens[index + 3]?.value === \"(\"\n    ) {\n      callStart = index + 3;\n    }\n    if (callStart !== -1) {\n      const callEnd = findMatchingToken(tokens, callStart, \"(\", \")\");\n      if (containsDynamicRenderer(callStart + 1, callEnd)) return true;\n      index = callEnd;\n      continue;\n    }\n\n    if (\n      (tokens[index].value === \"for\" || tokens[index].value === \"while\") &&\n      tokens[index + 1]?.value === \"(\"\n    ) {\n      const conditionEnd = findMatchingToken(tokens, index + 1, \"(\", \")\");\n      const bodyStart = conditionEnd + 1;\n      const bodyEnd =\n        tokens[bodyStart]?.value === \"{\"\n          ? findMatchingToken(tokens, bodyStart, \"{\", \"}\")\n          : tokens.findIndex((token, tokenIndex) => tokenIndex > bodyStart && token.value === \";\");\n      if (containsDynamicRenderer(bodyStart, bodyEnd === -1 ? tokens.length : bodyEnd)) return true;\n    }\n  }\n\n  return false;\n}\n\nfunction collectIsolatedClientBoundaries(\n  ownerPath: string,\n  root: string | undefined,\n): {\n  boundaries: IsolatedClientBoundaryReference[];\n  estimatedBoundaryCount: number;\n  costGuardExceeded?: boolean;\n  fallbackReason?: string;\n} {\n  const boundaries = new Map<string, IsolatedClientBoundaryReference>();\n  const estimates = new Map<string, number>();\n  const visiting = new Set<string>();\n  let fallbackReason: string | undefined;\n  let costGuardExceeded = false;\n  const projectRoot = root ? path.resolve(root) : undefined;\n\n  const visit = (moduleSourcePath: string): number => {\n    if (fallbackReason) return 0;\n    const cached = estimates.get(moduleSourcePath);\n    if (cached !== undefined) return cached;\n    if (visiting.has(moduleSourcePath)) return 0;\n    visiting.add(moduleSourcePath);\n    const content = readIfExists(moduleSourcePath);\n    const parsed = parseClientModuleMetadata(content, false);\n\n    if (parsed.isClientComponent) {\n      if (projectRoot && !path.resolve(moduleSourcePath).startsWith(`${projectRoot}${path.sep}`)) {\n        fallbackReason = `client boundary ${moduleSourcePath} is outside the application root`;\n        return 0;\n      }\n      if (!isIsolatableClientBoundarySource(content)) {\n        fallbackReason = `client boundary ${moduleSourcePath} uses an unsupported export shape`;\n        return 0;\n      }\n      boundaries.set(moduleSourcePath, {\n        modulePath: moduleSourcePath,\n        islandStrategy: parsed.islandStrategy ?? \"load\",\n      });\n      estimates.set(moduleSourcePath, 1);\n      visiting.delete(moduleSourcePath);\n      return 1;\n    }\n\n    if (parsed.hasHydrateExport) {\n      fallbackReason = `imported module ${moduleSourcePath} explicitly exports hydrate = true`;\n      return 0;\n    }\n\n    const importedBindings = getStaticImportBindings(content);\n    let estimatedBoundaryCount = 0;\n    for (const specifier of new Set(getImportSpecifiers(content))) {\n      const importedPath = resolveImportedModuleSourcePath(moduleSourcePath, specifier, root);\n      if (!importedPath) continue;\n      if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n        const packageMetadata = inspectPackageClientBoundary(importedPath, root, new Set());\n        if (packageMetadata.shouldHydrate) {\n          fallbackReason = `package client boundary ${specifier} cannot yet be isolated`;\n          return 0;\n        }\n        continue;\n      }\n      const importedBoundaryCount = visit(importedPath);\n      if (fallbackReason || importedBoundaryCount === 0) continue;\n      const localBindings = importedBindings.get(specifier) ?? [];\n      const staticUses = countStaticJsxUses(content, localBindings);\n      if (staticUses > 0) {\n        const container = findParserSensitiveJsxContainer(content, localBindings);\n        if (container) {\n          fallbackReason = `the client boundary imported from ${specifier} renders inside <${container}>, where the HTML parser relocates its hydration marker`;\n          return 0;\n        }\n        if (passesElementValuedProps(content, localBindings)) {\n          fallbackReason = `the client boundary imported from ${specifier} receives React elements, which cannot cross the boundary as serialized props`;\n          return 0;\n        }\n      }\n      if (staticUses > 0 && hasDynamicJsxCardinality(content, localBindings)) {\n        fallbackReason = `the client boundary count imported from ${specifier} is data-dependent`;\n        costGuardExceeded = true;\n        return 0;\n      }\n      estimatedBoundaryCount += importedBoundaryCount * Math.max(1, staticUses);\n    }\n\n    estimates.set(moduleSourcePath, estimatedBoundaryCount);\n    visiting.delete(moduleSourcePath);\n    return estimatedBoundaryCount;\n  };\n\n  const estimatedBoundaryCount = visit(ownerPath);\n  return {\n    boundaries: Array.from(boundaries.values()),\n    estimatedBoundaryCount,\n    costGuardExceeded,\n    fallbackReason,\n  };\n}\n\nexport function isClientComponentModule(modulePath: string, root?: string): boolean {\n  return getClientModuleMetadata(modulePath, root).isClientComponent;\n}\n\nexport function shouldHydrateModule(modulePath: string, root?: string): boolean {\n  return getClientModuleMetadata(modulePath, root).shouldHydrate;\n}\n\nfunction inspectClientModuleMetadata(\n  resolvedPath: string | null,\n  root: string | undefined,\n  visited: Set<string>,\n  inspectIslandExport: boolean,\n): ClientModuleMetadata {\n  if (!resolvedPath || visited.has(resolvedPath)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n    };\n  }\n\n  visited.add(resolvedPath);\n\n  const content = readIfExists(resolvedPath);\n  const parsed = parseClientModuleMetadata(content, inspectIslandExport);\n  if (parsed.isClientComponent) {\n    return {\n      isClientComponent: true,\n      shouldHydrate: true,\n      islandStrategy: parsed.islandStrategy ?? \"load\",\n    };\n  }\n\n  let importsClientBoundary = false;\n  let importedIslandStrategy: FarmIslandStrategy | null = null;\n  for (const specifier of getImportSpecifiers(content)) {\n    const importedPath = resolveImportedModuleSourcePath(resolvedPath, specifier, root);\n    const importedMetadata =\n      !specifier.startsWith(\".\") && !specifier.startsWith(\"/\")\n        ? inspectPackageClientBoundary(importedPath, root, visited)\n        : inspectClientModuleMetadata(importedPath, root, visited, false);\n    if (importedMetadata.isClientComponent || importedMetadata.shouldHydrate) {\n      importsClientBoundary = true;\n      if (importedIslandStrategy === null) {\n        importedIslandStrategy = importedMetadata.islandStrategy;\n      } else if (importedIslandStrategy !== importedMetadata.islandStrategy) {\n        // One route-level React root cannot honor multiple schedules safely.\n        // Fall back to eager hydration when its imported boundaries disagree.\n        importedIslandStrategy = \"load\";\n      }\n    }\n  }\n\n  const shouldHydrate = parsed.hasHydrateExport || importsClientBoundary;\n\n  // React cannot run an async component in a client root: hydrating the route\n  // module would throw, blank the server-rendered HTML, and re-run the page's\n  // data fetching in a loop. Keep async server pages server-only even when\n  // they import client components.\n  if (shouldHydrate && hasAsyncDefaultExport(content)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n      suppressedAsyncHydration: true,\n    };\n  }\n\n  return {\n    isClientComponent: false,\n    shouldHydrate,\n    islandStrategy: shouldHydrate\n      ? (parsed.islandStrategy ?? importedIslandStrategy ?? \"load\")\n      : null,\n  };\n}\n\nfunction inspectPackageClientBoundary(\n  resolvedPath: string | null,\n  root: string | undefined,\n  visited: Set<string>,\n): ClientModuleMetadata {\n  if (!resolvedPath || visited.has(resolvedPath)) {\n    return {\n      isClientComponent: false,\n      shouldHydrate: false,\n      islandStrategy: null,\n    };\n  }\n\n  visited.add(resolvedPath);\n  const content = readIfExists(resolvedPath);\n  const parsed = parseClientModuleMetadata(content, false);\n  let importsClientBoundary = false;\n  let importedIslandStrategy: FarmIslandStrategy | null = null;\n\n  // Package entry points commonly re-export their React implementation from a\n  // relative file. Follow only files inside that package entry graph: scanning\n  // bare dependencies here would incorrectly turn server package APIs into\n  // client boundaries because of unrelated transitive imports.\n  for (const specifier of getImportSpecifiers(content)) {\n    if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) continue;\n    const importedPath = resolveImportedModuleSourcePath(resolvedPath, specifier, root);\n    const importedMetadata = inspectPackageClientBoundary(importedPath, root, visited);\n    if (!importedMetadata.shouldHydrate) continue;\n    importsClientBoundary = true;\n    if (importedIslandStrategy === null) {\n      importedIslandStrategy = importedMetadata.islandStrategy;\n    } else if (importedIslandStrategy !== importedMetadata.islandStrategy) {\n      importedIslandStrategy = \"load\";\n    }\n  }\n\n  const shouldHydrate =\n    parsed.isClientComponent || parsed.hasHydrateExport || importsClientBoundary;\n  return {\n    isClientComponent: parsed.isClientComponent,\n    shouldHydrate,\n    islandStrategy: shouldHydrate\n      ? (parsed.islandStrategy ?? importedIslandStrategy ?? \"load\")\n      : null,\n  };\n}\n\nfunction getImportSpecifiers(content: string | null): string[] {\n  if (!content) return [];\n\n  const tokens = tokenizeModuleSource(content);\n  const matches = new Set<string>();\n  let braceDepth = 0;\n\n  for (let index = 0; index < tokens.length; index++) {\n    const keyword = tokens[index];\n    if (keyword.value === \"{\") {\n      braceDepth++;\n      continue;\n    }\n    if (keyword.value === \"}\") {\n      braceDepth = Math.max(0, braceDepth - 1);\n      continue;\n    }\n    if (braceDepth !== 0) continue;\n    if (keyword.kind !== \"identifier\" || ![\"import\", \"export\"].includes(keyword.value)) {\n      continue;\n    }\n\n    const previous = tokens[index - 1];\n    if (previous?.value === \".\") continue;\n\n    const first = tokens[index + 1];\n    if (!first || first.value === \"type\" || first.value === \"(\" || first.value === \".\") {\n      continue;\n    }\n\n    let specifier: string | undefined;\n    if (keyword.value === \"import\" && first.kind === \"string\") {\n      specifier = first.value;\n    } else {\n      if (keyword.value === \"export\" && first.value !== \"{\" && first.value !== \"*\") {\n        continue;\n      }\n\n      let fromIndex = -1;\n      for (let cursor = index + 1; cursor < tokens.length; cursor++) {\n        const token = tokens[cursor];\n        if (token.value === \";\") break;\n        if (token.value === \"from\" && tokens[cursor + 1]?.kind === \"string\") {\n          fromIndex = cursor;\n          break;\n        }\n      }\n      if (fromIndex === -1 || isTypeOnlyNamedClause(tokens, index + 1, fromIndex)) {\n        continue;\n      }\n      specifier = tokens[fromIndex + 1].value;\n    }\n\n    if (!specifier || specifier.startsWith(\"node:\") || specifier.includes(\"?\")) {\n      continue;\n    }\n    matches.add(specifier);\n  }\n\n  return Array.from(matches);\n}\n\nfunction isTypeOnlyNamedClause(\n  tokens: ModuleSourceToken[],\n  startIndex: number,\n  endIndex: number,\n): boolean {\n  if (tokens[startIndex]?.value !== \"{\") return false;\n\n  const closingBraceIndex = tokens.findIndex(\n    (token, index) => index > startIndex && index < endIndex && token.value === \"}\",\n  );\n  if (closingBraceIndex === -1) return false;\n\n  let entryStartsAt = startIndex + 1;\n  for (let index = entryStartsAt; index <= closingBraceIndex; index++) {\n    if (index !== closingBraceIndex && tokens[index]?.value !== \",\") continue;\n    const entry = tokens.slice(entryStartsAt, index);\n    if (entry.length > 0 && entry[0].value !== \"type\") return false;\n    entryStartsAt = index + 1;\n  }\n  return true;\n}\n\nfunction resolveImportedModuleSourcePath(\n  importerPath: string,\n  specifier: string,\n  root?: string,\n): string | null {\n  if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n    return resolvePackageModuleSourcePath(importerPath, specifier, root);\n  }\n\n  const candidates = new Set<string>();\n  const basePath = specifier.startsWith(\".\")\n    ? path.resolve(path.dirname(importerPath), specifier)\n    : root\n      ? path.resolve(root, specifier.replace(/^\\/+/, \"\"))\n      : path.resolve(specifier);\n\n  candidates.add(basePath);\n  return resolveSourceCandidate(candidates);\n}\n\nfunction resolvePackageModuleSourcePath(\n  importerPath: string,\n  specifier: string,\n  root?: string,\n): string | null {\n  const packageParts = specifier.split(\"/\");\n  const packageName = specifier.startsWith(\"@\")\n    ? packageParts.slice(0, 2).join(\"/\")\n    : packageParts[0];\n  const packageSubpath = packageParts.slice(packageName.startsWith(\"@\") ? 2 : 1).join(\"/\");\n  const packageDirectory = findPackageDirectory(importerPath, packageName, root);\n  if (!packageDirectory) return null;\n\n  const packageJsonPath = path.join(packageDirectory, \"package.json\");\n  const packageJson = readPackageJson(packageJsonPath);\n  const exportKey = packageSubpath ? `./${packageSubpath}` : \".\";\n  const exportTarget = resolvePackageExport(packageJson?.exports, exportKey);\n  const candidates = new Set<string>();\n\n  if (exportTarget?.startsWith(\"./\")) {\n    candidates.add(path.resolve(packageDirectory, exportTarget));\n  }\n  if (packageSubpath) {\n    candidates.add(path.join(packageDirectory, packageSubpath));\n  } else {\n    for (const entry of [packageJson?.browser, packageJson?.module, packageJson?.main]) {\n      if (typeof entry === \"string\") candidates.add(path.resolve(packageDirectory, entry));\n    }\n    candidates.add(path.join(packageDirectory, \"index\"));\n  }\n\n  return resolveSourceCandidate(candidates);\n}\n\nfunction findPackageDirectory(\n  importerPath: string,\n  packageName: string,\n  root?: string,\n): string | null {\n  const searchRoots = new Set<string>();\n  let current = path.dirname(importerPath);\n  while (true) {\n    searchRoots.add(current);\n    const parent = path.dirname(current);\n    if (parent === current) break;\n    current = parent;\n  }\n  if (root) {\n    current = path.resolve(root);\n    while (true) {\n      searchRoots.add(current);\n      const parent = path.dirname(current);\n      if (parent === current) break;\n      current = parent;\n    }\n  }\n\n  for (const searchRoot of searchRoots) {\n    const packageDirectory = path.join(searchRoot, \"node_modules\", packageName);\n    if (fs.existsSync(path.join(packageDirectory, \"package.json\"))) {\n      return packageDirectory;\n    }\n  }\n  return null;\n}\n\nfunction readPackageJson(packageJsonPath: string): Record<string, any> | null {\n  try {\n    return JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\"));\n  } catch {\n    return null;\n  }\n}\n\nfunction resolvePackageExport(exportsField: unknown, exportKey: string): string | null {\n  if (typeof exportsField === \"string\") {\n    return exportKey === \".\" ? exportsField : null;\n  }\n  if (Array.isArray(exportsField)) {\n    for (const candidate of exportsField) {\n      const resolved = resolvePackageExport(candidate, exportKey);\n      if (resolved) return resolved;\n    }\n    return null;\n  }\n  if (!exportsField || typeof exportsField !== \"object\") return null;\n\n  const entries = Object.entries(exportsField as Record<string, unknown>);\n  const subpathExports = entries.some(([key]) => key.startsWith(\".\"));\n  if (subpathExports) {\n    const exact = (exportsField as Record<string, unknown>)[exportKey];\n    if (exact !== undefined) return resolveConditionalExportTarget(exact);\n\n    for (const [key, value] of entries) {\n      const wildcardIndex = key.indexOf(\"*\");\n      if (wildcardIndex === -1) continue;\n      const prefix = key.slice(0, wildcardIndex);\n      const suffix = key.slice(wildcardIndex + 1);\n      if (!exportKey.startsWith(prefix) || !exportKey.endsWith(suffix)) continue;\n      const wildcard = exportKey.slice(prefix.length, exportKey.length - suffix.length);\n      const target = resolveConditionalExportTarget(value);\n      return target?.replace(\"*\", wildcard) ?? null;\n    }\n    return null;\n  }\n\n  return exportKey === \".\" ? resolveConditionalExportTarget(exportsField) : null;\n}\n\nfunction resolveConditionalExportTarget(value: unknown): string | null {\n  if (typeof value === \"string\") return value;\n  if (Array.isArray(value)) {\n    for (const candidate of value) {\n      const resolved = resolveConditionalExportTarget(candidate);\n      if (resolved) return resolved;\n    }\n    return null;\n  }\n  if (!value || typeof value !== \"object\") return null;\n\n  const conditions = value as Record<string, unknown>;\n  // This metadata controls browser hydration, so prefer client-facing exports\n  // regardless of declaration order while retaining Node-only package support.\n  for (const condition of [\"browser\", \"import\", \"module\", \"node\", \"default\", \"require\"]) {\n    if (conditions[condition] === undefined) continue;\n    const resolved = resolveConditionalExportTarget(conditions[condition]);\n    if (resolved) return resolved;\n  }\n  return null;\n}\n\nfunction resolveSourceCandidate(candidates: Iterable<string>): string | null {\n  for (const candidate of candidates) {\n    const paths = [candidate];\n    for (const extension of RESOLVABLE_SOURCE_EXTENSIONS) {\n      paths.push(`${candidate}${extension}`, path.join(candidate, `index${extension}`));\n    }\n    for (const sourcePath of paths) {\n      try {\n        if (fs.statSync(sourcePath).isFile()) return sourcePath;\n      } catch {\n        // Continue to the next candidate.\n      }\n    }\n  }\n  return null;\n}\n","/**\n * Controls when Farm loads and hydrates a server-rendered client boundary.\n *\n * `load` is the compatibility-first default. The deferred strategies keep the\n * server-rendered HTML visible while postponing the boundary's JavaScript.\n */\nexport type FarmIslandStrategy = \"load\" | \"interaction\" | \"visible\" | \"idle\";\n\nexport const FARM_ISLAND_STRATEGIES = [\"load\", \"interaction\", \"visible\", \"idle\"] as const;\n\nexport function isFarmIslandStrategy(value: unknown): value is FarmIslandStrategy {\n  return FARM_ISLAND_STRATEGIES.includes(value as FarmIslandStrategy);\n}\n","import 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 * as fs from \"fs\";\nimport * as path from \"path\";\nimport type {\n  FarmConfig,\n  FarmRequest,\n  FarmResponse,\n  LoadingProps,\n  PageProps,\n  RouteModule,\n  SSGPage,\n} from \"../types\";\nimport type { MatchedRouteSlot, RouteManager } from \"../routing/route-manager\";\nimport { logger, toViteModuleId } from \"../utils\";\nimport { collectDevStylesheetUrls } from \"./dev-styles\";\nimport {\n  composeFarmFullDocument,\n  extractFarmFullDocument,\n  opensFarmFullDocument,\n  removeFarmDocumentTitles,\n} from \"./full-document\";\nimport { getClientModuleMetadata } from \"../utils/client-component\";\nimport { Writable } from \"stream\";\nimport {\n  _clearCurrentMiddlewareContext,\n  _clearCurrentMiddlewareData,\n  _runWithMiddlewareContext,\n  _runWithMiddlewareData,\n} from \"../middleware/server\";\nimport { getRequestContextSnapshot } from \"../request-context\";\nimport { matchSSGPage, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport {\n  FARM_MARKDOWN_CONTENT_TYPE,\n  createFarmMarkdownErrorBody,\n  farmRequestWantsMarkdown,\n} from \"../app-markdown\";\nimport {\n  getIntegrationProviders,\n  getRegisteredIntegrationAPIManifest,\n  isFarmIntegrationProviderComponentReference,\n} from \"../integrations\";\nimport {\n  _runWithCurrentRequest,\n  createWebRequestFromFarmRequest,\n  resolveFarmRequestURL,\n} from \"./request\";\nimport { createFarmCacheKey, getFarmDataCache, normalizeRevalidatePath } from \"../cache\";\nimport { resolveFarmNotFoundComponentPath } from \"../not-found\";\nimport { getFarmAppDirectories } from \"../layers\";\nimport { emitFarmEvent } from \"../observability\";\nimport {\n  getFarmRedirectError,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n} from \"../navigation-errors\";\nimport {\n  addMetadataImageReference,\n  mergeMetadata,\n  renderMetadataHead,\n  type FarmMetadataImageReference,\n  type MetadataImageKind,\n} from \"../metadata\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"../route-context\";\nimport { searchParamsToObject } from \"../search-params\";\nimport { prepareDeferredData, snapshotDeferredData, type DeferredRecord } from \"../deferred\";\nimport { createFarmDeploymentCookie, FARM_DEPLOYMENT_ID_HEADER } from \"../deployment\";\nimport type { StaticMetadataImageInfo } from \"../static-metadata-image\";\nimport {\n  _runWithFarmI18nRequest,\n  getFarmI18nClientSnapshot,\n  type FarmI18nClientSnapshot,\n  type FarmI18nRuntime,\n} from \"../i18n/server\";\nimport { createFarmLocaleCookie, getFarmLocaleVaryHeaders } from \"../i18n/resolver\";\nimport { localizeFarmHref, localizeFarmPathname } from \"../i18n/routing\";\nimport { sendWebResponse } from \"./response\";\nimport { matchesFarmIfNoneMatch } from \"../server-http\";\nimport { renderFarmFontDevHead } from \"../font-vite\";\nimport { createFarmMetadataImageResponse } from \"../metadata-image\";\nimport { createFarmMetadataRouteResponse } from \"../metadata-route\";\nimport {\n  resolveFarmTrailingSlashRedirect,\n  setFarmTrailingSlashPreference,\n} from \"../trailing-slash\";\nimport { applyFarmBasePath, setFarmBasePath } from \"../base-path\";\nimport { DEFAULT_NOT_FOUND_STYLES } from \"../components/not-found-styles\";\nimport {\n  createDefaultErrorMarkup,\n  getDefaultErrorStatusText,\n  resolveDefaultErrorStatus,\n} from \"../components/error-page\";\nimport { createFarmThemeDocumentParts } from \"../theme/server-runtime\";\nimport { getTheme as getFarmTheme } from \"../theme/server\";\nimport { FARM_VERSION } from \"../version\";\nimport type { ViteDevServer } from \"vite\";\nimport {\n  getFarmRendererCapabilities,\n  getFarmRendererComponentExtensions,\n  isReactRenderer,\n  readFarmRendererWebStream,\n  resolveFarmRendererModule,\n  type FarmServerRendererRuntime,\n} from \"../renderer\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport { createDefaultErrorDiagnostics } from \"./error-diagnostics\";\n\nlet cachedClerkProvider: { ClerkProvider: any } | null = null;\n\nconst importRuntimeModule = new Function(\"specifier\", \"return import(specifier);\") as (\n  specifier: string,\n) => Promise<any>;\n\ninterface CachedSSGPage {\n  html: string;\n  document: boolean;\n}\n\ninterface CachedPPRShell {\n  html: string;\n}\n\nexport function shouldServePrerenderedPage(\n  nodeEnv: string | undefined,\n  method: string | undefined,\n): boolean {\n  if (nodeEnv !== \"production\") return false;\n  const normalizedMethod = (method || \"GET\").toUpperCase();\n  return normalizedMethod === \"GET\" || normalizedMethod === \"HEAD\";\n}\n\nfunction formatSSGManifestError(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\nfunction parseSSGManifest(content: string, manifestPath: string): SSGPage[] {\n  let manifest: unknown;\n\n  try {\n    manifest = JSON.parse(content);\n  } catch (error) {\n    throw new Error(\n      `Failed to parse SSG manifest at ${manifestPath}: ${formatSSGManifestError(error)}`,\n    );\n  }\n\n  if (!Array.isArray(manifest)) {\n    throw new Error(`Invalid SSG manifest at ${manifestPath}: expected an array of pages.`);\n  }\n\n  for (const [index, page] of manifest.entries()) {\n    if (!page || typeof page !== \"object\" || Array.isArray(page)) {\n      throw new Error(`Invalid SSG manifest at ${manifestPath}: page ${index} must be an object.`);\n    }\n\n    const entry = page as Record<string, unknown>;\n    if (typeof entry.urlPath !== \"string\") {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} must have a string urlPath.`,\n      );\n    }\n    if (\n      !entry.params ||\n      typeof entry.params !== \"object\" ||\n      Array.isArray(entry.params) ||\n      Object.values(entry.params).some((value) => typeof value !== \"string\")\n    ) {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} must have string params.`,\n      );\n    }\n    if (\n      entry.revalidate !== undefined &&\n      (typeof entry.revalidate !== \"number\" ||\n        !Number.isFinite(entry.revalidate) ||\n        entry.revalidate <= 0)\n    ) {\n      throw new Error(\n        `Invalid SSG manifest at ${manifestPath}: page ${index} revalidate must be a positive number.`,\n      );\n    }\n  }\n\n  return manifest as SSGPage[];\n}\n\ninterface PPRShellCacheOptions {\n  pathname: string;\n  search: string;\n  /**\n   * Locale the shell was rendered in, resolved once when these options are built.\n   * The shell carries `lang`, `dir`, the message catalog and the alternate links, so\n   * it cannot be shared across locales. It is captured rather than read at write\n   * time because the shell is stored from a streaming `onComplete` callback, which\n   * can run outside the request context that resolved the locale.\n   */\n  locale: string;\n  revalidate?: number;\n}\n\nexport interface FarmNavigationFragmentLayout {\n  pattern: string;\n  module: { default?: any };\n}\n\nexport interface FarmNavigationFragmentSlot {\n  name: string;\n  ownerPattern: string;\n  containerId: string;\n  module: { default?: any };\n  props: Record<string, unknown>;\n}\n\nexport interface FarmNavigationFragmentInput {\n  PageComponent: any;\n  LoadingComponent?: any;\n  pageProps: Record<string, unknown>;\n  params: Record<string, string>;\n  layouts: FarmNavigationFragmentLayout[];\n  /** First destination layout that changed compared with the active shell. */\n  layoutStartIndex?: number;\n  slots?: FarmNavigationFragmentSlot[];\n  pageShouldHydrate: boolean;\n  layoutShouldHydrate: boolean;\n  islandStrategy?: FarmIslandStrategy | null;\n}\n\nconst warnedSuppressedAsyncHydrationModules = new Set<string>();\n\nfunction warnSuppressedAsyncHydrationOnce(modulePath: string): void {\n  if (warnedSuppressedAsyncHydrationModules.has(modulePath)) return;\n  warnedSuppressedAsyncHydrationModules.add(modulePath);\n  logger.warn(\n    `${modulePath} is an async server component that imports client components. ` +\n      `React cannot hydrate async components in the browser, so this route stays ` +\n      `server-rendered and its client imports are not interactive. Move the ` +\n      `interactive UI into a \"use client\" child rendered by a synchronous page, ` +\n      `or enable experimental server components support.`,\n  );\n}\n\n// Routes whose layout was observed to render a full `<html>` document. The\n// streaming path can't rewrite a document after its shell is flushed, so once a\n// route is seen to be full-document it is served through the buffered path\n// (which composes the document correctly) on every subsequent request.\nconst fullDocumentRoutes = new Set<string>();\n\nlet warnedFullDocumentLayout = false;\n\nfunction warnFarmFullDocumentLayout(): void {\n  if (warnedFullDocumentLayout) return;\n  warnedFullDocumentLayout = true;\n  logger.warn(\n    `A root layout returned a full <html> document. Farm.js owns the document ` +\n      `shell, so a layout should return a fragment (its children) — like the docs ` +\n      `example — and let the framework provide <html>/<head>/<body>. The document ` +\n      `has been composed into the response, but returning a fragment avoids the ` +\n      `ambiguity and keeps dev and production identical.`,\n  );\n}\n\nfunction hasRequestHeader(req: FarmRequest, name: string): boolean {\n  const value = req.headers[name.toLowerCase()];\n  return Array.isArray(value) ? value.length > 0 : Boolean(value);\n}\n\n/**\n * The request pathname (without query/hash) used as the default canonical URL.\n * Prefers the resolved route path recorded on the request, falling back to the\n * raw request URL.\n */\nfunction getFarmMetadataPathname(req: FarmRequest): string | undefined {\n  const raw = (req as any).__FARM_ROUTE__ || req.url;\n  if (typeof raw !== \"string\" || raw.length === 0) return undefined;\n  const boundary = raw.search(/[?#]/);\n  return boundary === -1 ? raw : raw.slice(0, boundary);\n}\n\nfunction serializeInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nfunction appendResponseHeader(res: FarmResponse, name: string, value: string): void {\n  const current = res.getHeader(name);\n  if (current === undefined) {\n    res.setHeader(name, value);\n  } else if (Array.isArray(current)) {\n    res.setHeader(name, [...current.map(String), value]);\n  } else {\n    res.setHeader(name, [String(current), value]);\n  }\n}\n\nfunction appendResponseVary(res: FarmResponse, value: string): void {\n  const current = res.getHeader(\"Vary\");\n  const values = new Set(\n    (Array.isArray(current) ? current.join(\",\") : String(current || \"\"))\n      .split(\",\")\n      .map((entry) => entry.trim())\n      .filter(Boolean),\n  );\n  values.add(value);\n  res.setHeader(\"Vary\", Array.from(values).join(\", \"));\n}\n\nfunction renderI18nAlternateLinks(requestPath: string, snapshot: FarmI18nClientSnapshot): string {\n  if (snapshot.routing === \"none\") return \"\";\n  const url = new URL(requestPath, \"http://farm.local\");\n  const links = snapshot.locales.map((locale) => {\n    const href = localizeFarmPathname(url.pathname, locale, snapshot);\n    return `<link rel=\"alternate\" hreflang=\"${escapeHtmlAttribute(locale)}\" href=\"${escapeHtmlAttribute(href)}\">`;\n  });\n  links.push(\n    `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeHtmlAttribute(\n      localizeFarmPathname(url.pathname, snapshot.defaultLocale, snapshot),\n    )}\">`,\n  );\n  return links.join(\"\");\n}\n\nfunction createPPRRefreshScript(): string {\n  return `<script>(function(){if(window.__FARM_PPR_REFRESHING__)return;window.__FARM_PPR_REFRESHING__=true;function replaceRoot(html){var doc=new DOMParser().parseFromString(html,\"text/html\");var next=doc.getElementById(\"root\");var current=document.getElementById(\"root\");if(!next||!current)return;current.innerHTML=next.innerHTML;}fetch(window.location.href,{credentials:\"same-origin\",headers:{\"x-farm-ppr-refresh\":\"1\"}}).then(function(response){return response.ok?response.text():null;}).then(function(html){if(html)replaceRoot(html);}).catch(function(){});})();</script>`;\n}\n\nfunction createPreHydrationClickQueueScript(): string {\n  return `<script>(function(){if(window.__FARM_PREHYDRATION_CLICK_QUEUE__)return;var queue=[];window.__FARM_PREHYDRATION_CLICK_QUEUE__=queue;window.__FARM_HYDRATED__=false;document.documentElement.dataset.farmHydrated=\"false\";function isModified(event){return !!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}function closestQueuedTarget(target){while(target&&target!==document.documentElement){if(target.matches&&target.matches('button,[role=\"button\"],input[type=\"button\"],input[type=\"submit\"],input[type=\"reset\"]'))return target;target=target.parentElement}return null}document.addEventListener(\"click\",function(event){if(window.__FARM_HYDRATED__)return;if(event.defaultPrevented||event.button!==0||isModified(event))return;var target=closestQueuedTarget(event.target);if(!target||target.closest&&target.closest(\"a[href]\")||target.closest&&target.closest('[data-farm-island-hydrated=\"true\"]'))return;if(queue.some(function(item){return item.target===target}))return;queue.push({target:target,createdAt:Date.now()});document.dispatchEvent(new CustomEvent(\"farm:island-interaction\",{detail:{target:target}}));event.preventDefault();event.stopImmediatePropagation()},true);})();</script>`;\n}\n\nfunction createDocumentFooter(options: {\n  suspenseRevealFallback: string;\n  refreshPPR?: boolean;\n  deferredHydrationScript?: string;\n}): string {\n  return `</div>\n  ${options.suspenseRevealFallback}\n  ${options.refreshPPR ? createPPRRefreshScript() : \"\"}\n  ${options.deferredHydrationScript || \"\"}\n  <script type=\"module\" src=\"/@farm/client.js\"></script>\n</body>\n</html>`;\n}\n\nfunction createDeferredHydrationScript(records: readonly DeferredRecord[]): string {\n  if (records.length === 0) return \"\";\n  return `<script>window.__FARM_DEFERRED_DATA__=${serializeInlineValue(\n    snapshotDeferredData(records),\n  )};</script>`;\n}\n\nfunction toMiddlewareMap(input: unknown): Map<string, any> {\n  if (input instanceof Map) {\n    return new Map(input as Map<string, any>);\n  }\n  if (input && typeof input === \"object\") {\n    return new Map(Object.entries(input as Record<string, any>));\n  }\n  return new Map<string, any>();\n}\n\nfunction isWebResponse(value: unknown): value is Response {\n  return (\n    typeof Response !== \"undefined\" &&\n    value instanceof Response &&\n    typeof value.arrayBuffer === \"function\"\n  );\n}\n\nasync function parseRouteModuleProps(\n  routeModule: RouteModule,\n  input: {\n    props: PageProps;\n    search: Record<string, string | string[] | undefined>;\n    routePath: string;\n  },\n): Promise<\n  PageProps & {\n    search: unknown;\n    data?: unknown;\n    __farmCanonicalPath?: string;\n    __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n    __farmRoutePropsResolved?: true;\n  }\n> {\n  const resolveRouteProps = (routeModule as any).__farmResolveRouteProps;\n  if (typeof resolveRouteProps === \"function\") {\n    // Resolve the top-level route state before starting the HTTP stream. It can\n    // still return explicit defer() values for nested Suspense boundaries, but\n    // redirects, notFound(), and failures must retain their real HTTP status.\n    return await resolveRouteProps(input.props);\n  }\n\n  if ((routeModule as any).__farmRouteParsesProps) {\n    return {\n      ...input.props,\n      search: input.search,\n    };\n  }\n\n  const schemas = (routeModule as any).__farmRouteSchemas;\n  const params = parseRouteModuleSchema(\n    schemas?.params,\n    input.props.params,\n    \"params\",\n    input.routePath,\n  );\n  const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n  return {\n    ...input.props,\n    params: params as Record<string, string>,\n    search,\n    searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n  };\n}\n\nfunction parseRouteModuleSchema(\n  schema: { parse?: (value: unknown) => unknown } | undefined,\n  value: unknown,\n  label: string,\n  routePath: string,\n): unknown {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n  }\n}\n\nfunction createRouteStateProps(input: {\n  params: Record<string, string>;\n  searchParamsObject: Record<string, string | string[] | undefined>;\n  path: string;\n  middlewareMap: Map<string, any>;\n  pluginExposedContext: Map<string, any>;\n}): LoadingProps {\n  return {\n    params: input.params,\n    search: input.searchParamsObject,\n    searchParams: Promise.resolve(input.searchParamsObject),\n    path: input.path,\n    middleware: input.middlewareMap.size > 0 ? { data: input.middlewareMap } : undefined,\n    context: input.pluginExposedContext.size > 0 ? { data: input.pluginExposedContext } : undefined,\n  };\n}\n\nexport class ServerRenderer {\n  private config: Required<FarmConfig>;\n  private routeManager: RouteManager;\n  private ssgManifest: SSGPage[] = [];\n  private dataCache = getFarmDataCache();\n  private i18nRuntime?: FarmI18nRuntime;\n  private viteServer?: ViteDevServer;\n  private rendererRuntime!: FarmServerRendererRuntime;\n\n  constructor(\n    config: Required<FarmConfig>,\n    routeManager: RouteManager,\n    i18nRuntime?: FarmI18nRuntime,\n    viteServer?: ViteDevServer,\n  ) {\n    this.config = config;\n    this.routeManager = routeManager;\n    this.i18nRuntime = i18nRuntime;\n    this.viteServer = viteServer;\n    this.loadSSGManifest();\n  }\n\n  async initialize(): Promise<void> {\n    if (this.rendererRuntime) return;\n\n    if (this.config.notFound?.component?.trim()) {\n      resolveFarmNotFoundComponentPath(this.config, getFarmAppDirectories(this.config));\n    }\n\n    const loaded = isReactRenderer(this.config.renderer)\n      ? await import(\"../renderer/react/server\")\n      : this.viteServer\n        ? await this.viteServer.ssrLoadModule(this.config.renderer.server)\n        : await import(\n            pathToFileURL(\n              resolveFarmRendererModule(\n                this.config.root || process.cwd(),\n                this.config.renderer.server,\n              ),\n            ).href\n          );\n    const runtime = loaded as Partial<FarmServerRendererRuntime>;\n    const required = [\"createElement\", \"isValidElement\", \"renderToString\"] as const;\n    for (const key of required) {\n      if (typeof runtime[key] !== \"function\") {\n        throw new Error(\n          `Renderer \\`${this.config.renderer.name}\\` server module must export ${key}().`,\n        );\n      }\n    }\n\n    const capabilities = getFarmRendererCapabilities(this.config.renderer);\n    if (capabilities.streaming.node && typeof runtime.renderToPipeableStream !== \"function\") {\n      throw new Error(\n        `Renderer \\`${this.config.renderer.name}\\` advertises Node streaming but its server module does not export renderToPipeableStream().`,\n      );\n    }\n    if (capabilities.streaming.web && typeof runtime.renderToReadableStream !== \"function\") {\n      throw new Error(\n        `Renderer \\`${this.config.renderer.name}\\` advertises Web streaming but its server module does not export renderToReadableStream().`,\n      );\n    }\n\n    this.rendererRuntime = runtime as FarmServerRendererRuntime;\n    this.routeManager.setRendererRuntime?.(this.rendererRuntime);\n  }\n\n  private createPageBoundary(\n    pageElement: unknown,\n    options: {\n      pageShouldHydrate: boolean;\n      layoutShouldHydrate: boolean;\n      islandStrategy?: FarmIslandStrategy | null;\n    },\n  ): unknown {\n    return this.rendererRuntime.createElement(\n      \"div\",\n      {\n        id: \"__farm_page__\",\n        \"data-farm-segment\": \"page\",\n        \"data-farm-client\": options.pageShouldHydrate ? \"true\" : \"false\",\n        ...(options.layoutShouldHydrate ? { \"data-farm-layout-client\": \"true\" } : {}),\n        \"data-farm-island\": \"page\",\n        \"data-farm-island-strategy\": options.islandStrategy || \"load\",\n      },\n      pageElement,\n    );\n  }\n\n  /// Stylesheets the app imported through JS (fontsource packages, component\n  /// CSS) that the document must link alongside globals.css — see #658.\n  private collectDevStyleHrefs(): string[] {\n    const graph = this.viteServer?.moduleGraph;\n    if (!graph) return [];\n    return collectDevStylesheetUrls(graph.idToModuleMap.values());\n  }\n\n  private collectDevStyleLinks(): string[] {\n    return this.collectDevStyleHrefs().map(\n      (href) => `<link rel=\"stylesheet\" href=\"${escapeHtmlAttribute(href)}\">`,\n    );\n  }\n\n  private createLayoutBoundary(pattern: string, layoutElement: unknown): unknown {\n    return this.rendererRuntime.createElement(\n      \"div\",\n      {\n        \"data-farm-layout-boundary\": \"true\",\n        \"data-farm-layout-pattern\": pattern,\n        style: { display: \"contents\" },\n      },\n      layoutElement,\n    );\n  }\n\n  private wrapClientGraph(element: unknown): unknown {\n    const getIsolatedClientBoundaryModules = this.routeManager.getIsolatedClientBoundaryModules;\n    if (\n      !this.rendererRuntime.wrapClientGraph ||\n      typeof getIsolatedClientBoundaryModules !== \"function\" ||\n      getIsolatedClientBoundaryModules.call(this.routeManager, this.config.root).size === 0\n    ) {\n      return element;\n    }\n    return this.rendererRuntime.wrapClientGraph(element);\n  }\n\n  private async renderElementToCompleteHTML(element: unknown): Promise<string> {\n    const capabilities = getFarmRendererCapabilities(this.config.renderer);\n    const renderToPipeableStream = capabilities.streaming.node\n      ? this.rendererRuntime.renderToPipeableStream\n      : undefined;\n\n    if (renderToPipeableStream) {\n      return await new Promise<string>((resolve, reject) => {\n        const chunks: Buffer[] = [];\n        let started = false;\n        const writable = new Writable({\n          write(chunk, _encoding, callback) {\n            chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n            callback();\n          },\n        });\n        writable.once(\"finish\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n        writable.once(\"error\", reject);\n\n        const stream = renderToPipeableStream(element, {\n          onShellReady() {\n            started = true;\n            stream.pipe(writable);\n          },\n          onShellError(error) {\n            reject(error);\n          },\n          onError(error) {\n            if (!started) reject(error);\n          },\n        });\n      });\n    }\n\n    if (capabilities.streaming.web && this.rendererRuntime.renderToReadableStream) {\n      const stream = await this.rendererRuntime.renderToReadableStream(element);\n      return await readFarmRendererWebStream(stream);\n    }\n\n    return await this.rendererRuntime.renderToString(element);\n  }\n\n  /**\n   * Buffered render carrying document-head markup for renderers that emit it\n   * during render (e.g. <svelte:head>). Other renderers return an empty head.\n   */\n  private async renderElementToDocumentParts(\n    element: unknown,\n  ): Promise<{ html: string; head: string }> {\n    if (this.rendererRuntime.renderToStringWithHead) {\n      const rendered = await this.rendererRuntime.renderToStringWithHead(element);\n      return { html: rendered.html, head: rendered.head || \"\" };\n    }\n    return { html: await this.rendererRuntime.renderToString(element), head: \"\" };\n  }\n\n  /**\n   * Render the route tree used by client navigation without producing a second\n   * document response. Layout markers let the browser preserve the longest\n   * common shell and replace only the first changed boundary.\n   */\n  async renderNavigationFragment(input: FarmNavigationFragmentInput): Promise<string> {\n    await this.initialize();\n    setFarmBasePath(this.config.basePath);\n    setFarmTrailingSlashPreference(this.config.trailingSlash);\n    let element = this.rendererRuntime.createElement(input.PageComponent, input.pageProps);\n    if (input.LoadingComponent) {\n      element = this.rendererRuntime.createElement(\n        this.rendererRuntime.Suspense,\n        {\n          fallback: this.rendererRuntime.createElement(input.LoadingComponent, {\n            params: input.params,\n            path: (input.pageProps as any).path,\n          }),\n        },\n        element,\n      );\n    }\n    if (input.pageShouldHydrate && !input.layoutShouldHydrate) {\n      element = this.wrapClientGraph(element);\n    }\n    element = this.createPageBoundary(element, {\n      pageShouldHydrate: input.pageShouldHydrate,\n      layoutShouldHydrate: input.layoutShouldHydrate,\n      islandStrategy: input.islandStrategy,\n    });\n\n    const layoutStartIndex = Math.max(\n      0,\n      Math.min(input.layoutStartIndex ?? 0, input.layouts.length),\n    );\n    for (let index = input.layouts.length - 1; index >= layoutStartIndex; index--) {\n      const layout = input.layouts[index]!;\n      const LayoutComponent = layout.module.default;\n      if (!LayoutComponent) continue;\n      const slotProps: Record<string, unknown> = {};\n      for (const slot of input.slots || []) {\n        if (slot.ownerPattern !== layout.pattern || !slot.module.default) continue;\n        let slotElement = this.rendererRuntime.createElement(slot.module.default, slot.props);\n        slotElement = this.wrapClientGraph(slotElement);\n        slotProps[slot.name] = this.rendererRuntime.createElement(\n          \"div\",\n          {\n            id: slot.containerId,\n            \"data-farm-route-slot\": slot.name,\n            \"data-farm-slot-owner\": slot.ownerPattern,\n          },\n          slotElement,\n        );\n      }\n      element = this.rendererRuntime.createElement(LayoutComponent, {\n        children: element,\n        params: input.params,\n        ...slotProps,\n      });\n      element = this.createLayoutBoundary(layout.pattern, element);\n    }\n\n    if (input.layoutShouldHydrate) {\n      element = this.wrapClientGraph(element);\n    }\n\n    return this.renderElementToCompleteHTML(await this.wrapWithIntegrationProviders(element));\n  }\n\n  async runWithRequestContext<T>(request: Request, fn: () => T | Promise<T>): Promise<T> {\n    return _runWithCurrentRequest(request, () =>\n      this.i18nRuntime?.config.enabled\n        ? _runWithFarmI18nRequest(this.i18nRuntime, request, fn, {\n            redirect: false,\n          })\n        : fn(),\n    );\n  }\n\n  async resolveRouteContext(input: {\n    request: Request;\n    rawRequest?: FarmRequest;\n    params: Record<string, string>;\n    search: Record<string, string | string[] | undefined>;\n    path: string;\n  }): Promise<unknown> {\n    return resolveFarmRouteContext(this.config, input);\n  }\n\n  /**\n   * Load SSG manifest from build output\n   */\n  private loadSSGManifest(): void {\n    const manifestPath = path.join(this.config.root, this.config.outDir, \"__ssg_manifest.json\");\n    let content: string;\n\n    try {\n      content = fs.readFileSync(manifestPath, \"utf-8\");\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n        return;\n      }\n\n      throw new Error(\n        `Failed to read SSG manifest at ${manifestPath}: ${formatSSGManifestError(error)}`,\n      );\n    }\n\n    this.ssgManifest = parseSSGManifest(content, manifestPath);\n    logger.info(`Loaded SSG manifest: ${this.ssgManifest.length} pages`);\n  }\n\n  /**\n   * Check if a path should be served from SSG cache\n   */\n  private async shouldServeSSG(pathname: string): Promise<SSGPage | null> {\n    const ssgPage = matchSSGPage(pathname, this.ssgManifest);\n    if (!ssgPage) return null;\n\n    const cached = await this.getCachedSSGPage(pathname);\n    if (cached && (await this.dataCache.isStaleAsync(cached))) {\n      // Stale - needs revalidation (serve stale, regenerate in background)\n      this.regenerateSSGPage(ssgPage);\n    }\n\n    return ssgPage;\n  }\n\n  private getSSGCacheKey(urlPath: string): string {\n    return createFarmCacheKey([\"ssg\", normalizeRevalidatePath(urlPath)]);\n  }\n\n  private getPPRCacheKey(pathname: string, search = \"\", locale = \"\"): string {\n    return createFarmCacheKey([\"ppr\", locale, normalizeRevalidatePath(pathname), search]);\n  }\n\n  private getCachedSSGPage(urlPath: string) {\n    return this.dataCache.getEntryAsync<CachedSSGPage>(this.getSSGCacheKey(urlPath), {\n      allowStale: true,\n    });\n  }\n\n  private async cacheSSGPage(\n    page: SSGPage,\n    html: string,\n    options: { document: boolean; createdAt?: number },\n  ): Promise<void> {\n    await this.dataCache.setAsync(\n      this.getSSGCacheKey(page.urlPath),\n      { html, document: options.document },\n      {\n        createdAt: options.createdAt,\n        paths: [page.urlPath],\n        tags: [\"ssg\"],\n        revalidate: page.revalidate ?? false,\n      },\n    );\n  }\n\n  private getCachedPPRShell(pathname: string, search: string, locale = \"\") {\n    return this.dataCache.getEntryAsync<CachedPPRShell>(\n      this.getPPRCacheKey(pathname, search, locale),\n    );\n  }\n\n  private async cachePPRShell(options: PPRShellCacheOptions, html: string): Promise<void> {\n    const key = this.getPPRCacheKey(options.pathname, options.search, options.locale);\n    await this.dataCache.setAsync(\n      key,\n      { html },\n      {\n        paths: [options.pathname],\n        tags: [\"ppr\"],\n        revalidate: options.revalidate ?? false,\n      },\n    );\n    emitFarmEvent({\n      type: \"ppr.shell.cached\",\n      route: options.pathname,\n      key,\n      revalidate: options.revalidate,\n    });\n  }\n\n  private getPPRShellBypassReason(\n    req: FarmRequest,\n    middlewareMap: Map<string, any>,\n    middlewareContext: Map<string, any>,\n    pluginExposedContext: Map<string, any>,\n  ): string | undefined {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      return \"method\";\n    }\n\n    if (req.headers.cookie) {\n      return \"cookie\";\n    }\n\n    if (req.headers.authorization) {\n      return \"authorization\";\n    }\n\n    if (hasRequestHeader(req, \"x-farm-ppr-refresh\")) {\n      return \"refresh\";\n    }\n\n    if (middlewareMap.size > 0) {\n      return \"middleware-data\";\n    }\n\n    if (middlewareContext.size > 0) {\n      return \"middleware-context\";\n    }\n\n    if (pluginExposedContext.size > 0) {\n      return \"plugin-context\";\n    }\n\n    return undefined;\n  }\n\n  private getPPRHeaders(status: \"hit\" | \"miss\" | \"bypass\", revalidate?: number) {\n    const headers: Record<string, string> = {\n      \"X-Farm-PPR\": status,\n    };\n\n    if (status === \"bypass\") {\n      headers[\"Cache-Control\"] = \"private, no-store\";\n      return headers;\n    }\n\n    if (typeof revalidate === \"number\" && revalidate > 0) {\n      headers[\"Cache-Control\"] = `s-maxage=${revalidate}, stale-while-revalidate`;\n    }\n\n    return headers;\n  }\n\n  private serveCachedPPRShell(res: FarmResponse, shell: CachedPPRShell, revalidate?: number): void {\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    for (const [key, value] of Object.entries(this.getPPRHeaders(\"hit\", revalidate))) {\n      res.setHeader(key, value);\n    }\n    res.write(shell.html);\n    res.end();\n  }\n\n  /**\n   * Regenerate an SSG page in the background (ISR)\n   */\n  private async regenerateSSGPage(page: SSGPage): Promise<void> {\n    try {\n      // This runs in the background - don't await\n      setImmediate(async () => {\n        try {\n          const mod = await this.routeManager.loadRouteModule(page.filePath);\n          if (!mod?.default) return;\n\n          const { route, layouts } = this.routeManager.matchRoute(page.urlPath);\n          const layoutModules = await Promise.all(\n            layouts.map((l) => this.routeManager.loadLayoutModule(l.modulePath)),\n          );\n          const routeManifest = this.routeManager.generateClientManifest(this.config.root);\n\n          const PageComponent = mod.default;\n          const pageProps = {\n            params: page.params,\n            searchParams: Promise.resolve({}),\n            path: page.urlPath,\n          };\n\n          let pageElement: any = this.rendererRuntime.createElement(PageComponent, pageProps);\n          const pageMetadata = routeManifest.routes.find(\n            (entry) => entry.pattern === route?.pattern,\n          ) ?? {\n            shouldHydrate: false,\n            islandStrategy: null,\n          };\n          const layoutMetadata = layouts.map(\n            (layout) =>\n              routeManifest.layouts.find((entry) => entry.pattern === layout.pattern) ?? {\n                shouldHydrate: false,\n                islandStrategy: null,\n              },\n          );\n          const layoutShouldHydrate = layoutMetadata.some((metadata) => metadata.shouldHydrate);\n          pageElement = this.createPageBoundary(pageElement, {\n            pageShouldHydrate: pageMetadata.shouldHydrate,\n            layoutShouldHydrate,\n            islandStrategy: pageMetadata.islandStrategy,\n          });\n\n          for (let i = layoutModules.length - 1; i >= 0; i--) {\n            const layoutModule = layoutModules[i];\n            const LayoutComponent = layoutModule.default;\n            pageElement = this.rendererRuntime.createElement(LayoutComponent, {\n              children: pageElement,\n              params: page.params,\n            });\n            pageElement = this.createLayoutBoundary(layouts[i]!.pattern, pageElement);\n          }\n\n          const html = await this.rendererRuntime.renderToString(\n            await this.wrapWithIntegrationProviders(pageElement),\n          );\n\n          // Resolve metadata so the regenerated document keeps its title and\n          // meta/OG tags instead of falling back to the framework default\n          // (\"Farm.js App\"). Without this, a static route served from the ISR\n          // cache loses its metadata after the first revalidation (issue #1018).\n          const mergedMetadata = await this.resolveRouteMetadata({\n            layoutModules,\n            routeModule: mod,\n            pageProps: pageProps as unknown as PageProps,\n            pathname: page.urlPath,\n          });\n          const { title, tags, hasFavicon } = renderMetadataHead(mergedMetadata);\n          const metadataHead = `${\n            hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">\\n  '\n          }<title>${title}</title>${tags}`;\n          const fullDocument = this.createFullHTML(\n            html,\n            pageMetadata.shouldHydrate === true,\n            page.urlPath,\n            metadataHead,\n          );\n\n          await this.cacheSSGPage(page, fullDocument, { document: true });\n\n          logger.info(`ISR: Regenerated ${page.urlPath}`);\n        } catch (error) {\n          logger.error(`ISR regeneration failed for ${page.urlPath}: ${error}`);\n        }\n      });\n    } catch (error) {\n      logger.error(`ISR trigger failed: ${error}`);\n    }\n  }\n\n  /**\n   * Serve a pre-rendered SSG page\n   */\n  private async serveSSGPage(req: FarmRequest, res: FarmResponse, page: SSGPage): Promise<boolean> {\n    // Check cache first (for ISR)\n    const cached = await this.getCachedSSGPage(page.urlPath);\n    if (cached) {\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      res.setHeader(\"X-Farm-SSG\", \"cached\");\n      if (page.revalidate) {\n        res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n      }\n      res.write(\n        cached.value.document\n          ? cached.value.html\n          : this.createFullHTML(cached.value.html, false, page.urlPath),\n      );\n      res.end();\n      return true;\n    }\n\n    // Try to read from file system (production)\n    try {\n      const htmlPath =\n        page.urlPath === \"/\"\n          ? path.join(this.config.root, this.config.outDir, \"client\", \"index.html\")\n          : path.join(this.config.root, this.config.outDir, \"client\", page.urlPath + \".html\");\n\n      if (fs.existsSync(htmlPath)) {\n        const stat = fs.statSync(htmlPath);\n        const html = fs.readFileSync(htmlPath, \"utf-8\");\n        await this.cacheSSGPage(page, html, {\n          document: true,\n          createdAt: stat.mtimeMs,\n        });\n        const fileCacheEntry = await this.getCachedSSGPage(page.urlPath);\n        if (fileCacheEntry && (await this.dataCache.isStaleAsync(fileCacheEntry))) {\n          this.regenerateSSGPage(page);\n        }\n\n        res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n        res.setHeader(\"X-Farm-SSG\", \"file\");\n        if (page.revalidate) {\n          res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n        }\n        res.write(html);\n        res.end();\n        return true;\n      }\n    } catch (error) {\n      logger.error(`Failed to serve SSG page ${page.urlPath}: ${error}`);\n    }\n\n    return false;\n  }\n\n  async renderPage(req: FarmRequest, res: FarmResponse): Promise<void> {\n    await this.initialize();\n    setFarmBasePath(this.config.basePath);\n    setFarmTrailingSlashPreference(this.config.trailingSlash);\n    const request = createWebRequestFromFarmRequest(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const runtime = this.i18nRuntime;\n\n    if (runtime?.config.enabled) {\n      const resolution = runtime.resolveRequest(request);\n      const varyHeaders = getFarmLocaleVaryHeaders(runtime.config, resolution);\n      for (const header of varyHeaders) appendResponseVary(res, header);\n      if (resolution.persist) {\n        appendResponseHeader(\n          res,\n          \"Set-Cookie\",\n          createFarmLocaleCookie(resolution.locale, runtime.config),\n        );\n      }\n      if (resolution.redirect && (request.method === \"GET\" || request.method === \"HEAD\")) {\n        res.statusCode = 307;\n        res.setHeader(\"Location\", resolution.redirect);\n        if (varyHeaders.length > 0) res.setHeader(\"Cache-Control\", \"private, no-store\");\n        res.end();\n        return;\n      }\n    }\n\n    return this.runWithRequestContext(request, () => this.renderPageInContext(req, res));\n  }\n\n  private async renderPageInContext(req: FarmRequest, res: FarmResponse): Promise<void> {\n    const renderStartTime = Date.now();\n    let pathname = \"/\";\n    let params: Record<string, string> = {};\n    let layouts: Array<{ modulePath: string; pattern: string }> = [];\n    let routeSlots: MatchedRouteSlot[] = [];\n    let searchParamsObject: Record<string, string | string[] | undefined> = {};\n    let middlewareMap = new Map<string, any>();\n    let middlewareContext = new Map<string, any>();\n    let pluginExposedContext = new Map<string, any>();\n    let errorBoundaryEntry: { modulePath: string } | null = null;\n    let pprRefreshRoute: string | null = null;\n\n    const completeRender = (status = res.statusCode || 200, route = pathname) => {\n      emitFarmEvent({\n        type: \"render.complete\",\n        route,\n        pathname,\n        status,\n        durationMs: Date.now() - renderStartTime,\n      });\n    };\n\n    try {\n      const url = resolveFarmRequestURL(req, { trustProxy: this.config.server?.trustProxy });\n      pathname = url.pathname;\n      emitFarmEvent({ type: \"render.start\", route: pathname, pathname });\n      searchParamsObject = searchParamsToObject(url.searchParams);\n\n      const metadataRouteMatch = this.routeManager.matchMetadataRoute(pathname);\n      if (metadataRouteMatch) {\n        await this.renderMetadataRoute(req, res, metadataRouteMatch);\n        completeRender(res.statusCode || 200, pathname);\n        return;\n      }\n\n      const metadataImageMatch = this.routeManager.matchMetadataImage(pathname);\n      if (metadataImageMatch) {\n        await this.renderMetadataImage(req, res, {\n          pathname,\n          searchParamsObject,\n          ...metadataImageMatch,\n        });\n        completeRender(res.statusCode || 200, pathname);\n        return;\n      }\n\n      this.applyDeploymentHeaders(req, res);\n\n      const match = this.routeManager.matchRoute(pathname);\n      if (match.route) {\n        const redirectLocation = resolveFarmTrailingSlashRedirect(url, this.config.trailingSlash);\n        if (redirectLocation) {\n          res.statusCode = 308;\n          res.setHeader(\"Location\", redirectLocation);\n          res.end();\n          completeRender(308, match.route.pattern);\n          return;\n        }\n      }\n\n      // Pre-rendered HTML only represents retrieval requests. Other methods must\n      // continue through the live route so their request semantics are preserved.\n      if (shouldServePrerenderedPage(process.env.NODE_ENV, req.method)) {\n        const ssgPage = await this.shouldServeSSG(pathname);\n        if (ssgPage) {\n          const served = await this.serveSSGPage(req, res, ssgPage);\n          if (served) {\n            completeRender(res.statusCode || 200, ssgPage.urlPath);\n            return;\n          }\n        }\n      }\n\n      // Match route\n      const route = match.route;\n      params = match.params;\n      layouts = match.layouts;\n      routeSlots = match.slots ?? [];\n\n      if (!route) {\n        emitFarmEvent({ type: \"route.notFound\", pathname });\n        await this.render404(req, res);\n        completeRender(404);\n        return;\n      }\n\n      emitFarmEvent({\n        type: \"route.matched\",\n        pathname,\n        route: route.pattern,\n        params,\n      });\n\n      const loadingBoundaryEntry = this.routeManager.getMatchingLoading(pathname);\n      errorBoundaryEntry = this.routeManager.getMatchingError(pathname);\n\n      middlewareMap = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_DATA__);\n      middlewareContext = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_CONTEXT__);\n      pluginExposedContext = getRequestContextSnapshot(req as object, {\n        exposedOnly: true,\n      });\n      const currentRequest = createWebRequestFromFarmRequest(req, {\n        trustProxy: this.config.server?.trustProxy,\n      });\n      const routeContext = await this.resolveRouteContext({\n        request: currentRequest,\n        rawRequest: req,\n        params,\n        search: searchParamsObject,\n        path: pathname,\n      });\n\n      // Load route module\n      const routeModule = await this.routeManager.loadRouteModule(route.modulePath);\n\n      if (!routeModule.default) {\n        throw new Error(`Route module ${route.modulePath} does not export a default component`);\n      }\n\n      // Create page props with searchParams as plain object and middleware data\n      const rawPageProps: PageProps = withFarmRouteContext(\n        {\n          params,\n          searchParams: Promise.resolve(searchParamsObject),\n          path: pathname,\n          middleware: middlewareMap.size > 0 ? { data: middlewareMap } : undefined,\n          context: pluginExposedContext.size > 0 ? { data: pluginExposedContext } : undefined,\n        } as PageProps & { search: unknown },\n        routeContext,\n      );\n      const programmaticRouteComponents = (routeModule as any).__farmRouteComponents as\n        | {\n            error?: any;\n            notFound?: any;\n          }\n        | undefined;\n      let PageComponent = routeModule.default;\n      let pageProps: PageProps & {\n        search: unknown;\n        data?: unknown;\n        error?: unknown;\n        __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n        __farmRoutePropsResolved?: true;\n      };\n\n      try {\n        pageProps = await parseRouteModuleProps(routeModule, {\n          props: rawPageProps,\n          search: searchParamsObject,\n          routePath: route.pattern,\n        });\n      } catch (error) {\n        if (isFarmRedirectError(error)) throw error;\n\n        const routeStateProps = {\n          ...rawPageProps,\n          search: searchParamsObject,\n          searchParams: Promise.resolve(searchParamsObject),\n          error,\n        };\n\n        if (isFarmNotFoundError(error) && programmaticRouteComponents?.notFound) {\n          res.statusCode = 404;\n          PageComponent = programmaticRouteComponents.notFound;\n          pageProps = routeStateProps;\n        } else if (programmaticRouteComponents?.error) {\n          res.statusCode = 500;\n          PageComponent = programmaticRouteComponents.error;\n          pageProps = routeStateProps;\n        } else {\n          throw error;\n        }\n      }\n\n      const renderingConfig = await resolveRouteRenderingConfigFromFile(\n        routeModule,\n        route.modulePath,\n        { experimentalPPR: this.config.experimental?.ppr === true },\n      );\n      const pprBypassReason = renderingConfig.ppr\n        ? this.getPPRShellBypassReason(req, middlewareMap, middlewareContext, pluginExposedContext)\n        : undefined;\n      const canCachePPRShell = renderingConfig.ppr && !pprBypassReason;\n      const pprShellOptions: PPRShellCacheOptions | undefined = canCachePPRShell\n        ? {\n            pathname,\n            search: url.search,\n            locale: getFarmI18nClientSnapshot()?.locale ?? \"\",\n            revalidate: renderingConfig.revalidate,\n          }\n        : undefined;\n\n      if (renderingConfig.ppr && pprBypassReason) {\n        emitFarmEvent({\n          type: \"ppr.shell.bypass\",\n          route: pathname,\n          reason: pprBypassReason,\n        });\n        emitFarmEvent({\n          type: \"cache.bypass\",\n          route: pathname,\n          reason: pprBypassReason,\n        });\n\n        if (pprBypassReason === \"refresh\") {\n          pprRefreshRoute = pathname;\n          emitFarmEvent({ type: \"ppr.refresh.start\", route: pathname });\n        }\n      }\n\n      if (pprShellOptions) {\n        // Same locale for the lookup and the later store, so the two cannot diverge.\n        const pprCacheKey = this.getPPRCacheKey(pathname, url.search, pprShellOptions.locale);\n        const cachedPPRShell = await this.getCachedPPRShell(\n          pathname,\n          url.search,\n          pprShellOptions.locale,\n        );\n        if (cachedPPRShell) {\n          emitFarmEvent({\n            type: \"ppr.shell.hit\",\n            route: pathname,\n            key: pprCacheKey,\n          });\n          this.serveCachedPPRShell(res, cachedPPRShell.value, renderingConfig.revalidate);\n          completeRender(res.statusCode || 200, pathname);\n          return;\n        }\n        emitFarmEvent({\n          type: \"ppr.shell.miss\",\n          route: pathname,\n          key: pprCacheKey,\n        });\n      }\n\n      let LoadingFallbackComponent: any = null;\n      if (loadingBoundaryEntry) {\n        const loadingModule = await this.routeManager.loadRouteModule(\n          loadingBoundaryEntry.modulePath,\n        );\n        if (loadingModule.default) {\n          LoadingFallbackComponent = loadingModule.default;\n        }\n      }\n\n      let ErrorFallbackComponent: any = null;\n      if (errorBoundaryEntry) {\n        const errorModule = await this.routeManager.loadRouteModule(errorBoundaryEntry.modulePath);\n        if (errorModule.default) {\n          ErrorFallbackComponent = errorModule.default;\n        }\n      }\n\n      // Hydration decisions are compiled into a manifest and reused on requests.\n      // Development HMR invalidates this cache when a route module changes.\n      const routeManifest = this.routeManager.generateClientManifest(this.config.root);\n      const routeManifestEntry = routeManifest.routes.find(\n        (entry) => entry.pattern === route.pattern,\n      );\n      const moduleMetadata =\n        routeManifestEntry || getClientModuleMetadata(route.modulePath, this.config.root);\n      const isClientComponent = moduleMetadata.isClientComponent;\n      const renderedRouteSlots = await Promise.all(\n        routeSlots.map(async (slot) => {\n          const slotModule = await this.routeManager.loadRouteModule(slot.route.modulePath);\n          if (!slotModule.default) {\n            throw new Error(\n              `Route slot \"${slot.name}\" module ${slot.route.modulePath} does not export a default component`,\n            );\n          }\n\n          const slotContext = await this.resolveRouteContext({\n            request: currentRequest,\n            rawRequest: req,\n            params: slot.params,\n            search: searchParamsObject,\n            path: pathname,\n          });\n          const rawSlotProps = withFarmRouteContext(\n            {\n              params: slot.params,\n              searchParams: Promise.resolve(searchParamsObject),\n              path: pathname,\n              middleware: middlewareMap.size > 0 ? { data: middlewareMap } : undefined,\n              context: pluginExposedContext.size > 0 ? { data: pluginExposedContext } : undefined,\n            } as PageProps & { search: unknown },\n            slotContext,\n          );\n          const slotProps = await parseRouteModuleProps(slotModule, {\n            props: rawSlotProps,\n            search: searchParamsObject,\n            routePath: slot.route.pattern,\n          });\n          const metadata = routeManifest.slots.find(\n            (entry) =>\n              entry.name === slot.name &&\n              entry.ownerPattern === slot.ownerPattern &&\n              entry.pattern === slot.route.pattern,\n          ) ?? {\n            isClientComponent: false,\n            shouldHydrate: false,\n          };\n\n          return {\n            ...slot,\n            module: slotModule,\n            props: slotProps,\n            isClientComponent: metadata.isClientComponent,\n            shouldHydrate: metadata.shouldHydrate,\n          };\n        }),\n      );\n      const shouldHydrate = moduleMetadata.shouldHydrate;\n      if (moduleMetadata.suppressedAsyncHydration) {\n        warnSuppressedAsyncHydrationOnce(route.modulePath);\n      }\n      const layoutHydrationMetadata = layouts.map((layout) => {\n        const manifestEntry = routeManifest.layouts.find(\n          (entry) => entry.pattern === layout.pattern,\n        ) as\n          | {\n              isClientComponent?: boolean;\n              shouldHydrate?: boolean;\n              islandStrategy?: \"load\" | \"interaction\" | \"visible\" | \"idle\" | null;\n              hasIsolatedClientBoundaries?: boolean;\n            }\n          | undefined;\n        if (typeof manifestEntry?.shouldHydrate === \"boolean\") {\n          return {\n            isClientComponent: manifestEntry.isClientComponent === true,\n            shouldHydrate: manifestEntry.shouldHydrate,\n            islandStrategy: manifestEntry.islandStrategy ?? null,\n            ...(manifestEntry.hasIsolatedClientBoundaries === true\n              ? { hasIsolatedClientBoundaries: true }\n              : {}),\n          };\n        }\n        return {\n          isClientComponent: false,\n          shouldHydrate: false,\n          islandStrategy: null,\n        };\n      });\n      const shouldHydrateLayout = layoutHydrationMetadata.some(\n        (metadata) => metadata.shouldHydrate,\n      );\n      const clientLayouts = layouts.map((layout, index) => ({\n        pattern: layout.pattern,\n        modulePath: toViteModuleId(layout.modulePath, this.config.root),\n        shouldHydrate: layoutHydrationMetadata[index]?.shouldHydrate === true,\n        islandStrategy: layoutHydrationMetadata[index]?.islandStrategy ?? null,\n        ...(layoutHydrationMetadata[index]?.hasIsolatedClientBoundaries === true\n          ? { hasIsolatedClientBoundaries: true }\n          : {}),\n      }));\n      const hydrationStrategies = [\n        ...(shouldHydrate && moduleMetadata.islandStrategy ? [moduleMetadata.islandStrategy] : []),\n        ...layoutHydrationMetadata.flatMap((metadata) =>\n          metadata.shouldHydrate && metadata.islandStrategy ? [metadata.islandStrategy] : [],\n        ),\n      ];\n      const hydrationIslandStrategy = hydrationStrategies.every(\n        (strategy) => strategy === hydrationStrategies[0],\n      )\n        ? (hydrationStrategies[0] ?? \"load\")\n        : \"load\";\n      const hasHydratableRouteSlots = renderedRouteSlots.some(\n        (slot) => slot.isClientComponent || slot.shouldHydrate,\n      );\n      const hasIsolatedClientBoundaries =\n        routeManifestEntry?.hasIsolatedClientBoundaries === true ||\n        layoutHydrationMetadata.some((metadata) => metadata.hasIsolatedClientBoundaries === true);\n\n      (req as any).__FARM_PAGE_PATH__ = route.modulePath;\n      (req as any).__FARM_ROUTE__ = pathname;\n      (req as any).__FARM_IS_CLIENT_COMPONENT__ = isClientComponent;\n      (req as any).__FARM_PAGE_SHOULD_HYDRATE__ = shouldHydrate;\n      (req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ = shouldHydrateLayout;\n      (req as any).__FARM_LAYOUTS__ = clientLayouts;\n      if (hasIsolatedClientBoundaries) {\n        (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\n      }\n      (req as any).__FARM_SHOULD_HYDRATE__ =\n        shouldHydrate || shouldHydrateLayout || hasIsolatedClientBoundaries;\n      (req as any).__FARM_ISLAND_STRATEGY__ = hydrationIslandStrategy;\n      (req as any).__FARM_HAS_HYDRATABLE_ROUTE_SLOTS__ = hasHydratableRouteSlots;\n      (req as any).__FARM_LOADING_MODULE_PATH__ = loadingBoundaryEntry?.modulePath\n        ? toViteModuleId(loadingBoundaryEntry.modulePath, this.config.root)\n        : null;\n      (req as any).__FARM_ROUTE_SLOTS__ = renderedRouteSlots.map((slot) => ({\n        name: slot.name,\n        ownerPattern: slot.ownerPattern,\n        containerId: slot.containerId,\n        interception: slot.interception,\n        fallback: slot.fallback,\n        modulePath: slot.route.modulePath,\n        isClientComponent: slot.isClientComponent,\n        shouldHydrate: slot.shouldHydrate,\n        props: {\n          params: slot.props.params,\n          search: (slot.props as any).search,\n          searchParams: (slot.props as any).search,\n          ...(\"data\" in slot.props ? { data: (slot.props as any).data } : {}),\n          ...((slot.props as any).__farmCanonicalPath\n            ? { __farmCanonicalPath: (slot.props as any).__farmCanonicalPath }\n            : {}),\n          ...((slot.props as any).__farmRoutePropsResolved\n            ? { __farmRoutePropsResolved: true }\n            : {}),\n          path: pathname,\n        },\n      }));\n      // Store pageProps for client-side hydration (serializable version - no Promises)\n      (req as any).__FARM_PROPS__ = {\n        params: pageProps.params,\n        search: (pageProps as any).search,\n        searchParams: (pageProps as any).search,\n        ...(\"data\" in pageProps ? { data: (pageProps as any).data } : {}),\n        ...((pageProps as any).__farmCanonicalPath\n          ? { __farmCanonicalPath: (pageProps as any).__farmCanonicalPath }\n          : {}),\n        ...((pageProps as any).__farmRoutePropsResolved ? { __farmRoutePropsResolved: true } : {}),\n        path: pathname,\n        middleware:\n          middlewareMap.size > 0\n            ? {\n                data: Object.fromEntries(middlewareMap),\n              }\n            : undefined,\n        context:\n          pluginExposedContext.size > 0\n            ? {\n                data: Object.fromEntries(pluginExposedContext),\n              }\n            : undefined,\n      };\n\n      // Load layout modules\n      const layoutModules = await Promise.all(\n        layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n      );\n\n      const mergedMetadata = await this.resolveRouteMetadata({\n        layoutModules,\n        routeModule,\n        pageProps,\n        pathname,\n      });\n\n      // Store metadata on request for renderWithSSR\n      (req as any).__FARM_METADATA__ = mergedMetadata;\n\n      // Get middleware data for AsyncLocalStorage\n      const middlewareDataForContext = middlewareMap;\n\n      await _runWithMiddlewareData(middlewareDataForContext, async () => {\n        await _runWithMiddlewareContext(middlewareContext, async () => {\n          await _runWithCurrentRequest(currentRequest, async () => {\n            let pageElement: any = this.rendererRuntime.createElement(PageComponent, pageProps);\n\n            if (LoadingFallbackComponent) {\n              const loadingFallback = this.rendererRuntime.createElement(LoadingFallbackComponent, {\n                ...createRouteStateProps({\n                  params,\n                  searchParamsObject,\n                  path: pathname,\n                  middlewareMap,\n                  pluginExposedContext,\n                }),\n              });\n\n              pageElement = this.rendererRuntime.createElement(\n                this.rendererRuntime.Suspense,\n                { fallback: loadingFallback },\n                pageElement,\n              );\n            }\n\n            // A route-wide page owns every compiled client component beneath\n            // its React root. Keep shared leaf modules as ordinary components\n            // here even when an isolated layout also imports the same module.\n            if ((isClientComponent || shouldHydrate) && !shouldHydrateLayout) {\n              pageElement = this.wrapClientGraph(pageElement);\n            }\n\n            // Every route gets a stable HTML boundary. Server-only pages keep\n            // native markup with no React root; interactive pages hydrate this\n            // exact boundary.\n            pageElement = this.createPageBoundary(pageElement, {\n              pageShouldHydrate: isClientComponent || shouldHydrate,\n              layoutShouldHydrate: shouldHydrateLayout,\n              islandStrategy: hydrationIslandStrategy,\n            });\n\n            let wrappedElement: any = pageElement;\n            for (let i = layoutModules.length - 1; i >= 0; i--) {\n              const layoutModule = layoutModules[i];\n              const layoutEntry = layouts[i];\n              const LayoutComponent = layoutModule.default;\n              const slotProps: Record<string, any> = {};\n              for (const slot of renderedRouteSlots) {\n                if (slot.ownerPattern !== layoutEntry.pattern) continue;\n\n                let slotElement = this.rendererRuntime.createElement(\n                  slot.module.default,\n                  slot.props,\n                );\n                slotElement = this.wrapClientGraph(slotElement);\n                slotElement = this.rendererRuntime.createElement(\n                  \"div\",\n                  {\n                    id: slot.containerId,\n                    \"data-farm-route-slot\": slot.name,\n                    \"data-farm-slot-owner\": slot.ownerPattern,\n                  },\n                  slotElement,\n                );\n                slotProps[slot.name] = slotElement;\n              }\n              wrappedElement = this.rendererRuntime.createElement(LayoutComponent, {\n                children: wrappedElement,\n                params,\n                ...slotProps,\n              });\n              wrappedElement = this.createLayoutBoundary(layoutEntry.pattern, wrappedElement);\n            }\n\n            if (shouldHydrateLayout) {\n              wrappedElement = this.wrapClientGraph(wrappedElement);\n            }\n\n            if (ErrorFallbackComponent && this.rendererRuntime.ErrorBoundary) {\n              wrappedElement = this.rendererRuntime.createElement(\n                this.rendererRuntime.ErrorBoundary,\n                {\n                  Fallback: ErrorFallbackComponent,\n                  fallbackProps: {\n                    ...createRouteStateProps({\n                      params,\n                      searchParamsObject,\n                      path: pathname,\n                      middlewareMap,\n                      pluginExposedContext,\n                    }),\n                  },\n                },\n                wrappedElement,\n              );\n            }\n\n            const integratedElement = await this.wrapWithIntegrationProviders(wrappedElement);\n            const pprHeaders = renderingConfig.ppr\n              ? this.getPPRHeaders(pprShellOptions ? \"miss\" : \"bypass\", renderingConfig.revalidate)\n              : undefined;\n\n            // Render with middleware data available\n            await this.renderWithSSR(\n              integratedElement,\n              req,\n              res,\n              () => {\n                _clearCurrentMiddlewareData();\n                _clearCurrentMiddlewareContext();\n              },\n              {\n                responseHeaders: pprHeaders,\n                routeManifest,\n                captureStaticShell: Boolean(pprShellOptions),\n                observabilityRoute: pathname,\n                onSuspenseHoleDetected: pprShellOptions\n                  ? () =>\n                      emitFarmEvent({\n                        type: \"ppr.suspense.holeDetected\",\n                        route: pathname,\n                      })\n                  : undefined,\n                onComplete:\n                  pprShellOptions && req.method !== \"HEAD\"\n                    ? (html) => this.cachePPRShell(pprShellOptions, html)\n                    : undefined,\n              },\n            );\n            if (pprRefreshRoute) {\n              emitFarmEvent({\n                type: \"ppr.refresh.complete\",\n                route: pprRefreshRoute,\n                durationMs: Date.now() - renderStartTime,\n              });\n            }\n            completeRender(res.statusCode || 200, pathname);\n          });\n        });\n      });\n    } catch (caughtError) {\n      let error = caughtError;\n\n      if (isWebResponse(error)) {\n        if (!res.headersSent && !(res as any).writableEnded) {\n          await sendWebResponse(res, error);\n        } else if (!(res as any).writableEnded) {\n          res.end();\n        }\n        completeRender(error.status, pathname);\n        return;\n      }\n\n      if (isFarmRedirectError(error)) {\n        const redirect = getFarmRedirectError(error)!;\n        const snapshot = getFarmI18nClientSnapshot();\n        const redirectUrl =\n          snapshot && redirect.url.startsWith(\"/\") && !redirect.url.startsWith(\"//\")\n            ? localizeFarmHref(redirect.url, snapshot.locale, snapshot)\n            : redirect.url;\n        emitFarmEvent({\n          type: \"route.redirect\",\n          from: pathname,\n          to: redirectUrl,\n          status: redirect.status,\n        });\n        if (!res.headersSent && !(res as any).writableEnded) {\n          res.statusCode = redirect.status;\n          res.setHeader(\"Location\", redirectUrl);\n          res.end();\n        } else if (!(res as any).writableEnded) {\n          res.end();\n        }\n        completeRender(redirect.status, pathname);\n        return;\n      }\n\n      if (isFarmNotFoundError(error)) {\n        emitFarmEvent({ type: \"route.notFound\", pathname });\n        if (!res.headersSent && !(res as any).writableEnded) {\n          try {\n            await this.render404(req, res);\n            completeRender(404, pathname);\n            return;\n          } catch (notFoundRenderError) {\n            error = notFoundRenderError;\n          }\n        } else {\n          if (!(res as any).writableEnded) {\n            res.end();\n          }\n          completeRender(404, pathname);\n          return;\n        }\n      }\n\n      emitFarmEvent({ type: \"render.error\", route: pathname, error });\n      const errorStatus = resolveDefaultErrorStatus(error);\n      if (pprRefreshRoute) {\n        emitFarmEvent({\n          type: \"ppr.refresh.error\",\n          route: pprRefreshRoute,\n          error,\n        });\n      }\n      logger.error(`Error rendering page: ${error}`);\n\n      if (res.headersSent || (res as any).writableEnded) {\n        if (!(res as any).writableEnded) {\n          res.end();\n        }\n        return;\n      }\n\n      if (errorBoundaryEntry) {\n        const rendered = await this.renderRouteErrorBoundary(req, res, {\n          pathname,\n          params,\n          layouts,\n          searchParamsObject,\n          middlewareMap,\n          middlewareContext,\n          pluginExposedContext,\n          error,\n          statusCode: errorStatus,\n          errorModulePath: errorBoundaryEntry.modulePath,\n        });\n\n        if (rendered) {\n          return;\n        }\n      }\n\n      await this.renderError(req, res, error, errorStatus);\n    }\n  }\n\n  private async wrapWithIntegrationProviders(element: any): Promise<any> {\n    const providers = getIntegrationProviders(this.config.integrations);\n    let wrapped = element;\n\n    for (let i = providers.length - 1; i >= 0; i--) {\n      const provider = providers[i];\n      if (provider.component || provider.type === \"clerk\") {\n        if (!isReactRenderer(this.config.renderer)) {\n          throw new Error(\n            `Integration provider \\`${provider.type}\\` currently requires the React renderer.`,\n          );\n        }\n        let ProviderComponent;\n        if (isFarmIntegrationProviderComponentReference(provider.component)) {\n          const providerModuleId = provider.component.module.startsWith(\".\")\n            ? toViteModuleId(\n                path.resolve(this.config.root, provider.component.module),\n                this.config.root,\n              )\n            : provider.component.module;\n          const providerModule = this.viteServer\n            ? await this.viteServer.ssrLoadModule(providerModuleId)\n            : await importRuntimeModule(\n                provider.component.module.startsWith(\".\")\n                  ? pathToFileURL(path.resolve(this.config.root, provider.component.module)).href\n                  : provider.component.module,\n              );\n          ProviderComponent = providerModule[provider.component.export || \"default\"];\n        } else if (typeof provider.component === \"function\") {\n          ProviderComponent = provider.component;\n        } else if (provider.type === \"clerk\") {\n          if (!cachedClerkProvider) {\n            cachedClerkProvider = await importRuntimeModule(\"@clerk/react\");\n          }\n          ProviderComponent = cachedClerkProvider!.ClerkProvider;\n        } else {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` has an invalid component reference.`,\n          );\n        }\n        if (!ProviderComponent) {\n          throw new Error(\n            `Integration provider \\`${provider.name}\\` did not export its configured component.`,\n          );\n        }\n\n        wrapped = this.rendererRuntime.createElement(\n          ProviderComponent,\n          provider.props || {},\n          wrapped,\n        );\n      }\n    }\n\n    return wrapped;\n  }\n\n  private async resolveRouteMetadata(options: {\n    layoutModules: Array<Record<string, any>>;\n    routeModule: RouteModule;\n    pageProps: PageProps;\n    pathname: string;\n  }): Promise<Record<string, any>> {\n    let metadata: Record<string, any> = {};\n\n    for (const layoutModule of options.layoutModules) {\n      metadata = mergeMetadata(metadata, layoutModule.metadata);\n      if (typeof layoutModule.generateMetadata === \"function\") {\n        metadata = mergeMetadata(\n          metadata,\n          await layoutModule.generateMetadata({\n            params: options.pageProps.params,\n          }),\n        );\n      }\n    }\n\n    metadata = mergeMetadata(metadata, (options.routeModule as any).metadata);\n    if (typeof (options.routeModule as any).generateMetadata === \"function\") {\n      metadata = mergeMetadata(\n        metadata,\n        await (options.routeModule as any).generateMetadata(options.pageProps),\n      );\n    }\n\n    if (!metadata.manifest) {\n      const manifestMatch = this.routeManager.getMatchingMetadataRoute(\n        options.pathname,\n        \"manifest\",\n      );\n      if (manifestMatch) {\n        const rawHref = this.routeManager.resolveMetadataRoutePath(\n          manifestMatch.metadata,\n          manifestMatch.params,\n        );\n        const snapshot = getFarmI18nClientSnapshot();\n        const localizedHref = snapshot\n          ? localizeFarmHref(rawHref, snapshot.locale, snapshot)\n          : rawHref;\n        metadata.manifest = applyFarmBasePath(localizedHref, this.config.basePath);\n      }\n    }\n\n    for (const kind of [\"opengraph\", \"twitter\"] as const) {\n      const reference = await this.resolveMetadataImageReference(kind, options.pathname);\n      if (reference) {\n        metadata = addMetadataImageReference(metadata, reference);\n      }\n    }\n\n    return metadata;\n  }\n\n  private async resolveMetadataImageReference(\n    kind: MetadataImageKind,\n    pathname: string,\n  ): Promise<FarmMetadataImageReference | null> {\n    const match = this.routeManager.getMatchingMetadataImage(pathname, kind);\n    if (!match) return null;\n\n    const rawHref = this.routeManager.resolveMetadataImagePath(match.image, match.params);\n    const snapshot = getFarmI18nClientSnapshot();\n    const localizedHref = snapshot ? localizeFarmHref(rawHref, snapshot.locale, snapshot) : rawHref;\n    const href = applyFarmBasePath(localizedHref, this.config.basePath);\n    const reference: FarmMetadataImageReference = {\n      kind,\n      href,\n    };\n\n    if (match.image.sourceType === \"static\" && match.image.staticInfo) {\n      return {\n        ...reference,\n        width: match.image.staticInfo.width,\n        height: match.image.staticInfo.height,\n        alt: match.image.staticInfo.alt,\n        contentType: match.image.staticInfo.contentType,\n      };\n    }\n\n    try {\n      const imageModule = await this.routeManager.loadRouteModule(match.image.modulePath);\n      const size = (imageModule as any).size;\n      if (size && typeof size === \"object\") {\n        reference.width = typeof size.width === \"number\" ? size.width : undefined;\n        reference.height = typeof size.height === \"number\" ? size.height : undefined;\n      }\n      if (typeof (imageModule as any).alt === \"string\") {\n        reference.alt = (imageModule as any).alt;\n      }\n      if (typeof (imageModule as any).contentType === \"string\") {\n        reference.contentType = (imageModule as any).contentType;\n      }\n    } catch (error) {\n      logger.warn(`Failed to read ${kind} image metadata for ${pathname}: ${error}`);\n    }\n\n    return reference;\n  }\n\n  private async renderMetadataRoute(\n    req: FarmRequest,\n    res: FarmResponse,\n    match: NonNullable<ReturnType<RouteManager[\"matchMetadataRoute\"]>>,\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    try {\n      const routeModule = await this.routeManager.loadRouteModule(match.metadata.modulePath);\n      if (routeModule.default === undefined) {\n        throw new Error(\n          `Metadata route module ${match.metadata.modulePath} does not export a default value or handler`,\n        );\n      }\n\n      const request = createWebRequestFromFarmRequest(req, {\n        trustProxy: this.config.server?.trustProxy,\n      });\n      const url = new URL(request.url);\n      const value =\n        typeof routeModule.default === \"function\"\n          ? await (routeModule.default as any)({\n              request,\n              params: match.params,\n              searchParams: url.searchParams,\n              path: match.routePath,\n            })\n          : routeModule.default;\n      const response = createFarmMetadataRouteResponse(match.metadata.kind, value, routeModule, {\n        method,\n      });\n      await sendWebResponse(res as any, response);\n    } catch (error) {\n      logger.error(`Metadata route render failed for ${match.metadata.modulePath}: ${error}`);\n      await sendWebResponse(\n        res as any,\n        new Response(\"Internal Server Error\", {\n          status: 500,\n          headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n        }),\n      );\n    }\n  }\n\n  private async renderMetadataImage(\n    req: FarmRequest,\n    res: FarmResponse,\n    options: {\n      pathname: string;\n      pagePath: string;\n      params: Record<string, string>;\n      searchParamsObject: Record<string, string | string[] | undefined>;\n      image: {\n        modulePath: string;\n        kind: MetadataImageKind;\n        sourceType?: \"module\" | \"static\";\n        staticInfo?: StaticMetadataImageInfo;\n      };\n    },\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    if (options.image.sourceType === \"static\") {\n      if (!options.image.staticInfo) {\n        throw new Error(`Static metadata image ${options.image.modulePath} is missing file info`);\n      }\n      await this.writeStaticMetadataImageResponse(req, res, {\n        modulePath: options.image.modulePath,\n        staticInfo: options.image.staticInfo,\n      });\n      return;\n    }\n\n    const imageModule = await this.routeManager.loadRouteModule(options.image.modulePath);\n    if (!imageModule.default) {\n      throw new Error(\n        `Metadata image module ${options.image.modulePath} does not export a default component or handler`,\n      );\n    }\n\n    const imageProps: PageProps = {\n      params: options.params,\n      searchParams: Promise.resolve(options.searchParamsObject),\n      path: options.pagePath,\n    };\n    const handlerResult =\n      typeof imageModule.default === \"function\"\n        ? await (imageModule.default as any)(imageProps)\n        : imageModule.default;\n\n    await this.writeMetadataImageResponse(req, res, handlerResult, imageModule);\n  }\n\n  private async writeMetadataImageResponse(\n    req: FarmRequest,\n    res: FarmResponse,\n    value: unknown,\n    imageModule: RouteModule,\n  ): Promise<void> {\n    const ifNoneMatch = req.headers[\"if-none-match\"];\n    const response = await createFarmMetadataImageResponse(value, imageModule, {\n      method: req.method,\n      ifNoneMatch: Array.isArray(ifNoneMatch) ? ifNoneMatch[0] : ifNoneMatch,\n    });\n    await sendWebResponse(res as any, response);\n  }\n\n  private async writeStaticMetadataImageResponse(\n    req: FarmRequest,\n    res: FarmResponse,\n    image: { modulePath: string; staticInfo: StaticMetadataImageInfo },\n  ): Promise<void> {\n    const method = (req.method || \"GET\").toUpperCase();\n    if (method !== \"GET\" && method !== \"HEAD\") {\n      res.statusCode = 405;\n      res.setHeader(\"Allow\", \"GET, HEAD\");\n      res.end();\n      return;\n    }\n\n    const etag = `\"${image.staticInfo.hash}\"`;\n    const requestUrl = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const isVersioned = requestUrl.searchParams.get(\"v\") === image.staticInfo.hash;\n\n    res.setHeader(\"Content-Type\", image.staticInfo.contentType);\n    res.setHeader(\"Content-Length\", image.staticInfo.byteLength);\n    res.setHeader(\"ETag\", etag);\n    res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n    res.setHeader(\n      \"Cache-Control\",\n      isVersioned ? \"public, max-age=31536000, immutable\" : \"public, max-age=0, must-revalidate\",\n    );\n\n    if (matchesFarmIfNoneMatch(req.headers[\"if-none-match\"], etag)) {\n      res.statusCode = 304;\n      res.end();\n      return;\n    }\n\n    res.statusCode = res.statusCode || 200;\n    if (method === \"HEAD\") {\n      res.end();\n      return;\n    }\n\n    res.write(await fs.promises.readFile(image.modulePath));\n    res.end();\n  }\n\n  private async renderRouteErrorBoundary(\n    req: FarmRequest,\n    res: FarmResponse,\n    options: {\n      pathname: string;\n      params: Record<string, string>;\n      layouts: Array<{ modulePath: string }>;\n      searchParamsObject: Record<string, string | string[] | undefined>;\n      middlewareMap: Map<string, any>;\n      middlewareContext: Map<string, any>;\n      pluginExposedContext: Map<string, any>;\n      error: unknown;\n      statusCode: number;\n      errorModulePath: string;\n    },\n  ): Promise<boolean> {\n    try {\n      if (res.headersSent || (res as any).writableEnded) {\n        if (!(res as any).writableEnded) {\n          res.end();\n        }\n        return true;\n      }\n\n      const errorModule = await this.routeManager.loadRouteModule(options.errorModulePath);\n      if (!errorModule.default) {\n        return false;\n      }\n\n      const ErrorComponent = errorModule.default;\n      const errorElement = this.rendererRuntime.createElement(ErrorComponent, {\n        ...createRouteStateProps({\n          params: options.params,\n          searchParamsObject: options.searchParamsObject,\n          path: options.pathname,\n          middlewareMap: options.middlewareMap,\n          pluginExposedContext: options.pluginExposedContext,\n        }),\n        error: options.error,\n        reset: () => {},\n      });\n\n      let wrapped: any = errorElement;\n      const layoutModules = await Promise.all(\n        options.layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n      );\n      for (let i = layoutModules.length - 1; i >= 0; i--) {\n        const LayoutComponent = layoutModules[i].default;\n        wrapped = this.rendererRuntime.createElement(LayoutComponent, {\n          children: wrapped,\n          params: options.params,\n        });\n      }\n\n      wrapped = await this.wrapWithIntegrationProviders(wrapped);\n\n      const html = await _runWithMiddlewareData(options.middlewareMap, () =>\n        _runWithMiddlewareContext(options.middlewareContext, () =>\n          this.rendererRuntime.renderToString(wrapped),\n        ),\n      );\n      res.statusCode = options.statusCode;\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      // A PPR shell failure leaves the \"miss\" caching headers (s-maxage,\n      // stale-while-revalidate, X-Farm-PPR) on res. Error responses must not be\n      // cached by shared/CDN caches, so clear them here, matching renderError.\n      res.setHeader(\"Cache-Control\", \"private, no-store\");\n      res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n      if (typeof res.removeHeader === \"function\") {\n        res.removeHeader(\"X-Farm-PPR\");\n      }\n      res.write(this.createFullHTML(html, false, options.pathname));\n      res.end();\n      return true;\n    } catch (renderError) {\n      logger.warn(`Failed to render route-level error boundary: ${renderError}`);\n      return false;\n    }\n  }\n\n  private async renderBufferedSSR(\n    element: unknown,\n    req: FarmRequest,\n    res: FarmResponse,\n    clearMiddlewareData?: () => void,\n    options: {\n      responseHeaders?: Record<string, string> | undefined;\n      routeManifest?: ReturnType<RouteManager[\"generateClientManifest\"]>;\n      onComplete?: (html: string) => void | Promise<void>;\n      captureStaticShell?: boolean;\n      observabilityRoute?: string;\n      onSuspenseHoleDetected?: () => void;\n    } = {},\n  ): Promise<void> {\n    const startedAt = Date.now();\n    const route = options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n    emitFarmEvent({ type: \"render.stream.start\", route });\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    for (const [key, value] of Object.entries(options.responseHeaders || {})) {\n      res.setHeader(key, value);\n    }\n\n    try {\n      const manifest =\n        options.routeManifest ?? this.routeManager.generateClientManifest(this.config.root);\n      const clientManifest = {\n        clientEntry: \"/@farm/client.js\",\n        routes: {} as Record<string, any>,\n        layouts: {} as Record<string, any>,\n        slots: [] as Array<Record<string, any>>,\n        sharedAssets: [\n          {\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n          },\n          ...this.collectDevStyleHrefs().map((href) => ({\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href },\n          })),\n        ],\n      };\n\n      for (const routeEntry of manifest.routes) {\n        clientManifest.routes[routeEntry.pattern] = {\n          modulePath: routeEntry.modulePath,\n          pattern: routeEntry.pattern,\n          segments: routeEntry.segments,\n          search: routeEntry.search,\n          isClientComponent: routeEntry.isClientComponent,\n          shouldHydrate: routeEntry.shouldHydrate,\n          islandStrategy: routeEntry.islandStrategy,\n          renderPlan: routeEntry.renderPlan,\n          preloads: [routeEntry.modulePath],\n          assets: [],\n        };\n      }\n      for (const layoutEntry of manifest.layouts) {\n        clientManifest.layouts[layoutEntry.pattern] = {\n          modulePath: layoutEntry.modulePath,\n          pattern: layoutEntry.pattern,\n          shouldHydrate: layoutEntry.shouldHydrate,\n          islandStrategy: layoutEntry.islandStrategy,\n          preloads: [layoutEntry.modulePath],\n          assets: [],\n        };\n      }\n      for (const slotEntry of manifest.slots ?? []) {\n        clientManifest.slots.push({\n          ...slotEntry,\n          preloads: [slotEntry.modulePath],\n          assets: [],\n        });\n      }\n\n      const routeSlots = ((req as any).__FARM_ROUTE_SLOTS__ || []).map(\n        (slot: Record<string, any>) => ({\n          ...slot,\n          modulePath:\n            typeof slot.modulePath === \"string\"\n              ? toViteModuleId(slot.modulePath, this.config.root)\n              : slot.modulePath,\n        }),\n      );\n      const deferredProps = prepareDeferredData({\n        page: (req as any).__FARM_PROPS__ || {},\n        slots: routeSlots,\n      });\n      const pagePath = (req as any).__FARM_PAGE_PATH__;\n      const relativePath = pagePath\n        ? toViteModuleId(pagePath, this.config.root)\n        : \"/src/app/page.tsx\";\n      const deploymentId = this.getDeploymentId();\n      const bootstrapScript = `<script>\nwindow.__FARM_PROPS__ = ${serializeInlineValue((deferredProps.data as any).page)};\nwindow.__FARM_ROUTE_SLOTS__ = ${serializeInlineValue((deferredProps.data as any).slots)};\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(deploymentId)};\nwindow.__FARM_PATH__ = ${JSON.stringify((req as any).__FARM_ROUTE__ || req.url || \"/\")};\nwindow.__FARM_IS_CLIENT__ = ${JSON.stringify((req as any).__FARM_IS_CLIENT_COMPONENT__ === true)};\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_PAGE_SHOULD_HYDRATE__ === true)};\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ === true)};\nwindow.__FARM_LAYOUTS__ = ${JSON.stringify((req as any).__FARM_LAYOUTS__ || [])};\nwindow.__FARM_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_SHOULD_HYDRATE__ === true)};\n${\n  (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true\n    ? \"window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\"\n    : \"\"\n}\nwindow.__FARM_ISLAND_STRATEGY__ = ${JSON.stringify((req as any).__FARM_ISLAND_STRATEGY__ || \"load\")};\nwindow.__FARM_PAGE_MODULE__ = ${JSON.stringify(relativePath)};\nwindow.__FARM_LOADING_MODULE__ = ${JSON.stringify((req as any).__FARM_LOADING_MODULE_PATH__ || null)};\nwindow.__FARM_MANIFEST__ = ${JSON.stringify(clientManifest)};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${getFarmI18nClientSnapshot() ? `window.__FARM_I18N__ = ${serializeInlineValue(getFarmI18nClientSnapshot())};` : \"\"}\n</script>`;\n      const deferredScript = createDeferredHydrationScript(deferredProps.records);\n      const rendererHydrationScript = this.rendererRuntime.generateHydrationScript?.() || \"\";\n      const { html: content, head: rendererHead } =\n        await this.renderElementToDocumentParts(element);\n      const {\n        title,\n        tags: metaTags,\n        hasFavicon,\n        hasExplicitTitle,\n      } = renderMetadataHead((req as any).__FARM_METADATA__, {\n        pathname: getFarmMetadataPathname(req),\n        jsonLd: this.config.agent?.jsonLd,\n      });\n      // A renderer-emitted <title> (e.g. <svelte:head>) must take effect: the\n      // first <title> in a document wins, so the fallback framework title is\n      // suppressed when the renderer supplies one. Explicit metadata titles\n      // still come first and win.\n      const documentTitleTag =\n        !hasExplicitTitle && /<title[\\s>]/i.test(rendererHead) ? \"\" : `<title>${title}</title>`;\n      const rendererHasTitle = /<title[\\s>]/i.test(rendererHead);\n      const i18nSnapshot = getFarmI18nClientSnapshot();\n      const alternateTags = i18nSnapshot\n        ? renderI18nAlternateLinks((req as any).__FARM_ROUTE__ || req.url || \"/\", i18nSnapshot)\n        : \"\";\n      const themeDocument = createFarmThemeDocumentParts(\n        this.config.theme,\n        this.config.basePath,\n        getFarmTheme(),\n      );\n\n      // A layout that returns its own full `<html>` document is composed as the\n      // document (Farm assets merged in) rather than nested inside the shell,\n      // matching the production build and avoiding invalid nested documents.\n      const fullDocument = extractFarmFullDocument(content);\n      let html: string;\n      if (fullDocument) {\n        warnFarmFullDocumentLayout();\n        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      if ((req.method || \"GET\").toUpperCase() !== \"HEAD\") res.write(html);\n      res.end();\n      await options.onComplete?.(html);\n      emitFarmEvent({\n        type: \"render.stream.complete\",\n        route,\n        durationMs: Date.now() - startedAt,\n      });\n    } catch (error) {\n      emitFarmEvent({ type: \"render.error\", route, error });\n      throw error;\n    } finally {\n      clearMiddlewareData?.();\n    }\n  }\n\n  private async renderWithSSR(\n    element: any,\n    req: FarmRequest,\n    res: FarmResponse,\n    clearMiddlewareData?: () => void,\n    options: {\n      responseHeaders?: Record<string, string> | undefined;\n      routeManifest?: ReturnType<RouteManager[\"generateClientManifest\"]>;\n      onComplete?: (html: string) => void | Promise<void>;\n      captureStaticShell?: boolean;\n      observabilityRoute?: string;\n      onSuspenseHoleDetected?: () => void;\n    } = {},\n  ): Promise<void> {\n    const renderToPipeableStream = this.rendererRuntime.renderToPipeableStream;\n    const fullDocumentRouteKey =\n      options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n    // A full-document layout can't be composed once the stream's shell is\n    // flushed, so a route previously seen to render one is served through the\n    // buffered path, which produces a valid single document.\n    if (!renderToPipeableStream || fullDocumentRoutes.has(fullDocumentRouteKey)) {\n      return this.renderBufferedSSR(element, req, res, clearMiddlewareData, options);\n    }\n\n    return new Promise((resolve, reject) => {\n      const streamStartTime = Date.now();\n      const observabilityRoute =\n        options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n      const deploymentId = this.getDeploymentId();\n      emitFarmEvent({ type: \"render.stream.start\", route: observabilityRoute });\n      res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n      for (const [key, value] of Object.entries(options.responseHeaders || {})) {\n        res.setHeader(key, value);\n      }\n      const htmlParts: string[] = [];\n      // 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\n      // Get the page path for client-side hydration\n      const pagePath = (req as any).__FARM_PAGE_PATH__;\n      const isClientComponent = (req as any).__FARM_IS_CLIENT_COMPONENT__ === true;\n      const relativePath = pagePath\n        ? toViteModuleId(pagePath, this.config.root)\n        : \"/src/app/page.tsx\";\n\n      // Generate manifest for client-side SPA navigation (TanStack Start pattern)\n      // This manifest is inlined in HTML - no separate file or API endpoint\n      const manifest =\n        options.routeManifest ?? this.routeManager.generateClientManifest(this.config.root);\n\n      // Convert to object format for client\n      const clientManifest = {\n        clientEntry: \"/@farm/client.js\",\n        routes: {} as Record<string, any>,\n        layouts: {} as Record<string, any>,\n        slots: [] as Array<Record<string, any>>,\n        sharedAssets: [\n          {\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n          },\n          ...this.collectDevStyleHrefs().map((href) => ({\n            tag: \"link\",\n            attrs: { rel: \"stylesheet\", href },\n          })),\n        ],\n      };\n\n      // Convert routes array to object keyed by pattern\n      for (const routeEntry of manifest.routes) {\n        clientManifest.routes[routeEntry.pattern] = {\n          modulePath: routeEntry.modulePath,\n          pattern: routeEntry.pattern,\n          segments: routeEntry.segments,\n          search: routeEntry.search,\n          isClientComponent: routeEntry.isClientComponent,\n          shouldHydrate: routeEntry.shouldHydrate,\n          islandStrategy: routeEntry.islandStrategy,\n          renderPlan: routeEntry.renderPlan,\n          preloads: [routeEntry.modulePath],\n          assets: [],\n        };\n      }\n\n      // Convert layouts array to object\n      for (const layoutEntry of manifest.layouts) {\n        clientManifest.layouts[layoutEntry.pattern] = {\n          modulePath: layoutEntry.modulePath,\n          pattern: layoutEntry.pattern,\n          shouldHydrate: layoutEntry.shouldHydrate,\n          islandStrategy: layoutEntry.islandStrategy,\n          preloads: [layoutEntry.modulePath],\n          assets: [],\n        };\n      }\n\n      for (const slotEntry of manifest.slots ?? []) {\n        clientManifest.slots.push({\n          ...slotEntry,\n          preloads: [slotEntry.modulePath],\n          assets: [],\n        });\n      }\n\n      // Inject page props, component info, and MANIFEST for client-side SPA\n      // __FARM_MANIFEST__ contains the full route manifest (TanStack Start pattern)\n      const routeSlotPayload = ((req as any).__FARM_ROUTE_SLOTS__ || []).map(\n        (slot: Record<string, any>) => ({\n          ...slot,\n          modulePath:\n            typeof slot.modulePath === \"string\"\n              ? toViteModuleId(slot.modulePath, this.config.root)\n              : slot.modulePath,\n        }),\n      );\n      const deferredProps = prepareDeferredData({\n        page: (req as any).__FARM_PROPS__ || {},\n        slots: routeSlotPayload,\n      });\n      const propsScript = `<script>\nwindow.__FARM_PROPS__ = ${serializeInlineValue((deferredProps.data as any).page)};\nwindow.__FARM_ROUTE_SLOTS__ = ${serializeInlineValue((deferredProps.data as any).slots)};\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(deploymentId)};\nwindow.__FARM_PATH__ = ${JSON.stringify((req as any).__FARM_ROUTE__ || req.url || \"/\")};\nwindow.__FARM_IS_CLIENT__ = ${JSON.stringify(isClientComponent)};\nwindow.__FARM_PAGE_SHOULD_HYDRATE__ = ${JSON.stringify(\n        (req as any).__FARM_PAGE_SHOULD_HYDRATE__ === true,\n      )};\nwindow.__FARM_LAYOUT_SHOULD_HYDRATE__ = ${JSON.stringify(\n        (req as any).__FARM_LAYOUT_SHOULD_HYDRATE__ === true,\n      )};\nwindow.__FARM_LAYOUTS__ = ${JSON.stringify((req as any).__FARM_LAYOUTS__ || [])};\nwindow.__FARM_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_SHOULD_HYDRATE__ === true)};\n${\n  (req as any).__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true\n    ? \"window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ = true;\"\n    : \"\"\n}\nwindow.__FARM_ISLAND_STRATEGY__ = ${JSON.stringify((req as any).__FARM_ISLAND_STRATEGY__ || \"load\")};\nwindow.__FARM_PAGE_MODULE__ = ${JSON.stringify(relativePath)};\nwindow.__FARM_LOADING_MODULE__ = ${JSON.stringify(\n        (req as any).__FARM_LOADING_MODULE_PATH__ || null,\n      )};\nwindow.__FARM_MANIFEST__ = ${JSON.stringify(clientManifest)};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${getFarmI18nClientSnapshot() ? `window.__FARM_I18N__ = ${serializeInlineValue(getFarmI18nClientSnapshot())};` : \"\"}\n</script>`;\n      const hydrationClickQueueScript =\n        isClientComponent ||\n        (req as any).__FARM_SHOULD_HYDRATE__ === true ||\n        (req as any).__FARM_HAS_HYDRATABLE_ROUTE_SLOTS__ === true\n          ? createPreHydrationClickQueueScript()\n          : \"\";\n\n      const {\n        title,\n        tags: metaTags,\n        hasFavicon,\n      } = renderMetadataHead((req as any).__FARM_METADATA__, {\n        pathname: getFarmMetadataPathname(req),\n        jsonLd: this.config.agent?.jsonLd,\n      });\n      const i18nSnapshot = getFarmI18nClientSnapshot();\n      const i18nAlternateTags = i18nSnapshot\n        ? renderI18nAlternateLinks((req as any).__FARM_ROUTE__ || req.url || \"/\", i18nSnapshot)\n        : \"\";\n      const fontHead = renderFarmFontDevHead(this.config.root || process.cwd());\n      const themeDocument = createFarmThemeDocumentParts(\n        this.config.theme,\n        this.config.basePath,\n        getFarmTheme(),\n      );\n\n      // React 19: ensure root is a single DOM node so streaming starts early (avoids Fragment delay)\n      const streamRoot = this.rendererRuntime.createElement(\n        \"div\",\n        { style: { display: \"contents\" } },\n        element,\n      );\n      const devStyleLinks = this.collectDevStyleLinks();\n      const { pipe } = renderToPipeableStream(streamRoot, {\n        onShellReady() {\n          const shellReadyMs = Date.now() - streamStartTime;\n          emitFarmEvent({\n            type: \"render.stream.shellReady\",\n            route: observabilityRoute,\n            durationMs: shellReadyMs,\n          });\n          if (process.env.FARM_VERBOSE) {\n            console.log(`[FARM STREAM] onShellReady at ${shellReadyMs}ms`);\n          }\n          const shell = `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n            i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n          }${themeDocument.attributes}>\n<head>\n  ${themeDocument.head}\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">\n  ${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  <title>${title}</title>${metaTags}${i18nAlternateTags}\n  ${fontHead}\n  <link rel=\"stylesheet\" href=\"/src/app/globals.css\" />${devStyleLinks\n    .map((l) => `\\n  ${l}`)\n    .join(\"\")}\n  <script type=\"module\" src=\"/@vite/client\"></script>\n  ${propsScript}\n  ${hydrationClickQueueScript}\n</head>\n<body class=\"\">\n  <div id=\"root\">`;\n          htmlParts.push(shell);\n          staticShellParts?.push(shell);\n\n          let firstChunk = true;\n          let checkedFullDocument = false;\n          const writableStream = new Writable({\n            write(chunk, encoding, callback) {\n              if (firstChunk && process.env.FARM_VERBOSE) {\n                console.log(`[FARM STREAM] first pipe chunk at ${Date.now() - streamStartTime}ms`);\n                firstChunk = false;\n              }\n              const chunkText = Buffer.isBuffer(chunk) ? chunk.toString() : String(chunk);\n              // The shell was already flushed, so this response still nests the\n              // document; record the route so later requests take the buffered\n              // path (which composes it correctly) and warn the developer once.\n              if (!checkedFullDocument) {\n                checkedFullDocument = true;\n                if (opensFarmFullDocument(chunkText)) {\n                  fullDocumentRoutes.add(fullDocumentRouteKey);\n                  warnFarmFullDocumentLayout();\n                }\n              }\n              htmlParts.push(chunkText);\n\n              if (staticShellParts && 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              res.write(chunk, encoding, () => {\n                if (typeof (res as any).flush === \"function\") (res as any).flush();\n                callback();\n              });\n            },\n            final(callback) {\n              const suspenseRevealFallback = `<script>(function(){function moveFragment(srcId,placeholderId){var src=document.getElementById(srcId),ph=document.getElementById(placeholderId);if(!src||!ph||!ph.parentNode)return false;while(src.firstChild)ph.parentNode.insertBefore(src.firstChild,ph);ph.parentNode.removeChild(ph);if(src.parentNode)src.parentNode.removeChild(src);return true}function revealBoundary(boundaryId,sectionId){var boundary=document.getElementById(boundaryId),section=document.getElementById(sectionId);if(!boundary||!section||!boundary.parentNode)return false;var start=boundary.previousSibling;if(!start||start.nodeType!==8)return false;var parent=boundary.parentNode;var node=boundary;var depth=0;while(node){if(node.nodeType===8){var data=node.data;if(data===\"/$\"||data===\"/&\"){if(depth===0)break;depth--;}else if(data===\"$\"||data===\"$?\"||data===\"$~\"||data===\"$!\"||data===\"&\"){depth++;}}var next=node.nextSibling;parent.removeChild(node);node=next;}while(section.firstChild)parent.insertBefore(section.firstChild,node);if(section.parentNode)section.parentNode.removeChild(section);start.data=\"$\";return true}var tries=0;var timer=setInterval(function(){var changed=false;document.querySelectorAll('div[id^=\"S:\"]').forEach(function(section){var suffix=section.id.slice(2);changed=moveFragment('S:'+suffix,'P:'+suffix)||changed;});document.querySelectorAll('template[id^=\"B:\"]').forEach(function(boundary){var suffix=boundary.id.slice(2);changed=revealBoundary('B:'+suffix,'S:'+suffix)||changed;});tries++;if(tries>80||(!document.querySelector('template[id^=\"B:\"]')&&!document.querySelector('template[id^=\"P:\"]'))){clearInterval(timer);}},50);})();</script>`;\n              const footer = createDocumentFooter({\n                suspenseRevealFallback,\n                deferredHydrationScript: createDeferredHydrationScript(deferredProps.records),\n              });\n              htmlParts.push(footer);\n              res.write(footer);\n              res.end();\n              callback();\n              if (clearMiddlewareData) {\n                clearMiddlewareData();\n              }\n              if (!didError && options.onComplete) {\n                if (staticShellParts) {\n                  staticShellParts.push(\n                    createDocumentFooter({\n                      suspenseRevealFallback,\n                      refreshPPR: staticShellClosed,\n                    }),\n                  );\n                }\n\n                const cachedHtml = staticShellParts\n                  ? staticShellParts.join(\"\")\n                  : htmlParts.join(\"\");\n                Promise.resolve(options.onComplete(cachedHtml)).catch((error) => {\n                  logger.warn(`Failed to cache PPR shell: ${error}`);\n                });\n              }\n              emitFarmEvent({\n                type: \"render.stream.complete\",\n                route: observabilityRoute,\n                durationMs: Date.now() - streamStartTime,\n              });\n              resolve();\n            },\n          });\n\n          // Queue the shell immediately, then start piping the Suspense stream.\n          // Waiting for the write callback can delay the fallback until the whole\n          // response is ready under some dev-server wrappers.\n          res.write(shell);\n          if (typeof (res as any).flush === \"function\") {\n            (res as any).flush();\n          }\n          pipe(writableStream);\n        },\n        onShellError(error) {\n          didError = true;\n          if (!isWebResponse(error) && !isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n            logger.error(`SSR shell error: ${error}`);\n            emitFarmEvent({\n              type: \"render.error\",\n              route: observabilityRoute,\n              error,\n            });\n          }\n\n          if (clearMiddlewareData) {\n            clearMiddlewareData();\n          }\n\n          reject(error);\n        },\n        onError(error) {\n          didError = true;\n          if (!isWebResponse(error) && !isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n            logger.error(`SSR streaming error: ${error}`);\n            emitFarmEvent({\n              type: \"render.error\",\n              route: observabilityRoute,\n              error,\n            });\n          }\n        },\n      });\n    });\n  }\n\n  private async render404(req: FarmRequest, res: FarmResponse): Promise<void> {\n    res.statusCode = 404;\n\n    const pathname = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    }).pathname;\n\n    // Agents that navigate in Markdown (a `.md` URL or `Accept: text/markdown`)\n    // get a Markdown error body instead of the HTML not-found shell.\n    const acceptHeader = req.headers.accept;\n    const accept = Array.isArray(acceptHeader) ? acceptHeader.join(\",\") : acceptHeader;\n    if (farmRequestWantsMarkdown(pathname, accept)) {\n      res.setHeader(\"Content-Type\", FARM_MARKDOWN_CONTENT_TYPE);\n      res.setHeader(\"X-Farm-Markdown-Error\", \"404\");\n      res.setHeader(\"Cache-Control\", \"no-store\");\n      res.end(createFarmMarkdownErrorBody(404, pathname, this.config.basePath || \"/\"));\n      return;\n    }\n\n    try {\n      // Look for custom not-found page\n      const appDir = path.join(this.config.root, this.config.srcDir, \"app\");\n      const notFoundExtensions = getFarmRendererComponentExtensions(this.config.renderer);\n      const notFoundPath = resolveFarmNotFoundComponentPath(\n        this.config,\n        getFarmAppDirectories(this.config),\n      );\n\n      if (notFoundPath) {\n        // Use routeManager to load the module (uses Vite's ssrLoadModule in dev)\n        const notFoundModule = await this.routeManager.loadRouteModule(notFoundPath);\n        const NotFoundComponent = notFoundModule.default;\n\n        if (NotFoundComponent) {\n          // Look for root layout\n          let LayoutComponent: any = null;\n          for (const ext of notFoundExtensions) {\n            const layoutPath = path.join(appDir, `layout${ext}`);\n            if (fs.existsSync(layoutPath)) {\n              const layoutModule = await this.routeManager.loadLayoutModule(layoutPath);\n              LayoutComponent = layoutModule.default;\n              break;\n            }\n          }\n\n          // Render the 404 page\n          let element: any = this.rendererRuntime.createElement(NotFoundComponent, { pathname });\n\n          // Wrap with layout if available\n          if (LayoutComponent) {\n            element = this.rendererRuntime.createElement(LayoutComponent, {\n              children: element,\n            });\n          }\n\n          element = await this.wrapWithIntegrationProviders(element);\n\n          // Render to string\n          const content = await this.rendererRuntime.renderToString(element);\n\n          const html = this.createFullHTML(content, false, pathname);\n          res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n          res.write(html);\n          res.end();\n          return;\n        }\n      }\n    } catch (error) {\n      throw new Error(`Failed to render custom 404 page: ${error}`);\n    }\n\n    // Render the shared adaptive fallback when the app does not provide its own page.\n    const homeHref = escapeHtmlAttribute(applyFarmBasePath(\"/\", this.config.basePath));\n    const defaultContent = `<style>${DEFAULT_NOT_FOUND_STYLES}</style><main class=\"farm-default-not-found\" aria-labelledby=\"farm-default-not-found-title\" aria-describedby=\"farm-default-not-found-description\"><div class=\"farm-default-not-found__content\"><h1 id=\"farm-default-not-found-title\" class=\"farm-default-not-found__code\">404</h1><p id=\"farm-default-not-found-description\" class=\"farm-default-not-found__description\">Not found</p><a class=\"farm-default-not-found__home\" href=\"${homeHref}\">GO HOME</a></div></main>`;\n\n    const html = this.createFullHTML(defaultContent, false, pathname);\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    res.write(html);\n    res.end();\n  }\n\n  private async renderError(\n    req: FarmRequest,\n    res: FarmResponse,\n    error: unknown,\n    statusCode = 500,\n  ): Promise<void> {\n    if (res.headersSent || (res as any).writableEnded) {\n      if (!(res as any).writableEnded) {\n        res.end();\n      }\n      return;\n    }\n\n    res.statusCode = statusCode;\n    const isDev = process.env.NODE_ENV === \"development\";\n    const requestUrl = resolveFarmRequestURL(req, {\n      trustProxy: this.config.server?.trustProxy,\n    });\n    const diagnostics = isDev\n      ? createDefaultErrorDiagnostics(error, this.config.root || process.cwd())\n      : undefined;\n    const statusText = getDefaultErrorStatusText(statusCode);\n    const content = createDefaultErrorMarkup({\n      statusCode,\n      statusText,\n      requestPath: requestUrl.pathname,\n      method: req.method || \"GET\",\n      message: diagnostics?.message,\n      errorName: diagnostics?.name,\n      stack: diagnostics?.stack,\n      sourceFrame: diagnostics?.sourceFrame,\n      development: isDev,\n      farmVersion: FARM_VERSION,\n      nodeVersion: process.version,\n      mode: isDev ? \"development\" : \"production\",\n    });\n\n    const html = this.createFullHTML(\n      content,\n      false,\n      requestUrl.pathname,\n      `${statusCode} - ${statusText}`,\n    );\n\n    res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n    res.setHeader(\"Cache-Control\", \"private, no-store\");\n    res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n    res.write(html);\n    res.end();\n  }\n\n  private createFullHTML(\n    content: string,\n    isClientComponent = false,\n    requestPath = \"/\",\n    metadataHead?: string,\n  ): string {\n    const i18nSnapshot = getFarmI18nClientSnapshot();\n    const clientScript = isClientComponent\n      ? `  <script type=\"module\" src=\"/@farm/client.js\"></script>`\n      : \"\";\n    const integrationManifestScript = `<script>\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(this.getDeploymentId())};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${i18nSnapshot ? `window.__FARM_I18N__ = ${serializeInlineValue(i18nSnapshot)};` : \"\"}\n</script>`;\n    const alternateLinks = i18nSnapshot ? renderI18nAlternateLinks(requestPath, i18nSnapshot) : \"\";\n    const fontHead = renderFarmFontDevHead(this.config.root || process.cwd());\n    const themeDocument = createFarmThemeDocumentParts(\n      this.config.theme,\n      this.config.basePath,\n      getFarmTheme(),\n    );\n    const rendererHydrationScript = this.rendererRuntime.generateHydrationScript?.() || \"\";\n\n    // A layout that returns its own full `<html>` document must not be nested\n    // inside this shell (that yields invalid nested `<html>`/`<head>`/`<body>`).\n    // Compose Farm's managed assets into the layout's document instead, matching\n    // the production build's `hasFullDocument` path.\n    const fullDocument = extractFarmFullDocument(content);\n    if (fullDocument) {\n      warnFarmFullDocumentLayout();\n      return composeFarmFullDocument(\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 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","// Stylesheets the dev document must link beyond globals.css.\n//\n// The dev shell links `/src/app/globals.css` and nothing else, so CSS that\n// enters through a JS import — `import \"@fontsource-variable/geist\"` in a\n// layout, a component stylesheet, vendor CSS — never reaches the page: no\n// error, just silently missing rules (farming-labs/farm.js#658). Vite's module\n// graph knows every stylesheet the app touched; collecting it closes the gap.\n\n/** The slice of Vite's ModuleNode this module reads, kept minimal for tests. */\nexport interface DevStyleModule {\n  url?: string | null;\n  id?: string | null;\n  file?: string | null;\n}\n\nconst STYLE_EXTENSIONS = /\\.(css|scss|sass|less|styl|stylus)(?:$|\\?)/;\n\n/** The stylesheet link the shell already emits; its own `@import`s resolve\n * inside that response, so neither it nor its query variants repeat here. */\nconst ALREADY_LINKED = \"/src/app/globals.css\";\n\n/**\n * Stylesheet URLs from the module graph that the document should link,\n * deduped and sorted for a deterministic head. CSS modules (`.module.css`)\n * are excluded: their classes are hashed through the JS pipeline and a plain\n * link would apply nothing useful.\n */\nexport function collectDevStylesheetUrls(modules: Iterable<DevStyleModule>): string[] {\n  const seen = new Set<string>();\n  for (const mod of modules) {\n    const id = mod.id ?? mod.file ?? \"\";\n    if (!STYLE_EXTENSIONS.test(id)) continue;\n    if (id.includes(\".module.\")) continue;\n    const url = mod.url;\n    if (!url || !url.startsWith(\"/\")) continue;\n    const bare = url.split(\"?\")[0]!;\n    if (bare === ALREADY_LINKED) continue;\n    seen.add(bare);\n  }\n  return [...seen].sort();\n}\n","// Handling for a root layout that returns a full `<html>…</html>` document.\n//\n// Farm owns the document shell — a layout is expected to return a fragment (its\n// children), like the docs example does. When a layout instead returns a whole\n// document, the dev renderer must compose that document as the response rather\n// than nesting it inside the generated shell, which would emit invalid nested\n// `<html>`/`<head>`/`<body>`. This mirrors the production (Nitro) build's\n// `hasFullDocument` path so dev and prod agree.\n\n/** Peel Farm's leading `display:contents` wrapper divs (the stream root and any\n * layout-boundary divs) so the layout's own markup is exposed for inspection. */\nfunction stripContentsWrappers(markup: string): string {\n  let out = markup.replace(/^\\s+/, \"\");\n  const opener = /^<div\\b[^>]*style=\"display\\s*:\\s*contents\"[^>]*>/i;\n  let match: RegExpExecArray | null;\n  while ((match = opener.exec(out))) {\n    out = out.slice(match[0].length).replace(/^\\s+/, \"\");\n  }\n  return out;\n}\n\n/**\n * When `markup` (a rendered layout tree, possibly wrapped in Farm's\n * `display:contents` boundary divs) is a full HTML document, return just that\n * `<html>…</html>` document (leading `<!DOCTYPE>` preserved when present);\n * otherwise return `null`.\n */\nexport function extractFarmFullDocument(markup: string): string | null {\n  const inner = stripContentsWrappers(markup);\n  if (!/^<!doctype/i.test(inner) && !/^<html[\\s>]/i.test(inner)) return null;\n  const start = markup.search(/<!doctype|<html[\\s>]/i);\n  const closeIndex = markup.toLowerCase().lastIndexOf(\"</html>\");\n  if (start < 0 || closeIndex < 0) return null;\n  return markup.slice(start, closeIndex + \"</html>\".length);\n}\n\n/** True when a rendered layout tree is (or wraps) a full HTML document. */\nexport function isFarmFullDocument(markup: string): boolean {\n  return extractFarmFullDocument(markup) !== null;\n}\n\n/**\n * True when `markup` *begins* a full HTML document once Farm's wrappers are\n * peeled — usable on a streamed prefix, before the closing `</html>` has been\n * flushed.\n */\nexport function opensFarmFullDocument(markup: string): boolean {\n  const inner = stripContentsWrappers(markup);\n  return /^<!doctype/i.test(inner) || /^<html[\\s>]/i.test(inner);\n}\n\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: Set middleware data for the current request\n * This is called by the server renderer before rendering starts.\n * Prefer _runWithMiddlewareData for request-scoped async flows.\n */\nexport function _setCurrentMiddlewareData(data: MiddlewareStoreInput): void {\n  middlewareStore.enterWith(toMiddlewareMap(data));\n}\n\n/**\n * Internal: Clear middleware data after request completes\n */\nexport function _clearCurrentMiddlewareData(): void {\n  middlewareStore.enterWith(new Map());\n}\n\n/** Internal: Clear server-only middleware context after rendering. */\nexport function _clearCurrentMiddlewareContext(): void {\n  middlewareContextStore.enterWith(new Map());\n}\n\n/**\n * Internal: Run code with middleware data available\n * This is called by the server renderer\n */\nexport async function _runWithMiddlewareData<T>(\n  data: MiddlewareStoreInput,\n  fn: () => T | Promise<T>,\n): Promise<T> {\n  return middlewareStore.run(toMiddlewareMap(data), fn);\n}\n\n/** Internal: Run code with server-only middleware context available. */\nexport async function _runWithMiddlewareContext<T>(\n  context: MiddlewareStoreInput,\n  fn: () => T | Promise<T>,\n): Promise<T> {\n  return middlewareContextStore.run(toMiddlewareMap(context), fn);\n}\n\n/**\n * Get middleware data in a server component\n * No props needed - uses global storage!\n *\n * @example\n * ```tsx\n * import { getMiddlewareData } from 'farm/middleware';\n *\n * export default function Page() {\n *   const data = getMiddlewareData();  // ← No props needed!\n *   const user = data.get('user');\n *   const demoInfo = data.get('demoInfo');\n *\n *   return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function getMiddlewareData<T extends Record<string, any> = Record<string, any>>(): Map<\n  keyof T,\n  T[keyof T]\n> {\n  return (middlewareStore.getStore() || new Map()) as Map<keyof T, T[keyof T]>;\n}\n\n/**\n * Get a specific value from middleware data (synchronous)\n * Uses AsyncLocalStorage for request scoping - no props needed.\n *\n * @example\n * ```tsx\n * import { getMiddlewareValue } from 'farm/middleware';\n *\n * export default function Page() {\n *   const user = getMiddlewareValue<User>('user');  // ← No props needed!\n *   const stats = getMiddlewareValue('dashboardStats');\n *\n *   return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function getMiddlewareValue<T = any>(key: string): T | undefined {\n  const data = getMiddlewareData();\n  return data.get(key);\n}\n\n/**\n * Read server-only values set by route middleware for the current request.\n * The returned store is available to the matched page, layouts, and nested\n * Server Components, but is never added to hydration props.\n */\nexport function getMiddlewareContext<\n  T extends Record<string, any> = Record<string, any>,\n>(): ReadonlyMiddlewareStore<T> {\n  return (middlewareContextStore.getStore() || new Map()) as unknown as ReadonlyMiddlewareStore<T>;\n}\n\n/**\n * Type-safe middleware data accessor with type parameter\n *\n * @example\n * ```tsx\n * import { createMiddlewareAccessor } from 'farm/middleware/server';\n *\n * interface MiddlewareData {\n *   user: { id: number; name: string };\n *   dashboardStats: { views: number; clicks: number };\n * }\n *\n * const getData = createMiddlewareAccessor<MiddlewareData>();\n *\n * export default function Page() {\n *   const data = getData();\n *   const user = data.user;  // Fully typed!\n *   const stats = data.dashboardStats;  // Fully typed!\n *\n *   return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function createMiddlewareAccessor<T extends Record<string, any>>() {\n  return (): Partial<T> => {\n    const data = getMiddlewareData();\n    const result: any = {};\n\n    for (const [key, value] of data) {\n      result[key] = value;\n    }\n\n    return result as Partial<T>;\n  };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { Readable } from \"node:stream\";\nimport type { FarmRequest } from \"../types\";\nimport { _setCurrentRequestResolver } from \"./request-bridge\";\n\nconst REQUEST_STORAGE_KEY = Symbol.for(\"@farm.js/core/request-storage\");\n\nfunction getRequestStore(): AsyncLocalStorage<Request> {\n  const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n  const existing = runtime[REQUEST_STORAGE_KEY];\n  if (existing instanceof AsyncLocalStorage) {\n    return existing as AsyncLocalStorage<Request>;\n  }\n\n  const storage = new AsyncLocalStorage<Request>();\n  runtime[REQUEST_STORAGE_KEY] = storage;\n  return storage;\n}\n\nconst requestStore = getRequestStore();\n\n_setCurrentRequestResolver(() => requestStore.getStore());\n\nexport interface FarmRequestURLOptions {\n  origin?: string | URL;\n  trustProxy?: boolean;\n}\n\nexport function resolveFarmRequestURL(req: FarmRequest, options: FarmRequestURLOptions = {}): URL {\n  if (options.origin) {\n    return new URL(req.url || \"/\", options.origin);\n  }\n\n  const forwardedHost = options.trustProxy\n    ? firstForwardedHeaderValue(req.headers[\"x-forwarded-host\"])\n    : undefined;\n  const fallbackHost = firstForwardedHeaderValue(req.headers.host) || \"localhost\";\n  const forwardedProto = options.trustProxy\n    ? firstForwardedHeaderValue(req.headers[\"x-forwarded-proto\"])\n    : undefined;\n  const normalizedProto = forwardedProto?.toLowerCase();\n  const proto =\n    normalizedProto === \"https\" || normalizedProto === \"http\"\n      ? normalizedProto\n      : isEncryptedFarmRequest(req)\n        ? \"https\"\n        : \"http\";\n  return new URL(req.url || \"/\", resolveRequestOrigin(proto, forwardedHost, fallbackHost));\n}\n\nexport function createWebRequestFromFarmRequest(\n  req: FarmRequest,\n  options: FarmRequestURLOptions = {},\n): Request {\n  const fullUrl = resolveFarmRequestURL(req, options).toString();\n\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (value == null) {\n      continue;\n    }\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        headers.append(key, item);\n      }\n      continue;\n    }\n\n    headers.set(key, value);\n  }\n\n  const method = (req.method || \"GET\").toUpperCase();\n  const init: RequestInit & { duplex?: \"half\" } = {\n    method: req.method,\n    headers,\n  };\n\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    init.body = Readable.toWeb(req) as ReadableStream<Uint8Array>;\n    init.duplex = \"half\";\n  }\n\n  return new Request(fullUrl, init);\n}\n\nfunction isEncryptedFarmRequest(req: FarmRequest): boolean {\n  return Boolean((req.socket as { encrypted?: boolean } | undefined)?.encrypted);\n}\n\nfunction firstForwardedHeaderValue(value: string | string[] | undefined): string | undefined {\n  const first = Array.isArray(value) ? value[0] : value;\n  const token = first?.split(\",\", 1)[0]?.trim();\n  return token || undefined;\n}\n\nfunction resolveRequestOrigin(proto: \"http\" | \"https\", host: string | undefined, fallback: string) {\n  for (const candidate of [host, fallback, \"localhost\"]) {\n    if (!candidate) continue;\n    if (/[\\s/?#@\\\\]/u.test(candidate)) continue;\n    try {\n      const url = new URL(`${proto}://${candidate}`);\n      if (url.username || url.password || url.pathname !== \"/\" || url.search || url.hash) continue;\n      return url.origin;\n    } catch {\n      // Try the next host instead of turning an untrusted proxy header into a 500.\n    }\n  }\n  return `${proto}://localhost`;\n}\n\nexport async function _runWithCurrentRequest<T>(\n  request: Request,\n  fn: () => Promise<T> | T,\n): Promise<T> {\n  return requestStore.run(request, fn);\n}\n\nexport function getCurrentRequest(): Request {\n  const request = requestStore.getStore();\n  if (!request) {\n    throw new Error(\n      \"No current request is available. getCurrentRequest() can only be used during server rendering.\",\n    );\n  }\n\n  return request;\n}\n\n// Some runtimes (StackBlitz WebContainers among them) lose AsyncLocalStorage\n// context across async boundaries mid-render. Callers whose feature can\n// degrade gracefully should use this instead of getCurrentRequest() so a\n// missing store never turns into a 500.\nexport function getCurrentRequestOrNull(): Request | null {\n  return requestStore.getStore() ?? null;\n}\n","type CurrentRequestResolver = () => Request | undefined;\n\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\n\ntype GlobalWithCurrentRequestResolver = typeof globalThis & {\n  [CURRENT_REQUEST_RESOLVER_KEY]?: CurrentRequestResolver;\n};\n\nfunction getGlobalState(): GlobalWithCurrentRequestResolver {\n  return globalThis as GlobalWithCurrentRequestResolver;\n}\n\nexport function _setCurrentRequestResolver(resolver: CurrentRequestResolver | undefined): void {\n  getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;\n}\n\nexport function _resolveCurrentRequest(): Request | undefined {\n  return getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n","import 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 { Metadata } from \"./types\";\nimport { renderFarmAgentJsonLd, type FarmAgentJsonLd } from \"./agent-config\";\n\nexport type MetadataImageKind = \"opengraph\" | \"twitter\";\n\nexport interface FarmMetadataImageReference {\n  kind: MetadataImageKind;\n  href: string;\n  alt?: string;\n  width?: number;\n  height?: number;\n  contentType?: string;\n}\n\nexport interface RenderedMetadataHead {\n  title: string;\n  tags: string;\n  hasFavicon: boolean;\n  /** False when the title is the framework fallback rather than configured. */\n  hasExplicitTitle: boolean;\n}\n\ntype MetadataRecord = Metadata & Record<string, any>;\n\nexport function mergeMetadata(\n  base: MetadataRecord | undefined,\n  next: MetadataRecord | undefined,\n): MetadataRecord {\n  if (!base) return next ? { ...next } : {};\n  if (!next) return { ...base };\n\n  return {\n    ...base,\n    ...next,\n    title: mergeMetadataTitle(base.title, next.title),\n    openGraph: mergeNestedMetadata(base.openGraph, next.openGraph),\n    twitter: mergeNestedMetadata(base.twitter, next.twitter),\n    alternates: mergeNestedMetadata((base as any).alternates, (next as any).alternates),\n    icons: mergeNestedMetadata((base as any).icons, (next as any).icons),\n  };\n}\n\nfunction mergeMetadataTitle(base: Metadata[\"title\"], next: Metadata[\"title\"]): Metadata[\"title\"] {\n  if (next === undefined) return base;\n\n  const parentTemplate = isRecord(base) ? normalizeContent(base.template) : undefined;\n  if (typeof next === \"string\") {\n    return parentTemplate ? applyTitleTemplate(parentTemplate, next) : next;\n  }\n\n  if (!isRecord(next)) return next;\n\n  const defaultTitle = normalizeContent(next.default) ?? resolveMetadataTitle(base);\n  return {\n    ...next,\n    default:\n      defaultTitle && parentTemplate\n        ? applyTitleTemplate(parentTemplate, defaultTitle)\n        : defaultTitle,\n  };\n}\n\nfunction applyTitleTemplate(template: string, title: string): string {\n  return template.split(\"%s\").join(title);\n}\n\nexport function addMetadataImageReference(\n  metadata: MetadataRecord,\n  reference: FarmMetadataImageReference,\n): MetadataRecord {\n  if (reference.kind === \"opengraph\") {\n    const openGraph = { ...metadata.openGraph };\n    if (!hasMetadataImages(openGraph.images) && !hasMetadataImages((openGraph as any).image)) {\n      openGraph.images = [\n        {\n          url: reference.href,\n          width: reference.width,\n          height: reference.height,\n          alt: reference.alt,\n          type: reference.contentType,\n        },\n      ];\n    }\n\n    return {\n      ...metadata,\n      openGraph,\n    };\n  }\n\n  const twitter = { ...metadata.twitter };\n  if (!hasMetadataImages(twitter.images)) {\n    twitter.images = [reference.href];\n    twitter.card = twitter.card || \"summary_large_image\";\n  }\n\n  return {\n    ...metadata,\n    twitter,\n  };\n}\n\nexport interface RenderMetadataHeadOptions {\n  /**\n   * Current request pathname. Used to emit a default `<link rel=\"canonical\">`\n   * when the route does not set one, so agents and crawlers can resolve the\n   * page's identity. Combined with `metadataBase` into an absolute URL when a\n   * base is configured; otherwise emitted as a self-referential path.\n   */\n  pathname?: string;\n  /**\n   * Agent JSON-LD config. When truthy, a schema.org JSON-LD script is emitted in\n   * the head, built from this config and the page/site metadata. `true` uses the\n   * defaults; `false`/omitted (the default) emits nothing.\n   */\n  jsonLd?: FarmAgentJsonLd | boolean;\n}\n\nexport function renderMetadataHead(\n  metadata: MetadataRecord | undefined,\n  options: RenderMetadataHeadOptions = {},\n): RenderedMetadataHead {\n  const resolvedMetadata = metadata || {};\n  const metadataBase = resolveMetadataBase(resolvedMetadata);\n  const explicitTitle = resolveMetadataTitle(resolvedMetadata.title);\n  const title = explicitTitle || \"Farm.js App\";\n  const tags: string[] = [];\n\n  appendMetaName(tags, \"description\", resolvedMetadata.description);\n  appendMetaName(tags, \"keywords\", normalizeKeywords(resolvedMetadata.keywords));\n  appendMetaName(tags, \"author\", (resolvedMetadata as any).author);\n\n  if (Array.isArray(resolvedMetadata.authors)) {\n    for (const author of resolvedMetadata.authors) {\n      appendMetaName(tags, \"author\", author?.name);\n      if (author?.url) {\n        appendLink(tags, \"author\", resolveMetadataUrl(author.url, metadataBase));\n      }\n    }\n  }\n\n  appendMetaName(tags, \"creator\", resolvedMetadata.creator);\n  appendMetaName(tags, \"publisher\", resolvedMetadata.publisher);\n  appendMetaName(tags, \"robots\", normalizeRobots(resolvedMetadata.robots));\n\n  const alternates = (resolvedMetadata as any).alternates;\n  const explicitCanonical = isRecord(alternates) ? alternates.canonical : undefined;\n  // Default the canonical link to the current path when the route does not set\n  // one. This is a self-referential canonical (absolute when `metadataBase` is\n  // configured), which is safe for every page and gives agents/crawlers a\n  // stable identity for the URL.\n  const canonicalHref =\n    explicitCanonical != null\n      ? resolveMetadataUrl(explicitCanonical, metadataBase)\n      : options.pathname\n        ? resolveMetadataUrl(sanitizeSelfCanonicalPathname(options.pathname), metadataBase)\n        : undefined;\n  if (canonicalHref) {\n    appendLink(tags, \"canonical\", canonicalHref);\n  }\n\n  if (isRecord(alternates) && isRecord(alternates.languages)) {\n    for (const [language, href] of Object.entries(alternates.languages)) {\n      appendLink(tags, \"alternate\", resolveMetadataUrl(href, metadataBase), {\n        hreflang: language,\n      });\n    }\n  }\n\n  const hasFavicon = appendIcons(tags, (resolvedMetadata as any).icons, metadataBase);\n\n  if ((resolvedMetadata as any).manifest) {\n    appendLink(\n      tags,\n      \"manifest\",\n      resolveMetadataUrl((resolvedMetadata as any).manifest, metadataBase),\n    );\n  }\n\n  appendOpenGraph(tags, resolvedMetadata.openGraph, metadataBase);\n  appendTwitter(tags, resolvedMetadata.twitter, metadataBase);\n\n  if (options.jsonLd) {\n    const jsonLdConfig = options.jsonLd === true ? {} : options.jsonLd;\n    const jsonLdScript = renderFarmAgentJsonLd(jsonLdConfig, {\n      metadataBase,\n      siteName: isRecord(resolvedMetadata.openGraph)\n        ? normalizeContent(resolvedMetadata.openGraph.siteName)\n        : undefined,\n      title: explicitTitle,\n      description: normalizeContent(resolvedMetadata.description),\n    });\n    if (jsonLdScript) tags.push(jsonLdScript);\n  }\n\n  return {\n    title: escapeText(title),\n    tags: tags.length > 0 ? `\\n  ${tags.join(\"\\n  \")}` : \"\",\n    hasFavicon,\n    hasExplicitTitle: Boolean(explicitTitle),\n  };\n}\n\nfunction mergeNestedMetadata(base: unknown, next: unknown): any {\n  if (isRecord(base) && isRecord(next)) {\n    return {\n      ...base,\n      ...next,\n    };\n  }\n\n  return next ?? base;\n}\n\nfunction appendOpenGraph(tags: string[], openGraph: Metadata[\"openGraph\"], metadataBase?: string) {\n  if (!isRecord(openGraph)) return;\n\n  appendMetaProperty(tags, \"og:title\", openGraph.title);\n  appendMetaProperty(tags, \"og:description\", openGraph.description);\n  appendMetaProperty(tags, \"og:url\", resolveMetadataUrl(openGraph.url, metadataBase));\n  appendMetaProperty(tags, \"og:site_name\", openGraph.siteName);\n  // Default og:type so a route that sets Open Graph data without a type still\n  // emits a valid entity type for agents and social crawlers.\n  appendMetaProperty(tags, \"og:type\", openGraph.type ?? \"website\");\n  appendMetaProperty(tags, \"og:locale\", (openGraph as any).locale);\n\n  const images = normalizeMetadataImages(\n    openGraph.images ?? (openGraph as any).image,\n    metadataBase,\n  );\n  for (const image of images) {\n    appendMetaProperty(tags, \"og:image\", image.url);\n    appendMetaProperty(tags, \"og:image:width\", image.width);\n    appendMetaProperty(tags, \"og:image:height\", image.height);\n    appendMetaProperty(tags, \"og:image:alt\", image.alt);\n    appendMetaProperty(tags, \"og:image:type\", image.type);\n  }\n}\n\nfunction appendTwitter(tags: string[], twitter: Metadata[\"twitter\"], metadataBase?: string) {\n  if (!isRecord(twitter)) return;\n\n  appendMetaName(tags, \"twitter:card\", twitter.card);\n  appendMetaName(tags, \"twitter:site\", twitter.site);\n  appendMetaName(tags, \"twitter:creator\", twitter.creator);\n  appendMetaName(tags, \"twitter:title\", twitter.title);\n  appendMetaName(tags, \"twitter:description\", twitter.description);\n\n  for (const image of normalizeMetadataImages(twitter.images, metadataBase)) {\n    appendMetaName(tags, \"twitter:image\", image.url);\n    appendMetaName(tags, \"twitter:image:alt\", image.alt);\n  }\n}\n\nfunction appendIcons(tags: string[], icons: unknown, metadataBase?: string): boolean {\n  if (!icons) return false;\n\n  if (typeof icons === \"string\") {\n    const initialTagCount = tags.length;\n    appendLink(tags, \"icon\", resolveMetadataUrl(icons, metadataBase));\n    return tags.length > initialTagCount;\n  }\n\n  if (!isRecord(icons)) return false;\n\n  const initialTagCount = tags.length;\n  appendIconList(tags, \"icon\", icons.icon, metadataBase);\n  appendIconList(tags, \"shortcut icon\", icons.shortcut, metadataBase);\n  const hasFavicon = tags.length > initialTagCount;\n  appendIconList(tags, \"apple-touch-icon\", icons.apple, metadataBase);\n  return hasFavicon;\n}\n\nfunction appendIconList(tags: string[], rel: string, value: unknown, metadataBase?: string) {\n  for (const icon of normalizeArray(value)) {\n    if (typeof icon === \"string\") {\n      appendLink(tags, rel, resolveMetadataUrl(icon, metadataBase));\n      continue;\n    }\n\n    if (!isRecord(icon)) continue;\n    appendLink(tags, rel, resolveMetadataUrl(icon.url, metadataBase), {\n      sizes: icon.sizes,\n      type: icon.type,\n    });\n  }\n}\n\nfunction appendMetaName(tags: string[], name: string, content: unknown) {\n  const normalized = normalizeContent(content);\n  if (!normalized) return;\n  tags.push(`<meta name=\"${escapeAttribute(name)}\" content=\"${escapeAttribute(normalized)}\">`);\n}\n\nfunction appendMetaProperty(tags: string[], property: string, content: unknown) {\n  const normalized = normalizeContent(content);\n  if (!normalized) return;\n  tags.push(\n    `<meta property=\"${escapeAttribute(property)}\" content=\"${escapeAttribute(normalized)}\">`,\n  );\n}\n\nfunction appendLink(\n  tags: string[],\n  rel: string,\n  href: unknown,\n  attrs: Record<string, unknown> = {},\n) {\n  const normalizedHref = normalizeContent(href);\n  if (!normalizedHref) return;\n\n  const attrText = Object.entries(attrs)\n    .map(([key, value]) => {\n      const normalized = normalizeContent(value);\n      return normalized ? ` ${key}=\"${escapeAttribute(normalized)}\"` : \"\";\n    })\n    .join(\"\");\n\n  tags.push(\n    `<link rel=\"${escapeAttribute(rel)}\" href=\"${escapeAttribute(normalizedHref)}\"${attrText}>`,\n  );\n}\n\nfunction normalizeMetadataImages(\n  value: unknown,\n  metadataBase?: string,\n): Array<{\n  url: string;\n  width?: number;\n  height?: number;\n  alt?: string;\n  type?: string;\n}> {\n  return normalizeArray(value)\n    .map((item) => {\n      if (typeof item === \"string\") {\n        return { url: resolveMetadataUrl(item, metadataBase) || item };\n      }\n\n      if (!isRecord(item)) return null;\n      const rawUrl = item.url || item.src;\n      const url = resolveMetadataUrl(rawUrl, metadataBase);\n      if (!url) return null;\n\n      return {\n        url,\n        width: normalizeNumber(item.width),\n        height: normalizeNumber(item.height),\n        alt: typeof item.alt === \"string\" ? item.alt : undefined,\n        type: typeof item.type === \"string\" ? item.type : undefined,\n      };\n    })\n    .filter((item): item is NonNullable<typeof item> => item !== null);\n}\n\nfunction normalizeArray(value: unknown): unknown[] {\n  if (value == null) return [];\n  return Array.isArray(value) ? value : [value];\n}\n\nfunction hasMetadataImages(value: unknown): boolean {\n  return normalizeMetadataImages(value).length > 0;\n}\n\n/**\n * Resolve a metadata title into displayable text. Exported so client-side\n * navigation resolves the object form the same way SSR does instead of\n * stringifying it into \"[object Object]\".\n */\nexport function resolveMetadataTitle(title: Metadata[\"title\"]): string | undefined {\n  if (typeof title === \"string\") return title;\n  if (isRecord(title)) {\n    return normalizeContent(title.default);\n  }\n  return undefined;\n}\n\nfunction normalizeKeywords(keywords: Metadata[\"keywords\"]): string | undefined {\n  if (Array.isArray(keywords)) return keywords.filter(Boolean).join(\", \");\n  return keywords;\n}\n\nfunction normalizeRobots(robots: Metadata[\"robots\"]): string | undefined {\n  if (typeof robots === \"string\") return robots;\n  if (!isRecord(robots)) return undefined;\n\n  const values: string[] = [];\n  if (typeof robots.index === \"boolean\") values.push(robots.index ? \"index\" : \"noindex\");\n  if (typeof robots.follow === \"boolean\") values.push(robots.follow ? \"follow\" : \"nofollow\");\n  return values.join(\", \") || undefined;\n}\n\nfunction resolveMetadataBase(metadata: MetadataRecord): string | undefined {\n  const base = metadata.metadataBase;\n  if (!base) return undefined;\n  return String(base);\n}\n\n/**\n * Keep the defaulted self-canonical on this origin. The pathname comes straight\n * from the request URL, and forms like `//evil.com` or `/\\evil.com` resolve to a\n * cross-origin URL through `new URL()` (and browsers treat `\\` as `/`), which\n * would advertise an attacker's domain as the page's canonical identity. Any\n * request path introducing an authority is collapsed to a single leading slash\n * so the canonical stays same-origin. Developer-supplied `alternates.canonical`\n * is trusted and does not pass through here.\n */\nfunction sanitizeSelfCanonicalPathname(pathname: string): string {\n  if (typeof pathname !== \"string\" || pathname.length === 0) return \"/\";\n  const collapsed = pathname.replace(/^[/\\\\]+/, \"/\");\n  return collapsed.startsWith(\"/\") ? collapsed : `/${collapsed}`;\n}\n\nfunction resolveMetadataUrl(value: unknown, metadataBase?: string): string | undefined {\n  const normalized = normalizeContent(value);\n  if (!normalized) return undefined;\n  if (!metadataBase) return normalized;\n\n  try {\n    return new URL(normalized, metadataBase).toString();\n  } catch {\n    return normalized;\n  }\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n  if (typeof value === \"number\" && Number.isFinite(value)) return value;\n  if (typeof value === \"string\") {\n    const parsed = Number(value);\n    return Number.isFinite(parsed) ? parsed : undefined;\n  }\n  return undefined;\n}\n\nfunction normalizeContent(value: unknown): string | undefined {\n  if (value == null) return undefined;\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n  if (value instanceof URL) return value.toString();\n  return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n  return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction escapeText(value: string): string {\n  return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction escapeAttribute(value: string): string {\n  return escapeText(value).replace(/\"/g, \"&quot;\");\n}\n","export const FARM_DEFERRED_CONTENT_TYPE = \"application/x-farm-deferred+json\";\nexport const FARM_DEFERRED_ERROR_CODE = \"FARM_DEFERRED_DATA_ERROR\";\nexport const FARM_DEFERRED_BRAND: unique symbol = Symbol.for(\n  \"farm.deferred\",\n) as typeof FARM_DEFERRED_BRAND;\n\nconst FARM_DEFERRED_MARKER = \"$farmDeferred\";\n\ntype DeferredState<T = unknown> =\n  | { status: \"pending\" }\n  | { status: \"fulfilled\"; value: T }\n  | { status: \"rejected\"; reason: unknown };\n\nexport interface Deferred<T> extends Promise<T> {\n  readonly [FARM_DEFERRED_BRAND]: true;\n}\n\nexport interface PreparedDeferredData {\n  data: unknown;\n  records: readonly DeferredRecord[];\n}\n\nexport interface DeferredRecord {\n  id: string;\n  promise: Deferred<unknown>;\n}\n\nexport type DeferredSettlement =\n  | { status: \"fulfilled\"; value: unknown }\n  | { status: \"rejected\"; error: { code: typeof FARM_DEFERRED_ERROR_CODE; message: string } };\n\nexport type DeferredSettlements = Record<string, DeferredSettlement>;\n\nexport interface DeferredDataResponseOptions {\n  onError?: (error: unknown, id: string) => void;\n}\n\nexport class DeferredDataError extends Error {\n  readonly name = \"DeferredDataError\";\n  readonly code = FARM_DEFERRED_ERROR_CODE;\n\n  constructor(message = \"Deferred route data failed to load\") {\n    super(message);\n  }\n}\n\nconst deferredStates = new WeakMap<object, DeferredState>();\n\nexport function defer<T>(value: PromiseLike<T>): Deferred<Awaited<T>> {\n  if (isDeferred(value)) {\n    return value as Deferred<Awaited<T>>;\n  }\n\n  const promise = Promise.resolve(value) as Deferred<Awaited<T>>;\n  Object.defineProperty(promise, FARM_DEFERRED_BRAND, {\n    configurable: false,\n    enumerable: false,\n    value: true,\n    writable: false,\n  });\n  deferredStates.set(promise, { status: \"pending\" });\n  promise.then(\n    (resolved) => deferredStates.set(promise, { status: \"fulfilled\", value: resolved }),\n    (reason) => deferredStates.set(promise, { status: \"rejected\", reason }),\n  );\n  return promise;\n}\n\nexport function isDeferred<T = unknown>(value: unknown): value is Deferred<T> {\n  return Boolean(\n    value &&\n    (typeof value === \"object\" || typeof value === \"function\") &&\n    (value as Record<PropertyKey, unknown>)[FARM_DEFERRED_BRAND] === true,\n  );\n}\n\nexport function prepareDeferredData(value: unknown): PreparedDeferredData {\n  const context = createEncodingContext();\n  return {\n    data: encodeDeferredValue(value, context, new WeakSet()),\n    records: context.records,\n  };\n}\n\nexport function snapshotDeferredData(records: readonly DeferredRecord[]): DeferredSettlements {\n  const context = createEncodingContext(records);\n  const settlements: DeferredSettlements = {};\n\n  for (let index = 0; index < context.records.length; index++) {\n    const record = context.records[index]!;\n    const state = readDeferredState(record.promise);\n\n    if (state.status === \"fulfilled\") {\n      try {\n        settlements[record.id] = {\n          status: \"fulfilled\",\n          value: encodeDeferredValue(state.value, context, new WeakSet()),\n        };\n      } catch {\n        settlements[record.id] = createRejectedSettlement();\n      }\n    } else {\n      settlements[record.id] = createRejectedSettlement();\n    }\n  }\n\n  return settlements;\n}\n\nexport function reviveDeferredData<T>(value: T, settlements: DeferredSettlements): T {\n  return reviveDeferredValue(value, new Map(), settlements) as T;\n}\n\nexport function createDeferredDataResponse(\n  value: unknown,\n  init: ResponseInit = {},\n  options: DeferredDataResponseOptions = {},\n): Response {\n  const context = createEncodingContext();\n  const data = encodeDeferredValue(value, context, new WeakSet());\n  const headers = new Headers(init.headers);\n\n  if (context.records.length === 0) {\n    headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n    return new Response(JSON.stringify(data), { ...init, headers });\n  }\n\n  headers.set(\"Content-Type\", `${FARM_DEFERRED_CONTENT_TYPE}; charset=utf-8`);\n  headers.set(\"Cache-Control\", headers.get(\"Cache-Control\") || \"private, max-age=0\");\n  const initialLine = encodeDeferredMessage({ type: \"data\", data });\n  const encoder = new TextEncoder();\n  let cancelled = false;\n\n  const stream = new ReadableStream<Uint8Array>({\n    start(controller) {\n      controller.enqueue(encoder.encode(initialLine));\n      let pending = context.records.length;\n\n      const finishRecord = () => {\n        pending--;\n        if (!cancelled && pending === 0) controller.close();\n      };\n\n      const schedule = (record: DeferredRecord) => {\n        record.promise\n          .then(\n            (resolved) => {\n              if (cancelled) return;\n              try {\n                const previousLength = context.records.length;\n                const encoded = encodeDeferredValue(resolved, context, new WeakSet());\n                const nestedRecords = context.records.slice(previousLength);\n                pending += nestedRecords.length;\n                controller.enqueue(\n                  encoder.encode(\n                    encodeDeferredMessage({ type: \"resolve\", id: record.id, data: encoded }),\n                  ),\n                );\n                for (const nestedRecord of nestedRecords) schedule(nestedRecord);\n              } catch (error) {\n                reportDeferredError(options, error, record.id);\n                controller.enqueue(\n                  encoder.encode(\n                    encodeDeferredMessage({\n                      type: \"reject\",\n                      id: record.id,\n                      error: createDeferredPublicError(),\n                    }),\n                  ),\n                );\n              }\n            },\n            (error) => {\n              if (cancelled) return;\n              reportDeferredError(options, error, record.id);\n              controller.enqueue(\n                encoder.encode(\n                  encodeDeferredMessage({\n                    type: \"reject\",\n                    id: record.id,\n                    error: createDeferredPublicError(),\n                  }),\n                ),\n              );\n            },\n          )\n          .finally(finishRecord);\n      };\n\n      const initialRecords = context.records.slice();\n      for (const record of initialRecords) schedule(record);\n    },\n    cancel() {\n      cancelled = true;\n    },\n  });\n\n  return new Response(stream, { ...init, headers });\n}\n\nexport async function readDeferredDataResponse<T>(response: Response): Promise<T> {\n  const contentType = response.headers.get(\"Content-Type\") || \"\";\n  if (!contentType.toLowerCase().startsWith(FARM_DEFERRED_CONTENT_TYPE)) {\n    return (await response.json()) as T;\n  }\n  if (!response.body) {\n    throw new DeferredDataError(\"Deferred route data response has no body\");\n  }\n\n  const reader = response.body.getReader();\n  const decoder = new TextDecoder();\n  const controllers = new Map<string, ControlledDeferred>();\n  let buffer = \"\";\n  let complete = false;\n\n  const readLine = async (): Promise<string | undefined> => {\n    while (true) {\n      const newline = buffer.indexOf(\"\\n\");\n      if (newline >= 0) {\n        const line = buffer.slice(0, newline);\n        buffer = buffer.slice(newline + 1);\n        return line;\n      }\n      if (complete) {\n        if (!buffer) return undefined;\n        const line = buffer;\n        buffer = \"\";\n        return line;\n      }\n\n      const chunk = await reader.read();\n      complete = chunk.done;\n      if (chunk.value) buffer += decoder.decode(chunk.value, { stream: !chunk.done });\n      if (chunk.done) buffer += decoder.decode();\n    }\n  };\n\n  const firstLine = await readLine();\n  if (!firstLine) {\n    reader.releaseLock();\n    throw new DeferredDataError(\"Deferred route data response is empty\");\n  }\n\n  const initial = parseDeferredMessage(firstLine);\n  if (initial.type !== \"data\") {\n    reader.releaseLock();\n    throw new DeferredDataError(\"Deferred route data response is invalid\");\n  }\n  const data = reviveDeferredValue(initial.data, controllers) as T;\n\n  void (async () => {\n    try {\n      for (let line = await readLine(); line !== undefined; line = await readLine()) {\n        if (!line) continue;\n        const message = parseDeferredMessage(line);\n        if (message.type === \"resolve\") {\n          const controller = getControlledDeferred(message.id, controllers);\n          controller.resolve(reviveDeferredValue(message.data, controllers));\n        } else if (message.type === \"reject\") {\n          getControlledDeferred(message.id, controllers).reject(\n            new DeferredDataError(message.error?.message),\n          );\n        }\n      }\n      rejectPendingDeferred(controllers, \"Deferred route data stream ended before completion\");\n    } catch {\n      rejectPendingDeferred(controllers, \"Deferred route data stream could not be read\");\n    } finally {\n      reader.releaseLock();\n    }\n  })();\n\n  return data;\n}\n\ninterface EncodingContext {\n  records: DeferredRecord[];\n  ids: Map<Deferred<unknown>, string>;\n  nextId: number;\n}\n\ninterface ControlledDeferred {\n  promise: Promise<unknown> & {\n    status?: \"pending\" | \"fulfilled\" | \"rejected\";\n    value?: unknown;\n    reason?: unknown;\n  };\n  resolve(value: unknown): void;\n  reject(error: unknown): void;\n}\n\nfunction createEncodingContext(records: readonly DeferredRecord[] = []): EncodingContext {\n  return {\n    records: [...records],\n    ids: new Map(records.map((record) => [record.promise, record.id])),\n    nextId: records.reduce((highest, record) => {\n      const value = Number(record.id.replace(/^d/, \"\"));\n      return Number.isFinite(value) ? Math.max(highest, value + 1) : highest;\n    }, records.length),\n  };\n}\n\nfunction encodeDeferredValue(\n  value: unknown,\n  context: EncodingContext,\n  ancestors: WeakSet<object>,\n): unknown {\n  if (isDeferred(value)) {\n    let id = context.ids.get(value);\n    if (!id) {\n      id = `d${context.nextId++}`;\n      context.ids.set(value, id);\n      context.records.push({ id, promise: value as Deferred<unknown> });\n    }\n    return { [FARM_DEFERRED_MARKER]: id };\n  }\n  if (!value || typeof value !== \"object\") return value;\n  if (Array.isArray(value)) {\n    assertNotCircular(value, ancestors);\n    const output = value.map((item) => encodeDeferredValue(item, context, ancestors));\n    ancestors.delete(value);\n    return output;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) return value;\n\n  assertNotCircular(value, ancestors);\n  const output: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    defineDataProperty(output, key, encodeDeferredValue(item, context, ancestors));\n  }\n  ancestors.delete(value);\n  // User data that happens to have the marker shape must not be revived as a\n  // deferred reference. Real ids never start with \"!\", so prefix-escape the\n  // value; revive strips one \"!\" back off.\n  if (isDeferredMarker(output)) {\n    return { [FARM_DEFERRED_MARKER]: `!${output[FARM_DEFERRED_MARKER]}` };\n  }\n  return output;\n}\n\nfunction reviveDeferredValue(\n  value: unknown,\n  controllers: Map<string, ControlledDeferred>,\n  settlements?: DeferredSettlements,\n  applyingSettlements = new Set<string>(),\n): unknown {\n  if (isDeferredMarker(value)) {\n    const id = value[FARM_DEFERRED_MARKER];\n    // Escaped user data, not a deferred reference — restore the original.\n    if (id.startsWith(\"!\")) {\n      return { [FARM_DEFERRED_MARKER]: id.slice(1) };\n    }\n    const controller = getControlledDeferred(id, controllers);\n    const settlement = settlements?.[id];\n    if (settlement && controller.promise.status === \"pending\") {\n      if (applyingSettlements.has(id)) return controller.promise;\n      applyingSettlements.add(id);\n      if (settlement.status === \"fulfilled\") {\n        controller.resolve(\n          reviveDeferredValue(settlement.value, controllers, settlements, applyingSettlements),\n        );\n      } else {\n        controller.reject(new DeferredDataError(settlement.error.message));\n      }\n      applyingSettlements.delete(id);\n    } else if (settlements && controller.promise.status === \"pending\") {\n      controller.reject(new DeferredDataError(\"Deferred route data was not resolved\"));\n    }\n    return controller.promise;\n  }\n  if (Array.isArray(value)) {\n    return value.map((item) =>\n      reviveDeferredValue(item, controllers, settlements, applyingSettlements),\n    );\n  }\n  if (!value || typeof value !== \"object\") return value;\n\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) return value;\n  const output: Record<string, unknown> = {};\n  for (const [key, item] of Object.entries(value)) {\n    defineDataProperty(\n      output,\n      key,\n      reviveDeferredValue(item, controllers, settlements, applyingSettlements),\n    );\n  }\n  return output;\n}\n\n// Assign an own key preserving its data. A plain `output[key] = value` runs the\n// `Object.prototype.__proto__` setter when `key` is the string \"__proto__\" (the\n// shape JSON.parse of external input produces), which silently drops the entry\n// and mutates the object's prototype instead of storing the value. Defining the\n// property sidesteps the accessor for that one key; other keys keep the fast path.\nfunction defineDataProperty(output: Record<string, unknown>, key: string, value: unknown): void {\n  if (key === \"__proto__\") {\n    Object.defineProperty(output, key, {\n      value,\n      enumerable: true,\n      writable: true,\n      configurable: true,\n    });\n  } else {\n    output[key] = value;\n  }\n}\n\nfunction getControlledDeferred(\n  id: string,\n  controllers: Map<string, ControlledDeferred>,\n): ControlledDeferred {\n  const existing = controllers.get(id);\n  if (existing) return existing;\n\n  let nativeResolve!: (value: unknown) => void;\n  let nativeReject!: (error: unknown) => void;\n  const promise = new Promise<unknown>((resolve, reject) => {\n    nativeResolve = resolve;\n    nativeReject = reject;\n  }) as ControlledDeferred[\"promise\"];\n  promise.status = \"pending\";\n  promise.catch(() => undefined);\n\n  const controlled: ControlledDeferred = {\n    promise,\n    resolve(value) {\n      if (promise.status !== \"pending\") return;\n      promise.status = \"fulfilled\";\n      promise.value = value;\n      nativeResolve(value);\n    },\n    reject(error) {\n      if (promise.status !== \"pending\") return;\n      promise.status = \"rejected\";\n      promise.reason = error;\n      nativeReject(error);\n    },\n  };\n  controllers.set(id, controlled);\n  return controlled;\n}\n\nfunction readDeferredState(promise: Deferred<unknown>): DeferredState {\n  const tracked = deferredStates.get(promise);\n  if (tracked && tracked.status !== \"pending\") return tracked;\n\n  const reactState = promise as Deferred<unknown> & {\n    status?: string;\n    value?: unknown;\n    reason?: unknown;\n  };\n  if (reactState.status === \"fulfilled\") {\n    return { status: \"fulfilled\", value: reactState.value };\n  }\n  if (reactState.status === \"rejected\") {\n    return { status: \"rejected\", reason: reactState.reason };\n  }\n  return tracked || { status: \"pending\" };\n}\n\nfunction isDeferredMarker(value: unknown): value is { [FARM_DEFERRED_MARKER]: string } {\n  return Boolean(\n    value &&\n    typeof value === \"object\" &&\n    Object.keys(value).length === 1 &&\n    typeof (value as Record<string, unknown>)[FARM_DEFERRED_MARKER] === \"string\",\n  );\n}\n\nfunction assertNotCircular(value: object, ancestors: WeakSet<object>): void {\n  if (ancestors.has(value)) {\n    throw new TypeError(\"Deferred route data must be JSON-serializable and cannot be circular\");\n  }\n  ancestors.add(value);\n}\n\nfunction createDeferredPublicError() {\n  return {\n    code: FARM_DEFERRED_ERROR_CODE,\n    message: \"Deferred route data failed to load\",\n  } as const;\n}\n\nfunction createRejectedSettlement(): DeferredSettlement {\n  return { status: \"rejected\", error: createDeferredPublicError() };\n}\n\nfunction reportDeferredError(\n  options: DeferredDataResponseOptions,\n  error: unknown,\n  id: string,\n): void {\n  try {\n    options.onError?.(error, id);\n  } catch {\n    // Error reporting must not break the response stream.\n  }\n}\n\nfunction encodeDeferredMessage(message: Record<string, unknown>): string {\n  return `${JSON.stringify(message)}\\n`;\n}\n\nfunction parseDeferredMessage(line: string): any {\n  try {\n    return JSON.parse(line);\n  } catch {\n    throw new DeferredDataError(\"Deferred route data response contains invalid JSON\");\n  }\n}\n\nfunction rejectPendingDeferred(\n  controllers: Map<string, ControlledDeferred>,\n  message: string,\n): void {\n  for (const controller of controllers.values()) {\n    if (controller.promise.status === \"pending\") {\n      controller.reject(new DeferredDataError(message));\n    }\n  }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { FarmLocaleResolution } from \"./resolver\";\nimport { _setFarmI18nSnapshotResolver } from \"./bridge\";\nimport { FarmI18nRuntime, createFarmI18nRuntime } from \"./runtime\";\nimport type {\n  FarmI18nClientSnapshot,\n  FarmI18nLocale,\n  FarmI18nLocaleSource,\n  FarmI18nMessageArgs,\n  FarmI18nMessageKey,\n  FarmTranslator,\n} from \"./types\";\n\ninterface FarmI18nRequestState {\n  runtime: FarmI18nRuntime;\n  resolution: FarmLocaleResolution;\n  snapshot: FarmI18nClientSnapshot;\n}\n\ninterface FarmListFormatOptions {\n  localeMatcher?: \"lookup\" | \"best fit\";\n  type?: \"conjunction\" | \"disjunction\" | \"unit\";\n  style?: \"long\" | \"short\" | \"narrow\";\n}\n\nconst FARM_I18N_REQUEST_STORE = Symbol.for(\"farm.i18n.requestStore\");\nconst FARM_I18N_DEFAULT_RUNTIME = Symbol.for(\"farm.i18n.defaultRuntime\");\n\ntype GlobalFarmI18nState = typeof globalThis & {\n  [FARM_I18N_REQUEST_STORE]?: AsyncLocalStorage<FarmI18nRequestState>;\n  [FARM_I18N_DEFAULT_RUNTIME]?: FarmI18nRuntime;\n};\n\nfunction getRequestStore(): AsyncLocalStorage<FarmI18nRequestState> {\n  const state = globalThis as GlobalFarmI18nState;\n  return (state[FARM_I18N_REQUEST_STORE] ??= new AsyncLocalStorage<FarmI18nRequestState>());\n}\n\nfunction getState(): FarmI18nRequestState {\n  const state = getRequestStore().getStore();\n  if (!state) {\n    throw new Error(\n      \"No Farm i18n request context is active. Use this API while rendering, inside an API route, or use createTranslator(locale).\",\n    );\n  }\n  return state;\n}\n\nexport function _setDefaultFarmI18nRuntime(runtime: FarmI18nRuntime | undefined): void {\n  (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME] = runtime;\n}\n\nexport async function _runWithFarmI18nRequest<T>(\n  runtime: FarmI18nRuntime,\n  request: Request,\n  fn: (resolution: FarmLocaleResolution) => T | Promise<T>,\n  options: { redirect?: boolean } = {},\n): Promise<T> {\n  const resolution = runtime.resolveRequest(request, options);\n  const state: FarmI18nRequestState = {\n    runtime,\n    resolution,\n    snapshot: runtime.getClientSnapshot(resolution),\n  };\n  return getRequestStore().run(state, () => fn(resolution));\n}\n\nexport async function runWithLocale<T>(\n  locale: FarmI18nLocale,\n  fn: () => T | Promise<T>,\n): Promise<T> {\n  const runtime = getDefaultRuntime();\n  assertLocale(runtime, locale);\n  const resolution: FarmLocaleResolution = {\n    locale,\n    source: \"explicit\",\n    pathname: \"/\",\n    persist: false,\n  };\n  const state: FarmI18nRequestState = {\n    runtime,\n    resolution,\n    snapshot: runtime.getClientSnapshot(resolution),\n  };\n  return getRequestStore().run(state, fn);\n}\n\nexport function getLocale(): FarmI18nLocale {\n  return getState().resolution.locale as FarmI18nLocale;\n}\n\nexport function getLocaleSource(): FarmI18nLocaleSource {\n  return getState().resolution.source;\n}\n\nexport const t = createTranslatorFromState(() => getState());\n\nexport function createTranslator(locale: FarmI18nLocale): FarmTranslator {\n  const runtime = getDefaultRuntime();\n  assertLocale(runtime, locale);\n  return createTranslatorFromState(() => ({\n    runtime,\n    resolution: {\n      locale,\n      source: \"explicit\",\n      pathname: \"/\",\n      persist: false,\n    },\n    snapshot: runtime.getClientSnapshot({\n      locale,\n      source: \"explicit\",\n      pathname: \"/\",\n      persist: false,\n    }),\n  }));\n}\n\nexport function getFarmI18nClientSnapshot(): FarmI18nClientSnapshot | undefined {\n  return getRequestStore().getStore()?.snapshot;\n}\n\nexport const format = {\n  number(value: number, options?: Intl.NumberFormatOptions): string {\n    return new Intl.NumberFormat(getLocale(), options).format(value);\n  },\n  currency(\n    value: number,\n    currency: string,\n    options: Omit<Intl.NumberFormatOptions, \"style\" | \"currency\"> = {},\n  ): string {\n    return new Intl.NumberFormat(getLocale(), {\n      ...options,\n      style: \"currency\",\n      currency,\n    }).format(value);\n  },\n  date(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n    return new Intl.DateTimeFormat(getLocale(), options).format(value);\n  },\n  relativeTime(\n    value: number,\n    unit: Intl.RelativeTimeFormatUnit,\n    options?: Intl.RelativeTimeFormatOptions,\n  ): string {\n    return new Intl.RelativeTimeFormat(getLocale(), options).format(value, unit);\n  },\n  list(values: Iterable<string>, options?: FarmListFormatOptions): string {\n    const ListFormat = (Intl as any).ListFormat;\n    return new ListFormat(getLocale(), options).format(Array.from(values));\n  },\n};\n\nfunction getDefaultRuntime(): FarmI18nRuntime {\n  const runtime = (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME];\n  if (!runtime?.config.enabled) {\n    throw new Error(\"Farm i18n is not configured for this application.\");\n  }\n  return runtime;\n}\n\nfunction assertLocale(runtime: FarmI18nRuntime, locale: string): void {\n  if (!runtime.config.locales.includes(locale)) {\n    throw new Error(`Unsupported Farm i18n locale \"${locale}\".`);\n  }\n}\n\nfunction createTranslatorFromState(resolveState: () => FarmI18nRequestState): FarmTranslator {\n  const translator = ((key: string, values?: Record<string, unknown>) => {\n    const state = resolveState();\n    return state.runtime.translate(state.resolution.locale, key, values);\n  }) as FarmTranslator;\n  translator.rich = (key: string, values?: Record<string, unknown>) => {\n    const state = resolveState();\n    return state.runtime.translateRich(state.resolution.locale, key, values);\n  };\n  translator.raw = (key: string) => {\n    const state = resolveState();\n    return state.runtime.getRawMessage(state.resolution.locale, key);\n  };\n  translator.has = (key: string) => {\n    const state = resolveState();\n    return state.runtime.hasMessage(state.resolution.locale, key);\n  };\n  return translator;\n}\n\n_setFarmI18nSnapshotResolver(() => getFarmI18nClientSnapshot());\n\nexport { FarmI18nRuntime, createFarmI18nRuntime };\nexport type { FarmI18nClientSnapshot, FarmI18nLocale, FarmI18nMessageArgs, FarmI18nMessageKey };\n","import IntlMessageFormat from \"intl-messageformat\";\nimport { readFarmI18nCatalogs } from \"./catalog\";\nimport { getFarmLocaleDirection } from \"./routing\";\nimport { resolveFarmLocaleRequest, type FarmLocaleResolution } from \"./resolver\";\nimport type { FarmI18nCatalogs, FarmI18nClientSnapshot, ResolvedFarmI18nConfig } from \"./types\";\n\nexport class FarmI18nRuntime {\n  readonly config: ResolvedFarmI18nConfig;\n  private catalogs: FarmI18nCatalogs;\n  private compiled = new Map<string, IntlMessageFormat>();\n  private warnedMissing = new Set<string>();\n\n  constructor(config: ResolvedFarmI18nConfig, catalogs: FarmI18nCatalogs = {}) {\n    this.config = config;\n    this.catalogs = catalogs;\n  }\n\n  async initialize(): Promise<void> {\n    if (!this.config.enabled) return;\n    const bundle = await readFarmI18nCatalogs(this.config);\n    this.replaceCatalogs(bundle.catalogs);\n  }\n\n  async reload(): Promise<void> {\n    await this.initialize();\n  }\n\n  replaceCatalogs(catalogs: FarmI18nCatalogs): void {\n    this.catalogs = catalogs;\n    this.compiled.clear();\n    this.warnedMissing.clear();\n  }\n\n  getCatalogs(): FarmI18nCatalogs {\n    return Object.fromEntries(\n      Object.entries(this.catalogs).map(([locale, catalog]) => [locale, { ...catalog }]),\n    );\n  }\n\n  resolveRequest(request: Request, options: { redirect?: boolean } = {}): FarmLocaleResolution {\n    return resolveFarmLocaleRequest(request, this.config, options);\n  }\n\n  translate(locale: string, key: string, values?: Record<string, unknown>): string {\n    const result = this.formatMessage(locale, key, values);\n    if (Array.isArray(result) && result.some((part) => typeof part !== \"string\")) {\n      throw new Error(`Farm i18n message \"${key}\" contains rich content. Render it with t.rich().`);\n    }\n    return Array.isArray(result) ? result.join(\"\") : String(result);\n  }\n\n  translateRich(locale: string, key: string, values?: Record<string, unknown>): unknown {\n    const result = this.formatMessage(locale, key, values);\n    return Array.isArray(result) && result.length === 1 ? result[0] : result;\n  }\n\n  getRawMessage(locale: string, key: string): string {\n    return this.resolveMessage(locale, key);\n  }\n\n  hasMessage(locale: string, key: string): boolean {\n    return this.readOwnMessage(locale, key) !== undefined;\n  }\n\n  getClientSnapshot(resolution: FarmLocaleResolution): FarmI18nClientSnapshot {\n    return {\n      locale: resolution.locale,\n      source: resolution.source,\n      locales: this.config.locales,\n      defaultLocale: this.config.defaultLocale,\n      routing: this.config.routing,\n      basePath: this.config.basePath,\n      cookie: this.config.cookie,\n      direction: getFarmLocaleDirection(resolution.locale, this.config.direction),\n      messages: {\n        ...this.catalogs[this.config.fallbackLocale],\n        ...this.catalogs[resolution.locale],\n      },\n    };\n  }\n\n  private formatMessage(locale: string, key: string, values?: Record<string, unknown>): unknown {\n    const message = this.resolveMessage(locale, key);\n    const cacheKey = `${locale}\\u0000${key}\\u0000${message}`;\n    let formatter = this.compiled.get(cacheKey);\n    if (!formatter) {\n      formatter = new IntlMessageFormat(message, locale);\n      this.compiled.set(cacheKey, formatter);\n    }\n    return formatter.format(values as any);\n  }\n\n  // Look up a message by own-property only. A key named after an\n  // Object.prototype member (toString, valueOf, constructor, ...) must resolve\n  // to a real catalog entry or undefined, never the inherited prototype value\n  // (mirrors the own-property handling added to catalog.ts in #454).\n  private readOwnMessage(locale: string, key: string): string | undefined {\n    const direct = this.catalogs[locale];\n    if (direct && Object.prototype.hasOwnProperty.call(direct, key)) return direct[key];\n    const fallback = this.catalogs[this.config.fallbackLocale];\n    if (fallback && Object.prototype.hasOwnProperty.call(fallback, key)) return fallback[key];\n    return undefined;\n  }\n\n  private resolveMessage(locale: string, key: string): string {\n    const message = this.readOwnMessage(locale, key);\n    if (message !== undefined) return message;\n    if (this.config.strict) {\n      throw new Error(`Missing Farm i18n message \"${key}\" for locale \"${locale}\".`);\n    }\n    const warningKey = `${locale}:${key}`;\n    if (!this.warnedMissing.has(warningKey)) {\n      this.warnedMissing.add(warningKey);\n      console.warn(`[Farm.js] Missing i18n message \"${key}\" for locale \"${locale}\".`);\n    }\n    return key;\n  }\n}\n\nexport function createFarmI18nRuntime(\n  config: ResolvedFarmI18nConfig,\n  catalogs?: FarmI18nCatalogs,\n): FarmI18nRuntime {\n  return new FarmI18nRuntime(config, catalogs);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { TYPE, parse, type MessageFormatElement } from \"@formatjs/icu-messageformat-parser\";\nimport { resolveFarmI18nMessagePath } from \"./config\";\nimport type { FarmI18nCatalog, FarmI18nCatalogs, ResolvedFarmI18nConfig } from \"./types\";\n\nexport type FarmI18nArgumentKind = \"string\" | \"number\" | \"date\" | \"select\" | \"rich\";\nexport type FarmI18nMessageSignature = Record<string, FarmI18nArgumentKind>;\n\nexport interface FarmI18nCatalogBundle {\n  catalogs: FarmI18nCatalogs;\n  signatures: Record<string, FarmI18nMessageSignature>;\n}\n\nexport async function readFarmI18nCatalogs(\n  config: ResolvedFarmI18nConfig,\n): Promise<FarmI18nCatalogBundle> {\n  if (!config.enabled) {\n    return { catalogs: {}, signatures: {} };\n  }\n\n  const catalogs: FarmI18nCatalogs = {};\n  for (const locale of config.locales) {\n    const filePath = resolveFarmI18nMessagePath(config, locale);\n    let source: string;\n    try {\n      source = await readFile(filePath, \"utf8\");\n    } catch (error) {\n      throw new Error(\n        `Unable to read Farm i18n catalog for \"${locale}\" at ${filePath}: ${messageOf(error)}`,\n      );\n    }\n\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(source);\n    } catch (error) {\n      throw new Error(`Invalid JSON in Farm i18n catalog ${filePath}: ${messageOf(error)}`);\n    }\n    catalogs[locale] = flattenFarmI18nCatalog(parsed, filePath);\n  }\n\n  const reference = catalogs[config.defaultLocale] || {};\n  const signatures: Record<string, FarmI18nMessageSignature> = {};\n  for (const [key, message] of Object.entries(reference)) {\n    signatures[key] = analyzeFarmI18nMessage(message, `${config.defaultLocale}:${key}`);\n  }\n\n  validateFarmI18nCatalogs(config, catalogs, signatures);\n  return { catalogs, signatures };\n}\n\nexport function flattenFarmI18nCatalog(input: unknown, source = \"i18n catalog\"): FarmI18nCatalog {\n  if (!isPlainObject(input)) {\n    throw new Error(`${source} must contain a JSON object at its root.`);\n  }\n\n  const output: FarmI18nCatalog = {};\n  const visit = (value: unknown, segments: string[]) => {\n    if (typeof value === \"string\") {\n      const key = segments.join(\".\");\n      if (!key) throw new Error(`${source} contains an empty message key.`);\n      // Own-property check: `in` would see Object.prototype members, falsely\n      // rejecting legitimate keys like \"toString\" as duplicates.\n      if (Object.prototype.hasOwnProperty.call(output, key)) {\n        throw new Error(`${source} contains duplicate message key \"${key}\".`);\n      }\n      output[key] = value;\n      return;\n    }\n\n    if (!isPlainObject(value)) {\n      const key = segments.join(\".\") || \"<root>\";\n      throw new Error(`${source} message \"${key}\" must be a string or nested object.`);\n    }\n\n    for (const [key, nested] of Object.entries(value)) {\n      if (!key.trim()) throw new Error(`${source} contains an empty message key.`);\n      visit(nested, [...segments, key]);\n    }\n  };\n\n  visit(input, []);\n  return output;\n}\n\nexport function analyzeFarmI18nMessage(\n  message: string,\n  label = \"message\",\n): FarmI18nMessageSignature {\n  let ast: MessageFormatElement[];\n  try {\n    ast = parse(message, { captureLocation: false });\n  } catch (error) {\n    throw new Error(`Invalid ICU syntax in ${label}: ${messageOf(error)}`);\n  }\n\n  const signature: FarmI18nMessageSignature = {};\n  collectArguments(ast, signature, label);\n  return signature;\n}\n\nfunction validateFarmI18nCatalogs(\n  config: ResolvedFarmI18nConfig,\n  catalogs: FarmI18nCatalogs,\n  signatures: Record<string, FarmI18nMessageSignature>,\n): void {\n  const referenceKeys = Object.keys(catalogs[config.defaultLocale] || {}).sort();\n\n  for (const locale of config.locales) {\n    const catalog = catalogs[locale] || {};\n    const localeKeys = Object.keys(catalog).sort();\n    const missing = referenceKeys.filter(\n      (key) => !Object.prototype.hasOwnProperty.call(catalog, key),\n    );\n    const extra = localeKeys.filter(\n      (key) => !Object.prototype.hasOwnProperty.call(signatures, key),\n    );\n\n    if (config.strict && (missing.length > 0 || extra.length > 0)) {\n      const details = [\n        missing.length ? `missing: ${missing.join(\", \")}` : \"\",\n        extra.length ? `extra: ${extra.join(\", \")}` : \"\",\n      ]\n        .filter(Boolean)\n        .join(\"; \");\n      throw new Error(\n        `Farm i18n catalog \"${locale}\" does not match the default catalog (${details}).`,\n      );\n    }\n\n    for (const [key, message] of Object.entries(catalog)) {\n      const actual = analyzeFarmI18nMessage(message, `${locale}:${key}`);\n      const expected = signatures[key];\n      if (!expected || sameSignature(expected, actual)) continue;\n      throw new Error(\n        `Farm i18n message \"${key}\" in \"${locale}\" uses different variables than \"${config.defaultLocale}\".`,\n      );\n    }\n  }\n}\n\nfunction collectArguments(\n  elements: MessageFormatElement[],\n  signature: FarmI18nMessageSignature,\n  label: string,\n): void {\n  for (const element of elements) {\n    switch (element.type) {\n      case TYPE.argument:\n        addArgument(signature, element.value, \"string\", label);\n        break;\n      case TYPE.number:\n      case TYPE.plural:\n        addArgument(signature, element.value, \"number\", label);\n        break;\n      case TYPE.date:\n      case TYPE.time:\n        addArgument(signature, element.value, \"date\", label);\n        break;\n      case TYPE.select:\n        addArgument(signature, element.value, \"select\", label);\n        break;\n      case TYPE.tag:\n        addArgument(signature, element.value, \"rich\", label);\n        collectArguments(element.children, signature, label);\n        break;\n    }\n\n    if (element.type === TYPE.plural || element.type === TYPE.select) {\n      for (const option of Object.values(element.options)) {\n        collectArguments(option.value, signature, label);\n      }\n    }\n  }\n}\n\nfunction addArgument(\n  signature: FarmI18nMessageSignature,\n  name: string,\n  kind: FarmI18nArgumentKind,\n  label: string,\n): void {\n  const existing = signature[name];\n  if (existing && existing !== kind) {\n    throw new Error(`Farm i18n ${label} uses variable \"${name}\" as both ${existing} and ${kind}.`);\n  }\n  signature[name] = kind;\n}\n\nfunction sameSignature(\n  expected: FarmI18nMessageSignature,\n  actual: FarmI18nMessageSignature,\n): boolean {\n  const expectedEntries = Object.entries(expected).sort(([a], [b]) => a.localeCompare(b));\n  const actualEntries = Object.entries(actual).sort(([a], [b]) => a.localeCompare(b));\n  return JSON.stringify(expectedEntries) === JSON.stringify(actualEntries);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction messageOf(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n","import { 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 { 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","import { omitFarmResponseBody } from \"./response-body\";\n\nexport type ApplicationMetadataRouteKind = \"sitemap\" | \"robots\" | \"manifest\";\n\nexport namespace MetadataRoute {\n  export type SitemapChangeFrequency =\n    | \"always\"\n    | \"hourly\"\n    | \"daily\"\n    | \"weekly\"\n    | \"monthly\"\n    | \"yearly\"\n    | \"never\";\n\n  export interface SitemapEntry {\n    url: string;\n    lastModified?: string | Date;\n    changeFrequency?: SitemapChangeFrequency;\n    priority?: number;\n    alternates?: {\n      languages?: Record<string, string>;\n    };\n  }\n\n  export type Sitemap = SitemapEntry[];\n\n  export interface RobotsRule {\n    userAgent: string | string[];\n    allow?: string | string[];\n    disallow?: string | string[];\n    crawlDelay?: number;\n  }\n\n  export interface Robots {\n    rules: RobotsRule | RobotsRule[];\n    sitemap?: string | string[];\n    host?: string;\n  }\n\n  export interface ManifestIcon {\n    src: string;\n    sizes?: string;\n    type?: string;\n    purpose?: string;\n  }\n\n  export interface Manifest {\n    name?: string;\n    short_name?: string;\n    description?: string;\n    id?: string;\n    start_url?: string;\n    scope?: string;\n    display?: \"fullscreen\" | \"standalone\" | \"minimal-ui\" | \"browser\" | string;\n    orientation?: string;\n    background_color?: string;\n    theme_color?: string;\n    lang?: string;\n    dir?: \"ltr\" | \"rtl\" | \"auto\";\n    categories?: string[];\n    icons?: ManifestIcon[];\n    [key: string]: unknown;\n  }\n}\n\nexport interface MetadataRouteContext {\n  request: Request;\n  params: Record<string, string>;\n  searchParams: URLSearchParams;\n  /** The concrete route-segment path that owns the metadata file. */\n  path: string;\n}\n\nexport interface FarmMetadataRouteModule {\n  revalidate?: number | false;\n}\n\nexport interface FarmMetadataRouteResponseOptions {\n  method?: string;\n}\n\nfunction isResponse(value: unknown): value is Response {\n  return (\n    typeof Response !== \"undefined\" &&\n    (value instanceof Response ||\n      Boolean(\n        value &&\n        typeof value === \"object\" &&\n        typeof (value as Response).arrayBuffer === \"function\" &&\n        (value as Response).headers,\n      ))\n  );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction resolveCacheControl(revalidate: number | false | undefined): string {\n  if (revalidate === false) {\n    return \"public, max-age=31536000, immutable\";\n  }\n  if (typeof revalidate === \"number\" && Number.isFinite(revalidate) && revalidate > 0) {\n    return `public, s-maxage=${Math.floor(revalidate)}, stale-while-revalidate=300`;\n  }\n  return \"public, max-age=0, must-revalidate\";\n}\n\nfunction escapeXml(value: unknown): string {\n  return String(value)\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&apos;\");\n}\n\nfunction serializeSitemap(value: unknown): string {\n  if (!Array.isArray(value)) {\n    throw new TypeError(\"sitemap.ts must return an array or a Response\");\n  }\n\n  const entries = value.map((candidate, index) => {\n    if (!isRecord(candidate) || typeof candidate.url !== \"string\" || !candidate.url) {\n      throw new TypeError(`sitemap.ts entry ${index} must include a non-empty url`);\n    }\n    return candidate as unknown as MetadataRoute.SitemapEntry;\n  });\n  const hasLanguageAlternates = entries.some(\n    (entry) => entry.alternates?.languages && Object.keys(entry.alternates.languages).length > 0,\n  );\n  const namespace = hasLanguageAlternates ? ' xmlns:xhtml=\"http://www.w3.org/1999/xhtml\"' : \"\";\n  const lines = [\n    '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n    `<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"${namespace}>`,\n  ];\n\n  for (const entry of entries) {\n    lines.push(\"  <url>\", `    <loc>${escapeXml(entry.url)}</loc>`);\n    if (entry.lastModified !== undefined) {\n      const lastModified =\n        entry.lastModified instanceof Date ? entry.lastModified.toISOString() : entry.lastModified;\n      lines.push(`    <lastmod>${escapeXml(lastModified)}</lastmod>`);\n    }\n    if (entry.changeFrequency) {\n      lines.push(`    <changefreq>${escapeXml(entry.changeFrequency)}</changefreq>`);\n    }\n    if (entry.priority !== undefined) {\n      lines.push(`    <priority>${escapeXml(entry.priority)}</priority>`);\n    }\n    for (const [language, href] of Object.entries(entry.alternates?.languages || {})) {\n      lines.push(\n        `    <xhtml:link rel=\"alternate\" hreflang=\"${escapeXml(language)}\" href=\"${escapeXml(href)}\" />`,\n      );\n    }\n    lines.push(\"  </url>\");\n  }\n\n  lines.push(\"</urlset>\");\n  return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction toArray<T>(value: T | T[] | undefined): T[] {\n  return value === undefined ? [] : Array.isArray(value) ? value : [value];\n}\n\nfunction serializeRobots(value: unknown): string {\n  if (!isRecord(value)) {\n    throw new TypeError(\"robots.ts must return a robots object or a Response\");\n  }\n\n  const robots = value as unknown as MetadataRoute.Robots;\n  const rules = toArray(robots.rules);\n  if (rules.length === 0) {\n    throw new TypeError(\"robots.ts must return at least one rule\");\n  }\n\n  const sections = rules.map((rule, index) => {\n    if (!isRecord(rule)) {\n      throw new TypeError(`robots.ts rule ${index} must be an object`);\n    }\n    const userAgents = toArray(rule.userAgent).filter(\n      (userAgent): userAgent is string => typeof userAgent === \"string\" && Boolean(userAgent),\n    );\n    if (userAgents.length === 0) {\n      throw new TypeError(`robots.ts rule ${index} must include a userAgent`);\n    }\n\n    const lines = userAgents.map((userAgent) => `User-agent: ${userAgent}`);\n    for (const allow of toArray(rule.allow)) lines.push(`Allow: ${allow}`);\n    for (const disallow of toArray(rule.disallow)) lines.push(`Disallow: ${disallow}`);\n    if (rule.crawlDelay !== undefined) lines.push(`Crawl-delay: ${rule.crawlDelay}`);\n    return lines.join(\"\\n\");\n  });\n\n  const globalLines = [\n    ...toArray(robots.sitemap).map((sitemap) => `Sitemap: ${sitemap}`),\n    ...(robots.host ? [`Host: ${robots.host}`] : []),\n  ];\n  return `${[...sections, ...(globalLines.length ? [globalLines.join(\"\\n\")] : [])].join(\"\\n\\n\")}\\n`;\n}\n\nfunction serializeManifest(value: unknown): string {\n  if (!isRecord(value)) {\n    throw new TypeError(\"manifest.ts must return a manifest object or a Response\");\n  }\n  return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\n/** @internal */\nexport function createFarmMetadataRouteResponse(\n  kind: ApplicationMetadataRouteKind,\n  value: unknown,\n  routeModule: FarmMetadataRouteModule = {},\n  options: FarmMetadataRouteResponseOptions = {},\n): Response {\n  const method = (options.method || \"GET\").toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    return new Response(null, { status: 405, headers: { Allow: \"GET, HEAD\" } });\n  }\n\n  if (isResponse(value)) {\n    return method === \"HEAD\" ? omitFarmResponseBody(value) : value;\n  }\n\n  const body =\n    kind === \"sitemap\"\n      ? serializeSitemap(value)\n      : kind === \"robots\"\n        ? serializeRobots(value)\n        : serializeManifest(value);\n  const contentType =\n    kind === \"sitemap\"\n      ? \"application/xml; charset=utf-8\"\n      : kind === \"robots\"\n        ? \"text/plain; charset=utf-8\"\n        : \"application/manifest+json; charset=utf-8\";\n\n  return new Response(method === \"HEAD\" ? null : body, {\n    headers: {\n      \"Content-Type\": contentType,\n      \"Cache-Control\": resolveCacheControl(routeModule.revalidate),\n      \"X-Content-Type-Options\": \"nosniff\",\n    },\n  });\n}\n","const FARM_TRAILING_SLASH_PREFERENCE = Symbol.for(\"farm.trailingSlashPreference\");\n\nfunction getFarmGlobalState(): Record<PropertyKey, unknown> {\n  return globalThis as unknown as Record<PropertyKey, unknown>;\n}\n\n/** @internal Configure the app-wide URL preference for framework link rendering. */\nexport function setFarmTrailingSlashPreference(enabled: boolean | undefined): void {\n  getFarmGlobalState()[FARM_TRAILING_SLASH_PREFERENCE] = enabled === true;\n}\n\n/** @internal Read the app-wide URL preference used by framework links. */\nexport function getFarmTrailingSlashPreference(): boolean {\n  return getFarmGlobalState()[FARM_TRAILING_SLASH_PREFERENCE] === true;\n}\n\nexport function normalizeFarmTrailingSlashPathname(pathname: string, enabled: boolean): string {\n  if (pathname === \"/\") return pathname;\n  if (enabled) return pathname.endsWith(\"/\") ? pathname : `${pathname}/`;\n  return pathname.replace(/\\/+$/, \"\") || \"/\";\n}\n\nexport function resolveFarmTrailingSlashRedirect(url: URL, enabled: boolean): string | null {\n  const pathname = normalizeFarmTrailingSlashPathname(url.pathname, enabled);\n  return pathname === url.pathname ? null : `${pathname}${url.search}`;\n}\n","export const DEFAULT_NOT_FOUND_STYLES = `\nbody {\n  margin: 0;\n}\n\n.farm-default-not-found {\n  --farm-not-found-bg: #fafafa;\n  --farm-not-found-fg: #171717;\n  --farm-not-found-muted: #737373;\n  --farm-not-found-line: rgba(0, 0, 0, 0.16);\n  --farm-not-found-button-fg: #ffffff;\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  place-items: center;\n  padding: 24px;\n  color: var(--farm-not-found-fg);\n  background: var(--farm-not-found-bg);\n  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  color-scheme: light;\n}\n\n.farm-default-not-found,\n.farm-default-not-found * {\n  box-sizing: border-box;\n}\n\n.farm-default-not-found__content {\n  width: min(100%, 280px);\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n}\n\n.farm-default-not-found__code {\n  margin: 0;\n  color: var(--farm-not-found-fg);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: clamp(88px, 20vw, 140px);\n  font-weight: 800;\n  line-height: 0.75;\n  letter-spacing: -0.1em;\n  transform: translateX(-3px);\n}\n\n@supports (-webkit-text-stroke: 1px currentColor) {\n  .farm-default-not-found__code {\n    color: var(--farm-not-found-bg);\n    -webkit-text-stroke: 2px var(--farm-not-found-fg);\n    text-shadow: 5px 5px 0 var(--farm-not-found-fg);\n  }\n}\n\n.farm-default-not-found__description {\n  width: 100%;\n  display: flex;\n  align-items: center;\n  gap: 12px;\n  margin: 34px 0 30px;\n  color: var(--farm-not-found-muted);\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: 10px;\n  line-height: 1;\n  letter-spacing: 0.14em;\n  text-transform: uppercase;\n  white-space: nowrap;\n}\n\n.farm-default-not-found__description::before,\n.farm-default-not-found__description::after {\n  content: \"\";\n  height: 1px;\n  flex: 1 1 auto;\n  background: var(--farm-not-found-line);\n}\n\n.farm-default-not-found__home {\n  min-width: 132px;\n  min-height: 44px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 20px;\n  border: 1px solid var(--farm-not-found-fg);\n  border-radius: 0;\n  color: var(--farm-not-found-button-fg);\n  background: var(--farm-not-found-fg);\n  font-size: 14px;\n  font-weight: 500;\n  line-height: 1;\n  text-decoration: none;\n  transition: opacity 150ms ease-out, transform 100ms ease-out;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  .farm-default-not-found__home:hover {\n    opacity: 0.78;\n  }\n}\n\n.farm-default-not-found__home:active {\n  transform: translateY(1px);\n}\n\n.farm-default-not-found__home:focus-visible {\n  outline: 2px solid var(--farm-not-found-fg);\n  outline-offset: 3px;\n}\n\n@media (prefers-color-scheme: dark) {\n  .farm-default-not-found {\n    --farm-not-found-bg: #0a0a0a;\n    --farm-not-found-fg: #ededed;\n    --farm-not-found-muted: #a1a1a1;\n    --farm-not-found-line: rgba(255, 255, 255, 0.2);\n    --farm-not-found-button-fg: #0a0a0a;\n    color-scheme: dark;\n  }\n}\n\n.dark .farm-default-not-found,\n[data-theme=\"dark\"] .farm-default-not-found,\n[data-color-scheme=\"dark\"] .farm-default-not-found {\n  --farm-not-found-bg: #0a0a0a;\n  --farm-not-found-fg: #ededed;\n  --farm-not-found-muted: #a1a1a1;\n  --farm-not-found-line: rgba(255, 255, 255, 0.2);\n  --farm-not-found-button-fg: #0a0a0a;\n  color-scheme: dark;\n}\n\n.light .farm-default-not-found,\n[data-theme=\"light\"] .farm-default-not-found,\n[data-color-scheme=\"light\"] .farm-default-not-found {\n  --farm-not-found-bg: #fafafa;\n  --farm-not-found-fg: #171717;\n  --farm-not-found-muted: #737373;\n  --farm-not-found-line: rgba(0, 0, 0, 0.16);\n  --farm-not-found-button-fg: #ffffff;\n  color-scheme: light;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .farm-default-not-found__home {\n    transition: none;\n  }\n\n  .farm-default-not-found__home:active {\n    transform: none;\n  }\n}\n`;\n","/**\n * Shared styles for Farm's default HTTP error page.\n *\n * Kept framework-agnostic so the same fallback can be used by the development\n * renderer and generated production runtimes.\n */\nexport const DEFAULT_ERROR_STYLES = `\nbody {\n  margin: 0;\n  background: #080808;\n}\n\n.farm-default-error {\n  --farm-error-bg: #080808;\n  --farm-error-panel: #0d0d0d;\n  --farm-error-fg: #f3f3f3;\n  --farm-error-muted: #9a9a9a;\n  --farm-error-subtle: #6f6f6f;\n  --farm-error-line: rgba(255, 255, 255, 0.1);\n  --farm-error-line-strong: rgba(255, 255, 255, 0.2);\n  --farm-error-button-bg: #f1f1f1;\n  --farm-error-button-fg: #0a0a0a;\n  --farm-error-source-line: rgba(255, 255, 255, 0.055);\n  --farm-error-source-marker: #f3f3f3;\n  --farm-error-font-sans: \"Geist Variable\", \"Geist Sans\", Geist, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n  --farm-error-font-mono: \"Geist Mono Variable\", \"Geist Mono\", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  color: var(--farm-error-fg);\n  background: var(--farm-error-bg);\n  font-family: var(--farm-error-font-sans);\n  font-synthesis: none;\n  color-scheme: dark;\n  text-rendering: optimizeLegibility;\n}\n\n.farm-default-error,\n.farm-default-error * {\n  box-sizing: border-box;\n}\n\n.farm-default-error__frame {\n  width: min(100%, 1180px);\n  min-height: 100vh;\n  min-height: 100svh;\n  display: grid;\n  grid-template-rows: auto minmax(0, 1fr) auto;\n  margin: 0 auto;\n  padding: clamp(24px, 4vw, 52px);\n}\n\n.farm-default-error__brand {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 11px;\n  font-weight: 520;\n  line-height: 1;\n  letter-spacing: 0.08em;\n}\n\n.farm-default-error__brand > span:first-child {\n  color: var(--farm-error-fg);\n}\n\n.farm-default-error__brand-divider,\n.farm-default-error__status-divider,\n.farm-default-error__footer-divider {\n  color: var(--farm-error-subtle);\n}\n\n.farm-default-error__content {\n  width: min(100%, 680px);\n  min-width: 0;\n  align-self: center;\n  margin: 0 auto;\n  padding: clamp(64px, 10vh, 112px) 0;\n}\n\n.farm-default-error--development .farm-default-error__content {\n  width: min(100%, 900px);\n}\n\n.farm-default-error > .farm-default-error__content {\n  align-self: center;\n  padding-right: 24px;\n  padding-left: 24px;\n}\n\n.farm-default-error__status,\n.farm-default-error__eyebrow {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin: 0 0 24px;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  font-weight: 520;\n  line-height: 1.4;\n  letter-spacing: 0.055em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__status-mark {\n  width: 6px;\n  height: 6px;\n  flex: 0 0 auto;\n  background: var(--farm-error-fg);\n}\n\n.farm-default-error__code {\n  margin: 0 0 18px;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-mono);\n  font-size: clamp(48px, 8vw, 72px);\n  font-weight: 540;\n  line-height: 0.95;\n  letter-spacing: -0.055em;\n}\n\n.farm-default-error__summary {\n  margin: 0;\n}\n\n.farm-default-error__title {\n  max-width: 680px;\n  margin: 0;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-sans);\n  font-size: clamp(36px, 5.2vw, 56px);\n  font-weight: 560;\n  line-height: 1.04;\n  letter-spacing: -0.052em;\n  text-wrap: balance;\n}\n\n.farm-default-error__message {\n  max-width: 590px;\n  margin: 18px 0 0;\n  color: var(--farm-error-muted);\n  font-family: var(--farm-error-font-sans);\n  font-size: clamp(16px, 2vw, 19px);\n  line-height: 1.55;\n  letter-spacing: -0.012em;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__actions {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 10px;\n  margin-top: 30px;\n}\n\n.farm-default-error__action {\n  min-height: 44px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 17px;\n  border: 1px solid var(--farm-error-line-strong);\n  border-radius: 7px;\n  color: var(--farm-error-fg);\n  background: transparent;\n  font: inherit;\n  font-family: var(--farm-error-font-mono);\n  font-size: 13px;\n  font-weight: 560;\n  line-height: 1;\n  letter-spacing: 0.015em;\n  text-decoration: none;\n  cursor: pointer;\n  transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out, transform 100ms ease-out;\n}\n\n.farm-default-error__action--primary {\n  border-color: var(--farm-error-button-bg);\n  color: var(--farm-error-button-fg);\n  background: var(--farm-error-button-bg);\n}\n\n.farm-default-error__panel {\n  margin-top: 42px;\n  border-top: 1px solid var(--farm-error-line-strong);\n}\n\n.farm-default-error__row {\n  min-height: 45px;\n  display: grid;\n  grid-template-columns: 92px minmax(0, 1fr);\n  align-items: center;\n  border-bottom: 1px solid var(--farm-error-line);\n}\n\n.farm-default-error__label,\n.farm-default-error__value,\n.farm-default-error__details-title,\n.farm-default-error__source-path,\n.farm-default-error__meta,\n.farm-default-error__footer-action {\n  font-family: var(--farm-error-font-mono);\n}\n\n.farm-default-error__label {\n  color: var(--farm-error-subtle);\n  font-size: 10px;\n  font-weight: 560;\n  letter-spacing: 0.09em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__value {\n  min-width: 0;\n  padding: 11px 0;\n  color: var(--farm-error-muted);\n  font-size: 12px;\n  line-height: 1.55;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__details {\n  padding: 24px 0 0;\n  border-bottom: 1px solid var(--farm-error-line);\n}\n\n.farm-default-error__details-header {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 16px;\n  margin-bottom: 12px;\n}\n\n.farm-default-error__details-title {\n  margin: 0;\n  color: var(--farm-error-muted);\n  font-size: 10px;\n  font-weight: 560;\n  line-height: 1;\n  letter-spacing: 0.09em;\n  text-transform: uppercase;\n}\n\n.farm-default-error__copy {\n  min-height: 32px;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0 10px;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 6px;\n  color: var(--farm-error-muted);\n  background: transparent;\n  font: inherit;\n  font-size: 11px;\n  cursor: pointer;\n  transition: background-color 150ms ease-out, border-color 150ms ease-out, color 150ms ease-out;\n}\n\n.farm-default-error__source {\n  overflow: hidden;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 7px;\n  background: var(--farm-error-panel);\n}\n\n.farm-default-error__source-path {\n  margin: 0;\n  padding: 10px 13px;\n  border-bottom: 1px solid var(--farm-error-line);\n  color: var(--farm-error-muted);\n  font-size: 11px;\n  line-height: 1.45;\n  overflow-wrap: anywhere;\n}\n\n.farm-default-error__source-code {\n  margin: 0;\n  padding: 8px 0;\n  overflow-x: auto;\n  color: var(--farm-error-fg);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  line-height: 1.75;\n  tab-size: 2;\n}\n\n.farm-default-error__source-line {\n  min-width: max-content;\n  display: grid;\n  grid-template-columns: 68px minmax(0, 1fr);\n  padding: 0 14px 0 0;\n  border-left: 1px solid transparent;\n}\n\n.farm-default-error__source-line--active {\n  border-left-color: var(--farm-error-source-marker);\n  background: var(--farm-error-source-line);\n}\n\n.farm-default-error__source-gutter {\n  padding-right: 14px;\n  color: var(--farm-error-subtle);\n  text-align: right;\n  user-select: none;\n}\n\n.farm-default-error__source-line--active .farm-default-error__source-gutter {\n  color: var(--farm-error-source-marker);\n}\n\n.farm-default-error__source-text {\n  white-space: pre;\n}\n\n.farm-default-error__details-empty {\n  margin: 0;\n  padding: 14px;\n  border: 1px solid var(--farm-error-line);\n  border-radius: 7px;\n  color: var(--farm-error-muted);\n  background: var(--farm-error-panel);\n  font-family: var(--farm-error-font-mono);\n  font-size: 12px;\n  line-height: 1.5;\n}\n\n.farm-default-error__meta {\n  margin: 12px 0 20px;\n  color: var(--farm-error-subtle);\n  font-size: 10px;\n  line-height: 1.5;\n  letter-spacing: 0.035em;\n}\n\n.farm-default-error__footer {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: center;\n  gap: 12px;\n  padding-top: 24px;\n}\n\n.farm-default-error__footer-action {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  padding: 0;\n  border: 0;\n  color: var(--farm-error-muted);\n  background: transparent;\n  font-size: 10px;\n  font-weight: 540;\n  line-height: 1.4;\n  letter-spacing: 0.065em;\n  text-decoration: none;\n  cursor: pointer;\n  transition: color 150ms ease-out;\n}\n\n.farm-default-error__docs-icon {\n  width: 14px;\n  height: 14px;\n  flex: 0 0 auto;\n  stroke: currentColor;\n  stroke-width: 1.25;\n  stroke-linecap: round;\n  stroke-linejoin: round;\n}\n\n.farm-default-error__sr-only {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  padding: 0;\n  margin: -1px;\n  overflow: hidden;\n  clip: rect(0, 0, 0, 0);\n  white-space: nowrap;\n  border: 0;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  .farm-default-error__action:hover {\n    border-color: var(--farm-error-fg);\n    background: var(--farm-error-source-line);\n  }\n\n  .farm-default-error__action--primary:hover {\n    border-color: var(--farm-error-muted);\n    background: var(--farm-error-muted);\n  }\n\n  .farm-default-error__copy:hover {\n    border-color: var(--farm-error-line-strong);\n    color: var(--farm-error-fg);\n    background: var(--farm-error-source-line);\n  }\n\n  .farm-default-error__footer-action:hover {\n    color: var(--farm-error-fg);\n  }\n}\n\n.farm-default-error__copy:active,\n.farm-default-error__action:active {\n  transform: translateY(1px);\n}\n\n.farm-default-error__copy:focus-visible,\n.farm-default-error__action:focus-visible,\n.farm-default-error__footer-action:focus-visible {\n  outline: 2px solid var(--farm-error-fg);\n  outline-offset: 3px;\n}\n\n@media (max-width: 620px) {\n  .farm-default-error__frame {\n    padding: 22px 18px 26px;\n  }\n\n  .farm-default-error__content {\n    padding: 56px 0 68px;\n  }\n\n  .farm-default-error > .farm-default-error__content {\n    padding: 48px 18px;\n  }\n\n  .farm-default-error__title {\n    font-size: clamp(34px, 11vw, 44px);\n  }\n\n  .farm-default-error__message {\n    margin-top: 15px;\n  }\n\n  .farm-default-error__actions {\n    display: grid;\n    grid-template-columns: 1fr;\n  }\n\n  .farm-default-error__action {\n    width: 100%;\n  }\n\n  .farm-default-error__row {\n    grid-template-columns: 1fr;\n    gap: 2px;\n    padding: 11px 0;\n  }\n\n  .farm-default-error__value {\n    padding: 0;\n  }\n\n  .farm-default-error__details-header {\n    align-items: flex-start;\n    flex-direction: column;\n  }\n\n  .farm-default-error__copy {\n    width: 100%;\n  }\n\n  .farm-default-error__source-line {\n    grid-template-columns: 54px minmax(0, 1fr);\n  }\n}\n\n@media (prefers-color-scheme: light) {\n  .farm-default-error {\n    --farm-error-bg: #f7f7f5;\n    --farm-error-panel: #ffffff;\n    --farm-error-fg: #141414;\n    --farm-error-muted: #666666;\n    --farm-error-subtle: #8a8a8a;\n    --farm-error-line: rgba(0, 0, 0, 0.1);\n    --farm-error-line-strong: rgba(0, 0, 0, 0.19);\n    --farm-error-button-bg: #141414;\n    --farm-error-button-fg: #ffffff;\n    --farm-error-source-line: rgba(0, 0, 0, 0.045);\n    --farm-error-source-marker: #141414;\n    color-scheme: light;\n  }\n}\n\n.dark .farm-default-error,\n[data-theme=\"dark\"] .farm-default-error,\n[data-color-scheme=\"dark\"] .farm-default-error {\n  --farm-error-bg: #080808;\n  --farm-error-panel: #0d0d0d;\n  --farm-error-fg: #f3f3f3;\n  --farm-error-muted: #9a9a9a;\n  --farm-error-subtle: #6f6f6f;\n  --farm-error-line: rgba(255, 255, 255, 0.1);\n  --farm-error-line-strong: rgba(255, 255, 255, 0.2);\n  --farm-error-button-bg: #f1f1f1;\n  --farm-error-button-fg: #0a0a0a;\n  --farm-error-source-line: rgba(255, 255, 255, 0.055);\n  --farm-error-source-marker: #f3f3f3;\n  color-scheme: dark;\n}\n\n.light .farm-default-error,\n[data-theme=\"light\"] .farm-default-error,\n[data-color-scheme=\"light\"] .farm-default-error {\n  --farm-error-bg: #f7f7f5;\n  --farm-error-panel: #ffffff;\n  --farm-error-fg: #141414;\n  --farm-error-muted: #666666;\n  --farm-error-subtle: #8a8a8a;\n  --farm-error-line: rgba(0, 0, 0, 0.1);\n  --farm-error-line-strong: rgba(0, 0, 0, 0.19);\n  --farm-error-button-bg: #141414;\n  --farm-error-button-fg: #ffffff;\n  --farm-error-source-line: rgba(0, 0, 0, 0.045);\n  --farm-error-source-marker: #141414;\n  color-scheme: light;\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .farm-default-error__copy,\n  .farm-default-error__action,\n  .farm-default-error__footer-action {\n    transition: none;\n  }\n\n  .farm-default-error__copy:active,\n  .farm-default-error__action:active {\n    transform: none;\n  }\n}\n`;\n","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://farm.js.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 { resolveFarmThemeConfig } from \"./config\";\nimport type {\n  FarmThemeConfig,\n  FarmThemePreference,\n  FarmThemeRuntime,\n  ResolvedFarmThemeConfig,\n} from \"./types\";\n\nconst THEME_SCRIPT_ID = \"farm-theme-script\";\nconst THEME_STYLE_ID = \"farm-theme-style\";\n\ndeclare global {\n  interface Window {\n    __FARM_THEME__?: FarmThemeRuntime;\n  }\n}\n\nexport interface FarmThemeDocumentParts {\n  attributes: string;\n  head: string;\n}\n\nexport function createFarmThemeDocumentParts(\n  input: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n  serverTheme?: FarmThemePreference,\n): FarmThemeDocumentParts {\n  const config = resolveFarmThemeConfig(input, basePath);\n  if (!config.enabled) return { attributes: \"\", head: \"\" };\n\n  const hydrationTheme = serverTheme ?? config.default;\n  const initialTheme = hydrationTheme === \"system\" ? \"light\" : hydrationTheme;\n  const script = createFarmThemeBootstrapScript(config, hydrationTheme);\n\n  return {\n    attributes: ` data-theme=\"${initialTheme}\"`,\n    head: `<style id=\"${THEME_STYLE_ID}\">:root[data-theme=\"light\"]{color-scheme:light}:root[data-theme=\"dark\"]{color-scheme:dark}</style><script id=\"${THEME_SCRIPT_ID}\">${script}</script>`,\n  };\n}\n\nexport function createFarmThemeBootstrapScript(\n  config: ResolvedFarmThemeConfig,\n  serverTheme: FarmThemePreference = config.default,\n): string {\n  return `(function(config,serverTheme){\nvar isTheme=function(value){return value===\"light\"||value===\"dark\"||value===\"system\";};\nvar decode=function(value){try{return decodeURIComponent(value);}catch(_error){return value;}};\nvar readCookie=function(){var entries=document.cookie.split(\";\");for(var index=0;index<entries.length;index++){var entry=entries[index];var separator=entry.indexOf(\"=\");if(separator<0)continue;if(decode(entry.slice(0,separator).trim())===config.storageKey)return decode(entry.slice(separator+1).trim());}};\nvar media=window.matchMedia(\"(prefers-color-scheme: dark)\");\nvar resolveTheme=function(theme){return theme===\"system\"?(media.matches?\"dark\":\"light\"):theme;};\nvar storedTheme=readCookie();\nvar preference=isTheme(storedTheme)?storedTheme:config.default;\nvar serverSnapshot={theme:serverTheme,resolvedTheme:serverTheme===\"system\"?undefined:serverTheme,mounted:false};\nvar apply=function(){var resolvedTheme=resolveTheme(preference);document.documentElement.dataset.theme=resolvedTheme;var snapshot={theme:preference,resolvedTheme:resolvedTheme,mounted:true};if(window.__FARM_THEME__)window.__FARM_THEME__.snapshot=snapshot;return snapshot;};\nvar emit=function(){var snapshot=apply();window.dispatchEvent(new CustomEvent(\"farm:themechange\",{detail:snapshot}));};\nvar persist=function(theme){var secure=window.location.protocol===\"https:\"?\"; Secure\":\"\";document.cookie=encodeURIComponent(config.storageKey)+\"=\"+encodeURIComponent(theme)+\"; Path=\"+config.cookiePath+\"; Max-Age=31536000; SameSite=Lax\"+secure;try{localStorage.setItem(config.storageKey,theme);}catch(_error){}};\nvar setTheme=function(theme){if(!isTheme(theme))throw new TypeError(\"Unknown FARMJS theme: \"+String(theme));preference=theme;persist(theme);emit();};\nvar initialSnapshot={theme:preference,resolvedTheme:resolveTheme(preference),mounted:true};\nwindow.__FARM_THEME__={config:config,serverSnapshot:serverSnapshot,snapshot:initialSnapshot,setTheme:setTheme};\ndocument.documentElement.dataset.theme=initialSnapshot.resolvedTheme;\nvar handleSystemChange=function(){if(preference===\"system\")emit();};\nif(typeof media.addEventListener===\"function\")media.addEventListener(\"change\",handleSystemChange);else if(typeof media.addListener===\"function\")media.addListener(handleSystemChange);\nwindow.addEventListener(\"storage\",function(event){if(event.key!==config.storageKey||!isTheme(event.newValue))return;preference=event.newValue;persist(preference);emit();});\n})(${serializeInlineValue(config)},${serializeInlineValue(serverTheme)});`;\n}\n\nexport function applyFarmThemeDocument(\n  html: string,\n  input: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n  serverTheme?: FarmThemePreference,\n): string {\n  const parts = createFarmThemeDocumentParts(input, basePath, serverTheme);\n  if (!parts.head) return html;\n\n  let output = html.replace(/<html([^>]*)>/i, (_match, attributes: string) => {\n    const nextAttributes = attributes.replace(/\\sdata-theme=(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/i, \"\");\n    return `<html${nextAttributes}${parts.attributes}>`;\n  });\n\n  if (!output.includes(`id=\"${THEME_SCRIPT_ID}\"`)) {\n    output = output.replace(/<head([^>]*)>/i, `<head$1>${parts.head}`);\n  }\n\n  return output;\n}\n\nfunction serializeInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n","import type { FarmThemeSnapshot } from \"./types\";\n\nconst FALLBACK_SERVER_SNAPSHOT: FarmThemeSnapshot = Object.freeze({\n  theme: \"system\",\n  resolvedTheme: undefined,\n  mounted: false,\n});\n\nconst FARM_THEME_SERVER_SNAPSHOT_RESOLVER = Symbol.for(\"farm.js.theme.server-snapshot-resolver\");\n\ntype FarmThemeBridgeGlobal = typeof globalThis & {\n  [FARM_THEME_SERVER_SNAPSHOT_RESOLVER]?: () => FarmThemeSnapshot;\n};\n\nexport function _setFarmThemeServerSnapshotResolver(resolver: () => FarmThemeSnapshot): void {\n  (globalThis as FarmThemeBridgeGlobal)[FARM_THEME_SERVER_SNAPSHOT_RESOLVER] = resolver;\n}\n\nexport function getFarmThemeServerSnapshot(): FarmThemeSnapshot {\n  return (\n    (globalThis as FarmThemeBridgeGlobal)[FARM_THEME_SERVER_SNAPSHOT_RESOLVER]?.() ??\n    FALLBACK_SERVER_SNAPSHOT\n  );\n}\n","import { getCurrentRequestOrNull } from \"../server/request\";\nimport { _setFarmThemeServerSnapshotResolver } from \"./bridge\";\nimport { resolveFarmThemeConfig } from \"./config\";\nimport type {\n  FarmThemeConfig,\n  FarmThemePreference,\n  FarmThemeSnapshot,\n  ResolvedFarmThemeConfig,\n} from \"./types\";\n\nlet defaultThemeConfig = resolveFarmThemeConfig(undefined);\n\nexport function _setDefaultFarmThemeConfig(\n  config: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n): void {\n  defaultThemeConfig = resolveFarmThemeConfig(config, basePath);\n}\n\n// The theme preference is cosmetic, so a missing request context must never\n// crash a render: without a request to read the cookie from, the configured\n// default applies. Runtimes with partial AsyncLocalStorage support (for\n// example StackBlitz WebContainers) can lose the store mid-render, and a\n// thrown error here would also take down the error page itself.\nexport function getTheme(request: Request | null = getCurrentRequestOrNull()): FarmThemePreference {\n  if (!request) return defaultThemeConfig.default;\n  return readFarmThemePreference(request, defaultThemeConfig);\n}\n\nexport function getThemeSnapshot(\n  request: Request | null = getCurrentRequestOrNull(),\n): FarmThemeSnapshot {\n  const theme = request\n    ? readFarmThemePreference(request, defaultThemeConfig)\n    : defaultThemeConfig.default;\n  return {\n    theme,\n    resolvedTheme: theme === \"system\" ? undefined : theme,\n    mounted: false,\n  };\n}\n\nexport function readFarmThemePreference(\n  request: Request,\n  config: ResolvedFarmThemeConfig,\n): FarmThemePreference {\n  if (!config.enabled) return config.default;\n  const stored = readCookie(request.headers.get(\"cookie\"), config.storageKey);\n  return isFarmThemePreference(stored) ? stored : config.default;\n}\n\nfunction readCookie(cookieHeader: string | null, name: string): string | undefined {\n  if (!cookieHeader) return undefined;\n  for (const entry of cookieHeader.split(\";\")) {\n    const separator = entry.indexOf(\"=\");\n    if (separator < 0) continue;\n    const key = decodeCookieValue(entry.slice(0, separator).trim());\n    if (key !== name) continue;\n    return decodeCookieValue(entry.slice(separator + 1).trim());\n  }\n  return undefined;\n}\n\nfunction decodeCookieValue(value: string): string {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return value;\n  }\n}\n\nfunction isFarmThemePreference(value: unknown): value is FarmThemePreference {\n  return value === \"light\" || value === \"dark\" || value === \"system\";\n}\n\n_setFarmThemeServerSnapshotResolver(() => {\n  try {\n    return getThemeSnapshot();\n  } catch {\n    const theme = defaultThemeConfig.default;\n    return {\n      theme,\n      resolvedTheme: theme === \"system\" ? undefined : theme,\n      mounted: false,\n    };\n  }\n});\n","{\n  \"name\": \"@farm.js/core\",\n  \"version\": \"0.1.0-beta.102\",\n  \"description\": \"Core Farm.js framework for modern integrated apps\",\n  \"keywords\": [\n    \"@farm.js/core\",\n    \"framework\",\n    \"react\",\n    \"rsc\",\n    \"server-components\",\n    \"ssr\",\n    \"vite\"\n  ],\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/farming-labs/farm.js\",\n    \"directory\": \"packages/farm\"\n  },\n  \"files\": [\n    \"dist\",\n    \"types\"\n  ],\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.mjs\",\n  \"types\": \"./dist/index.d.ts\",\n  \"typesVersions\": {\n    \"*\": {\n      \"middleware\": [\n        \"./types/middleware.d.ts\",\n        \"./dist/middleware.d.ts\"\n      ],\n      \"version\": [\n        \"./dist/version.d.ts\"\n      ],\n      \"router\": [\n        \"./dist/router.d.ts\"\n      ],\n      \"routes\": [\n        \"./dist/routes.d.ts\"\n      ],\n      \"storage\": [\n        \"./dist/storage.d.ts\"\n      ],\n      \"integrations\": [\n        \"./dist/integrations.d.ts\"\n      ],\n      \"schema\": [\n        \"./dist/schema.d.ts\"\n      ],\n      \"cache\": [\n        \"./dist/cache.d.ts\"\n      ],\n      \"deferred\": [\n        \"./dist/deferred.d.ts\"\n      ],\n      \"after\": [\n        \"./dist/after.d.ts\"\n      ],\n      \"navigation\": [\n        \"./dist/navigation.d.ts\"\n      ],\n      \"headers\": [\n        \"./dist/headers.d.ts\"\n      ],\n      \"theme\": [\n        \"./dist/theme/index.d.ts\"\n      ],\n      \"theme/client\": [\n        \"./dist/theme/client.d.ts\"\n      ],\n      \"theme/runtime\": [\n        \"./dist/theme/runtime.d.ts\"\n      ],\n      \"theme/server\": [\n        \"./dist/theme/server.d.ts\"\n      ],\n      \"docs\": [\n        \"./dist/docs.d.ts\"\n      ],\n      \"markdown\": [\n        \"./dist/markdown.d.ts\"\n      ],\n      \"app-markdown\": [\n        \"./dist/app-markdown.d.ts\"\n      ],\n      \"observability\": [\n        \"./dist/observability.d.ts\"\n      ],\n      \"instrumentation\": [\n        \"./dist/instrumentation.d.ts\"\n      ],\n      \"workflows\": [\n        \"./dist/workflows.d.ts\"\n      ],\n      \"cron\": [\n        \"./dist/cron.d.ts\"\n      ],\n      \"server-fn\": [\n        \"./dist/server-fn.d.ts\"\n      ],\n      \"server-fn/client\": [\n        \"./dist/server-fn-client.d.ts\"\n      ],\n      \"server-query\": [\n        \"./dist/server-query.d.ts\"\n      ],\n      \"server-query/client\": [\n        \"./dist/server-query-client.d.ts\"\n      ],\n      \"server-action-security\": [\n        \"./dist/server-action-security.d.ts\"\n      ],\n      \"deployment\": [\n        \"./dist/deployment.d.ts\"\n      ],\n      \"env\": [\n        \"./dist/env.d.ts\"\n      ],\n      \"env-types\": [\n        \"./dist/env-types.d.ts\"\n      ],\n      \"environment\": [\n        \"./dist/environment.d.ts\"\n      ],\n      \"environment/vite\": [\n        \"./dist/environment/vite.d.ts\"\n      ],\n      \"font\": [\n        \"./dist/font.d.ts\"\n      ],\n      \"testing\": [\n        \"./dist/testing.d.ts\"\n      ],\n      \"agent-runtime\": [\n        \"./dist/agent-runtime.d.ts\"\n      ],\n      \"css\": [\n        \"./types/css.d.ts\"\n      ],\n      \"image\": [\n        \"./types/image.d.ts\",\n        \"./dist/image.d.ts\"\n      ],\n      \"image/server\": [\n        \"./dist/image/server.d.ts\"\n      ],\n      \"image/sharp\": [\n        \"./dist/image/sharp.d.ts\"\n      ],\n      \"i18n\": [\n        \"./dist/i18n/index.d.ts\"\n      ],\n      \"i18n/server\": [\n        \"./dist/i18n/server.d.ts\"\n      ],\n      \"i18n/client\": [\n        \"./dist/i18n/client.d.ts\"\n      ],\n      \"internal/production-runtime\": [\n        \"./dist/internal/production-runtime.d.ts\"\n      ],\n      \"internal/product-telemetry-runtime\": [\n        \"./dist/internal/product-telemetry-runtime.d.ts\"\n      ],\n      \"internal/metadata-image-runtime\": [\n        \"./dist/internal/metadata-image-runtime.d.ts\"\n      ],\n      \"internal/client-runtime\": [\n        \"./dist/internal/client-runtime.d.ts\"\n      ],\n      \"internal/isolated-boundary\": [\n        \"./dist/internal/isolated-boundary.d.ts\"\n      ],\n      \"internal/build-runtime\": [\n        \"./dist/internal/build-runtime.d.ts\"\n      ],\n      \"internal/config-runtime\": [\n        \"./dist/internal/config-runtime.d.ts\"\n      ],\n      \"internal/production-node-env\": [\n        \"./dist/internal/production-node-env.d.ts\"\n      ],\n      \"config\": [\n        \"./dist/config.d.ts\"\n      ],\n      \"renderer\": [\n        \"./dist/renderer.d.ts\"\n      ],\n      \"renderer-client\": [\n        \"./dist/renderer-client.d.ts\"\n      ],\n      \"api\": [\n        \"./types/api.d.ts\",\n        \"./dist/api.d.ts\"\n      ],\n      \"api/client\": [\n        \"./dist/api/client.d.ts\"\n      ],\n      \"api/route-manager\": [\n        \"./dist/api/route-manager.d.ts\"\n      ],\n      \"api/runtime\": [\n        \"./dist/api/runtime.d.ts\"\n      ],\n      \"request\": [\n        \"./dist/request.d.ts\"\n      ],\n      \"client\": [\n        \"./types/client.d.ts\",\n        \"./dist/client.d.ts\"\n      ],\n      \"client/lifecycle\": [\n        \"./dist/client/lifecycle.d.ts\"\n      ],\n      \"server\": [\n        \"./dist/server.d.ts\"\n      ],\n      \"vite\": [\n        \"./dist/vite.d.ts\"\n      ],\n      \"plugin\": [\n        \"./dist/plugin.d.ts\"\n      ],\n      \"query\": [\n        \"./dist/query/index.d.ts\"\n      ],\n      \"*\": [\n        \"./dist/*.d.ts\"\n      ]\n    }\n  },\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.mjs\",\n      \"require\": \"./dist/index.cjs\",\n      \"default\": \"./dist/index.mjs\"\n    },\n    \"./version\": {\n      \"types\": \"./dist/version.d.ts\",\n      \"import\": \"./dist/version.mjs\",\n      \"require\": \"./dist/version.cjs\"\n    },\n    \"./config\": {\n      \"types\": \"./dist/config.d.ts\",\n      \"import\": \"./dist/config.mjs\",\n      \"require\": \"./dist/config.cjs\"\n    },\n    \"./renderer\": {\n      \"types\": \"./dist/renderer.d.ts\",\n      \"import\": \"./dist/renderer.mjs\",\n      \"require\": \"./dist/renderer.cjs\"\n    },\n    \"./renderer-client\": {\n      \"types\": \"./dist/renderer-client.d.ts\",\n      \"import\": \"./dist/renderer-client.mjs\",\n      \"require\": \"./dist/renderer-client.cjs\"\n    },\n    \"./renderer/react/server\": {\n      \"types\": \"./dist/renderer/react/server.d.ts\",\n      \"import\": \"./dist/renderer/react/server.mjs\",\n      \"require\": \"./dist/renderer/react/server.cjs\"\n    },\n    \"./renderer/react/client\": {\n      \"types\": \"./dist/renderer/react/client.d.ts\",\n      \"import\": \"./dist/renderer/react/client.mjs\",\n      \"require\": \"./dist/renderer/react/client.cjs\"\n    },\n    \"./renderer/react/vite\": {\n      \"types\": \"./dist/renderer/react/vite.d.ts\",\n      \"import\": \"./dist/renderer/react/vite.mjs\",\n      \"require\": \"./dist/renderer/react/vite.cjs\"\n    },\n    \"./server\": {\n      \"types\": \"./dist/server.d.ts\",\n      \"import\": \"./dist/server.mjs\",\n      \"require\": \"./dist/server.cjs\"\n    },\n    \"./client\": {\n      \"types\": \"./types/client.d.ts\",\n      \"import\": \"./dist/client.mjs\",\n      \"require\": \"./dist/client.cjs\"\n    },\n    \"./client/lifecycle\": {\n      \"types\": \"./dist/client/lifecycle.d.ts\",\n      \"import\": \"./dist/client/lifecycle.mjs\",\n      \"require\": \"./dist/client/lifecycle.cjs\"\n    },\n    \"./storage\": {\n      \"types\": \"./dist/storage.d.ts\",\n      \"import\": \"./dist/storage.mjs\",\n      \"require\": \"./dist/storage.cjs\"\n    },\n    \"./integrations\": {\n      \"types\": \"./dist/integrations.d.ts\",\n      \"import\": \"./dist/integrations.mjs\",\n      \"require\": \"./dist/integrations.cjs\"\n    },\n    \"./schema\": {\n      \"types\": \"./dist/schema.d.ts\",\n      \"import\": \"./dist/schema.mjs\",\n      \"require\": \"./dist/schema.cjs\"\n    },\n    \"./cache\": {\n      \"types\": \"./dist/cache.d.ts\",\n      \"import\": \"./dist/cache.mjs\",\n      \"require\": \"./dist/cache.cjs\"\n    },\n    \"./deferred\": {\n      \"types\": \"./dist/deferred.d.ts\",\n      \"import\": \"./dist/deferred.mjs\",\n      \"require\": \"./dist/deferred.cjs\"\n    },\n    \"./after\": {\n      \"types\": \"./dist/after.d.ts\",\n      \"import\": \"./dist/after.mjs\",\n      \"require\": \"./dist/after.cjs\"\n    },\n    \"./navigation\": {\n      \"types\": \"./dist/navigation.d.ts\",\n      \"import\": \"./dist/navigation.mjs\",\n      \"require\": \"./dist/navigation.cjs\"\n    },\n    \"./headers\": {\n      \"types\": \"./dist/headers.d.ts\",\n      \"import\": \"./dist/headers.mjs\",\n      \"require\": \"./dist/headers.cjs\"\n    },\n    \"./theme\": {\n      \"types\": \"./dist/theme/index.d.ts\",\n      \"import\": \"./dist/theme/index.mjs\",\n      \"require\": \"./dist/theme/index.cjs\"\n    },\n    \"./theme/client\": {\n      \"types\": \"./dist/theme/client.d.ts\",\n      \"import\": \"./dist/theme/client.mjs\",\n      \"require\": \"./dist/theme/client.cjs\"\n    },\n    \"./theme/runtime\": {\n      \"types\": \"./dist/theme/runtime.d.ts\",\n      \"import\": \"./dist/theme/runtime.mjs\",\n      \"require\": \"./dist/theme/runtime.cjs\"\n    },\n    \"./theme/server\": {\n      \"types\": \"./dist/theme/server.d.ts\",\n      \"import\": \"./dist/theme/server.mjs\",\n      \"require\": \"./dist/theme/server.cjs\"\n    },\n    \"./docs\": {\n      \"types\": \"./dist/docs.d.ts\",\n      \"import\": \"./dist/docs.mjs\",\n      \"require\": \"./dist/docs.cjs\"\n    },\n    \"./markdown\": {\n      \"types\": \"./dist/markdown.d.ts\",\n      \"import\": \"./dist/markdown.mjs\",\n      \"require\": \"./dist/markdown.cjs\"\n    },\n    \"./app-markdown\": {\n      \"types\": \"./dist/app-markdown.d.ts\",\n      \"import\": \"./dist/app-markdown.mjs\",\n      \"require\": \"./dist/app-markdown.cjs\"\n    },\n    \"./observability\": {\n      \"types\": \"./dist/observability.d.ts\",\n      \"import\": \"./dist/observability.mjs\",\n      \"require\": \"./dist/observability.cjs\"\n    },\n    \"./instrumentation\": {\n      \"types\": \"./dist/instrumentation.d.ts\",\n      \"import\": \"./dist/instrumentation.mjs\",\n      \"require\": \"./dist/instrumentation.cjs\"\n    },\n    \"./workflows\": {\n      \"types\": \"./dist/workflows.d.ts\",\n      \"import\": \"./dist/workflows.mjs\",\n      \"require\": \"./dist/workflows.cjs\"\n    },\n    \"./cron\": {\n      \"types\": \"./dist/cron.d.ts\",\n      \"import\": \"./dist/cron.mjs\",\n      \"require\": \"./dist/cron.cjs\"\n    },\n    \"./server-fn\": {\n      \"types\": \"./dist/server-fn.d.ts\",\n      \"import\": \"./dist/server-fn.mjs\",\n      \"require\": \"./dist/server-fn.cjs\"\n    },\n    \"./server-fn/client\": {\n      \"types\": \"./dist/server-fn-client.d.ts\",\n      \"import\": \"./dist/server-fn-client.mjs\",\n      \"require\": \"./dist/server-fn-client.cjs\"\n    },\n    \"./server-query\": {\n      \"types\": \"./dist/server-query.d.ts\",\n      \"import\": \"./dist/server-query.mjs\",\n      \"require\": \"./dist/server-query.cjs\"\n    },\n    \"./server-query/client\": {\n      \"types\": \"./dist/server-query-client.d.ts\",\n      \"import\": \"./dist/server-query-client.mjs\",\n      \"require\": \"./dist/server-query-client.cjs\"\n    },\n    \"./server-action-security\": {\n      \"types\": \"./dist/server-action-security.d.ts\",\n      \"import\": \"./dist/server-action-security.mjs\",\n      \"require\": \"./dist/server-action-security.cjs\"\n    },\n    \"./deployment\": {\n      \"types\": \"./dist/deployment.d.ts\",\n      \"import\": \"./dist/deployment.mjs\",\n      \"require\": \"./dist/deployment.cjs\"\n    },\n    \"./env\": {\n      \"types\": \"./dist/env.d.ts\",\n      \"import\": \"./dist/env.mjs\",\n      \"require\": \"./dist/env.cjs\"\n    },\n    \"./env-types\": {\n      \"types\": \"./dist/env-types.d.ts\",\n      \"import\": \"./dist/env-types.mjs\",\n      \"require\": \"./dist/env-types.cjs\"\n    },\n    \"./environment\": {\n      \"types\": \"./dist/environment.d.ts\",\n      \"import\": \"./dist/environment.mjs\",\n      \"require\": \"./dist/environment.cjs\"\n    },\n    \"./environment/vite\": {\n      \"types\": \"./dist/environment/vite.d.ts\",\n      \"import\": \"./dist/environment/vite.mjs\",\n      \"require\": \"./dist/environment/vite.cjs\"\n    },\n    \"./font\": {\n      \"types\": \"./dist/font.d.ts\",\n      \"import\": \"./dist/font.mjs\",\n      \"require\": \"./dist/font.cjs\"\n    },\n    \"./vite\": {\n      \"types\": \"./dist/vite.d.ts\",\n      \"import\": \"./dist/vite.mjs\",\n      \"require\": \"./dist/vite.cjs\"\n    },\n    \"./plugin\": {\n      \"types\": \"./dist/plugin.d.ts\",\n      \"import\": \"./dist/plugin.mjs\",\n      \"require\": \"./dist/plugin.cjs\"\n    },\n    \"./plugin/server\": {\n      \"types\": \"./dist/server-plugins.d.ts\",\n      \"import\": \"./dist/server-plugins.mjs\",\n      \"require\": \"./dist/server-plugins.cjs\"\n    },\n    \"./plugin/client\": {\n      \"types\": \"./dist/client-plugins.d.ts\",\n      \"import\": \"./dist/client-plugins.mjs\",\n      \"require\": \"./dist/client-plugins.cjs\"\n    },\n    \"./query\": {\n      \"types\": \"./dist/query/index.d.ts\",\n      \"import\": \"./dist/query/index.mjs\",\n      \"require\": \"./dist/query/index.cjs\"\n    },\n    \"./query/parsers\": {\n      \"types\": \"./dist/query/parsers.d.ts\",\n      \"import\": \"./dist/query/parsers.mjs\",\n      \"require\": \"./dist/query/parsers.cjs\"\n    },\n    \"./query/client\": {\n      \"types\": \"./dist/query/client.d.ts\",\n      \"import\": \"./dist/query/client.mjs\",\n      \"require\": \"./dist/query/client.cjs\"\n    },\n    \"./query/server\": {\n      \"types\": \"./dist/query/server.d.ts\",\n      \"import\": \"./dist/query/server.mjs\",\n      \"require\": \"./dist/query/server.cjs\"\n    },\n    \"./middleware\": {\n      \"types\": \"./dist/middleware.d.ts\",\n      \"import\": \"./dist/middleware.mjs\",\n      \"require\": \"./dist/middleware.cjs\"\n    },\n    \"./api\": {\n      \"types\": \"./dist/api.d.ts\",\n      \"import\": \"./dist/api.mjs\",\n      \"require\": \"./dist/api.cjs\"\n    },\n    \"./api/client\": {\n      \"types\": \"./dist/api/client.d.ts\",\n      \"import\": \"./dist/api/client.mjs\",\n      \"require\": \"./dist/api/client.cjs\"\n    },\n    \"./api/route-manager\": {\n      \"types\": \"./dist/api/route-manager.d.ts\",\n      \"import\": \"./dist/api/route-manager.mjs\",\n      \"require\": \"./dist/api/route-manager.cjs\"\n    },\n    \"./api/runtime\": {\n      \"types\": \"./dist/api/runtime.d.ts\",\n      \"import\": \"./dist/api/runtime.mjs\",\n      \"require\": \"./dist/api/runtime.cjs\"\n    },\n    \"./request\": {\n      \"types\": \"./dist/request.d.ts\",\n      \"import\": \"./dist/request.mjs\",\n      \"require\": \"./dist/request.cjs\"\n    },\n    \"./router\": {\n      \"types\": \"./dist/router.d.ts\",\n      \"import\": \"./dist/router.mjs\",\n      \"require\": \"./dist/router.cjs\"\n    },\n    \"./routes\": {\n      \"types\": \"./dist/routes.d.ts\",\n      \"import\": \"./dist/routes.mjs\",\n      \"require\": \"./dist/routes.cjs\"\n    },\n    \"./testing\": {\n      \"types\": \"./dist/testing.d.ts\",\n      \"import\": \"./dist/testing.mjs\",\n      \"require\": \"./dist/testing.cjs\"\n    },\n    \"./agent-runtime\": {\n      \"types\": \"./dist/agent-runtime.d.ts\",\n      \"import\": \"./dist/agent-runtime.mjs\",\n      \"require\": \"./dist/agent-runtime.cjs\"\n    },\n    \"./css\": {\n      \"types\": \"./types/css.d.ts\"\n    },\n    \"./image\": {\n      \"types\": \"./types/image.d.ts\",\n      \"import\": \"./dist/image.mjs\",\n      \"require\": \"./dist/image.cjs\"\n    },\n    \"./image/server\": {\n      \"types\": \"./dist/image/server.d.ts\",\n      \"import\": \"./dist/image/server.mjs\",\n      \"require\": \"./dist/image/server.cjs\"\n    },\n    \"./image/sharp\": {\n      \"types\": \"./dist/image/sharp.d.ts\",\n      \"import\": \"./dist/image/sharp.mjs\",\n      \"require\": \"./dist/image/sharp.cjs\"\n    },\n    \"./i18n\": {\n      \"types\": \"./dist/i18n/index.d.ts\",\n      \"import\": \"./dist/i18n/index.mjs\",\n      \"require\": \"./dist/i18n/index.cjs\"\n    },\n    \"./i18n/server\": {\n      \"types\": \"./dist/i18n/server.d.ts\",\n      \"import\": \"./dist/i18n/server.mjs\",\n      \"require\": \"./dist/i18n/server.cjs\"\n    },\n    \"./i18n/client\": {\n      \"types\": \"./dist/i18n/client.d.ts\",\n      \"import\": \"./dist/i18n/client.mjs\",\n      \"require\": \"./dist/i18n/client.cjs\"\n    },\n    \"./internal/production-runtime\": {\n      \"types\": \"./dist/internal/production-runtime.d.ts\",\n      \"import\": \"./dist/internal/production-runtime.mjs\",\n      \"require\": \"./dist/internal/production-runtime.cjs\"\n    },\n    \"./internal/product-telemetry-runtime\": {\n      \"types\": \"./dist/internal/product-telemetry-runtime.d.ts\",\n      \"import\": \"./dist/internal/product-telemetry-runtime.mjs\",\n      \"require\": \"./dist/internal/product-telemetry-runtime.cjs\"\n    },\n    \"./internal/metadata-image-runtime\": {\n      \"types\": \"./dist/internal/metadata-image-runtime.d.ts\",\n      \"import\": \"./dist/internal/metadata-image-runtime.mjs\",\n      \"require\": \"./dist/internal/metadata-image-runtime.cjs\"\n    },\n    \"./internal/client-runtime\": {\n      \"types\": \"./dist/internal/client-runtime.d.ts\",\n      \"import\": \"./dist/internal/client-runtime.mjs\",\n      \"require\": \"./dist/internal/client-runtime.cjs\"\n    },\n    \"./internal/isolated-boundary\": {\n      \"types\": \"./dist/internal/isolated-boundary.d.ts\",\n      \"import\": \"./dist/internal/isolated-boundary.mjs\",\n      \"require\": \"./dist/internal/isolated-boundary.cjs\"\n    },\n    \"./internal/build-runtime\": {\n      \"types\": \"./dist/internal/build-runtime.d.ts\",\n      \"import\": \"./dist/internal/build-runtime.mjs\",\n      \"require\": \"./dist/internal/build-runtime.cjs\"\n    },\n    \"./internal/config-runtime\": {\n      \"types\": \"./dist/internal/config-runtime.d.ts\",\n      \"import\": \"./dist/internal/config-runtime.mjs\",\n      \"require\": \"./dist/internal/config-runtime.cjs\"\n    },\n    \"./internal/production-node-env\": {\n      \"types\": \"./dist/internal/production-node-env.d.ts\",\n      \"import\": \"./dist/internal/production-node-env.mjs\",\n      \"require\": \"./dist/internal/production-node-env.cjs\"\n    }\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"scripts\": {\n    \"build\": \"tsup\",\n    \"build:runtime\": \"tsup --config tsup.runtime.config.ts\",\n    \"dev\": \"tsup --watch\",\n    \"test\": \"vitest run\",\n    \"test:coverage\": \"vitest --coverage\",\n    \"lint\": \"biome lint .\",\n    \"lint:fix\": \"biome lint --write .\",\n    \"format\": \"biome format --write .\",\n    \"type-check\": \"tsc --noEmit\",\n    \"clean\": \"rm -rf dist\"\n  },\n  \"dependencies\": {\n    \"@farming-labs/docs\": \"^0.2.44\",\n    \"@farming-labs/orm\": \"0.0.62\",\n    \"@farming-labs/orm-runtime\": \"0.0.62\",\n    \"@formatjs/icu-messageformat-parser\": \"3.5.15\",\n    \"@jridgewell/trace-mapping\": \"0.3.31\",\n    \"@mdx-js/mdx\": \"^3.1.1\",\n    \"@opentelemetry/api\": \"1.9.1\",\n    \"@scalar/api-reference\": \"^1.38.1\",\n    \"@scalar/openapi-parser\": \"^0.22.3\",\n    \"@tailwindcss/vite\": \"4.1.18\",\n    \"@vercel/og\": \"0.11.1\",\n    \"@vitejs/plugin-react\": \"^4.2.1\",\n    \"better-call\": \"^1.0.19\",\n    \"db0\": \"^0.3.4\",\n    \"es-module-lexer\": \"2.0.0\",\n    \"esbuild\": \"^0.28.0\",\n    \"fast-glob\": \"^3.3.2\",\n    \"h3\": \"2.0.1-rc.5\",\n    \"image-size\": \"^2.0.2\",\n    \"intl-messageformat\": \"11.2.12\",\n    \"marked\": \"^12.0.2\",\n    \"nitro\": \"3.0.1-alpha.0\",\n    \"pg\": \"^8.20.0\",\n    \"picocolors\": \"^1.0.0\",\n    \"remark-gfm\": \"^4.0.1\",\n    \"sirv\": \"^2.0.4\",\n    \"sugar-high\": \"^0.9.5\",\n    \"supports-color\": \"^10.2.2\",\n    \"tailwindcss\": \"4.1.18\",\n    \"unstorage\": \"^2.0.0-alpha.3\",\n    \"vite\": \"^5.0.10\",\n    \"zod\": \"^4.1.12\"\n  },\n  \"devDependencies\": {\n    \"@clerk/react\": \"^6.1.0\",\n    \"@farm.js/otel\": \"workspace:*\",\n    \"@farm.js/renderer-tests\": \"workspace:*\",\n    \"@opentelemetry/sdk-node\": \"0.221.0\",\n    \"@opentelemetry/sdk-trace-base\": \"2.10.0\",\n    \"@types/react\": \"^18.2.45\",\n    \"@types/react-dom\": \"^18.2.18\",\n    \"@vitest/coverage-v8\": \"^3.2.7\",\n    \"jsdom\": \"^25.0.0\",\n    \"react\": \"19.2.8\",\n    \"react-dom\": \"19.2.8\",\n    \"tsup\": \"^8.3.5\",\n    \"typescript\": \"^5.3.3\",\n    \"vitest\": \"^3.2.7\"\n  },\n  \"peerDependencies\": {\n    \"react\": \"^18.2.0 || ^19.0.0\",\n    \"react-dom\": \"^18.2.0 || ^19.0.0\"\n  },\n  \"peerDependenciesMeta\": {\n    \"react\": {\n      \"optional\": true\n    },\n    \"react-dom\": {\n      \"optional\": true\n    }\n  },\n  \"optionalDependencies\": {\n    \"rolldown\": \"1.2.0\",\n    \"sharp\": \"^0.34.5\",\n    \"vite-rolldown\": \"npm:vite@8.1.5\"\n  },\n  \"engines\": {\n    \"node\": \">=22.13.0\"\n  }\n}\n","import { version } from \"../package.json\";\n\nexport const FARM_VERSION = version;\n","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","import type { ConfigEnv, Plugin, UserConfig, ViteDevServer, HmrContext, Connect } from \"vite\";\nimport type { FarmConfig, FarmRequest } from \"./types\";\nimport { FarmApp } from \"./app\";\nimport { logger, toPosixPath, toViteModuleId } from \"./utils\";\nimport { defaultGlobalCSS } from \"./default-styles\";\nimport {\n  FARM_NODE_RESPONSE_END_PENDING,\n  type FarmPlugin,\n  type FarmPluginRuntimeSession,\n  type PluginManager,\n} from \"./plugin\";\nimport { generateFarmClientPluginEntryCode } from \"./client-plugin-build\";\nimport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n  type ClientCachePersistenceEntryCode,\n} from \"./client-cache-persistence-build\";\n\nexport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n} from \"./client-cache-persistence-build\";\nexport type { ClientCachePersistenceEntryCode } from \"./client-cache-persistence-build\";\nimport { APIRouteManager } from \"./api/route-manager\";\nimport { DEFAULT_FARM_API_BASE_PATH } from \"./api/config\";\nimport { resolveFarmAPIServerBasePath } from \"./api/server-path\";\nimport { isFarmAPIPathname } from \"./api/runtime\";\nimport type { OpenAPIManager } from \"./openapi/manager\";\nimport { MiddlewareManager } from \"./middleware/manager\";\nimport { generateFarmTypeArtifacts, type GenerateFarmTypeArtifactsOptions } from \"./type-artifacts\";\nimport {\n  isProgrammaticRoutesFileName,\n  parseProgrammaticRouteModuleId,\n  scanProgrammaticPagePaths,\n} from \"./routes-shared\";\nimport type { FarmDocsAPIHandler } from \"./docs\";\nimport { createMarkdownMirrorResponse, resolveMarkdownMirrorTarget } from \"./markdown\";\nimport {\n  FARM_MARKDOWN_CONTENT_TYPE,\n  createFarmMarkdownErrorBody,\n  createFarmMarkdownSourceResponse,\n  farmRequestWantsMarkdown,\n  isFarmMarkdownPageFile,\n  normalizeFarmMarkdownRoutePath,\n} from \"./app-markdown\";\nimport { applyWebResponseHeaders, sendWebResponse } from \"./server/response\";\nimport {\n  getClientModuleMetadata,\n  getIslandStrategyExport,\n  hasUseClientDirective,\n  isIsolatableClientBoundarySource,\n  resolveFarmIsolatedClientHydrationMode,\n  stripUseClientDirective,\n} from \"./utils/client-component\";\nimport {\n  dispatchIntegrationRequest,\n  getFarmIntegrationPluginOwner,\n  getIntegrationDocumentNavigationMatchers,\n  getIntegrationProviders,\n  matchIntegrationRoute,\n} from \"./integrations\";\nimport type { FarmDiscoveredWorkflow } from \"./workflows\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"./route-context\";\nimport {\n  FARM_DEVTOOLS_LAUNCH_PARAM,\n  FARM_DEVTOOLS_PATH,\n  resolveFarmDevtoolsConfig,\n} from \"./devtools-config\";\nimport { generateFarmDevIndicatorsClientRuntime } from \"./dev-indicators\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { FarmUserConfig } from \"./config\";\nimport { getFarmAppDirectories, getFarmLayerAliases, getFarmSourceRoots } from \"./layers\";\nimport { farmEnvironmentFunctionsPlugin } from \"./environment-vite\";\nimport { FARM_VERSION } from \"./version\";\nimport { createDeferredDataResponse } from \"./deferred\";\nimport { _withAfterNodeMiddleware } from \"./after\";\nimport { _runWithAPIRequestRuntime } from \"./api/server-context\";\nimport type { APIRequestRuntime } from \"./api/server-client-bridge\";\nimport { shouldBypassFarmRouterForDottedPath } from \"./dev-static\";\nimport { findClientServerFnViolation, formatServerFnBoundaryError } from \"./server-query-boundary\";\nimport {\n  analyzeClientBoundary,\n  formatClientBoundaryWarning,\n  shouldInspectClientBoundary,\n} from \"./client-boundary-env\";\nimport {\n  createFarmDeploymentMismatchResponse,\n  FARM_DEPLOYMENT_ID_HEADER,\n  getFarmDeploymentMismatch,\n} from \"./deployment\";\nimport { getPublicFarmImageConfig, resolveFarmImageConfig } from \"./image-config\";\nimport { farmImageImportsPlugin } from \"./image-vite\";\nimport { farmFontImportsPlugin } from \"./font-vite\";\nimport { resolveFarmLayoutFonts } from \"./font\";\nimport { createFarmImageHandler, type FarmImageHandler } from \"./image-server\";\nimport { isFarmI18nCatalogFile, resolveFarmI18nMessagePath } from \"./i18n/config\";\nimport { getFarmI18nClientSnapshot } from \"./i18n/server\";\nimport { localizeFarmPathname } from \"./i18n/routing\";\nimport type { FarmI18nClientSnapshot } from \"./i18n/types\";\nimport {\n  createFarmClientOptimizeDepsConfig,\n  createFarmClientOptimizeDepsEntries,\n  createFarmSourceAlias,\n} from \"./server/vite-config\";\nimport { resolveFarmDocsFontAssets, toFarmDocsPublicFontAssets } from \"./docs/fonts\";\nimport {\n  createFarmNodeRequestAbortSignal,\n  createFarmRequestBodyErrorResponse,\n  readNodeRequestBody,\n  resolveFarmServerConfig,\n} from \"./server-http\";\nimport { createCliColors } from \"./cli-colors\";\nimport { createFarmThemeCssPlugin } from \"./theme/vite\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { emitFarmEvent, runWithFarmRequestSpan } from \"./observability\";\nimport {\n  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 { mergeMetadata } from \"./metadata\";\nimport { FARM_CONFIG_REWRITES_PLUGIN_NAME } from \"./plugins/rewrites\";\nimport { resolveFarmRequestURL } from \"./server/request\";\nimport { reportOpenAPIDevGenerationResult } from \"./openapi/dev-status\";\n\ninterface FarmVitePluginOptions extends FarmConfig {\n  openapi?: FarmUserConfig[\"openapi\"];\n  images?: FarmUserConfig[\"images\"];\n  publicDir?: FarmUserConfig[\"publicDir\"];\n  /** @internal Modules selected by the compiled isolated-hydration ownership plan. */\n  isolatedClientBoundaryModules?: ReadonlySet<string>;\n}\n\ntype TypeArtifactSelection = Pick<\n  GenerateFarmTypeArtifactsOptions,\n  \"routes\" | \"api\" | \"env\" | \"images\" | \"i18n\"\n>;\n\nconst ALL_TYPE_ARTIFACTS: TypeArtifactSelection = {\n  routes: true,\n  api: true,\n  env: true,\n  images: false,\n  i18n: true,\n};\n\nconst createEmptyTypeArtifactSelection = (): TypeArtifactSelection => ({\n  routes: false,\n  api: false,\n  env: false,\n  images: false,\n  i18n: false,\n});\n\nconst FARM_I18N_CLIENT_BRIDGE_ID = \"\\0farm-i18n-client-bridge\";\n\n// The @farm.js/devtools plugin serves this path itself; reaching the built-in\n// dashboard render means the app is still on the deprecated core UI.\nlet warnedDeprecatedDevtoolsDashboard = false;\nconst EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME = `\nfunction isFarmDocsSearchPage() {\n  return false;\n}\n\nasync function mountFarmDocsSearch() {\n  return false;\n}\n`;\n\nfunction loadFarmDocsDevRuntime() {\n  return import(\"./docs\");\n}\n\nfunction loadFarmDocsSearchDevRuntime() {\n  return import(\"./docs/search-client\");\n}\n\nfunction loadFarmOpenAPIDevRuntime() {\n  return import(\"./openapi/manager\");\n}\n\nfunction loadFarmWorkflowsDevRuntime() {\n  return import(\"./workflows\");\n}\n\nfunction loadFarmDevtoolsSnapshotRuntime() {\n  return import(\"./devtools\");\n}\n\nfunction loadFarmDevtoolsUIRuntime() {\n  return import(\"./devtools-ui\");\n}\n\nfunction loadFarmDevtoolsClientRuntime() {\n  return import(\"./devtools-client\");\n}\n\nexport function farmI18nClientBridgePlugin(): Plugin {\n  return {\n    name: \"farm:i18n-client-bridge\",\n    enforce: \"pre\",\n    resolveId(id, _importer, options) {\n      if (id === \"@farm.js/core/i18n/server\" && !options?.ssr) {\n        return FARM_I18N_CLIENT_BRIDGE_ID;\n      }\n      return null;\n    },\n    load(id) {\n      if (id !== FARM_I18N_CLIENT_BRIDGE_ID) return null;\n      return 'export { createTranslator, format, getLocale, getLocaleSource, t } from \"@farm.js/core/i18n/client\";';\n    },\n  };\n}\n\nconst FARM_CONFIG_FILENAMES = new Set([\n  \"farm.config.ts\",\n  \"farm.config.tsx\",\n  \"farm.config.mts\",\n  \"farm.config.cts\",\n  \"farm.config.js\",\n  \"farm.config.jsx\",\n  \"farm.config.mjs\",\n  \"farm.config.cjs\",\n  \"config.ts\",\n  \"config.tsx\",\n  \"config.mts\",\n  \"config.cts\",\n  \"config.js\",\n  \"config.jsx\",\n  \"config.mjs\",\n  \"config.cjs\",\n]);\n\nfunction serializeFarmInlineValue(value: unknown): string {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\u003c\")\n    .replace(/\\u2028/g, \"\\\\u2028\")\n    .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeFarmHtmlAttribute(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nfunction renderFarmI18nStaticHead(\n  requestPath: string,\n  snapshot: FarmI18nClientSnapshot | undefined,\n): string {\n  if (!snapshot) return \"\";\n  const runtime = `<script>window.__FARM_I18N__ = ${serializeFarmInlineValue(snapshot)};</script>`;\n  if (snapshot.routing === \"none\") return runtime;\n\n  const links = snapshot.locales.map(\n    (locale) =>\n      `<link rel=\"alternate\" hreflang=\"${escapeFarmHtmlAttribute(locale)}\" href=\"${escapeFarmHtmlAttribute(\n        localizeFarmPathname(requestPath, locale, snapshot),\n      )}\">`,\n  );\n  links.push(\n    `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeFarmHtmlAttribute(\n      localizeFarmPathname(requestPath, snapshot.defaultLocale, snapshot),\n    )}\">`,\n  );\n  return `${links.join(\"\")}${runtime}`;\n}\n\nfunction getPublicEnvDefine(config: FarmVitePluginOptions): Record<string, unknown> {\n  const publicEnv = (config as any).env?.public;\n  if (!isResolvedEnvScope(publicEnv)) {\n    return {};\n  }\n\n  return publicEnv;\n}\n\nfunction createRequestFromNodeRequest(\n  req: {\n    method?: string;\n    headers: Record<string, string | string[] | undefined>;\n  },\n  url: URL,\n  signal?: AbortSignal,\n): Request {\n  const headers = new Headers();\n  for (const [key, value] of Object.entries(req.headers)) {\n    if (Array.isArray(value)) {\n      for (const item of value) headers.append(key, item);\n    } else if (value !== undefined) {\n      headers.set(key, value);\n    }\n  }\n\n  return new Request(url.toString(), {\n    method: req.method || \"GET\",\n    headers,\n    signal,\n  });\n}\n\nexport { createFarmNodeRequestAbortSignal } from \"./server-http\";\n\n/** Exported for tests: the request boundary all Farm dev middlewares share. */\nexport function withFarmRequestTracing(\n  handler: Parameters<typeof _withAfterNodeMiddleware>[0],\n  apiRuntime?: APIRequestRuntime,\n  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. On Solid and Svelte `render()`\n * tears the tree down and rebuilds it, so a one character change in any client\n * component would wipe the page's state. Those renderers ship their own HMR\n * integration (solid-refresh, svelte's hot API) which preserves component\n * state, and appending an `import.meta.hot.accept` here would swallow the\n * update before theirs could run.\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      const apiServerBasePath = resolveFarmAPIServerBasePath(farmConfig.api);\n      const serverConfig = resolveFarmServerConfig(farmConfig.server);\n      let imageHandler: FarmImageHandler | null = null;\n      if (farmConfig.images.provider !== \"none\") {\n        const { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } =\n          await import(\"./image-sharp\");\n        imageHandler = createFarmImageHandler(farmConfig.images, {\n          transform: createSharpImageTransformer(),\n          fetchRemote: createNodeImageFetcher(farmConfig.images),\n          validateRemoteUrl: createNodeImageUrlValidator(farmConfig.images),\n          onError(error) {\n            logger.error(\n              `Image optimization failed: ${error instanceof Error ? error.message : String(error)}`,\n            );\n          },\n        });\n      }\n      const sourceRoots = getFarmSourceRoots(farmConfig);\n      server.watcher.add(sourceRoots.map((source) => path.join(source.root, source.srcDir)));\n      if (farmConfig.i18n.enabled) {\n        server.watcher.add(\n          farmConfig.i18n.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        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 farmApp\n              .getServerRenderer()\n              .runWithRequestContext(middlewareRequest, () => middlewareManager!.execute(req, res));\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();\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();\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          if (farmDocsHandler) {\n            const docsRequest = new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            });\n            const docsResponse = await farmDocsHandler(docsRequest.clone());\n            if (docsResponse) {\n              if (await runAppMiddlewareForContentRoute()) return;\n              await sendWebResponse(\n                res,\n                await wrapFarmDocsResponseWithLayouts(docsRequest, docsResponse),\n              );\n              return;\n            }\n          }\n\n          const markdownSourceResponse = await createFarmMarkdownSourceResponse({\n            request: new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            }),\n            config: farmApp.getConfig().mdx,\n            resolveSource: async (pathname) => {\n              const match = farmApp.getRouteManager().matchRoute(pathname);\n              const sourcePath =\n                match.route?.markdownSourcePath ||\n                (match.route && isFarmMarkdownPageFile(match.route.modulePath)\n                  ? match.route.modulePath\n                  : null);\n              if (!sourcePath) {\n                return null;\n              }\n              return {\n                source: await fs.promises.readFile(sourcePath, \"utf8\"),\n                filePath: sourcePath,\n              };\n            },\n          });\n          if (markdownSourceResponse) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            await sendWebResponse(res, markdownSourceResponse);\n            return;\n          }\n\n          const markdownResponse = await createMarkdownMirrorResponse({\n            request: new Request(fullUrl, {\n              method: requestMethod,\n              headers: docsHeaders,\n            }),\n            config: farmApp.getConfig().md,\n            routeExists: (pathname) =>\n              Boolean(farmApp.getRouteManager().matchRoute(pathname).route),\n            renderPage: async (request) => fetch(request),\n          });\n          if (markdownResponse) {\n            if (await runAppMiddlewareForContentRoute()) return;\n            await sendWebResponse(res, markdownResponse);\n            return;\n          }\n\n          // No Markdown source or mirror matched. When the client explicitly\n          // asked for Markdown (a `.md` URL or `Accept: text/markdown`) and no\n          // page route exists, return a Markdown 404 body rather than letting a\n          // `.md` request fall through to a static-asset 404 or an HTML shell.\n          if (farmRequestWantsMarkdown(requestPathname, req.headers.accept)) {\n            const markdownRoute = farmApp\n              .getRouteManager()\n              .matchRoute(normalizeFarmMarkdownRoutePath(requestPathname));\n            if (!markdownRoute.route) {\n              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 =\n              markdownPageTarget.pathname === \"/\"\n                ? \"/index.md\"\n                : `${markdownPageTarget.pathname}.md`;\n            const alternateLink = `<${alternatePath}>; rel=\"alternate\"; type=\"text/markdown\"`;\n            const currentLink = res.getHeader(\"Link\");\n            res.setHeader(\n              \"Link\",\n              currentLink ? `${String(currentLink)}, ${alternateLink}` : alternateLink,\n            );\n          }\n\n          if (\n            workflowHandler &&\n            (requestPathname === workflowConfig.route ||\n              requestPathname.startsWith(`${workflowConfig.route}/`))\n          ) {\n            let workflowBody: Buffer | undefined;\n            try {\n              if (requestMethod !== \"GET\" && requestMethod !== \"HEAD\") {\n                workflowBody = await readNodeRequestBody(\n                  req as any,\n                  currentServerConfig.bodySizeLimit,\n                );\n              }\n            } catch (error) {\n              const response = createFarmRequestBodyErrorResponse(error);\n              if (!response) throw error;\n              await sendWebResponse(res, response);\n              return;\n            }\n            const workflowResponse = await workflowHandler(\n              new Request(fullUrl, {\n                method: requestMethod,\n                headers: docsHeaders,\n                body: toRequestBody(workflowBody),\n              }),\n            );\n            if (workflowResponse) {\n              await sendWebResponse(res, workflowResponse);\n              return;\n            }\n          }\n\n          const configuredIntegrations = currentConfig.integrations;\n\n          const tryConfiguredIntegrationRoute = async () => {\n            const matchedRoute = matchIntegrationRoute(configuredIntegrations, {\n              pathname: requestPathname,\n              method: requestMethod,\n            });\n\n            if (!matchedRoute) {\n              return false;\n            }\n\n            const startTime = Date.now();\n\n            try {\n              if (pm) {\n                await pm.runHookParallelFiltered(\n                  \"beforeRequest\",\n                  (plugin) => {\n                    const owner = getFarmIntegrationPluginOwner(plugin);\n                    return (\n                      plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME &&\n                      (owner?.source !== \"lifecycle\" || owner.key !== matchedRoute.key)\n                    );\n                  },\n                  req,\n                  res,\n                );\n              }\n\n              if (res.writableEnded) {\n                const duration = Date.now() - startTime;\n                logResponse(requestMethod, requestUrl, res.statusCode || 200, duration, \"API\");\n                return true;\n              }\n\n              const headers = new Headers();\n              for (const [key, value] of Object.entries(req.headers)) {\n                if (value) {\n                  headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                }\n              }\n\n              let body: Buffer | undefined;\n              if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n              }\n\n              const integrationRequest = new Request(fullUrl, {\n                method: req.method,\n                headers,\n                body: toRequestBody(body),\n              });\n\n              const dispatchIntegration = async (request: Request) => {\n                const result = await dispatchIntegrationRequest(\n                  {\n                    integration: matchedRoute.integration,\n                    config: currentConfig,\n                    isDev: true,\n                    isProd: false,\n                  },\n                  request,\n                );\n                if (!result) {\n                  throw new Error(`Matched integration route did not return a response`);\n                }\n                return result;\n              };\n              const response = pm\n                ? await pm.runRuntimeRequest(integrationRequest, dispatchIntegration, {\n                    kind: \"integration\",\n                    route: {\n                      pathname: requestPathname,\n                      pattern: matchedRoute.route.path,\n                    },\n                  })\n                : await dispatchIntegration(integrationRequest);\n\n              if (!response) {\n                return false;\n              }\n\n              const duration = Date.now() - startTime;\n              logResponse(requestMethod, requestUrl, response.status, duration, \"API\");\n\n              await sendWebResponse(res, response);\n              return true;\n            } catch (error) {\n              const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n              if (bodyErrorResponse) {\n                await sendWebResponse(res, bodyErrorResponse);\n                return true;\n              }\n              const duration = Date.now() - startTime;\n              logResponse(requestMethod, requestUrl, 500, duration, \"API\");\n              await emitPluginError(\"integration-handler\", error, {\n                pathname: requestPathname,\n                routePath: requestUrl,\n                method: requestMethod,\n                integration: matchedRoute.key,\n              });\n              logger.error(`Integration route error: ${error}`);\n              if (!res.writableEnded) {\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n              }\n              return true;\n            }\n          };\n\n          if (await tryConfiguredIntegrationRoute()) {\n            return;\n          }\n\n          const redirectMatch = farmApp\n            .getRouteManager()\n            .matchRedirect(requestPathname, parsedRequestUrl.search);\n          if (redirectMatch) {\n            res.statusCode = redirectMatch.statusCode;\n            res.setHeader(\"Location\", redirectMatch.destination);\n            res.end(`Redirecting to ${redirectMatch.destination}`);\n            return;\n          }\n\n          // Handle API routes first\n          const matchedApiRoute = apiRouteManager.matchRoute(requestPathname);\n          const hasMatchedApiRoute = Boolean(matchedApiRoute);\n          if (hasMatchedApiRoute || isFarmAPIPathname(requestPathname, apiServerBasePath)) {\n            const startTime = Date.now();\n            const method = req.method || \"GET\";\n            const urlPath = req.url || \"/\";\n            const pathname = 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                const request = new Request(url, {\n                  method: req.method,\n                  headers,\n                  body: toRequestBody(body),\n                });\n\n                const apiLifecyclePayload = {\n                  pathname: new URL(url).pathname,\n                  method,\n                  routePath: apiRoutePattern,\n                };\n                const invokeAPIHandler = async (runtimeRequest: Request) => {\n                  const handledRequest: Request = pm\n                    ? await pm.runHookSerial(\n                        \"beforeApiHandler\",\n                        runtimeRequest,\n                        apiLifecyclePayload,\n                      )\n                    : runtimeRequest;\n\n                  const response = await apiHandler(handledRequest);\n                  return pm\n                    ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n                    : response;\n                };\n                const handledResponse: Response = pm\n                  ? await pm.runRuntimeRequest(request, invokeAPIHandler, {\n                      kind: \"api\",\n                      route: {\n                        pathname: apiLifecyclePayload.pathname,\n                        pattern: apiLifecyclePayload.routePath,\n                      },\n                    })\n                  : await invokeAPIHandler(request);\n\n                const duration = Date.now() - startTime;\n                emitFarmEvent({\n                  type: \"api.request.complete\",\n                  pathname,\n                  route: apiRoutePattern,\n                  method,\n                  status: handledResponse.status,\n                  durationMs: duration,\n                });\n                logResponse(method, urlPath, handledResponse.status, duration, \"API\");\n\n                // Send response\n                await sendWebResponse(res, handledResponse);\n                return;\n              } catch (error) {\n                const duration = Date.now() - startTime;\n                emitFarmEvent({\n                  type: \"api.error\",\n                  pathname,\n                  route: apiRoutePattern,\n                  method,\n                  durationMs: duration,\n                  error,\n                });\n                const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n                if (bodyErrorResponse) {\n                  logResponse(method, urlPath, bodyErrorResponse.status, duration, \"API\");\n                  await sendWebResponse(res, bodyErrorResponse);\n                  return;\n                }\n                await emitPluginError(\"api-handler\", error, {\n                  urlPath,\n                  method,\n                });\n                logger.error(`API route error: ${error}`);\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n                return;\n              }\n            }\n\n            if (farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname)) {\n              try {\n                const url = `http://${req.headers.host || \"localhost:3000\"}${req.url}`;\n                const headers = new Headers();\n                for (const [key, value] of Object.entries(req.headers)) {\n                  if (value) {\n                    headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n                  }\n                }\n\n                let body: Buffer | undefined;\n                if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n                  body = await readNodeRequestBody(req as any, currentServerConfig.bodySizeLimit);\n                }\n\n                const request = new Request(url, {\n                  method: req.method,\n                  headers,\n                  body: toRequestBody(body),\n                });\n\n                const apiLifecyclePayload = {\n                  pathname,\n                  method,\n                  routePath: urlPath,\n                };\n                const invokeDocsAPIHandler = async (runtimeRequest: Request) => {\n                  const handledRequest: Request = pm\n                    ? await pm.runHookSerial(\n                        \"beforeApiHandler\",\n                        runtimeRequest,\n                        apiLifecyclePayload,\n                      )\n                    : runtimeRequest;\n                  const response = await farmDocsAPIHandler(handledRequest);\n                  if (!response) {\n                    return new Response(null, { status: 404 });\n                  }\n                  return pm\n                    ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n                    : response;\n                };\n                const docsResponse = pm\n                  ? await pm.runRuntimeRequest(request, invokeDocsAPIHandler, {\n                      kind: \"docs\",\n                      route: {\n                        pathname,\n                        pattern: apiLifecyclePayload.routePath,\n                      },\n                    })\n                  : await invokeDocsAPIHandler(request);\n                if (docsResponse) {\n                  const duration = Date.now() - startTime;\n                  logResponse(method, urlPath, docsResponse.status, duration, \"API\");\n                  await sendWebResponse(res, docsResponse);\n                  return;\n                }\n              } catch (error) {\n                const bodyErrorResponse = createFarmRequestBodyErrorResponse(error);\n                if (bodyErrorResponse) {\n                  await sendWebResponse(res, bodyErrorResponse);\n                  return;\n                }\n                await emitPluginError(\"docs-api-handler\", error, {\n                  urlPath,\n                  method,\n                });\n                logger.error(`Docs API route error: ${error}`);\n                res.statusCode = 500;\n                res.setHeader(\"Content-Type\", \"application/json\");\n                res.end(JSON.stringify({ error: \"Internal server error\" }));\n                return;\n              }\n            }\n\n            const duration = Date.now() - startTime;\n            logResponse(method, urlPath, 404, duration, \"API\");\n            res.statusCode = 404;\n            res.setHeader(\"Content-Type\", \"application/json\");\n            res.end(JSON.stringify({ error: \"API route not found\", pathname }));\n            return;\n          }\n\n          // Skip internal Vite requests\n          if (req.url?.startsWith(\"/@\") || req.url?.startsWith(\"/node_modules\")) {\n            return next();\n          }\n\n          // Dotted paths are usually static assets (modules, images, source\n          // maps), but dots are also valid inside route segments and in\n          // application metadata routes (/manifest.webmanifest, /sitemap.xml,\n          // /robots.txt, metadata images). Only skip the router when the\n          // request maps to a real file on disk or nothing in the app matches\n          // the pathname.\n          if (\n            shouldBypassFarmRouterForDottedPath(requestPathname, farmApp?.getRouteManager(), [\n              server.config.publicDir,\n              server.config.root,\n            ])\n          ) {\n            return next();\n          }\n\n          // Handle SPA page-data requests for client-side navigation\n          if (req.url?.startsWith(\"/__farm/page-data\")) {\n            const urlObj = parsedRequestUrl;\n            const targetPath = urlObj.searchParams.get(\"path\") || \"/\";\n\n            try {\n              const request = createRequestFromNodeRequest(\n                req,\n                urlObj,\n                createFarmNodeRequestAbortSignal(req, res),\n              );\n              const deploymentMismatch = getFarmDeploymentMismatch(\n                request,\n                farmConfig.deploymentId,\n              );\n              if (deploymentMismatch) {\n                await sendWebResponse(\n                  res,\n                  createFarmDeploymentMismatchResponse(deploymentMismatch),\n                );\n                return;\n              }\n\n              const targetRequestUrl = new URL(targetPath, request.url);\n              const targetRequest = new Request(targetRequestUrl, {\n                method: \"GET\",\n                headers: request.headers,\n                signal: request.signal,\n              });\n              await farmApp.getServerRenderer().runWithRequestContext(targetRequest, async () => {\n                const routeManager = farmApp.getRouteManager();\n                if (pm) {\n                  await pm.runHookParallel(\"beforeRouteMatch\", {\n                    pathname: targetPath,\n                    method: req.method || \"GET\",\n                  });\n                }\n                const interceptFromHeader =\n                  request.headers.get(\"x-farm-intercept-from\") || undefined;\n                const match = routeManager.matchRoute(targetRequestUrl.pathname, {\n                  interceptFrom: interceptFromHeader,\n                });\n                if (pm) {\n                  await pm.runHookParallel(\"afterRouteMatch\", {\n                    pathname: targetPath,\n                    matched: !!match?.route,\n                    routePattern: match?.route?.pattern || null,\n                    params: match?.params || {},\n                    layoutPatterns: (match?.layouts || []).map((l) => l.pattern),\n                  });\n                }\n\n                if (!match) {\n                  res.statusCode = 404;\n                  res.setHeader(\"Content-Type\", \"application/json\");\n                  res.end(JSON.stringify({ error: \"Route not found\" }));\n                  return;\n                }\n\n                const { route, params, layouts, slots } = match;\n\n                // Check if route was found\n                if (!route) {\n                  res.statusCode = 404;\n                  res.setHeader(\"Content-Type\", \"application/json\");\n                  res.end(JSON.stringify({ error: \"Route not found\" }));\n                  return;\n                }\n\n                // Load route module to get metadata\n                const routeModule = await routeManager.loadRouteModule(route.modulePath);\n                const loadingBoundary = routeManager.getMatchingLoading(targetRequestUrl.pathname);\n                const loadingModule = loadingBoundary\n                  ? await routeManager.loadRouteModule(loadingBoundary.modulePath)\n                  : null;\n\n                const navigationManifest = routeManager.generateClientManifest(server.config.root);\n                const moduleMetadata =\n                  navigationManifest.routes.find((entry) => entry.pattern === route.pattern) ??\n                  getClientModuleMetadata(route.modulePath, server.config.root);\n                const isClientComponent = moduleMetadata.isClientComponent;\n                const shouldHydrate = moduleMetadata.shouldHydrate;\n\n                // Collect metadata from layouts and page\n                let mergedMetadata: Record<string, any> = {};\n                const layoutModules = await Promise.all(\n                  layouts.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n                );\n                const layoutHydrationMetadata = layouts.map(\n                  (layout) =>\n                    navigationManifest.layouts.find((entry) => entry.pattern === layout.pattern) ??\n                    getClientModuleMetadata(layout.modulePath, server.config.root),\n                );\n                const shouldHydrateLayout = layoutHydrationMetadata.some(\n                  (metadata) => metadata.shouldHydrate,\n                );\n                const hydrationStrategies = [\n                  ...(shouldHydrate && moduleMetadata.islandStrategy\n                    ? [moduleMetadata.islandStrategy]\n                    : []),\n                  ...layoutHydrationMetadata.flatMap((metadata) =>\n                    metadata.shouldHydrate && metadata.islandStrategy\n                      ? [metadata.islandStrategy]\n                      : [],\n                  ),\n                ];\n                const hydrationIslandStrategy = hydrationStrategies.every(\n                  (strategy) => strategy === hydrationStrategies[0],\n                )\n                  ? (hydrationStrategies[0] ?? \"load\")\n                  : \"load\";\n\n                // 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\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 pathname = 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          if (pm && hasBeforeRouteMatchHook) {\n            await pm.runHookParallel(\"beforeRouteMatch\", {\n              pathname,\n              method,\n            });\n          }\n          const routeMatch = routeManager.matchRoute(pathname);\n          if (pm && hasAfterRouteMatchHook) {\n            await pm.runHookParallel(\"afterRouteMatch\", {\n              pathname,\n              matched: !!routeMatch?.route,\n              routePattern: routeMatch?.route?.pattern || null,\n              params: routeMatch?.params || {},\n              layoutPatterns: (routeMatch?.layouts || []).map((l) => l.pattern),\n            });\n          }\n          const renderPayload = {\n            pathname,\n            method,\n            routePattern: routeMatch?.route?.pattern || null,\n            params: routeMatch?.params || {},\n          };\n          let runtimeSession: FarmPluginRuntimeSession | undefined;\n          if (pm && hasRuntimeRequestHooks) {\n            try {\n              runtimeSession = await pm.beginRuntimeRequest(\n                createRequestFromNodeRequest(req, new URL(fullUrl)),\n                {\n                  kind: \"page\",\n                  route: {\n                    pathname,\n                    pattern: renderPayload.routePattern,\n                    params: renderPayload.params,\n                  },\n                },\n              );\n              pm.copyRequestContext(runtimeSession.request, req);\n              applyWebRequestToNodeRequest(runtimeSession.request, req);\n\n              if (runtimeSession.response) {\n                const response = await pm.endRuntimeRequest(\n                  runtimeSession,\n                  runtimeSession.response,\n                );\n                await sendWebResponse(res, response);\n                return;\n              }\n            } catch (error) {\n              await emitPluginError(\"runtime-before\", error, { pathname });\n              res.statusCode = 500;\n              res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n              res.end(\"Internal Server Error\");\n              return;\n            }\n          }\n\n          // Runtime response transforms need the complete byte stream, including\n          // responses completed by middleware or beforeRequest hooks.\n          const shouldInterceptResponse = Boolean(\n            pm &&\n            (hasAfterResponseHook ||\n              hasHTMLTransformHook ||\n              (runtimeSession && hasRuntimeAfterHook)),\n          );\n          const responseInterceptor =\n            pm && shouldInterceptResponse\n              ? interceptFarmDevPageResponse({\n                  req,\n                  res,\n                  pm,\n                  runtimeSession,\n                  hasRuntimeAfterHook,\n                  hasAfterResponseHook,\n                  hasHTMLTransformHook,\n                  renderPayload,\n                  method,\n                  urlPath,\n                  pathname,\n                  startTime,\n                  logResponse,\n                  emitError: (error) => emitPluginError(\"response-end\", error, { pathname }),\n                })\n              : undefined;\n\n          try {\n            if (middlewareManager?.hasMiddleware()) {\n              const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));\n              const handled = await farmApp\n                .getServerRenderer()\n                .runWithRequestContext(middlewareRequest, () =>\n                  middlewareManager!.execute(req, res),\n                );\n              if (handled) {\n                if (!responseInterceptor?.isEnded()) {\n                  const duration = Date.now() - startTime;\n                  logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n                }\n                return; // Middleware handled the response\n              }\n            }\n\n            // Run beforeRequest hooks\n            if (pm && hasBeforeRequestHook) {\n              const currentPathname = new URL(\n                req.url || \"/\",\n                `http://${req.headers.host || \"localhost:3000\"}`,\n              ).pathname;\n              const hasLocalPageRoute = Boolean(routeManager.matchRoute(currentPathname)?.route);\n              await pm.runHookParallelFiltered(\n                \"beforeRequest\",\n                (plugin) => !hasLocalPageRoute || plugin.name !== FARM_CONFIG_REWRITES_PLUGIN_NAME,\n                req,\n                res,\n              );\n            }\n\n            if (res.writableEnded || responseInterceptor?.isEnded()) {\n              if (!responseInterceptor?.isEnded()) {\n                const duration = Date.now() - startTime;\n                logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n              }\n              return;\n            }\n\n            // Note: __FARM_PROPS__ is set by the renderer with actual page props (params, searchParams)\n\n            const renderer = farmApp.getServerRenderer();\n            if (pm && hasBeforeRenderHook) {\n              await pm.runHookParallel(\"beforeRender\", renderPayload);\n            }\n            await renderer.renderPage(req as any, res as any);\n            if (!shouldInterceptResponse) {\n              logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, \"PAGE\");\n            }\n          } catch (error) {\n            // Log error response\n            const duration = Date.now() - startTime;\n            logResponse(method, urlPath, 500, duration, \"PAGE\");\n            if (pm && runtimeSession) {\n              await pm.failRuntimeRequest(runtimeSession, error);\n            }\n            await emitPluginError(\"render-page\", error, { pathname });\n            next(error);\n          }\n        }),\n      );\n    },\n\n    async resolveId(id, importer, resolveOptions) {\n      if (typeof fontImports.resolveId === \"function\") {\n        const fontId = await fontImports.resolveId.call(this, id, importer, resolveOptions);\n        if (fontId) return fontId;\n      }\n\n      if (typeof imageImports.resolveId === \"function\") {\n        const imageId = await imageImports.resolveId.call(this, id, importer, resolveOptions);\n        if (imageId) return imageId;\n      }\n\n      if (parseProgrammaticRouteModuleId(id)) {\n        return id;\n      }\n\n      if (isFarmClientVirtualId(id)) {\n        return id;\n      }\n\n      if (id === \"/@farm/server\") {\n        return id;\n      }\n\n      // Virtual manifest module - TanStack Start pattern\n      if (id === \"virtual:farm-manifest\" || id === \"/@farm/manifest\") {\n        return \"/@farm/manifest\";\n      }\n    },\n\n    async load(id) {\n      if (typeof fontImports.load === \"function\") {\n        const fontModule = await fontImports.load.call(this, id);\n        if (fontModule) return fontModule;\n      }\n\n      if (typeof imageImports.load === \"function\") {\n        const imageModule = await imageImports.load.call(this, id);\n        if (imageModule) return imageModule;\n      }\n\n      if (parseProgrammaticRouteModuleId(id)) {\n        const renderer = farmApp?.getConfig().renderer || resolveFarmRenderer(options.renderer);\n        return generateProgrammaticRouteModule(id, server?.config.root || options.root, renderer);\n      }\n\n      if (isFarmClientVirtualId(id)) {\n        const resolvedConfig = farmApp?.getConfig();\n        const renderer = resolvedConfig?.renderer || resolveFarmRenderer(options.renderer);\n        const integrations = resolvedConfig?.integrations || options.integrations;\n        const root = resolvedConfig?.root || server?.config.root || process.cwd();\n        const docs = resolvedConfig?.docs;\n        const adapterOwnsDocsRuntime = Boolean(\n          isReactRenderer(renderer) && docs?.adapter?.server && docs.adapter.react,\n        );\n        const devtools = resolvedConfig?.devtools ?? resolveFarmDevtoolsConfig(false, \"production\");\n        const [docsRuntime, docsSearchRuntime, devtoolsClientRuntime] = await Promise.all([\n          docs?.enabled ? loadFarmDocsDevRuntime() : null,\n          docs?.enabled && !adapterOwnsDocsRuntime ? loadFarmDocsSearchDevRuntime() : null,\n          devtools.enabled ? loadFarmDevtoolsClientRuntime() : null,\n        ]);\n        const docsSearchEnabled = docsSearchRuntime?.isFarmDocsSearchEnabled(docs) ?? false;\n        const generatedDocsSearchRuntime = docsSearchRuntime\n          ? docsSearchRuntime.generateFarmDocsSearchClientRuntime(\n              docsSearchEnabled,\n              docsSearchEnabled\n                ? docsSearchRuntime.resolveFarmDocsSearchClientModule(root)\n                : undefined,\n            )\n          : EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME;\n        const generatedDevtoolsClientRuntime = devtoolsClientRuntime\n          ? devtoolsClientRuntime.generateFarmDevtoolsClientRuntime(devtools)\n          : \"\";\n        const generatedDevIndicatorsClientRuntime = farmApp\n          ? generateFarmDevIndicatorsClientRuntime(farmApp.getConfig().devIndicators)\n          : \"\";\n        const integrationProviders = isReactRenderer(renderer)\n          ? getIntegrationProviders(integrations)\n          : [];\n        const isolatedHydrationMode = resolveFarmIsolatedClientHydrationMode(\n          resolvedConfig?.experimental?.isolatedClientHydration,\n          {\n            serverComponents: resolvedConfig?.experimental?.serverComponents === true,\n            hasUnsupportedIntegrationProvider: integrationProviders\n              .filter((provider) => provider.component || provider.type === \"clerk\")\n              .some((provider) => provider.supportsIsolatedHydration !== true),\n          },\n        );\n\n        return generateClientCode(\n          integrationProviders,\n          [\n            ...getIntegrationDocumentNavigationMatchers(integrations),\n            ...(docsRuntime?.getFarmDocsDocumentNavigationMatchers(docs) ?? []),\n          ],\n          generatedDocsSearchRuntime,\n          `${generatedDevtoolsClientRuntime}\\n${generatedDevIndicatorsClientRuntime}`,\n          resolvedConfig?.plugins || [],\n          root,\n          resolvedConfig?.srcDir || options.srcDir || \"src\",\n          resolvedConfig?.publicRuntimeConfig || options.publicRuntimeConfig,\n          isReactRenderer(renderer) ? docs?.adapter?.react : undefined,\n          renderer,\n          isolatedHydrationMode === \"enabled\",\n          resolvedConfig?.trailingSlash ?? false,\n          resolvedConfig?.basePath ?? \"/\",\n          generateClientCachePersistenceCode(\n            resolveFarmClientCacheAdapterEntry(root, resolvedConfig?.cache),\n          ),\n        );\n      }\n\n      if (id === \"/@farm/server\") {\n        return generateServerCode();\n      }\n\n      // Virtual manifest module - TanStack Start pattern\n      // Manifest is generated at build time and inlined\n      if (id === \"/@farm/manifest\") {\n        const routeManager = farmApp?.getRouteManager();\n        if (!routeManager) {\n          return `\nexport const getManifest = () => ({\n  routes: {},\n  layouts: {},\n  slots: [],\n  clientEntry: \"/@farm/client.js\",\n  sharedAssets: []\n});\n`;\n        }\n\n        const manifest = routeManager.generateClientManifest(server.config.root);\n\n        // Convert to full manifest format\n        const fullManifest = {\n          clientEntry: \"/@farm/client.js\",\n          routes: {} as Record<string, any>,\n          layouts: {} as Record<string, any>,\n          slots: [] as Array<Record<string, any>>,\n          sharedAssets: [\n            {\n              tag: \"link\",\n              attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n            },\n          ],\n        };\n\n        // Convert routes array to object keyed by pattern\n        for (const route of manifest.routes) {\n          fullManifest.routes[route.pattern] = {\n            modulePath: route.modulePath,\n            pattern: route.pattern,\n            segments: route.segments,\n            search: route.search,\n            isClientComponent: route.isClientComponent,\n            shouldHydrate: route.shouldHydrate,\n            islandStrategy: route.islandStrategy,\n            renderPlan: route.renderPlan,\n            preloads: [route.modulePath], // In dev, preload is just the module\n            assets: [],\n          };\n        }\n\n        // Convert layouts array to object keyed by pattern\n        for (const layout of manifest.layouts) {\n          fullManifest.layouts[layout.pattern] = {\n            modulePath: layout.modulePath,\n            pattern: layout.pattern,\n            shouldHydrate: layout.shouldHydrate,\n            islandStrategy: layout.islandStrategy,\n            preloads: [layout.modulePath],\n            assets: [],\n          };\n        }\n\n        for (const slot of manifest.slots) {\n          fullManifest.slots.push({\n            ...slot,\n            preloads: [slot.modulePath],\n            assets: [],\n          });\n        }\n\n        return `\n// Auto-generated manifest for SPA navigation (TanStack Start pattern)\n// This manifest is inlined in the server bundle - no file on disk\n// Client receives this via window.__FARM_MANIFEST__ in HTML\nexport const getManifest = () => (${JSON.stringify(fullManifest, null, 2)});\nexport const manifest = getManifest();\n`;\n      }\n    },\n\n    async transform(code, id, transformOptions) {\n      if (!transformOptions?.ssr) {\n        const currentConfig = (farmApp?.getConfig() ?? options) as FarmVitePluginOptions;\n        if (currentConfig.experimental?.serverActions !== true) {\n          // Without the server-function transform there is no client stub for\n          // server queries: bundling the defining module into the browser\n          // executes the server handler there. Fail with an actionable\n          // boundary error instead of Vite's Node-builtin externalization\n          // failure at runtime.\n          const violation = findClientServerFnViolation(code, id);\n          if (violation) {\n            this.error(formatServerFnBoundaryError(violation, id));\n          }\n        }\n      }\n\n      if (!transformOptions?.ssr && shouldInspectClientBoundary(id, code)) {\n        warnClientBoundaryOnce(this, id, code, farmApp?.getConfig() ?? options);\n      }\n\n      if (typeof imageImports.transform === \"function\") {\n        const imageModule = await imageImports.transform.call(this, code, id, transformOptions);\n        if (imageModule) return imageModule;\n      }\n\n      let transformedCode = code;\n      let transformed = false;\n\n      if (typeof fontImports.transform === \"function\") {\n        const fontResult = await fontImports.transform.call(\n          this,\n          transformedCode,\n          id,\n          transformOptions,\n        );\n        const fontCode = typeof fontResult === \"string\" ? fontResult : fontResult?.code;\n        if (fontCode) {\n          transformedCode = fontCode;\n          transformed = true;\n        }\n      }\n\n      if (transformOptions?.ssr && server) {\n        const rewrittenImports = rewriteEarlySsrRelativeImports({\n          code: transformedCode,\n          id,\n          root: server.config.root,\n          parse: (source) => this.parse(source) as unknown as FarmModuleAstNode,\n        });\n        if (rewrittenImports) {\n          transformedCode = rewrittenImports;\n          transformed = true;\n        }\n      }\n\n      if (hasUseClientDirective(transformedCode)) {\n        const clientBoundarySource = transformedCode;\n        const moduleInfo = this.getModuleInfo(id);\n        if (moduleInfo) {\n          (moduleInfo as any).isClientComponent = true;\n        }\n\n        transformedCode = stripUseClientDirective(transformedCode);\n        transformed = true;\n\n        const currentConfig = (farmApp?.getConfig() ?? options) as FarmVitePluginOptions;\n        const configuredProviders = getIntegrationProviders(currentConfig.integrations).filter(\n          (provider) => provider.component || provider.type === \"clerk\",\n        );\n        const isolatedHydrationEnabled =\n          resolveFarmIsolatedClientHydrationMode(\n            currentConfig.experimental?.isolatedClientHydration,\n            {\n              serverComponents: currentConfig.experimental?.serverComponents === true,\n              hasUnsupportedIntegrationProvider: configuredProviders.some(\n                (provider) => provider.supportsIsolatedHydration !== true,\n              ),\n            },\n          ) === \"enabled\" && isReactRenderer(resolveFarmRenderer(currentConfig.renderer));\n        let isolatedModuleReference: string | null = null;\n        const root = currentConfig.root || server?.config.root || process.cwd();\n        const cleanId = id.split(\"?\", 1)[0];\n        const selectedIsolatedModules =\n          options.isolatedClientBoundaryModules ??\n          farmApp?.getRouteManager().getIsolatedClientBoundaryModules(root);\n        const selectedForIsolatedHydration =\n          selectedIsolatedModules?.has(path.resolve(cleanId)) === true;\n        if (\n          isolatedHydrationEnabled &&\n          selectedForIsolatedHydration &&\n          isIsolatableClientBoundarySource(clientBoundarySource)\n        ) {\n          isolatedModuleReference = toViteModuleId(cleanId, root);\n          const transformedBoundary = transformIsolatedClientBoundaryModule({\n            code: transformedCode,\n            moduleReference: isolatedModuleReference,\n            islandStrategy: getIslandStrategyExport(clientBoundarySource) ?? \"load\",\n            parse: (source) => this.parse(source) as unknown as FarmModuleAstNode,\n          });\n          if (!transformedBoundary) {\n            this.error(\n              `[Farm.js] Could not compile isolated client boundary ${cleanId}. ` +\n                `Use experimental.isolatedClientHydration = \"analyze\" to inspect eligibility ` +\n                `or \"off\" to retain route-wide hydration.`,\n            );\n          }\n          transformedCode = transformedBoundary;\n        }\n\n        // Store client component for later injection\n        if (!farmApp) {\n          return {\n            code: transformedCode,\n            map: null,\n          };\n        }\n\n        const clientComponents = (farmApp as any).__clientComponents__ || new Set();\n        clientComponents.add(id);\n        (farmApp as any).__clientComponents__ = clientComponents;\n\n        // Add HMR support for client components\n        // This ensures React re-renders when the component updates\n        const isolatedHmrUpdate = isolatedModuleReference\n          ? `\n    if (\n      newModule &&\n      newModule.__farm_client_boundary_originals__ &&\n      window.__FARM_ISOLATED_HYDRATION_RUNTIME__\n    ) {\n      window.__FARM_ISOLATED_HYDRATION_RUNTIME__.updateModule(\n        ${JSON.stringify(isolatedModuleReference)},\n        newModule,\n      );\n      return;\n    }`\n          : \"\";\n        // 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      if (\n        currentSrcRoot &&\n        (isolatedHydrationMode === \"enabled\" || isolatedHydrationMode === \"analyze\") &&\n        /\\.[cm]?[jt]sx?$/.test(normalizedFile)\n      ) {\n        const routeManager = farmApp?.getRouteManager();\n        if (routeManager) {\n          const previousPlan = JSON.stringify(\n            routeManager.generateClientManifest(currentFarmConfig.root),\n          );\n          routeManager.invalidateClientManifest();\n          const nextPlan = JSON.stringify(\n            routeManager.generateClientManifest(currentFarmConfig.root),\n          );\n          const planChanged = previousPlan !== nextPlan;\n          const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n          if (manifestModule) server.moduleGraph.invalidateModule(manifestModule);\n          if (planChanged) {\n            for (const mod of modules) server.moduleGraph.invalidateModule(mod);\n            server.ws.send({ type: \"full-reload\", path: \"*\" });\n            return [];\n          }\n        }\n      }\n\n      if (normalizedFile.includes(\"/app/\")) {\n        // Hot reload middleware changes\n        if (normalizedFile.includes(\"middleware.\")) {\n          if (middlewareManager) {\n            await middlewareManager.reload();\n            logger.success(\"✅ Middleware reloaded!\");\n            if (initialPluginManager) {\n              for (const middleware of middlewareManager.getMiddlewares()) {\n                await initialPluginManager.runHookParallel(\"middlewareDiscovered\", {\n                  path: middleware.path,\n                  filePath: middleware.filePath,\n                  handlerCount: middleware.handlers.length,\n                });\n              }\n            }\n          }\n\n          return [];\n        }\n\n        farmApp?.getRouteManager().invalidateClientManifest();\n        const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n        if (manifestModule) {\n          server.moduleGraph.invalidateModule(manifestModule);\n        }\n\n        if (normalizedFile.includes(\"page.\") || normalizedFile.includes(\"layout.\")) {\n          const shortPath = normalizedFile.split(\"/app/\")[1] || normalizedFile;\n          logUpdate(\"PAGE\", `updated ${shortPath}`);\n\n          for (const mod of modules) {\n            server.moduleGraph.invalidateModule(mod);\n          }\n\n          server.ws.send({\n            type: \"full-reload\",\n            path: \"*\",\n          });\n\n          return [];\n        }\n      }\n\n      return modules;\n    },\n  };\n}\n\nfunction isFarmClientVirtualId(id: string): boolean {\n  const pathname = id.split(\"?\", 1)[0];\n  return pathname === \"/@farm/client\" || pathname === \"/@farm/client.js\";\n}\n\nfunction generateProgrammaticRouteModule(\n  moduleId: string,\n  root?: string,\n  renderer: FarmRenderer = REACT_RENDERER,\n): string {\n  const parsed = parseProgrammaticRouteModuleId(moduleId);\n  if (!parsed) {\n    return \"\";\n  }\n\n  const routeFile = toProgrammaticRouteImportSpecifier(parsed.filePath, root);\n\n  if (parsed.kind === \"api\") {\n    return generateProgrammaticApiRouteModule(parsed.routePath, routeFile);\n  }\n\n  return `\nimport {\n  createElement as __farmCreateElement,\n  Suspense as __farmSuspense,\n} from ${JSON.stringify(renderer.server)};\nimport {\n  createLayoutModuleFromProgrammaticLayout as __farmCreateLayoutRouteModule,\n  createRouteModuleFromProgrammaticPage as __farmCreatePageRouteModule,\n} from \"@farm.js/core/routes\";\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n  value &&\n  typeof value === \"object\" &&\n  (\n    value.kind === \"page\" ||\n    value.kind === \"layout\" ||\n    value.kind === \"api\" ||\n    value.kind === \"redirect\"\n  )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n  if (Array.isArray(candidate)) return candidate;\n  if (Array.isArray(candidate?.routes)) return candidate.routes;\n  if (__farmIsRouteDefinition(candidate)) return [candidate];\n  return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n  __farmGetRouteExport(\"default\"),\n  __farmGetRouteExport(\"routes\"),\n  __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n  __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n  if (__farmRoutes.length > 0) break;\n}\n\nif (__farmRoutes.length === 0) {\n  __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (routePath) => {\n  const withSlash = routePath && routePath.startsWith(\"/\") ? routePath : \"/\" + (routePath || \"\");\n  const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n  return withoutTrailing || \"/\";\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n  route &&\n  route.kind === ${JSON.stringify(parsed.kind)} &&\n  __farmNormalizeRoutePath(route.path) === ${JSON.stringify(parsed.routePath)}\n));\n\nif (!__farmRoute) {\n  throw new Error(${JSON.stringify(\n    `Programmatic ${parsed.kind} route \"${parsed.routePath}\" was not found in ${routeFile}.`,\n  )});\n}\n\nconst __farmRouteModule = __farmRoute.kind === \"layout\"\n  ? __farmCreateLayoutRouteModule(__farmRoute)\n  : __farmCreatePageRouteModule(__farmRoute, {\n      createElement: __farmCreateElement,\n      Suspense: __farmSuspense,\n    });\n\nexport const metadata = __farmRouteModule.metadata;\nexport const generateMetadata = __farmRouteModule.generateMetadata;\nconst __farmIsSearchSchema = (value) => value && typeof value.parse === \"function\";\nconst __farmGetSearchSchema = (search) => __farmIsSearchSchema(search) ? search : search?.schema;\nconst __farmGetSearchOptions = (search) => __farmIsSearchSchema(search) ? undefined : search;\nconst __farmSearchSchema = __farmGetSearchSchema(__farmRoute.search);\nconst __farmSearchOptions = __farmGetSearchOptions(__farmRoute.search);\nexport const __farmRouteSchemas = __farmRouteModule.__farmRouteSchemas;\nexport const __farmRouteSearch = __farmRouteModule.__farmRouteSearch;\nexport const __farmRouteData = __farmRouteModule.__farmRouteData;\nexport const __farmRouteGuard = __farmRouteModule.__farmRouteGuard;\nexport const __farmRouteParsesProps = __farmRouteModule.__farmRouteParsesProps;\nexport const __farmRouteComponents = __farmRouteModule.__farmRouteComponents;\nexport const __farmResolveRouteCanonicalPath =\n  __farmRouteModule.__farmResolveRouteCanonicalPath;\nexport const ssg = __farmRouteModule.ssg;\nexport const dynamic = __farmRouteModule.dynamic;\nexport const revalidate = __farmRouteModule.revalidate;\nexport const ppr = __farmRouteModule.ppr;\nexport const getStaticPaths = __farmRouteModule.getStaticPaths;\n\nconst __farmParseSchema = (schema, value, label) => {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    throw new Error(\"Invalid \" + label + \" for route \" + JSON.stringify(__farmRoute.path) + \": \" + (error?.message || String(error)));\n  }\n};\n\nconst __farmMarkRoutePropsResolved = (props) => ({\n  ...props,\n  __farmRoutePropsResolved: true,\n});\n\nconst __farmAddCanonicalPath = (props, canonicalPath) => (\n  canonicalPath ? { ...props, __farmCanonicalPath: canonicalPath } : props\n);\n\nconst __farmStripRoutePropsMarker = (props) => {\n  if (!props || props.__farmRoutePropsResolved !== true) {\n    return props;\n  }\n\n  const {\n    __farmRoutePropsResolved,\n    __farmCanonicalPath,\n    __farmRoutePropsPromise,\n    ...componentProps\n  } = props;\n  return componentProps;\n};\n\nconst __farmCreateSearchParams = (value) => {\n  const params = new URLSearchParams();\n  for (const [key, item] of Object.entries(value || {})) {\n    if (item == null) continue;\n    const values = Array.isArray(item) ? item : [item];\n    for (const entry of values) {\n      if (entry != null) params.append(key, String(entry));\n    }\n  }\n  return params;\n};\n\nconst __farmComparable = (value) => {\n  if (Array.isArray(value)) return value.map(__farmComparable);\n  if (value && typeof value === \"object\") {\n    return Object.keys(value).sort().reduce((output, key) => {\n      output[key] = __farmComparable(value[key]);\n      return output;\n    }, {});\n  }\n  return value;\n};\n\nconst __farmEqual = (left, right) => (\n  JSON.stringify(__farmComparable(left)) === JSON.stringify(__farmComparable(right))\n);\n\nconst __farmReadSearchValue = (value, key) => (\n  value && typeof value === \"object\" ? value[key] : undefined\n);\n\nconst __farmParseDefaultSearch = () => {\n  if (!__farmSearchSchema) return undefined;\n  try {\n    const value = __farmSearchSchema.parse({});\n    return value && typeof value === \"object\" ? value : undefined;\n  } catch {\n    return undefined;\n  }\n};\n\nconst __farmResolveCanonicalPath = (rawSearch, parsedSearch, path) => {\n  if (!__farmSearchOptions?.temporary?.length && !__farmSearchOptions?.stripDefaults) {\n    return undefined;\n  }\n\n  const params = __farmCreateSearchParams(rawSearch);\n  const original = params.toString();\n\n  for (const key of __farmSearchOptions.temporary || []) {\n    params.delete(key);\n  }\n\n  if (__farmSearchOptions.stripDefaults) {\n    const defaults = __farmParseDefaultSearch();\n    if (defaults) {\n      const keys = __farmSearchOptions.stripDefaults === true\n        ? Array.from(new Set(Array.from(params.keys())))\n        : [...__farmSearchOptions.stripDefaults];\n      for (const key of keys) {\n        if (params.has(key) && __farmEqual(__farmReadSearchValue(parsedSearch, key), __farmReadSearchValue(defaults, key))) {\n          params.delete(key);\n        }\n      }\n    }\n  }\n\n  const next = params.toString();\n  if (next === original) return undefined;\n  return next ? path + \"?\" + next : path;\n};\n\nexport async function __farmResolveRouteProps(props) {\n  return typeof __farmRouteModule.__farmResolveRouteProps === \"function\"\n    ? __farmRouteModule.__farmResolveRouteProps(props)\n    : props;\n}\n\nconst __farmNeedsPageWrapper = __farmRoute.kind === \"page\" && !!(\n  __farmRoute.params ||\n  __farmRoute.search ||\n  __farmRoute.data\n);\n\nasync function __farmProgrammaticPage(props) {\n  const deferredRouteProps = props?.__farmRoutePropsPromise;\n  const resolvedProps = props?.__farmRoutePropsResolved === true\n    ? props\n    : deferredRouteProps && typeof deferredRouteProps.then === \"function\"\n      ? await deferredRouteProps\n      : await __farmResolveRouteProps(props);\n\n  return __farmCreateElement(\n    __farmRoute.component,\n    __farmStripRoutePropsMarker(resolvedProps)\n  );\n}\n\nexport default __farmRouteModule.default;\n`;\n}\n\nfunction generateProgrammaticApiRouteModule(routePath: string, routeFile: string): string {\n  return `\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n  value && typeof value === \"object\" && (\n    value.kind === \"page\" ||\n    value.kind === \"layout\" ||\n    value.kind === \"api\" ||\n    value.kind === \"redirect\"\n  )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n  if (Array.isArray(candidate)) return candidate;\n  if (Array.isArray(candidate?.routes)) return candidate.routes;\n  if (__farmIsRouteDefinition(candidate)) return [candidate];\n  return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n  __farmGetRouteExport(\"default\"),\n  __farmGetRouteExport(\"routes\"),\n  __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n  __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n  if (__farmRoutes.length > 0) break;\n}\nif (__farmRoutes.length === 0) {\n  __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (value) => {\n  const withSlash = value && value.startsWith(\"/\") ? value : \"/\" + (value || \"\");\n  return withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n  route?.kind === \"api\" &&\n  __farmNormalizeRoutePath(route.path) === ${JSON.stringify(routePath)}\n));\n\nif (!__farmRoute) {\n  throw new Error(${JSON.stringify(\n    `Programmatic api route \"${routePath}\" was not found in ${routeFile}.`,\n  )});\n}\n\nexport const GET = __farmRoute.methods.GET;\nexport const HEAD = __farmRoute.methods.HEAD;\nexport const QUERY = __farmRoute.methods.QUERY;\nexport const POST = __farmRoute.methods.POST;\nexport const PUT = __farmRoute.methods.PUT;\nexport const DELETE = __farmRoute.methods.DELETE;\nexport const PATCH = __farmRoute.methods.PATCH;\nexport const OPTIONS = __farmRoute.methods.OPTIONS;\n`.trim();\n}\n\nfunction toProgrammaticRouteImportSpecifier(filePath: string, root?: string): string {\n  return root ? toViteModuleId(filePath, root) : filePath;\n}\n\ntype RouteModuleLike = {\n  __farmRouteParsesProps?: boolean;\n  __farmResolveRouteProps?: (props: {\n    params: Record<string, string>;\n    searchParams: Promise<Record<string, string | string[] | undefined>>;\n    path: string;\n    [key: string]: unknown;\n  }) => Promise<Record<string, unknown>>;\n  __farmRouteSchemas?: {\n    params?: { parse?: (value: unknown) => unknown };\n    search?: { parse?: (value: unknown) => unknown };\n  };\n};\n\nasync function parseRouteModuleProps(\n  routeModule: RouteModuleLike,\n  input: {\n    props: {\n      params: Record<string, string>;\n      searchParams: Promise<Record<string, string | string[] | undefined>>;\n      path: string;\n      [key: string]: unknown;\n    };\n    search: Record<string, string | string[] | undefined>;\n    routePath: string;\n  },\n): Promise<Record<string, unknown>> {\n  if (typeof routeModule.__farmResolveRouteProps === \"function\") {\n    return await routeModule.__farmResolveRouteProps(input.props);\n  }\n\n  if (routeModule.__farmRouteParsesProps) {\n    return {\n      ...input.props,\n      search: input.search,\n    };\n  }\n\n  const schemas = routeModule.__farmRouteSchemas;\n  const params = parseRouteModuleSchema(\n    schemas?.params,\n    input.props.params,\n    \"params\",\n    input.routePath,\n  );\n  const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n  return {\n    ...input.props,\n    params,\n    search,\n    searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n  };\n}\n\nfunction parseRouteModuleSchema(\n  schema: { parse?: (value: unknown) => unknown } | undefined,\n  value: unknown,\n  label: string,\n  routePath: string,\n): unknown {\n  if (!schema || typeof schema.parse !== \"function\") {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n  }\n}\n\nfunction generateClientCode(\n  integrationProviders: ReturnType<typeof getIntegrationProviders> = [],\n  documentNavigationMatchers: string[] = [],\n  docsSearchClientRuntime = EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME,\n  devtoolsClientRuntime = \"\",\n  plugins: readonly FarmPlugin[] = [],\n  root = process.cwd(),\n  srcDir = \"src\",\n  publicRuntimeConfig: Record<string, unknown> | undefined = undefined,\n  docsAdapterReact?: string,\n  renderer: FarmRenderer = REACT_RENDERER,\n  isolatedHydrationEnabled = false,\n  trailingSlash = false,\n  basePath = \"/\",\n  clientCachePersistence: ClientCachePersistenceEntryCode = { imports: \"\", init: \"\" },\n): string {\n  const providerClientCode = generateFarmIntegrationProviderClientCode(integrationProviders, root);\n  const clientPluginEntry = generateFarmClientPluginEntryCode(\n    plugins,\n    root,\n    srcDir,\n    publicRuntimeConfig,\n  );\n  const rendererClientImports = isReactRenderer(renderer)\n    ? `import React from 'react'\\nimport { hydrateRoot, createRoot } from 'react-dom/client'`\n    : `import React, { hydrateRoot, createRoot } from ${JSON.stringify(renderer.client)}`;\n  const isolatedHydrationImport = isolatedHydrationEnabled\n    ? `import { createFarmIsolatedHydrationRuntime, wrapFarmIsolatedClientGraph } from '@farm.js/core/internal/isolated-boundary'`\n    : \"\";\n  const docsAdapterImportBlock = docsAdapterReact\n    ? `import * as FarmDocsAdapterReact from ${JSON.stringify(docsAdapterReact)};\n\nasync function hydrateFarmDocsAdapterRuntime() {\n  const runtime = window.__FARM_DOCS_ADAPTER__;\n  if (!runtime) return false;\n  if (typeof FarmDocsAdapterReact.hydrateFarmDocs !== 'function') {\n    throw new Error('The configured Farm docs adapter does not export hydrateFarmDocs().');\n  }\n  FarmDocsAdapterReact.hydrateFarmDocs({\n    config: runtime.config || {},\n    data: runtime.data,\n  });\n  return true;\n}`\n    : `async function hydrateFarmDocsAdapterRuntime() { return false; }`;\n  const isolatedHydrationRuntime = isolatedHydrationEnabled\n    ? `const farmIsolatedHydrationRuntime = createFarmIsolatedHydrationRuntime({\n  ReactRuntime: React,\n  hydrateRoot,\n  load: (reference) => import(/* @vite-ignore */ reference),\n  schedule: scheduleFarmIslandHydration,\n  wrap: wrapWithIntegrationProviders,\n});\nwindow.__FARM_ISOLATED_HYDRATION_RUNTIME__ = farmIsolatedHydrationRuntime;\n\nfunction disposeFarmIsolatedClientBoundaries(scope) {\n  farmIsolatedHydrationRuntime.dispose(scope);\n}\n\nasync function hydrateFarmIsolatedClientBoundaries(scope = document, signal) {\n  await farmIsolatedHydrationRuntime.hydrate(scope, signal);\n}`\n    : \"\";\n\n  return `\n${rendererClientImports}\n${isolatedHydrationImport}\nimport { installChunkErrorRecovery, SPARouter } from '@farm.js/core/client'\nimport { createClientPluginManager } from '@farm.js/core/plugin/client'\nimport { isFarmRouteActive } from '@farm.js/core/router'\nimport { scheduleFarmIslandHydration, searchParamsToObject, setFarmBasePath, setFarmTrailingSlashPreference, stripFarmBasePath } from '@farm.js/core/internal/client-runtime'\nimport { reviveDeferredData } from '@farm.js/core/deferred'\nimport {\n  createFarmDeploymentMismatchError,\n  createFarmDeploymentRequestHeaders,\n  isFarmDeploymentMismatchResponse,\n} from '@farm.js/core/deployment'\n${providerClientCode.imports}\n${clientPluginEntry.imports}\n${clientCachePersistence.imports}\n${docsSearchClientRuntime}\n${devtoolsClientRuntime}\n${docsAdapterImportBlock}\n\n// ⭐ Farm.js SPA Client Runtime (TanStack Start pattern)\n// Uses manifest-based chunk loading - NO HTML fetching!\n// Manifest is inlined in HTML via window.__FARM_MANIFEST__\n\n// Expose React for HMR\nwindow.__FARM_REACT__ = React;\nconst integrationDocumentNavigationMatchers = ${JSON.stringify(documentNavigationMatchers)};\n\nsetFarmBasePath(${JSON.stringify(basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(trailingSlash)});\ninstallChunkErrorRecovery();\n${clientCachePersistence.init}\n\nlet reactRoot = null;\n${isolatedHydrationRuntime}\n\nfunction matchesDocumentNavigation(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  return integrationDocumentNavigationMatchers.some((matcher) => {\n    if (matcher === '/(.*)' || matcher === '*') {\n      return true;\n    }\n    if (matcher.endsWith('(.*)')) {\n      const prefix = matcher.slice(0, -4);\n      return pathname === prefix || pathname.startsWith(prefix + '/');\n    }\n    return matcher === pathname;\n  });\n}\n\n${providerClientCode.runtime}\n\nwindow.__FARM_WRAP_PROVIDERS__ = wrapWithIntegrationProviders;\n${isolatedHydrationEnabled ? \"window.__FARM_WRAP_CLIENT_GRAPH__ = (element) => wrapFarmIsolatedClientGraph(React, element);\" : \"\"}\n\n// Get manifest from window (inlined by server in HTML)\n// Fallback to empty manifest if not available yet\nconst getManifest = () => window.__FARM_MANIFEST__ || { routes: {}, layouts: {}, slots: [], clientEntry: '', sharedAssets: [] };\n\n// ====== CLIENT-SIDE ROUTE MATCHING ======\n// Matches URL to route using manifest (no server request!)\n\nfunction matchSegment(urlSegment, routeSegment) {\n  if (!routeSegment.isDynamic) {\n    return urlSegment === routeSegment.segment ? {} : null;\n  }\n  if (routeSegment.isCatchAll) {\n    return { [routeSegment.segment]: urlSegment };\n  }\n  return { [routeSegment.segment]: urlSegment };\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction matchRoute(pathname, routeSegments) {\n  const normalizedPath = pathname === '/' ? '' : pathname.replace(/^\\\\//, '').replace(/\\\\/$/, '');\n  const pathSegments = normalizedPath ? normalizedPath.split('/').map(decodeRouteSegment) : [];\n  \n  // Handle catch-all routes\n  const hasCatchAll = routeSegments.some(s => s.isCatchAll);\n  \n  if (!hasCatchAll && pathSegments.length !== routeSegments.length) {\n    return null;\n  }\n  \n  const params = {};\n  \n  for (let i = 0; i < routeSegments.length; i++) {\n    const routeSeg = routeSegments[i];\n    const pathSeg = pathSegments[i];\n\n    if (routeSeg.isCatchAll) {\n      // Collect remaining segments\n      params[routeSeg.segment] = pathSegments.slice(i).join('/');\n      return params;\n    }\n    \n    if (pathSeg === undefined) {\n      if (routeSeg.isOptional) continue;\n      return null;\n    }\n    \n    const match = matchSegment(pathSeg, routeSeg);\n    if (match === null) return null;\n    Object.assign(params, match);\n  }\n  \n  return params;\n}\n\nfunction findRoute(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  const manifest = getManifest();\n  const routes = Object.values(manifest.routes);\n  \n  for (const route of routes) {\n    const params = matchRoute(pathname, route.segments);\n    if (params !== null) {\n      return { route, params };\n    }\n  }\n  return null;\n}\n\nfunction findLayouts(pathname) {\n  pathname = stripFarmBasePath(pathname);\n  const manifest = getManifest();\n  const layouts = Object.values(manifest.layouts);\n  const matchingLayouts = [];\n  \n  for (const layout of layouts) {\n    if (layout.pattern === '/' || isFarmRouteActive(layout.pattern, pathname, { exact: false })) {\n      matchingLayouts.push(layout);\n    }\n  }\n  \n  return matchingLayouts.sort((a, b) => a.pattern.length - b.pattern.length);\n}\n\n// ====== SPA ROUTER ======\n// Client-side router - no server requests needed!\n\nclass LegacyManifestSPARouter {\n  constructor() {\n    this.moduleCache = new Map();\n    this.prefetchingUrls = new Set();\n    this.observers = new Map();\n    \n    if (typeof window !== 'undefined') {\n      window.addEventListener('popstate', this.handlePopState.bind(this));\n    }\n  }\n\n  setNavigationHandler(handler) {\n    this.onNavigate = handler;\n  }\n\n  async navigate(href, options = {}) {\n    const { replace = false, scroll = true } = options;\n    const url = new URL(href, window.location.origin);\n    const pathname = url.pathname;\n    const search = url.search;\n    const fullPath = pathname + search;\n\n    if (matchesDocumentNavigation(pathname)) {\n      if (replace) {\n        window.location.replace(url.toString());\n      } else {\n        window.location.assign(url.toString());\n      }\n      return;\n    }\n\n    // Same page - update fragment history without loading route data.\n    if (pathname === window.location.pathname && search === window.location.search) {\n      if (url.hash === window.location.hash) return;\n      if (replace) {\n        window.history.replaceState(window.history.state, '', url);\n      } else {\n        window.history.pushState(window.history.state, '', url);\n      }\n      if (scroll) {\n        if (url.hash) document.querySelector(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      }\n      return;\n    }\n\n    // Save scroll position\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n\n    try {\n      // CLIENT-SIDE route matching - no server request!\n      const match = findRoute(pathname);\n      if (!match) {\n        console.warn('[Farm.js] Route not found:', pathname);\n        window.location.href = href;\n        return;\n      }\n\n      const { route, params } = match;\n\n      // Parse search params\n      const searchParams = searchParamsToObject(url.searchParams);\n\n      // Build page data from manifest (no server request!)\n      const pageData = {\n        route: route, // Full route entry from manifest\n        params,\n        searchParams,\n        layouts: findLayouts(pathname),\n      };\n\n      // Update URL\n      if (replace) {\n        window.history.replaceState({ path: fullPath }, '', fullPath);\n      } else {\n        window.history.pushState({ path: fullPath }, '', fullPath);\n      }\n\n      // Navigate using the handler\n      if (this.onNavigate) {\n        await this.onNavigate(pageData);\n      }\n      applyCanonicalPathFromProps(currentPageProps);\n\n      // Handle scroll\n      if (scroll) {\n        if (url.hash) {\n          const element = document.querySelector(url.hash);\n          if (element) element.scrollIntoView();\n        } else {\n          window.scrollTo(0, 0);\n        }\n      }\n    } catch (error) {\n      console.error('[Farm.js] Navigation error:', error);\n      window.location.href = href; // Fallback\n    }\n  }\n\n  async prefetch(href) {\n    // Prefetching disabled in dev mode to avoid Vite dep optimization issues\n    // In production, assets are already bundled and prefetched via link tags\n    if (import.meta.env?.DEV) return;\n    \n    const url = new URL(href, window.location.origin);\n    const pathname = url.pathname;\n\n    if (this.prefetchingUrls.has(pathname)) return;\n\n    // Find route in manifest\n    const match = findRoute(pathname);\n    if (!match) return;\n\n    // Only prefetch routes that will hydrate on the client.\n    if (!match.route.isClientComponent && !match.route.shouldHydrate) return;\n    if (match.route.islandStrategy && match.route.islandStrategy !== 'load') return;\n\n    const modulePath = match.route.modulePath;\n    if (this.moduleCache.has(modulePath)) return;\n\n    this.prefetchingUrls.add(pathname);\n    try {\n      // Prefetch by importing the module (Vite caches it)\n      const module = await import(/* @vite-ignore */ modulePath);\n      this.moduleCache.set(modulePath, module);\n      pageModuleCache.set(modulePath, module);\n    } catch (error) {\n      // Silently fail for prefetch\n    } finally {\n      this.prefetchingUrls.delete(pathname);\n    }\n  }\n\n  observeForPrefetch(element) {\n    if (typeof IntersectionObserver === 'undefined') return;\n    const href = element.getAttribute('href');\n    if (!href || this.isExternalUrl(href)) return;\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        for (const entry of entries) {\n          if (entry.isIntersecting) {\n            setTimeout(() => this.prefetch(href), 100);\n            observer.unobserve(element);\n            this.observers.delete(element);\n          }\n        }\n      },\n      { rootMargin: '200px' }\n    );\n    observer.observe(element);\n    this.observers.set(element, observer);\n  }\n\n  unobserveForPrefetch(element) {\n    const observer = this.observers.get(element);\n    if (observer) {\n      observer.unobserve(element);\n      this.observers.delete(element);\n    }\n  }\n\n  async handlePopState(event) {\n    if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n    const pathname = window.location.pathname;\n    const search = window.location.search;\n    \n    try {\n      // Client-side route matching for back/forward\n      const match = findRoute(pathname);\n      if (!match) {\n        window.location.reload();\n        return;\n      }\n\n      const { route, params } = match;\n      const url = new URL(window.location.href);\n      const searchParams = searchParamsToObject(url.searchParams);\n\n      const pageData = {\n        route: route,\n        params,\n        searchParams,\n        layouts: findLayouts(pathname),\n      };\n\n      if (this.onNavigate) await this.onNavigate(pageData);\n      this.restoreScrollPosition(pathname + search);\n    } catch (error) {\n      console.error('[Farm.js] Popstate error:', error);\n      window.location.reload();\n    }\n  }\n\n  isExternalUrl(href) {\n    return href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//');\n  }\n\n  saveScrollPosition(path) {\n    try {\n      sessionStorage.setItem('farm-scroll-' + path, JSON.stringify({ x: window.scrollX, y: window.scrollY }));\n    } catch {}\n  }\n\n  restoreScrollPosition(path) {\n    try {\n      const saved = sessionStorage.getItem('farm-scroll-' + path);\n      if (saved) {\n        const { x, y } = JSON.parse(saved);\n        setTimeout(() => window.scrollTo(x, y), 0);\n      }\n    } catch {}\n  }\n}\n\n// Initialize the SPA router\nconst spaRouter = new SPARouter({\n  shouldUseDocumentNavigation: matchesDocumentNavigation,\n});\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nconst farmClientRuntime = createClientPluginManager(\n  ${clientPluginEntry.registrations},\n  {\n    router: spaRouter,\n    isDev: import.meta.env?.DEV === true,\n    isProd: import.meta.env?.PROD === true,\n    deploymentId: window.__FARM_DEPLOYMENT_ID__,\n  },\n);\nspaRouter.setClientPluginManager(farmClientRuntime);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\nif (import.meta.hot) {\n  // 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 || typeof target.click !== 'function') continue;\n    if (target.isConnected === false) continue;\n    setTimeout(() => target.click(), 0);\n  }\n}\n\nfunction markFarmHydrated() {\n  window.__FARM_HYDRATED__ = true;\n  document.documentElement.dataset.farmHydrated = 'true';\n}\n\nasync function buildClientHydrationElement(\n  PageComponent,\n  pageProps,\n  loadingModuleOverride,\n) {\n  let element = React.createElement(PageComponent, pageProps);\n  const loadingModulePath = loadingModuleOverride === undefined\n    ? window.__FARM_LOADING_MODULE__\n    : loadingModuleOverride;\n\n  if (loadingModulePath) {\n    try {\n      const loadingModule = await import(/* @vite-ignore */ loadingModulePath);\n      const LoadingComponent = loadingModule?.default;\n      if (LoadingComponent) {\n        const loadingFallback = React.createElement(LoadingComponent, {\n          params: pageProps?.params || {},\n          path: pageProps?.path || window.location.pathname,\n        });\n        element = React.createElement(React.Suspense, { fallback: loadingFallback }, element);\n      }\n    } catch (error) {\n      console.error(\n        '[Farm.js] Loading boundary failed to load and was skipped: ' + loadingModulePath,\n        error,\n      );\n    }\n  }\n\n  return element;\n}\n\nasync function loadLayoutComponents(layouts = []) {\n  const loadedLayouts = [];\n\n  for (const layout of layouts) {\n    if (!layout?.modulePath) continue;\n    try {\n      let LayoutComponent = layoutComponentCache.get(layout.modulePath);\n      if (!LayoutComponent) {\n        const layoutModule = await import(/* @vite-ignore */ layout.modulePath);\n        LayoutComponent = layoutModule.default;\n        if (LayoutComponent) {\n          layoutComponentCache.set(layout.modulePath, LayoutComponent);\n        }\n      }\n      if (LayoutComponent) loadedLayouts.push({ ...layout, Component: LayoutComponent });\n    } catch (error) {\n      // Skipping the layout leaves the client tree different from the server's,\n      // so React discards the server rendered markup for this branch, including\n      // whatever the layout drew. Losing visible UI deserves more than a warning.\n      console.error(\n        '[Farm.js] Layout failed to load and was skipped: ' + layout.modulePath +\n          '. The client tree no longer matches the server, so React will discard the ' +\n          'server rendered markup for this route, including anything this layout renders.',\n        error,\n      );\n    }\n  }\n\n  return loadedLayouts;\n}\n\nfunction wrapWithLoadedLayouts(element, loadedLayouts, params) {\n  let wrapped = element;\n  for (let index = loadedLayouts.length - 1; index >= 0; index--) {\n    const layout = loadedLayouts[index];\n    wrapped = React.createElement(layout.Component, {\n      children: wrapped,\n      params,\n    });\n    wrapped = React.createElement('div', {\n      'data-farm-layout-boundary': 'true',\n      'data-farm-layout-pattern': layout.pattern,\n      style: { display: 'contents' },\n    }, wrapped);\n  }\n  return wrapped;\n}\n\nfunction getCurrentSearchParams() {\n  const url = new URL(window.location.href);\n  return searchParamsToObject(url.searchParams);\n}\n\nfunction parseClientRouteSchema(schema, value, label) {\n  if (!schema || typeof schema.parse !== 'function') {\n    return value;\n  }\n\n  try {\n    return schema.parse(value);\n  } catch (error) {\n    throw new Error('Invalid route ' + label + ': ' + (error?.message || String(error)));\n  }\n}\n\nasync function buildRouteComponentProps(pageModule, params, searchParams, path, existingProps) {\n  if (existingProps?.__farmRoutePropsResolved === true) {\n    const revivedProps = reviveDeferredData(\n      existingProps,\n      window.__FARM_DEFERRED_DATA__ || {},\n    );\n    window.__FARM_PROPS__ = revivedProps;\n    return {\n      ...revivedProps,\n      searchParams: Promise.resolve(revivedProps.search ?? revivedProps.searchParams ?? {}),\n      path: revivedProps.path || path,\n    };\n  }\n\n  if (typeof pageModule?.__farmResolveRouteProps === 'function') {\n    const rawProps = {\n      ...(existingProps || {}),\n      params,\n      searchParams: Promise.resolve(searchParams),\n      path,\n    };\n    // Keep top-level route errors inside the router's navigation transaction.\n    // Explicit defer() values can still suspend nested UI after this resolves.\n    return await pageModule.__farmResolveRouteProps(rawProps);\n  }\n\n  const schemas = pageModule?.__farmRouteSchemas;\n  const parsedParams = parseClientRouteSchema(schemas?.params, params, 'params');\n  const parsedSearch = parseClientRouteSchema(schemas?.search, searchParams, 'search');\n\n  return {\n    ...(existingProps || {}),\n    params: parsedParams,\n    search: parsedSearch,\n    searchParams: schemas ? Promise.resolve(parsedSearch) : parsedSearch,\n    path,\n  };\n}\n\nasync function buildWrappedHydrationElement(PageComponent, pageProps, layouts = []) {\n  const loadedLayouts = await loadLayoutComponents(layouts);\n  const pageElement = await buildClientHydrationElement(PageComponent, pageProps);\n  const wrappedTree = wrapWithLoadedLayouts(\n    pageElement,\n    loadedLayouts,\n    pageProps?.params || {},\n  );\n  return wrapWithIntegrationProviders(wrappedTree);\n}\n\nfunction createLayoutPageBoundary(\n  pageShouldHydrate,\n  islandStrategy,\n  pageElement,\n  serverHtml,\n) {\n  const props = {\n    id: '__farm_page__',\n    'data-farm-client': pageShouldHydrate ? 'true' : 'false',\n    'data-farm-layout-client': 'true',\n    'data-farm-island': 'page',\n    'data-farm-island-strategy': islandStrategy || 'load',\n  };\n  if (typeof serverHtml === 'string') {\n    props.suppressHydrationWarning = true;\n    props.dangerouslySetInnerHTML = { __html: serverHtml };\n    return React.createElement('div', props);\n  }\n  return React.createElement('div', props, pageElement);\n}\n\nasync function tryHydrateImportedPage(\n  container,\n  route,\n  params,\n  layouts,\n  useHydrate = false,\n  existingProps = null,\n  signal = null,\n  hydrationOptions = {},\n) {\n  const modulePath = route?.modulePath;\n  if (!modulePath || signal?.aborted) {\n    return false;\n  }\n\n  const pageShouldHydrate = hydrationOptions.pageShouldHydrate !== false;\n  const layoutShouldHydrate = hydrationOptions.layoutShouldHydrate === true;\n  const islandStrategy = hydrationOptions.islandStrategy || route.islandStrategy || 'load';\n  let pageElement = null;\n\n  if (pageShouldHydrate) {\n    let pageModule = pageModuleCache.get(modulePath);\n    if (!pageModule) {\n      pageModule = await import(/* @vite-ignore */ modulePath);\n      pageModuleCache.set(modulePath, pageModule);\n    }\n    if (signal?.aborted || !container?.isConnected) return false;\n\n    const PageComponent = pageModule?.default;\n    if (!PageComponent) return false;\n\n    if (\n      typeof PageComponent === 'function' &&\n      PageComponent.constructor &&\n      PageComponent.constructor.name === 'AsyncFunction'\n    ) {\n      console.warn(\n        '[Farm.js] Skipping hydration for ' + modulePath +\n        ': async server components cannot run in the browser. ' +\n        'Server-rendered HTML is preserved; move interactive UI into a \"use client\" child of a synchronous page.'\n      );\n      return false;\n    }\n\n    currentPageComponent = PageComponent;\n    currentPageProps = await buildRouteComponentProps(\n      pageModule,\n      params,\n      getCurrentSearchParams(),\n      window.location.pathname,\n      existingProps,\n    );\n    pageElement = await buildClientHydrationElement(\n      PageComponent,\n      currentPageProps,\n      hydrationOptions.loadingModulePath,\n    );\n  } else if (layoutShouldHydrate) {\n    currentPageProps = existingProps || { params };\n    const serverPage = document.getElementById('__farm_page__');\n    pageElement = createLayoutPageBoundary(\n      false,\n      islandStrategy,\n      null,\n      typeof hydrationOptions.serverHtml === 'string'\n        ? hydrationOptions.serverHtml\n        : serverPage ? serverPage.innerHTML : '',\n    );\n  }\n  if (signal?.aborted || !container?.isConnected || !pageElement) return false;\n\n  let wrappedElement;\n  if (layoutShouldHydrate) {\n    const loadedLayouts = await loadLayoutComponents(layouts);\n    if (pageShouldHydrate) {\n      pageElement = createLayoutPageBoundary(true, islandStrategy, pageElement);\n    }\n    const wrappedTree = wrapWithLoadedLayouts(pageElement, loadedLayouts, params);\n    wrappedElement = wrapWithIntegrationProviders(wrappedTree);\n  } else if (useHydrate && container?.id === '__farm_page__') {\n    wrappedElement = wrapWithIntegrationProviders(pageElement);\n  } else {\n    wrappedElement = await buildWrappedHydrationElement(\n      currentPageComponent,\n      currentPageProps,\n      layouts,\n    );\n  }\n  if (signal?.aborted || !container?.isConnected) return false;\n\n  ${isolatedHydrationEnabled ? \"wrappedElement = wrapFarmIsolatedClientGraph(React, wrappedElement);\" : \"\"}\n\n  if (useHydrate) {\n    try {\n      reactRoot = hydrateRoot(container, wrappedElement);\n      window.__FARM_REACT_ROOT__ = reactRoot;\n      return true;\n    } catch (error) {\n      appRoot = createRoot(container);\n      appRoot.render(wrappedElement);\n      window.__FARM_REACT_ROOT__ = appRoot;\n      hasClientTakenOver = true;\n      return true;\n    }\n  }\n\n  hasClientTakenOver = true;\n  const existingRoot = appRoot || reactRoot;\n  if (existingRoot && layoutShouldHydrate) {\n    existingRoot.render(wrappedElement);\n    appRoot = existingRoot;\n    reactRoot = null;\n    window.__FARM_REACT_ROOT__ = appRoot;\n    return true;\n  }\n  if (reactRoot) { try { reactRoot.unmount(); } catch (e) {} reactRoot = null; }\n  if (appRoot) { try { appRoot.unmount(); } catch (e) {} appRoot = null; }\n  appRoot = createRoot(container);\n  window.__FARM_REACT_ROOT__ = appRoot;\n  appRoot.render(wrappedElement);\n  return true;\n}\n\nfunction findLayoutBoundary(root, pattern) {\n  const boundaries = root.querySelectorAll\n    ? root.querySelectorAll('[data-farm-layout-boundary=\"true\"]')\n    : [];\n  for (const boundary of boundaries) {\n    if (boundary.getAttribute('data-farm-layout-pattern') === pattern) return boundary;\n  }\n  return null;\n}\n\nfunction readActiveLayoutPatterns() {\n  return Array.from(document.querySelectorAll('[data-farm-layout-boundary=\"true\"]'))\n    .map((element) => element.getAttribute('data-farm-layout-pattern'))\n    .filter(Boolean);\n}\n\nfunction activateFragmentScripts(root) {\n  for (const script of Array.from(root.querySelectorAll?.('script') || [])) {\n    const freshScript = document.createElement('script');\n    for (const attribute of Array.from(script.attributes)) {\n      freshScript.setAttribute(attribute.name, attribute.value);\n    }\n    freshScript.textContent = script.textContent || '';\n    script.replaceWith(freshScript);\n  }\n}\n\nfunction parseNavigationFragment(html) {\n  const template = document.createElement('template');\n  template.innerHTML = html;\n  return template.content;\n}\n\nfunction replaceNavigationBoundary(container, fragment, currentPatterns, nextPatterns) {\n  let sharedCount = 0;\n  while (\n    sharedCount < currentPatterns.length &&\n    sharedCount < nextPatterns.length &&\n    currentPatterns[sharedCount] === nextPatterns[sharedCount]\n  ) {\n    sharedCount++;\n  }\n\n  const fragmentTreeRoot = nextPatterns.length > 0\n    ? findLayoutBoundary(fragment, nextPatterns[0])\n    : fragment.querySelector('#__farm_page__');\n  const currentTarget = sharedCount < currentPatterns.length\n    ? findLayoutBoundary(container, currentPatterns[sharedCount])\n    : container.querySelector('#__farm_page__');\n  const nextTarget = sharedCount < nextPatterns.length\n    ? findLayoutBoundary(fragment, nextPatterns[sharedCount])\n    : fragment.querySelector('#__farm_page__');\n\n  if (!currentTarget || !nextTarget) {\n    ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(container);\" : \"\"}\n    container.replaceChildren(fragment);\n    activateFragmentScripts(container);\n    return container;\n  }\n\n  ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(currentTarget);\" : \"\"}\n  currentTarget.replaceWith(nextTarget);\n  activateFragmentScripts(nextTarget);\n  if (fragmentTreeRoot && fragmentTreeRoot !== nextTarget) fragmentTreeRoot.remove();\n\n  // React's completed streaming markup can include reveal instructions next\n  // to the route tree. Execute those support nodes after the boundary exists.\n  if (fragment.childNodes.length > 0) {\n    const support = document.createElement('div');\n    support.hidden = true;\n    support.dataset.farmFragmentSupport = 'true';\n    support.append(fragment);\n    document.body.appendChild(support);\n    activateFragmentScripts(support);\n    setTimeout(() => support.remove(), 0);\n  }\n  return nextTarget;\n}\n\nlet activeLayoutPatterns = readActiveLayoutPatterns();\nlet activeLayoutShouldHydrate = window.__FARM_LAYOUT_SHOULD_HYDRATE__ === true;\n\n// ====== MANIFEST-DRIVEN HTML-FRAGMENT NAVIGATION ======\n// One page-data response carries both server HTML and the hydration plan.\nasync function renderPage(pageData) {\n  const container = document.getElementById('root');\n  if (!container) return;\n  cancelPendingPageHydration();\n  const destination = window.location.pathname + window.location.search;\n\n  if (pageData.interception) {\n    if (await renderRouteInterception(pageData)) return;\n    window.location.assign(destination);\n    return;\n  }\n\n  if (await clearRouteInterception(destination)) {\n    return;\n  }\n\n  const manifestRoute = findRoute(window.location.pathname)?.route;\n  const renderPlan = pageData.renderPlan || manifestRoute?.renderPlan;\n  const hydrationMode = renderPlan?.hydration;\n  const route = {\n    modulePath: pageData.modulePath,\n    isClientComponent: pageData.isClientComponent === true,\n    pageShouldHydrate:\n      hydrationMode === 'route-island' ||\n      hydrationMode === 'route-and-layout-islands' ||\n      pageData.pageShouldHydrate === true,\n    layoutShouldHydrate:\n      hydrationMode === 'layout-island' ||\n      hydrationMode === 'route-and-layout-islands' ||\n      pageData.layoutShouldHydrate === true,\n    shouldHydrate: pageData.shouldHydrate === true,\n    islandStrategy: renderPlan?.islandStrategy || pageData.islandStrategy || 'load',\n    loadingModulePath: pageData.loadingModulePath,\n  };\n  const params = pageData.props?.params || {};\n  const nextLayoutPatterns = Array.isArray(pageData.fragment?.layoutPatterns)\n    ? pageData.fragment.layoutPatterns\n    : [];\n  const layouts = (pageData.layoutModules || []).map((modulePath, index) => ({\n    modulePath,\n    pattern: nextLayoutPatterns[index] || (index === 0 ? '/' : modulePath),\n  }));\n  const path = window.location.pathname + window.location.search;\n\n  // A legacy server may omit the fragment. Keep one compatibility fallback,\n  // but current servers send HTML in the page-data response and avoid this\n  // second network round trip.\n  const fetchAndSwapHTML = async () => {\n    let fragmentHtml = pageData.fragment?.html;\n    let layoutPatterns = nextLayoutPatterns;\n\n    if (typeof fragmentHtml !== 'string') {\n      const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n      const response = await fetch(path, {\n        headers: createFarmDeploymentRequestHeaders(deploymentId, { 'Accept': 'text/html' }),\n      });\n      if (isFarmDeploymentMismatchResponse(response, deploymentId)) {\n        const error = createFarmDeploymentMismatchError(response, deploymentId || 'unknown');\n        window.dispatchEvent(new CustomEvent('farm:deployment-mismatch', { detail: error }));\n        window.location.assign(path);\n        return false;\n      }\n      const documentHtml = await response.text();\n      const doc = new DOMParser().parseFromString(documentHtml, 'text/html');\n      const nextRoot = doc.getElementById('root');\n      if (!nextRoot) return false;\n      fragmentHtml = nextRoot.innerHTML;\n      layoutPatterns = Array.from(\n        nextRoot.querySelectorAll('[data-farm-layout-boundary=\"true\"]'),\n      ).map((element) => element.getAttribute('data-farm-layout-pattern')).filter(Boolean);\n    }\n\n    const fragment = parseNavigationFragment(fragmentHtml);\n    const nextPage = fragment.querySelector('#__farm_page__');\n    const pageShouldHydrate = route.pageShouldHydrate || route.isClientComponent;\n    const layoutShouldHydrate = route.layoutShouldHydrate;\n    ${\n      isolatedHydrationEnabled\n        ? `const hasIsolatedClientBoundaries = Boolean(\n      fragment.querySelector('farm-client-boundary[data-farm-client-boundary]'),\n    );\n    const shouldHydrate =\n      pageShouldHydrate || layoutShouldHydrate || (route.shouldHydrate && !hasIsolatedClientBoundaries);`\n        : \"const shouldHydrate = route.shouldHydrate || pageShouldHydrate || layoutShouldHydrate;\"\n    }\n\n    // A React-owned layout can update in place. Rendering the same layout\n    // component chain preserves its state while changing only the route child.\n    if (activeLayoutShouldHydrate && layoutShouldHydrate && (appRoot || reactRoot)) {\n      await tryHydrateImportedPage(\n        container,\n        route,\n        params,\n        layouts,\n        false,\n        pageData.props,\n        null,\n        {\n          pageShouldHydrate,\n          layoutShouldHydrate,\n          islandStrategy: route.islandStrategy,\n          serverHtml: nextPage ? nextPage.innerHTML : '',\n          loadingModulePath: route.loadingModulePath,\n        },\n      );\n    } else {\n      ${isolatedHydrationEnabled ? \"let isolatedHydrationScope = container;\" : \"\"}\n      if (activeLayoutShouldHydrate) {\n        ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(container);\" : \"\"}\n        if (appRoot) { try { appRoot.unmount(); } catch (error) {} appRoot = null; }\n        if (reactRoot) { try { reactRoot.unmount(); } catch (error) {} reactRoot = null; }\n        container.replaceChildren(fragment);\n        activateFragmentScripts(container);\n      } else {\n        if (appRoot) { try { appRoot.unmount(); } catch (error) {} appRoot = null; }\n        if (reactRoot) { try { reactRoot.unmount(); } catch (error) {} reactRoot = null; }\n        delete window.__FARM_REACT_ROOT__;\n        ${\n          isolatedHydrationEnabled\n            ? \"isolatedHydrationScope = replaceNavigationBoundary(container, fragment, activeLayoutPatterns, layoutPatterns) || container;\"\n            : \"replaceNavigationBoundary(container, fragment, activeLayoutPatterns, layoutPatterns);\"\n        }\n      }\n\n      const hydrationController = new AbortController();\n      if (\n        shouldHydrate${\n          isolatedHydrationEnabled\n            ? \" || (hasIsolatedClientBoundaries && !layoutShouldHydrate)\"\n            : \"\"\n        }\n      ) {\n        pendingPageHydrationController = hydrationController;\n      }\n      if (shouldHydrate) {\n        const hydrationContainer = layoutShouldHydrate\n          ? container\n          : document.getElementById('__farm_page__') || container;\n        const scheduledHydration = scheduleFarmIslandHydration({\n          container: hydrationContainer,\n          strategy: route.islandStrategy,\n          signal: hydrationController.signal,\n          hydrate: async () => {\n            await tryHydrateImportedPage(\n              hydrationContainer,\n              route,\n              params,\n              layouts,\n              true,\n              pageData.props,\n              hydrationController.signal,\n              {\n                pageShouldHydrate,\n                layoutShouldHydrate,\n                islandStrategy: route.islandStrategy,\n                loadingModulePath: route.loadingModulePath,\n              },\n            );\n          },\n        });\n        if (route.islandStrategy === 'load') {\n          await scheduledHydration;\n        } else {\n          void scheduledHydration.catch((error) => {\n            console.warn('[Farm.js] Deferred island hydration failed:', error);\n          });\n        }\n      }\n      ${\n        isolatedHydrationEnabled\n          ? `if (hasIsolatedClientBoundaries && !layoutShouldHydrate) {\n        await hydrateFarmIsolatedClientBoundaries(\n          isolatedHydrationScope,\n          hydrationController.signal,\n        );\n        if (hydrationController.signal.aborted) return;\n      }`\n          : \"\"\n      }\n    }\n\n    activeLayoutPatterns = layoutPatterns;\n    activeLayoutShouldHydrate = layoutShouldHydrate;\n    window.__FARM_LOADING_MODULE__ = route.loadingModulePath || null;\n    return true;\n  };\n\n  try {\n    await fetchAndSwapHTML();\n  } catch (error) {\n    console.error('[Farm.js] Render error:', error);\n    // Fallback to full navigation\n    window.location.href = path;\n  }\n}\n\n// Set up the navigation handler\nspaRouter.setNavigationHandler(renderPage);\n\nasync function hydrate() {\n  await farmClientRuntime.start();\n\n  if (isFarmDocsSearchPage()) {\n    await mountFarmDocsSearch();\n  }\n\n  if (await hydrateFarmDocsAdapterRuntime()) {\n    return;\n  }\n\n  const rootContainer = document.getElementById('root')\n  \n  if (!rootContainer) {\n    console.error('[Farm.js] Root container not found')\n    return\n  }\n\n  try {\n    // Check if this is a client component (set by SSR)\n    const isClientComponent = window.__FARM_IS_CLIENT__ === true;\n    const modulePath = window.__FARM_PAGE_MODULE__;\n    ${\n      isolatedHydrationEnabled\n        ? `const hasIsolatedClientBoundaries =\n      window.__FARM_HAS_ISOLATED_CLIENT_BOUNDARIES__ === true ||\n      Boolean(rootContainer.querySelector('farm-client-boundary[data-farm-client-boundary]'));`\n        : \"\"\n    }\n\n    let pageProps = normalizeServerProps(window.__FARM_PROPS__);\n    applyCanonicalPathFromProps(pageProps);\n\n    const pageShouldHydrate =\n      typeof window.__FARM_PAGE_SHOULD_HYDRATE__ === 'boolean'\n        ? window.__FARM_PAGE_SHOULD_HYDRATE__\n        : isClientComponent ||\n          findRoute(window.location.pathname)?.route?.shouldHydrate === true;\n    const layoutShouldHydrate = window.__FARM_LAYOUT_SHOULD_HYDRATE__ === true;\n    const shouldHydrate =\n      window.__FARM_SHOULD_HYDRATE__ === true ||\n      pageShouldHydrate ||\n      layoutShouldHydrate;\n    const hydratedSlots = await hydrateInitialRouteSlots();\n    ${\n      isolatedHydrationEnabled\n        ? `if (hasIsolatedClientBoundaries && !pageShouldHydrate && !layoutShouldHydrate) {\n      const hydrationController = new AbortController();\n      pendingPageHydrationController = hydrationController;\n      await hydrateFarmIsolatedClientBoundaries(rootContainer, hydrationController.signal);\n      if (hydrationController.signal.aborted) return;\n      return;\n    }`\n        : \"\"\n    }\n    if (!shouldHydrate) {\n      if (hydratedSlots) replayPreHydrationClicks();\n      return\n    }\n    if (!modulePath) {\n      console.error('[Farm.js] No page module path found')\n      return\n    }\n\n    // Get props - either from server-injected props or by matching the current URL\n    if (!pageProps || !pageProps.params || Object.keys(pageProps.params).length === 0) {\n      // Extract params from URL using manifest route matching (fallback)\n      const pathname = window.location.pathname;\n      const foundRoute = findRoute(pathname);\n      pageProps = normalizeServerProps({\n        params: foundRoute?.params || {},\n        search: getCurrentSearchParams(),\n        searchParams: getCurrentSearchParams(),\n        path: pathname,\n      });\n    }\n    currentPageProps = pageProps;\n\n    // Prefer the exact root-to-leaf layout chain selected by the server. The\n    // manifest lookup remains a fallback for generated/static responses.\n    const layouts = Array.isArray(window.__FARM_LAYOUTS__)\n      ? window.__FARM_LAYOUTS__\n      : findLayouts(window.location.pathname);\n    const pageContainer = layoutShouldHydrate\n      ? rootContainer\n      : document.getElementById('__farm_page__') || rootContainer;\n\n    if (!pageContainer) {\n      return\n    }\n\n    const currentRoute = findRoute(window.location.pathname)?.route;\n    const islandStrategy = window.__FARM_ISLAND_STRATEGY__ || currentRoute?.islandStrategy || 'load';\n    pageContainer.dataset.farmIsland = 'page';\n    pageContainer.dataset.farmIslandStrategy = islandStrategy;\n\n    const hydrationPathname = window.location.pathname;\n    const hydrationController = new AbortController();\n    pendingPageHydrationController = hydrationController;\n    try {\n      const pageHydration = scheduleFarmIslandHydration({\n        container: pageContainer,\n        strategy: islandStrategy,\n        signal: hydrationController.signal,\n        hydrate: async () => {\n          if (\n            hydrationController.signal.aborted ||\n            !pageContainer.isConnected ||\n            window.location.pathname !== hydrationPathname\n          ) {\n            return;\n          }\n\n          const hydrationSession = await farmClientRuntime.beginHydration({\n            container: pageContainer,\n            mode: shouldHydrate ? 'hydrate' : 'render',\n          });\n\n          let hydrated = false;\n          try {\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) {\n              await farmClientRuntime.failHydration(\n                hydrationSession,\n                new DOMException('Route hydration was cancelled', 'AbortError'),\n              );\n              return;\n            }\n            hydrated = await tryHydrateImportedPage(\n              pageContainer,\n              { modulePath },\n              currentPageProps.params || {},\n              layouts,\n              shouldHydrate,\n              currentPageProps,\n              hydrationController.signal,\n              {\n                pageShouldHydrate,\n                layoutShouldHydrate,\n                islandStrategy,\n              },\n            );\n            if (hydrationController.signal.aborted || !pageContainer.isConnected) {\n              await farmClientRuntime.failHydration(\n                hydrationSession,\n                new DOMException('Route hydration was cancelled', 'AbortError'),\n              );\n              return;\n            }\n            await farmClientRuntime.completeHydration(hydrationSession);\n          } catch (error) {\n            await farmClientRuntime.failHydration(hydrationSession, error);\n            throw error;\n          }\n\n          if (hydrated) {\n            // The scheduler owns queue draining and exactly-once click replay.\n            markFarmHydrated();\n            return;\n          }\n        },\n      });\n      ${\n        isolatedHydrationEnabled\n          ? `const isolatedHydration =\n        hasIsolatedClientBoundaries &&\n        !layoutShouldHydrate\n          ? hydrateFarmIsolatedClientBoundaries(rootContainer, hydrationController.signal)\n          : Promise.resolve();\n      await Promise.all([pageHydration, isolatedHydration]);`\n          : \"await pageHydration;\"\n      }\n    } finally {\n      if (pendingPageHydrationController === hydrationController) {\n        pendingPageHydrationController = null;\n      }\n    }\n  } catch (error) {\n    console.error('[Farm.js] Hydration error:', error)\n  }\n}\n\nif (document.readyState === 'loading') {\n  document.addEventListener('DOMContentLoaded', hydrate)\n} else {\n  hydrate()\n}\n\n// ====== EVENT DELEGATION FOR LINKS ======\n// This catches all link clicks even without React hydration\n// This is essential for server component pages where React doesn't hydrate\n\nfunction isModifierEvent(e) {\n  return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);\n}\n\nfunction hasAbsoluteNavigationHref(href) {\n  return /^[a-zA-Z][a-zA-Z\\\\d+.-]*:/.test(href) || href.startsWith('//');\n}\n\ndocument.addEventListener('click', function(event) {\n  if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n  // Find the closest anchor element\n  let target = event.target;\n  while (target && target.tagName !== 'A') {\n    target = target.parentElement;\n  }\n  \n  if (!target || target.tagName !== 'A') return;\n  \n  const href = target.getAttribute('href');\n  if (!href) return;\n  if (target.hasAttribute('download')) return;\n  \n  // Leave absolute URLs and non-HTTP schemes to the browser.\n  if (hasAbsoluteNavigationHref(href)) return;\n  \n  // Don't intercept hash-only links\n  if (href.startsWith('#')) return;\n  \n  // Don't intercept if target is set to open in new window\n  const linkTarget = target.getAttribute('target');\n  if (linkTarget && linkTarget !== '_self') return;\n  \n  // Don't intercept modifier clicks (Ctrl+Click = new tab)\n  if (isModifierEvent(event)) return;\n  \n  // Don't intercept non-left clicks\n  if (event.button !== 0) return;\n  \n  // Don't intercept if already prevented\n  if (event.defaultPrevented) return;\n  \n  // Use SPA router\n  event.preventDefault();\n  const replace = target.hasAttribute('data-replace');\n  const scroll = !target.hasAttribute('data-no-scroll');\n  const viewTransitionValue = target.getAttribute('data-view-transition');\n  const viewTransition = viewTransitionValue === 'auto'\n    ? 'auto'\n    : viewTransitionValue === 'true';\n  \n  spaRouter.navigate(href, { replace, scroll, viewTransition });\n});\n\nif (import.meta.hot) {\n  import.meta.hot.on('vite:beforeUpdate', () => {\n    // Clear module cache on HMR to pick up changes\n    pageModuleCache.clear();\n  })\n}\n`;\n}\n\nfunction generateServerCode(): string {\n  return `\nexport { FarmApp, createFarmApp } from './app'\nexport { ServerRenderer } from './server/renderer'\nexport { RouteManager } from './routing/route-manager'\nexport * from './types'\n`;\n}\n\nfunction generateClientManifest(bundle: any): Record<string, any> {\n  const manifest: Record<string, any> = {};\n\n  for (const [fileName, chunk] of Object.entries(bundle)) {\n    if ((chunk as any).type === \"chunk\") {\n      manifest[fileName] = {\n        id: fileName,\n        chunks: [fileName],\n        name: (chunk as any).name || fileName,\n      };\n    }\n  }\n\n  return manifest;\n}\n\nexport async function defineConfig(config: FarmVitePluginOptions = {}): Promise<UserConfig> {\n  const tailwindcss = (await import(\"@tailwindcss/vite\")).default;\n  const appRoot = path.resolve(config.root || process.cwd());\n  if (config.extends?.length) {\n    const { config: layeredConfig } = await import(\"./layers\").then(({ resolveFarmLayers }) =>\n      resolveFarmLayers(config, {\n        root: appRoot,\n        mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n      }),\n    );\n    config = layeredConfig;\n  }\n  config.renderer = resolveFarmRenderer(config.renderer);\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, appRoot, {\n    ssr: true,\n  });\n  // Node.js built-in module stubs for browser\n  const nodeBuiltinStubs: Record<string, string> = {\n    \"node:string_decoder\":\n      \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n    \"node:buffer\":\n      \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n    \"node:stream\":\n      \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n    \"node:util\":\n      \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n    \"node:events\":\n      \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n    \"node:path\":\n      \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n    \"node:fs\": \"data:text/javascript,export default {};\",\n    \"node:url\":\n      \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n    \"node:crypto\":\n      \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n    \"node:os\":\n      \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n    \"node:child_process\": \"data:text/javascript,export default {};\",\n    \"node:http\": \"data:text/javascript,export default {};\",\n    \"node:https\": \"data:text/javascript,export default {};\",\n    \"node:net\": \"data:text/javascript,export default {};\",\n    \"node:tls\": \"data:text/javascript,export default {};\",\n    \"node:zlib\": \"data:text/javascript,export default {};\",\n    \"node:async_hooks\":\n      \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n    \"node:worker_threads\": \"data:text/javascript,export default {};\",\n    \"node:perf_hooks\":\n      \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n    string_decoder:\n      \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n    buffer:\n      \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n    stream:\n      \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n    util: \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n    events:\n      \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n    path: \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n    fs: \"data:text/javascript,export default {};\",\n    url: \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n    crypto:\n      \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n    os: \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n    child_process: \"data:text/javascript,export default {};\",\n    http: \"data:text/javascript,export default {};\",\n    https: \"data:text/javascript,export default {};\",\n    net: \"data:text/javascript,export default {};\",\n    tls: \"data:text/javascript,export default {};\",\n    zlib: \"data:text/javascript,export default {};\",\n    async_hooks:\n      \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n    worker_threads: \"data:text/javascript,export default {};\",\n    perf_hooks:\n      \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n  };\n\n  // Plugin to intercept __vite-browser-external requests\n  const viteBrowserExternalPlugin = {\n    name: \"farm:browser-external-stub\",\n    enforce: \"pre\" as const,\n    resolveId(id: string) {\n      // Handle Vite's browser external markers\n      if (id.includes(\"__vite-browser-external:\")) {\n        const moduleName = id.replace(/__vite-browser-external:/, \"\");\n        const stub = nodeBuiltinStubs[moduleName];\n        if (stub) return stub;\n        // Generic stub for unknown node modules\n        return \"data:text/javascript,export default {};\";\n      }\n      // Handle direct node: imports\n      if (id.startsWith(\"node:\")) {\n        const stub = nodeBuiltinStubs[id];\n        if (stub) return stub;\n        return \"data:text/javascript,export default {};\";\n      }\n      return null;\n    },\n  };\n\n  // Custom logger to replace Vite's default logs with Farm.js branding\n  const pc = createCliColors();\n  let serverStarted = false;\n  let startTime = Date.now();\n\n  const farmLogger = {\n    info: (msg: string) => {\n      // Suppress ALL Vite startup messages - we print our own Farm.js branded output\n      if (\n        msg.includes(\"VITE\") ||\n        msg.includes(\"vite\") ||\n        msg.includes(\"ready in\") ||\n        msg.includes(\"Local:\") ||\n        msg.includes(\"Network:\") ||\n        msg.includes(\"➜\") ||\n        msg.includes(\"Port\") ||\n        msg.includes(\"trying another\")\n      ) {\n        return;\n      }\n      // Pass through other info messages\n      console.log(msg);\n    },\n    warn: (msg: string) => console.warn(pc.yellow(msg)),\n    warnOnce: (msg: string) => console.warn(pc.yellow(msg)),\n    error: (msg: string) => console.error(pc.red(msg)),\n    clearScreen: () => {},\n    hasErrorLogged: () => false,\n    hasWarned: false,\n  };\n\n  // Plugin to print Farm.js branding after server starts\n  const farmBrandingPlugin = {\n    name: \"farm:branding\",\n    enforce: \"pre\" as const,\n    configureServer(server: ViteDevServer) {\n      startTime = Date.now();\n\n      const originalListen = server.listen.bind(server);\n      server.listen = async (port?: number, ...args: any[]) => {\n        const result = await originalListen(port, ...args);\n        if (!serverStarted) {\n          serverStarted = true;\n          const elapsed = Date.now() - startTime;\n          const address = server.httpServer?.address();\n          const resolvedPort =\n            typeof address === \"object\" && address\n              ? address.port\n              : server.config.server.port || port || 3000;\n          const hostConfig = server.config.server.host;\n          const isExposed = hostConfig === true || hostConfig === \"0.0.0.0\";\n\n          console.log(\"\");\n          console.log(\n            `  ${pc.bold(pc.green(\"Farm.js\"))} ${pc.dim(`v${FARM_VERSION}`)} ${pc.dim(`ready in ${elapsed}ms`)}`,\n          );\n          console.log(\"\");\n          console.log(\n            `  ${pc.dim(\"➜\")}  ${pc.bold(\"Local:\")}   ${pc.cyan(`http://localhost:${resolvedPort}/`)}`,\n          );\n          if (isExposed) {\n            // Get actual network address\n            const os = require(\"os\");\n            const interfaces = os.networkInterfaces();\n            for (const name of Object.keys(interfaces)) {\n              for (const iface of interfaces[name] || []) {\n                if (iface.family === \"IPv4\" && !iface.internal) {\n                  console.log(\n                    `  ${pc.dim(\"➜\")}  ${pc.bold(\"Network:\")} ${pc.cyan(`http://${iface.address}:${resolvedPort}/`)}`,\n                  );\n                  break;\n                }\n              }\n            }\n          } else {\n            console.log(\n              `  ${pc.dim(\"➜\")}  ${pc.bold(\"Network:\")} ${pc.dim(\"use --host to expose\")}`,\n            );\n          }\n          console.log(\"\");\n        }\n        return result;\n      };\n    },\n  };\n\n  return {\n    plugins: [\n      createFarmThemeCssPlugin(config.theme, config.basePath),\n      tailwindcss(),\n      ...(rendererVitePlugins as any[]),\n      viteBrowserExternalPlugin,\n      farmI18nClientBridgePlugin(),\n      farmPlugin(config),\n      farmEnvironmentFunctionsPlugin(),\n      farmBrandingPlugin,\n    ],\n    customLogger: farmLogger,\n    clearScreen: false,\n    optimizeDeps: {\n      ...createFarmClientOptimizeDepsConfig(\n        createFarmClientOptimizeDepsEntries(\n          appRoot,\n          getFarmAppDirectories({ ...config, root: appRoot }),\n        ),\n        config.renderer,\n      ),\n      // Pre-bundle every framework client-runtime entry with the renderer. Without\n      // this, Vite can discover a linked Farm entry after the page has loaded,\n      // regenerate the optimizer browser hash, and leave the browser runtime\n      // holding a different renderer instance from a client component.\n      // Exclude server-side packages from browser bundling\n      exclude: [\n        \"@farm.js/core/server\",\n        \"@farm.js/core/api\",\n        \"@farm.js/core/middleware\",\n        \"@farm.js/core/config\",\n        \"nitro\",\n        \"h3\",\n        \"vite\",\n        \"esbuild\",\n        \"rollup\",\n        \"fsevents\",\n        \"nf3\",\n        \"better-call\",\n        \"zod\",\n        \"supports-color\",\n        \"node-fetch\",\n        \"consola\",\n        \"mock-aws-s3\",\n        \"aws-sdk\",\n        \"nock\",\n      ],\n    },\n    ssr: {\n      noExternal: [\"farm\", \"@farm.js/core\"],\n      // Externalize the renderer to prevent multiple runtime instances during SSR.\n      external: [...(config.renderer.dedupe || [])],\n    },\n    resolve: {\n      // Ensure one renderer instance across application and framework modules.\n      dedupe: [...(config.renderer.dedupe || [])],\n      // Stub out problematic server-only modules during dev mode\n      alias: {\n        ...getFarmLayerAliases(config.layers),\n        ...createFarmSourceAlias(appRoot, config.srcDir),\n        // Nitro internals that should not be resolved in browser\n        \"supports-color\":\n          \"data:text/javascript,export default false; export const supportsColor = false; export const stdout = false; export const stderr = false;\",\n        \"@poppinss/dumper\": \"data:text/javascript,export default {};\",\n        \"@poppinss/dumper/html\":\n          \"data:text/javascript,export const createScript = () => ''; export const createStyleSheet = () => '';\",\n        \"consola/basic\":\n          \"data:text/javascript,export default { log: console.log, info: console.info, warn: console.warn, error: console.error };\",\n        youch:\n          \"data:text/javascript,export default class Youch { toJSON() { return {}; } toHTML() { return ''; } };\",\n        // Add all node stubs to alias as well\n        ...nodeBuiltinStubs,\n      },\n    },\n    define: {\n      __FARM_DEV__: JSON.stringify(process.env.NODE_ENV === \"development\"),\n      __FARM_API_BASE_URL__: JSON.stringify(getFarmAPIBaseURLDefine(config)),\n      __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),\n    },\n  };\n}\n","// 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","import { createEndpoint as betterCallEndpoint } from \"better-call\";\nimport { applyFarmCacheInvalidationTargets, type FarmCacheInvalidationTarget } from \"../cache\";\nimport { isMultipartSchema, type MultipartSchema, type TypedFormData } from \"./transport\";\nimport type { RouteSchema, RouteSchemaInput, RouteSchemaOutput } from \"./route-schema\";\n\n// Share the route factory's Zod and Standard Schema contract.\ntype AnySchema = RouteSchema;\n\ntype MaybePromise<T> = T | Promise<T>;\ntype Simplify<T> = { [TKey in keyof T]: T[TKey] } & {};\ntype UnionToIntersection<T> = (T extends unknown ? (value: T) => void : never) extends (\n  value: infer TIntersection,\n) => void\n  ? TIntersection\n  : never;\n\n// Handlers receive parsed output; callers supply the schema input.\ntype InferOutput<T> = RouteSchemaOutput<T>;\n\ntype InferInput<T> = T extends { _input: infer I }\n  ? I\n  : T extends { \"~standard\": unknown }\n    ? RouteSchemaInput<T>\n    : T extends { parse: (data: infer I) => unknown }\n      ? I\n      : unknown;\n\ntype InferBodyInput<T> =\n  T extends MultipartSchema<AnySchema> ? TypedFormData<InferInput<T>> : InferInput<T>;\n\ntype InferHeadersOutput<T> = [T] extends [never]\n  ? Record<string, string>\n  : T extends AnySchema\n    ? InferOutput<T>\n    : Record<string, string>;\n\nexport type EndpointErrorSchema = AnySchema & { parse: (data: unknown) => unknown };\n\ntype EndpointErrorDefinitionBase<TStatus extends number> = {\n  status: TStatus;\n  /** Public message safe to expose to API callers. */\n  message?: string;\n};\n\nexport type EndpointErrorDefinition<\n  TSchema extends EndpointErrorSchema = EndpointErrorSchema,\n  TStatus extends number = number,\n> = EndpointErrorDefinitionBase<TStatus> &\n  (\n    | {\n        /** Schema for the public error payload exposed to API callers. */\n        data: TSchema;\n        schema?: never;\n      }\n    | {\n        data?: never;\n        /** @deprecated Use `data` for consistency with server functions. */\n        schema: TSchema;\n      }\n  );\n\nexport type EndpointErrorDefinitions = Record<\n  string,\n  EndpointErrorDefinition<EndpointErrorSchema, number>\n>;\n\ntype InferEndpointErrorSchema<TDefinition> = TDefinition extends {\n  data: infer TSchema extends AnySchema;\n}\n  ? TSchema\n  : TDefinition extends { schema: infer TSchema extends AnySchema }\n    ? TSchema\n    : never;\n\nexport type EndpointErrorContracts<TErrors extends EndpointErrorDefinitions> = {\n  [TCode in keyof TErrors]: {\n    data: InferOutput<InferEndpointErrorSchema<TErrors[TCode]>>;\n    status: TErrors[TCode][\"status\"];\n  };\n};\n\nexport type EndpointErrorHandler<TErrors extends EndpointErrorDefinitions> = <\n  TCode extends keyof TErrors & string,\n>(\n  code: TCode,\n  data: InferInput<InferEndpointErrorSchema<TErrors[TCode]>>,\n) => never;\n\n/** @deprecated Use `EndpointErrorHandler`. */\nexport type EndpointFail<TErrors extends EndpointErrorDefinitions> = EndpointErrorHandler<TErrors>;\n\nexport class EndpointFailure<TCode extends string = string, TData = unknown> extends Error {\n  readonly code: TCode;\n  readonly data: TData;\n  readonly status: number;\n\n  constructor(\n    code: TCode,\n    data: TData,\n    options: {\n      status: number;\n      message: string;\n    },\n  ) {\n    super(options.message);\n    this.name = \"EndpointFailure\";\n    this.code = code;\n    this.data = data;\n    this.status = options.status;\n  }\n}\n\nexport function isEndpointFailure(value: unknown): value is EndpointFailure<string, unknown> {\n  return value instanceof EndpointFailure;\n}\n\nexport type EndpointParamValue = string | string[];\nexport type EndpointParams = Record<string, EndpointParamValue>;\n\nexport type EndpointMiddlewareContext<\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> = {\n  body: TBody;\n  query: TQuery;\n  headers: THeaders;\n  request: Request;\n  /** Context accumulated from middleware that ran earlier in the chain. */\n  context: Readonly<TContext>;\n  params: EndpointParams;\n};\n\nexport type EndpointMiddlewareResult<TProvidedContext extends object = object> =\n  | TProvidedContext\n  | true\n  | false\n  | Response;\n\n/** A plain async function. No wrapper or `next()` callback is required. */\nexport type EndpointMiddleware<\n  TProvidedContext extends object = object,\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> = (\n  ctx: EndpointMiddlewareContext<TContext, TBody, TQuery, THeaders>,\n) => MaybePromise<EndpointMiddlewareResult<TProvidedContext>>;\n\nexport type AnyEndpointMiddleware = (ctx: EndpointMiddlewareContext<any, any, any, any>) => unknown;\n\nexport type EndpointInvalidationTarget = FarmCacheInvalidationTarget;\n\nexport type EndpointInvalidationContext<\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> = EndpointMiddlewareContext<TContext, TBody, TQuery, THeaders> & {\n  /** The raw value returned by the endpoint handler. */\n  result: unknown;\n};\n\nexport type EndpointInvalidations<\n  TContext extends object = {},\n  TBody = unknown,\n  TQuery = unknown,\n  THeaders = Record<string, string>,\n> =\n  | readonly EndpointInvalidationTarget[]\n  | ((\n      context: EndpointInvalidationContext<TContext, TBody, TQuery, THeaders>,\n    ) => readonly EndpointInvalidationTarget[] | Promise<readonly EndpointInvalidationTarget[]>);\n\ntype ValidateEndpointMiddlewares<TMiddlewares extends readonly AnyEndpointMiddleware[]> = {\n  readonly [TIndex in keyof TMiddlewares]: TMiddlewares[TIndex] extends AnyEndpointMiddleware\n    ? [Awaited<ReturnType<TMiddlewares[TIndex]>>] extends [EndpointMiddlewareResult<object>]\n      ? TMiddlewares[TIndex]\n      : never\n    : never;\n};\n\ntype ContextFromMiddlewareResult<TResult> =\n  Exclude<TResult, Response | boolean> extends infer TContext\n    ? [TContext] extends [never]\n      ? {}\n      : TContext extends object\n        ? TContext\n        : {}\n    : {};\n\ntype ContextFromMiddleware<TMiddleware> = TMiddleware extends (...args: any[]) => infer TResult\n  ? ContextFromMiddlewareResult<Awaited<TResult>>\n  : {};\n\nexport type InferEndpointMiddlewareContext<\n  TMiddlewares extends readonly ((...args: any[]) => any)[],\n  TContext extends object = {},\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n  ? TMiddleware extends (...args: any[]) => any\n    ? TRest extends readonly ((...args: any[]) => any)[]\n      ? InferEndpointMiddlewareContext<\n          TRest,\n          Simplify<TContext & ContextFromMiddleware<TMiddleware>>\n        >\n      : Simplify<TContext>\n    : Simplify<TContext>\n  : number extends TMiddlewares[\"length\"]\n    ? Simplify<TContext & UnionToIntersection<ContextFromMiddleware<TMiddlewares[number]>>>\n    : Simplify<TContext>;\n\nexport type EndpointOptions<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TMiddlewares extends readonly AnyEndpointMiddleware[] = readonly [],\n  TErrors extends EndpointErrorDefinitions = {},\n> = {\n  method?: \"GET\" | \"HEAD\" | \"QUERY\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"OPTIONS\";\n  body?: TBody;\n  query?: TQuery;\n  headers?: THeaders;\n  middleware?: TMiddlewares;\n  /**\n   * Cache keys, tags, and route paths made stale after a successful handler result.\n   * The resolver receives validated input and middleware context.\n   */\n  invalidates?: EndpointInvalidations<\n    InferEndpointMiddlewareContext<TMiddlewares>,\n    InferOutput<TBody>,\n    InferOutput<TQuery>,\n    InferHeadersOutput<THeaders>\n  >;\n  errors?: TErrors;\n  /** @deprecated Use plain functions in `middleware` for Farm endpoint middleware. */\n  use?: any[];\n};\n\nexport type EndpointHandler<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n  TContext extends object = {},\n  TErrors extends EndpointErrorDefinitions = {},\n> = (ctx: {\n  body: InferOutput<TBody>;\n  query: InferOutput<TQuery>;\n  headers: InferHeadersOutput<THeaders>;\n  request: Request;\n  context: Readonly<TContext>;\n  params: EndpointParams;\n  error: EndpointErrorHandler<TErrors>;\n  /** @deprecated Use `error`. */\n  fail: EndpointFail<TErrors>;\n}) => Promise<TResponse> | TResponse;\n\n// Type to represent an endpoint with its input/output types\nexport type TypedEndpoint<\n  TBody = never,\n  TQuery = never,\n  TResponse = any,\n  THeaders = Record<string, string>,\n  TErrors = never,\n  TBodyInput = TBody,\n  TQueryInput = TQuery,\n> = {\n  __types: {\n    body: TBody;\n    inputBody: TBodyInput;\n    query: TQuery;\n    inputQuery: TQueryInput;\n    headers: THeaders;\n    response: TResponse;\n    errors: TErrors;\n  };\n  __path?: string;\n  __method?: string;\n} & ((options?: { body?: TBodyInput; query?: TQueryInput }) => Promise<TResponse>);\n\ntype CreatedEndpoint<\n  TBody extends AnySchema,\n  TQuery extends AnySchema,\n  THeaders extends AnySchema,\n  TResponse,\n  TErrors extends EndpointErrorDefinitions = {},\n> = TypedEndpoint<\n  InferOutput<TBody>,\n  InferOutput<TQuery>,\n  Awaited<TResponse>,\n  InferHeadersOutput<THeaders>,\n  EndpointErrorContracts<TErrors>,\n  InferBodyInput<TBody>,\n  InferInput<TQuery>\n>;\n\ntype AnyEndpointOptions = EndpointOptions<\n  AnySchema,\n  AnySchema,\n  AnySchema,\n  readonly AnyEndpointMiddleware[],\n  EndpointErrorDefinitions\n>;\ntype EndpointBodyFromOptions<TOptions> = TOptions extends {\n  body: infer TBody extends AnySchema;\n}\n  ? TBody\n  : never;\ntype EndpointQueryFromOptions<TOptions> = TOptions extends {\n  query: infer TQuery extends AnySchema;\n}\n  ? TQuery\n  : never;\ntype EndpointHeadersFromOptions<TOptions> = TOptions extends {\n  headers: infer THeaders extends AnySchema;\n}\n  ? THeaders\n  : never;\ntype EndpointMiddlewaresFromOptions<TOptions> = TOptions extends {\n  middleware: infer TMiddlewares extends readonly AnyEndpointMiddleware[];\n}\n  ? TMiddlewares\n  : readonly [];\ntype EndpointErrorsFromOptions<TOptions> = TOptions extends {\n  errors: infer TErrors extends EndpointErrorDefinitions;\n}\n  ? TErrors\n  : {};\ntype MethodlessEndpointOptions = Omit<AnyEndpointOptions, \"method\">;\ntype EndpointHandlerFromOptions<TOptions, TResponse> = EndpointHandler<\n  EndpointBodyFromOptions<TOptions>,\n  EndpointQueryFromOptions<TOptions>,\n  EndpointHeadersFromOptions<TOptions>,\n  TResponse,\n  InferEndpointMiddlewareContext<EndpointMiddlewaresFromOptions<TOptions>>,\n  EndpointErrorsFromOptions<TOptions>\n>;\ntype ValidatedEndpointHandlerFromOptions<TOptions, TResponse> = EndpointHandlerFromOptions<\n  TOptions,\n  TResponse\n> &\n  (EndpointMiddlewaresFromOptions<TOptions> extends ValidateEndpointMiddlewares<\n    EndpointMiddlewaresFromOptions<TOptions>\n  >\n    ? unknown\n    : never);\ntype CreatedEndpointFromOptions<TOptions, TResponse> = CreatedEndpoint<\n  EndpointBodyFromOptions<TOptions>,\n  EndpointQueryFromOptions<TOptions>,\n  EndpointHeadersFromOptions<TOptions>,\n  TResponse,\n  EndpointErrorsFromOptions<TOptions>\n>;\n\n/**\n * Create a Farm.js API endpoint\n *\n * Supports two patterns:\n * 1. File-based routing (path auto-inferred from file location):\n *    `export const POST = createEndpoint({ method: 'POST', body: schema }, handler)`\n *    `createEndpoint({ method: 'GET', query: z.object({...}) }, handler)`\n *\n * 2. Explicit path (for routes.ts at project root):\n *    `createEndpoint('/api/hello', { method: 'GET', query: z.object({...}) }, handler)`\n */\nexport function createEndpoint<const TOptions extends AnyEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function createEndpoint<const TOptions extends AnyEndpointOptions, TResponse = any>(\n  path: string,\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function createEndpoint<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: EndpointOptions<TBody, TQuery, THeaders, readonly []>,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function createEndpoint<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  path: string,\n  options: EndpointOptions<TBody, TQuery, THeaders, readonly []>,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function createEndpoint(\n  pathOrOptions:\n    | string\n    | EndpointOptions<any, any, any, readonly AnyEndpointMiddleware[], EndpointErrorDefinitions>,\n  optionsOrHandler:\n    | EndpointOptions<any, any, any, readonly AnyEndpointMiddleware[], EndpointErrorDefinitions>\n    | EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n  maybeHandler?: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n): TypedEndpoint<any, any, any, any> {\n  // Determine if first arg is path or options\n  let path: string;\n  let options: EndpointOptions<\n    any,\n    any,\n    any,\n    readonly AnyEndpointMiddleware[],\n    EndpointErrorDefinitions\n  >;\n  let handler: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>;\n\n  if (typeof pathOrOptions === \"string\") {\n    // createEndpoint('/path', options, handler)\n    path = pathOrOptions;\n    options = optionsOrHandler as typeof options;\n    handler = maybeHandler as typeof handler;\n  } else {\n    // createEndpoint(options, handler) - path will be set by API plugin from file location\n    path = \"\";\n    options = pathOrOptions;\n    handler = optionsOrHandler as typeof handler;\n  }\n\n  if (typeof handler !== \"function\") {\n    throw new TypeError(\"createEndpoint requires a handler function\");\n  }\n\n  const middleware = normalizeEndpointMiddleware(options.middleware);\n  const errors = normalizeEndpointErrors(options.errors);\n  const error = createEndpointErrorHandler(errors);\n  const wrappedHandler = (async (ctx: EndpointMiddlewareContext<any, any, any, any>) => {\n    const execution = await runEndpointMiddleware(\n      middleware,\n      ctx,\n      handler,\n      error,\n      options.invalidates,\n    );\n    return execution.result;\n  }) as typeof handler;\n  const {\n    middleware: _middleware,\n    errors: _errors,\n    invalidates: _invalidates,\n    ...betterCallOptions\n  } = options;\n\n  // Create the endpoint - path will be set later by API plugin if not provided\n  // We use a temporary path that will be replaced when the router is created\n  const endpoint = betterCallEndpoint(\n    path || \"/__farm_auto_path__\",\n    betterCallOptions as any,\n    wrappedHandler as any,\n  ) as any;\n\n  // Store the path and type information on the endpoint for later access\n  // Empty/undefined path means it will be inferred from file location by the API plugin\n  endpoint.__path = path || undefined;\n  endpoint.__method = options.method || \"GET\";\n  endpoint.__autoPath = !path; // Flag to indicate path should be auto-inferred\n  endpoint.__handler = wrappedHandler; // Used by Farm's route runtime.\n  endpoint.__farmInvoke = (ctx: EndpointMiddlewareContext<any, any, any, any>) =>\n    runEndpointMiddleware(middleware, ctx, handler, error, options.invalidates);\n  endpoint.__middleware = middleware;\n  endpoint.__sourceHandler = handler;\n  endpoint.__invalidates = options.invalidates;\n  endpoint.__errors = errors;\n\n  // Store type information for inference\n  endpoint.__types = {\n    body: options.body,\n    inputBody: isMultipartSchema(options.body) ? \"form-data\" : options.body,\n    query: options.query,\n    inputQuery: options.query,\n    headers: options.headers,\n    response: null as any,\n    errors,\n  };\n\n  return endpoint as any;\n}\n\nconst EMPTY_ENDPOINT_MIDDLEWARE = Object.freeze([]) as readonly AnyEndpointMiddleware[];\nconst EMPTY_ENDPOINT_CONTEXT = Object.freeze(Object.create(null)) as Readonly<\n  Record<string | symbol, unknown>\n>;\nconst UNSAFE_ENDPOINT_CONTEXT_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction normalizeEndpointErrors(\n  definitions: EndpointErrorDefinitions | undefined,\n): Readonly<EndpointErrorDefinitions> {\n  if (definitions === undefined) return Object.freeze({});\n  if (!isPlainEndpointContext(definitions)) {\n    throw new TypeError(\"createEndpoint errors must be an object\");\n  }\n\n  const normalized: EndpointErrorDefinitions = Object.create(null);\n  for (const [code, definition] of Object.entries(definitions)) {\n    if (!code.trim()) {\n      throw new TypeError(\"Endpoint error codes cannot be empty\");\n    }\n    if (!definition || typeof definition !== \"object\") {\n      throw new TypeError(`Endpoint error \"${code}\" must be an object`);\n    }\n    if (\n      !Number.isInteger(definition.status) ||\n      definition.status < 400 ||\n      definition.status > 599\n    ) {\n      throw new TypeError(`Endpoint error \"${code}\" status must be an integer between 400 and 599`);\n    }\n    const dataSchema = resolveEndpointErrorSchema(definition);\n    if (!dataSchema || typeof dataSchema.parse !== \"function\") {\n      throw new TypeError(`Endpoint error \"${code}\" requires a data schema with parse()`);\n    }\n    if (definition.message !== undefined && typeof definition.message !== \"string\") {\n      throw new TypeError(`Endpoint error \"${code}\" message must be a string`);\n    }\n\n    normalized[code] = Object.freeze({ ...definition });\n  }\n\n  return Object.freeze(normalized);\n}\n\nfunction resolveEndpointErrorSchema(\n  definition: EndpointErrorDefinition<EndpointErrorSchema, number>,\n): EndpointErrorSchema | undefined {\n  if (definition.data && definition.schema) {\n    throw new TypeError(\"Endpoint errors cannot define both data and schema\");\n  }\n  return definition.data ?? definition.schema;\n}\n\nfunction createEndpointErrorHandler(\n  definitions: Readonly<EndpointErrorDefinitions>,\n): EndpointErrorHandler<EndpointErrorDefinitions> {\n  return ((code: string, data: unknown): never => {\n    const definition = definitions[code];\n    if (!definition) {\n      throw new TypeError(`Endpoint error \"${code}\" is not declared`);\n    }\n\n    const parsed = resolveEndpointErrorSchema(definition)!.parse(data);\n    throw new EndpointFailure(code, parsed, {\n      status: definition.status,\n      message: definition.message ?? \"Request failed\",\n    });\n  }) as EndpointErrorHandler<EndpointErrorDefinitions>;\n}\n\nfunction normalizeEndpointMiddleware(\n  middleware: readonly AnyEndpointMiddleware[] | undefined,\n): readonly AnyEndpointMiddleware[] {\n  if (middleware === undefined) return EMPTY_ENDPOINT_MIDDLEWARE;\n  if (!Array.isArray(middleware)) {\n    throw new TypeError(\"createEndpoint middleware must be an array of functions\");\n  }\n\n  const normalized = [...middleware];\n  for (const entry of normalized) {\n    if (typeof entry !== \"function\") {\n      throw new TypeError(\"createEndpoint middleware entries must be functions\");\n    }\n  }\n\n  return Object.freeze(normalized);\n}\n\nasync function runEndpointMiddleware(\n  middleware: readonly AnyEndpointMiddleware[],\n  handlerContext: EndpointMiddlewareContext<any, any, any, any>,\n  handler: EndpointHandler<any, any, any, any, any, EndpointErrorDefinitions>,\n  error: EndpointErrorHandler<EndpointErrorDefinitions>,\n  invalidations: EndpointInvalidations<any, any, any, any> | undefined,\n): Promise<{\n  result: unknown;\n  context: Readonly<Record<string | symbol, unknown>>;\n  handlerExecuted: boolean;\n  invalidations: readonly string[];\n}> {\n  let context = createInitialEndpointContext(handlerContext.context);\n\n  for (let index = 0; index < middleware.length; index++) {\n    const result = await middleware[index]({ ...handlerContext, context });\n\n    if (isEndpointResponse(result)) {\n      return {\n        result,\n        context,\n        handlerExecuted: false,\n        invalidations: [],\n      };\n    }\n    if (result === false) {\n      return {\n        result: forbiddenEndpointResponse(),\n        context,\n        handlerExecuted: false,\n        invalidations: [],\n      };\n    }\n    if (result === true) continue;\n\n    if (!isPlainEndpointContext(result)) {\n      throw new TypeError(\n        `Endpoint middleware ${index + 1} must return an object, true, false, or a Response`,\n      );\n    }\n\n    context = mergeEndpointContext(context, result, index);\n  }\n\n  const result = await handler({ ...handlerContext, context, error, fail: error });\n  return {\n    result,\n    context,\n    handlerExecuted: true,\n    invalidations: await applyEndpointInvalidations(\n      invalidations,\n      {\n        ...handlerContext,\n        context,\n        result,\n      },\n      result,\n    ),\n  };\n}\n\nasync function applyEndpointInvalidations(\n  declaration: EndpointInvalidations<any, any, any, any> | undefined,\n  context: EndpointInvalidationContext<any, any, any, any>,\n  result: unknown,\n): Promise<readonly string[]> {\n  if (!declaration || (isEndpointResponse(result) && result.status >= 400)) {\n    return [];\n  }\n\n  const targets = typeof declaration === \"function\" ? await declaration(context) : declaration;\n  if (!Array.isArray(targets)) {\n    throw new TypeError(\n      \"Endpoint invalidates must resolve to an array of { key }, { path }, or { tag } targets\",\n    );\n  }\n\n  return applyFarmCacheInvalidationTargets(targets);\n}\n\nfunction createInitialEndpointContext(value: unknown) {\n  if (value === undefined || value === null) return EMPTY_ENDPOINT_CONTEXT;\n  if (!isPlainEndpointContext(value)) {\n    throw new TypeError(\"Endpoint context must be a plain object\");\n  }\n\n  return mergeEndpointContext(EMPTY_ENDPOINT_CONTEXT, value);\n}\n\nfunction mergeEndpointContext(\n  current: Readonly<Record<string | symbol, unknown>>,\n  added: object,\n  middlewareIndex?: number,\n) {\n  const next = Object.assign(Object.create(null), current) as Record<string | symbol, unknown>;\n\n  for (const key of Reflect.ownKeys(added)) {\n    if (!Object.prototype.propertyIsEnumerable.call(added, key)) continue;\n    if (typeof key === \"string\" && UNSAFE_ENDPOINT_CONTEXT_KEYS.has(key)) {\n      throw new TypeError(`Endpoint middleware cannot provide the unsafe context key \"${key}\"`);\n    }\n    if (Object.prototype.hasOwnProperty.call(current, key)) {\n      const source =\n        middlewareIndex === undefined\n          ? \"Endpoint context\"\n          : `Endpoint middleware ${middlewareIndex + 1}`;\n      throw new TypeError(`${source} cannot replace the existing context key \"${String(key)}\"`);\n    }\n    next[key] = (added as Record<string | symbol, unknown>)[key];\n  }\n\n  return Object.freeze(next);\n}\n\nfunction isPlainEndpointContext(value: unknown): value is object {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction isEndpointResponse(value: unknown): value is Response {\n  return (\n    value instanceof Response ||\n    (typeof value === \"object\" &&\n      value !== null &&\n      \"headers\" in value &&\n      \"status\" in value &&\n      typeof (value as Response).arrayBuffer === \"function\")\n  );\n}\n\nfunction forbiddenEndpointResponse() {\n  return new Response(JSON.stringify({ error: \"Forbidden\" }), {\n    status: 403,\n    headers: { \"Content-Type\": \"application/json\" },\n  });\n}\n\n/**\n * Convenience method for GET requests\n */\nexport function GET<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function GET<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function GET<\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<never, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<never, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<never, TQuery, THeaders, TResponse>;\nexport function GET(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"GET\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"GET\" }, args[1]);\n}\n\n/**\n * Convenience method for HEAD requests\n */\nexport function HEAD<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function HEAD<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function HEAD<\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<never, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<never, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<never, TQuery, THeaders, TResponse>;\nexport function HEAD(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"HEAD\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"HEAD\" }, args[1]);\n}\n\n/**\n * Convenience method for safe, idempotent QUERY requests with a request body\n */\nexport function QUERY<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function QUERY<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function QUERY<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function QUERY(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"QUERY\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"QUERY\" }, args[1]);\n}\n\n/**\n * Convenience method for POST requests\n */\nexport function POST<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function POST<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function POST<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function POST(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"POST\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"POST\" }, args[1]);\n}\n\n/**\n * Convenience method for PUT requests\n */\nexport function PUT<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function PUT<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function PUT<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function PUT(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"PUT\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"PUT\" }, args[1]);\n}\n\n/**\n * Convenience method for DELETE requests\n */\nexport function DELETE<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function DELETE<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function DELETE<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function DELETE(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"DELETE\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"DELETE\" }, args[1]);\n}\n\n/**\n * Convenience method for PATCH requests\n */\nexport function PATCH<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function PATCH<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function PATCH<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function PATCH(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"PATCH\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"PATCH\" }, args[1]);\n}\n\n/**\n * Convenience method for OPTIONS requests\n */\nexport function OPTIONS<T = any>(\n  handler: EndpointHandler<never, never, never, T>,\n): CreatedEndpoint<never, never, never, T>;\nexport function OPTIONS<const TOptions extends MethodlessEndpointOptions, TResponse = any>(\n  options: TOptions,\n  handler: ValidatedEndpointHandlerFromOptions<TOptions, TResponse>,\n): CreatedEndpointFromOptions<TOptions, TResponse>;\nexport function OPTIONS<\n  TBody extends AnySchema = never,\n  TQuery extends AnySchema = never,\n  THeaders extends AnySchema = never,\n  TResponse = any,\n>(\n  options: Omit<EndpointOptions<TBody, TQuery, THeaders, readonly []>, \"method\">,\n  handler: EndpointHandler<TBody, TQuery, THeaders, TResponse>,\n): CreatedEndpoint<TBody, TQuery, THeaders, TResponse>;\nexport function OPTIONS(...args: any[]): any {\n  if (args.length === 1) {\n    return createEndpoint(\"\", { method: \"OPTIONS\" }, args[0]);\n  }\n  return createEndpoint(\"\", { ...args[0], method: \"OPTIONS\" }, args[1]);\n}\n","export type MultipartField = string | number | boolean | bigint | Blob | Date | null | undefined;\n\nexport type MultipartValues = Record<string, MultipartField | readonly MultipartField[]>;\n\n/**\n * A real FormData value that retains the submitted value shape for generated\n * API-client inference.\n */\nexport type TypedFormData<TValues> = FormData & {\n  readonly __farmMultipartInput: TValues;\n};\n\nexport type MultipartSchema<TSchema> = TSchema & {\n  readonly __farmMultipartSchema: true;\n};\n\nexport type FarmStreamResponse<TItem> = Response & {\n  readonly __farmStreamItem: TItem;\n};\n\nexport interface FarmAPIStream<TItem> extends AsyncIterable<TItem> {\n  readonly response: Response;\n  cancel(reason?: unknown): Promise<void>;\n}\n\ntype SchemaLike = {\n  parse(data: unknown): unknown;\n};\n\n/**\n * Mark a body schema as multipart. The handler still receives the schema's\n * parsed object; generated clients require `toFormData(...)` for the request.\n */\nexport function multipart<TSchema extends SchemaLike>(schema: TSchema): MultipartSchema<TSchema> {\n  if (!Object.isExtensible(schema) && !isMultipartSchema(schema)) {\n    throw new TypeError(\"multipart() requires an extensible schema object\");\n  }\n\n  if (!isMultipartSchema(schema)) {\n    Object.defineProperty(schema, \"__farmMultipartSchema\", {\n      value: true,\n      configurable: false,\n      enumerable: false,\n      writable: false,\n    });\n  }\n\n  return schema as MultipartSchema<TSchema>;\n}\n\nexport function isMultipartSchema(value: unknown): value is MultipartSchema<SchemaLike> {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    (value as { __farmMultipartSchema?: unknown }).__farmMultipartSchema === true &&\n    typeof (value as SchemaLike).parse === \"function\"\n  );\n}\n\n/**\n * Encode a typed object as multipart FormData without converting File or Blob\n * values to JSON or base64.\n */\nexport function toFormData<TValues extends MultipartValues>(\n  values: TValues,\n): TypedFormData<TValues> {\n  const formData = new FormData();\n\n  for (const [key, value] of Object.entries(values)) {\n    if (isUnsafeFormKey(key)) continue;\n    if (Array.isArray(value)) {\n      for (const entry of value) appendFormValue(formData, key, entry);\n      continue;\n    }\n    appendFormValue(formData, key, value as MultipartField);\n  }\n\n  return formData as TypedFormData<TValues>;\n}\n\n/**\n * Stream JSON values as newline-delimited JSON. Each source value becomes one\n * independently decodable item instead of buffering the whole response.\n */\nexport function jsonStream<TItem>(\n  source: AsyncIterable<TItem> | Iterable<TItem>,\n  init: ResponseInit = {},\n): FarmStreamResponse<TItem> {\n  const iterator = toAsyncIterator(source);\n  const encoder = new TextEncoder();\n  let finished = false;\n  let cleanup: Promise<unknown> | undefined;\n  const closeSource = (reason?: unknown) =>\n    (cleanup ??= Promise.resolve().then(() => iterator.return?.(reason)));\n\n  const body = new ReadableStream<Uint8Array>(\n    {\n      async pull(controller) {\n        if (finished) return;\n\n        try {\n          const next = await iterator.next();\n          if (finished) return;\n          if (next.done) {\n            finished = true;\n            controller.close();\n            return;\n          }\n          controller.enqueue(encoder.encode(`${JSON.stringify(next.value)}\\n`));\n        } catch (error) {\n          if (finished) return;\n          finished = true;\n          try {\n            await closeSource(error);\n          } catch {\n            // Preserve the serialization/source error that failed the response stream.\n          }\n          controller.error(error);\n        }\n      },\n      async cancel(reason) {\n        finished = true;\n        await closeSource(reason);\n      },\n    },\n    {\n      // Do not read the next application event until the response consumer\n      // requests another chunk.\n      highWaterMark: 0,\n    },\n  );\n  const headers = new Headers(init.headers);\n  if (!headers.has(\"content-type\")) {\n    headers.set(\"content-type\", \"application/x-ndjson; charset=utf-8\");\n  }\n  headers.set(\"cache-control\", headers.get(\"cache-control\") ?? \"no-store\");\n\n  return new Response(body, {\n    ...init,\n    headers,\n  }) as FarmStreamResponse<TItem>;\n}\n\nexport function isJSONStreamResponse(response: { headers?: Pick<Headers, \"get\"> | null }): boolean {\n  const contentType = response.headers?.get?.(\"content-type\")?.toLowerCase() ?? \"\";\n  return contentType.includes(\"application/x-ndjson\") || contentType.includes(\"application/ndjson\");\n}\n\n/**\n * Decode a Farm JSON stream lazily. The response body is read only as the\n * consumer advances the async iterator, preserving fetch backpressure.\n */\nexport function readJSONStream<TItem>(response: Response): FarmAPIStream<TItem> {\n  if (!response.body) {\n    throw new TypeError(\"Cannot read a JSON stream response without a body\");\n  }\n\n  const reader = response.body.getReader();\n  const decoder = new TextDecoder();\n  let buffer = \"\";\n  let completed = false;\n  let cancelled = false;\n  let claimed = false;\n  let released = false;\n\n  const releaseReader = () => {\n    if (released) return;\n    released = true;\n    reader.releaseLock();\n  };\n  const parseLine = async (line: string) => {\n    try {\n      return JSON.parse(line) as TItem;\n    } catch (error) {\n      completed = true;\n      buffer = \"\";\n      // A tee branch can wait for an unread sibling during cancellation. The\n      // parse failure is already known and must not wait for producer cleanup.\n      void reader.cancel(error).catch(() => {});\n      releaseReader();\n      throw error;\n    }\n  };\n\n  const readNext = async (): Promise<IteratorResult<TItem>> => {\n    while (true) {\n      if (cancelled) return { done: true, value: undefined };\n      const lineEnd = buffer.indexOf(\"\\n\");\n      if (lineEnd >= 0) {\n        const line = buffer.slice(0, lineEnd).trim();\n        buffer = buffer.slice(lineEnd + 1);\n        if (!line) continue;\n        return { done: false, value: await parseLine(line) };\n      }\n\n      if (completed) {\n        const line = buffer.trim();\n        buffer = \"\";\n        if (!line) {\n          releaseReader();\n          return { done: true, value: undefined };\n        }\n        return { done: false, value: await parseLine(line) };\n      }\n\n      let chunk: ReadableStreamReadResult<Uint8Array>;\n      try {\n        chunk = await reader.read();\n      } catch (error) {\n        if (cancelled) return { done: true, value: undefined };\n        completed = true;\n        buffer = \"\";\n        releaseReader();\n        throw error;\n      }\n      if (cancelled) return { done: true, value: undefined };\n      completed = chunk.done;\n      buffer += decoder.decode(chunk.value, { stream: !chunk.done });\n    }\n  };\n\n  let readQueue = Promise.resolve();\n  const iterator: AsyncIterator<TItem> = {\n    next() {\n      const result = readQueue.then(readNext);\n      // A failed read must not poison subsequent operations on this iterator.\n      readQueue = result.then(\n        () => {},\n        () => {},\n      );\n      return result;\n    },\n    async return() {\n      cancelled = true;\n      completed = true;\n      buffer = \"\";\n      if (!released) {\n        try {\n          await reader.cancel();\n        } finally {\n          releaseReader();\n        }\n      }\n      return { done: true, value: undefined };\n    },\n  };\n\n  return {\n    response,\n    async cancel(reason) {\n      // Cancellation must interrupt the active reader, not wait in its queue.\n      cancelled = true;\n      completed = true;\n      buffer = \"\";\n      if (!released) {\n        try {\n          await reader.cancel(reason);\n        } finally {\n          releaseReader();\n        }\n      }\n    },\n    [Symbol.asyncIterator]() {\n      if (claimed) {\n        throw new TypeError(\"Farm API streams can only be consumed once\");\n      }\n      claimed = true;\n      return iterator;\n    },\n  };\n}\n\nexport function isFarmAPIStream(value: unknown): value is FarmAPIStream<unknown> {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"response\" in value &&\n    typeof (value as FarmAPIStream<unknown>).cancel === \"function\" &&\n    typeof (value as FarmAPIStream<unknown>)[Symbol.asyncIterator] === \"function\"\n  );\n}\n\nfunction appendFormValue(formData: FormData, key: string, value: MultipartField): void {\n  if (value === undefined) return;\n  if (value === null) {\n    formData.append(key, \"\");\n    return;\n  }\n  if (value instanceof Blob) {\n    formData.append(key, value);\n    return;\n  }\n  if (value instanceof Date) {\n    formData.append(key, value.toISOString());\n    return;\n  }\n  formData.append(key, String(value));\n}\n\nfunction isUnsafeFormKey(key: string): boolean {\n  return key === \"__proto__\" || key === \"constructor\" || key === \"prototype\";\n}\n\nfunction toAsyncIterator<TItem>(\n  source: AsyncIterable<TItem> | Iterable<TItem>,\n): AsyncIterator<TItem> {\n  if (Symbol.asyncIterator in Object(source)) {\n    return (source as AsyncIterable<TItem>)[Symbol.asyncIterator]();\n  }\n\n  const iterator = (source as Iterable<TItem>)[Symbol.iterator]();\n  return {\n    next: async () => iterator.next(),\n    return: iterator.return ? async (value?: unknown) => iterator.return!(value) : undefined,\n  };\n}\n","import {\n  createEndpoint,\n  type TypedEndpoint,\n  type AnyEndpointMiddleware,\n  type EndpointMiddlewareResult,\n  type InferEndpointMiddlewareContext,\n} from \"./endpoint\";\nimport {\n  assertBrowserStableRoutePath,\n  assertUniqueRouteParameters,\n  getRoutePatternShape,\n} from \"../routing/specificity\";\nimport type { RouteSchema, RouteSchemaInput, RouteSchemaOutput } from \"./route-schema\";\n\nexport type RouteMethod =\n  | \"GET\"\n  | \"HEAD\"\n  | \"QUERY\"\n  | \"POST\"\n  | \"PUT\"\n  | \"PATCH\"\n  | \"DELETE\"\n  | \"OPTIONS\";\nexport type RoutePathParams<Path extends string> = Path extends `${infer Head}/${infer Tail}`\n  ? RoutePathParams<Head> & RoutePathParams<Tail>\n  : Path extends `[[...${infer Name}]]`\n    ? { [K in Name]?: string[] }\n    : Path extends `[...${infer Name}]`\n      ? { [K in Name]: string[] }\n      : Path extends `[${infer Name}]`\n        ? { [K in Name]: string }\n        : {};\n\nexport interface RouteInputSchemas {\n  body?: RouteSchema;\n  query?: RouteSchema;\n  params?: RouteSchema;\n  headers?: RouteSchema;\n}\ntype Input<I, K extends PropertyKey> = K extends keyof I ? RouteSchemaInput<I[K]> : never;\ntype Output<I, K extends PropertyKey, Fallback = unknown> = K extends keyof I\n  ? RouteSchemaOutput<I[K]>\n  : Fallback;\n/** JSON responses have wire types, not server-side instances such as Date. */\nexport type RouteJSON<T> = T extends Response\n  ? unknown\n  : T extends { toJSON(): infer J }\n    ? RouteJSON<J>\n    : T extends bigint | symbol | ((...args: any[]) => any)\n      ? never\n      : T extends readonly (infer V)[]\n        ? RouteJSON<V>[]\n        : T extends object\n          ? { [K in keyof T]: RouteJSON<T[K]> }\n          : T;\n\nexport type RouteDefinition<\n  P extends string = string,\n  M extends RouteMethod = RouteMethod,\n  E = any,\n> = {\n  readonly path: P;\n  readonly method: M;\n  readonly endpoint: E;\n};\n\ntype RouteEndpoint<P extends string, I extends RouteInputSchemas, R> = TypedEndpoint<\n  Output<I, \"body\">,\n  Input<I, \"query\">,\n  RouteJSON<R>,\n  Input<I, \"headers\">,\n  never,\n  Input<I, \"body\">\n> & {\n  __types: { params: RoutePathParams<P>; inputHeaders: Input<I, \"headers\"> };\n};\n\ntype TrimStart<P extends string> = P extends `/${infer Rest}` ? TrimStart<Rest> : P;\ntype Join<P extends string, C extends string> = C extends \"\" ? P : `${P}/${TrimStart<C>}`;\ntype ParamsCheck<P extends string, I extends RouteInputSchemas> = I extends { params: infer S }\n  ? Exclude<keyof RoutePathParams<P>, keyof RouteSchemaOutput<S>> extends never\n    ? Exclude<keyof RouteSchemaOutput<S>, keyof RoutePathParams<P>> extends never\n      ? unknown\n      : { __error_unknown_route_params: never }\n    : { __error_missing_route_params: never }\n  : unknown;\n\ntype RouteMiddlewareResults = readonly (\n  | EndpointMiddlewareResult\n  | Promise<EndpointMiddlewareResult>\n)[];\n// Infer callback results directly so inline middleware is contextually typed before\n// its returned context is exposed to the route handler.\ntype RouteMiddlewares<Results extends readonly unknown[]> = {\n  readonly [K in keyof Results]: (context: Parameters<AnyEndpointMiddleware>[0]) => Results[K];\n};\n\nexport type RouteOptions<\n  P extends string,\n  I extends RouteInputSchemas,\n  O extends RouteSchema | undefined,\n  R,\n  MiddlewareResults extends RouteMiddlewareResults = RouteMiddlewareResults,\n> = {\n  input?: I & ParamsCheck<P, I>;\n  /** Validate plain JSON handler results. Raw Response/stream results are never buffered. */\n  output?: O;\n  middleware?: RouteMiddlewares<MiddlewareResults>;\n  handler(\n    request: Request,\n    context: {\n      input: {\n        body: Output<I, \"body\">;\n        query: Output<I, \"query\", Record<string, string | string[]>>;\n        headers: Output<I, \"headers\", Record<string, string>>;\n        params: Output<I, \"params\", RoutePathParams<P>>;\n      };\n      params: Output<I, \"params\", RoutePathParams<P>>;\n      context: Readonly<InferEndpointMiddlewareContext<RouteMiddlewares<MiddlewareResults>>>;\n    },\n  ): R | Promise<R>;\n};\n\ntype RouteBuilder<P extends string, M extends RouteMethod> = <\n  const C extends string,\n  const MiddlewareResults extends RouteMiddlewareResults,\n  const I extends RouteInputSchemas = {},\n  O extends RouteSchema | undefined = undefined,\n  R = unknown,\n>(\n  path: C,\n  options: RouteOptions<Join<P, C>, I, O, R, MiddlewareResults>,\n) => RouteDefinition<\n  Join<P, C>,\n  M,\n  RouteEndpoint<\n    Join<P, C>,\n    I,\n    Extract<Awaited<R>, Response> extends never\n      ? O extends RouteSchema\n        ? RouteSchemaOutput<O>\n        : Awaited<R>\n      : unknown\n  >\n>;\n\nexport type RouteFactory<P extends string = \"\"> = {\n  [M in Lowercase<RouteMethod>]: RouteBuilder<P, Uppercase<M> & RouteMethod>;\n} & {\n  /** Return a new builder; never mutate the parent scope. */\n  scope<const C extends string>(path: C): RouteFactory<Join<P, C>>;\n};\n\nexport type PluginRoutes = readonly RouteDefinition[];\nexport type PluginRoutesFactory<R extends PluginRoutes = PluginRoutes> = (context: {\n  route: RouteFactory;\n}) => R;\n\nexport function createRouteFactory(): RouteFactory {\n  return createRouteFactoryAt(\"\");\n}\n\nfunction createRouteFactoryAt(prefix: string): RouteFactory {\n  const factory: Record<string, unknown> = {\n    scope(child: string) {\n      return createRouteFactoryAt(joinRoutePath(prefix, child));\n    },\n  };\n  for (const method of [\n    \"GET\",\n    \"HEAD\",\n    \"QUERY\",\n    \"POST\",\n    \"PUT\",\n    \"PATCH\",\n    \"DELETE\",\n    \"OPTIONS\",\n  ] as const) {\n    factory[method.toLowerCase()] = (\n      child: string,\n      options: RouteOptions<string, any, any, any>,\n    ) => {\n      const path = joinRoutePath(prefix, child);\n      const input = options.input ?? {};\n      const endpoint = createEndpoint(\n        path,\n        {\n          method,\n          body: input.body,\n          query: input.query,\n          headers: input.headers,\n          middleware: options.middleware,\n        },\n        (ctx) =>\n          options.handler(ctx.request, {\n            input: { body: ctx.body, query: ctx.query, headers: ctx.headers, params: ctx.params },\n            params: ctx.params,\n            context: ctx.context,\n          }),\n      ) as any;\n      endpoint.__types.params = input.params;\n      endpoint.__output = options.output;\n      return Object.freeze({ path, method, endpoint });\n    };\n  }\n  return Object.freeze(factory) as RouteFactory;\n}\n\nfunction joinRoutePath(prefix: string, child: string): string {\n  if (typeof child !== \"string\") throw new TypeError(\"Route paths must be strings.\");\n  const path = child === \"\" ? prefix : `${prefix}/${child.replace(/^\\//, \"\")}`;\n  if (!(path === \"/api\" || path.startsWith(\"/api/\")) || /[?#]|\\/\\/|\\/$/.test(path)) {\n    throw new TypeError(\n      `Plugin route \"${path}\" must be a canonical /api path without a query, hash, or empty segment.`,\n    );\n  }\n  assertBrowserStableRoutePath(path);\n  assertUniqueRouteParameters(path, \"api\");\n  getRoutePatternShape(path, \"api\");\n  for (const segment of path.split(\"/\")) {\n    if ([\"__proto__\", \"constructor\", \"prototype\", \"$params\"].includes(segment)) {\n      throw new TypeError(`Route segment \"${segment}\" is reserved.`);\n    }\n  }\n  return path;\n}\n\ntype UnionToIntersection<U> = (U extends unknown ? (v: U) => void : never) extends (\n  v: infer I,\n) => void\n  ? I\n  : never;\ntype RouteTree<P extends string, M extends string, E> = P extends `${infer Head}/${infer Tail}`\n  ? { [K in Head]: RouteTree<Tail, M, E> }\n  : P extends \"\"\n    ? { [K in Lowercase<M>]: E }\n    : { [K in P]: { [Method in Lowercase<M>]: E } };\ntype HasMethodSegment<P extends string> = P extends `${infer H}/${infer T}`\n  ? H extends Lowercase<RouteMethod>\n    ? true\n    : HasMethodSegment<T>\n  : P extends Lowercase<RouteMethod>\n    ? true\n    : false;\ntype DefinitionTree<D> =\n  D extends RouteDefinition<infer P, infer M, infer E>\n    ? string extends P\n      ? {}\n      : (P extends `/api/integrations${string}` ? true : HasMethodSegment<P>) extends true\n        ? { [K in P extends `/api/${infer C}` ? `/${C}` : \"/\"]: { [Method in Lowercase<M>]: E } }\n        : RouteTree<P extends `/api/${infer C}` ? C : \"\", M, E>\n    : {};\nexport type PluginAPIRouter<C> = C extends { plugins: readonly (infer P)[] }\n  ? UnionToIntersection<\n      P extends { routes?: PluginRoutesFactory<infer R> } ? DefinitionTree<R[number]> : {}\n    >\n  : {};\n\nexport function resolvePluginRoutes(\n  plugins: readonly { name: string; routes?: PluginRoutesFactory }[] = [],\n): PluginRoutes {\n  return plugins.flatMap((plugin) => {\n    if (!plugin.routes) return [];\n    const routes = plugin.routes({ route: createRouteFactory() });\n    if (!Array.isArray(routes))\n      throw new TypeError(`Plugin \"${plugin.name}\" routes must return an array synchronously.`);\n    for (const route of routes) {\n      if (\n        !route ||\n        joinRoutePath(\"\", route.path) !== route.path ||\n        typeof route.endpoint !== \"function\" ||\n        ![\"GET\", \"HEAD\", \"QUERY\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\"].includes(\n          route.method,\n        )\n      ) {\n        throw new TypeError(`Plugin \"${plugin.name}\" returned an invalid API route.`);\n      }\n    }\n    return routes;\n  });\n}\n","import { resolvePluginRoutes, type PluginRoutesFactory } from \"./route\";\nimport { registerAPIRouteShape } from \"./route-shape\";\n\ninterface MountedRoute {\n  path: string;\n  methods: string[];\n  endpoints: Record<string, any>;\n  filePath?: string;\n  pluginMethods?: string[];\n}\n\n/** The same registration step is used by dev discovery and the production bundle. */\nexport function mergePluginAPIRoutes(\n  existing: readonly MountedRoute[],\n  plugins: readonly { name: string; routes?: PluginRoutesFactory }[],\n  expected?: readonly { path: string; methods: readonly string[] }[],\n): Array<MountedRoute & { filePath: string }> {\n  const routes = new Map<string, MountedRoute & { filePath: string }>();\n  const shapes = new Map();\n  for (const route of existing) {\n    registerAPIRouteShape(shapes, route.path, route.filePath || route.path, \"app\");\n    routes.set(route.path, {\n      ...route,\n      filePath: route.filePath || \"\",\n      methods: [...route.methods],\n      endpoints: { ...route.endpoints },\n    });\n  }\n  for (const definition of resolvePluginRoutes(plugins)) {\n    registerAPIRouteShape(shapes, definition.path, `plugin:${definition.path}`, \"app\");\n    let route = routes.get(definition.path);\n    if (route?.methods.includes(definition.method)) {\n      throw new Error(\n        `Duplicate API route for ${definition.method} ${definition.path}. Plugin routes cannot override app or other plugin endpoints.`,\n      );\n    }\n    if (!route) {\n      route = { path: definition.path, filePath: \"\", methods: [], endpoints: {} };\n      routes.set(definition.path, route);\n    }\n    route.methods.push(definition.method);\n    route.pluginMethods = [...(route.pluginMethods ?? []), definition.method];\n    route.endpoints[definition.method] = definition.endpoint;\n  }\n  const result = [...routes.values()];\n  if (expected) {\n    const signature = (entries: readonly { path: string; methods: readonly string[] }[]) =>\n      entries\n        .map(({ path, methods }) => `${path}:${[...methods].sort().join(\",\")}`)\n        .sort()\n        .join(\"\\n\");\n    if (signature(result) !== signature(expected)) {\n      throw new Error(\n        \"Plugin API routes changed between build and runtime. Route paths and methods must be stable across environments; rebuild the app.\",\n      );\n    }\n  }\n  return result;\n}\n","import { mergePluginAPIRoutes } from \"./plugin-route-runtime\";\nimport type { FarmPlugin } from \"../plugin\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { logger } from \"../utils\";\nimport type { ProgrammaticApiRoute } from \"../routes\";\nimport { createProgrammaticRouteModuleId } from \"../routes-shared\";\nimport { findProgrammaticRouteFilesInDir } from \"../routes.server\";\nimport {\n  getFarmRouteRuntimeConfig,\n  normalizeFarmRouteRuntimeConfig,\n  type FarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport { _runWithFarmI18nRequest, type FarmI18nRuntime } from \"../i18n/server\";\nimport {\n  getAllowedAPIRouteMethods,\n  invokeAPIRouteEndpoint,\n  registerAPIRouteShape,\n  type APIRouteShapeSource,\n  matchAPIRouteAtBasePath,\n  matchAPIRoute,\n  resolveAPIRouteEndpoint,\n  type APIRouteMatch,\n} from \"./runtime\";\nimport { isFarmAPIRouteFileName } from \"./route-files\";\nimport { AmbiguousRouteError, NonTerminalCatchAllRouteError } from \"../routing/specificity\";\n\nexport interface APIRoute extends FarmRouteRuntimeConfig {\n  pluginMethods?: string[];\n  path: string;\n  filePath: string;\n  methods: string[];\n  endpoints: Record<string, any>;\n}\n\nexport interface APIRouteManagerOptions {\n  plugins?: readonly FarmPlugin[];\n  throwOnLoadError?: boolean;\n  i18n?: FarmI18nRuntime;\n  bodySizeLimit?: number;\n  /** Same-origin path where canonical `/api` routes are served. */\n  basePath?: string;\n}\n\nexport interface APIRouteHandlerOptions {\n  /** Let a framework request boundary report the original endpoint error. */\n  throwOnError?: boolean;\n}\n\nexport class APIRouteConflictError extends Error {\n  constructor(routePath: string, method: string, existingFile: string, conflictingFile: string) {\n    super(\n      `Duplicate API route for ${method.toUpperCase()} ${routePath}: ${existingFile} conflicts with ${conflictingFile}`,\n    );\n    this.name = \"APIRouteConflictError\";\n  }\n}\n\nexport const API_ROUTE_METHODS = [\n  \"GET\",\n  \"HEAD\",\n  \"QUERY\",\n  \"POST\",\n  \"PUT\",\n  \"DELETE\",\n  \"PATCH\",\n  \"OPTIONS\",\n] as const;\n\nexport class APIRouteManager {\n  private plugins: readonly FarmPlugin[];\n  private routes: Map<string, APIRoute> = new Map();\n  private endpointSources: Map<string, Map<string, { appDir: string; filePath: string }>> =\n    new Map();\n  private routeShapes = new Map<string, APIRouteShapeSource<string>>();\n  private viteServer?: ViteDevServer;\n  private appDirs: string[];\n  private throwOnLoadError: boolean;\n  private i18n?: FarmI18nRuntime;\n  private bodySizeLimit?: number;\n  private basePath?: string;\n\n  constructor(\n    appDir: string | readonly string[],\n    viteServer?: ViteDevServer,\n    options: APIRouteManagerOptions = {},\n  ) {\n    this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n    this.viteServer = viteServer;\n    this.plugins = options.plugins ?? [];\n    this.throwOnLoadError = options.throwOnLoadError === true;\n    this.i18n = options.i18n;\n    this.bodySizeLimit = options.bodySizeLimit;\n    this.basePath = options.basePath;\n  }\n\n  /**\n   * Discover route.ts files in /app/api and explicit endpoints in root routes.ts\n   */\n  async discoverRoutes(): Promise<void> {\n    const previousRoutes = this.routes;\n    const previousEndpointSources = this.endpointSources;\n    const previousRouteShapes = this.routeShapes;\n    this.routes = new Map();\n    this.endpointSources = new Map();\n    this.routeShapes = new Map();\n\n    try {\n      for (const appDir of this.appDirs) {\n        const apiDir = path.join(appDir, \"api\");\n        let routeFiles: string[] = [];\n\n        if (fs.existsSync(apiDir)) {\n          routeFiles = this.findRouteFiles(apiDir);\n        }\n\n        for (const filePath of routeFiles) {\n          await this.loadRoute(filePath, appDir);\n        }\n\n        await this.loadRootRoutes(appDir);\n        await this.loadProgrammaticApiRoutes(appDir);\n      }\n      this.routes = new Map(\n        mergePluginAPIRoutes([...this.routes.values()], this.plugins).map((route) => [\n          route.path,\n          route,\n        ]),\n      );\n    } catch (error) {\n      this.routes = previousRoutes;\n      this.endpointSources = previousEndpointSources;\n      this.routeShapes = previousRouteShapes;\n      throw error;\n    }\n\n    if (process.env.FARM_VERBOSE) {\n      logger.success(`Discovered ${this.routes.size} API routes`);\n      for (const [routePath, route] of this.routes) {\n        logger.info(`  ${route.methods.join(\", \")} ${routePath}`);\n      }\n    }\n  }\n\n  /**\n   * Recursively find all route.ts files\n   */\n  private findRouteFiles(dir: string): string[] {\n    const files: string[] = [];\n\n    if (!fs.existsSync(dir)) {\n      return files;\n    }\n\n    const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n    for (const entry of entries) {\n      const fullPath = path.join(dir, entry.name);\n\n      if (entry.isDirectory()) {\n        files.push(...this.findRouteFiles(fullPath));\n      } else if (isFarmAPIRouteFileName(entry.name)) {\n        files.push(fullPath);\n      }\n    }\n\n    return files;\n  }\n\n  /**\n   * Load a route.ts file and extract HTTP method exports\n   */\n  private async loadRoute(filePath: string, appDir: string): Promise<void> {\n    try {\n      // Convert file path to API route path\n      // /app/api/auth/login/route.ts -> /api/auth/login\n      const apiDir = path.join(appDir, \"api\");\n      const relativePath = path.relative(apiDir, path.dirname(filePath));\n      const routePath = \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n\n      const routeModule = await this.loadModule(filePath);\n\n      const endpoints: Record<string, any> = {};\n      const availableMethods: string[] = [];\n\n      for (const method of API_ROUTE_METHODS) {\n        if (routeModule[method]) {\n          endpoints[method] = routeModule[method];\n          availableMethods.push(method);\n        }\n      }\n\n      if (availableMethods.length > 0) {\n        const existingSources = this.endpointSources.get(routePath);\n        if (existingSources) {\n          for (const method of availableMethods) {\n            const existingSource = existingSources.get(method);\n            if (existingSource?.appDir === appDir) {\n              throw new APIRouteConflictError(routePath, method, existingSource.filePath, filePath);\n            }\n          }\n        }\n        const runtimeConfig = normalizeFarmRouteRuntimeConfig(\n          getFarmRouteRuntimeConfig(routeModule),\n          `API route \"${routePath}\"`,\n        );\n        this.registerRouteShape(routePath, filePath, appDir);\n        const existingRoute = this.routes.get(routePath);\n        const mergedMethods = existingRoute ? [...existingRoute.methods] : [];\n        for (const method of availableMethods) {\n          if (!mergedMethods.includes(method)) mergedMethods.push(method);\n        }\n        this.routes.set(routePath, {\n          ...existingRoute,\n          path: routePath,\n          filePath,\n          methods: mergedMethods,\n          endpoints: { ...existingRoute?.endpoints, ...endpoints },\n          ...runtimeConfig,\n        });\n        const nextSources = new Map(existingSources);\n        for (const method of availableMethods) {\n          nextSources.set(method, { appDir, filePath });\n        }\n        this.endpointSources.set(routePath, nextSources);\n      }\n    } catch (error) {\n      this.handleLoadError(`Error loading route ${filePath}`, error);\n    }\n  }\n\n  /**\n   * Load explicit-path endpoints from src/routes.ts-style files.\n   */\n  private async loadRootRoutes(appDir: string): Promise<void> {\n    const routesFile = this.findRootRoutesFile(appDir);\n    if (!routesFile) {\n      return;\n    }\n\n    try {\n      const routesModule = await this.loadModule(routesFile);\n\n      for (const exportValue of Object.values(routesModule)) {\n        const endpoint = exportValue as any;\n        if (!endpoint?.__path) {\n          continue;\n        }\n\n        const method = String(endpoint.__method || \"GET\").toUpperCase();\n        this.registerRouteShape(endpoint.__path, routesFile, appDir);\n        this.addEndpoint(endpoint.__path, routesFile, method, endpoint, appDir);\n      }\n    } catch (error) {\n      this.handleLoadError(`Error loading root API routes ${routesFile}`, error);\n    }\n  }\n\n  private async loadProgrammaticApiRoutes(appDir: string): Promise<void> {\n    const candidateRoots = [path.dirname(appDir), appDir];\n    const routeFiles = Array.from(\n      new Set(candidateRoots.flatMap((srcRoot) => findProgrammaticRouteFilesInDir(srcRoot))),\n    );\n    if (routeFiles.length === 0) return;\n\n    const { getProgrammaticRouteManifest } = await import(\"../routes\");\n\n    for (const routeFile of routeFiles) {\n      try {\n        const routesModule = await this.loadModule(routeFile);\n        const manifest = getProgrammaticRouteManifest(routesModule);\n        if (!manifest) continue;\n\n        for (const definition of manifest.routes) {\n          if (definition.kind !== \"api\") continue;\n          if (!Object.values(definition.methods).some(Boolean)) continue;\n          this.addProgrammaticApiRoute(routeFile, definition, appDir);\n        }\n      } catch (error) {\n        this.handleLoadError(`Error loading programmatic API routes ${routeFile}`, error);\n      }\n    }\n  }\n\n  private handleLoadError(message: string, error: unknown): void {\n    logger.error(`${message}: ${error}`);\n    if (\n      this.throwOnLoadError ||\n      error instanceof APIRouteConflictError ||\n      error instanceof AmbiguousRouteError ||\n      error instanceof NonTerminalCatchAllRouteError\n    ) {\n      throw error;\n    }\n  }\n\n  private findRootRoutesFile(appDir: string): string | null {\n    const routeNames = [\"routes.ts\", \"routes.tsx\", \"routes.js\"];\n    const candidateDirs = [path.dirname(appDir), appDir];\n    const seen = new Set<string>();\n\n    for (const dir of candidateDirs) {\n      for (const routeName of routeNames) {\n        const routesFile = path.join(dir, routeName);\n        if (seen.has(routesFile)) {\n          continue;\n        }\n        seen.add(routesFile);\n\n        if (fs.existsSync(routesFile)) {\n          return routesFile;\n        }\n      }\n    }\n\n    return null;\n  }\n\n  private async loadModule(filePath: string): Promise<Record<string, unknown>> {\n    if (this.viteServer) {\n      return await this.viteServer.ssrLoadModule(filePath);\n    }\n\n    const fileUrl = `file://${filePath}`;\n    return await import(/* @vite-ignore */ fileUrl);\n  }\n\n  private addEndpoint(\n    routePath: string,\n    filePath: string,\n    method: string,\n    endpoint: any,\n    appDir: string,\n    runtimeConfig: FarmRouteRuntimeConfig = {},\n  ): void {\n    const normalizedMethod = method.toUpperCase();\n    const existingRoute = this.routes.get(routePath);\n    const existingSource = this.endpointSources.get(routePath)?.get(normalizedMethod);\n\n    if (existingSource?.appDir === appDir) {\n      throw new APIRouteConflictError(\n        routePath,\n        normalizedMethod,\n        existingSource.filePath,\n        filePath,\n      );\n    }\n\n    if (existingRoute) {\n      if (!existingRoute.methods.includes(normalizedMethod)) {\n        existingRoute.methods.push(normalizedMethod);\n      }\n      existingRoute.endpoints[normalizedMethod] = endpoint;\n      Object.assign(existingRoute, runtimeConfig);\n      const sources = this.endpointSources.get(routePath) ?? new Map();\n      sources.set(normalizedMethod, { appDir, filePath });\n      this.endpointSources.set(routePath, sources);\n      return;\n    }\n\n    this.routes.set(routePath, {\n      path: routePath,\n      filePath,\n      methods: [normalizedMethod],\n      endpoints: { [normalizedMethod]: endpoint },\n      ...runtimeConfig,\n    });\n    this.endpointSources.set(routePath, new Map([[normalizedMethod, { appDir, filePath }]]));\n  }\n\n  private addProgrammaticApiRoute(\n    filePath: string,\n    route: ProgrammaticApiRoute,\n    appDir: string,\n  ): void {\n    const modulePath = createProgrammaticRouteModuleId(filePath, \"api\", route.path);\n    const runtimeConfig = normalizeFarmRouteRuntimeConfig(route, `API route \"${route.path}\"`);\n    for (const [method, endpoint] of Object.entries(route.methods)) {\n      if (endpoint) {\n        this.addEndpoint(route.path, modulePath, method, endpoint, appDir, runtimeConfig);\n      }\n    }\n  }\n\n  private registerRouteShape(routePath: string, filePath: string, appDir: string): void {\n    const replacedPath = registerAPIRouteShape(this.routeShapes, routePath, filePath, appDir);\n    if (replacedPath) {\n      this.routes.delete(replacedPath);\n      this.endpointSources.delete(replacedPath);\n    }\n  }\n\n  /**\n   * Get the handler that directly invokes endpoint handlers\n   */\n  getHandler(options: APIRouteHandlerOptions = {}): ((req: Request) => Promise<Response>) | null {\n    if (this.routes.size === 0) {\n      return null;\n    }\n\n    return async (request: Request): Promise<Response> => {\n      const url = new URL(request.url);\n      const pathname = url.pathname;\n      const method = request.method.toUpperCase();\n\n      // Find matching route\n      const match = matchAPIRouteAtBasePath(this.routes, pathname, this.basePath);\n      if (!match) {\n        return new Response(JSON.stringify({ error: \"Not Found\" }), {\n          status: 404,\n          headers: { \"Content-Type\": \"application/json\" },\n        });\n      }\n\n      // Check if method is supported\n      const { route, params } = match;\n      const endpoint = resolveAPIRouteEndpoint(route, method);\n      if (!endpoint) {\n        return new Response(JSON.stringify({ error: \"Method Not Allowed\" }), {\n          status: 405,\n          headers: {\n            Allow: getAllowedAPIRouteMethods(route).join(\", \"),\n            \"Content-Type\": \"application/json\",\n          },\n        });\n      }\n\n      const invoke = async () => {\n        try {\n          return await invokeAPIRouteEndpoint(endpoint, request, params, this.bodySizeLimit);\n        } catch (error: any) {\n          if (options.throwOnError) throw error;\n          console.error(`[API Error] ${pathname}:`, error);\n          return new Response(JSON.stringify({ error: \"Internal Server Error\" }), {\n            status: 500,\n            headers: { \"Content-Type\": \"application/json\" },\n          });\n        }\n      };\n\n      return this.i18n?.config.enabled\n        ? _runWithFarmI18nRequest(this.i18n, request, invoke, {\n            redirect: false,\n          })\n        : invoke();\n    };\n  }\n\n  /**\n   * Check if a path is an API route\n   */\n  isAPIRoute(pathname: string): boolean {\n    return Boolean(this.matchRoute(pathname));\n  }\n\n  matchRoute(pathname: string): APIRouteMatch<APIRoute> | null {\n    return matchAPIRouteAtBasePath(this.routes, pathname, this.basePath);\n  }\n\n  /**\n   * Get all routes for client type generation\n   */\n  getRoutes(): Map<string, APIRoute> {\n    return this.routes;\n  }\n}\n\nexport {\n  getAllowedAPIRouteMethods,\n  invokeAPIRouteEndpoint,\n  isWebResponse,\n  matchAPIRoute,\n  normalizeRouteResponse,\n  resolveAPIRouteEndpoint,\n} from \"./runtime\";\nexport type { APIRouteMatch, APIRouteParams, APIRouteParamValue } from \"./runtime\";\n","import { _runWithCurrentRequest } from \"../server/request\";\nimport {\n  decodeFarmCacheInvalidations,\n  encodeFarmCacheInvalidations,\n  FARM_CACHE_INVALIDATION_HEADER,\n} from \"../cache-invalidation\";\nimport { isEndpointFailure, type EndpointFailure } from \"./endpoint\";\nimport {\n  bufferFarmRequestBody,\n  createFarmRequestBodyErrorResponse,\n  DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n} from \"../server-http\";\nimport { DEFAULT_FARM_API_BASE_PATH, normalizeFarmAPIBasePath } from \"./config\";\nimport { resolveFarmAPICanonicalPathname } from \"./server-path\";\nimport { parseRouteSchema } from \"./route-schema\";\nimport { omitFarmResponseBody } from \"../response-body\";\n\nexport { registerAPIRouteShape, type APIRouteShapeSource } from \"./route-shape\";\nexport { mergePluginAPIRoutes } from \"./plugin-route-runtime\";\n\nexport {\n  matchAPIRoute,\n  type APIRouteParams,\n  type APIRouteParamValue,\n  type APIRouteMatch,\n} from \"./route-pattern\";\nimport { matchAPIRoute, type APIRouteParams, type APIRouteMatch } from \"./route-pattern\";\ninterface APIRouteMethodTable {\n  methods: string[];\n  endpoints: Record<string, any>;\n}\n\nexport function resolveAPIRouteEndpoint(\n  route: APIRouteMethodTable,\n  method: string,\n): any | undefined {\n  const normalizedMethod = method.toUpperCase();\n  return (\n    route.endpoints[normalizedMethod] ??\n    (normalizedMethod === \"HEAD\" ? route.endpoints.GET : undefined)\n  );\n}\n\nexport function getAllowedAPIRouteMethods(route: APIRouteMethodTable): string[] {\n  const methods = [...route.methods];\n  const getIndex = methods.indexOf(\"GET\");\n  if (getIndex >= 0 && !methods.includes(\"HEAD\")) {\n    methods.splice(getIndex + 1, 0, \"HEAD\");\n  }\n  return methods;\n}\n\n/** Match canonical routes through a configurable same-origin public API path. */\nexport function matchAPIRouteAtBasePath<T extends { path: string }>(\n  routes: Map<string, T>,\n  pathname: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): APIRouteMatch<T> | null {\n  const directMatch = matchAPIRoute(routes, pathname);\n  if (directMatch) return directMatch;\n\n  const canonicalPathname = resolveFarmAPICanonicalPathname(pathname, serverBasePath);\n  return canonicalPathname === pathname ? null : matchAPIRoute(routes, canonicalPathname);\n}\n\n/** Test whether a pathname belongs to the configured local API surface. */\nexport function isFarmAPIPathname(\n  pathname: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): boolean {\n  const basePath = normalizeFarmAPIBasePath(serverBasePath);\n  return basePath !== \"/\" && (pathname === basePath || pathname.startsWith(`${basePath}/`));\n}\n\nexport async function invokeAPIRouteEndpoint(\n  endpoint: any,\n  request: Request,\n  params: APIRouteParams = {},\n  bodySizeLimit = DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n): Promise<Response> {\n  try {\n    request = await bufferFarmRequestBody(request, bodySizeLimit);\n  } catch (error) {\n    const response = createFarmRequestBodyErrorResponse(error);\n    if (response) return response;\n    throw error;\n  }\n\n  const response = await _runWithCurrentRequest(request, () =>\n    invokeAPIRouteEndpointInContext(endpoint, request, params),\n  );\n\n  if (request.method.toUpperCase() !== \"HEAD\") {\n    return response;\n  }\n\n  return omitFarmResponseBody(response);\n}\n\nasync function invokeAPIRouteEndpointInContext(\n  endpoint: any,\n  request: Request,\n  params: APIRouteParams,\n): Promise<Response> {\n  const queryContentTypeError = validateQueryContentType(request);\n  if (queryContentTypeError) {\n    return queryContentTypeError;\n  }\n\n  // `createEndpoint` brands its parsed-context handler explicitly. Plain route\n  // exports always receive the Web Request regardless of their parameter name;\n  // inferring a calling convention from `Function#toString()` misclassified\n  // valid handlers named `context`, `ctx`, or using destructuring.\n  const farmHandler = endpoint.__handler || null;\n\n  if (!farmHandler) {\n    const result = await endpoint(request, {\n      params: Promise.resolve(params),\n    });\n    return normalizeRouteResponse(result);\n  }\n\n  const url = new URL(request.url);\n  // Repeated keys collect into arrays, the same representation the rest of the\n  // framework hands to routes, and the same helper this path already uses for\n  // urlencoded and multipart bodies. Spread back onto a normal object so an\n  // endpoint without a query schema still receives the object shape it did\n  // before; `entriesToObject` has already dropped the prototype-poisoning keys.\n  const query: Record<string, string | string[]> = {\n    ...searchParamsToObject(url.searchParams),\n  };\n\n  let body: any = undefined;\n  if (request.method.toUpperCase() !== \"GET\" && request.method.toUpperCase() !== \"HEAD\") {\n    const parsedBody = await readRequestBody(request);\n    if (parsedBody.error) return parsedBody.error;\n    body = parsedBody.body;\n  }\n\n  const headers = Object.fromEntries(request.headers.entries());\n  const types = endpoint.__types || {};\n\n  const queryValidation = await validateInput(types.query, query, \"Invalid query parameters\");\n  if (queryValidation instanceof Response) {\n    return queryValidation;\n  }\n\n  const bodyValidation = await validateInput(types.body, body, \"Invalid request body\");\n  if (bodyValidation instanceof Response) {\n    return bodyValidation;\n  }\n\n  const headersValidation = await validateInput(types.headers, headers, \"Invalid request headers\");\n  if (headersValidation instanceof Response) {\n    return headersValidation;\n  }\n\n  const paramsValidation = await validateInput(types.params, params, \"Invalid route parameters\");\n  if (paramsValidation instanceof Response) return paramsValidation;\n\n  const handlerContext = {\n    query: queryValidation,\n    body: bodyValidation,\n    headers: headersValidation,\n    request,\n    context: {},\n    params: paramsValidation,\n  };\n  let execution: {\n    result: unknown;\n    context: unknown;\n    handlerExecuted: boolean;\n    invalidations: readonly string[];\n  };\n  try {\n    execution =\n      typeof endpoint.__farmInvoke === \"function\"\n        ? await endpoint.__farmInvoke(handlerContext)\n        : {\n            result: await farmHandler(handlerContext),\n            context: handlerContext.context,\n            handlerExecuted: true,\n            invalidations: [],\n          };\n  } catch (error) {\n    if (isEndpointFailure(error)) {\n      return createEndpointFailureResponse(error);\n    }\n    throw error;\n  }\n\n  if (execution.handlerExecuted && endpoint.__output && !isWebResponse(execution.result)) {\n    try {\n      execution.result = await parseRouteSchema(endpoint.__output, execution.result);\n    } catch {\n      throw new Error(\"API route returned a value that does not match its output schema.\");\n    }\n  }\n  const response = normalizeRouteResponse(execution.result);\n  return attachEndpointInvalidations(response, execution.invalidations);\n}\n\nfunction validateQueryContentType(request: Request): Response | null {\n  if (request.method.toUpperCase() !== \"QUERY\" || request.headers.has(\"content-type\")) {\n    return null;\n  }\n\n  return new Response(\n    JSON.stringify({\n      error: \"Invalid QUERY request\",\n      message: \"QUERY requests must include a Content-Type header.\",\n    }),\n    {\n      status: 400,\n      headers: { \"Content-Type\": \"application/json\" },\n    },\n  );\n}\n\nexport function normalizeRouteResponse(result: unknown): Response {\n  if (isWebResponse(result)) {\n    return result;\n  }\n\n  if (result === undefined) {\n    return new Response(null, { status: 204 });\n  }\n\n  return new Response(JSON.stringify(result), {\n    status: 200,\n    headers: { \"Content-Type\": \"application/json\" },\n  });\n}\n\nexport function isWebResponse(value: unknown): value is Response {\n  return (\n    value instanceof Response ||\n    (typeof value === \"object\" &&\n      value !== null &&\n      \"headers\" in value &&\n      \"status\" in value &&\n      typeof (value as Response).arrayBuffer === \"function\")\n  );\n}\n\nfunction attachEndpointInvalidations(response: Response, keys: readonly string[]): Response {\n  const existing = decodeFarmCacheInvalidations(\n    response.headers.get(FARM_CACHE_INVALIDATION_HEADER),\n  );\n  const encoded = encodeFarmCacheInvalidations([...existing, ...keys]);\n  if (!encoded) return response;\n\n  const headers = new Headers(response.headers);\n  headers.set(FARM_CACHE_INVALIDATION_HEADER, encoded);\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nexport function createEndpointFailureResponse(failure: EndpointFailure<string, unknown>): Response {\n  return new Response(\n    JSON.stringify({\n      error: {\n        code: failure.code,\n        message: failure.message,\n        data: failure.data,\n      },\n    }),\n    {\n      status: failure.status,\n      headers: {\n        \"cache-control\": \"no-store\",\n        \"content-type\": \"application/json\",\n      },\n    },\n  );\n}\n\ninterface RequestBodyParseResult {\n  body?: unknown;\n  error?: Response;\n}\n\nasync function readRequestBody(request: Request): Promise<RequestBodyParseResult> {\n  const contentType = request.headers.get(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n\n  try {\n    if (contentType === \"multipart/form-data\") {\n      return { body: formDataToObject(await request.clone().formData()) };\n    }\n\n    const text = await request.clone().text();\n    if (!text) return { body: undefined };\n    if (contentType === \"application/x-www-form-urlencoded\") {\n      return { body: searchParamsToObject(new URLSearchParams(text)) };\n    }\n    if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n      return { body: JSON.parse(text) };\n    }\n\n    // 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      return { body: JSON.parse(text) };\n    }\n\n    return { body: undefined };\n  } catch {\n    if (contentType === \"application/json\" || contentType?.endsWith(\"+json\")) {\n      return {\n        error: new Response(\n          JSON.stringify({\n            error: \"Invalid request body\",\n            message: \"The request body is not valid JSON.\",\n          }),\n          {\n            status: 400,\n            headers: { \"Content-Type\": \"application/json\" },\n          },\n        ),\n      };\n    }\n    // The body format is unsupported or malformed. Schema validation below\n    // will turn the missing value into a typed 400 response when applicable.\n  }\n\n  return { body: undefined };\n}\n\nfunction formDataToObject(\n  formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n  return entriesToObject(formData.entries());\n}\n\nfunction searchParamsToObject(searchParams: URLSearchParams): Record<string, string | string[]> {\n  return entriesToObject(searchParams.entries());\n}\n\nfunction entriesToObject<TValue>(\n  entries: IterableIterator<[string, TValue]>,\n): Record<string, TValue | TValue[]> {\n  const output: Record<string, TValue | TValue[]> = Object.create(null);\n  for (const [key, value] of entries) {\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n    const current = output[key];\n    if (current === undefined) {\n      output[key] = value;\n    } else if (Array.isArray(current)) {\n      current.push(value);\n    } else {\n      output[key] = [current, value];\n    }\n  }\n  return output;\n}\n\nasync function validateInput(\n  schema: any,\n  value: unknown,\n  error: string,\n): Promise<unknown | Response> {\n  if (!schema) return value;\n  try {\n    return await parseRouteSchema(schema, value);\n  } catch (validationError: any) {\n    return Response.json(\n      {\n        error,\n        details: (validationError.issues || validationError.errors || []).map((issue: any) => ({\n          path: issue.path,\n          message: issue.message,\n          code: issue.code,\n        })),\n      },\n      { status: 400 },\n    );\n  }\n}\n","import {\n  DEFAULT_FARM_API_BASE_PATH,\n  normalizeFarmAPIBasePath,\n  resolveFarmAPIRequestURL,\n  type ResolvedFarmAPIConfig,\n} from \"./config\";\n\n/** Return the same-origin path served by this Farm application. */\nexport function resolveFarmAPIServerBasePath(config: ResolvedFarmAPIConfig): string {\n  // Absolute API URLs belong to another origin and must not move local routes.\n  return config.baseURL.startsWith(\"/\") ? config.basePath : DEFAULT_FARM_API_BASE_PATH;\n}\n\n/** Translate a public local API pathname back to Farm's canonical `/api` route table. */\nexport function resolveFarmAPICanonicalPathname(\n  pathname: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): string {\n  const basePath = normalizeFarmAPIBasePath(serverBasePath);\n  if (basePath === DEFAULT_FARM_API_BASE_PATH) return pathname;\n\n  if (basePath === \"/\") {\n    return pathname === \"/\"\n      ? DEFAULT_FARM_API_BASE_PATH\n      : `${DEFAULT_FARM_API_BASE_PATH}${pathname.startsWith(\"/\") ? pathname : `/${pathname}`}`;\n  }\n\n  if (pathname === basePath) return DEFAULT_FARM_API_BASE_PATH;\n  if (pathname.startsWith(`${basePath}/`)) {\n    return `${DEFAULT_FARM_API_BASE_PATH}${pathname.slice(basePath.length)}`;\n  }\n  return pathname;\n}\n\n/** Resolve a canonical `/api` route to the path served by this application. */\nexport function resolveFarmAPIServerRoutePath(\n  routePath: string,\n  serverBasePath = DEFAULT_FARM_API_BASE_PATH,\n): string {\n  return resolveFarmAPIRequestURL(routePath, serverBasePath).pathname;\n}\n","/** Server-only schema contract shared by declarative routes and the API runtime. */\nexport interface RouteSchema {\n  readonly _input?: unknown;\n  readonly _output?: unknown;\n  parse?: (value: unknown) => unknown;\n  parseAsync?: (value: unknown) => Promise<unknown>;\n  readonly \"~standard\"?: {\n    readonly types?: { input: unknown; output: unknown };\n    validate(value: unknown): unknown;\n  };\n}\n\nexport type RouteSchemaInput<T> = T extends { _input: infer I }\n  ? I\n  : T extends { \"~standard\": { types?: { input: infer I } } }\n    ? I\n    : unknown;\n\nexport type RouteSchemaOutput<T> = T extends { _output: infer O }\n  ? O\n  : T extends { \"~standard\": { types?: { output: infer O } } }\n    ? O\n    : T extends { parse: (...args: any[]) => infer O }\n      ? Awaited<O>\n      : unknown;\n\nexport async function parseRouteSchema(schema: RouteSchema, value: unknown): Promise<unknown> {\n  if (schema[\"~standard\"]) {\n    const result = (await schema[\"~standard\"].validate(value)) as {\n      value?: unknown;\n      issues?: readonly unknown[];\n    };\n    if (result.issues)\n      throw Object.assign(new Error(\"Validation failed\"), { issues: result.issues });\n    return result.value;\n  }\n  if (schema.parseAsync) return schema.parseAsync(value);\n  if (schema.parse) return schema.parse(value);\n  throw new TypeError(\"Route validators must implement Standard Schema or parse().\");\n}\n","import { compareRouteSpecificity, type RouteSegmentSpecificity } from \"../routing/specificity\";\n\nexport type APIRouteParamValue = string | string[];\nexport type APIRouteParams = Record<string, APIRouteParamValue>;\n\nexport interface APIRouteMatch<T extends { path: string }> {\n  route: T;\n  params: APIRouteParams;\n}\n\nexport function matchAPIRoute<T extends { path: string }>(\n  routes: Map<string, T>,\n  pathname: string,\n): APIRouteMatch<T> | null {\n  const exactRoute = routes.get(pathname);\n  if (exactRoute) {\n    return { route: exactRoute, params: {} };\n  }\n\n  const normalizedPathname = normalizePathname(pathname);\n  if (normalizedPathname !== pathname) {\n    const normalizedRoute = routes.get(normalizedPathname);\n    if (normalizedRoute) {\n      return { route: normalizedRoute, params: {} };\n    }\n  }\n\n  let bestMatch: APIRouteMatch<T> | null = null;\n  let bestSpecificity: RouteSegmentSpecificity[] | null = null;\n\n  for (const route of routes.values()) {\n    const params = matchRoutePath(route.path, pathname);\n    if (!params) continue;\n\n    const specificity = getAPIRouteSpecificity(route.path);\n    if (bestSpecificity === null || compareRouteSpecificity(specificity, bestSpecificity) < 0) {\n      bestMatch = { route, params };\n      bestSpecificity = specificity;\n    }\n  }\n\n  return bestMatch;\n}\n\nfunction matchRoutePath(routePath: string, pathname: string): APIRouteParams | null {\n  const routeSegments = getPathSegments(routePath);\n  const pathnameSegments = getPathSegments(pathname);\n  const params: APIRouteParams = {};\n  let pathIndex = 0;\n\n  for (const routeSegment of routeSegments) {\n    const dynamicSegment = parseDynamicSegment(routeSegment);\n\n    if (dynamicSegment?.catchAll) {\n      const remainingSegments = pathnameSegments.slice(pathIndex).map(decodePathSegment);\n      if (remainingSegments.length === 0 && !dynamicSegment.optional) {\n        return null;\n      }\n      if (remainingSegments.length > 0) {\n        params[dynamicSegment.name] = remainingSegments;\n      }\n      pathIndex = pathnameSegments.length;\n      continue;\n    }\n\n    const pathnameSegment = pathnameSegments[pathIndex];\n    if (pathnameSegment === undefined) {\n      return null;\n    }\n\n    if (dynamicSegment) {\n      params[dynamicSegment.name] = decodePathSegment(pathnameSegment);\n      pathIndex++;\n      continue;\n    }\n\n    if (decodePathSegment(routeSegment) !== decodePathSegment(pathnameSegment)) {\n      return null;\n    }\n\n    pathIndex++;\n  }\n\n  return pathIndex === pathnameSegments.length ? params : null;\n}\n\nfunction getPathSegments(pathname: string): string[] {\n  return normalizePathname(pathname)\n    .split(\"/\")\n    .filter((segment) => segment.length > 0);\n}\n\nfunction getAPIRouteSpecificity(routePath: string): RouteSegmentSpecificity[] {\n  return getPathSegments(routePath).map((segment) => {\n    const dynamic = parseDynamicSegment(segment);\n    if (!dynamic) return \"static\";\n    if (!dynamic.catchAll) return \"dynamic\";\n    return dynamic.optional ? \"optional-catch-all\" : \"catch-all\";\n  });\n}\n\nfunction normalizePathname(pathname: string): string {\n  if (pathname.length > 1 && pathname.endsWith(\"/\")) {\n    return pathname.replace(/\\/+$/, \"\");\n  }\n\n  return pathname;\n}\n\nexport function parseDynamicSegment(\n  segment: string,\n): { name: string; catchAll: boolean; optional: boolean } | null {\n  const optionalCatchAll = segment.match(/^\\[\\[\\.\\.\\.(.+)\\]\\]$/);\n  if (optionalCatchAll?.[1]) {\n    return { name: optionalCatchAll[1], catchAll: true, optional: true };\n  }\n\n  const catchAll = segment.match(/^\\[\\.\\.\\.(.+)\\]$/);\n  if (catchAll?.[1]) {\n    return { name: catchAll[1], catchAll: true, optional: false };\n  }\n\n  const dynamic = segment.match(/^\\[(.+)\\]$/);\n  if (dynamic?.[1]) {\n    return { name: dynamic[1], catchAll: false, optional: false };\n  }\n\n  return null;\n}\n\nfunction decodePathSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n","/**\n * Middleware Manager\n *\n * Discovers and executes middleware files in the file system\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { decodeRouteSegment } from \"../utils/decode\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type {\n  FarmMiddlewareConfig,\n  MiddlewareFunction,\n  MiddlewareMatcher,\n  MiddlewareConfig,\n  MiddlewareContext,\n  MiddlewareResult,\n} from \"./types\";\nimport { createContext } from \"./context\";\nimport { normalizeMiddlewareModule } from \"./module\";\nimport { logger } from \"../utils\";\nimport { sendWebResponse } from \"../server/response\";\nimport { emitFarmEvent } from \"../observability\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { createCliColors } from \"../cli-colors\";\nimport { appendMiddlewareRoutePath } from \"./path\";\nimport type { FarmServerConfig, ResolvedFarmServerConfig } from \"../server-http\";\nimport { resolveFarmRequestURL } from \"../server/request\";\n\nexport interface DiscoveredMiddleware {\n  path: string;\n  filePath: string;\n  handlers: MiddlewareFunction[];\n  config?: MiddlewareConfig;\n  source?: \"config\" | \"file\";\n}\n\nfunction isMiddlewareResponse(value: unknown): value is Response {\n  return value instanceof Response;\n}\n\n/**\n * Middleware Manager - discovers and executes middleware\n */\nexport class MiddlewareManager {\n  private middleware: DiscoveredMiddleware[] = [];\n  private configMiddleware: DiscoveredMiddleware[] = [];\n  private globalConfig?: MiddlewareConfig;\n  private viteServer?: ViteDevServer;\n  private appDirs: string[];\n  private i18n?: ResolvedFarmI18nConfig;\n  private server?: FarmServerConfig | ResolvedFarmServerConfig;\n\n  constructor(\n    appDir: string | readonly string[],\n    viteServer?: ViteDevServer,\n    config?: FarmMiddlewareConfig,\n    i18n?: ResolvedFarmI18nConfig,\n    server?: FarmServerConfig | ResolvedFarmServerConfig,\n  ) {\n    this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n    this.viteServer = viteServer;\n    this.i18n = i18n;\n    this.server = server;\n    this.configure(config);\n  }\n\n  configure(config?: FarmMiddlewareConfig): void {\n    this.configMiddleware = [];\n    this.globalConfig = undefined;\n\n    if (!config) return;\n\n    const entries = Array.isArray(config) ? config : [config];\n\n    for (const [index, entry] of entries.entries()) {\n      const handlers = this.getConfigHandlers(entry);\n      const middlewareConfig = this.toMiddlewareConfig(entry);\n\n      if (handlers.length === 0) {\n        this.globalConfig = middlewareConfig;\n        continue;\n      }\n\n      this.configMiddleware.push({\n        path: \"/\",\n        filePath: `farm.config.ts#middleware-${index}`,\n        handlers,\n        config: middlewareConfig,\n        source: \"config\",\n      });\n    }\n  }\n\n  /**\n   * Discover all middleware.ts files\n   */\n  async discover(): Promise<void> {\n    const middlewareByPath = new Map<string, DiscoveredMiddleware>();\n    for (const appDir of this.appDirs) {\n      const discovered: DiscoveredMiddleware[] = [];\n      await this.discoverInDirectory(appDir, \"/\", discovered);\n      for (const middleware of discovered) {\n        middlewareByPath.set(middleware.path, middleware);\n      }\n    }\n    this.middleware = Array.from(middlewareByPath.values());\n\n    // Sort by path depth (root first, then nested)\n    this.middleware.sort((a, b) => {\n      const depthA = a.path.split(\"/\").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        const fileUrl = `file://${filePath}`;\n        module = await import(/* @vite-ignore */ fileUrl);\n      }\n\n      const normalized = normalizeMiddlewareModule(module, routePath);\n      if (!normalized) {\n        throw new Error(\"must export a default handler or a named middleware handler\");\n      }\n\n      return {\n        path: routePath,\n        filePath,\n        handlers: normalized.handlers,\n        config: normalized.config,\n        source: \"file\",\n      };\n    } catch (error) {\n      throw new Error(`Failed to load middleware ${filePath}: ${error}`);\n    }\n  }\n\n  /**\n   * Execute middleware for a request\n   */\n  async execute(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n    const url = resolveFarmRequestURL(req, { trustProxy: this.server?.trustProxy });\n    const pathname = url.pathname;\n    const routePathname = this.i18n?.enabled\n      ? stripFarmLocaleFromPathname(pathname, this.i18n)\n      : pathname;\n    const method = req.method || \"GET\";\n    const startTime = Date.now();\n\n    let parentData: MiddlewareContext[\"parent\"] | undefined;\n    let ctx = createContext(req, res, this.viteServer, undefined, this.server);\n\n    if (this.globalConfig) {\n      const globalMatch = this.matchesConfig(routePathname, this.globalConfig, ctx);\n      if (!globalMatch.matched) {\n        return false;\n      }\n      if (globalMatch.params) {\n        ctx.params = { ...ctx.params, ...globalMatch.params };\n      }\n    }\n\n    // Find applicable middleware (config entries first, then cascading files)\n    const applicable: Array<{\n      mw: DiscoveredMiddleware;\n      routeMatch: { matched: boolean; params?: Record<string, string> };\n    }> = [\n      ...this.configMiddleware.map((mw) => ({ mw, routeMatch: { matched: true } })),\n      ...this.middleware\n        .map((mw) => ({ mw, routeMatch: this.matchRoutePath(routePathname, mw.path) }))\n        .filter((entry) => entry.routeMatch.matched),\n    ];\n\n    if (applicable.length === 0) {\n      return false; // No middleware to run\n    }\n    const pc = createCliColors();\n    const log = [\n      pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.magenta(\"MIDDLEWARE\")) + pc.dim(\"]\"),\n      pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n      pc.gray(\"Executing middleware: \"),\n      pc.gray(pathname),\n      pc.dim(` (${(Date.now() - startTime).toFixed(2)}ms)`),\n    ].join(\" \");\n    console.log(log);\n\n    // Execute middleware in cascade order\n    for (const entry of applicable) {\n      // Check matcher configuration\n      const { mw, routeMatch } = entry;\n      const configMatch = mw.config\n        ? this.matchesConfig(routePathname, mw.config, ctx)\n        : { matched: true };\n      if (!configMatch.matched) {\n        continue;\n      }\n      if (routeMatch.params) {\n        ctx.params = { ...ctx.params, ...routeMatch.params };\n      }\n      if (configMatch.params) {\n        ctx.params = { ...ctx.params, ...configMatch.params };\n      }\n\n      // Create new context with parent data\n      if (parentData) {\n        ctx = createContext(req, res, this.viteServer, parentData, this.server);\n        if (routeMatch.params) {\n          ctx.params = { ...ctx.params, ...routeMatch.params };\n        }\n        if (configMatch.params) {\n          ctx.params = { ...ctx.params, ...configMatch.params };\n        }\n      }\n\n      const middlewareStartTime = Date.now();\n      const middlewareEvent = {\n        route: mw.path,\n        pathname,\n        name: mw.filePath,\n      };\n      emitFarmEvent({ type: \"middleware.start\", ...middlewareEvent });\n\n      try {\n        // Execute all handlers in this middleware\n        let handlerIndex = 0;\n        let returnedResponse: Response | undefined;\n        const executeNext = async (): Promise<MiddlewareResult> => {\n          if (handlerIndex < mw.handlers.length) {\n            const handler = mw.handlers[handlerIndex++];\n            const result = await handler(ctx, executeNext);\n            if (isMiddlewareResponse(result)) {\n              returnedResponse = result;\n              return result;\n            }\n          }\n          return returnedResponse;\n        };\n\n        const result = await executeNext();\n        const response = isMiddlewareResponse(result) ? result : returnedResponse;\n        if (response) {\n          if (!res.headersSent && !res.writableEnded) {\n            for (const [key, value] of ctx.headers) {\n              try {\n                res.setHeader(key, value);\n              } catch (error) {}\n            }\n          }\n          emitFarmEvent({\n            type: \"middleware.shortCircuit\",\n            ...middlewareEvent,\n            status: response.status,\n          });\n          await sendWebResponse(res, response);\n          return true;\n        }\n\n        // Check if response has been sent or handled by middleware helpers.\n        if (ctx._handled || res.headersSent || res.writableEnded) {\n          emitFarmEvent({\n            type: \"middleware.shortCircuit\",\n            ...middlewareEvent,\n            status: res.statusCode,\n          });\n          return true;\n        }\n\n        emitFarmEvent({\n          type: \"middleware.complete\",\n          ...middlewareEvent,\n          durationMs: Date.now() - middlewareStartTime,\n        });\n      } catch (error) {\n        emitFarmEvent({\n          type: \"middleware.error\",\n          ...middlewareEvent,\n          error,\n        });\n        throw error;\n      }\n\n      parentData = {\n        data: new Map(ctx.data),\n        locals: new Map(ctx.locals),\n        headers: Object.fromEntries(ctx.headers),\n      };\n    }\n\n    if (!res.headersSent && !res.writableEnded) {\n      for (const [key, value] of ctx.headers) {\n        try {\n          res.setHeader(key, value);\n        } catch (error) {}\n      }\n    }\n\n    (req as any).__FARM_MIDDLEWARE_DATA__ = new Map(ctx.data);\n    (req as any).__FARM_MIDDLEWARE_CONTEXT__ = new Map(ctx.locals);\n\n    return false; // Continue to page rendering\n  }\n\n  /**\n   * Check if pathname matches middleware config\n   */\n  private matchesConfig(\n    pathname: string,\n    config: MiddlewareConfig,\n    ctx: MiddlewareContext,\n  ): { matched: boolean; params?: Record<string, string> } {\n    // Check exclusions\n    if (config.exclude) {\n      for (const pattern of config.exclude) {\n        if (this.matchPattern(pattern, pathname).matched) {\n          return { matched: false };\n        }\n      }\n    }\n\n    // Check matchers\n    if (config.matcher) {\n      for (const matcher of this.toMatcherList(config.matcher)) {\n        if (typeof matcher === \"string\" || matcher instanceof RegExp) {\n          const result = this.matchPattern(matcher, pathname);\n          if (result.matched) {\n            return result;\n          }\n        } else if (typeof matcher === \"function\" && matcher(ctx)) {\n          return { matched: true };\n        }\n      }\n      return { matched: false };\n    }\n\n    return { matched: true };\n  }\n\n  /**\n   * Match a pattern against pathname\n   */\n  private matchPattern(\n    pattern: string | RegExp,\n    pathname: string,\n  ): { matched: boolean; params?: Record<string, string> } {\n    if (pattern instanceof RegExp) {\n      pattern.lastIndex = 0;\n      const match = pattern.exec(pathname);\n      return {\n        matched: !!match,\n        params: match?.groups ? { ...match.groups } : undefined,\n      };\n    }\n\n    if (pattern === \"*\" || pattern === \"/(.*)\") {\n      return { matched: true };\n    }\n\n    if (pattern.endsWith(\"(.*)\")) {\n      // Strip a trailing slash before the wildcard so `/admin/(.*)` matches the\n      // `/admin` subtree like `/admin/**` does. Without this the prefix keeps\n      // its slash and the check becomes startsWith(\"/admin//\"), which no path\n      // satisfies, so the matcher silently matches nothing.\n      const prefix = pattern.slice(0, -4).replace(/\\/$/, \"\");\n      return { matched: pathname === prefix || pathname.startsWith(`${prefix}/`) };\n    }\n\n    const { regex, params } = this.compilePathPattern(pattern);\n    const match = regex.exec(pathname);\n    if (!match) {\n      return { matched: false };\n    }\n\n    const values: Record<string, string> = {};\n    params.forEach((param, index) => {\n      values[param] = decodeRouteSegment(match[index + 1] || \"\");\n    });\n\n    return {\n      matched: true,\n      params: Object.keys(values).length > 0 ? values : undefined,\n    };\n  }\n\n  /**\n   * Reload middleware (for HMR)\n   */\n  async reload(): Promise<void> {\n    await this.discover();\n  }\n\n  getMiddlewares(): DiscoveredMiddleware[] {\n    return [...this.configMiddleware, ...this.middleware];\n  }\n\n  hasMiddleware(): boolean {\n    return this.configMiddleware.length > 0 || this.middleware.length > 0;\n  }\n\n  private matchRoutePath(\n    pathname: string,\n    middlewarePath: string,\n  ): { matched: boolean; params?: Record<string, string> } {\n    if (middlewarePath === \"/\") return { matched: true };\n\n    const exactMatch = this.matchPattern(middlewarePath, pathname);\n    if (exactMatch.matched) {\n      return exactMatch;\n    }\n\n    const nestedMatch = this.matchPattern(`${middlewarePath}/:__farmRest*`, pathname);\n    if (!nestedMatch.matched) {\n      return { matched: false };\n    }\n\n    const params = { ...nestedMatch.params };\n    delete params.__farmRest;\n    return {\n      matched: true,\n      params: Object.keys(params).length > 0 ? params : undefined,\n    };\n  }\n\n  private toMatcherList(matcher: MiddlewareConfig[\"matcher\"]): MiddlewareMatcher[] {\n    if (!matcher) return [];\n    return Array.isArray(matcher) ? matcher : [matcher];\n  }\n\n  private getConfigHandlers(\n    entry:\n      | MiddlewareConfig\n      | (MiddlewareConfig & {\n          handler?: MiddlewareFunction;\n          handlers?: MiddlewareFunction[];\n        }),\n  ): MiddlewareFunction[] {\n    const handlers: MiddlewareFunction[] = [];\n    if (\"handler\" in entry && typeof entry.handler === \"function\") {\n      handlers.push(entry.handler);\n    }\n    if (\"handlers\" in entry && Array.isArray(entry.handlers)) {\n      handlers.push(...entry.handlers.filter((handler) => typeof handler === \"function\"));\n    }\n    return handlers;\n  }\n\n  private toMiddlewareConfig(\n    entry: MiddlewareConfig & {\n      handler?: MiddlewareFunction;\n      handlers?: MiddlewareFunction[];\n    },\n  ): MiddlewareConfig {\n    const { matcher, exclude, runtime } = entry;\n    return { matcher, exclude, runtime };\n  }\n\n  private compilePathPattern(pattern: string): { regex: RegExp; params: string[] } {\n    const params: string[] = [];\n    const segments = pattern.split(\"/\").filter(Boolean);\n\n    if (segments.length === 0) {\n      return { regex: /^\\/$/, params };\n    }\n\n    const parts = segments.map((segment) => {\n      if (segment === \"**\") {\n        return \"(?:/.*)?\";\n      }\n\n      if (segment === \"*\") {\n        return \"/[^/]+\";\n      }\n\n      if (segment.startsWith(\":\")) {\n        const { name, modifier } = this.parseColonParam(segment);\n        params.push(name);\n\n        if (modifier === \"*\") {\n          return \"(?:/(.*))?\";\n        }\n        if (modifier === \"+\") {\n          return \"/(.+)\";\n        }\n        return \"/([^/]+)\";\n      }\n\n      if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n        params.push(segment.slice(4, -1));\n        return \"(?:/(.*))?\";\n      }\n\n      if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n        params.push(segment.slice(1, -1));\n        return \"/([^/]+)\";\n      }\n\n      return `/${this.escapeRegex(segment).replace(/\\\\\\*/g, \"[^/]*\")}`;\n    });\n\n    return {\n      regex: new RegExp(`^${parts.join(\"\")}$`),\n      params,\n    };\n  }\n\n  private parseColonParam(segment: string): { name: string; modifier?: string } {\n    const raw = segment.slice(1);\n    const last = raw[raw.length - 1];\n    const modifier = last === \"*\" || last === \"+\" || last === \"?\" ? last : undefined;\n    return {\n      name: modifier ? raw.slice(0, -1) : raw,\n      modifier,\n    };\n  }\n\n  private escapeRegex(value: string): string {\n    return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n  }\n}\n","import type { CookieOptions } from \"./types\";\n\nfunction decodeCookieValue(value: string): string {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    // Cookies are not required to be percent-encoded; keep the raw value\n    // instead of failing the whole request on malformed encoding.\n    return value;\n  }\n}\n\nexport function parseMiddlewareCookieHeader(cookieHeader?: string | null): Record<string, string> {\n  const cookies = Object.create(null) as Record<string, string>;\n  if (!cookieHeader) return cookies;\n\n  for (const cookie of cookieHeader.split(\";\")) {\n    const separator = cookie.indexOf(\"=\");\n    if (separator < 0) continue;\n\n    const name = cookie.slice(0, separator).trim();\n    if (!name) continue;\n\n    const value = cookie.slice(separator + 1).trim();\n    cookies[name] = decodeCookieValue(value);\n  }\n\n  return cookies;\n}\n\n/**\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, `http://${req.headers.host || \"localhost\"}`);\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 { existsSync, mkdirSync, readFileSync, unlinkSync } from \"fs\";\nimport { dirname, isAbsolute, join, resolve } from \"path\";\nimport { APITypeGenerator, type APIRouteInfo } from \"./type-generator\";\nimport {\n  createRouteTypeDeclarations,\n  generateRouteTypes,\n  type GenerateRouteTypesOptions,\n} from \"./routing/generate-route-types\";\nimport { createEnvTypeDeclarations, generateEnvTypes } from \"./env-types\";\nimport { createFarmImageTypeDeclarations, generateFarmImageTypes } from \"./image-types\";\nimport { createContentTypeDeclarations } from \"./content-types\";\nimport { generateFarmI18nTypes, renderFarmI18nTypes } from \"./i18n/type-generator\";\nimport { readFarmI18nCatalogs } from \"./i18n/catalog\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport { getFarmAppDirectories, getFarmSourceRoots, type ResolvedFarmLayer } from \"./layers\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\nimport type { FarmPlugin } from \"./plugin\";\nimport { resolvePluginRoutes } from \"./api/route\";\n\nexport { generateFarmI18nTypes };\n\nexport interface GenerateFarmTypeArtifactsOptions {\n  root: string;\n  srcDir?: string;\n  configPath?: string;\n  plugins?: readonly FarmPlugin[];\n  extraRoutes?: string[];\n  layers?: readonly ResolvedFarmLayer[];\n  suppressLintOnLink?: boolean;\n  componentExtensions?: readonly string[];\n  routeTypesOutFile?: string;\n  apiTypesOutFile?: string;\n  envTypesOutFile?: string;\n  imageTypesOutFile?: string;\n  i18nTypesOutFile?: string;\n  i18nConfig?: ResolvedFarmI18nConfig;\n  routes?: boolean;\n  api?: boolean;\n  env?: boolean;\n  images?: boolean;\n  i18n?: boolean;\n  /** Compare generated content with disk without writing files. */\n  check?: boolean;\n}\n\nexport interface GenerateFarmTypeArtifactsResult {\n  typesPath?: string;\n  routeTypesPath?: string;\n  apiTypesPath?: string;\n  envTypesPath?: string;\n  imageTypesPath?: string;\n  i18nTypesPath?: string;\n  apiRoutes: APIRouteInfo[];\n  /** Generated files whose checked-in content is missing or stale. */\n  stalePaths: string[];\n}\n\nexport async function generateFarmTypeArtifacts(\n  options: GenerateFarmTypeArtifactsOptions,\n): Promise<GenerateFarmTypeArtifactsResult> {\n  const root = resolve(options.root);\n  const srcDir = options.srcDir || \"src\";\n  const shouldGenerateRoutes = options.routes !== false;\n  const shouldGenerateApi = options.api !== false;\n  const shouldGenerateEnv = options.env !== false;\n  const shouldGenerateImages = options.images !== false;\n  const shouldGenerateI18n = options.i18n !== false && options.i18nConfig?.enabled;\n  const sourceRoots = getFarmSourceRoots({ root, srcDir, layers: options.layers });\n  const appDirs = getFarmAppDirectories({ root, srcDir, layers: options.layers });\n\n  const result: GenerateFarmTypeArtifactsResult = {\n    apiRoutes: [],\n    stalePaths: [],\n  };\n  const unifiedTypesPath = join(root, srcDir, \"farm.d.ts\");\n  const shouldRefreshUnifiedTypes =\n    (shouldGenerateRoutes && !options.routeTypesOutFile) ||\n    (shouldGenerateEnv && !options.envTypesOutFile) ||\n    (shouldGenerateI18n && !options.i18nTypesOutFile);\n  const unifiedSections: string[] = [];\n\n  if (shouldRefreshUnifiedTypes && !options.routeTypesOutFile) {\n    const routeOptions: GenerateRouteTypesOptions = {\n      root,\n      srcDir,\n      extraRoutes: options.extraRoutes || [],\n      suppressLintOnLink: options.suppressLintOnLink,\n      componentExtensions: options.componentExtensions,\n      sourceRoots,\n    };\n    unifiedSections.push(await createRouteTypeDeclarations(routeOptions, unifiedTypesPath));\n    result.routeTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateRoutes) {\n    const routeOptions = {\n      root,\n      srcDir,\n      outFile: options.routeTypesOutFile,\n      extraRoutes: options.extraRoutes || [],\n      suppressLintOnLink: options.suppressLintOnLink,\n      componentExtensions: options.componentExtensions,\n      sourceRoots,\n    } satisfies GenerateRouteTypesOptions;\n    if (options.check) {\n      const routeTypesPath = resolveGeneratedPath(root, srcDir, options.routeTypesOutFile!);\n      const content = await createRouteTypeDeclarations(routeOptions, routeTypesPath);\n      checkGeneratedFile(routeTypesPath, content, result.stalePaths);\n      result.routeTypesPath = routeTypesPath;\n    } else {\n      result.routeTypesPath = await generateRouteTypes(routeOptions);\n    }\n  }\n\n  if (shouldGenerateApi) {\n    const generator = new APITypeGenerator(appDirs);\n    const apiRoutes = generator.scanAPIRoutes();\n    const apiTypesPath = options.apiTypesOutFile\n      ? resolve(root, options.apiTypesOutFile)\n      : join(root, srcDir, \"lib\", \"api.generated.ts\");\n    const pluginRoutes = resolvePluginRoutes(options.plugins);\n    const configFiles = [\n      ...(options.layers ?? [])\n        .map((layer) => layer.configFile)\n        .filter((file): file is string => Boolean(file)),\n      options.configPath\n        ? resolve(root, options.configPath)\n        : [\n            \"farm.config.ts\",\n            \"farm.config.mts\",\n            \"farm.config.js\",\n            \"farm.config.mjs\",\n            \"farm.config.cts\",\n            \"farm.config.cjs\",\n            \"config.ts\",\n            \"config.js\",\n          ]\n            .map((name) => join(root, name))\n            .find((file) => existsSync(file)),\n    ].filter((file): file is string => Boolean(file));\n    if (pluginRoutes.length && !configFiles.length) {\n      throw new Error(\n        \"Cannot generate plugin API types without a Farm config file. Pass configPath.\",\n      );\n    }\n    const content = generator.generateAPIRouter(apiRoutes, {\n      outFile: apiTypesPath,\n      pluginConfigs: pluginRoutes.length ? [...new Set(configFiles)] : [],\n      pluginRoutes,\n    });\n\n    writeOrCheckGeneratedFile(apiTypesPath, content, options.check, result.stalePaths);\n\n    result.apiTypesPath = apiTypesPath;\n    result.apiRoutes = apiRoutes;\n  }\n\n  if (shouldRefreshUnifiedTypes && !options.envTypesOutFile) {\n    unifiedSections.push(\n      createEnvTypeDeclarations(\n        {\n          root,\n          srcDir,\n          configPath: options.configPath,\n          layerConfigPaths: (options.layers ?? [])\n            .map((layer) => layer.configFile)\n            .filter((configFile): configFile is string => Boolean(configFile)),\n        },\n        unifiedTypesPath,\n      ),\n    );\n    result.envTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateEnv) {\n    const envOptions = {\n      root,\n      srcDir,\n      outFile: options.envTypesOutFile,\n      configPath: options.configPath,\n      layerConfigPaths: (options.layers ?? [])\n        .map((layer) => layer.configFile)\n        .filter((configFile): configFile is string => Boolean(configFile)),\n    };\n    if (options.check) {\n      const envTypesPath = resolveGeneratedPath(root, srcDir, options.envTypesOutFile!);\n      checkGeneratedFile(\n        envTypesPath,\n        createEnvTypeDeclarations(envOptions, envTypesPath),\n        result.stalePaths,\n      );\n      result.envTypesPath = envTypesPath;\n    } else {\n      result.envTypesPath = await generateEnvTypes(envOptions);\n    }\n  }\n\n  // Static image modules are declared by @farm.js/core itself. Keep the\n  // explicit output option for callers that need a standalone declaration.\n  if (shouldGenerateImages && options.imageTypesOutFile) {\n    const imageTypesPath = resolveGeneratedPath(root, srcDir, options.imageTypesOutFile, false);\n    if (options.check) {\n      checkGeneratedFile(imageTypesPath, createFarmImageTypeDeclarations(), result.stalePaths);\n      result.imageTypesPath = imageTypesPath;\n    } else {\n      result.imageTypesPath = generateFarmImageTypes({\n        root,\n        srcDir,\n        outFile: options.imageTypesOutFile,\n      });\n    }\n  }\n\n  if (shouldRefreshUnifiedTypes && options.i18nConfig?.enabled && !options.i18nTypesOutFile) {\n    const { signatures } = await readFarmI18nCatalogs(options.i18nConfig);\n    unifiedSections.push(renderFarmI18nTypes(options.i18nConfig.locales, signatures));\n    result.i18nTypesPath = unifiedTypesPath;\n  } else if (shouldGenerateI18n && options.i18nConfig) {\n    if (options.check) {\n      const i18nTypesPath = resolveGeneratedPath(root, srcDir, options.i18nTypesOutFile!, false);\n      const { signatures } = await readFarmI18nCatalogs(options.i18nConfig);\n      checkGeneratedFile(\n        i18nTypesPath,\n        renderFarmI18nTypes(options.i18nConfig.locales, signatures),\n        result.stalePaths,\n      );\n      result.i18nTypesPath = i18nTypesPath;\n    } else {\n      result.i18nTypesPath = await generateFarmI18nTypes({\n        root,\n        srcDir,\n        config: options.i18nConfig,\n        outFile: options.i18nTypesOutFile,\n      });\n    }\n  }\n\n  if (shouldRefreshUnifiedTypes) {\n    unifiedSections.push(\n      createContentTypeDeclarations(\n        {\n          root,\n          configPath: options.configPath,\n          layerConfigPaths: (options.layers ?? [])\n            .map((layer) => layer.configFile)\n            .filter((configFile): configFile is string => Boolean(configFile)),\n        },\n        unifiedTypesPath,\n      ),\n    );\n  }\n\n  if (shouldRefreshUnifiedTypes) {\n    writeOrCheckGeneratedFile(\n      unifiedTypesPath,\n      `/**\n * Generated by Farm.js. Do not edit.\n * Contains project-specific route, environment, content, and internationalization types.\n */\n\nimport \"@farm.js/core/image\";\nimport \"@farm.js/core/css\";\n\n${unifiedSections.map(normalizeUnifiedTypeSection).join(\"\\n\\n\")}\n`,\n      options.check,\n      result.stalePaths,\n    );\n    result.typesPath = unifiedTypesPath;\n    if (options.check) {\n      collectLegacyTypeArtifacts(root, srcDir, result.stalePaths);\n    } else {\n      removeLegacyTypeArtifacts(root, srcDir);\n    }\n  }\n\n  return result;\n}\n\nfunction normalizeUnifiedTypeSection(section: string): string {\n  // The unified artifact already imports Farm's asset types, so it is a module.\n  // Individual generators add this marker for standalone declaration files, but\n  // formatters remove the now-redundant export and make `farm generate --check`\n  // report a false stale-file failure.\n  return section.trimEnd().replace(/\\n+export \\{\\};$/, \"\");\n}\n\nfunction resolveGeneratedPath(\n  root: string,\n  srcDir: string,\n  outFile: string,\n  relativeToSrc = true,\n): string {\n  if (isAbsolute(outFile)) return resolve(outFile);\n  return resolve(root, relativeToSrc ? join(srcDir, outFile) : outFile);\n}\n\nfunction writeOrCheckGeneratedFile(\n  filePath: string,\n  content: string,\n  check: boolean | undefined,\n  stalePaths: string[],\n): void {\n  if (check) {\n    checkGeneratedFile(filePath, content, stalePaths);\n    return;\n  }\n\n  mkdirSync(dirname(filePath), { recursive: true });\n  writeFileIfChanged(filePath, content);\n}\n\nfunction checkGeneratedFile(filePath: string, content: string, stalePaths: string[]): void {\n  if (!existsSync(filePath) || readFileSync(filePath, \"utf8\") !== content) {\n    stalePaths.push(filePath);\n  }\n}\n\nconst LEGACY_TYPE_ARTIFACTS = [\n  [\"farm-routes.d.ts\", \"Auto-generated route types\"],\n  [\"farm-env.d.ts\", \"Auto-generated env types\"],\n  [\"farm-images.d.ts\", \"Generated by Farm.js\"],\n  [\"farm-i18n.d.ts\", \"Generated by Farm.js\"],\n] as const;\n\nfunction removeLegacyTypeArtifacts(root: string, srcDir: string): void {\n  for (const [fileName, marker] of LEGACY_TYPE_ARTIFACTS) {\n    const filePath = join(root, srcDir, fileName);\n    if (!existsSync(filePath)) continue;\n    const source = readFileSync(filePath, \"utf8\");\n    if (source.includes(marker)) {\n      unlinkSync(filePath);\n    }\n  }\n}\n\nfunction collectLegacyTypeArtifacts(root: string, srcDir: string, stalePaths: string[]): void {\n  for (const [fileName, marker] of LEGACY_TYPE_ARTIFACTS) {\n    const filePath = join(root, srcDir, fileName);\n    if (!existsSync(filePath)) continue;\n    if (readFileSync(filePath, \"utf8\").includes(marker)) stalePaths.push(filePath);\n  }\n}\n","import * 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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nexport type AfterCallback = () => void | Promise<void>;\n\n/** Runtime hooks supplied by a deployment adapter. */\nexport interface FarmAfterPlatformContext {\n  /** Keep a serverless invocation alive until the scheduled work settles. */\n  waitUntil?: (promise: Promise<void>) => void;\n  /** Register a callback that runs once the response has finished. */\n  onResponseFinished?: (callback: () => void) => void;\n}\n\ninterface AfterTask {\n  result: Promise<void>;\n  start: () => void;\n}\n\ninterface AfterRequestState {\n  completion: Promise<void>;\n  finishResponse: () => void;\n  phase: \"open\" | \"running\" | \"closed\";\n  reportError: (error: unknown) => void;\n  tasks: AfterTask[];\n}\n\nconst AFTER_STORAGE = Symbol.for(\"@farm.js/core/after-storage\");\n\nfunction getAfterStorage(): AsyncLocalStorage<AfterRequestState> {\n  const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n  const existing = runtime[AFTER_STORAGE];\n  if (existing instanceof AsyncLocalStorage) {\n    return existing as AsyncLocalStorage<AfterRequestState>;\n  }\n\n  const storage = new AsyncLocalStorage<AfterRequestState>();\n  runtime[AFTER_STORAGE] = storage;\n  return storage;\n}\n\nconst afterStorage = getAfterStorage();\n\nfunction defaultAfterErrorReporter(error: unknown): void {\n  console.error(\"[Farm.js] after() callback failed:\", error);\n}\n\nfunction reportAfterError(state: AfterRequestState, error: unknown): void {\n  try {\n    state.reportError(error);\n  } catch {\n    // Error reporting must never interrupt the remaining post-response work.\n  }\n}\n\nfunction createAfterRequestState(\n  reportError: (error: unknown) => void = defaultAfterErrorReporter,\n): AfterRequestState {\n  let resolveResponseFinished!: () => void;\n  let responseFinished = false;\n  const responseFinishedPromise = new Promise<void>((resolve) => {\n    resolveResponseFinished = resolve;\n  });\n\n  const state: AfterRequestState = {\n    completion: Promise.resolve(),\n    finishResponse: () => {\n      if (responseFinished) return;\n      responseFinished = true;\n      resolveResponseFinished();\n    },\n    phase: \"open\",\n    reportError,\n    tasks: [],\n  };\n\n  state.completion = responseFinishedPromise.then(() =>\n    afterStorage.run(state, async () => {\n      state.phase = \"running\";\n\n      for (let index = 0; index < state.tasks.length; index++) {\n        const task = state.tasks[index];\n        task.start();\n        try {\n          await task.result;\n        } catch (error) {\n          reportAfterError(state, error);\n        }\n      }\n\n      state.phase = \"closed\";\n    }),\n  );\n\n  return state;\n}\n\nfunction registerPlatformLifetime(\n  state: AfterRequestState,\n  context: FarmAfterPlatformContext | undefined,\n): void {\n  if (!context?.waitUntil) return;\n\n  try {\n    context.waitUntil(state.completion);\n  } catch (error) {\n    reportAfterError(state, error);\n  }\n}\n\nfunction registerResponseFinishedHook(\n  state: AfterRequestState,\n  context: FarmAfterPlatformContext | undefined,\n): boolean {\n  if (!context?.onResponseFinished) return false;\n\n  try {\n    context.onResponseFinished(state.finishResponse);\n    return true;\n  } catch (error) {\n    reportAfterError(state, error);\n    return false;\n  }\n}\n\nfunction finishSoon(state: AfterRequestState): void {\n  setTimeout(state.finishResponse, 0);\n}\n\nfunction wrapResponseBody(\n  response: Response,\n  request: Request,\n  state: AfterRequestState,\n): Response {\n  if (\n    request.method === \"HEAD\" ||\n    response.status < 200 ||\n    response.status > 599 ||\n    !response.body ||\n    response.bodyUsed ||\n    response.body.locked\n  ) {\n    finishSoon(state);\n    return response;\n  }\n\n  const reader = response.body.getReader();\n  let released = false;\n  const releaseReader = () => {\n    if (released) return;\n    released = true;\n    reader.releaseLock();\n  };\n\n  const body = new ReadableStream<Uint8Array>({\n    async pull(controller) {\n      try {\n        const chunk = await reader.read();\n        if (chunk.done) {\n          releaseReader();\n          controller.close();\n          finishSoon(state);\n          return;\n        }\n        controller.enqueue(chunk.value);\n      } catch (error) {\n        releaseReader();\n        controller.error(error);\n        finishSoon(state);\n      }\n    },\n    cancel(reason) {\n      try {\n        // Preserve the caller's cleanup promise, but response completion must\n        // not depend on whether producer-owned cancellation ever settles.\n        return reader.cancel(reason);\n      } finally {\n        releaseReader();\n        finishSoon(state);\n      }\n    },\n  });\n\n  return new Response(body, {\n    headers: response.headers,\n    status: response.status,\n    statusText: response.statusText,\n  });\n}\n\n/**\n * Schedule non-blocking work for after the current response finishes.\n *\n * Callbacks run in registration order. A callback failure is reported without\n * changing the response or preventing later callbacks from running.\n */\nexport function after(callback: AfterCallback): void {\n  if (typeof callback !== \"function\") {\n    throw new TypeError(\"after() expects a callback function.\");\n  }\n\n  const state = afterStorage.getStore();\n  if (!state) {\n    throw new Error(\"after() can only be used while Farm is handling a server request.\");\n  }\n  if (state.phase === \"closed\") {\n    throw new Error(\"after() cannot schedule work after the request lifecycle has completed.\");\n  }\n\n  let start!: () => void;\n  const ready = new Promise<void>((resolve) => {\n    start = resolve;\n  });\n\n  // Registering the continuation here preserves every request AsyncLocalStorage\n  // context that is active at the after() call site.\n  const result = ready.then(callback);\n  state.tasks.push({ result, start });\n}\n\n/** @internal Run a Web Request handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterRequest(\n  request: Request,\n  handler: () => Response | Promise<Response>,\n  context?: FarmAfterPlatformContext,\n): Promise<Response> {\n  if (afterStorage.getStore()) {\n    return await handler();\n  }\n\n  const state = createAfterRequestState();\n  registerPlatformLifetime(state, context);\n  const hasResponseHook = registerResponseFinishedHook(state, context);\n\n  try {\n    const response = await afterStorage.run(state, handler);\n    return hasResponseHook ? response : wrapResponseBody(response, request, state);\n  } catch (error) {\n    // The handler threw, so there is no successful response for a\n    // response-finished hook to fire on. Run the after-lifecycle now regardless\n    // of the hook; otherwise a spec-compliant adapter (whose hook only fires on\n    // a real response) never runs the registered after() callbacks and\n    // waitUntil(state.completion) hangs forever. finishResponse is idempotent,\n    // so a later hook firing (e.g. a Node error response's close) is a no-op.\n    finishSoon(state);\n    throw error;\n  }\n}\n\n/** @internal Run a Node response handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterNodeResponse<T>(\n  response: ServerResponse,\n  handler: () => T | Promise<T>,\n  context?: Pick<FarmAfterPlatformContext, \"waitUntil\">,\n): Promise<T> {\n  if (afterStorage.getStore()) {\n    return await handler();\n  }\n\n  const state = createAfterRequestState();\n  let finished = false;\n  const finish = () => {\n    if (finished) return;\n    finished = true;\n    response.off(\"finish\", finish);\n    response.off(\"close\", finish);\n    state.finishResponse();\n  };\n\n  response.once(\"finish\", finish);\n  response.once(\"close\", finish);\n  if (response.writableEnded) finishSoon(state);\n  registerPlatformLifetime(state, context);\n\n  return await afterStorage.run(state, handler);\n}\n\n/** @internal Add Farm's post-response lifecycle to a Node middleware. */\nexport function _withAfterNodeMiddleware(\n  handler: (\n    request: IncomingMessage,\n    response: ServerResponse,\n    next: (error?: unknown) => void,\n  ) => void | Promise<void>,\n): (\n  request: IncomingMessage,\n  response: ServerResponse,\n  next: (error?: unknown) => void,\n) => Promise<void> {\n  return async (request, response, next) => {\n    await _runWithAfterNodeResponse(response, () => handler(request, response, next));\n  };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { setAPIRequestRuntimeResolver, type APIRequestRuntime } from \"./server-client-bridge\";\n\nconst API_RUNTIME_STORAGE = Symbol.for(\"@farm.js/core/api-request-storage\");\nconst runtimeGlobal = globalThis as typeof globalThis & {\n  [API_RUNTIME_STORAGE]?: AsyncLocalStorage<APIRequestRuntime>;\n};\nconst storage = (runtimeGlobal[API_RUNTIME_STORAGE] ??= new AsyncLocalStorage<APIRequestRuntime>());\nsetAPIRequestRuntimeResolver(() => storage.getStore());\n\n/** Bind the owning app's live route dispatcher, never a process-wide route table. */\nexport function _runWithAPIRequestRuntime<T>(runtime: APIRequestRuntime, run: () => T): T {\n  return storage.run(runtime, run);\n}\n","/** 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 * as fs from \"fs\";\nimport * as path from \"path\";\n\ninterface DottedPathRouteMatcher {\n  matchRoute(pathname: string): { route: unknown } | null | undefined;\n  matchMetadataRoute(pathname: string): object | null;\n  matchMetadataImage(pathname: string): object | null;\n}\n\n/**\n * Decide whether the dev server should hand a dotted request path to the\n * static pipeline instead of Farm's renderer. Dotted paths are usually asset\n * requests, but they are also how page routes with dotted segments and\n * application metadata routes (/manifest.webmanifest, /sitemap.xml,\n * /robots.txt, generated metadata images) are addressed, so the router is\n * only bypassed when nothing in the app matches the pathname or a real file\n * shadows it.\n */\nexport function shouldBypassFarmRouterForDottedPath(\n  pathname: string,\n  routeManager: DottedPathRouteMatcher | null | undefined,\n  baseDirs: Array<string | false | undefined>,\n): boolean {\n  if (!pathname.includes(\".\") || pathname.endsWith(\".html\")) return false;\n  const matchesAppRoute = Boolean(\n    routeManager?.matchRoute(pathname)?.route ||\n    routeManager?.matchMetadataRoute(pathname) ||\n    routeManager?.matchMetadataImage(pathname),\n  );\n  return !matchesAppRoute || devServableFileExists(pathname, baseDirs);\n}\n\n/**\n * Route segments may legitimately contain dots (e.g. /kinfish/farm.js), so a\n * dot alone cannot classify a dev request as a static asset. A dotted path is\n * only treated as an asset when it maps to a real file under one of the\n * servable base dirs (project root, public dir), matching the\n * filesystem-first behavior of production hosting.\n */\nexport function devServableFileExists(\n  pathname: string,\n  baseDirs: Array<string | false | undefined>,\n): boolean {\n  let decodedPathname: string;\n  try {\n    decodedPathname = decodeURIComponent(pathname);\n  } catch {\n    return false;\n  }\n  const relativePathname = decodedPathname.replace(/^\\/+/, \"\");\n  if (!relativePathname) return false;\n  for (const baseDir of baseDirs) {\n    if (typeof baseDir !== \"string\" || baseDir.length === 0) continue;\n    const resolvedBase = path.resolve(baseDir);\n    const candidate = path.resolve(resolvedBase, relativePathname);\n    if (!candidate.startsWith(resolvedBase + path.sep)) continue;\n    try {\n      if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {\n        return true;\n      }\n    } catch {\n      // Ignore filesystem errors and keep checking other base dirs.\n    }\n  }\n  return false;\n}\n","const SERVER_FN_FACTORIES = [\"createServerQuery\", \"createServerFn\"] as const;\n\nconst FARM_CORE_IMPORT_RE =\n  /import\\s*(?!type\\b)(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*([\"'])@farm\\.js\\/core(?:\\/[\\w./-]+)?\\2/g;\n\nexport type ServerFnBoundaryViolation = {\n  factory: (typeof SERVER_FN_FACTORIES)[number];\n};\n\n/**\n * Detect a module that defines a Farm server function (createServerQuery /\n * createServerFn) while being compiled for the client environment. Without\n * the server-function transform (@farm.js/plugin/rsc with\n * experimental.serverActions enabled) there is no client stub: the server\n * handler and its dependency graph would be bundled into the browser and\n * executed there, surfacing as confusing Vite externalization errors for\n * Node built-ins (#408).\n */\nexport function findClientServerFnViolation(\n  code: string,\n  id: string,\n): ServerFnBoundaryViolation | null {\n  if (id.startsWith(\"\\0\") || id.startsWith(\"virtual:\") || id.includes(\"node_modules\")) return null;\n  // Markdown modules never execute import statements: matched text is\n  // documentation (fenced code examples), not code, before and after the\n  // markdown transform (fences compile to string content).\n  if (/\\.(md|mdx)(\\?|$)/.test(id)) return null;\n  if (!code.includes(\"@farm.js/core\")) return null;\n\n  for (const match of code.matchAll(FARM_CORE_IMPORT_RE)) {\n    const specifiers = match[1];\n    for (const factory of SERVER_FN_FACTORIES) {\n      if (!new RegExp(`(?:^|[\\\\s{,])${factory}(?:[\\\\s},]|$)`).test(specifiers)) continue;\n      // Only a call site makes the module a server-function definition; a\n      // type-only or re-exported symbol never executes a handler.\n      if (new RegExp(`(?<![\\\\w$.])${factory}\\\\s*(?:<[^>]*>)?\\\\s*\\\\(`).test(code)) {\n        return { factory };\n      }\n    }\n  }\n  return null;\n}\n\nexport function formatServerFnBoundaryError(\n  violation: ServerFnBoundaryViolation,\n  id: string,\n): string {\n  return [\n    `${violation.factory} handlers run only on the server, but ${id} is being bundled into the client.`,\n    `Importing a ${violation.factory} module from client code executes the server handler (and its Node-only imports) in the browser.`,\n    `Either enable the server-function transform (add @farm.js/plugin/rsc and set experimental.serverActions: true in farm.config.ts) so client imports become server references,`,\n    `or keep the query on the server: call it from server components, or expose an API route and use createAPIClient from the client.`,\n  ].join(\"\\n\");\n}\n","/**\n * Diagnostics for server-only access in modules compiled for the client.\n *\n * A module entering the client graph runs in the browser. Module-scope reads\n * of non-public process.env values evaluate to undefined there and broke\n * layout hydration in #560, and node: builtin imports are silently stubbed\n * with empty objects by farm:browser-external-stub. Both deserve a clear\n * build-time warning naming the module instead of a runtime mystery (#1065).\n */\n\ntype EstreeNode = { type: string; [key: string]: unknown };\n\nconst FUNCTION_BODY_TYPES = new Set([\n  \"FunctionDeclaration\",\n  \"FunctionExpression\",\n  \"ArrowFunctionExpression\",\n]);\n\nexport function shouldInspectClientBoundary(id: string, code: string): boolean {\n  if (id.startsWith(\"\\0\") || id.startsWith(\"virtual:\") || id.includes(\"node_modules\")) return false;\n  return code.includes(\"process.env\") || code.includes(\"node:\");\n}\n\nexport interface ClientBoundaryFindings {\n  /** Non-public process.env keys read at module scope. */\n  envKeys: string[];\n  /**\n   * Declared-public keys read via process.env at module scope. The value is\n   * still undefined in the browser — only publicEnv is populated there — so\n   * these get their own warning pointing at the supported accessor.\n   */\n  publicEnvKeys: string[];\n  /** node: builtin specifiers imported into the module. */\n  builtinImports: string[];\n}\n\n/**\n * One walk over the module AST for both diagnostics.\n *\n * Reads and dynamic imports inside function bodies are skipped: they may be\n * server-gated at runtime — a lazy `await import(\"node:fs\")` behind a server\n * check is the recommended escape hatch — and flagging them would drown the\n * signal in noise. Static import/export-from declarations always execute at\n * module scope, so they are always flagged.\n */\nexport function analyzeClientBoundary(\n  program: EstreeNode,\n  publicKeys: ReadonlySet<string>,\n): ClientBoundaryFindings {\n  const envKeys = new Set<string>();\n  const publicEnvKeys = new Set<string>();\n  const builtinImports = new Set<string>();\n\n  const visit = (node: unknown, inFunction: boolean): void => {\n    if (!node || typeof node !== \"object\") return;\n    if (Array.isArray(node)) {\n      for (const entry of node) visit(entry, inFunction);\n      return;\n    }\n    const estree = node as EstreeNode;\n    if (typeof estree.type !== \"string\") return;\n\n    if (!inFunction) {\n      const builtin = readNodeBuiltinSource(estree);\n      if (builtin !== undefined) builtinImports.add(builtin);\n\n      const key = readProcessEnvKey(estree);\n      if (key !== undefined) {\n        if (key !== \"NODE_ENV\") {\n          (publicKeys.has(key) ? publicEnvKeys : envKeys).add(key);\n        }\n        return;\n      }\n    }\n\n    // Params and defaults evaluate at call time along with the body.\n    const nextInFunction = inFunction || FUNCTION_BODY_TYPES.has(estree.type);\n    for (const [childKey, value] of Object.entries(estree)) {\n      if (childKey === \"type\") continue;\n      visit(value, nextInFunction);\n    }\n  };\n\n  visit((program as { body?: unknown }).body, false);\n  return {\n    envKeys: [...envKeys],\n    publicEnvKeys: [...publicEnvKeys],\n    builtinImports: [...builtinImports],\n  };\n}\n\nfunction readNodeBuiltinSource(node: EstreeNode): string | undefined {\n  if (\n    node.type === \"ImportDeclaration\" ||\n    node.type === \"ExportNamedDeclaration\" ||\n    node.type === \"ExportAllDeclaration\" ||\n    node.type === \"ImportExpression\"\n  ) {\n    const value = (node.source as { value?: unknown } | null | undefined)?.value;\n    return typeof value === \"string\" && value.startsWith(\"node:\") ? value : undefined;\n  }\n  if (node.type === \"CallExpression\") {\n    const callee = node.callee as EstreeNode | undefined;\n    if (callee?.type === \"Identifier\" && (callee as { name?: string }).name === \"require\") {\n      const arg = (node.arguments as EstreeNode[] | undefined)?.[0];\n      const value = arg?.type === \"Literal\" ? (arg as { value?: unknown }).value : undefined;\n      return typeof value === \"string\" && value.startsWith(\"node:\") ? value : undefined;\n    }\n  }\n  return undefined;\n}\n\nfunction readProcessEnvKey(node: EstreeNode): string | undefined {\n  if (node.type !== \"MemberExpression\") return undefined;\n  const object = node.object as EstreeNode | undefined;\n  if (\n    !object ||\n    object.type !== \"MemberExpression\" ||\n    (object.object as EstreeNode | undefined)?.type !== \"Identifier\" ||\n    (object.object as { name?: string }).name !== \"process\" ||\n    (object.property as { name?: string })?.name !== \"env\"\n  ) {\n    return undefined;\n  }\n\n  const property = node.property as EstreeNode | undefined;\n  if (!property) return undefined;\n  if (!node.computed && property.type === \"Identifier\") {\n    return (property as { name?: string }).name;\n  }\n  if (node.computed && property.type === \"Literal\") {\n    const value = (property as { value?: unknown }).value;\n    return typeof value === \"string\" ? value : undefined;\n  }\n  return undefined;\n}\n\nexport function formatClientBoundaryWarning(id: string, findings: ClientBoundaryFindings): string {\n  const { envKeys, publicEnvKeys, builtinImports } = findings;\n  const lines = [`${id} is compiled for the client but uses server-only APIs:`];\n  if (envKeys.length > 0) {\n    lines.push(\n      `- module-scope read of process.env.${envKeys.join(\", process.env.\")} — undefined in the browser. Move the read behind a server boundary, or expose it through env.public in farm.config.ts.`,\n    );\n  }\n  if (publicEnvKeys.length > 0) {\n    lines.push(\n      `- module-scope read of process.env.${publicEnvKeys.join(\", process.env.\")} — process.env is not populated in the browser even for public keys. Read it through publicEnv from \"@farm.js/core/env\".`,\n    );\n  }\n  if (builtinImports.length > 0) {\n    lines.push(\n      `- import of ${builtinImports.join(\", \")} — stubbed with an empty object in the browser. Move the import into server-only code.`,\n    );\n  }\n  return lines.join(\"\\n\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { imageSize } from \"image-size\";\nimport type { Plugin } from \"vite\";\n\nconst FARM_IMAGE_ID_PREFIX = \"\\0farm:image:\";\nconst STATIC_IMAGE_RE = /\\.(?:avif|gif|jpe?g|png|webp)$/i;\nconst SCRIPT_IMPORTER_RE = /\\.(?:[cm]?[jt]sx?|mdx?)$/i;\n\nexport function farmImageImportsPlugin(): Plugin {\n  return {\n    name: \"farm-image-imports\",\n    enforce: \"pre\",\n\n    async resolveId(source, importer, options) {\n      if (\n        !importer ||\n        source.includes(\"?\") ||\n        !STATIC_IMAGE_RE.test(source) ||\n        !SCRIPT_IMPORTER_RE.test(importer.split(\"?\", 1)[0])\n      ) {\n        return null;\n      }\n\n      const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n      if (!resolved || resolved.external) return null;\n\n      return `${FARM_IMAGE_ID_PREFIX}${encodeURIComponent(resolved.id.split(\"?\", 1)[0])}`;\n    },\n\n    async load(id) {\n      if (!id.startsWith(FARM_IMAGE_ID_PREFIX)) return null;\n\n      const filePath = decodeURIComponent(id.slice(FARM_IMAGE_ID_PREFIX.length));\n      const assetRequest = `${filePath.replace(/\\\\/g, \"/\")}?url`;\n      return createStaticImageModule(filePath, `import src from ${JSON.stringify(assetRequest)};`);\n    },\n\n    async transform(code, id) {\n      const filePath = id.split(\"?\", 1)[0];\n      if (id.includes(\"?\") || !STATIC_IMAGE_RE.test(filePath)) return null;\n\n      const defaultExport = code.match(/^\\s*export\\s+default\\s+(.+?);?\\s*$/s)?.[1];\n      if (!defaultExport) return null;\n      return createStaticImageModule(filePath, `const src = ${defaultExport};`);\n    },\n  };\n}\n\nasync function createStaticImageModule(\n  filePath: string,\n  sourceDeclaration: string,\n): Promise<string> {\n  const bytes = await readFile(filePath);\n  const dimensions = imageSize(bytes);\n  if (!dimensions.width || !dimensions.height) {\n    throw new Error(`Could not determine image dimensions for ${filePath}`);\n  }\n\n  const blurDataURL = await createBlurDataURL(bytes);\n  return [\n    sourceDeclaration,\n    `const image = ${JSON.stringify({\n      width: dimensions.width,\n      height: dimensions.height,\n      ...(blurDataURL ? { blurDataURL } : {}),\n    })};`,\n    \"image.src = src;\",\n    \"export { src };\",\n    \"export const width = image.width;\",\n    \"export const height = image.height;\",\n    \"export const blurDataURL = image.blurDataURL;\",\n    \"export default image;\",\n  ].join(\"\\n\");\n}\n\nasync function createBlurDataURL(bytes: Buffer): Promise<string | undefined> {\n  try {\n    const { default: sharp } = await import(\"sharp\");\n    const placeholder = await sharp(bytes)\n      .rotate()\n      .resize({ width: 8, height: 8, fit: \"inside\", withoutEnlargement: true })\n      .webp({ quality: 35 })\n      .toBuffer();\n    return `data:image/webp;base64,${placeholder.toString(\"base64\")}`;\n  } catch {\n    return undefined;\n  }\n}\n\nexport function isFarmStaticImageFile(filePath: string): boolean {\n  return STATIC_IMAGE_RE.test(path.extname(filePath));\n}\n","export type FarmFontDisplay = \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n\nexport interface FarmFontSource {\n  /** Local file path or remote URL, depending on the loader. */\n  path: string;\n  /** A fixed weight (`400`) or variable range (`100 900`). */\n  weight?: number | string;\n  /** Font style for this source. */\n  style?: string;\n  /** Optional CSS unicode-range descriptor. */\n  unicodeRange?: string;\n}\n\nexport interface FarmFontOptions {\n  /** CSS font-family name. */\n  family: string;\n  /** A fixed weight (`400`) or variable range (`100 900`). */\n  weight?: number | string;\n  /** Font style. @default \"normal\" */\n  style?: string;\n  /** Browser loading behavior. @default \"swap\" */\n  display?: FarmFontDisplay;\n  /** CSS custom property populated by `variable`, for example `--font-sans`. */\n  variable?: `--${string}`;\n  /** Fallback family names appended to the generated stack. */\n  fallback?: string[];\n  /** Emit font preload hints. @default true */\n  preload?: boolean;\n}\n\nexport interface LocalFontOptions extends FarmFontOptions {\n  /**\n   * A file relative to this module, a package font specifier, or explicit\n   * sources for a multi-weight family.\n   */\n  src: string | FarmFontSource[];\n}\n\nexport interface RemoteFontSource extends FarmFontSource {\n  /** Optional integrity value for this source. Overrides the family-level value. */\n  integrity?: string;\n}\n\nexport interface RemoteFontOptions extends FarmFontOptions {\n  /** HTTPS font URL, or explicit remote sources for a multi-weight family. */\n  src: string | RemoteFontSource[];\n  /** Download and fingerprint the font during the build, or retain its URL. */\n  strategy?: \"self-host\" | \"external\";\n  /** Optional Subresource Integrity value checked while self-hosting. */\n  integrity?: string;\n}\n\nexport interface FarmFont {\n  /** Generated class that applies the font family and fallback stack. */\n  className: string;\n  /** Generated class that defines the configured CSS custom property. */\n  variable: string;\n  /** Inline-style equivalent of the generated family. */\n  style: Readonly<{\n    fontFamily: string;\n    fontStyle?: string;\n    fontWeight?: number | string;\n  }>;\n  /** Compiled resources that should be preloaded when this font is selected. */\n  preloads: readonly Readonly<{\n    href: string;\n    type: string;\n  }>[];\n}\n\n/** Semantic font roles inherited by framework-owned surfaces such as Farm Docs. */\nexport interface FarmLayoutFonts {\n  /** Default text and prose font. */\n  body?: FarmFont;\n  /** Code, keyboard input, and other technical UI font. */\n  code?: FarmFont;\n}\n\nexport interface FarmLayoutFontModule {\n  fonts?: FarmLayoutFonts;\n}\n\n/**\n * Define the semantic fonts exported by a layout.\n *\n * Layouts are resolved from the root toward the requested route. A nearer\n * layout overrides only the roles it defines, so it can replace `body` while\n * continuing to inherit `code` from a parent layout.\n */\nexport function defineLayoutFonts<const T extends FarmLayoutFonts>(fonts: T): T {\n  return fonts;\n}\n\n/** Resolve semantic font roles from root layout to nearest layout. */\nexport function resolveFarmLayoutFonts(\n  layouts: readonly FarmLayoutFontModule[],\n): FarmLayoutFonts | undefined {\n  let resolved: FarmLayoutFonts | undefined;\n\n  for (const layout of layouts) {\n    if (!layout.fonts) continue;\n    resolved = { ...resolved, ...layout.fonts };\n  }\n\n  return resolved;\n}\n\nfunction fontCompilerError(loader: string): never {\n  throw new Error(\n    `[Farm fonts] ${loader}() must be called at module scope with static options and compiled by the Farm Vite plugin.`,\n  );\n}\n\n/**\n * Compile local font files into hashed application assets and generated CSS.\n * The call is removed at build time and adds no font-loader runtime code.\n */\nexport function localFont(_options: LocalFontOptions): FarmFont {\n  return fontCompilerError(\"localFont\");\n}\n\n/**\n * Compile a remote font into a self-hosted application asset by default.\n * Use `strategy: \"external\"` only when the browser should retain the remote URL.\n */\nexport function remoteFont(_options: RemoteFontOptions): FarmFont {\n  return fontCompilerError(\"remoteFont\");\n}\n","import path from \"node:path\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport type { FarmRenderer } from \"../renderer\";\n\nconst FARM_CLIENT_ENTRY_PATTERN =\n  \"**/{page,layout,loading,error,not-found,default}.{js,jsx,ts,tsx}\";\n\n/**\n * Client runtimes that must be optimized in the same generation as React.\n * Farm loads route modules dynamically, so Vite's HTML crawl cannot reliably\n * discover these linked-package entry points before hydration begins.\n */\nexport const FARM_CLIENT_OPTIMIZE_DEPS_INCLUDE = [\n  \"react\",\n  \"react-dom\",\n  \"react-dom/client\",\n  \"react/jsx-runtime\",\n  \"react/jsx-dev-runtime\",\n  \"@farm.js/core/client\",\n  \"@farm.js/core/plugin/client\",\n  \"@farm.js/core/deferred\",\n  \"@farm.js/core/deployment\",\n  \"@farm.js/core/i18n/client\",\n  \"@farm.js/core/query/client\",\n  \"@farm.js/core/server-fn/client\",\n  \"@farm.js/core/server-query/client\",\n] as const;\n\nexport function getFarmClientOptimizeDepsInclude(renderer?: FarmRenderer): string[] {\n  return Array.from(\n    new Set([...FARM_CLIENT_OPTIMIZE_DEPS_INCLUDE, ...(renderer?.optimizeDeps || [])]),\n  );\n}\n\nexport function createFarmClientOptimizeDepsEntries(\n  projectRoot: string,\n  appDirectories: readonly string[],\n): string[] {\n  const resolvedProjectRoot = path.resolve(projectRoot);\n\n  return appDirectories.map((appDirectory) => {\n    const relativeAppDirectory = path\n      .relative(resolvedProjectRoot, path.resolve(appDirectory))\n      .replace(/\\\\/g, \"/\");\n    const prefix = relativeAppDirectory || \".\";\n    return `${prefix}/${FARM_CLIENT_ENTRY_PATTERN}`;\n  });\n}\n\nexport function createFarmClientOptimizeDepsConfig(\n  entries?: readonly string[],\n  renderer?: FarmRenderer,\n): ViteUserConfig[\"optimizeDeps\"] {\n  return {\n    // Keep normal application dependency discovery for CJS-only packages, but\n    // seed every Farm browser runtime so React is present in the first crawl.\n    noDiscovery: false,\n    // Waiting for the crawl avoids serving a partial optimizer generation and\n    // then changing browser hashes while hydration is already in progress.\n    holdUntilCrawlEnd: true,\n    include: getFarmClientOptimizeDepsInclude(renderer),\n    // Farm's HTML boots through a virtual module and imports route UI lazily.\n    // Explicit entries let Vite finish that crawl before a navigation can\n    // rotate the optimizer hash underneath a hydrated React runtime.\n    ...(entries?.length ? { entries: [...entries] } : {}),\n  };\n}\n\n/**\n * Farm's application-source alias. Keep this shared by development, route\n * discovery, and production bundling so `@/…` always follows `srcDir`.\n */\nexport function createFarmSourceAlias(projectRoot: string, srcDir = \"src\"): Record<string, string> {\n  return {\n    \"@\": path.resolve(projectRoot, srcDir),\n  };\n}\n\ntype ViteNoExternal = NonNullable<NonNullable<ViteUserConfig[\"ssr\"]>[\"noExternal\"]>;\ntype ViteAlias = NonNullable<NonNullable<ViteUserConfig[\"resolve\"]>[\"alias\"]>;\n\nfunction mergeNoExternal(\n  farmValue: ViteNoExternal | undefined,\n  userValue: ViteNoExternal | undefined,\n): ViteNoExternal {\n  if (farmValue === true || userValue === true) return true;\n\n  const normalize = (value: ViteNoExternal | undefined): Array<string | RegExp> =>\n    value == null || value === true ? [] : Array.isArray(value) ? value : [value];\n\n  return Array.from(new Set([...normalize(farmValue), ...normalize(userValue)]));\n}\n\nfunction mergeAlias(farmValue: ViteAlias | undefined, userValue: ViteAlias | undefined): ViteAlias {\n  if (!farmValue) return userValue || {};\n  if (!userValue) return farmValue;\n\n  if (!Array.isArray(farmValue) && !Array.isArray(userValue)) {\n    return {\n      ...farmValue,\n      ...userValue,\n    };\n  }\n\n  const normalize = (value: ViteAlias): Exclude<ViteAlias, Record<string, string>> =>\n    Array.isArray(value)\n      ? [...value]\n      : Object.entries(value).map(([find, replacement]) => ({ find, replacement }));\n\n  // Vite uses the first matching array entry. Put application entries first\n  // so an explicit user alias can intentionally override a Farm default.\n  return [...normalize(userValue), ...normalize(farmValue)];\n}\n\nexport function mergeFarmViteConfig(\n  farmConfig: ViteUserConfig,\n  userConfig: ViteUserConfig = {},\n): ViteUserConfig {\n  const noDiscovery = userConfig.optimizeDeps?.noDiscovery ?? farmConfig.optimizeDeps?.noDiscovery;\n  const holdUntilCrawlEnd =\n    userConfig.optimizeDeps?.holdUntilCrawlEnd ??\n    (userConfig.optimizeDeps?.noDiscovery === true\n      ? false\n      : farmConfig.optimizeDeps?.holdUntilCrawlEnd);\n\n  return {\n    ...farmConfig,\n    ...userConfig,\n    plugins: [...(farmConfig.plugins || []), ...(userConfig.plugins || [])],\n    server: {\n      ...farmConfig.server,\n      ...userConfig.server,\n    },\n    resolve: {\n      ...farmConfig.resolve,\n      ...userConfig.resolve,\n      alias: mergeAlias(farmConfig.resolve?.alias, userConfig.resolve?.alias),\n      dedupe: Array.from(\n        new Set([...(farmConfig.resolve?.dedupe || []), ...(userConfig.resolve?.dedupe || [])]),\n      ),\n    },\n    optimizeDeps: {\n      ...farmConfig.optimizeDeps,\n      ...userConfig.optimizeDeps,\n      noDiscovery,\n      holdUntilCrawlEnd,\n      include: Array.from(\n        new Set([\n          ...(farmConfig.optimizeDeps?.include || []),\n          ...(userConfig.optimizeDeps?.include || []),\n        ]),\n      ),\n      exclude: Array.from(\n        new Set([\n          ...(farmConfig.optimizeDeps?.exclude || []),\n          ...(userConfig.optimizeDeps?.exclude || []),\n        ]),\n      ),\n    },\n    ssr: {\n      ...farmConfig.ssr,\n      ...userConfig.ssr,\n      noExternal: mergeNoExternal(farmConfig.ssr?.noExternal, userConfig.ssr?.noExternal),\n    },\n  };\n}\n","import type { Plugin } from \"vite\";\nimport { resolveFarmThemeConfig } from \"./config\";\nimport type { FarmThemeConfig, ResolvedFarmThemeConfig } from \"./types\";\n\nconst FARM_DARK_VARIANT =\n  '@custom-variant dark (&:where([data-theme=\"dark\"], [data-theme=\"dark\"] *));';\n\nexport function createFarmThemeCssPlugin(\n  input: FarmThemeConfig | ResolvedFarmThemeConfig | false | undefined,\n  basePath = \"/\",\n): Plugin {\n  const config = resolveFarmThemeConfig(input, basePath);\n\n  return {\n    name: \"farm:theme-css\",\n    enforce: \"pre\",\n    transform(code, id) {\n      if (\n        !config.enabled ||\n        !/\\.css(?:\\?.*)?$/.test(id) ||\n        !/@import\\s+[\"']tailwindcss[\"']/.test(code) ||\n        /@custom-variant\\s+dark\\b/.test(code)\n      ) {\n        return null;\n      }\n\n      return {\n        code: `${code.trimEnd()}\\n\\n${FARM_DARK_VARIANT}\\n`,\n        map: null,\n      };\n    },\n  };\n}\n","import path from \"node:path\";\nimport type { FarmIntegrationProvider } from \"./integrations\";\nimport { isFarmIntegrationProviderComponentReference } from \"./integrations\";\nimport { toViteModuleId } from \"./utils\";\n\nexport type FarmIntegrationProviderClientCode = {\n  hasProviders: boolean;\n  imports: string;\n  runtime: string;\n};\n\nexport function generateFarmIntegrationProviderClientCode(\n  providers: FarmIntegrationProvider[],\n  root: string,\n): FarmIntegrationProviderClientCode {\n  const renderedProviders = providers.filter(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  const imports: string[] = [];\n  const registrations: string[] = [];\n  let hasClerkProvider = false;\n\n  renderedProviders.forEach((provider, index) => {\n    let componentExpression = \"null\";\n    if (isFarmIntegrationProviderComponentReference(provider.component)) {\n      const namespace = `FarmIntegrationProviderModule${index}`;\n      imports.push(\n        `import * as ${namespace} from ${JSON.stringify(resolveProviderModule(provider.component.module, root))};`,\n      );\n      componentExpression = `${namespace}[${JSON.stringify(provider.component.export || \"default\")}]`;\n    } else if (typeof provider.component === \"function\") {\n      throw new Error(\n        `Integration provider \"${provider.name}\" must use an importable component reference for client hydration, for example component: { module: \"@/components/provider\" }.`,\n      );\n    } else if (provider.type === \"clerk\") {\n      hasClerkProvider = true;\n      componentExpression = \"FarmClerkProvider\";\n    }\n\n    registrations.push(`{\n  name: ${JSON.stringify(provider.name)},\n  type: ${JSON.stringify(provider.type)},\n  props: ${JSON.stringify(provider.props || {})},\n  Component: ${componentExpression},\n}`);\n  });\n\n  if (hasClerkProvider) {\n    imports.unshift(`import { ClerkProvider as FarmClerkProvider } from \"@clerk/react\";`);\n  }\n\n  return {\n    hasProviders: renderedProviders.length > 0,\n    imports: imports.join(\"\\n\"),\n    runtime: `const integrationProviders = [${registrations.join(\",\\n\")}];\n\nfunction wrapWithIntegrationProviders(element) {\n  let wrapped = element;\n  for (let index = integrationProviders.length - 1; index >= 0; index--) {\n    const provider = integrationProviders[index];\n    if (!provider.Component) {\n      throw new Error(\"Integration provider \" + provider.name + \" did not export its configured component.\");\n    }\n    wrapped = React.createElement(provider.Component, provider.props || {}, wrapped);\n  }\n  return wrapped;\n}`,\n  };\n}\n\nexport function createFarmIntegrationProviderModuleKey(component: {\n  module: string;\n  export?: string;\n}): string {\n  return `${component.module}\\0${component.export || \"default\"}`;\n}\n\nexport function generateFarmIntegrationProviderServerModules(\n  providers: FarmIntegrationProvider[],\n  root: string,\n): { imports: string; entries: string; hasClerkProvider: boolean } {\n  const imports: string[] = [];\n  const entries: string[] = [];\n\n  providers.forEach((provider, index) => {\n    if (!isFarmIntegrationProviderComponentReference(provider.component)) return;\n    const namespace = `FarmServerIntegrationProviderModule${index}`;\n    imports.push(\n      `import * as ${namespace} from ${JSON.stringify(resolveProviderModule(provider.component.module, root))};`,\n    );\n    entries.push(\n      `[${JSON.stringify(createFarmIntegrationProviderModuleKey(provider.component))}, ${namespace}[${JSON.stringify(provider.component.export || \"default\")}]]`,\n    );\n  });\n\n  return {\n    imports: imports.join(\"\\n\"),\n    entries: entries.join(\",\\n\"),\n    hasClerkProvider: providers.some(\n      (provider) => provider.type === \"clerk\" && !provider.component,\n    ),\n  };\n}\n\nfunction resolveProviderModule(moduleId: string, root: string): string {\n  if (!moduleId.startsWith(\".\")) return moduleId;\n  return toViteModuleId(path.resolve(root, moduleId), root);\n}\n","import { isFarmNotFoundError } from \"../navigation-errors\";\n\nexport interface FarmPageDataFailure {\n  status: number;\n  payload: {\n    error: string;\n    message: string;\n    code?: string;\n  };\n}\n\n/**\n * Preserve expected route outcomes when a page-data render fails. Internal\n * navigation must report the same HTTP class as a full document render so a\n * missing resource never masquerades as a framework crash.\n */\nexport function resolveFarmPageDataFailure(error: unknown): FarmPageDataFailure {\n  if (isFarmNotFoundError(error)) {\n    return {\n      status: 404,\n      payload: {\n        error: \"Route not found\",\n        message: \"The requested route did not resolve to a resource.\",\n        code: \"FARM_NOT_FOUND\",\n      },\n    };\n  }\n\n  if (error instanceof Response) {\n    return {\n      status: error.status || 500,\n      payload: {\n        error: error.statusText || \"Page data request failed\",\n        message: error.statusText || `The route returned HTTP ${error.status || 500}.`,\n      },\n    };\n  }\n\n  return {\n    status: 500,\n    payload: {\n      error: \"Failed to load page data\",\n      message: error instanceof Error ? error.message : \"Unknown error\",\n    },\n  };\n}\n","import type { FarmPlugin, FarmPluginContext } from \"../plugin\";\nimport type { RewriteConfig } from \"../config\";\nimport type { FarmRequest, FarmResponse } from \"../types\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { resolveFarmRequestURL } from \"../server/request\";\nimport {\n  compileConfigRoutePattern,\n  interpolateConfigRouteDestination,\n  localizeConfigRouteDestination,\n  resolveConfigRoutePathname,\n} from \"./route-pattern\";\n\nexport const FARM_CONFIG_REWRITES_PLUGIN_NAME = \"farm:rewrites\";\n\nexport function createRewritesPlugin(\n  rewrites: RewriteConfig[],\n  {\n    beforeRequest: overrideBeforeRequest,\n    afterResponse: overrideAfterResponse,\n    i18n,\n  }: {\n    beforeRequest?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    afterResponse?: (\n      req: FarmRequest,\n      res: FarmResponse,\n      context: FarmPluginContext,\n    ) => void | Promise<void>;\n    i18n?: ResolvedFarmI18nConfig;\n  } = {},\n): FarmPlugin {\n  const compiledRewrites = rewrites.map((rewrite) => ({\n    rewrite,\n    pattern: compileConfigRoutePattern(rewrite.source),\n  }));\n\n  return {\n    name: FARM_CONFIG_REWRITES_PLUGIN_NAME,\n    enforce: \"pre\",\n\n    async beforeRequest(req, res, context) {\n      if (overrideBeforeRequest) {\n        await overrideBeforeRequest(req, res, context);\n      }\n      const url = resolveFarmRequestURL(req);\n      const routePath = resolveConfigRoutePathname(url.pathname, i18n);\n      const pathname = routePath.pathname;\n\n      for (const { rewrite, pattern } of compiledRewrites) {\n        const match = pathname.match(pattern.regex);\n        if (match) {\n          const newPath = localizeConfigRouteDestination(\n            interpolateConfigRouteDestination(rewrite.destination, match, pattern.tokens),\n            routePath.locale,\n            i18n,\n          );\n          const destinationUrl = new URL(newPath, url);\n          if (!destinationUrl.search && url.search) {\n            destinationUrl.search = url.search;\n          }\n          req.url =\n            destinationUrl.origin === url.origin\n              ? destinationUrl.pathname + destinationUrl.search\n              : destinationUrl.href;\n          break;\n        }\n      }\n    },\n\n    async afterResponse(req, res, context) {\n      if (overrideAfterResponse) {\n        await overrideAfterResponse(req, res, context);\n      }\n    },\n  };\n}\n","import { logger } from \"../utils\";\n\ninterface OpenAPIDevStatusLogger {\n  success(message: string): void;\n  warn(message: string): void;\n}\n\nexport function reportOpenAPIDevGenerationResult(\n  spec: unknown,\n  output: OpenAPIDevStatusLogger = logger,\n): void {\n  if (spec) {\n    output.success(\"✅ OpenAPI documentation enabled\");\n    return;\n  }\n\n  output.warn(\"OpenAPI documentation is enabled, but its specification failed to generate.\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFO,SAAS,iBAAoE;AAClF,SAAO,cAAc;AACvB;AAuEA,SAAS,eAAe,OAAqD;AAC3E,SAAO,IAAI;AAAA,IACT,CAAC;AAAA,IACD;AAAA,MACE,IAAI,SAAS,UAAU;AACrB,YAAI,OAAO,aAAa,UAAU;AAChC,iBAAO;AAAA,QACT;AAEA,cAAMA,OAAM,YAAY,KAAK;AAC7B,eAAOA,KAAI,QAAQ;AAAA,MACrB;AAAA,MACA,UAAU;AACR,eAAO,QAAQ,QAAQ,YAAY,KAAK,CAAC;AAAA,MAC3C;AAAA,MACA,yBAAyB,SAAS,UAAU;AAC1C,cAAMA,OAAM,YAAY,KAAK;AAC7B,YAAI,EAAE,YAAYA,OAAM;AACtB,iBAAO;AAAA,QACT;AAEA,eAAO;AAAA,UACL,YAAY;AAAA,UACZ,c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ACnE;AAAA,MACF;AACA,YAAM,QAAQ,IAAIA,SAAQ;AAAA,IAC5B;AAEA,QAAI,aAAa,OAAQ,MAAK,cAAc;AAC5C,QAAI,aAAa,QAAS,MAAK,eAAe;AAE9C,WAAO;AAAA,EACT;AAAA,EAEA,cAAc,SAAqC;AACjD,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,MACH,gBAAgB,KAAK,QAAQ;AAAA,IAC/B;AAAA,EACF;AACF;AArxB2B;AAApB,IAAM,gBAAN;AAuxBA,SAAS,aAQd,QAiBA;AACA,SAAO;AACT;AA3BgB;AAAA,CA6BT,CAAUC,kBAAV;AAEE,WAAS,iBAAuC;AACrD,WAAO,gCAAS,kBAMd,QAeA;AACA,aAAO;AAAA,IACT,GAvBO;AAAA,EAwBT;AAzBO,EAAAA,cAAS;AAAA;AAAA,GAFD;","names":["env","globalState","text","name","path","resolve","name","path","relativePath","fs","module","secretError","context","fs","path","isAbsolutePath","normalizePath","pathToFileURL","resolvePath","relativeFilePath","pathSeparator","text","name","path","memoryDriver","storage","name","module","resolveDriver","base","globalState","path","name","path","import_node_path","text","name","name","resolve","serialized","context","PROGRAMMATIC_ROUTE_FILE_NAMES","createProgrammaticRouteModuleId","getProgrammaticRouteSearchClientOptions","isProgrammaticRoutesFileName","parseProgrammaticRouteModuleId","parseProgrammaticRoutePath","scanProgrammaticPagePaths","path","createElement","FarmProgrammaticPageContent","FarmProgrammaticPage","context","name","action","resolve","context","path","globalState","api","text","resolveStorageRuntimeClient","createIntegrationOrm","response","path","import_node_module","import_node_path","import_node_url","context","path","name","path","name","import_node_path","normalizeCookiePath","init_config","context","React","reactRenderToString","reactRenderToPipeableStream","normalizeBasePath","import_node_module","import_node_path","import_node_url","name","url","path","init_config","import_node_fs","import_fs","import_path","relativePath","exports","path","throwIfAborted","text","name","resolve","path","import_node_crypto","import_node_fs","import_node_path","path","relativePath","import_node_fs","import_node_path","path","import_node_fs","import_node_module","import_node_path","page","escapeXml","name","import_node_crypto","trimSlashes","normalizeEntry","path","escapeAttribute","escapeHtml","relative","DOCS_FILE_EXTENSIONS","titleFromMarkdown","page","text","body","icon","renderedSections","import_node_fs","import_node_path","import_promises","import_node_module","import_node_path","import_node_url","existsSync","path","isRecord","fs","pathToFileURL","relativePath","import_path","init_config","isRecord","isResolvedDocsConfig","getDocsTitle","getDocsDescription","getLoadedDocsPages","context","page","toDocsSitemapPage","toDocsLlmsPage","getDocsLlmsOptions","getDocsDiscoveryOptions","buildFarmingDocsDiagnostics","import_docs","init_config","path","fs","normalizePath","storage","env","path","import_node_path","init_config","name","escapeHtml","escapeAttribute","throwIfAborted","Readable","name","resolve","address","import_promises","escapeRegExp","name","loadModule","page","import_path","getProgrammaticRouteManifest","import_promises","import_path","createElement","path","import_path","import_fs","import_path","import_url","fs","path","name","layout","estimatedBoundaryCount","path","fs","import_promises","import_node_path","path","name","layout","path","createRouteModuleFromProgrammaticPage","module","createLayoutModuleFromProgrammaticLayout","page","fs","path","name","context","import_node_async_hooks","storage","import_node_fs","import_node_path","path","fs","isRecord","initialTagCount","icon","name","context","context","context","output","import_node_async_hooks","import_promises","name","redirect","readCookie","locale","name","IntlMessageFormat","getRequestStore","getRequestStore","import_node_crypto","import_node_fs","import_promises","import_node_path","import_node_module","import_node_url","context","bytes","path","path","relative","name","createElement","isResponse","isRecord","resolveCacheControl","getFarmGlobalState","init_config","init_config","readCookie","name","import_node_url","fs","path","import_node_url","relative","relativePath","page","name","serializeInlineValue","escapeHtmlAttribute","toMiddlewareMap","capabilities","renderToPipeableStream","resolve","layout","redirect","relativePath","findStaticShellBoundary","html","import_path","init_config","init_config","path","import_node_fs","import_node_path","path","fs","import_node_fs","import_node_path","path","fs","path","betterCallEndpoint","context","result","path","path","fs","path","init_config","init_config","normalizePathname","response","searchParamsToObject","isWebResponse","text","relativePath","getProgrammaticRouteManifest","init_config","fs","path","decodeCookieValue","name","name","context","module","picocolors","module","result","match","name","import_fs","import_path","path","fs","name","fs","path","DEFAULT_OUT_FILE","relativePath","import_node_fs","import_node_path","path","fs","path","CONFIG_FILENAMES","findConfigPath","toTypeImportPath","registries","relativePath","import_node_fs","import_node_path","name","name","fs","path","import_node_url","import_node_async_hooks","storage","resolve","context","context","import_node_async_hooks","fs","path","import_promises","import_node_path","import_image_size","layout","import_node_path","init_config","import_node_path","path","publicEnv","name","isHtmlResponse","env","declaration","relative","context","createNodeImageFetcher","createNodeImageUrlValidator","createSharpImageTransformer","isStaticMetadataImageFile","createFarmWorkflowRequestHandler","discoverFarmWorkflows","OpenAPIManager","layout","handler","createFarmDevtoolsSnapshot","renderFarmDevtoolsHtml","pathname","startTime","duration","method","urlPath","routeManager","parseRouteModuleProps","options","page","React","renderToString","server","parseRouteModuleSchema","context","createContext","promises","definePlugin"]}