{"version":3,"sources":["../src/build/index.ts","../src/nitro/client-css-href.ts","../src/nitro/universal-build.ts","../src/docs/compiler.ts","../src/route-runtime-manifest.ts","../src/nitro/vercel-route-runtime.ts","../src/nitro/vercel-assets.ts","../src/nitro/node-server-entry.ts","../src/build/vite-plugin-compat.ts"],"sourcesContent":["import type { ResolvedFarmConfig } from \"../config\";\nimport {\n  getDefaultDeployOutputDir,\n  getDeployTargetForPreset,\n  resolveDeployOutputPath,\n} from \"../config\";\nimport type { ViteDevServer } from \"vite\";\nimport path from \"path\";\nimport { existsSync } from \"node:fs\";\nimport { logger } from \"../utils\";\nimport { createFarmApp } from \"../app\";\nimport { APIRouteManager } from \"../api/route-manager\";\nimport { resolveFarmAPIServerBasePath } from \"../api/server-path\";\nimport { getFarmAppDirectories } from \"../layers\";\nimport { buildUniversal } from \"../nitro/universal-build\";\nimport { getFarmDocsRouteTypeEntries } from \"../docs\";\nimport { generateFarmTypeArtifacts } from \"../type-artifacts\";\nimport { PluginManager } from \"../plugin\";\nimport { farmEnvironmentFunctionsPlugin } from \"../environment-vite\";\nimport { farmFontImportsPlugin } from \"../font-vite\";\nimport { createFarmSourceAlias, mergeFarmViteConfig } from \"../server/vite-config\";\nimport { getFarmRendererComponentExtensions, loadFarmRendererVitePlugins } from \"../renderer\";\nimport {\n  canUseRolldownForRouteDiscovery,\n  loadFarmProductionVite,\n  type FarmProductionViteRuntime,\n} from \"./production-vite\";\nimport { withProductionNodeEnv } from \"./production-node-env\";\n\ninterface BuildOptions {\n  preset?: string;\n  root?: string;\n  universal?: boolean; // Use universal build pattern (TanStack Start style)\n  /** @internal Production Vite preload started by the CLI. */\n  productionVite?: FarmProductionViteRuntime | Promise<FarmProductionViteRuntime>;\n}\n\ninterface BuildTargetBaseline {\n  preset: string;\n  distDir: string;\n  outputDir: string;\n  outputWasDerived: boolean;\n}\n\n/**\n * Build Farm.js application for production\n */\nexport async function build(config: ResolvedFarmConfig, options: BuildOptions = {}) {\n  return withProductionNodeEnv(() => buildWithProductionNodeEnv(config, options));\n}\n\n/** Every build path derived from config, recomputed once plugins have transformed it. */\nfunction createBuildTargetBaseline(config: ResolvedFarmConfig): BuildTargetBaseline {\n  const preset = config.preset || \"node-server\";\n  const distDir = config.distDir || \".farm\";\n  const outputDir = config.deploy.outputDir;\n  return {\n    preset,\n    distDir,\n    outputDir,\n    outputWasDerived:\n      outputDir === getDefaultDeployOutputDir(config.deploy.target, preset, distDir),\n  };\n}\n\nfunction resolveBuildTargets(\n  config: ResolvedFarmConfig,\n  options: BuildOptions,\n  baseline: BuildTargetBaseline,\n) {\n  const root = options.root || config.root || process.cwd();\n  const preset = options.preset || config.preset || \"node-server\";\n  const distDir = config.distDir || \".farm\";\n  const outputWasReplaced = config.deploy.outputDir !== baseline.outputDir;\n  const shouldRefreshDerivedOutput =\n    baseline.outputWasDerived &&\n    !outputWasReplaced &&\n    (preset !== baseline.preset || distDir !== baseline.distDir);\n  const deployTarget =\n    preset === config.deploy.preset ? config.deploy.target : getDeployTargetForPreset(preset);\n  const outputDir = shouldRefreshDerivedOutput\n    ? getDefaultDeployOutputDir(deployTarget, preset, distDir)\n    : config.deploy.outputDir;\n\n  return {\n    root,\n    preset,\n    srcDir: config.srcDir || \"src\",\n    distDir,\n    deployTarget,\n    outputDir,\n    deployOutputDir: resolveDeployOutputPath(root, outputDir),\n  };\n}\n\nasync function buildWithProductionNodeEnv(inputConfig: ResolvedFarmConfig, options: BuildOptions) {\n  let config = inputConfig;\n  const targetBaseline = createBuildTargetBaseline(config);\n  let targets: ReturnType<typeof resolveBuildTargets> | undefined;\n  const productionViteResultPromise =\n    options.universal === false\n      ? undefined\n      : Promise.allSettled([Promise.resolve(options.productionVite ?? loadFarmProductionVite())]);\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n  let projectModuleServer: ViteDevServer | undefined;\n\n  try {\n    await pluginManager.runHookParallel(\"init\");\n\n    // Settle plugin config before deriving the paths and deployment plan used\n    // by the production pipeline. Otherwise the build can report the returned\n    // config while still writing to the original locations.\n    config = await pluginManager.runHookSerial(\"config\", config);\n    if (options.universal === false && config.plugins.some((plugin) => plugin.routes)) {\n      throw new Error(\n        \"Plugin API routes require the default universal production build. Remove universal: false.\",\n      );\n    }\n    targets = resolveBuildTargets(config, options, targetBaseline);\n    config = {\n      ...config,\n      preset: targets.preset,\n      deploy: {\n        ...config.deploy,\n        target: targets.deployTarget,\n        preset: targets.preset,\n        outputDir: targets.outputDir,\n      },\n    };\n    pluginManager.updateContext({ config });\n    const { root, preset, srcDir, distDir, deployOutputDir } = targets;\n\n    logger.info(`🚜 Building Farm.js application with preset: ${preset}...`);\n\n    await pluginManager.setupPlugins();\n    await pluginManager.runHookParallel(\"beforeBundle\", {\n      root,\n      preset,\n      universal: options.universal !== false,\n      distDir,\n      outputDir: deployOutputDir,\n    });\n\n    // Step 1: Initialize Farm app to get route managers\n    logger.info(\"🔍 Discovering routes and API endpoints...\");\n    const productionViteResult = productionViteResultPromise\n      ? (await productionViteResultPromise)[0]\n      : undefined;\n    if (productionViteResult?.status === \"rejected\") throw productionViteResult.reason;\n    const productionVite = productionViteResult?.value;\n    const useProductionViteForDiscovery =\n      productionVite && canUseRolldownForRouteDiscovery(config.vite);\n    if (productionVite?.builder === \"rolldown\" && !useProductionViteForDiscovery) {\n      logger.info(\"🔌 Using Vite Rollup for route discovery with custom Vite configuration\");\n    }\n    const createViteServer = useProductionViteForDiscovery\n      ? productionVite.createServer\n      : (await import(\"vite\")).createServer;\n    projectModuleServer = await createProjectModuleServer(createViteServer, config, root);\n    const farmApp = createFarmApp(config, projectModuleServer);\n    await farmApp.initialize();\n\n    const routeManager = farmApp.getRouteManager();\n    const serverRenderer = farmApp.getServerRenderer();\n\n    const typeArtifacts = generateFarmTypeArtifacts({\n      root,\n      srcDir,\n      layers: config.layers,\n      plugins: config.plugins,\n      extraRoutes: [\n        ...(config.openapi?.enabled && config.openapi.route ? [config.openapi.route] : []),\n        ...getFarmDocsRouteTypeEntries(config.docs),\n      ],\n      suppressLintOnLink: config.suppressLintOnLink,\n      componentExtensions: config.renderer.componentExtensions,\n      i18nConfig: config.i18n,\n    }).catch((error: unknown) => {\n      // Non-fatal; type generation is for DX only. But say so: a silently\n      // skipped run leaves src/farm.d.ts describing routes that no longer\n      // exist, which reads as the framework having gone stale.\n      const message = error instanceof Error ? error.message : String(error);\n      logger.warn(`Route type generation failed (farm.d.ts may be stale): ${message}`);\n    });\n\n    // Type artifacts and API discovery scan independent inputs, so keep them\n    // off the critical path by running both after app initialization.\n    const apiRouteManager = new APIRouteManager(\n      getFarmAppDirectories(config),\n      projectModuleServer,\n      {\n        throwOnLoadError: true,\n        plugins: config.plugins,\n        i18n: farmApp.getI18nRuntime(),\n        bodySizeLimit: config.server.bodySizeLimit,\n        basePath: resolveFarmAPIServerBasePath(config.api),\n      },\n    );\n    const [, apiDiscovery] = await Promise.allSettled([\n      typeArtifacts,\n      apiRouteManager.discoverRoutes(),\n    ]);\n    if (apiDiscovery.status === \"rejected\") throw apiDiscovery.reason;\n\n    // Use universal build pattern if enabled\n    if (options.universal !== false) {\n      // Default to universal build (new pattern)\n      await buildUniversal(config, routeManager, apiRouteManager, serverRenderer, {\n        preset,\n        root,\n        pluginManager,\n        productionVite,\n      });\n    } else {\n      const { build: legacyViteBuild } = await import(\"vite\");\n      // Legacy build pattern (for backward compatibility)\n      // Step 1: Build client bundle with Vite\n      logger.info(\"📦 Building client bundle...\");\n      await buildClient(legacyViteBuild, config, root, srcDir, path.join(root, distDir, \"client\"));\n\n      // Step 2: Build SSR bundle with Vite\n      logger.info(\"📦 Building SSR bundle...\");\n      await buildSSR(legacyViteBuild, config, root, srcDir, path.join(root, distDir, \"server\"));\n\n      // Step 3: Build with Nitro\n      logger.info(`🚀 Building server with Nitro (preset: ${preset})...`);\n      await buildNitro(\n        config,\n        routeManager,\n        apiRouteManager,\n        serverRenderer,\n        preset,\n        root,\n        distDir,\n        pluginManager,\n      );\n    }\n\n    await pluginManager.runHookParallel(\"buildEnd\");\n    await pluginManager.runHookParallel(\"afterBundle\", {\n      root,\n      preset,\n      universal: options.universal !== false,\n      distDir,\n      outputDir: deployOutputDir,\n      success: true,\n    });\n\n    // The one completion summary for the whole pipeline: inner stages and the\n    // CLI stay quiet so success is reported exactly once, and the line that\n    // names the output directory also names the preset that chose it.\n    logger.success(`✅ Build completed successfully! (preset: ${preset})`);\n    logger.info(`📁 Output directory: ${deployOutputDir}`);\n  } catch (error) {\n    const { root, preset, distDir, deployOutputDir } =\n      targets ?? resolveBuildTargets(config, options, targetBaseline);\n    await pluginManager.runHookParallel(\"onError\", {\n      phase: \"build\",\n      error,\n      meta: {\n        root,\n        preset,\n      },\n    });\n    await pluginManager.runHookParallel(\"afterBundle\", {\n      root,\n      preset,\n      universal: options.universal !== false,\n      distDir,\n      outputDir: deployOutputDir,\n      success: false,\n    });\n    logger.error(`❌ Build failed: ${error}`);\n    throw error;\n  } finally {\n    await projectModuleServer?.close();\n  }\n}\n\nasync function createProjectModuleServer(\n  createViteServer: FarmProductionViteRuntime[\"createServer\"],\n  config: ResolvedFarmConfig,\n  root: string,\n): Promise<ViteDevServer> {\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, root, {\n    ssr: true,\n  });\n  const viteConfig = mergeFarmViteConfig(\n    {\n      root,\n      appType: \"custom\",\n      mode: \"production\",\n      css: {\n        postcss: {\n          plugins: [],\n        },\n      },\n      plugins: [\n        ...(rendererVitePlugins as any[]),\n        farmFontImportsPlugin({\n          root,\n          basePath: config.basePath,\n          publicDir: config.publicDir,\n        }),\n        farmEnvironmentFunctionsPlugin(),\n      ],\n      server: {\n        middlewareMode: true,\n        hmr: false,\n      },\n      resolve: {\n        alias: createFarmSourceAlias(root, config.srcDir),\n        dedupe: [...(config.renderer.dedupe || [])],\n      },\n      optimizeDeps: {\n        noDiscovery: true,\n      },\n      logLevel: \"silent\",\n    },\n    config.vite,\n  );\n\n  return createViteServer({\n    ...viteConfig,\n    root,\n    configFile: false,\n    appType: \"custom\",\n    mode: \"production\",\n    esbuild: {\n      ...(typeof viteConfig.esbuild === \"object\" ? viteConfig.esbuild : {}),\n      jsxDev: false,\n    },\n    server: {\n      ...viteConfig.server,\n      middlewareMode: true,\n      hmr: false,\n      // This server only loads modules for a single build. HMR alone does not\n      // disable filesystem watching, which can race with generated output.\n      watch: null,\n    },\n    optimizeDeps: {\n      ...viteConfig.optimizeDeps,\n      noDiscovery: true,\n    },\n  });\n}\n\n/**\n * Build client bundle\n */\nasync function buildClient(\n  viteBuild: (typeof import(\"vite\"))[\"build\"],\n  config: ResolvedFarmConfig,\n  root: string,\n  srcDir: string,\n  outputDir: string,\n) {\n  const { farmI18nClientBridgePlugin, farmPlugin, farmServerOnlyEntriesPlugin } =\n    await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n\n  await viteBuild({\n    root,\n    build: {\n      outDir: outputDir,\n      emptyOutDir: true,\n      rollupOptions: {\n        input: resolveLegacyPageEntry(config, root, srcDir),\n      },\n    },\n    plugins: [\n      farmI18nClientBridgePlugin(),\n      farmServerOnlyEntriesPlugin(),\n      farmPlugin(config, pluginManager),\n      farmEnvironmentFunctionsPlugin(),\n    ],\n    mode: \"production\",\n  });\n}\n\n/**\n * Build SSR bundle\n */\nasync function buildSSR(\n  viteBuild: (typeof import(\"vite\"))[\"build\"],\n  config: ResolvedFarmConfig,\n  root: string,\n  srcDir: string,\n  outputDir: string,\n) {\n  const { farmI18nClientBridgePlugin, farmPlugin } = await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n\n  const ssrEntry = resolveLegacyPageEntry(config, root, srcDir);\n\n  await viteBuild({\n    root,\n    build: {\n      ssr: true,\n      outDir: outputDir,\n      emptyOutDir: true,\n      rollupOptions: {\n        input: ssrEntry,\n      },\n    },\n    define: {\n      __FARM_API_BASE_URL__: JSON.stringify(config.api.baseURL),\n      __FARM_ENV__: JSON.stringify(config.env || { server: {}, public: {} }),\n      __FARM_PUBLIC_ENV__: JSON.stringify(config.env?.public || {}),\n    },\n    plugins: [\n      farmI18nClientBridgePlugin(),\n      farmPlugin(config, pluginManager),\n      farmEnvironmentFunctionsPlugin(),\n    ],\n    mode: \"production\",\n  });\n}\n\nfunction resolveLegacyPageEntry(config: ResolvedFarmConfig, root: string, srcDir: string): string {\n  const appDir = path.join(root, srcDir, \"app\");\n  for (const extension of getFarmRendererComponentExtensions(config.renderer)) {\n    const candidate = path.join(appDir, `page${extension}`);\n    if (existsSync(candidate)) return candidate;\n  }\n  return path.join(appDir, \"page.tsx\");\n}\n\n/**\n * Build with Nitro\n */\nasync function buildNitro(\n  config: ResolvedFarmConfig,\n  routeManager: any,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: any,\n  preset: string,\n  root: string,\n  distDir: string,\n  pluginManager?: PluginManager,\n) {\n  const [{ createNitroConfig }, { createNitro, build: nitroBuild }] = await Promise.all([\n    import(\"../nitro\"),\n    import(\"nitro/builder\"),\n  ]);\n  let nitroConfig = await createNitroConfig(\n    config,\n    routeManager,\n    apiRouteManager,\n    serverRenderer,\n    preset,\n  );\n\n  if (pluginManager) {\n    nitroConfig = await pluginManager.runHookSerial(\"beforeNitroBuild\", nitroConfig);\n  }\n\n  // Directory structure:\n  // .farm/\n  //   ├── client/          - Client-side build output (Vite)\n  //   ├── server/          - SSR build output (Vite)\n  //   ├── .nitro/          - Nitro's build directory (temporary, where it does its work)\n  //   │   └── server/      - Handlers and source files for Nitro\n  //   └── .output/         - Final deployable output (this is what gets deployed)\n  //       ├── server/      - Serverless function bundles\n  //       ├── public/      - Static assets\n  //       └── config.json  - Vercel routing config\n  //\n  // IMPORTANT: Nitro is configured to output to .farm/.output (NOT .nitro/.output)\n  // This is ensured by explicitly setting output.dir in the Nitro config\n  //\n  // Build flow:\n  // 1. Vite builds client → .farm/client\n  // 2. Vite builds SSR → .farm/server\n  // 3. Copy client assets → .farm/.output/public\n  // 4. Copy SSR bundles → .farm/.nitro/server/farm\n  // 5. Nitro builds from .farm/.nitro → outputs to .farm/.output (via output.dir config)\n  // 6. Deploy from .farm/.output\n\n  // Ensure output directory exists before building\n  const outputDir = resolveDeployOutputPath(root, config.deploy.outputDir);\n  const serverOutputDir = path.join(outputDir, \"server\");\n  const publicOutputDir = path.join(outputDir, \"public\");\n  const { mkdir, cp } = await import(\"fs/promises\");\n  await mkdir(serverOutputDir, { recursive: true });\n  await mkdir(publicOutputDir, { recursive: true });\n\n  // Copy client assets to public directory for Nitro to serve\n  // This ensures Vercel can serve static files from the public directory\n  const clientDir = path.join(root, distDir, \"client\");\n  try {\n    // Ensure public directory exists\n    await mkdir(publicOutputDir, { recursive: true });\n\n    // Copy all client assets including manifest\n    await cp(clientDir, publicOutputDir, { recursive: true });\n    logger.info(\"📦 Copied client assets to public directory\");\n\n    // Verify important files are present\n    const manifestPath = path.join(publicOutputDir, \"farm-client-manifest.json\");\n    const assetsDir = path.join(publicOutputDir, \"assets\");\n    const manifestExists = await import(\"fs/promises\").then((fs) =>\n      fs\n        .access(manifestPath)\n        .then(() => true)\n        .catch(() => false),\n    );\n    const assetsExist = await import(\"fs/promises\").then((fs) =>\n      fs\n        .access(assetsDir)\n        .then(() => true)\n        .catch(() => false),\n    );\n\n    if (manifestExists && assetsExist) {\n      logger.info(\"✅ Verified client assets are present\");\n    } else {\n      logger.warn(\"⚠️  Some client assets may be missing\");\n    }\n  } catch (error) {\n    logger.error(`❌ Failed to copy client assets: ${error}`);\n    throw error;\n  }\n\n  // Copy SSR bundles to Nitro server directory so they're included in the build\n  // These go into .farm/.nitro/server/farm (build directory)\n  // Nitro will then bundle them and output to .farm/.output/server\n  const serverDir = path.join(root, distDir, \"server\");\n  const nitroServerDir = path.join(root, distDir, \".nitro\", \"server\", \"farm\");\n  try {\n    await mkdir(nitroServerDir, { recursive: true });\n    await cp(serverDir, nitroServerDir, { recursive: true });\n    logger.info(\"📦 Copied SSR bundles to Nitro server directory\");\n  } catch (error) {\n    logger.warn(`Could not copy SSR bundles: ${error}`);\n  }\n\n  // Create Nitro instance - this handles preset loading and config preparation\n  // The createNitro function loads the preset and normalizes the config\n  const nitro = await createNitro(nitroConfig);\n\n  // Populate the runtime registry before building\n  // This ensures route managers are available at runtime\n  // Note: The registry will be populated again in the build:before hook\n  // but we also populate it here to ensure it's available\n  // Registry file is in .farm/.nitro/server (build directory)\n  // But will be bundled and available in .farm/.output/server (output directory)\n  const registryPath = path.join(root, distDir, \".nitro\", \"server\", \"farm-registry.ts\");\n  try {\n    const { farmRegistry } = await import(/* @vite-ignore */ registryPath);\n    farmRegistry.apiRouteManager = apiRouteManager;\n    farmRegistry.routeManager = routeManager;\n    farmRegistry.serverRenderer = serverRenderer;\n    farmRegistry.env = config.env || { server: {}, public: {} };\n\n    // Store route paths for SSR module loading\n    const routePaths: Record<string, string> = {};\n    for (const [pattern, entry] of routeManager.getRoutes()) {\n      const bundledPath = entry.modulePath\n        .replace(/.*\\/src\\/app\\//, \"\")\n        .replace(/\\.(tsx?|jsx?)$/, \".js\");\n      routePaths[pattern] = bundledPath;\n    }\n    farmRegistry.routePaths = routePaths;\n\n    // Load client manifest\n    try {\n      const clientManifestPath = path.join(root, distDir, \"client\", \"farm-client-manifest.json\");\n      const { readFile } = await import(\"fs/promises\");\n      const manifestContent = await readFile(clientManifestPath, \"utf-8\");\n      farmRegistry.clientManifest = JSON.parse(manifestContent);\n    } catch {\n      farmRegistry.clientManifest = {};\n    }\n  } catch (error) {\n    logger.warn(`Could not populate registry: ${error}`);\n  }\n\n  // Build Nitro with the prepared instance\n  await nitroBuild(nitro);\n\n  if (pluginManager) {\n    await pluginManager.runHookParallel(\"afterNitroBuild\", {\n      root,\n      preset,\n      distDir,\n      outputDir: resolveDeployOutputPath(root, config.deploy.outputDir),\n    });\n  }\n}\n","import path from \"path\";\n\n/**\n * Stand-ins for the client asset URLs inside generated server code.\n * The client and SSR graphs build in parallel, so the final asset bytes\n * (fonts are merged into the stylesheet after Vite emits it) do not exist\n * yet when server code is generated. buildNitroUniversal substitutes the\n * real, content-hashed URLs once the client build has settled.\n */\nexport const FARM_CLIENT_CSS_HREF_PLACEHOLDER = \"/__farm_client_css_href__\";\nexport const FARM_CLIENT_JS_SRC_PLACEHOLDER = \"/__farm_client_js_src__\";\n\nasync function hashAndCopy(\n  sourcePath: string,\n  destinationDir: string,\n  hashedName: (hash: string) => string,\n): Promise<string | null> {\n  const fs = await import(\"fs/promises\");\n  try {\n    const bytes = await fs.readFile(sourcePath);\n    if (bytes.length === 0) return null;\n    const { createHash } = await import(\"node:crypto\");\n    const hash = createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 8);\n    const name = hashedName(hash);\n    await fs.mkdir(destinationDir, { recursive: true });\n    await fs.writeFile(path.join(destinationDir, name), bytes);\n    return name;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Content-hash the final client stylesheet and return the href generated\n * server code should reference.\n *\n * The hash is taken after font CSS has been merged in, so any change to the\n * bytes a browser would receive changes the URL. The hashed copy lives under\n * assets/, where the -h fingerprint already qualifies for immutable caching;\n * the stable farm-client.css stays in place for anything that hardcoded it.\n * A missing or empty stylesheet falls back to the stable name, matching the\n * empty file written for intentionally style-free applications.\n */\nexport async function resolveHashedClientCssHref(clientOutputDir: string): Promise<string> {\n  const name = await hashAndCopy(\n    path.join(clientOutputDir, \"farm-client.css\"),\n    path.join(clientOutputDir, \"assets\"),\n    (hash) => `farm-client-h${hash}.css`,\n  );\n  return name ? `/assets/${name}` : \"/farm-client.css\";\n}\n\n/**\n * The client entry emitted by the current build, if it carries a content\n * fingerprint. Vite names it farm-client-h<hash>.js so its code-split chunks\n * import the fingerprinted name natively; emptyOutDir keeps stale builds from\n * leaving older fingerprints behind.\n */\nexport async function findFingerprintedClientEntry(\n  clientOutputDir: string,\n): Promise<string | null> {\n  const fs = await import(\"fs/promises\");\n  try {\n    const entries = await fs.readdir(clientOutputDir);\n    return entries.find((name) => /^farm-client-h[0-9a-f]+\\.js$/.test(name)) ?? null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Resolve the src generated server code should reference for the client\n * entry, and keep the stable name working.\n *\n * The entry cannot be duplicated under a second name: its chunks import back\n * into it (it is the shared runtime), so a copy would be instantiated twice\n * and React would see two instances. Instead the bundler emits the\n * fingerprinted name directly, and the stable farm-client.js becomes a\n * re-export shim — anything that hardcoded the old path still executes the\n * one real module.\n */\nexport async function resolveHashedClientJsSrc(clientOutputDir: string): Promise<string> {\n  const entryName = await findFingerprintedClientEntry(clientOutputDir);\n  if (!entryName) return \"/farm-client.js\";\n  const fs = await import(\"fs/promises\");\n  const shim = `export * from \"./${entryName}\";\\n`;\n  await fs.writeFile(path.join(clientOutputDir, \"farm-client.js\"), shim);\n  return `/${entryName}`;\n}\n","import type { RedirectConfig, ResolvedFarmConfig, RewriteConfig } from \"../config\";\nimport { hasCustomFarmRouteContext, resolveDeployOutputPath } from \"../config\";\nimport {\n  FARM_CLIENT_CSS_HREF_PLACEHOLDER,\n  FARM_CLIENT_JS_SRC_PLACEHOLDER,\n  findFingerprintedClientEntry,\n  resolveHashedClientCssHref,\n  resolveHashedClientJsSrc,\n} from \"./client-css-href\";\nimport type { RouteManager, ApplicationMetadataRouteEntry } from \"../routing/route-manager\";\nimport { compareRoutePatternSpecificity } from \"../routing/specificity\";\nimport type { APIRouteManager } from \"../api/route-manager\";\nimport { resolveFarmAPIServerBasePath } from \"../api/server-path\";\nimport type { ServerRenderer } from \"../server/renderer\";\nimport type { FarmPlugin, PluginManager } from \"../plugin\";\nimport {\n  generateFarmClientPluginEntryCode,\n  type FarmClientPluginEntryCode,\n} from \"../client-plugin-build\";\nimport {\n  generateClientCachePersistenceCode,\n  resolveFarmClientCacheAdapterEntry,\n  type ClientCachePersistenceEntryCode,\n} from \"../client-cache-persistence-build\";\nimport type { Rollup } from \"vite\";\nimport os from \"os\";\nimport path from \"path\";\nimport { constants as fsConstants, existsSync, readFileSync, realpathSync } from \"fs\";\nimport { findRequestBoundSourceBlockers, parseRouteRenderingDirective } from \"../ssg\";\nimport { FARM_LAYOUT_ELEMENT_CLIENT_SOURCE } from \"../document-layout-client\";\nimport { fileURLToPath } from \"url\";\nimport { builtinModules, createRequire } from \"module\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport { logger, toPosixPath, toViteModuleId } from \"../utils\";\nimport {\n  describeSuppressedAsyncHydration,\n  enforceFarmIsolatedHydrationRouteBudget,\n  getClientModuleHydrationPlan,\n  getClientModuleMetadata,\n  getFarmClientHydrationPlanOptions,\n  createMarkdownPageHydrationPlanner,\n  resolveFarmIsolatedClientHydrationMode,\n  type ClientModuleHydrationPlan,\n  type FarmClientHydrationPlanOptions,\n  type IsolatedClientBoundaryReference,\n} from \"../utils/client-component\";\nimport type { FarmIsolatedClientHydrationMode } from \"../types\";\nimport { isFarmMarkdownPageFile } from \"../app-markdown\";\nimport { resolveFarmMdxComponentsModulePath, resolveMdxConfig } from \"../app-markdown-config\";\nimport type { ProgrammaticRedirectRoute } from \"../routes\";\nimport type { NitroConfig } from \"nitro/types\";\nimport { applyFarmCspHashesToHtml } from \"../security\";\nimport {\n  applyFarmWorkflowVercelCrons,\n  prepareFarmWorkflowsForNitro,\n  type PreparedFarmWorkflows,\n} from \"../workflows\";\nimport {\n  applyFarmCronVercelCrons,\n  createFarmCronCloudflareConfig,\n  mergeScheduledTasks,\n  prepareFarmCronForNitro,\n} from \"../cron\";\nimport { routeRulesToNitroRouteRules } from \"../route-rules\";\nimport { getFarmAppDirectories } from \"../layers\";\nimport { farmEnvironmentFunctionsPlugin } from \"../environment-vite\";\nimport {\n  createFarmDocsLastModifiedManifest,\n  FARM_DOCS_LAST_MODIFIED_MANIFEST,\n} from \"../docs/last-modified\";\nimport {\n  generateFarmDocsSearchClientRuntime,\n  isFarmDocsSearchEnabled,\n  resolveFarmDocsSearchClientModule,\n} from \"../docs/search-client\";\nimport { generateFarmDocsAdapterClientRuntime } from \"../docs/adapter-client\";\nimport { resolveFarmDocsFontAssets, toFarmDocsPublicFontAssets } from \"../docs/fonts\";\nimport { compileFarmDocsManifest } from \"../docs/compiler\";\nimport { compileFarmDocsAdapterEdgeManifest } from \"../docs/adapter\";\nimport type { FarmDocsCompiledManifest } from \"../docs/precompiled-runtime\";\nimport {\n  createFarmRouteRuntimeManifest,\n  validateFarmRouteRuntimeDeployment,\n  writeFarmRouteRuntimeManifest,\n} from \"../route-runtime-manifest\";\nimport type { FarmRouteRuntimeManifest, FarmRouteRuntimeManifestEntry } from \"../route-runtime\";\nimport { createFarmVercelRouteRuntimeFunctions } from \"./vercel-route-runtime\";\nimport { buildFarmVercelRoutes } from \"./vercel-assets\";\nimport { createFarmNodeServerEntry } from \"./node-server-entry\";\nimport { resolveFarmNotFoundComponentPath } from \"../not-found\";\nimport { readFarmI18nCatalogs } from \"../i18n/catalog\";\nimport type { FarmI18nCatalogs } from \"../i18n/types\";\nimport { getFarmIntegrationPluginServerRuntime, getIntegrationProviders } from \"../integrations\";\nimport {\n  generateFarmIntegrationProviderClientCode,\n  generateFarmIntegrationProviderServerModules,\n} from \"../integration-provider-build\";\nimport type { TransformOptions } from \"esbuild\";\nimport { loadFarmProductionVite, type FarmProductionViteRuntime } from \"../build/production-vite\";\nimport { adaptTailwindVitePlugin } from \"../build/vite-plugin-compat\";\nimport { mergeFarmFontCss } from \"../font-vite\";\nimport type { FarmIslandStrategy } from \"../island\";\nimport { createFarmSourceAlias } from \"../server/vite-config\";\nimport { DEFAULT_NOT_FOUND_STYLES } from \"../components/not-found-styles\";\nimport { createFarmThemeCssPlugin } from \"../theme/vite\";\nimport { resolveFarmInstrumentationFile } from \"../instrumentation\";\nimport { getFarmPresetRuntime } from \"../deployment\";\nimport { isFarmPreviewDeploymentEnvironment } from \"../deployment-environment\";\nimport { resolveFarmInstrumentationRuntime } from \"../instrumentation-runtime\";\nimport { FARM_PRERENDER_ENV } from \"../plugins/infra-analytics\";\nimport {\n  getFarmRendererCapabilities,\n  getFarmRendererStreamingCapabilitiesForRuntime,\n  isReactRenderer,\n  loadFarmRendererVitePlugins,\n  REACT_RENDERER,\n} from \"../renderer\";\nimport { appendMiddlewareRoutePath } from \"../middleware/path\";\nimport type { FarmRenderer } from \"../renderer\";\nimport { farmPluginMayAffectRuntimePath } from \"../plugin-runtime-endpoint\";\n\n// Type alias for OutputBundle\ntype OutputBundle = Rollup.OutputBundle;\ntype FarmEsbuildOptions = TransformOptions & {\n  exclude?: unknown;\n  include?: unknown;\n  loaders?: unknown;\n  sourceMap?: unknown;\n};\ntype NitroOutputPackage = {\n  dependencies?: Record<string, string>;\n  [key: string]: unknown;\n};\ntype FarmNitroBuilder = typeof import(\"nitro/builder\");\ntype UniversalPageRoute = {\n  pattern: string;\n  modulePath: string;\n  source?: string;\n  markdownSourcePath?: string;\n};\ntype UniversalBoundaryRoute = {\n  pattern: string;\n  modulePath: string;\n};\ntype UniversalRouteSlot = {\n  name: string;\n  ownerPattern: string;\n  pattern: string;\n  modulePath: string;\n  containerId: string;\n  interception: boolean;\n  fallback: boolean;\n};\ntype UniversalConfiguredHeaderRoute = {\n  source: string;\n  headers: Array<{ key: string; value: string }>;\n};\ntype UniversalMetadataImageRoute = {\n  pattern: string;\n  kind: \"opengraph\" | \"twitter\";\n  fileName: \"opengraph-image\" | \"twitter-image\";\n  sourceType: \"module\" | \"static\";\n  modulePath?: string;\n  staticInfo?: {\n    contentType: string;\n    width: number;\n    height: number;\n    alt?: string;\n    hash: string;\n    byteLength: number;\n  };\n  data?: string;\n};\n// Derived from the route manager so new metadata route kinds cannot drift out of sync.\ntype UniversalApplicationMetadataRoute = Pick<\n  ApplicationMetadataRouteEntry,\n  \"pattern\" | \"kind\" | \"outputName\" | \"modulePath\"\n>;\ntype UniversalMiddlewareRoute = {\n  path: string;\n  filePath: string;\n};\n\nfunction preloadFarmNitroBuilder(): Promise<PromiseSettledResult<FarmNitroBuilder>> {\n  return import(\"nitro/builder\").then(\n    (value) => ({ status: \"fulfilled\", value }),\n    (reason) => ({ status: \"rejected\", reason }),\n  );\n}\n\n// Get __dirname equivalent for ESM\nconst _filename = typeof import.meta.url !== \"undefined\" ? fileURLToPath(import.meta.url) : \"\";\nconst _dirname = path.dirname(_filename);\n\n/** The installed @farm.js/core package directory, found from this module's own file. */\nfunction findFarmCoreRoot(from: string): string | null {\n  let dir = path.dirname(from);\n  while (dir !== path.dirname(dir)) {\n    const manifest = path.join(dir, \"package.json\");\n    if (existsSync(manifest)) {\n      try {\n        if (JSON.parse(readFileSync(manifest, \"utf8\")).name === \"@farm.js/core\") return dir;\n      } catch {}\n    }\n    dir = path.dirname(dir);\n  }\n  return null;\n}\n\nconst farmCoreRoot = _filename ? findFarmCoreRoot(_filename) : null;\n\nfunction toModulePath(file: string): string {\n  const normalized = file.split(\"\\\\\").join(\"/\");\n  return process.platform === \"win32\" ? normalized.toLowerCase() : normalized;\n}\n\n/** Node's package lookup: the nearest node_modules/<name> at or above `from`. */\nfunction findInstalledPackageDir(name: string, from: string): string | null {\n  for (let dir = from; ; dir = path.dirname(dir)) {\n    const candidate = path.join(dir, \"node_modules\", name);\n    if (existsSync(path.join(candidate, \"package.json\"))) {\n      try {\n        return realpathSync(candidate);\n      } catch {\n        return null;\n      }\n    }\n    if (dir === path.dirname(dir)) return null;\n  }\n}\n\n/** Directories of Farm's packages and every package they depend on, as installed for the app. */\nfunction collectFarmDependencyDirs(root: string): string[] {\n  const queue: Array<{ name: string; from: string }> = [];\n  const seen = new Set<string>();\n  const visit = (dir: string) => {\n    if (seen.has(dir)) return;\n    seen.add(dir);\n    let manifest: Record<string, Record<string, string> | undefined>;\n    try {\n      manifest = JSON.parse(readFileSync(path.join(dir, \"package.json\"), \"utf8\"));\n    } catch {\n      return;\n    }\n    for (const field of [\"dependencies\", \"optionalDependencies\", \"peerDependencies\"]) {\n      for (const name of Object.keys(manifest[field] ?? {})) queue.push({ name, from: dir });\n    }\n  };\n\n  if (farmCoreRoot) visit(realpathSync(farmCoreRoot));\n  queue.push({ name: \"@farm.js/core\", from: root });\n  try {\n    const manifest = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\"));\n    for (const field of [\"dependencies\", \"devDependencies\"]) {\n      for (const name of Object.keys(manifest[field] ?? {})) {\n        if (name.startsWith(\"@farm.js/\")) queue.push({ name, from: root });\n      }\n    }\n  } catch {}\n\n  for (let next = queue.pop(); next; next = queue.pop()) {\n    const dir = findInstalledPackageDir(next.name, next.from);\n    if (dir) visit(dir);\n  }\n  return [...seen];\n}\n\n/**\n * Tree-shaking for the server bundle. Farm's packages and their dependencies are treated\n * as free of import side effects, so unused parts of Farm's graph (the docs Markdown\n * pipeline, build-time helpers) stay out of the bundle. The app's own code and\n * dependencies get the bundler default instead: SDKs register state on import (the OpenAI\n * Agents default model provider, LangGraph's AsyncLocalStorage), and dropping that code\n * broke them and crashed Rolldown on LangGraph.\n *\n * `undefined` defers to the package: Rolldown reads its `sideEffects` field, and Rollup\n * keeps the module unless the resolved package marked it side-effect free.\n */\nfunction createFarmServerModuleSideEffects(root: string) {\n  const installed = new Set<string>();\n  const linked: string[] = [];\n  for (const dir of collectFarmDependencyDirs(root)) {\n    const modulePath = toModulePath(dir);\n    if (modulePath.includes(\"/node_modules/\")) installed.add(modulePath);\n    else linked.push(`${modulePath}/`);\n  }\n\n  return (id: string): false | undefined => {\n    const file = toModulePath(id.split(\"?\")[0]);\n    const index = file.lastIndexOf(\"/node_modules/\");\n    if (index !== -1) {\n      const start = index + \"/node_modules/\".length;\n      const segments = file.slice(start).split(\"/\");\n      const packageDir =\n        file.slice(0, start) + segments.slice(0, segments[0].startsWith(\"@\") ? 2 : 1).join(\"/\");\n      return installed.has(packageDir) ? false : undefined;\n    }\n    return linked.some((prefix) => file.startsWith(prefix)) ? false : undefined;\n  };\n}\n\nconst NODE_BUILTIN_MODULES = new Set([\n  ...builtinModules,\n  ...builtinModules.map((moduleName) => `node:${moduleName}`),\n]);\nconst NITRO_EXTERNAL_MODULES = new Set([\n  \"react\",\n  \"react-dom\",\n  \"react-dom/server\",\n  \"@prisma/client\",\n  \"@prisma/client/default\",\n  \"@prisma/client/default.js\",\n  \".prisma/client\",\n  \".prisma/client/default\",\n  \"better-sqlite3\",\n  \"fsevents\",\n  \"esbuild\",\n  \"lightningcss\",\n  \"rollup\",\n  \"vite\",\n  \"vite-rolldown\",\n  \"nitro\",\n  \"nitropack\",\n  \"sharp\",\n]);\n// Node presets trace these into the output's node_modules. A Cloudflare\n// module Worker has no node_modules, so it must bundle them instead.\nconst NITRO_REACT_RUNTIME_MODULES = new Set([\"react\", \"react-dom\", \"react-dom/server\"]);\nconst FARM_SSR_PACKAGE_IMPORT = \"#farm-ssr-entry\";\nconst FARM_SSR_OUTPUT_DIR = \"farm-ssr\";\nconst FARM_CLIENT_BUILD_TARGET = [\"es2020\", \"edge88\", \"firefox78\", \"chrome87\", \"safari14\"];\n\nfunction resolveNitroRuntimeDependency(root: string, specifier: string): string {\n  return createRequire(resolveNitroPackageEntry(root)).resolve(specifier).split(path.sep).join(\"/\");\n}\n\nfunction resolveNitroInternalRuntimeAliases(root: string): Record<string, string> {\n  const runtimeDir = path.dirname(resolveNitroPackageEntry(root));\n  return Object.fromEntries(\n    [\"app\", \"error/hooks\", \"runtime-config\", \"shutdown\", \"task\"].map((moduleName) => [\n      `#nitro/runtime/${moduleName}`,\n      path.join(runtimeDir, \"internal\", `${moduleName}.mjs`).split(path.sep).join(\"/\"),\n    ]),\n  );\n}\n\n/**\n * Rollup fallback resolver for the temporary prerender server. Bare ids that\n * the regular pipeline cannot resolve (Nitro virtual modules import Nitro's\n * runtime dependencies without a real importer) are retried from Nitro's own\n * package location, where pnpm's strict layout can supply them.\n */\nexport function createPrerenderRuntimeResolverPlugin(\n  root: string,\n  resolveNitroEntry: (projectRoot: string) => string = resolveNitroPackageEntry,\n): Rollup.Plugin {\n  let nitroEntry: string | null | undefined;\n\n  return {\n    name: \"farm-prerender-runtime-resolver\",\n    async resolveId(id, _importer, options) {\n      if (options.custom?.farmPrerenderRuntimeResolve) return null;\n      if (\n        id.startsWith(\"\\0\") ||\n        id.startsWith(\".\") ||\n        id.startsWith(\"#\") ||\n        id.startsWith(\"virtual:\") ||\n        path.isAbsolute(id) ||\n        NODE_BUILTIN_MODULES.has(id)\n      ) {\n        return null;\n      }\n\n      if (nitroEntry === undefined) {\n        try {\n          nitroEntry = resolveNitroEntry(root);\n        } catch {\n          nitroEntry = null;\n        }\n      }\n      if (!nitroEntry) return null;\n\n      return this.resolve(id, nitroEntry, {\n        ...options,\n        skipSelf: true,\n        custom: { ...options.custom, farmPrerenderRuntimeResolve: true },\n      });\n    },\n  };\n}\n\nfunction resolveNitroPackageEntry(root: string): string {\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  let runtimeRequire = projectRequire;\n  try {\n    runtimeRequire = createRequire(projectRequire.resolve(\"@farm.js/core\"));\n  } catch {\n    // Source-only framework builds can resolve Nitro directly from the project.\n  }\n  return runtimeRequire.resolve(\"nitro\");\n}\n\nfunction cloneConfigValue<T>(value: T, seen = new WeakMap<object, unknown>()): T {\n  if (value === null || typeof value !== \"object\") return value;\n  if (seen.has(value)) return seen.get(value) as T;\n  if (value instanceof RegExp) return new RegExp(value.source, value.flags) as T;\n  if (value instanceof Date) return new Date(value) as T;\n\n  if (Array.isArray(value)) {\n    const clone: unknown[] = [];\n    seen.set(value, clone);\n    for (const entry of value) clone.push(cloneConfigValue(entry, seen));\n    return clone as T;\n  }\n\n  const clone: Record<PropertyKey, unknown> = {};\n  seen.set(value, clone);\n  for (const key of Reflect.ownKeys(value)) {\n    clone[key] = cloneConfigValue((value as Record<PropertyKey, unknown>)[key], seen);\n  }\n  return clone as T;\n}\n\nfunction snapshotSSRRebundleOptions(config: NitroConfig) {\n  return cloneConfigValue({\n    alias: config.alias,\n    commonJS: config.commonJS,\n    entry: config.entry,\n    exportConditions: config.exportConditions,\n    inlineDynamicImports: config.inlineDynamicImports,\n    noExternals: config.noExternals,\n    node: config.node,\n    oxc: config.oxc,\n    plugins: config.plugins,\n    replace: config.replace,\n    rolldownConfig: config.rolldownConfig,\n    serverEntry: config.serverEntry,\n    sourcemap: config.sourcemap,\n    traceDeps: config.traceDeps,\n    traceOpts: config.traceOpts,\n    typescript: config.typescript,\n    unenv: config.unenv,\n    virtual: config.virtual,\n    wasm: config.wasm,\n  });\n}\n\nasync function canUseRolldownBuilder(): Promise<boolean> {\n  const [major = 0, minor = 0] = process.versions.node.split(\".\").map(Number);\n  const isSupportedNode = major > 22 || (major === 22 && minor >= 12);\n  if (!isSupportedNode) {\n    return false;\n  }\n\n  try {\n    await import(\"rolldown\");\n    return true;\n  } catch {\n    // Rolldown is optional so --no-optional installs retain Rollup.\n    return false;\n  }\n}\n\n/**\n * Alias that points React's server entry at a Web-stream build.\n *\n * React splits `react-dom/server` by export condition: the Node build exports\n * renderToPipeableStream, and only the Web builds export renderToReadableStream.\n * React 19 ships `./server.edge` for Workers and edge runtimes. Its\n * `./server.browser` build schedules work through a global MessageChannel,\n * which a Cloudflare Worker only exposes on recent compatibility dates, so it\n * can fail at module load. React 18 has no edge build, and its browser build\n * does not need MessageChannel.\n */\nexport function createFarmReactWebServerAlias(hasEdgeBuild: boolean) {\n  return {\n    find: /^react-dom\\/server$/,\n    replacement: hasEdgeBuild ? \"react-dom/server.edge\" : \"react-dom/server.browser\",\n  };\n}\n\n/** Whether the app's installed React DOM exports the dedicated edge server build. */\nexport function hasReactDomEdgeServerBuild(root: string): boolean {\n  try {\n    createRequire(path.join(root, \"package.json\")).resolve(\"react-dom/server.edge\");\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Whether the SSR graph must resolve React's server entry to the Web-stream\n * build instead of the Node one.\n *\n * Vite resolves the SSR graph with Node conditions, and React applications\n * bundle react-dom rather than externalizing it, so without this an edge\n * preset inlines the Node build. React 18's Node build has no\n * `renderToReadableStream`, so the edge renderer cannot stream at all; React\n * 19's Node build streams only through Node built-in polyfills.\n */\nexport function shouldAliasReactServerToWebBuild(\n  renderer: Pick<FarmRenderer, \"name\"> | undefined,\n  preset: string,\n): boolean {\n  return isReactRenderer(renderer) && getFarmPresetRuntime(preset) === \"edge\";\n}\n\nfunction isCloudflareImagePreset(preset: string): boolean {\n  return preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\";\n}\n\n/**\n * Whether the server output loads @vercel/og from node_modules. Its Node build\n * reads its wasm and default font from beside its own file, so Node presets\n * cannot inline it into a bundle, whether generated metadata images or app\n * server code imports it.\n */\nfunction shouldUseExternalMetadataImageRuntime(preset: string, usesImageRuntime: boolean): boolean {\n  return usesImageRuntime && preset !== \"vercel-edge\" && !isCloudflareImagePreset(preset);\n}\n\nfunction resolveImageRuntime(\n  config: ResolvedFarmConfig,\n  preset: string,\n): \"none\" | \"node\" | \"cloudflare\" {\n  if (config.images.provider === \"none\") return \"none\";\n  const cloudflarePreset = isCloudflareImagePreset(preset);\n  if (config.images.provider === \"node\" && cloudflarePreset) {\n    throw new Error('images.provider \"node\" cannot run in a Cloudflare deployment');\n  }\n  if (config.images.provider === \"cloudflare\" && !cloudflarePreset) {\n    throw new Error('images.provider \"cloudflare\" requires a Cloudflare deployment preset');\n  }\n  return config.images.provider === \"cloudflare\" ||\n    (config.images.provider === \"auto\" && cloudflarePreset)\n    ? \"cloudflare\"\n    : \"node\";\n}\n\nfunction isNitroRollupExternal(id: string): boolean {\n  const normalizedId = id.replace(/\\\\/g, \"/\");\n\n  return (\n    NODE_BUILTIN_MODULES.has(id) ||\n    NITRO_EXTERNAL_MODULES.has(id) ||\n    normalizedId.startsWith(\".prisma/\") ||\n    normalizedId.includes(\"/node_modules/@prisma/client/\") ||\n    normalizedId.includes(\"/node_modules/.prisma/client/\")\n  );\n}\n\nconst FARM_METADATA_IMAGE_WASM_PREFIX = \"\\0farm-metadata-image-wasm:\";\n\nfunction createMetadataImageWasmPlugin(): Rollup.Plugin {\n  return {\n    name: \"farm-metadata-image-wasm\",\n    resolveId(source, importer) {\n      if (\n        !source.endsWith(\".wasm?module\") ||\n        !importer?.replace(/\\\\/g, \"/\").includes(\"/@vercel/og/\")\n      ) {\n        return null;\n      }\n\n      const requestPath = source.slice(0, -\"?module\".length);\n      const resolvedPath = path.isAbsolute(requestPath)\n        ? requestPath\n        : path.resolve(path.dirname(importer.split(\"?\", 1)[0]), requestPath);\n      return `${FARM_METADATA_IMAGE_WASM_PREFIX}${resolvedPath}`;\n    },\n    load(id) {\n      if (!id.startsWith(FARM_METADATA_IMAGE_WASM_PREFIX)) return null;\n      const wasmPath = id.slice(FARM_METADATA_IMAGE_WASM_PREFIX.length);\n      const encoded = readFileSync(wasmPath).toString(\"base64\");\n      return `\nconst encoded = ${JSON.stringify(encoded)};\nconst bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));\nexport default new WebAssembly.Module(bytes);\n`;\n    },\n  };\n}\n\nfunction collectSSRExternalPackages(ssrBundle: OutputBundle): Set<string> {\n  const emittedFiles = new Set(\n    Object.keys(ssrBundle).map((fileName) => fileName.replace(/^\\.\\//, \"\")),\n  );\n  const externalPackages = new Set<string>();\n\n  for (const [fileName, output] of Object.entries(ssrBundle)) {\n    if (output.type !== \"chunk\") continue;\n\n    for (const importId of [...output.imports, ...output.dynamicImports]) {\n      const normalizedImportId = importId.replace(/\\\\/g, \"/\");\n      const normalizedId = normalizedImportId.replace(/^\\.\\//, \"\");\n      const resolvedRelativeId =\n        normalizedImportId.startsWith(\"./\") || normalizedImportId.startsWith(\"../\")\n          ? path.posix.normalize(path.posix.join(path.posix.dirname(fileName), normalizedImportId))\n          : null;\n      if (\n        emittedFiles.has(normalizedId) ||\n        (resolvedRelativeId !== null && emittedFiles.has(resolvedRelativeId)) ||\n        NODE_BUILTIN_MODULES.has(importId) ||\n        importId.startsWith(\"node:\")\n      ) {\n        continue;\n      }\n\n      if (\n        path.isAbsolute(importId) ||\n        /^[A-Za-z]:[\\\\/]/.test(importId) ||\n        importId.startsWith(\"#\") ||\n        importId.startsWith(\"\\0\")\n      ) {\n        externalPackages.add(importId);\n        continue;\n      }\n\n      const segments = importId.split(\"/\");\n      const packageName = importId.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\n      if (packageName) externalPackages.add(packageName);\n    }\n  }\n\n  return externalPackages;\n}\n\nfunction createExternalSSRBundlePlugin(\n  nitroEntryPath: string,\n  ssrOutputDir: string,\n  ssrEntryFile: string,\n): Rollup.Plugin {\n  const resolvedNitroEntry = path.resolve(nitroEntryPath);\n  const resolvedSSREntry = path.resolve(ssrOutputDir, ssrEntryFile);\n\n  return {\n    name: \"farm-externalize-prebuilt-ssr\",\n    resolveId(source, importer) {\n      if (!importer || path.resolve(importer) !== resolvedNitroEntry) {\n        return null;\n      }\n\n      const resolvedImport = path.resolve(path.dirname(importer), source);\n      if (resolvedImport !== resolvedSSREntry) return null;\n\n      // A package import remains valid even when Nitro moves its adapter into a\n      // nested chunk. A relative external import would be resolved from that\n      // adapter chunk and can point at the wrong location.\n      return { id: FARM_SSR_PACKAGE_IMPORT, external: true };\n    },\n  };\n}\n\nfunction hasRollupPlugins(plugins: unknown): boolean {\n  if (Array.isArray(plugins)) {\n    return plugins.some((plugin) => hasRollupPlugins(plugin));\n  }\n  return Boolean(plugins);\n}\n\nexport function hasFarmRuntimeConfigModule(\n  config: Pick<ResolvedFarmConfig, \"layers\">,\n  configModulePath: string | null,\n): boolean {\n  return Boolean(configModulePath || (config.layers || []).some((layer) => layer.configFile));\n}\n\nfunction createEsbuildTransformOptions(\n  configuredEsbuildOptions: FarmEsbuildOptions,\n  minify: boolean,\n  defaultTarget: string,\n): TransformOptions {\n  const {\n    include: _include,\n    exclude: _exclude,\n    sourceMap: _sourceMap,\n    loaders: _loaders,\n    ...configuredTransformOptions\n  } = configuredEsbuildOptions;\n  const configuredTarget = Array.isArray(configuredTransformOptions.target)\n    ? configuredTransformOptions.target.filter(\n        (target): target is string => typeof target === \"string\",\n      )\n    : configuredTransformOptions.target;\n  const transformTarget =\n    Array.isArray(configuredTarget) && configuredTarget.length === 0\n      ? defaultTarget\n      : (configuredTarget ?? defaultTarget);\n  const transformSupported = configuredTransformOptions.supported\n    ? Object.fromEntries(\n        Object.entries(configuredTransformOptions.supported).filter(\n          (entry): entry is [string, boolean] => typeof entry[1] === \"boolean\",\n        ),\n      )\n    : undefined;\n\n  return {\n    ...(configuredTransformOptions as TransformOptions),\n    format: \"esm\",\n    target: transformTarget,\n    loader: \"js\",\n    sourcemap: false,\n    minify,\n    keepNames: configuredTransformOptions.keepNames ?? true,\n    legalComments: configuredTransformOptions.legalComments ?? \"none\",\n    supported: transformSupported,\n  };\n}\n\nfunction createEsbuildChunkMinifyPlugin(\n  configuredEsbuildOptions: FarmEsbuildOptions,\n): Rollup.Plugin {\n  const configuredTransformOptions = createEsbuildTransformOptions(\n    configuredEsbuildOptions,\n    true,\n    \"esnext\",\n  );\n  // Nitro already applies the configured esbuild transform to every module.\n  // Keep this final chunk pass limited to minification controls so options such\n  // as banner, footer, define, drop, and property mangling are not applied twice.\n  const transformOptions: TransformOptions = {\n    format: \"esm\",\n    target: configuredTransformOptions.target,\n    loader: \"js\",\n    sourcemap: false,\n    minify: true,\n    keepNames: configuredTransformOptions.keepNames,\n    legalComments: configuredTransformOptions.legalComments,\n    charset: configuredTransformOptions.charset,\n  };\n\n  return {\n    name: \"farm-esbuild-minify\",\n    async renderChunk(code, chunk) {\n      const { transform } = await import(\"esbuild\");\n      const result = await transform(code, {\n        ...transformOptions,\n        sourcefile: chunk.fileName,\n      });\n      if (!result.code) return null;\n      return {\n        code: result.code,\n        map: result.map || null,\n      };\n    },\n  };\n}\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction resolveBuildDocsContentDir(config: ResolvedFarmConfig, root: string): string | null {\n  if (!config.docs?.enabled) return null;\n\n  const configuredContentDir = config.docs.contentDir || config.docs.config.contentDir;\n  if (typeof configuredContentDir === \"string\" && configuredContentDir.trim()) {\n    const contentDir = path.isAbsolute(configuredContentDir)\n      ? configuredContentDir\n      : path.join(root, configuredContentDir);\n    return existsSync(contentDir) ? contentDir : null;\n  }\n\n  const entryDir = config.docs.config.entry || trimSlashes(config.docs.entry) || \"docs\";\n  const appDocsDir = path.join(root, config.srcDir || \"src\", \"app\", entryDir);\n  if (existsSync(appDocsDir)) return appDocsDir;\n\n  const rootDocsDir = path.join(root, entryDir);\n  return existsSync(rootDocsDir) ? rootDocsDir : null;\n}\n\nfunction hasProjectPostcssConfig(root: string): boolean {\n  const candidates = [\n    \"postcss.config.js\",\n    \"postcss.config.cjs\",\n    \"postcss.config.mjs\",\n    \"postcss.config.ts\",\n    \"postcss.config.json\",\n    \".postcssrc\",\n    \".postcssrc.json\",\n    \".postcssrc.js\",\n    \".postcssrc.cjs\",\n    \".postcssrc.mjs\",\n    \".postcssrc.ts\",\n  ];\n\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  return candidates.some((file) => {\n    try {\n      projectRequire.resolve(`./${file}`);\n      return true;\n    } catch {\n      return false;\n    }\n  });\n}\n\nasync function findFarmConfigPath(root: string): Promise<string | null> {\n  const fs = await import(\"fs/promises\");\n  const candidates = [\n    \"farm.config.ts\",\n    \"farm.config.mts\",\n    \"farm.config.js\",\n    \"farm.config.mjs\",\n    \"config.ts\",\n    \"config.mts\",\n    \"config.js\",\n    \"config.mjs\",\n  ];\n\n  for (const candidate of candidates) {\n    const resolvedPath = path.join(root, candidate);\n    try {\n      await fs.access(resolvedPath);\n      return resolvedPath;\n    } catch {\n      // Continue checking the next supported config path.\n    }\n  }\n\n  return null;\n}\n\nfunction hasFarmMiddlewareConfig(config: ResolvedFarmConfig[\"middleware\"]): boolean {\n  if (!config) return false;\n  if (Array.isArray(config)) return config.length > 0;\n\n  const configRecord = config as Record<string, unknown>;\n  return Boolean(\n    configRecord.matcher ||\n    configRecord.exclude ||\n    configRecord.runtime ||\n    configRecord.handler ||\n    (Array.isArray(configRecord.handlers) && configRecord.handlers.length > 0),\n  );\n}\n\nfunction hasFarmServerRuntimePlugins(config: ResolvedFarmConfig): boolean {\n  return (config.plugins || []).some((plugin) => {\n    if (getFarmIntegrationPluginServerRuntime(plugin) === false) return false;\n\n    return Boolean(\n      plugin.setup ||\n      plugin.init ||\n      plugin.ready ||\n      plugin.shutdown ||\n      plugin.runtime ||\n      plugin.router ||\n      plugin.render ||\n      plugin.beforeRouteMatch ||\n      plugin.afterRouteMatch ||\n      plugin.beforeRender ||\n      plugin.afterRender ||\n      plugin.onError ||\n      plugin.transformHTML,\n    );\n  });\n}\n\nfunction hasFarmPluginRoutes(config: ResolvedFarmConfig): boolean {\n  return (config.plugins || []).some((plugin) => Boolean(plugin.routes));\n}\n\nfunction farmServerRuntimePluginsMayHandlePath(\n  config: ResolvedFarmConfig,\n  pathname: string,\n): boolean {\n  return (config.plugins || []).some(\n    (plugin) =>\n      getFarmIntegrationPluginServerRuntime(plugin) !== false &&\n      farmPluginMayAffectRuntimePath(plugin, pathname),\n  );\n}\n\nexport async function discoverMiddlewareRoutes(\n  appDir: string | readonly string[],\n): Promise<UniversalMiddlewareRoute[]> {\n  const fs = await import(\"fs/promises\");\n  const appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n  const routes = new Map<string, UniversalMiddlewareRoute>();\n\n  async function walk(\n    dir: string,\n    routePath: string,\n    discovered: UniversalMiddlewareRoute[],\n  ): Promise<void> {\n    let entries: import(\"fs\").Dirent[];\n    try {\n      entries = await fs.readdir(dir, { withFileTypes: true });\n    } catch {\n      return;\n    }\n\n    const middlewareFile = entries.find(\n      (entry) => entry.isFile() && /^middleware\\.(tsx?|jsx?)$/.test(entry.name),\n    );\n\n    if (middlewareFile) {\n      discovered.push({\n        path: routePath,\n        filePath: path.join(dir, middlewareFile.name),\n      });\n    }\n\n    for (const entry of entries) {\n      if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name.startsWith(\"_\")) {\n        continue;\n      }\n\n      const childRoutePath = appendMiddlewareRoutePath(routePath, entry.name);\n      await walk(path.join(dir, entry.name), childRoutePath, discovered);\n    }\n  }\n\n  for (const sourceAppDir of appDirs) {\n    const discovered: UniversalMiddlewareRoute[] = [];\n    await walk(sourceAppDir, \"/\", discovered);\n    for (const route of discovered) {\n      routes.set(route.path, route);\n    }\n  }\n\n  return Array.from(routes.values()).sort((a, b) => {\n    const depthA = a.path.split(\"/\").filter(Boolean).length;\n    const depthB = b.path.split(\"/\").filter(Boolean).length;\n    return depthA - depthB || a.path.localeCompare(b.path);\n  });\n}\n\n/**\n * Universal build using TanStack Start pattern\n * - Builds SSR bundle in memory\n * - Uses virtual bundle plugin to expose to Nitro\n * - Creates virtual entry wrapping Web Standard handler\n */\n/** External docs adapters must explicitly publish the versioned compiler Farm\n * uses to turn their Node-backed build runtime into an edge-safe snapshot. */\nexport function assertFarmDocsRuntimeSupported(\n  config: Pick<ResolvedFarmConfig, \"docs\">,\n  preset: string,\n): void {\n  if (\n    !config.docs?.enabled ||\n    !config.docs.adapter?.server ||\n    getFarmPresetRuntime(preset) !== \"edge\" ||\n    Boolean(config.docs.adapter.edgeCompiler)\n  ) {\n    return;\n  }\n  throw new Error(\n    `The configured docs adapter (${config.docs.adapter.id}) has not declared an edge compiler, ` +\n      `but the \"${preset}\" preset deploys to an edge runtime. Set docs.adapter = false ` +\n      \"to use Farm's precompiled embedded renderer, choose a Node target, or disable docs for \" +\n      \"this deployment.\",\n  );\n}\n\nexport async function buildUniversal(\n  config: ResolvedFarmConfig,\n  routeManager: RouteManager,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: ServerRenderer,\n  options: {\n    preset?: string;\n    root?: string;\n    pluginManager?: PluginManager;\n    routeRuntimeManifest?: FarmRouteRuntimeManifest;\n    productionVite?: FarmProductionViteRuntime | Promise<FarmProductionViteRuntime>;\n  } = {},\n): Promise<void> {\n  const root = options.root || config.root || process.cwd();\n  const preset = options.preset || config.preset || \"node-server\";\n  assertFarmDocsRuntimeSupported(config, preset);\n  const srcDir = config.srcDir || \"src\";\n  const distDir = config.distDir || \".farm\";\n  const deployOutputDir = resolveDeployOutputPath(root, config.deploy.outputDir);\n  const lifecyclePluginManager = options.pluginManager;\n  // Attach all-settled handlers immediately so an earlier discovery failure\n  // cannot leave a rejected preload unobserved.\n  const productionViteResultPromise = Promise.allSettled([\n    Promise.resolve(options.productionVite ?? loadFarmProductionVite()),\n  ]);\n  // Nitro is guaranteed to be needed for every universal production build.\n  // Start resolving it while route metadata and the client/SSR bundles are\n  // prepared, then consume the settled result at the adapter stage.\n  const nitroBuilderResultPromise = preloadFarmNitroBuilder();\n\n  logger.info(`🚜 Building Farm.js application (universal) with preset: ${preset}...`);\n\n  try {\n    const routeRuntimeManifestPromise = options.routeRuntimeManifest\n      ? Promise.resolve(options.routeRuntimeManifest)\n      : createFarmRouteRuntimeManifest({\n          config,\n          routeManager,\n          apiRouteManager,\n          root,\n        });\n    const routeRuntimeManifestResultPromise = Promise.allSettled([routeRuntimeManifestPromise]);\n\n    // Get page routes first (needed for both client and SSR builds)\n    const pageRoutes: UniversalPageRoute[] = [];\n    for (const [pattern, entry] of routeManager.getRoutes()) {\n      const markdownSourcePath =\n        entry.markdownSourcePath ||\n        (isFarmMarkdownPageFile(entry.modulePath) ? entry.modulePath : undefined);\n      pageRoutes.push({\n        pattern,\n        modulePath: entry.modulePath,\n        ...(markdownSourcePath\n          ? {\n              source: readFileSync(markdownSourcePath, \"utf8\"),\n              markdownSourcePath,\n            }\n          : {}),\n      });\n    }\n    const routeSlots: UniversalRouteSlot[] = Array.from(\n      routeManager.getRouteSlots().values(),\n      (entry) => ({\n        name: entry.name,\n        ownerPattern: entry.ownerPattern,\n        pattern: entry.pattern,\n        modulePath: entry.modulePath,\n        containerId: entry.containerId,\n        interception: entry.interception,\n        fallback: entry.fallback,\n      }),\n    );\n    logger.info(`📋 Found ${pageRoutes.length} page routes`);\n\n    // Discover layout files early (needed for client CSS scanning)\n    const fs = await import(\"fs/promises\");\n    const layoutRoutes: Array<{ pattern: string; modulePath: string }> = [];\n    const appDir = path.join(root, srcDir, \"app\");\n\n    async function findLayoutsForClient(dir: string, routePrefix: string = \"/\"): Promise<void> {\n      try {\n        const entries = await fs.readdir(dir, { withFileTypes: true });\n        for (const entry of entries) {\n          if (entry.isFile() && entry.name.match(/^layout\\.(tsx?|jsx?|vue|svelte)$/)) {\n            layoutRoutes.push({\n              pattern: routePrefix,\n              modulePath: path.join(dir, entry.name),\n            });\n          } else if (\n            entry.isDirectory() &&\n            !entry.name.startsWith(\".\") &&\n            !entry.name.startsWith(\"_\")\n          ) {\n            const childPrefix =\n              routePrefix === \"/\" ? `/${entry.name}` : `${routePrefix}/${entry.name}`;\n            await findLayoutsForClient(path.join(dir, entry.name), childPrefix);\n          }\n        }\n      } catch {\n        // Directory doesn't exist or can't be read\n      }\n    }\n    await findLayoutsForClient(appDir);\n    const seenLayoutPatterns = new Set(layoutRoutes.map((layout) => layout.pattern));\n    for (const [pattern, entry] of routeManager.getLayouts()) {\n      if (seenLayoutPatterns.has(pattern)) continue;\n      seenLayoutPatterns.add(pattern);\n      layoutRoutes.push({ pattern, modulePath: entry.modulePath });\n    }\n    logger.info(`📋 Found ${pageRoutes.length} page routes and ${layoutRoutes.length} layouts`);\n\n    const isolatedClientBoundaryModules = routeManager.getIsolatedClientBoundaryModules(root);\n    const hydrationPlanCache = new Map<string, ClientModuleHydrationPlan>();\n\n    const clientOutputDir = path.join(root, distDir, \"client\");\n    const [productionViteResult] = await productionViteResultPromise;\n    if (productionViteResult.status === \"rejected\") {\n      // Route evaluation may still be using the project module server. Drain it\n      // before the outer build cleanup closes that server.\n      await routeRuntimeManifestResultPromise;\n      throw productionViteResult.reason;\n    }\n    const productionVite = productionViteResult.value;\n    if (productionVite.builder === \"rolldown\") {\n      logger.info(\"⚡ Building application bundles with Vite Rolldown\");\n    }\n\n    const buildClientBundle = () =>\n      buildClient(\n        productionVite,\n        config,\n        root,\n        srcDir,\n        clientOutputDir,\n        pageRoutes,\n        layoutRoutes,\n        routeSlots,\n        isolatedClientBoundaryModules,\n        hydrationPlanCache,\n      );\n    const buildSSRBundle = () =>\n      buildSSRInMemory(\n        productionVite,\n        config,\n        root,\n        routeManager,\n        apiRouteManager,\n        serverRenderer,\n        preset,\n        pageRoutes,\n        layoutRoutes,\n        routeSlots,\n        isolatedClientBoundaryModules,\n        hydrationPlanCache,\n      );\n\n    // Route metadata and the client/SSR graphs read independent inputs. Drain\n    // every task before propagating a deterministic first failure so a rejected\n    // sibling cannot keep mutating build output in the background. Renderer\n    // compiler plugins with process-global caches can request serial graphs.\n    let clientBuildResult: PromiseSettledResult<Awaited<ReturnType<typeof buildClientBundle>>>;\n    let ssrBuildResult: PromiseSettledResult<Awaited<ReturnType<typeof buildSSRBundle>>>;\n    if (config.renderer.buildConcurrency === \"serial\") {\n      logger.info(`📦 Building client and SSR bundles serially for ${config.renderer.name}...`);\n      [clientBuildResult] = await Promise.allSettled([buildClientBundle()]);\n      [ssrBuildResult] = await Promise.allSettled([buildSSRBundle()]);\n    } else {\n      logger.info(\"📦 Building client and SSR bundles in parallel...\");\n      [clientBuildResult, ssrBuildResult] = await Promise.allSettled([\n        buildClientBundle(),\n        buildSSRBundle(),\n      ]);\n    }\n    const [routeRuntimeManifestResult] = await routeRuntimeManifestResultPromise;\n    if (routeRuntimeManifestResult.status === \"rejected\") {\n      throw routeRuntimeManifestResult.reason;\n    }\n    if (ssrBuildResult.status === \"rejected\") throw ssrBuildResult.reason;\n    if (clientBuildResult.status === \"rejected\") {\n      if (\n        productionVite.builder !== \"rolldown\" ||\n        !(clientBuildResult.reason instanceof IncompleteClientBuildOutputError)\n      ) {\n        throw clientBuildResult.reason;\n      }\n\n      // Rolldown can very rarely complete a parallel client build without\n      // traversing its entry graph. Preserve the fast parallel path, then\n      // recover only that invalid result once the SSR graph is fully drained.\n      logger.warn(\"Client bundle was incomplete; retrying after the SSR build...\");\n      try {\n        await buildClient(\n          productionVite,\n          config,\n          root,\n          srcDir,\n          clientOutputDir,\n          pageRoutes,\n          layoutRoutes,\n          routeSlots,\n          isolatedClientBoundaryModules,\n          hydrationPlanCache,\n        );\n      } catch (retryError) {\n        if (!(retryError instanceof IncompleteClientBuildOutputError)) throw retryError;\n\n        // A second Rolldown pass can observe the same incomplete graph when a\n        // renderer or build plugin leaves process-global state behind. Keep\n        // the server/SSR bundle on the selected builder, but use Vite's\n        // compatibility Rollup path for the client rather than shipping a\n        // missing browser entry.\n        logger.warn(\"Client bundle remained incomplete; falling back to Rollup...\");\n        const rollupVite = await loadFarmProductionVite(\"rollup\");\n        await buildClient(\n          rollupVite,\n          config,\n          root,\n          srcDir,\n          clientOutputDir,\n          pageRoutes,\n          layoutRoutes,\n          routeSlots,\n          isolatedClientBoundaryModules,\n          hydrationPlanCache,\n        );\n      }\n    }\n\n    const ssrResult = ssrBuildResult.value;\n    const routeRuntimeManifest = routeRuntimeManifestResult.value;\n\n    const runtimeValidation = validateFarmRouteRuntimeDeployment(routeRuntimeManifest, preset);\n    for (const warning of runtimeValidation.warnings) {\n      logger.warn(warning);\n    }\n\n    const { bundle: ssrBundle, entryFile: ssrEntryFile, configuredHeaderRoutes } = ssrResult;\n    await writeSSRAssetsToClient(ssrBundle, clientOutputDir);\n    if (config.docs.enabled) {\n      await copyFarmDocsFontAssetsToClient(root, clientOutputDir);\n    }\n\n    // Step 3: Build with Nitro using virtual bundle\n    logger.info(`🚀 Building server with Nitro (preset: ${preset})...`);\n    await buildNitroUniversal(\n      config,\n      routeManager,\n      apiRouteManager,\n      serverRenderer,\n      preset,\n      root,\n      distDir,\n      ssrBundle,\n      ssrEntryFile,\n      clientOutputDir,\n      routeRuntimeManifest,\n      configuredHeaderRoutes,\n      nitroBuilderResultPromise,\n      lifecyclePluginManager,\n    );\n\n    const runtimeManifestPath = await writeFarmRouteRuntimeManifest(\n      path.join(root, distDir),\n      routeRuntimeManifest,\n    );\n    logger.info(`📋 Route runtime manifest: ${path.relative(root, runtimeManifestPath)}`);\n    // The completion summary is printed once, by the build orchestrator.\n  } catch (error) {\n    if (lifecyclePluginManager) {\n      await lifecyclePluginManager.runHookParallel(\"onError\", {\n        phase: \"buildUniversal\",\n        error,\n        meta: {\n          root,\n          preset,\n        },\n      });\n    }\n    logger.error(`❌ Build failed: ${error}`);\n    throw error;\n  }\n}\n\nasync function writeSSRAssetsToClient(bundle: OutputBundle, outputDir: string): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  for (const [fileName, output] of Object.entries(bundle)) {\n    if (output.type !== \"asset\") continue;\n    if (fileName === \"farm-fonts.css\") {\n      await mergeBuiltFontCss(outputDir, output.source);\n      continue;\n    }\n    const filePath = path.join(outputDir, fileName);\n    await fs.mkdir(path.dirname(filePath), { recursive: true });\n    await fs.writeFile(filePath, output.source);\n  }\n}\n\nasync function copyFarmDocsFontAssetsToClient(root: string, outputDir: string): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  await Promise.all(\n    resolveFarmDocsFontAssets(root).map(async ({ sourcePath, url }) => {\n      const targetPath = path.join(outputDir, url.replace(/^\\/+/, \"\"));\n      await fs.mkdir(path.dirname(targetPath), { recursive: true });\n      await fs.copyFile(sourcePath, targetPath);\n    }),\n  );\n}\n\nasync function mergeBuiltFontCss(\n  outputDir: string,\n  fontCssSource?: string | Uint8Array,\n): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const fontCssPath = path.join(outputDir, \"farm-fonts.css\");\n  let fontCss = fontCssSource;\n  if (fontCss === undefined) {\n    try {\n      fontCss = await fs.readFile(fontCssPath);\n    } catch {\n      return;\n    }\n  }\n\n  const clientCssPath = path.join(outputDir, \"farm-client.css\");\n  let clientCss = \"\";\n  try {\n    clientCss = await fs.readFile(clientCssPath, \"utf8\");\n  } catch {\n    // A font-only app may not have produced a stylesheet yet.\n  }\n  const normalizedFontCss =\n    typeof fontCss === \"string\" ? fontCss : Buffer.from(fontCss).toString(\"utf8\");\n  await fs.writeFile(fontCssPath, normalizedFontCss);\n  await fs.writeFile(clientCssPath, mergeFarmFontCss(clientCss, normalizedFontCss));\n}\n\nclass IncompleteClientBuildOutputError extends Error {\n  constructor(detail: string) {\n    super(`Farm client build produced incomplete output: ${detail}`);\n    this.name = \"IncompleteClientBuildOutputError\";\n  }\n}\n\nasync function validateClientBuildOutput(\n  root: string,\n  srcDir: string,\n  outputDir: string,\n): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const fingerprinted = await findFingerprintedClientEntry(outputDir);\n  const clientEntryPath = path.join(outputDir, fingerprinted ?? \"farm-client.js\");\n  let clientEntrySize = 0;\n\n  try {\n    const clientEntry = await fs.stat(clientEntryPath);\n    if (clientEntry.isFile()) clientEntrySize = clientEntry.size;\n  } catch {\n    // Report the missing entry through the shared incomplete-output diagnostic.\n  }\n\n  if (clientEntrySize === 0) {\n    throw new IncompleteClientBuildOutputError(\"farm-client.js is missing or empty\");\n  }\n\n  const clientCssPath = path.join(outputDir, \"farm-client.css\");\n  const globalsCssPath = path.join(root, srcDir, \"app\", \"globals.css\");\n  let expectsCss = false;\n  try {\n    const globalsCss = await fs.readFile(globalsCssPath, \"utf8\");\n    expectsCss = globalsCss.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\").trim().length > 0;\n  } catch {\n    // Vite reports a missing imported stylesheet before output validation.\n  }\n\n  try {\n    const clientCss = await fs.stat(clientCssPath);\n    if (expectsCss && (!clientCss.isFile() || clientCss.size === 0)) {\n      throw new IncompleteClientBuildOutputError(\"farm-client.css is empty\");\n    }\n  } catch (error) {\n    if (error instanceof IncompleteClientBuildOutputError) throw error;\n    if (expectsCss) {\n      throw new IncompleteClientBuildOutputError(\"farm-client.css is missing\");\n    }\n\n    // Farm's HTML always references this stable path. Keep intentionally\n    // style-free applications from receiving an unnecessary 404.\n    await fs.writeFile(clientCssPath, \"\");\n  }\n}\n\n/**\n * Build client bundle (to disk) with hydration for \"use client\" components\n */\nfunction getCachedClientModuleHydrationPlan(\n  modulePath: string,\n  root: string,\n  mode: FarmIsolatedClientHydrationMode,\n  cache: Map<string, ClientModuleHydrationPlan>,\n  options: FarmClientHydrationPlanOptions = {},\n): ClientModuleHydrationPlan {\n  const key = `${path.resolve(root)}\\0${mode}\\0${options.asyncOwnerIslands === true}\\0${path.resolve(modulePath)}`;\n  let plan = cache.get(key);\n  if (!plan) {\n    plan = getClientModuleHydrationPlan(modulePath, root, mode, options);\n    cache.set(key, plan);\n  }\n  return { ...plan, isolatedBoundaries: [...plan.isolatedBoundaries] };\n}\n\nasync function buildClient(\n  productionVite: FarmProductionViteRuntime,\n  config: ResolvedFarmConfig,\n  root: string,\n  srcDir: string,\n  outputDir: string,\n  pageRoutes: UniversalPageRoute[],\n  layoutRoutes: Array<{ pattern: string; modulePath: string }> = [],\n  routeSlots: UniversalRouteSlot[] = [],\n  isolatedClientBoundaryModules: ReadonlySet<string> = new Set(),\n  hydrationPlanCache: Map<string, ClientModuleHydrationPlan> = new Map(),\n) {\n  const viteBuild = productionVite.build;\n  const { farmPlugin, farmServerOnlyEntriesPlugin } = await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n  const fs = await import(\"fs/promises\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n\n  // Detect which pages should hydrate on the client.\n  const clientPages: Array<{\n    pattern: string;\n    modulePath: string;\n    relativePath: string;\n    pageShouldHydrate: boolean;\n    islandStrategy: FarmIslandStrategy;\n    hasIsolatedClientBoundaries: boolean;\n    isolatedBoundaries: IsolatedClientBoundaryReference[];\n  }> = [];\n\n  const integrationProviders = getIntegrationProviders(config.integrations).filter(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  const unsupportedIntegrationProvider = integrationProviders.find(\n    (provider) => provider.supportsIsolatedHydration !== true,\n  );\n  if (\n    config.experimental?.isolatedClientHydration === \"enabled\" &&\n    config.experimental?.serverComponents !== true &&\n    unsupportedIntegrationProvider\n  ) {\n    logger.warn(\n      `[Farm.js] isolated hydration kept route-wide because integration provider \"${unsupportedIntegrationProvider.name}\" does not declare supportsIsolatedHydration: true.`,\n    );\n  }\n  const isolatedMode = resolveFarmIsolatedClientHydrationMode(\n    config.experimental?.isolatedClientHydration,\n    {\n      serverComponents: config.experimental?.serverComponents === true,\n      hasUnsupportedIntegrationProvider: Boolean(unsupportedIntegrationProvider),\n    },\n  );\n  const planOptions = getFarmClientHydrationPlanOptions(\n    config.renderer,\n    Boolean(unsupportedIntegrationProvider),\n  );\n\n  const clientLayouts = layoutRoutes.map((layout) => {\n    try {\n      const metadata = getCachedClientModuleHydrationPlan(\n        layout.modulePath,\n        root,\n        isolatedMode,\n        hydrationPlanCache,\n        planOptions,\n      );\n      return {\n        ...layout,\n        shouldHydrate: metadata.shouldHydrate,\n        islandStrategy: metadata.islandStrategy,\n        legacyShouldHydrate: metadata.legacyShouldHydrate,\n        legacyIslandStrategy: metadata.legacyIslandStrategy,\n        mode: metadata.mode,\n        estimatedIsolatedRootCount: metadata.estimatedIsolatedRootCount,\n        hasIsolatedClientBoundaries: metadata.hasIsolatedClientBoundaries,\n        isolatedHydrationEligible: metadata.isolatedHydrationEligible,\n        isolatedBoundaries: metadata.isolatedBoundaries,\n        asyncOwnerIslands: metadata.asyncOwnerIslands,\n        suppressedAsyncHydration: metadata.suppressedAsyncHydration,\n        fallbackReason: metadata.fallbackReason,\n      };\n    } catch (error) {\n      logger.warn(`⚠️  Could not inspect layout file ${layout.modulePath}: ${error}`);\n      return {\n        ...layout,\n        shouldHydrate: false,\n        islandStrategy: null,\n        legacyShouldHydrate: false,\n        legacyIslandStrategy: null,\n        mode: isolatedMode,\n        estimatedIsolatedRootCount: 0,\n        hasIsolatedClientBoundaries: false,\n        isolatedHydrationEligible: false,\n        isolatedBoundaries: [],\n        asyncOwnerIslands: undefined,\n        suppressedAsyncHydration: undefined,\n        fallbackReason: undefined,\n      };\n    }\n  });\n\n  const layoutAppliesToRoute = (layoutPattern: string, routePattern: string) =>\n    layoutPattern === \"/\" ||\n    routePattern === layoutPattern ||\n    routePattern.startsWith(`${layoutPattern}/`);\n\n  const adapterOwnsDocsRuntime = Boolean(\n    isReactRenderer(config.renderer) &&\n    config.docs?.enabled &&\n    config.docs.adapter?.server &&\n    config.docs.adapter.react,\n  );\n  const adapterDocsEntry = config.docs?.enabled\n    ? `/${config.docs.entry || \"docs\"}`.replace(/\\/+/g, \"/\").replace(/\\/$/, \"\") || \"/\"\n    : null;\n  const isAdapterDocsRoute = (routePattern: string) =>\n    Boolean(\n      adapterOwnsDocsRuntime &&\n      adapterDocsEntry &&\n      (adapterDocsEntry === \"/\" ||\n        routePattern === adapterDocsEntry ||\n        routePattern.startsWith(`${adapterDocsEntry}/`)),\n    );\n  const syntheticDocsEntry =\n    config.docs?.enabled && !adapterOwnsDocsRuntime ? adapterDocsEntry : null;\n  const syntheticDocsPatterns = syntheticDocsEntry\n    ? syntheticDocsEntry === \"/\"\n      ? [\"/\", \"/[...slug]\"]\n      : [syntheticDocsEntry, `${syntheticDocsEntry}/[...slug]`]\n    : [];\n\n  const markdownPagePlan = createMarkdownPageHydrationPlanner(\n    resolveFarmMdxComponentsModulePath(resolveMdxConfig(config.mdx), root),\n    root,\n    isolatedMode,\n    planOptions,\n  );\n  const routePlans = pageRoutes.map((route) => ({\n    route,\n    metadata: isFarmMarkdownPageFile(route.modulePath)\n      ? markdownPagePlan()\n      : getCachedClientModuleHydrationPlan(\n          route.modulePath,\n          root,\n          isolatedMode,\n          hydrationPlanCache,\n          planOptions,\n        ),\n  }));\n\n  enforceFarmIsolatedHydrationRouteBudget(\n    clientLayouts.map((layout) => ({\n      pattern: layout.pattern,\n      depth: layout.pattern.split(\"/\").filter(Boolean).length,\n      metadata: layout,\n    })),\n    [\n      ...routePlans.map(({ route, metadata }) => ({\n        pattern: route.pattern,\n        depth: route.pattern.split(\"/\").filter(Boolean).length,\n        metadata,\n      })),\n      ...syntheticDocsPatterns.map((pattern) => ({\n        pattern,\n        depth: pattern.split(\"/\").filter(Boolean).length,\n        metadata: {\n          mode: isolatedMode,\n          shouldHydrate: false,\n          islandStrategy: null,\n          legacyShouldHydrate: false,\n          legacyIslandStrategy: null,\n          estimatedIsolatedRootCount: 0,\n          hasIsolatedClientBoundaries: false,\n          isolatedBoundaries: [] as IsolatedClientBoundaryReference[],\n        },\n      })),\n    ],\n    layoutAppliesToRoute,\n  );\n\n  for (const layout of clientLayouts) {\n    const matchesBuiltRoute =\n      pageRoutes.some((route) => layoutAppliesToRoute(layout.pattern, route.pattern)) ||\n      Boolean(adapterDocsEntry && layoutAppliesToRoute(layout.pattern, adapterDocsEntry));\n    if (matchesBuiltRoute && layout.suppressedAsyncHydration) {\n      logger.warn(`⚠️  ${describeSuppressedAsyncHydration(layout.pattern, layout.fallbackReason)}`);\n    }\n  }\n\n  if (isolatedMode === \"analyze\") {\n    for (const { entry, metadata } of [\n      ...clientLayouts.map((layout) => ({ entry: layout, metadata: layout })),\n      ...routePlans.map(({ route, metadata }) => ({ entry: route, metadata })),\n    ]) {\n      if (!(\"isolatedHydrationEligible\" in metadata) || !metadata.isolatedHydrationEligible) {\n        continue;\n      }\n      logger.info(\n        `📊 Isolated hydration analysis: ${entry.modulePath} can exclude its server owner and hydrate ${metadata.isolatedBoundaries.length} client ${metadata.isolatedBoundaries.length === 1 ? \"boundary\" : \"boundaries\"}.`,\n      );\n    }\n  }\n\n  for (const { route, metadata } of routePlans) {\n    // The adapter imports and hydrates its compiled MDX modules itself. Keeping\n    // the same files in Farm's generic route table duplicates the docs runtime\n    // and can pull server-only Markdown dependencies into the browser bundle.\n    if (isAdapterDocsRoute(route.pattern)) continue;\n\n    try {\n      const applicableClientLayouts = clientLayouts.filter(\n        (layout) =>\n          (layout.shouldHydrate || layout.hasIsolatedClientBoundaries) &&\n          layoutAppliesToRoute(layout.pattern, route.pattern),\n      );\n      if (metadata.suppressedAsyncHydration) {\n        logger.warn(\n          `⚠️  ${describeSuppressedAsyncHydration(route.pattern, metadata.fallbackReason)}`,\n        );\n      }\n      if (\n        metadata.shouldHydrate ||\n        metadata.hasIsolatedClientBoundaries ||\n        applicableClientLayouts.length > 0\n      ) {\n        const relativePath = route.modulePath.replace(root, \"\").replace(/^\\//, \"\");\n        const hydrationStrategies = [\n          ...(metadata.islandStrategy ? [metadata.islandStrategy] : []),\n          ...applicableClientLayouts.flatMap((layout) =>\n            layout.islandStrategy ? [layout.islandStrategy] : [],\n          ),\n        ];\n        const islandStrategy = hydrationStrategies.every(\n          (strategy) => strategy === hydrationStrategies[0],\n        )\n          ? (hydrationStrategies[0] ?? \"load\")\n          : \"load\";\n        clientPages.push({\n          ...route,\n          relativePath,\n          pageShouldHydrate: metadata.shouldHydrate,\n          islandStrategy,\n          hasIsolatedClientBoundaries:\n            metadata.hasIsolatedClientBoundaries ||\n            applicableClientLayouts.some((layout) => layout.hasIsolatedClientBoundaries),\n          isolatedBoundaries: [\n            ...(metadata.hasIsolatedClientBoundaries ? metadata.isolatedBoundaries : []),\n            ...applicableClientLayouts\n              .filter((layout) => layout.hasIsolatedClientBoundaries)\n              .flatMap((layout) => layout.isolatedBoundaries),\n          ],\n        });\n        logger.info(`📱 Found hydratable route: ${route.pattern} -> ${route.modulePath}`);\n      }\n    } catch (error) {\n      logger.warn(`⚠️  Could not inspect route file ${route.modulePath}: ${error}`);\n    }\n  }\n\n  if (syntheticDocsEntry) {\n    const docsEntry = syntheticDocsEntry;\n    const applicableClientLayouts = clientLayouts.filter(\n      (layout) =>\n        (layout.shouldHydrate || layout.hasIsolatedClientBoundaries) &&\n        layoutAppliesToRoute(layout.pattern, docsEntry),\n    );\n    if (applicableClientLayouts.length > 0) {\n      const hydrationStrategies = applicableClientLayouts.flatMap((layout) =>\n        layout.islandStrategy ? [layout.islandStrategy] : [],\n      );\n      const islandStrategy = hydrationStrategies.every(\n        (strategy) => strategy === hydrationStrategies[0],\n      )\n        ? (hydrationStrategies[0] ?? \"load\")\n        : \"load\";\n      const docsClientRoutes = syntheticDocsPatterns.map((pattern) => ({\n        pattern,\n        modulePath: \"\",\n        relativePath: \"\",\n        pageShouldHydrate: false,\n        islandStrategy,\n        hasIsolatedClientBoundaries: applicableClientLayouts.some(\n          (layout) => layout.hasIsolatedClientBoundaries,\n        ),\n        isolatedBoundaries: applicableClientLayouts\n          .filter((layout) => layout.hasIsolatedClientBoundaries)\n          .flatMap((layout) => layout.isolatedBoundaries),\n      }));\n\n      // Docs requests take precedence over app page routes on the server, so\n      // their synthetic layout-only entries must take precedence in the client\n      // route table as well.\n      clientPages.unshift(...docsClientRoutes);\n    }\n  }\n\n  const clientRouteSlots = routeSlots.filter((slot) => {\n    try {\n      return getClientModuleMetadata(slot.modulePath, root).shouldHydrate;\n    } catch (error) {\n      logger.warn(`⚠️  Could not inspect route slot ${slot.modulePath}: ${error}`);\n      return false;\n    }\n  });\n\n  logger.info(\n    `📱 Total hydratable routes detected: ${clientPages.length} pages, ${clientLayouts.filter((layout) => layout.shouldHydrate || layout.hasIsolatedClientBoundaries).length} layouts, and ${clientRouteSlots.length} slots`,\n  );\n\n  // Generate client hydration entry code\n  // Keep generated entries under the project so bare imports resolve through the\n  // application's node_modules, including isolated production-build fixtures.\n  const clientEntryRoot = path.join(root, \".farm\", \"tmp\");\n  await fs.mkdir(clientEntryRoot, { recursive: true });\n  const clientEntryDir = await fs.mkdtemp(path.join(clientEntryRoot, \"client-entry-\"));\n  const clientEntryPath = path.join(clientEntryDir, \"farm-client-entry.tsx\");\n  const clientHydrationCode = generateClientHydrationEntry(\n    clientPages,\n    clientLayouts,\n    clientRouteSlots,\n    root,\n    srcDir,\n    adapterOwnsDocsRuntime ? false : isFarmDocsSearchEnabled(config.docs),\n    adapterOwnsDocsRuntime ? undefined : resolveFarmDocsSearchClientModule(root),\n    config.docs?.enabled ? config.docs.entry : undefined,\n    adapterOwnsDocsRuntime ? config.docs.adapter?.react : undefined,\n    config.i18n,\n    config.plugins,\n    config.renderer,\n    config.publicRuntimeConfig,\n    config.trailingSlash,\n    getIntegrationProviders(config.integrations),\n    config.basePath,\n    generateClientCachePersistenceCode(resolveFarmClientCacheAdapterEntry(root, config.cache)),\n  );\n\n  // Write the client entry to a temporary file\n  await fs.writeFile(clientEntryPath, clientHydrationCode);\n\n  // Tailwind support:\n  // - If project has explicit PostCSS config, respect it.\n  // - Otherwise enable built-in @tailwindcss/vite (out of the box).\n  const hasScopedPostcssConfig = hasProjectPostcssConfig(root);\n  let postcssSearchPath: string | undefined;\n  let tailwindVitePlugin: any = undefined;\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, root, {\n    ssr: false,\n  });\n  if (hasScopedPostcssConfig) {\n    logger.info(\"📦 Using project PostCSS/Tailwind configuration\");\n  } else {\n    const postcssConfigPath = path.join(clientEntryDir, \"postcss.config.cjs\");\n    await fs.writeFile(postcssConfigPath, \"module.exports = { plugins: [] };\\n\");\n    postcssSearchPath = clientEntryDir;\n    try {\n      const tailwindVite = (await import(\"@tailwindcss/vite\")).default;\n      tailwindVitePlugin = adaptTailwindVitePlugin(tailwindVite(), productionVite.builder);\n      logger.info(\"📦 Enabled built-in Tailwind support (@tailwindcss/vite)\");\n    } catch (error) {\n      logger.warn(\n        `Tailwind plugin auto-enable failed; continuing without it: ${(error as Error).message}`,\n      );\n    }\n  }\n\n  try {\n    await viteBuild({\n      root,\n      // Vite otherwise falls back to <root>/public, silently dropping every\n      // asset in a custom config.publicDir from the production client output.\n      publicDir: config.publicDir,\n      esbuild: {\n        jsxDev: false,\n      },\n      build: {\n        // Preserve Farm's Vite 5 browser baseline when the production builder\n        // uses Vite 8, whose default target only covers newer browsers.\n        target: FARM_CLIENT_BUILD_TARGET,\n        outDir: outputDir,\n        emptyOutDir: true,\n        assetsInlineLimit: 0,\n        cssCodeSplit: false, // Bundle all CSS into one file\n        rollupOptions: {\n          input: {\n            \"farm-client\": clientEntryPath,\n          },\n          output: {\n            entryFileNames: \"[name]-h[hash].js\",\n            chunkFileNames: \"chunks/[name]-h[hash].js\",\n            hashCharacters: \"hex\",\n            // Use predictable name for CSS so we can reference it in SSR HTML\n            assetFileNames: (assetInfo) => {\n              if (assetInfo.name?.endsWith(\".css\")) {\n                return \"farm-client.css\";\n              }\n              return \"assets/[name]-h[hash][extname]\";\n            },\n          },\n          // Externalize Node.js built-ins and server-side modules for client build\n          external: (id) => {\n            // Externalize Node.js built-ins\n            if (\n              id.startsWith(\"node:\") ||\n              [\n                \"path\",\n                \"url\",\n                \"fs\",\n                \"fs/promises\",\n                \"os\",\n                \"crypto\",\n                \"http\",\n                \"https\",\n                \"net\",\n                \"stream\",\n                \"util\",\n                \"events\",\n                \"child_process\",\n                \"module\",\n                \"tty\",\n                \"dns\",\n              ].includes(id)\n            ) {\n              return true;\n            }\n            // Externalize native modules that can't be bundled for browser\n            if (id === \"fsevents\" || id.includes(\"fsevents\") || id.endsWith(\".node\")) {\n              return true;\n            }\n            return false;\n          },\n        },\n      },\n      plugins: [\n        createFarmThemeCssPlugin(config.theme, config.basePath),\n        ...(tailwindVitePlugin ? [tailwindVitePlugin] : []),\n        ...(rendererVitePlugins as any[]),\n        ...(config.vite.plugins || []),\n        farmServerOnlyEntriesPlugin(),\n        // Plugin to redirect @farm.js/core imports to client-only exports\n        {\n          name: \"farm-client-only-imports\",\n          enforce: \"pre\" as const,\n          resolveId(id) {\n            // Redirect @farm.js/core to just export client-safe parts\n            // Don't redirect @farm.js/core/client - that's already client-safe\n            if (id === \"@farm.js/core\") {\n              return { id: \"\\0farm-client-exports\", external: false };\n            }\n            if (id === \"@farm.js/core/i18n/server\") {\n              return { id: \"\\0farm-i18n-client-bridge\", external: false };\n            }\n            // Block server-only imports completely\n            if (\n              id === \"@farm.js/core/server\" ||\n              id === \"@farm.js/core/api\" ||\n              id === \"@farm.js/core/middleware\" ||\n              id === \"@farm.js/core/headers\" ||\n              id === \"@farm.js/core/config\" ||\n              id.includes(\"@farm.js/core/middleware\") ||\n              id.includes(\"@farm.js/core/query/server\")\n            ) {\n              return { id: \"\\0empty-module\", external: false };\n            }\n            // Block API route imports (they come from type-only imports in api.generated.ts)\n            if (id.includes(\"/api/\") && id.includes(\"/route\")) {\n              return { id: \"\\0empty-api-route\", external: false };\n            }\n            // Block problematic node modules\n            if (\n              id === \"fsevents\" ||\n              id.includes(\"fsevents\") ||\n              id.endsWith(\".node\") ||\n              id === \"nitro\" ||\n              id === \"vite\" ||\n              id === \"vite-rolldown\" ||\n              id === \"esbuild\" ||\n              id === \"rollup\" ||\n              id.startsWith(\"nitro/\") ||\n              id.includes(\"node-pre-gyp\") ||\n              id.includes(\"nf3\")\n            ) {\n              return { id: \"\\0empty-module\", external: false };\n            }\n            return null;\n          },\n          load(id) {\n            if (id === \"\\0empty-module\") {\n              return \"const emptyMiddlewareStore = new Map(); export default {}; export const getMiddlewareContext = () => emptyMiddlewareStore; export const getMiddlewareData = () => emptyMiddlewareStore; export const getMiddlewareValue = () => undefined; export const middleware = () => ({});\";\n            }\n            if (id === \"\\0empty-api-route\") {\n              // Stub for API routes - only used in type context, provide empty exports\n              return \"export const GET = () => {}; export const HEAD = () => {}; export const QUERY = () => {}; export const POST = () => {}; export const PUT = () => {}; export const DELETE = () => {}; export const PATCH = () => {}; export const OPTIONS = () => {}; export default {};\";\n            }\n            if (id === \"\\0farm-i18n-client-bridge\") {\n              return 'export { createTranslator, format, getLocale, getLocaleSource, t } from \"@farm.js/core/i18n/client\";';\n            }\n            if (id === \"\\0farm-client-exports\") {\n              // Only export client-safe parts (no type exports - they're erased at compile time)\n              return [\n                \"// Farm.js Client Exports - Safe for browser bundling\",\n                'export { Link } from \"@farm.js/core/client\";',\n                'export { useRouter } from \"@farm.js/core/client\";',\n                'export { usePathname, useSearchParams } from \"@farm.js/core/navigation\";',\n                // A page that hydrates ships to the browser with its notFound()/redirect() calls.\n                'export { getFarmRedirectError, isFarmNotFoundError, isFarmRedirectError, notFound, permanentRedirect, redirect } from \"@farm.js/core/navigation\";',\n                'export { createAPIClient } from \"@farm.js/core/client\";',\n                'export { localFont, remoteFont } from \"@farm.js/core/font\";',\n              ].join(\"\\n\");\n            }\n            return null;\n          },\n        },\n        farmPlugin({ ...config, isolatedClientBoundaryModules }, pluginManager),\n        farmEnvironmentFunctionsPlugin(),\n      ],\n      mode: \"production\",\n      css: postcssSearchPath\n        ? {\n            postcss: postcssSearchPath,\n          }\n        : undefined,\n      // Ensure React is bundled for client\n      resolve: {\n        alias: createFarmSourceAlias(root, config.srcDir),\n        dedupe: [...(config.renderer.dedupe || [])],\n      },\n      // Optimize dependencies - exclude server-side code from client bundle\n      optimizeDeps: {\n        exclude: [\n          \"@farm.js/core/server\",\n          \"@farm.js/core/api\",\n          \"@farm.js/core/middleware\",\n          \"@farm.js/core/headers\",\n        ],\n      },\n    });\n    await mergeBuiltFontCss(outputDir);\n    await validateClientBuildOutput(root, srcDir, outputDir);\n  } finally {\n    // Clean up temporary entry file\n    try {\n      await fs.rm(clientEntryDir, { recursive: true, force: true });\n    } catch {\n      // Ignore cleanup errors\n    }\n  }\n}\n\n/**\n * Generate client hydration entry that imports and hydrates client components\n */\n/**\n * The X-Farm-Markdown-Source header is a diagnostic, not a filesystem\n * disclosure: production output must never bake the build machine's absolute\n * paths into every markdown response. Bake the project-relative path with\n * POSIX separators; a path outside the root falls back to its basename.\n */\nexport function toBakedMarkdownSourcePath(root: string, filePath: string | undefined): string {\n  if (!filePath) return \"\";\n  if (!path.isAbsolute(filePath)) return filePath.split(path.sep).join(\"/\");\n  const relative = path.relative(root, filePath);\n  if (!relative || relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n    return path.basename(filePath);\n  }\n  return relative.split(path.sep).join(\"/\");\n}\n\nexport function generateUniversalRouterStateRuntime(): string {\n  return `\nconst FARM_PAGE_STATE_KEY = \"__farmPageState\";\nconst FARM_HISTORY_INDEX_KEY = \"__farmHistoryIndex\";\nconst IDLE_NAVIGATION_STATE = {\n  state: \"idle\",\n  pending: false,\n  from: null,\n  to: null,\n  action: null,\n  startedAt: null,\n};\n\nfunction createNavigationLocation(url) {\n  return {\n    href: url.href,\n    pathname: url.pathname,\n    search: url.search,\n    hash: url.hash,\n  };\n}\n\nfunction scrollElementStorageKey(pathname, key) {\n  return \"farm-scroll-\" + pathname + \":\" + key;\n}\n\nfunction createHistoryState(path, pageState, currentState) {\n  const base = currentState && typeof currentState === \"object\" ? { ...currentState } : {};\n  return {\n    ...base,\n    path,\n    [FARM_PAGE_STATE_KEY]: pageState,\n  };\n}\n\nasync function fetchFarmNavigationDocument(url, headers, recover = true, signal) {\n  const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n  const response = await fetch(url, {\n    headers: createFarmDeploymentRequestHeaders(deploymentId, headers),\n    signal,\n    redirect: \"manual\",\n  });\n  // Let a document navigation follow redirects, including cross-origin chains\n  // and fragment inheritance. Never cache/swap their HTML under the source URL.\n  if (response.type === \"opaqueredirect\" || response.redirected) {\n    const error = new Error(\"Farm navigation requires a document redirect\");\n    error.name = \"FarmNavigationRedirect\";\n    throw error;\n  }\n  if (isFarmDeploymentMismatchResponse(response, deploymentId)) {\n    const error = createFarmDeploymentMismatchError(response, deploymentId || \"unknown\");\n    window.dispatchEvent(new CustomEvent(\"farm:deployment-mismatch\", { detail: error }));\n    if (recover) window.location.assign(url);\n    throw error;\n  }\n  // Only an HTML page can be swapped in. A feed, JSON, file, or other API\n  // response belongs to the browser, so it takes the redirect path: a document\n  // navigation that is never cached or reported as a failed navigation.\n  const contentType = (response.headers.get(\"Content-Type\") || \"\").toLowerCase();\n  if (response.ok && !contentType.includes(\"text/html\")) {\n    response.body?.cancel().catch(() => {});\n    const error = new Error(\"Farm navigation requires a document load\");\n    error.name = \"FarmNavigationRedirect\";\n    throw error;\n  }\n  return response;\n}\n\nfunction clearFarmPrefetchCacheOnDeploymentMismatch(router, error) {\n  if (error?.name === \"FarmDeploymentMismatchError\") {\n    router.clearCache();\n  }\n}\n\nfunction readHistoryIndex(state) {\n  if (!state || typeof state !== \"object\") return null;\n  const value = state[FARM_HISTORY_INDEX_KEY];\n  return Number.isSafeInteger(value) ? value : null;\n}\n\nfunction hasAbsoluteNavigationHref(href) {\n  return /^[a-zA-Z][a-zA-Z\\\\d+.-]*:/.test(href) || href.startsWith(\"//\");\n}\n`.trim();\n}\n\n/**\n * Path matcher emitted into the production runtime. Extracted so tests can\n * assert the emitted source decodes segments through the guarded helper;\n * a bare decodeURIComponent here throws URIError on malformed\n * percent-encoding out of route matching in deployed apps (#502).\n */\nexport function generateRuntimePathMatcherSource(): string {\n  return `\nfunction normalizeRuntimePath(pathname) {\n  if (!pathname || pathname === \"/\") return \"/\";\n  return pathname.endsWith(\"/\") ? pathname.replace(/\\\\/+$/, \"\") : pathname;\n}\n\nfunction splitRuntimePath(pathname) {\n  return normalizeRuntimePath(pathname).split(\"/\").filter(Boolean);\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    // Request paths are not guaranteed to be validly percent-encoded; a\n    // malformed segment must not throw out of route matching.\n    return segment;\n  }\n}\n\nconst farmCatchAllParamSegments = Symbol(\"farm.catch-all-param-segments\");\n\nfunction prepareRuntimePageSegments(segments) {\n  const prepared = [];\n  for (const segment of segments) {\n    // Only fixed-length patterns use this path. Leave all wildcard/catch-all\n    // forms (including ambiguous spellings) to the complete backtracking matcher.\n    if (segment.includes(\"*\") || segment.startsWith(\"[...\") || segment.startsWith(\"[[...\")) {\n      return null;\n    }\n    const dynamic = segment.match(/^\\\\[(.+)\\\\]$/) || segment.match(/^:([^/]+)$/);\n    prepared.push({ literal: segment, param: dynamic ? dynamic[1] : null });\n  }\n  return prepared;\n}\n\nfunction matchPreparedRuntimePageSegments(prepared, pathnameSegments) {\n  if (prepared.length !== pathnameSegments.length) return null;\n  const params = {};\n  for (let i = 0; i < prepared.length; i++) {\n    const segment = prepared[i];\n    if (segment.param !== null) params[segment.param] = pathnameSegments[i];\n    else if (segment.literal !== pathnameSegments[i]) return null;\n  }\n  Object.defineProperty(params, farmCatchAllParamSegments, { value: {} });\n  return params;\n}\n\nfunction matchRuntimePathPattern(pattern, pathname) {\n  const patternSegments = splitRuntimePath(pattern);\n  const pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n  return matchRuntimePathSegments(patternSegments, pathnameSegments);\n}\n\nfunction matchRuntimePathSegments(patternSegments, pathnameSegments) {\n  const failedStates = new Set();\n\n  function matchFrom(patternIndex, pathIndex, params, catchAllParamSegments) {\n    const stateKey = patternIndex + \":\" + pathIndex;\n    if (failedStates.has(stateKey)) return null;\n    const matched = matchFromUncached(patternIndex, pathIndex, params, catchAllParamSegments);\n    if (!matched) failedStates.add(stateKey);\n    return matched;\n  }\n\n  function matchFromUncached(patternIndex, pathIndex, params, catchAllParamSegments) {\n    while (patternIndex < patternSegments.length) {\n      const segment = patternSegments[patternIndex];\n      const optionalCatchAll = segment.match(/^\\\\[\\\\[\\\\.\\\\.\\\\.(.+)\\\\]\\\\]$/);\n      const catchAll = segment.match(/^\\\\[\\\\.\\\\.\\\\.(.+)\\\\]$/);\n      const dynamic = segment.match(/^\\\\[(.+)\\\\]$/);\n      const namedCatchAll = segment.match(/^:([^/]+)\\\\*$/);\n      const namedDynamic = segment.match(/^:([^/]+)$/);\n      const starCatchAll = segment.match(/^\\\\*([^?]+)(\\\\?)?$/);\n      const wildcard = segment === \"*\";\n\n      if (optionalCatchAll || catchAll || namedCatchAll || starCatchAll || wildcard) {\n        const name = wildcard\n          ? \"wildcard\"\n          : (optionalCatchAll || catchAll || namedCatchAll || starCatchAll)[1];\n        const required = !!(catchAll || (starCatchAll && !starCatchAll[2]));\n\n        if (patternIndex === patternSegments.length - 1) {\n          const remainingSegments = pathnameSegments.slice(pathIndex);\n          const remaining = remainingSegments.join(\"/\");\n          if (!remaining && required) return null;\n          params[name] = remaining;\n          catchAllParamSegments[name] = remainingSegments;\n          pathIndex = pathnameSegments.length;\n          patternIndex += 1;\n          continue;\n        }\n\n        const maxConsume = pathnameSegments.length - pathIndex;\n        const minConsume = required ? 1 : 0;\n        for (let consume = maxConsume; consume >= minConsume; consume--) {\n          const trialParams = Object.assign({}, params);\n          const trialCatchAll = Object.assign({}, catchAllParamSegments);\n          // Downstream matching only needs path indexes. Defer constructing the\n          // catch-all value until a split actually matches; otherwise a long\n          // failing path repeatedly slices, decodes, and joins the same prefix.\n          trialParams[name] = \"\";\n          const matched = matchFrom(\n            patternIndex + 1,\n            pathIndex + consume,\n            trialParams,\n            trialCatchAll,\n          );\n          if (matched) {\n            const consumedSegments = pathnameSegments.slice(pathIndex, pathIndex + consume);\n            matched[name] = consumedSegments.join(\"/\");\n            matched[farmCatchAllParamSegments][name] = consumedSegments;\n            return matched;\n          }\n        }\n        return null;\n      }\n\n      const pathnameSegment = pathnameSegments[pathIndex];\n      if (pathnameSegment === undefined) return null;\n\n      if (dynamic || namedDynamic) {\n        // Segments were already decoded once at entry; decoding again here\n        // turns a literal \"%2541BC\" request into \"ABC\" and diverges from dev.\n        params[(dynamic || namedDynamic)[1]] = pathnameSegment;\n        pathIndex += 1;\n        patternIndex += 1;\n        continue;\n      }\n\n      if (segment !== pathnameSegment) return null;\n      pathIndex += 1;\n      patternIndex += 1;\n    }\n\n    if (pathIndex !== pathnameSegments.length) return null;\n    Object.defineProperty(params, farmCatchAllParamSegments, {\n      value: catchAllParamSegments,\n    });\n    return params;\n  }\n\n  return matchFrom(0, 0, {}, {});\n}\n`.trim();\n}\n\nexport function generateRedirectInterpolationSource(): string {\n  // Interpolates redirect/rewrite destinations from the params produced by\n  // matchRuntimePathPattern. Must stay in parity with the development path in\n  // packages/farm/src/plugins/route-pattern.ts: named captures (:name, [name],\n  // catch-alls), a positional * for the wildcard param, and numbered captures\n  // ($1-based, in pattern order). Depends on farmCatchAllParamSegments from\n  // generateRuntimePathMatcherSource(), so emit that source alongside this one.\n  return `\nfunction encodeRuntimePathSegment(value) {\n  return encodeURIComponent(String(value)).replace(\n    /[!'()*]/g,\n    function(character) {\n      return \"%\" + character.charCodeAt(0).toString(16).toUpperCase();\n    },\n  );\n}\n\nfunction interpolateRedirectDestination(destination, params) {\n  let result = destination;\n  const catchAllParamSegments = params[farmCatchAllParamSegments] || {};\n  const orderedCaptures = [];\n  for (const [key, value] of Object.entries(params)) {\n    const segments = catchAllParamSegments[key];\n    const encodedValue = Array.isArray(segments)\n      ? segments.map(encodeRuntimePathSegment).join(\"/\")\n      : encodeRuntimePathSegment(value);\n    orderedCaptures.push(encodedValue);\n    result = result.split(\"[[...\" + key + \"]]\").join(encodedValue);\n    result = result.split(\"[...\" + key + \"]\").join(encodedValue);\n    result = result.split(\"[\" + key + \"]\").join(encodedValue);\n    result = result.split(\":\" + key + \"*\").join(encodedValue);\n    result = result.split(\":\" + key).join(encodedValue);\n    if (key === \"wildcard\") result = result.split(\"*\").join(encodedValue);\n  }\n  // Numbered captures resolve after the named substitutions. Encoded values\n  // never contain \"$\", so this cannot rewrite an already-injected value. An\n  // out-of-range index resolves to \"\", matching the development path.\n  result = result.replace(/\\\\$(\\\\d+)/g, function(_whole, group) {\n    const captured = orderedCaptures[Number(group) - 1];\n    return captured === undefined ? \"\" : captured;\n  });\n  return result;\n}\n`.trim();\n}\n\nexport function generateUniversalRouterStateProperties(): string {\n  return `\n  blockers: new Set(),\n  unloadBlockers: new Map(),\n  navigationListeners: new Set(),\n  navigationState: IDLE_NAVIGATION_STATE,\n  navigationSequence: 0,\n  activeNavigation: null,\n  pendingPrefetches: new Map(),\n  prefetchGeneration: 0,\n  prefetchObserver: null,\n  observedPrefetchLinks: new Map(),\n  viewportPrefetchQueue: [],\n  viewportPrefetchTasksByHref: new Map(),\n  viewportPrefetchTasksByElement: new Map(),\n  activeViewportPrefetches: 0,\n  scrollElements: new Map(),\n  currentPath: window.location.pathname + window.location.search,\n  currentHistoryIndex: null,\n  currentHistoryState: null,\n\n  getPrefetchObserver: function(rootMargin) {\n    if (this.prefetchObserver) return this.prefetchObserver;\n    const router = this;\n    this.prefetchObserver = new IntersectionObserver(function(entries) {\n      for (const entry of entries) {\n        if (!entry.isIntersecting) continue;\n        const element = entry.target;\n        const href = router.observedPrefetchLinks.get(element);\n        if (!href) continue;\n        router.prefetchObserver.unobserve(element);\n        router.observedPrefetchLinks.delete(element);\n        router.enqueueViewportPrefetch(element, href);\n      }\n    }, { rootMargin: rootMargin });\n    return this.prefetchObserver;\n  },\n\n  enqueueViewportPrefetch: function(element, href) {\n    let task = this.viewportPrefetchTasksByHref.get(href);\n    if (!task) {\n      task = { href: href, elements: new Set(), cancelled: false, started: false };\n      this.viewportPrefetchTasksByHref.set(href, task);\n      this.viewportPrefetchQueue.push(task);\n    }\n    task.elements.add(element);\n    this.viewportPrefetchTasksByElement.set(element, task);\n    this.drainViewportPrefetchQueue();\n  },\n\n  cancelViewportPrefetch: function(element) {\n    const task = this.viewportPrefetchTasksByElement.get(element);\n    if (!task) return;\n    this.viewportPrefetchTasksByElement.delete(element);\n    task.elements.delete(element);\n    if (task.elements.size > 0) return;\n    if (task.started) return;\n    task.cancelled = true;\n    if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n      this.viewportPrefetchTasksByHref.delete(task.href);\n    }\n  },\n\n  drainViewportPrefetchQueue: function() {\n    while (this.activeViewportPrefetches < 4 && this.viewportPrefetchQueue.length > 0) {\n      const task = this.viewportPrefetchQueue.shift();\n      if (task.cancelled || task.elements.size === 0) {\n        if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n          this.viewportPrefetchTasksByHref.delete(task.href);\n        }\n        continue;\n      }\n\n      task.started = true;\n      this.activeViewportPrefetches += 1;\n      let prefetchResult;\n      try {\n        prefetchResult = this.prefetch(task.href);\n      } catch {\n        prefetchResult = undefined;\n      }\n      Promise.resolve(prefetchResult)\n        .catch(() => undefined)\n        .finally(() => {\n          if (this.viewportPrefetchTasksByHref.get(task.href) === task) {\n            this.viewportPrefetchTasksByHref.delete(task.href);\n          }\n          for (const element of task.elements) {\n            if (this.viewportPrefetchTasksByElement.get(element) === task) {\n              this.viewportPrefetchTasksByElement.delete(element);\n            }\n          }\n          this.activeViewportPrefetches -= 1;\n          this.drainViewportPrefetchQueue();\n        });\n    }\n  },\n\n  initializeHistory: function() {\n    const existingIndex = readHistoryIndex(window.history.state);\n    if (existingIndex != null) {\n      this.currentHistoryIndex = existingIndex;\n      this.currentHistoryState = window.history.state;\n      return;\n    }\n    try {\n      const initialState = {\n        ...(window.history.state && typeof window.history.state === \"object\"\n          ? window.history.state\n          : {}),\n        [FARM_HISTORY_INDEX_KEY]: 0,\n      };\n      window.history.replaceState(initialState, \"\", window.location.href);\n      this.currentHistoryIndex = 0;\n      this.currentHistoryState = initialState;\n    } catch {\n      this.currentHistoryIndex = null;\n      this.currentHistoryState = null;\n    }\n  },\n\n  getNavigationState: function() {\n    return this.navigationState;\n  },\n\n  subscribeNavigation: function(listener) {\n    this.navigationListeners.add(listener);\n    listener(this.navigationState);\n    return () => this.navigationListeners.delete(listener);\n  },\n\n  addBlocker: function(blocker, shouldBlockUnload) {\n    this.blockers.add(blocker);\n    this.unloadBlockers.set(blocker, shouldBlockUnload || (() => {\n      const result = blocker({ from: this.currentPath, to: this.currentPath, action: \"replace\" });\n      if (result && typeof result.then === \"function\") {\n        result.catch(() => undefined);\n        return true;\n      }\n      return result === true;\n    }));\n    return () => {\n      this.blockers.delete(blocker);\n      this.unloadBlockers.delete(blocker);\n    };\n  },\n\n  shouldBlockNavigation: async function(context) {\n    for (const blocker of this.blockers) {\n      if (await blocker(context)) return true;\n    }\n    return false;\n  },\n\n  shouldBlockUnload: function() {\n    for (const blocker of this.blockers) {\n      try {\n        if (this.unloadBlockers.get(blocker)?.()) return true;\n      } catch {\n        return true;\n      }\n    }\n    return false;\n  },\n\n  handlePopState: function(event) {\n    if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n    return this.navigate(window.location.href, {\n      action: \"pop\",\n      scroll: false,\n      popState: event.state,\n    });\n  },\n\n  revertBlockedPopState: function(from) {\n    try {\n      const previousState = this.currentHistoryState;\n      const pageState = previousState && typeof previousState === \"object\"\n        ? previousState[FARM_PAGE_STATE_KEY]\n        : undefined;\n      const restoredState = createHistoryState(from, pageState, previousState);\n      if (this.currentHistoryIndex != null) {\n        restoredState[FARM_HISTORY_INDEX_KEY] = this.currentHistoryIndex;\n      }\n      window.history.pushState(restoredState, \"\", from);\n      this.currentHistoryState = restoredState;\n    } catch {}\n  },\n\n  startNavigation: function(from, to, action) {\n    this.activeNavigation?.controller.abort(\"superseded\");\n    const navigation = {\n      id: ++this.navigationSequence,\n      controller: new AbortController(),\n      clientNavigation: null,\n    };\n    this.activeNavigation = navigation;\n    this.setNavigationState({\n      state: \"loading\",\n      pending: true,\n      from,\n      to: createNavigationLocation(to),\n      action,\n      startedAt: Date.now(),\n    });\n    return navigation;\n  },\n\n  isCurrentNavigation: function(navigation, clientNavigation) {\n    return this.activeNavigation?.id === navigation.id &&\n      !navigation.controller.signal.aborted &&\n      !clientNavigation?.signal.aborted;\n  },\n\n  finishNavigation: function(navigation) {\n    if (this.activeNavigation?.id !== navigation.id) return;\n    this.activeNavigation = null;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  },\n\n  cancelActiveNavigation: function() {\n    if (!this.activeNavigation) return;\n    farmClientRuntime.cancelNavigation(\n      this.activeNavigation.clientNavigation || undefined,\n      \"superseded\",\n    );\n    this.activeNavigation.controller.abort(\"superseded\");\n    this.activeNavigation = null;\n    this.setNavigationState(IDLE_NAVIGATION_STATE);\n  },\n\n  clearPrefetchedPath: function(url) {\n    const interceptionPrefix = url + \"\\\\nintercept:\";\n    for (const key of this.prefetchCache.keys()) {\n      if (key === url || key.startsWith(interceptionPrefix)) {\n        this.prefetchCache.delete(key);\n      }\n    }\n    for (const [key, pending] of this.pendingPrefetches) {\n      if (key === url || key.startsWith(interceptionPrefix)) {\n        pending.valid = false;\n        this.pendingPrefetches.delete(key);\n      }\n    }\n  },\n\n  clearCache: function() {\n    this.prefetchGeneration++;\n    this.prefetchCache.clear();\n    for (const pending of this.pendingPrefetches.values()) pending.valid = false;\n    this.pendingPrefetches.clear();\n  },\n\n  fetchPrefetchedDocument: async function(url, interceptFrom, fresh, recover, signal, cacheResult = true) {\n    signal?.throwIfAborted();\n    const cacheKey = interceptFrom ? url + \"\\\\nintercept:\" + interceptFrom : url;\n    if (fresh) this.clearPrefetchedPath(url);\n    const cached = fresh ? undefined : this.readFreshPrefetch(cacheKey);\n    if (cached !== undefined) return cached;\n    const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n    const pending = this.pendingPrefetches.get(cacheKey);\n    if (!fresh && pending && pending.deploymentId === deploymentId) {\n      const cancellation = createClientCancellation(signal);\n      try {\n        const html = await cancellation.run(() => pending.promise);\n        if (pending.valid && deploymentId === window.__FARM_DEPLOYMENT_ID__) return html;\n      } catch (error) {\n        if (signal?.aborted || !recover) throw error;\n        if (error?.name === \"FarmNavigationRedirect\") throw error;\n        if (error?.name === \"FarmDeploymentMismatchError\") {\n          window.location.assign(url);\n          throw error;\n        }\n        // A speculative failure must not poison a real navigation: retry it.\n      } finally {\n        cancellation.dispose();\n      }\n    }\n\n    const generation = this.prefetchGeneration;\n    // Only speculative requests have shared ownership. Ordinary navigations\n    // keep their own abort signal and cannot cancel another caller's work.\n    const record = recover ? null : { valid: true, deploymentId, promise: null };\n    const request = async () => {\n      const response = await fetchFarmNavigationDocument(url, {\n        \"Accept\": \"text/html\",\n        ...(interceptFrom ? { \"X-Farm-Intercept-From\": interceptFrom } : {}),\n      }, recover, signal);\n      if (!response.ok) throw new Error(\"Failed to fetch page\");\n      const html = await response.text();\n      if (cacheResult && !signal?.aborted && generation === this.prefetchGeneration &&\n          deploymentId === window.__FARM_DEPLOYMENT_ID__ && (!record || record.valid)) {\n        this.storePrefetchedHtml(cacheKey, html);\n      }\n      return html;\n    };\n    if (!record) return request();\n    record.promise = request().finally(() => {\n      if (this.pendingPrefetches.get(cacheKey) === record) this.pendingPrefetches.delete(cacheKey);\n    });\n    this.pendingPrefetches.set(cacheKey, record);\n    return record.promise;\n  },\n\n  // Cached documents go stale the moment a mutation lands, and a long-lived\n  // tab prefetching on hover accumulates full HTML forever - so entries have\n  // the same 30 second lifetime the development router uses, and the cache\n  // keeps at most 25 documents, evicting the oldest first.\n  readFreshPrefetch: function(cacheKey) {\n    const entry = this.prefetchCache.get(cacheKey);\n    if (!entry) return undefined;\n    if (Date.now() - entry.at > 30000) {\n      this.prefetchCache.delete(cacheKey);\n      return undefined;\n    }\n    return entry.html;\n  },\n  storePrefetchedHtml: function(cacheKey, html) {\n    this.prefetchCache.delete(cacheKey);\n    this.prefetchCache.set(cacheKey, { html: html, at: Date.now() });\n    while (this.prefetchCache.size > 25) {\n      const oldest = this.prefetchCache.keys().next().value;\n      if (oldest === undefined) break;\n      this.prefetchCache.delete(oldest);\n    }\n  },\n\n  setNavigationState: function(state) {\n    this.navigationState = state;\n    for (const listener of this.navigationListeners) listener(state);\n  },\n\n  pushState: function(state, href) {\n    this.writePageState(\"push\", state, href);\n  },\n\n  replaceState: function(state, href) {\n    this.writePageState(\"replace\", state, href);\n  },\n\n  writePageState: function(action, state, href) {\n    const url = new URL(href || window.location.href, window.location.href);\n    this.writeHistoryEntry(action, url.pathname + url.search + url.hash, state, url, \"page-state\");\n  },\n\n  writeURLSearch: function(action, href) {\n    const url = new URL(href || window.location.href, window.location.href);\n    const currentState = window.history.state;\n    const pageState = currentState && typeof currentState === \"object\"\n      ? currentState[FARM_PAGE_STATE_KEY]\n      : undefined;\n    this.writeHistoryEntry(\n      action,\n      url.pathname + url.search + url.hash,\n      pageState,\n      url,\n      \"url-search\",\n      false,\n    );\n    this.currentPath = url.pathname + url.search;\n  },\n\n  writeHistoryEntry: function(action, path, pageState, url, changeKind = \"url-search\", notify = true) {\n    if (action === \"pop\") return;\n    const nextState = createHistoryState(path, pageState, window.history.state);\n    const nextIndex = this.currentHistoryIndex == null\n      ? null\n      : action === \"replace\"\n        ? this.currentHistoryIndex\n        : this.currentHistoryIndex + 1;\n    if (nextIndex != null) nextState[FARM_HISTORY_INDEX_KEY] = nextIndex;\n    if (action === \"replace\") window.history.replaceState(nextState, \"\", url);\n    else window.history.pushState(nextState, \"\", url);\n    this.currentHistoryIndex = nextIndex;\n    this.currentHistoryState = nextState;\n    // Announce programmatic history writes without synthesizing popstate,\n    // which the router reserves for real back/forward navigation.\n    if (notify) {\n      window.dispatchEvent(\n        new CustomEvent(\"farm:historychange\", { detail: { kind: changeKind } }),\n      );\n    }\n  },\n\n  registerScrollElement: function(key, element) {\n    this.scrollElements.set(key, element);\n    this.restoreScrollElement(window.location.pathname + window.location.search, key, element);\n    return () => {\n      if (this.scrollElements.get(key) === element) this.scrollElements.delete(key);\n    };\n  },\n\n  saveScrollPosition: function(pathname) {\n    try {\n      sessionStorage.setItem(\n        \"farm-scroll-\" + pathname,\n        JSON.stringify({ x: window.scrollX, y: window.scrollY }),\n      );\n      for (const [key, element] of this.scrollElements) {\n        sessionStorage.setItem(\n          scrollElementStorageKey(pathname, key),\n          JSON.stringify({ x: element.scrollLeft, y: element.scrollTop }),\n        );\n      }\n    } catch {}\n  },\n\n  restoreScrollPosition: function(pathname) {\n    try {\n      const saved = sessionStorage.getItem(\"farm-scroll-\" + pathname);\n      if (saved) {\n        const position = JSON.parse(saved);\n        setTimeout(() => window.scrollTo(position.x, position.y), 0);\n      }\n      for (const [key, element] of this.scrollElements) {\n        this.restoreScrollElement(pathname, key, element);\n      }\n    } catch {}\n  },\n\n  restoreScrollElement: function(pathname, key, element) {\n    try {\n      const saved = sessionStorage.getItem(scrollElementStorageKey(pathname, key));\n      if (!saved) return;\n      const position = JSON.parse(saved);\n      setTimeout(() => {\n        element.scrollLeft = position.x;\n        element.scrollTop = position.y;\n      }, 0);\n    } catch {}\n  },\n\n  runViewTransition: async function(enabled, callback) {\n    const startViewTransition = document.startViewTransition;\n    if (!enabled || typeof startViewTransition !== \"function\") {\n      await callback();\n      return;\n    }\n    const transition = startViewTransition.call(document, () => callback());\n    await transition.finished;\n  },\n`.trim();\n}\n\nfunction generateClientHydrationEntry(\n  clientPages: Array<{\n    pattern: string;\n    modulePath: string;\n    relativePath: string;\n    pageShouldHydrate: boolean;\n    islandStrategy: FarmIslandStrategy;\n    hasIsolatedClientBoundaries: boolean;\n    isolatedBoundaries: IsolatedClientBoundaryReference[];\n  }>,\n  layoutRoutes: Array<{\n    pattern: string;\n    modulePath: string;\n    shouldHydrate: boolean;\n    islandStrategy: FarmIslandStrategy | null;\n    hasIsolatedClientBoundaries: boolean;\n    isolatedBoundaries: IsolatedClientBoundaryReference[];\n  }>,\n  clientRouteSlots: UniversalRouteSlot[],\n  root: string,\n  srcDir: string,\n  docsSearchEnabled: boolean,\n  docsSearchModuleId: string | undefined,\n  docsEntryPath: string | undefined,\n  docsAdapterReact: string | undefined,\n  i18nConfig: ResolvedFarmConfig[\"i18n\"] = {\n    enabled: false,\n    basePath: \"/\",\n    locales: [\"en\"],\n    defaultLocale: \"en\",\n    messages: \"\",\n    routing: \"none\",\n    detection: [],\n    fallbackLocale: \"en\",\n    strict: false,\n    cookie: {\n      name: \"farm_locale\",\n      maxAge: 0,\n      path: \"/\",\n      sameSite: \"lax\",\n      secure: false,\n    },\n    direction: {},\n  },\n  plugins: readonly FarmPlugin[] = [],\n  renderer: FarmRenderer = REACT_RENDERER,\n  publicRuntimeConfig: Record<string, unknown> | undefined = undefined,\n  trailingSlash = false,\n  integrationProviders: ReturnType<typeof getIntegrationProviders> = [],\n  basePath = \"/\",\n  clientCachePersistence: ClientCachePersistenceEntryCode = { imports: \"\", init: \"\" },\n): string {\n  const toImportPath = (targetPath: string) => targetPath.replace(/\\\\/g, \"/\");\n  const clientPluginEntry: FarmClientPluginEntryCode = generateFarmClientPluginEntryCode(\n    plugins,\n    root,\n    srcDir,\n    publicRuntimeConfig,\n  );\n  const rendererClientImports = isReactRenderer(renderer)\n    ? `import React from \"react\";\\nimport { createRoot, hydrateRoot } from \"react-dom/client\";`\n    : `import React, { createRoot, hydrateRoot } from ${JSON.stringify(renderer.client)};`;\n  const providerClientCode = generateFarmIntegrationProviderClientCode(\n    integrationProviders,\n    root,\n    renderer.componentExtensions ?? [],\n  );\n\n  // Import global CSS (the Tailwind entry) only when the app ships one; an\n  // unconditional import of a missing file fails the client build with\n  // UNRESOLVED_IMPORT. Output validation already treats a missing globals.css\n  // as an intentionally style-free application.\n  const globalsCssPath = path.join(root, srcDir, \"app\", \"globals.css\");\n  const cssImport = existsSync(globalsCssPath)\n    ? `import ${JSON.stringify(toImportPath(globalsCssPath))};`\n    : \"\";\n\n  // Import layouts for wrapping client components\n  const layoutImportStatements: string[] = [];\n  const layoutRegistrations: string[] = [];\n\n  layoutRoutes.forEach((layout, index) => {\n    const relativePath = toImportPath(layout.modulePath);\n    if (!layout.hasIsolatedClientBoundaries) {\n      layoutImportStatements.push(`import Layout${index} from \"${relativePath}\";`);\n    }\n    layoutRegistrations.push(\n      `  { pattern: ${JSON.stringify(layout.pattern)}, Component: ${layout.hasIsolatedClientBoundaries ? \"null\" : `Layout${index}`}, shouldHydrate: ${JSON.stringify(layout.shouldHydrate)}, islandStrategy: ${JSON.stringify(layout.islandStrategy)} }`,\n    );\n  });\n\n  const layoutImports = layoutImportStatements.join(\"\\n\");\n  const i18nRoutingConfig = {\n    locales: i18nConfig.locales,\n    defaultLocale: i18nConfig.defaultLocale,\n    routing: i18nConfig.routing,\n  };\n  const i18nClientRuntime = i18nConfig.enabled\n    ? `\nimport { stripFarmLocaleFromPathname } from \"@farm.js/core/i18n\";\nimport { _setFarmI18nClientSnapshot } from \"@farm.js/core/i18n/client\";\n\nconst farmI18nConfig = ${JSON.stringify(i18nRoutingConfig)};\nif (window.__FARM_I18N__) {\n  _setFarmI18nClientSnapshot(window.__FARM_I18N__);\n}\n\nfunction getFarmRoutePathname(pathname) {\n  return stripFarmLocaleFromPathname(stripFarmBasePath(pathname), farmI18nConfig);\n}\n\nfunction isFarmLocaleDocumentChange(doc) {\n  const currentLocale = window.__FARM_I18N__?.locale || document.documentElement.lang;\n  const nextLocale = doc.documentElement?.lang;\n  return Boolean(currentLocale && nextLocale && currentLocale !== nextLocale);\n}\n`\n    : `\nfunction getFarmRoutePathname(pathname) {\n  return stripFarmBasePath(pathname);\n}\n\nfunction isFarmLocaleDocumentChange() {\n  return false;\n}\n`;\n  const docsNavigationRuntime = docsEntryPath\n    ? `\nconst farmDocsEntryPath = ${JSON.stringify(docsEntryPath)};\nfunction isFarmDocsPath(pathname) {\n  const routePathname = getFarmRoutePathname(pathname);\n  const normalizedPath = routePathname.length > 1 ? routePathname.replace(/\\\\/+$/, \"\") : routePathname;\n  return normalizedPath === farmDocsEntryPath || normalizedPath.startsWith(farmDocsEntryPath + \"/\");\n}\n`\n    : `\nfunction isFarmDocsPath() {\n  return false;\n}\n`;\n  const docsAdapterRuntime = generateFarmDocsAdapterClientRuntime(docsAdapterReact);\n\n  if (\n    clientPages.length === 0 &&\n    clientRouteSlots.length === 0 &&\n    !providerClientCode.hasProviders\n  ) {\n    // No client pages - just basic runtime with CSS and SPA navigation\n    return `\n// Farm.js Client Runtime (no client components)\n${cssImport}\n${layoutImports}\nimport { createClientCancellation, createClientPluginManager, getHashTargetElement, installChunkErrorRecovery, isFarmExternalNavigationURL, reconcileFarmDocumentHead, setFarmBasePath, setFarmTrailingSlashPreference, stripFarmBasePath } from \"@farm.js/core/internal/client-runtime\";\nimport { createFarmDeploymentMismatchError, createFarmDeploymentRequestHeaders, isFarmDeploymentMismatchResponse } from \"@farm.js/core/deployment\";\n${clientPluginEntry.imports}\n${clientCachePersistence.imports}\n${i18nClientRuntime}\n${docsNavigationRuntime}\n${docsAdapterRuntime}\n${generateFarmDocsSearchClientRuntime(docsSearchEnabled, docsSearchModuleId)}\n\nsetFarmBasePath(${JSON.stringify(basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(trailingSlash)});\ninstallChunkErrorRecovery();\n${clientCachePersistence.init}\nmountFarmDocsSearch();\n\n${generateUniversalRouterStateRuntime()}\n\n// SPA Router for server-rendered pages (HTML swap)\nconst spaRouter = {\n${generateUniversalRouterStateProperties()}\n  prefetchCache: new Map(),\n  \n  navigate: async function(href, options = {}) {\n    const url = new URL(href, window.location.href);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n    if (isFarmDocsPath(url.pathname)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n\n    const action = options.action || (options.replace ? \"replace\" : \"push\");\n    const to = url.pathname + url.search;\n    if (!options.refresh && action !== \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      if (url.hash === window.location.hash) return;\n      const pageState = options.state === undefined\n        ? window.history.state?.[FARM_PAGE_STATE_KEY]\n        : options.state;\n      this.writeHistoryEntry(action, to, pageState, url);\n      if (options.scroll !== false) {\n        if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      }\n      return;\n    }\n    if (action === \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n      return;\n    }\n\n    const from = this.currentPath;\n    if (await this.shouldBlockNavigation({ from, to, action })) {\n      if (action === \"pop\") this.revertBlockedPopState(from);\n      return;\n    }\n    if (action === \"pop\") {\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n    }\n\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n    const navigation = this.startNavigation(from, url, action);\n    let clientNavigation;\n    try {\n      clientNavigation = await farmClientRuntime.beginNavigation({\n        from: action === \"pop\" ? null : window.location.href,\n        to: url,\n        action,\n      });\n      navigation.clientNavigation = clientNavigation;\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      const html = await this.fetchPage(\n        url.pathname + url.search,\n        options.refresh === true,\n        true,\n        navigation.controller.signal,\n      );\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      await farmClientRuntime.markNavigationLoaded(clientNavigation, html);\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      await this.runViewTransition(options.viewTransition, async () => {\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        if (!this.swapContent(html)) {\n          throw new Error(\"Farm could not swap the target document\");\n        }\n        this.writeHistoryEntry(action, url.pathname + url.search, options.state, url);\n        this.currentPath = to;\n        if (options.scroll !== false) {\n          if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n          else window.scrollTo(0, 0);\n        } else {\n          this.restoreScrollPosition(to);\n        }\n      });\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      await farmClientRuntime.resolveNavigation(clientNavigation);\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (error?.name === \"FarmNavigationRedirect\") {\n        this.cancelActiveNavigation();\n        if (action === \"pop\") window.location.reload();\n        else if (action === \"replace\") window.location.replace(url.href);\n        else window.location.assign(url.href);\n        return;\n      }\n      if (clientNavigation) {\n        await farmClientRuntime.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      if (error?.name === \"FarmDeploymentMismatchError\") return;\n      console.error(\"[Farm.js] Navigation error:\", error);\n      if (action === \"pop\") window.location.reload();\n      else window.location.href = href;\n    }\n  },\n\n  refresh: function(options = {}) {\n    return this.navigate(window.location.href, {\n      ...options,\n      action: \"replace\",\n      replace: true,\n      refresh: true,\n      scroll: options.scroll === undefined ? false : options.scroll,\n    });\n  },\n  \n  fetchPage: async function(url, fresh = false, recover = true, signal) {\n    return this.fetchPrefetchedDocument(url, undefined, fresh, recover, signal, !recover);\n  },\n  \n  swapContent: function(html) {\n    const parser = new DOMParser();\n    const doc = parser.parseFromString(html, \"text/html\");\n    if (isFarmLocaleDocumentChange(doc)) return false;\n    if (doc.getElementById(\"nd-docs-layout\")) return false;\n    \n    reconcileFarmDocumentHead(doc);\n    \n    // Swap root content\n    const newRoot = doc.getElementById(\"root\");\n    const currentRoot = document.getElementById(\"root\");\n    if (!newRoot || !currentRoot) return this.swapDocument(doc);\n    currentRoot.innerHTML = newRoot.innerHTML;\n    return true;\n  },\n\n  swapDocument: function(doc) {\n    if (!doc.documentElement || !doc.body) return false;\n\n    Array.from(document.documentElement.attributes).forEach(function(attr) {\n      if (!doc.documentElement.hasAttribute(attr.name)) {\n        document.documentElement.removeAttribute(attr.name);\n      }\n    });\n    Array.from(doc.documentElement.attributes).forEach(function(attr) {\n      document.documentElement.setAttribute(attr.name, attr.value);\n    });\n\n    document.head.innerHTML = doc.head ? doc.head.innerHTML : \"\";\n    document.body.innerHTML = doc.body.innerHTML;\n    delete window.__farmDocsRuntime;\n    delete window.__farmDocsPageActionsRuntime;\n\n    setTimeout(function() {\n      Array.from(document.querySelectorAll(\"script\")).forEach(function(script) {\n        const freshScript = document.createElement(\"script\");\n        Array.from(script.attributes).forEach(function(attr) {\n          freshScript.setAttribute(attr.name, attr.value);\n        });\n        freshScript.textContent = script.textContent || \"\";\n        script.replaceWith(freshScript);\n      });\n    }, 0);\n\n    return true;\n  },\n  prefetch: function(href) {\n    const url = new URL(href, window.location.href);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) return;\n    if (isFarmDocsPath(url.pathname)) return;\n    \n    const pathname = url.pathname + url.search;\n    if (this.readFreshPrefetch(pathname) !== undefined) return;\n    \n    return this.fetchPage(pathname, false, false)\n      .catch(function(error) {\n        clearFarmPrefetchCacheOnDeploymentMismatch(spaRouter, error);\n      });\n  },\n\n  observeForPrefetch: function(element) {\n    if (!(\"IntersectionObserver\" in window)) return;\n\n    const href = element.getAttribute(\"href\");\n    if (!href) return;\n    this.unobserveForPrefetch(element);\n    const observer = this.getPrefetchObserver(\"50px\");\n    this.observedPrefetchLinks.set(element, href);\n    observer.observe(element);\n  },\n\n  unobserveForPrefetch: function(element) {\n    if (this.observedPrefetchLinks.delete(element)) {\n      this.prefetchObserver?.unobserve(element);\n    }\n    this.cancelViewportPrefetch(element);\n  }\n};\n\nconst farmClientRuntime = createClientPluginManager(\n  ${clientPluginEntry.registrations},\n  {\n    router: spaRouter,\n    isDev: false,\n    isProd: true,\n    deploymentId: window.__FARM_DEPLOYMENT_ID__,\n  },\n);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\n// Expose router globally\nspaRouter.initializeHistory();\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nvoid hydrateFarmDocsAdapterRuntime();\n\nwindow.addEventListener(\"beforeunload\", function(event) {\n  if (spaRouter.shouldBlockUnload()) {\n    event.preventDefault();\n    event.returnValue = \"\";\n  }\n  spaRouter.saveScrollPosition(window.location.pathname + window.location.search);\n});\n\n// Handle popstate (back/forward)\nwindow.addEventListener(\"popstate\", function(event) {\n  void spaRouter.handlePopState(event);\n});\n\n// Intercept link clicks\ndocument.addEventListener(\"click\", function(e) {\n  const target = e.target;\n  const anchor = target.closest ? target.closest(\"a\") : null;\n  if (!anchor) return;\n  \n  const href = anchor.getAttribute(\"href\");\n  if (!href) return;\n  if (anchor.hasAttribute(\"download\")) return;\n  if (hasAbsoluteNavigationHref(href)) return;\n  if (href.startsWith(\"#\")) return;\n  if (anchor.target && anchor.target !== \"_self\") return;\n  if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n  if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;\n  if (e.button !== 0) return;\n  if (e.defaultPrevented) return;\n  \n  e.preventDefault();\n  spaRouter.navigate(href);\n});\n`.trim();\n  }\n\n  // Generate imports for client components\n  const imports: string[] = [];\n  const routeEntries: string[] = [];\n  const routeSlotEntries: string[] = [];\n  const isolatedBoundaryModules = new Map<string, string>();\n\n  clientPages.forEach((page) => {\n    for (const boundary of page.isolatedBoundaries) {\n      isolatedBoundaryModules.set(\n        toViteModuleId(boundary.modulePath, root),\n        toImportPath(boundary.modulePath),\n      );\n    }\n    const load = page.pageShouldHydrate\n      ? `() => import(${JSON.stringify(toImportPath(page.modulePath))}).then((module) => module.default)`\n      : \"null\";\n    routeEntries.push(`  {\n    pattern: ${JSON.stringify(page.pattern)},\n    pageShouldHydrate: ${JSON.stringify(page.pageShouldHydrate)},\n    ${page.hasIsolatedClientBoundaries ? \"hasIsolatedClientBoundaries: true,\" : \"\"}\n    islandStrategy: ${JSON.stringify(page.islandStrategy)},\n    navigation: \"html-fragment\",\n    load: ${load},\n  }`);\n  });\n  const isolatedHydrationEnabled = isolatedBoundaryModules.size > 0;\n  const isolatedHydrationImport = isolatedHydrationEnabled\n    ? `import { createFarmIsolatedHydrationRuntime, createFarmServerPageBoundary, wrapFarmIsolatedClientGraph } from \"@farm.js/core/internal/isolated-boundary\";`\n    : \"\";\n  const isolatedHydrationRuntime = isolatedHydrationEnabled\n    ? `const farmIsolatedBoundaryLoaders = {\n${Array.from(isolatedBoundaryModules.entries())\n  .map(\n    ([reference, modulePath]) =>\n      `  ${JSON.stringify(reference)}: () => import(${JSON.stringify(modulePath)}),`,\n  )\n  .join(\"\\n\")}\n};\nconst farmIsolatedHydrationRuntime = createFarmIsolatedHydrationRuntime({\n  ReactRuntime: React,\n  hydrateRoot,\n  load: async function(reference) {\n    const loader = farmIsolatedBoundaryLoaders[reference];\n    if (!loader) throw new Error(\"isolated client boundary loader was not found: \" + reference);\n    return loader();\n  },\n  schedule: scheduleFarmIslandHydration,\n  wrap: wrapWithIntegrationProviders,\n});\n\n// A hydrating layout keeps a non-hydrating page as server HTML; this wrapper runs its islands.\nconst FarmServerPage = createFarmServerPageBoundary(React, farmIsolatedHydrationRuntime);\n\nfunction disposeFarmIsolatedClientBoundaries(scope) {\n  farmIsolatedHydrationRuntime.dispose(scope);\n}\n\nasync function hydrateFarmIsolatedClientBoundaries(scope = document, signal) {\n  await farmIsolatedHydrationRuntime.hydrate(scope, signal);\n}`\n    : \"\";\n  const routeClientGraphRuntime = isolatedHydrationEnabled\n    ? `function wrapFarmRouteClientGraph(element) {\n  return wrapFarmIsolatedClientGraph(React, element);\n}`\n    : `function wrapFarmRouteClientGraph(element) { return element; }`;\n  clientRouteSlots.forEach((slot, index) => {\n    const importPath = toImportPath(slot.modulePath);\n    imports.push(`import RouteSlot${index} from \"${importPath}\";`);\n    routeSlotEntries.push(`  {\n    name: ${JSON.stringify(slot.name)},\n    ownerPattern: ${JSON.stringify(slot.ownerPattern)},\n    pattern: ${JSON.stringify(slot.pattern)},\n    containerId: ${JSON.stringify(slot.containerId)},\n    interception: ${JSON.stringify(slot.interception)},\n    fallback: ${JSON.stringify(slot.fallback)},\n    Component: RouteSlot${index},\n  }`);\n  });\n\n  // Full SPA client with hydration for client components\n  return `\n// Farm.js Client Runtime - SPA with Hydration\n${cssImport}\n${layoutImports}\n${rendererClientImports}\n${isolatedHydrationImport}\n${providerClientCode.imports}\nimport { createClientCancellation, createClientPluginManager, getHashTargetElement, installChunkErrorRecovery, isFarmExternalNavigationURL, reconcileFarmDocumentHead, scheduleFarmIslandHydration, searchParamsToObject, setFarmBasePath, setFarmTrailingSlashPreference, stripFarmBasePath } from \"@farm.js/core/internal/client-runtime\";\nimport { createFarmDeploymentMismatchError, createFarmDeploymentRequestHeaders, isFarmDeploymentMismatchResponse } from \"@farm.js/core/deployment\";\nimport { createFarmRouter, isFarmRouteActive, matchFarmRoute } from \"@farm.js/core/router\";\n${clientPluginEntry.imports}\n${clientCachePersistence.imports}\n${i18nClientRuntime}\n${docsNavigationRuntime}\n${docsAdapterRuntime}\n\n${imports.join(\"\\n\")}\n${generateFarmDocsSearchClientRuntime(docsSearchEnabled, docsSearchModuleId)}\n\n${providerClientCode.runtime}\n\nsetFarmBasePath(${JSON.stringify(basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(trailingSlash)});\ninstallChunkErrorRecovery();\n${clientCachePersistence.init}\n\n// Client component routes\nconst clientRoutes = [\n${routeEntries.join(\",\\n\")}\n];\nconst clientRouteMatcher = createFarmRouter(clientRoutes.map(function(route) {\n  return { path: route.pattern, meta: route };\n}));\n\n${isolatedHydrationRuntime}\n${routeClientGraphRuntime}\n\nconst clientRouteSlots = [\n${routeSlotEntries.join(\",\\n\")}\n];\n\n// Layout routes for wrapping client components\nconst layoutRoutes = [\n${layoutRegistrations.join(\",\\n\")}\n];\n\n// Get applicable layouts for a pathname (sorted by depth, root first)\nfunction getApplicableLayouts(pathname) {\n  const applicable = [];\n  const normalizedPath = getFarmRoutePathname(pathname).replace(/\\\\/$/, '') || '/';\n  \n  for (const layout of layoutRoutes) {\n    if (layout.pattern === '/' || isFarmRouteActive(layout.pattern, normalizedPath, { exact: false })) {\n      applicable.push(layout);\n    }\n  }\n  \n  // Sort by depth (root first)\n  applicable.sort(function(a, b) {\n    const depthA = a.pattern.split('/').filter(Boolean).length;\n    const depthB = b.pattern.split('/').filter(Boolean).length;\n    return depthA - depthB;\n  });\n  \n  return applicable;\n}\n\nfunction hasHydratableLayout(pathname) {\n  return getApplicableLayouts(pathname).some(function(layout) {\n    return layout.shouldHydrate === true;\n  });\n}\n\n${FARM_LAYOUT_ELEMENT_CLIENT_SOURCE}\n// Wrap a page element with applicable layouts\nfunction wrapWithLayouts(pageElement, pathname, params) {\n  const layouts = getApplicableLayouts(pathname);\n  let wrapped = pageElement;\n  \n  // Wrap from innermost to outermost (reverse order since layouts are root-first)\n  for (let i = layouts.length - 1; i >= 0; i--) {\n    const layout = layouts[i];\n    if (layout.Component) {\n      wrapped = createFarmLayoutElement(layout.Component, layout.pattern, wrapped, params);\n    }\n  }\n  \n  return wrapped;\n}\n\nfunction createLayoutPageBoundary(route, pageElement, serverHtml) {\n  const props = {\n    id: \"__farm_page__\",\n    // Same attributes as the server's page boundary, or React reports a mismatch.\n    \"data-farm-segment\": \"page\",\n    \"data-farm-client\": route.pageShouldHydrate ? \"true\" : \"false\",\n    \"data-farm-layout-client\": \"true\",\n    \"data-farm-island\": \"page\",\n    \"data-farm-island-strategy\": route.islandStrategy || \"load\",\n  };\n  if (typeof serverHtml === \"string\") {\n    props.suppressHydrationWarning = true;\n    props.dangerouslySetInnerHTML = { __html: serverHtml };\n    return React.createElement(${isolatedHydrationEnabled ? \"FarmServerPage\" : '\"div\"'}, props);\n  }\n  return React.createElement(\"div\", props, pageElement);\n}\n\n// Match pathname to client route\nfunction matchRoute(pathname) {\n  const matched = clientRouteMatcher.match(getFarmRoutePathname(pathname));\n  return matched\n    ? { route: matched.route.meta, params: matched.params }\n    : null;\n}\n\nasync function loadRouteComponent(route) {\n  if (!route.load) return null;\n  if (route.Component) return route.Component;\n  route.Component = await route.load();\n  return route.Component;\n}\n\nasync function createMatchedHydrationRoute(matched, pathname, searchParams, serverHtml) {\n  const hydrateLayouts = hasHydratableLayout(pathname);\n  const params = matched.params;\n  let pageElement = null;\n\n  if (matched.route.pageShouldHydrate) {\n    const Component = await loadRouteComponent(matched.route);\n    if (!Component) return null;\n    if (typeof Component === \"function\" && Component.constructor && Component.constructor.name === \"AsyncFunction\") {\n      console.warn(\n        \"[Farm.js] Skipping hydration for \" + pathname +\n        \": async server components cannot run in the browser. Server-rendered HTML is preserved.\"\n      );\n      return null;\n    }\n    const props = { params: params, searchParams: Promise.resolve(searchParams) };\n    pageElement = React.createElement(Component, props);\n  } else if (hydrateLayouts) {\n    const serverPage = document.getElementById(\"__farm_page__\");\n    pageElement = createLayoutPageBoundary(\n      matched.route,\n      null,\n      typeof serverHtml === \"string\" ? serverHtml : serverPage ? serverPage.innerHTML : \"\",\n    );\n  }\n\n  if (!pageElement) return null;\n  if (!hydrateLayouts) return createFarmRouteState(pageElement, pathname, params, false);\n  if (matched.route.pageShouldHydrate) {\n    pageElement = createLayoutPageBoundary(matched.route, pageElement);\n  }\n  return createFarmRouteState(pageElement, pathname, params, true);\n}\n\nfunction createFarmRouteState(page, pathname, params, includeLayouts) {\n  const layouts = includeLayouts ? getApplicableLayouts(pathname).filter(function(layout) {\n    return Boolean(layout.Component);\n  }) : [];\n  const wrap = function(element) {\n    return wrapFarmRouteClientGraph(wrapWithIntegrationProviders(element));\n  };\n  return {\n    element: wrap(includeLayouts ? wrapWithLayouts(page, pathname, params) : page),\n    layouts,\n    page,\n    params,\n    wrap,\n  };\n}\n\nfunction hydrateFarmRoute(container, route) {\n  ${\n    isReactRenderer(renderer)\n      ? \"return hydrateRoot(container, route.element);\"\n      : \"return route.layouts.length > 0 ? hydrateRoot(container, route.element, route) : hydrateRoot(container, route.element);\"\n  }\n}\n\nfunction renderFarmRoute(root, route) {\n  if (route.layouts.length > 0 && typeof root.renderRoute === \"function\") root.renderRoute(route);\n  else root.render(route.element);\n}\n\nfunction matchesRoutePrefix(pathname, pattern) {\n  return pattern === \"/\" ||\n    isFarmRouteActive(pattern, getFarmRoutePathname(pathname), { exact: false });\n}\n\nfunction matchInterceptedRouteSlot(pathname, from) {\n  for (const slot of clientRouteSlots) {\n    if (!slot.interception || !matchesRoutePrefix(from, slot.ownerPattern)) continue;\n    const params = matchFarmRoute(slot.pattern, getFarmRoutePathname(pathname));\n    if (params !== null) return { slot: slot, params: params };\n  }\n  return null;\n}\n\nfunction routeSlotKey(slot) {\n  return slot.ownerPattern + \":\" + slot.name;\n}\n\nfunction findClientRouteSlot(slot) {\n  return clientRouteSlots.find(function(candidate) {\n    return candidate.name === slot.name &&\n      candidate.ownerPattern === slot.ownerPattern &&\n      candidate.pattern === slot.pattern &&\n      candidate.interception === slot.interception &&\n      candidate.fallback === slot.fallback;\n  });\n}\n\nfunction readRouteSlotPayload(doc) {\n  const script = doc.getElementById(\"__farm_route_slots_data__\");\n  if (!script?.textContent) return [];\n  try {\n    const parsed = JSON.parse(script.textContent);\n    return Array.isArray(parsed) ? parsed : [];\n  } catch {\n    return [];\n  }\n}\n\nconst routeSlotRoots = new Map();\nlet activeRouteInterception = null;\n\nfunction resetRouteSlotRoots() {\n  for (const root of routeSlotRoots.values()) {\n    try { root.unmount(); } catch {}\n  }\n  routeSlotRoots.clear();\n  activeRouteInterception = null;\n}\n\nfunction renderClientRouteSlot(slot, registration, mode) {\n  const container = document.getElementById(slot.containerId);\n  if (!container || !registration?.Component) return false;\n  const key = routeSlotKey(slot);\n  const existingRoot = routeSlotRoots.get(key);\n  const props = slot.props && typeof slot.props === \"object\" ? slot.props : {};\n  const element = wrapFarmRouteClientGraph(\n    wrapWithIntegrationProviders(React.createElement(registration.Component, props)),\n  );\n\n  if (mode === \"hydrate\") {\n    if (existingRoot) return true;\n    const root = hydrateRoot(container, element);\n    routeSlotRoots.set(key, root);\n    return true;\n  }\n\n  if (existingRoot) {\n    try { existingRoot.unmount(); } catch {}\n    routeSlotRoots.delete(key);\n  } else {\n    container.replaceChildren();\n  }\n  const root = createRoot(container);\n  root.render(element);\n  routeSlotRoots.set(key, root);\n  return true;\n}\n\nfunction hydrateInitialRouteSlots() {\n  const slots = Array.isArray(window.__FARM_ROUTE_SLOTS__)\n    ? window.__FARM_ROUTE_SLOTS__\n    : [];\n  for (const slot of slots) {\n    const registration = findClientRouteSlot(slot);\n    if (!registration) continue;\n    try {\n      renderClientRouteSlot(slot, registration, \"hydrate\");\n    } catch (error) {\n      console.warn(\"[Farm.js] Could not hydrate route slot:\", slot.name, error);\n    }\n  }\n}\n\nfunction renderRouteInterception(slot, registration, from, nextDocument) {\n  const container = document.getElementById(slot.containerId);\n  if (!container || !registration?.Component) return false;\n  const key = routeSlotKey(slot);\n  const previousSlot = (window.__FARM_ROUTE_SLOTS__ || []).find(function(candidate) {\n    return routeSlotKey(candidate) === key;\n  }) || null;\n  const previousHtml = container.innerHTML;\n\n  reconcileFarmDocumentHead(nextDocument);\n  if (!renderClientRouteSlot(slot, registration, \"render\")) return false;\n  activeRouteInterception = {\n    from: from,\n    key: key,\n    slot: slot,\n    previousSlot: previousSlot,\n    previousHtml: previousHtml,\n  };\n  return true;\n}\n\nfunction clearRouteInterception(destination) {\n  if (!activeRouteInterception) return false;\n  const active = activeRouteInterception;\n  activeRouteInterception = null;\n  const root = routeSlotRoots.get(active.key);\n  if (root) {\n    try { root.unmount(); } catch {}\n    routeSlotRoots.delete(active.key);\n  }\n  const container = document.getElementById(active.slot.containerId);\n  if (container) {\n    container.innerHTML = active.previousHtml;\n    if (active.previousSlot) {\n      const registration = findClientRouteSlot(active.previousSlot);\n      if (registration) {\n        try {\n          renderClientRouteSlot(active.previousSlot, registration, \"hydrate\");\n        } catch {}\n      }\n    }\n  }\n  return destination === active.from;\n}\n\n// State\nlet reactRoot = null;\nlet reactRootContainer = null;\nlet currentPathname = null;\nlet isHydrated = false;\nlet pendingPageHydrationController = null;\n\n${generateUniversalRouterStateRuntime()}\n\nfunction cancelPendingPageHydration() {\n  pendingPageHydrationController?.abort();\n  pendingPageHydrationController = null;\n}\n\nfunction resetReactRoot() {\n  cancelPendingPageHydration();\n  if (!reactRoot) return;\n  reactRoot.unmount();\n  reactRoot = null;\n  reactRootContainer = null;\n  isHydrated = false;\n}\n\n// Hydrate client components\nasync function hydrate() {\n  await window.__FARM_PPR_REFRESH_PROMISE__;\n  // A PPR refresh that is still retrying must not replace DOM once hydration starts.\n  window.__FARM_PPR_HYDRATING__ = true;\n  await farmClientRuntime.start();\n\n  if (await hydrateFarmDocsAdapterRuntime()) {\n    return;\n  }\n\n  const pathname = window.location.pathname;\n  const matched = matchRoute(pathname);\n  hydrateInitialRouteSlots();\n\n  if (!matched) {\n    return;\n  }\n\n  ${\n    isolatedHydrationEnabled\n      ? `if (\n    matched.route.hasIsolatedClientBoundaries &&\n    !matched.route.pageShouldHydrate &&\n    !hasHydratableLayout(pathname)\n  ) {\n    const hydrationController = new AbortController();\n    pendingPageHydrationController = hydrationController;\n    await hydrateFarmIsolatedClientBoundaries(document, hydrationController.signal);\n    return;\n  }`\n      : \"\"\n  }\n  \n  const rootContainer = document.getElementById(\"root\");\n  const container = hasHydratableLayout(pathname)\n    ? rootContainer\n    : document.getElementById(\"__farm_page__\") || rootContainer;\n  if (!container) {\n    console.error(\"[Farm.js] No root element found\");\n    return;\n  }\n  \n  container.dataset.farmIsland = \"page\";\n  container.dataset.farmIslandStrategy = matched.route.islandStrategy || \"load\";\n\n  const hydrationController = new AbortController();\n  pendingPageHydrationController = hydrationController;\n  try {\n    const pageHydration = scheduleFarmIslandHydration({\n      container,\n      strategy: matched.route.islandStrategy,\n      signal: hydrationController.signal,\n      hydrate: async function() {\n        if (\n          hydrationController.signal.aborted ||\n          !container.isConnected ||\n          window.location.pathname !== pathname\n        ) {\n          return;\n        }\n        const searchParams = searchParamsToObject(new URLSearchParams(window.location.search));\n        const routeState = await createMatchedHydrationRoute(\n          matched,\n          pathname,\n          searchParams,\n        );\n        if (!routeState) return;\n        const shouldHydrate = !isHydrated && Boolean(container.innerHTML.trim());\n        const hydrationSession = await farmClientRuntime.beginHydration({\n          container,\n          mode: shouldHydrate ? \"hydrate\" : \"render\",\n        });\n\n        try {\n          // A navigation replaced this route before it hydrated. Like a superseded\n          // navigation, that is not a failure, so error hooks never see it.\n          if (hydrationController.signal.aborted || !container.isConnected) return;\n          if (shouldHydrate) {\n            reactRoot = hydrateFarmRoute(container, routeState);\n            reactRootContainer = container;\n            isHydrated = true;\n          } else {\n            if (!reactRoot) {\n              reactRoot = createRoot(container);\n              reactRootContainer = container;\n            }\n            renderFarmRoute(reactRoot, routeState);\n          }\n          currentPathname = pathname;\n          await farmClientRuntime.completeHydration(hydrationSession);\n        } catch (error) {\n          await farmClientRuntime.failHydration(hydrationSession, error);\n          console.error(\"[Farm.js] Hydration error:\", error);\n        }\n      },\n    });\n    ${\n      isolatedHydrationEnabled\n        ? `const isolatedHydration =\n      !hasHydratableLayout(pathname) &&\n      document.querySelector('farm-client-boundary[data-farm-client-boundary]')\n        ? hydrateFarmIsolatedClientBoundaries(document, hydrationController.signal)\n        : Promise.resolve();\n    await Promise.all([pageHydration, isolatedHydration]);`\n        : \"await pageHydration;\"\n    }\n  } finally {\n    if (pendingPageHydrationController === hydrationController) {\n      pendingPageHydrationController = null;\n    }\n  }\n}\n\nfunction findLayoutBoundary(root, pattern) {\n  const boundaries = root?.querySelectorAll?.('[data-farm-layout-boundary=\"true\"]') || [];\n  for (const boundary of boundaries) {\n    if (boundary.getAttribute(\"data-farm-layout-pattern\") === pattern) return boundary;\n  }\n  return null;\n}\n\nfunction getLayoutPatterns(root) {\n  return Array.from(root?.querySelectorAll?.('[data-farm-layout-boundary=\"true\"]') || [])\n    .map(function(element) { return element.getAttribute(\"data-farm-layout-pattern\"); })\n    .filter(Boolean);\n}\n\nfunction activateNavigationScripts(root) {\n  for (const script of Array.from(root?.querySelectorAll?.(\"script\") || [])) {\n    const freshScript = document.createElement(\"script\");\n    for (const attribute of Array.from(script.attributes)) {\n      freshScript.setAttribute(attribute.name, attribute.value);\n    }\n    freshScript.textContent = script.textContent || \"\";\n    script.replaceWith(freshScript);\n  }\n}\n\nfunction replaceSharedLayoutBoundary(currentRoot, nextRoot) {\n  const currentPatterns = getLayoutPatterns(currentRoot);\n  const nextPatterns = getLayoutPatterns(nextRoot);\n  let sharedCount = 0;\n  while (\n    sharedCount < currentPatterns.length &&\n    sharedCount < nextPatterns.length &&\n    currentPatterns[sharedCount] === nextPatterns[sharedCount]\n  ) sharedCount++;\n\n  const nextTreeRoot = nextPatterns.length\n    ? findLayoutBoundary(nextRoot, nextPatterns[0])\n    : nextRoot.querySelector(\"#__farm_page__\");\n  const currentTarget = sharedCount < currentPatterns.length\n    ? findLayoutBoundary(currentRoot, currentPatterns[sharedCount])\n    : currentRoot.querySelector(\"#__farm_page__\");\n  const nextTarget = sharedCount < nextPatterns.length\n    ? findLayoutBoundary(nextRoot, nextPatterns[sharedCount])\n    : nextRoot.querySelector(\"#__farm_page__\");\n\n  if (!currentTarget || !nextTarget) return false;\n  ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(currentTarget);\" : \"\"}\n  currentTarget.replaceWith(nextTarget);\n  activateNavigationScripts(nextTarget);\n  if (nextTreeRoot && nextTreeRoot !== nextTarget) nextTreeRoot.remove();\n\n  if (nextRoot.childNodes.length) {\n    const support = document.createElement(\"div\");\n    support.hidden = true;\n    support.dataset.farmFragmentSupport = \"true\";\n    while (nextRoot.firstChild) support.appendChild(nextRoot.firstChild);\n    document.body.appendChild(support);\n    activateNavigationScripts(support);\n    setTimeout(function() { support.remove(); }, 0);\n  }\n  return nextTarget;\n}\n\n// SPA Router\nconst spaRouter = {\n${generateUniversalRouterStateProperties()}\n  prefetchCache: new Map(),\n  \n  navigate: async function(href, options = {}) {\n    const url = new URL(href, window.location.href);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n    if (isFarmDocsPath(url.pathname)) {\n      this.cancelActiveNavigation();\n      if (options.replace || options.action === \"replace\") window.location.replace(href);\n      else window.location.href = href;\n      return;\n    }\n\n    const action = options.action || (options.replace ? \"replace\" : \"push\");\n    const to = url.pathname + url.search;\n    if (!options.refresh && action !== \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      if (url.hash === window.location.hash) return;\n      const pageState = options.state === undefined\n        ? window.history.state?.[FARM_PAGE_STATE_KEY]\n        : options.state;\n      this.writeHistoryEntry(action, to, pageState, url);\n      if (options.scroll !== false) {\n        if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      }\n      return;\n    }\n    if (action === \"pop\" && to === this.currentPath) {\n      this.cancelActiveNavigation();\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n      return;\n    }\n    \n    const pathname = url.pathname;\n    const matched = matchRoute(pathname);\n    const from = this.currentPath;\n    if (await this.shouldBlockNavigation({ from, to, action })) {\n      if (action === \"pop\") this.revertBlockedPopState(from);\n      return;\n    }\n    if (action === \"pop\") {\n      this.currentHistoryIndex = readHistoryIndex(options.popState);\n      this.currentHistoryState = options.popState;\n    }\n\n    // A route transition invalidates any trigger waiting on the previous DOM boundary.\n    cancelPendingPageHydration();\n    this.saveScrollPosition(window.location.pathname + window.location.search);\n    const navigation = this.startNavigation(from, url, action);\n    let clientNavigation;\n\n    try {\n      clientNavigation = await farmClientRuntime.beginNavigation({\n        from: action === \"pop\" ? null : window.location.href,\n        to: url,\n        action,\n        route: matched\n          ? { pattern: matched.route.pattern, params: matched.params }\n          : undefined,\n      });\n      navigation.clientNavigation = clientNavigation;\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n      if (!options.refresh && activeRouteInterception && clearRouteInterception(to)) {\n        this.currentPath = to;\n        await farmClientRuntime.markNavigationLoaded(clientNavigation, {\n          routeSlots: \"restored\",\n        });\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        await farmClientRuntime.resolveNavigation(clientNavigation);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n        this.finishNavigation(navigation);\n        return;\n      }\n      if (activeRouteInterception) {\n        clearRouteInterception(to);\n      }\n\n      const intercepted = options.refresh ? null : matchInterceptedRouteSlot(pathname, from);\n      if (intercepted) {\n        const html = await this.fetchPage(to, from, false, true, navigation.controller.signal);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        const doc = new DOMParser().parseFromString(html, \"text/html\");\n        const slotPayload = readRouteSlotPayload(doc);\n        const selectedSlot = slotPayload.find(function(slot) {\n          return slot.interception &&\n            slot.name === intercepted.slot.name &&\n            slot.ownerPattern === intercepted.slot.ownerPattern;\n        });\n\n        if (selectedSlot) {\n          await farmClientRuntime.markNavigationLoaded(clientNavigation, {\n            route: intercepted.slot.pattern,\n            params: intercepted.params,\n          });\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          if (renderRouteInterception(selectedSlot, intercepted.slot, from, doc)) {\n            this.writeHistoryEntry(action, to, options.state, url);\n            this.currentPath = to;\n            await farmClientRuntime.resolveNavigation(clientNavigation);\n            if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n            void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n            this.finishNavigation(navigation);\n            return;\n          }\n        }\n      }\n\n      if (!options.refresh && matched?.route.navigation === \"client-render\") {\n        // Navigation itself signals intent, so destination routes load eagerly even\n        // when their initial document hydration strategy is deferred.\n        const Component = await loadRouteComponent(matched.route);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        const params = matched.params;\n        const searchParams = searchParamsToObject(url.searchParams);\n        const props = { params: params, searchParams: Promise.resolve(searchParams) };\n        let pageElement = React.createElement(Component, props);\n        if (hasHydratableLayout(pathname)) {\n          pageElement = createLayoutPageBoundary(matched.route, pageElement);\n        }\n        const routeState = createFarmRouteState(\n          pageElement,\n          pathname,\n          params,\n          hasHydratableLayout(pathname),\n        );\n\n        await farmClientRuntime.markNavigationLoaded(clientNavigation, {\n          route: matched.route.pattern,\n          params,\n        });\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n\n        await this.runViewTransition(options.viewTransition, async () => {\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          this.writeHistoryEntry(action, url.pathname + url.search, options.state, url);\n\n          const container = document.getElementById(\"root\");\n          if (container) {\n            if (reactRoot && reactRootContainer !== container) resetReactRoot();\n            if (!reactRoot) {\n              reactRoot = createRoot(container);\n              reactRootContainer = container;\n            }\n            renderFarmRoute(reactRoot, routeState);\n            currentPathname = pathname;\n          }\n          this.currentPath = to;\n        });\n      } else {\n        const html = await this.fetchPage(\n          url.pathname + url.search,\n          undefined,\n          options.refresh === true,\n          true,\n          navigation.controller.signal,\n        );\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        await farmClientRuntime.markNavigationLoaded(clientNavigation, html);\n        if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n        await this.runViewTransition(options.viewTransition, async () => {\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          const swapped = await this.swapContent(\n            html,\n            url.pathname + url.search,\n            navigation,\n            clientNavigation,\n          );\n          if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n          if (!swapped) {\n            throw new Error(\"Farm could not swap the target document\");\n          }\n          this.writeHistoryEntry(action, url.pathname + url.search, options.state, url);\n          currentPathname = pathname;\n          this.currentPath = to;\n        });\n      }\n\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (options.scroll !== false) {\n        if (url.hash) getHashTargetElement(url.hash)?.scrollIntoView();\n        else window.scrollTo(0, 0);\n      } else {\n        this.restoreScrollPosition(to);\n      }\n      await farmClientRuntime.resolveNavigation(clientNavigation);\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      void farmClientRuntime.scheduleNavigationRendered(clientNavigation);\n      this.finishNavigation(navigation);\n    } catch (error) {\n      if (!this.isCurrentNavigation(navigation, clientNavigation)) return;\n      if (error?.name === \"FarmNavigationRedirect\") {\n        this.cancelActiveNavigation();\n        if (action === \"pop\") window.location.reload();\n        else if (action === \"replace\") window.location.replace(url.href);\n        else window.location.assign(url.href);\n        return;\n      }\n      if (clientNavigation) {\n        await farmClientRuntime.failNavigation(clientNavigation, error);\n      }\n      this.finishNavigation(navigation);\n      if (error?.name === \"FarmDeploymentMismatchError\") return;\n      console.error(\"[Farm.js] Navigation error:\", error);\n      if (action === \"pop\") window.location.reload();\n      else window.location.href = href;\n    }\n  },\n\n  refresh: function(options = {}) {\n    return this.navigate(window.location.href, {\n      ...options,\n      action: \"replace\",\n      replace: true,\n      refresh: true,\n      scroll: options.scroll === undefined ? false : options.scroll,\n    });\n  },\n  \n  fetchPage: async function(url, interceptFrom, fresh = false, recover = true, signal) {\n    return this.fetchPrefetchedDocument(url, interceptFrom, fresh, recover, signal);\n  },\n  \n  swapContent: async function(html, targetPath, navigation, clientNavigation) {\n    const parser = new DOMParser();\n    const doc = parser.parseFromString(html, \"text/html\");\n    if (isFarmLocaleDocumentChange(doc)) return false;\n    if (doc.getElementById(\"nd-docs-layout\")) return false;\n    const nextRouteSlots = readRouteSlotPayload(doc);\n    const isNavigationCurrent = () =>\n      this.isCurrentNavigation(navigation, clientNavigation);\n    \n    reconcileFarmDocumentHead(doc);\n    \n    // A full-document app owns <html>/<body> directly and therefore has no\n    // synthetic #root container. Treat each body as the navigation root so\n    // shared layout boundaries can still be reconciled without replacing the\n    // whole document (and remounting every isolated client boundary).\n    const newRoot = doc.getElementById(\"root\") || doc.body;\n    const currentRoot = document.getElementById(\"root\") || document.body;\n    if (!newRoot || !currentRoot) {\n      if (!isNavigationCurrent()) return false;\n      return this.swapDocument(doc);\n    }\n    const targetUrl = new URL(targetPath || window.location.href, window.location.origin);\n    const newPathname = targetUrl.pathname;\n    const matched = matchRoute(newPathname);\n    const hydrateLayouts = hasHydratableLayout(newPathname);\n    const nextPage = newRoot.querySelector(\"#__farm_page__\");\n\n    // If React already owns the shared layout, update that root. React keeps\n    // matching layout component instances and their state mounted.\n    if (matched && hydrateLayouts && reactRoot && reactRootContainer === currentRoot) {\n      const searchParams = searchParamsToObject(targetUrl.searchParams);\n      const routeState = await createMatchedHydrationRoute(\n        matched,\n        newPathname,\n        searchParams,\n        nextPage ? nextPage.innerHTML : \"\",\n      );\n      if (!isNavigationCurrent()) return false;\n      if (routeState) {\n        renderFarmRoute(reactRoot, routeState);\n        window.__FARM_ROUTE_SLOTS__ = nextRouteSlots;\n        isHydrated = true;\n        return true;\n      }\n    }\n\n    const rootWasReactOwned = reactRootContainer === currentRoot;\n    resetReactRoot();\n    resetRouteSlotRoots();\n    const replacedSharedBoundary = rootWasReactOwned\n      ? null\n      : replaceSharedLayoutBoundary(currentRoot, newRoot);\n    let isolatedHydrationScope = replacedSharedBoundary || currentRoot;\n    if (!replacedSharedBoundary) {\n      ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(currentRoot);\" : \"\"}\n      currentRoot.innerHTML = newRoot.innerHTML;\n      activateNavigationScripts(currentRoot);\n      isolatedHydrationScope = currentRoot;\n    }\n    window.__FARM_ROUTE_SLOTS__ = nextRouteSlots;\n    hydrateInitialRouteSlots();\n\n    // Check if the new HTML contains an interactive route boundary.\n    if (matched) {\n      const searchParams = searchParamsToObject(targetUrl.searchParams);\n      const pageContainer =\n        hydrateLayouts ? currentRoot : document.getElementById(\"__farm_page__\") || currentRoot;\n      const routeState = await createMatchedHydrationRoute(\n        matched,\n        newPathname,\n        searchParams,\n      );\n      if (!isNavigationCurrent()) return false;\n      if (routeState) {\n        reactRoot = hydrateFarmRoute(pageContainer, routeState);\n        reactRootContainer = pageContainer;\n        isHydrated = true;\n      }\n      ${\n        isolatedHydrationEnabled\n          ? `if (matched.route.hasIsolatedClientBoundaries && !hydrateLayouts) {\n        await hydrateFarmIsolatedClientBoundaries(\n          isolatedHydrationScope,\n          navigation.controller.signal,\n        );\n        if (!isNavigationCurrent()) return false;\n      }`\n          : \"\"\n      }\n    }\n    return true;\n  },\n\n  swapDocument: function(doc) {\n    if (!doc.documentElement || !doc.body) return false;\n\n    resetReactRoot();\n    resetRouteSlotRoots();\n    ${isolatedHydrationEnabled ? \"disposeFarmIsolatedClientBoundaries(document);\" : \"\"}\n\n    Array.from(document.documentElement.attributes).forEach(function(attr) {\n      if (!doc.documentElement.hasAttribute(attr.name)) {\n        document.documentElement.removeAttribute(attr.name);\n      }\n    });\n    Array.from(doc.documentElement.attributes).forEach(function(attr) {\n      document.documentElement.setAttribute(attr.name, attr.value);\n    });\n\n    document.head.innerHTML = doc.head ? doc.head.innerHTML : \"\";\n    document.body.innerHTML = doc.body.innerHTML;\n    delete window.__farmDocsRuntime;\n    delete window.__farmDocsPageActionsRuntime;\n\n    setTimeout(function() {\n      Array.from(document.querySelectorAll(\"script\")).forEach(function(script) {\n        const freshScript = document.createElement(\"script\");\n        Array.from(script.attributes).forEach(function(attr) {\n          freshScript.setAttribute(attr.name, attr.value);\n        });\n        freshScript.textContent = script.textContent || \"\";\n        script.replaceWith(freshScript);\n      });\n    }, 0);\n\n    return true;\n  },\n  prefetch: function(href) {\n    const url = new URL(href, window.location.href);\n    if (isFarmExternalNavigationURL(url, window.location.origin)) return;\n    if (isFarmDocsPath(url.pathname)) return;\n    \n    // A prefetch warms an ordinary future navigation, which reads the bare\n    // URL key. Carrying the intercept identity here both missed every real\n    // navigation (double fetch per prefetched link) and sent\n    // X-Farm-Intercept-From, which bypasses the shared cache server-side.\n    const pathname = url.pathname + url.search;\n    if (this.readFreshPrefetch(pathname) !== undefined) return;\n    \n    return this.fetchPage(pathname, undefined, false, false)\n      .catch(function(error) {\n        clearFarmPrefetchCacheOnDeploymentMismatch(spaRouter, error);\n      });\n  },\n  \n  observeForPrefetch: function(element) {\n    if (!(\"IntersectionObserver\" in window)) return;\n\n    const href = element.getAttribute(\"href\");\n    if (!href) return;\n    this.unobserveForPrefetch(element);\n    const observer = this.getPrefetchObserver(\"50px\");\n    this.observedPrefetchLinks.set(element, href);\n    observer.observe(element);\n  },\n\n  unobserveForPrefetch: function(element) {\n    if (this.observedPrefetchLinks.delete(element)) {\n      this.prefetchObserver?.unobserve(element);\n    }\n    this.cancelViewportPrefetch(element);\n  }\n};\n\nconst farmClientRuntime = createClientPluginManager(\n  ${clientPluginEntry.registrations},\n  {\n    router: spaRouter,\n    isDev: false,\n    isProd: true,\n    deploymentId: window.__FARM_DEPLOYMENT_ID__,\n  },\n);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\n// Expose router globally\nspaRouter.initializeHistory();\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nwindow.addEventListener(\"beforeunload\", function(event) {\n  if (spaRouter.shouldBlockUnload()) {\n    event.preventDefault();\n    event.returnValue = \"\";\n  }\n  spaRouter.saveScrollPosition(window.location.pathname + window.location.search);\n});\n\n// Handle popstate (back/forward)\nwindow.addEventListener(\"popstate\", function(event) {\n  void spaRouter.handlePopState(event);\n});\n\n// Intercept link clicks\ndocument.addEventListener(\"click\", function(e) {\n  const target = e.target;\n  const anchor = target.closest ? target.closest(\"a\") : null;\n  if (!anchor) return;\n  \n  const href = anchor.getAttribute(\"href\");\n  if (!href) return;\n  if (anchor.hasAttribute(\"download\")) return;\n  if (hasAbsoluteNavigationHref(href)) return;\n  if (href.startsWith(\"#\")) return;\n  if (anchor.target && anchor.target !== \"_self\") return;\n  if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n  if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;\n  if (e.button !== 0) return;\n  if (e.defaultPrevented) return;\n  \n  e.preventDefault();\n  spaRouter.navigate(href);\n});\n\n// Initial hydration\nif (isFarmDocsSearchPage()) {\n  mountFarmDocsSearch();\n}\nvoid hydrate();\n`.trim();\n}\n\n/**\n * Build SSR bundle in memory (write: false)\n * Creates a virtual entry that bundles all API routes and page routes\n * Managers are created at runtime from the bundled code\n */\nasync function buildSSRInMemory(\n  productionVite: FarmProductionViteRuntime,\n  config: ResolvedFarmConfig,\n  root: string,\n  routeManager: RouteManager,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: ServerRenderer,\n  preset: string,\n  collectedPageRoutes: readonly UniversalPageRoute[],\n  collectedLayoutRoutes: ReadonlyArray<{ pattern: string; modulePath: string }>,\n  collectedRouteSlots: readonly UniversalRouteSlot[],\n  isolatedClientBoundaryModules: ReadonlySet<string>,\n  hydrationPlanCache: Map<string, ClientModuleHydrationPlan>,\n): Promise<{\n  bundle: OutputBundle;\n  entryFile: string;\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[];\n}> {\n  const viteBuild = productionVite.build;\n  const { farmPlugin } = await import(\"../vite\");\n  const { PluginManager } = await import(\"../plugin\");\n  const fs = await import(\"fs/promises\");\n\n  const pluginManager = new PluginManager({\n    config,\n    isDev: false,\n    isProd: true,\n  });\n  pluginManager.addPlugins(config.plugins || []);\n  const hasScopedPostcssConfig = hasProjectPostcssConfig(root);\n  let postcssConfigDir: string | undefined;\n  let tailwindVitePlugin: any = undefined;\n  const rendererVitePlugins = await loadFarmRendererVitePlugins(config.renderer, root, {\n    ssr: true,\n  });\n  if (!hasScopedPostcssConfig) {\n    postcssConfigDir = await fs.mkdtemp(path.join(os.tmpdir(), \"farm-postcss-\"));\n    await fs.writeFile(\n      path.join(postcssConfigDir, \"postcss.config.cjs\"),\n      \"module.exports = { plugins: [] };\\n\",\n    );\n    try {\n      const tailwindVite = (await import(\"@tailwindcss/vite\")).default;\n      tailwindVitePlugin = adaptTailwindVitePlugin(tailwindVite(), productionVite.builder);\n    } catch (error) {\n      logger.warn(\n        `Tailwind plugin auto-enable failed for SSR; continuing without it: ${(error as Error).message}`,\n      );\n    }\n  }\n\n  let ssrBundle: OutputBundle;\n  let ssrEntryFile: string;\n\n  // Reuse the route and layout manifests already collected for the parallel\n  // client build instead of rescanning the same project tree.\n  const pageRoutes = collectedPageRoutes.map((route) => ({ ...route }));\n  const layoutRoutes = collectedLayoutRoutes.map((route) => ({ ...route }));\n  const routeSlots = collectedRouteSlots.map((slot) => ({ ...slot }));\n\n  const metadataImageRoutes: UniversalMetadataImageRoute[] = [];\n  for (const entry of routeManager.getMetadataImages().values()) {\n    if (entry.sourceType === \"static\") {\n      if (!entry.staticInfo) {\n        throw new Error(`Static metadata image ${entry.modulePath} is missing file info`);\n      }\n      metadataImageRoutes.push({\n        pattern: entry.pattern,\n        kind: entry.kind,\n        fileName: entry.fileName,\n        sourceType: \"static\",\n        staticInfo: entry.staticInfo,\n        data: (await fs.readFile(entry.modulePath)).toString(\"base64\"),\n      });\n      continue;\n    }\n\n    metadataImageRoutes.push({\n      pattern: entry.pattern,\n      kind: entry.kind,\n      fileName: entry.fileName,\n      sourceType: \"module\",\n      modulePath: entry.modulePath,\n    });\n  }\n\n  const applicationMetadataRoutes: UniversalApplicationMetadataRoute[] = Array.from(\n    routeManager.getMetadataRoutes().values(),\n    (entry) => ({\n      pattern: entry.pattern,\n      kind: entry.kind,\n      outputName: entry.outputName,\n      modulePath: entry.modulePath,\n    }),\n  );\n\n  // Generate API route manifest\n  const apiRoutes: Array<{\n    path: string;\n    filePath: string;\n    methods: string[];\n    pluginMethods?: string[];\n  }> = [];\n  for (const [routePath, route] of apiRouteManager.getRoutes()) {\n    apiRoutes.push({\n      path: routePath,\n      filePath: route.filePath,\n      methods: route.methods,\n      pluginMethods: route.pluginMethods,\n    });\n  }\n  const [configuredRedirects, configuredRewrites, configuredHeaderRoutes] = await Promise.all([\n    config.redirects(),\n    config.rewrites(),\n    config.headers(),\n  ]);\n  const redirectRoutes: ProgrammaticRedirectRoute[] = [\n    ...routeManager.getRedirects(),\n    ...configuredRedirects.map((redirect: RedirectConfig) => ({\n      source: redirect.source,\n      destination: redirect.destination,\n      permanent: redirect.permanent,\n      statusCode: redirect.statusCode,\n    })),\n  ];\n  const errorRoutes: UniversalBoundaryRoute[] = Array.from(\n    routeManager.getErrors().values(),\n    (entry) => ({\n      pattern: entry.pattern,\n      modulePath: entry.modulePath,\n    }),\n  );\n  const i18nCatalogs = config.i18n.enabled\n    ? (await readFarmI18nCatalogs(config.i18n)).catalogs\n    : {};\n\n  const appDirs = getFarmAppDirectories(config);\n  let openAPIReference: {\n    route: string;\n    html: string;\n    spec: unknown;\n    specRoute: string | null;\n  } | null = null;\n  if (config.openapi.enabled && config.openapi.route) {\n    const { OpenAPIManager, renderOpenAPIReferenceHTML } = await import(\"../openapi/manager\");\n    const openAPIManager = new OpenAPIManager(appDirs, config.openapi, {\n      mode: \"production\",\n      apiBaseURL: config.api.baseURL,\n    });\n    const spec = await openAPIManager.generateSpec();\n    if (!spec) {\n      throw new Error(\"Failed to generate the OpenAPI specification for the production build.\");\n    }\n    openAPIReference = {\n      route: config.openapi.route,\n      html: renderOpenAPIReferenceHTML(spec, config.openapi),\n      spec,\n      specRoute: config.openapi.specRoute || null,\n    };\n  }\n  const middlewareRoutes = await discoverMiddlewareRoutes(appDirs);\n  const instrumentationPath = resolveFarmInstrumentationFile(root, config.srcDir || \"src\");\n\n  // Check for custom not-found page\n  const notFoundPath = resolveFarmNotFoundComponentPath(config, appDirs);\n  if (notFoundPath) logger.info(`📋 Found custom 404 page: ${notFoundPath}`);\n\n  // Sort layouts by depth (root first)\n  layoutRoutes.sort((a, b) => {\n    const depthA = a.pattern.split(\"/\").filter(Boolean).length;\n    const depthB = b.pattern.split(\"/\").filter(Boolean).length;\n    return depthA - depthB;\n  });\n\n  logger.info(\n    `📋 Found ${pageRoutes.length} page routes, ${layoutRoutes.length} layouts, ${apiRoutes.length} API routes, ${applicationMetadataRoutes.length} metadata routes, and ${middlewareRoutes.length} middleware files`,\n  );\n\n  const configuredIntegrationValues = Object.values(config.integrations || {});\n  const hasAnyConfiguredIntegrations = configuredIntegrationValues.some(\n    (integration) => typeof integration === \"object\" && integration !== null,\n  );\n  const hasServerRuntimeIntegrations = configuredIntegrationValues.some(\n    (integration) =>\n      typeof integration === \"object\" &&\n      integration !== null &&\n      (!(\"serverRuntime\" in integration) || integration.serverRuntime !== false),\n  );\n  const hasIntegrationProviders = getIntegrationProviders(config.integrations).some(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  const hasObservabilityHandler =\n    !!config.observability &&\n    typeof config.observability === \"object\" &&\n    \"onEvent\" in config.observability;\n  const hasMdxComponentConfig = Boolean(config.mdx?.components);\n  const hasMiddlewareConfig = hasFarmMiddlewareConfig(config.middleware);\n  const hasRouteContextConfig = hasCustomFarmRouteContext(config);\n  const hasServerRuntimePlugins = hasFarmServerRuntimePlugins(config);\n  const hasPluginRoutes = hasFarmPluginRoutes(config);\n  const configModulePath =\n    hasServerRuntimeIntegrations ||\n    hasObservabilityHandler ||\n    hasMdxComponentConfig ||\n    hasMiddlewareConfig ||\n    hasRouteContextConfig ||\n    hasServerRuntimePlugins ||\n    hasPluginRoutes ||\n    hasIntegrationProviders\n      ? await findFarmConfigPath(root)\n      : null;\n  const hasRuntimeConfigModule = hasFarmRuntimeConfigModule(config, configModulePath);\n  const hasRuntimeIntegrationConfig = hasRuntimeConfigModule && hasAnyConfiguredIntegrations;\n  const hasConfiguredRuntimePlugins = Boolean(\n    hasRuntimeConfigModule && (config.plugins || []).length > 0,\n  );\n  const farmDocsPrecompiledManifest =\n    config.docs?.enabled && getFarmPresetRuntime(preset) === \"edge\"\n      ? config.docs.adapter?.server\n        ? await compileFarmDocsAdapterEdgeManifest(config.docs, {\n            root,\n            srcDir: config.srcDir,\n            clientEntry: FARM_CLIENT_JS_SRC_PLACEHOLDER,\n            fontStylesheetHref: \"/farm-fonts.css\",\n            globalStylesheetHref: \"/assets/globals.css\",\n          })\n        : await compileFarmDocsManifest(config.docs, {\n            root,\n            srcDir: config.srcDir,\n            clientEntry: FARM_CLIENT_JS_SRC_PLACEHOLDER,\n            fontAssets: toFarmDocsPublicFontAssets(resolveFarmDocsFontAssets(root)),\n            fontStylesheetHref: \"/farm-fonts.css\",\n            globalStylesheetHref: \"/assets/globals.css\",\n          })\n      : null;\n\n  // Generate virtual entry code that imports and bundles all routes\n  // This ensures all route handlers are captured in the bundle closure\n  const virtualEntryCode = generateVirtualEntryCode(\n    apiRoutes,\n    pageRoutes,\n    layoutRoutes,\n    routeSlots,\n    errorRoutes,\n    metadataImageRoutes,\n    applicationMetadataRoutes,\n    middlewareRoutes,\n    redirectRoutes,\n    configuredRewrites,\n    configuredHeaderRoutes,\n    openAPIReference,\n    notFoundPath,\n    instrumentationPath,\n    config,\n    farmDocsPrecompiledManifest,\n    configModulePath,\n    hasServerRuntimeIntegrations,\n    hasRuntimeIntegrationConfig,\n    hasConfiguredRuntimePlugins,\n    hasServerRuntimePlugins,\n    preset,\n    i18nCatalogs,\n    isolatedClientBoundaryModules,\n    hydrationPlanCache,\n  );\n\n  // Find a temporary file path for the virtual entry\n  // We'll use a plugin to intercept this\n  const virtualEntryId = \"\\0virtual:farm-ssr-entry\";\n  // Any server module may import @vercel/og, which is only known once this\n  // graph is built. Keep it external on Node presets regardless: an unused\n  // external costs nothing, and Nitro copies the package only when the bundle\n  // imports it.\n  const useExternalMetadataImageRuntime = shouldUseExternalMetadataImageRuntime(preset, true);\n  const rendererOptionalExternals = isReactRenderer(config.renderer)\n    ? []\n    : [\n        \"react\",\n        \"react/jsx-runtime\",\n        \"react/jsx-dev-runtime\",\n        \"react-dom\",\n        \"react-dom/client\",\n        \"react-dom/server\",\n      ];\n\n  try {\n    await viteBuild({\n      root,\n      build: {\n        target: \"esnext\",\n        ssr: true,\n        write: false, // ⭐ Keep in memory\n        ssrEmitAssets: true,\n        assetsInlineLimit: 0,\n        minify: false, // Skip minification for SSR (faster build, Nitro will minify)\n        sourcemap: false, // Skip sourcemaps for faster SSR build\n        rollupOptions: {\n          input: virtualEntryId,\n          // Externalize native modules and Node.js built-ins\n          external: [\n            \"fsevents\",\n            \"sharp\",\n            ...rendererOptionalExternals,\n            ...(useExternalMetadataImageRuntime ? [\"@vercel/og\"] : []),\n            \"@prisma/client\",\n            \"@prisma/client/default\",\n            \"@prisma/client/default.js\",\n            \".prisma/client\",\n            \".prisma/client/default\",\n            /^\\.prisma\\//,\n            /\\.node$/,\n            /^node:/,\n          ],\n          treeshake: {\n            // Rollup's type wants a boolean; both bundlers accept `undefined` (see the hook).\n            moduleSideEffects: createFarmServerModuleSideEffects(\n              root,\n            ) as Rollup.HasModuleSideEffects,\n          },\n        },\n      },\n      // Use esbuild for faster transforms\n      esbuild: {\n        target: \"node18\",\n        // Adapters can render provider scripts by serializing function source.\n        // keepNames injects helper calls into those functions; after Nitro\n        // minifies the server chunk the helper is no longer in script scope.\n        keepNames: !(config.docs?.enabled && config.docs.adapter?.server),\n        jsxDev: false,\n      },\n      // SSR configuration to externalize problematic modules\n      ssr: {\n        // Externalize native modules and build tools that can't be bundled\n        // These have native binaries that won't work in serverless environments\n        external: [\n          \"fsevents\",\n          \"sharp\",\n          ...rendererOptionalExternals,\n          ...(useExternalMetadataImageRuntime ? [\"@vercel/og\"] : []),\n          \"esbuild\",\n          \"lightningcss\",\n          \"rollup\",\n          \"@rollup/rollup-darwin-arm64\",\n          \"@rollup/rollup-darwin-x64\",\n          \"@rollup/rollup-linux-x64-gnu\",\n          \"@rollup/rollup-linux-x64-musl\",\n          \"@rollup/rollup-linux-arm64-gnu\",\n          \"@rollup/rollup-linux-arm64-musl\",\n          \"@rollup/rollup-win32-x64-msvc\",\n          \"@rollup/rollup-win32-arm64-msvc\",\n          \"@rollup/rollup-win32-ia32-msvc\",\n          \"vite\",\n          \"vite-rolldown\",\n          \"nitro\",\n          \"nitropack\",\n          \"@prisma/client\",\n          \"@prisma/client/default\",\n          \"@prisma/client/default.js\",\n          \".prisma/client\",\n          \".prisma/client/default\",\n        ],\n        // Node deployments must bundle application dependencies with Farm's\n        // React runtime. Leaving a React component package external can make it\n        // resolve a second React instance at runtime and break hooks during SSR.\n        // Native and build-only packages above remain explicitly external.\n        noExternal:\n          preset === \"cloudflare-module\"\n            ? [\n                \"@farm.js/core\",\n                \"@farm.js/core/image\",\n                \"better-call\",\n                ...(metadataImageRoutes.some((image) => image.sourceType === \"module\")\n                  ? [\"@vercel/og\"]\n                  : []),\n              ]\n            : true,\n      },\n      define: {\n        __FARM_API_BASE_URL__: JSON.stringify(config.api.baseURL),\n        __FARM_ENV__: JSON.stringify(config.env || { server: {}, public: {} }),\n        __FARM_PUBLIC_ENV__: JSON.stringify(config.env?.public || {}),\n      },\n      plugins: [\n        createFarmThemeCssPlugin(config.theme, config.basePath),\n        ...(tailwindVitePlugin ? [tailwindVitePlugin] : []),\n        ...(rendererVitePlugins as any[]),\n        ...(config.vite.plugins || []),\n        ...(!useExternalMetadataImageRuntime &&\n        metadataImageRoutes.some((image) => image.sourceType === \"module\")\n          ? [createMetadataImageWasmPlugin()]\n          : []),\n        {\n          name: \"farm-react-production-mode\",\n          enforce: \"pre\",\n          transform(code, id) {\n            const normalizedId = id.replace(/\\\\/g, \"/\");\n            const isReactRuntime =\n              normalizedId.includes(\"/node_modules/react/\") ||\n              normalizedId.includes(\"/node_modules/react-dom/\");\n            const nodeEnvExpression = [\"process\", \"env\", \"NODE_ENV\"].join(\".\");\n\n            if (!isReactRuntime || !code.includes(nodeEnvExpression)) return null;\n\n            return {\n              code: code.split(nodeEnvExpression).join('\"production\"'),\n              map: null,\n            };\n          },\n        },\n        farmPlugin({ ...config, isolatedClientBoundaryModules }, pluginManager),\n        farmEnvironmentFunctionsPlugin(),\n        {\n          name: \"farm-virtual-ssr-entry\",\n          resolveId(id) {\n            if (id === virtualEntryId || id === \"\\0virtual:farm-ssr-entry\") {\n              return virtualEntryId;\n            }\n            return null;\n          },\n          load(id) {\n            if (id === virtualEntryId) {\n              return virtualEntryCode;\n            }\n            return null;\n          },\n        },\n        {\n          name: \"capture-ssr-bundle\",\n          generateBundle(_options, bundle) {\n            ssrBundle = bundle;\n\n            // Find entry file\n            for (const [fileName, file] of Object.entries(bundle)) {\n              if (file.type === \"chunk\" && file.isEntry) {\n                ssrEntryFile = fileName;\n                break;\n              }\n            }\n\n            if (!ssrEntryFile) {\n              throw new Error(\"No entry point found in SSR bundle\");\n            }\n          },\n        },\n      ],\n      mode: \"production\",\n      css: postcssConfigDir\n        ? {\n            postcss: postcssConfigDir,\n          }\n        : undefined,\n      resolve: {\n        alias: [\n          ...(shouldAliasReactServerToWebBuild(config.renderer, preset)\n            ? [createFarmReactWebServerAlias(hasReactDomEdgeServerBuild(root))]\n            : []),\n          ...Object.entries(createFarmSourceAlias(root, config.srcDir)).map(\n            ([find, replacement]) => ({ find, replacement }),\n          ),\n        ],\n        // Route modules and the renderer adapter must share one runtime instance.\n        dedupe: [...(config.renderer.dedupe || [])],\n      },\n    });\n  } finally {\n    if (postcssConfigDir) {\n      try {\n        await fs.rm(postcssConfigDir, { recursive: true, force: true });\n      } catch {\n        // Ignore cleanup errors.\n      }\n    }\n  }\n\n  return {\n    bundle: ssrBundle!,\n    entryFile: ssrEntryFile!,\n    configuredHeaderRoutes,\n  };\n}\n\n/**\n * Root paths the docs engine answers that the app serves itself, so the\n * production server leaves them to the app: /llms.txt and /llms-full.txt\n * (agent.llmsTxt, llms.ts, llms-full.ts), /sitemap.xml (sitemap.ts), and\n * /robots.txt (agent.crawlers, robots.ts). A public file needs no entry, since\n * the platform serves it before any route.\n */\nexport function getFarmAppOwnedDocsEnginePaths(\n  agent:\n    | (Pick<ResolvedFarmConfig[\"agent\"], \"llmsTxt\"> &\n        Partial<Pick<ResolvedFarmConfig[\"agent\"], \"crawlers\">>)\n    | undefined,\n  applicationMetadataRoutes: ReadonlyArray<\n    Pick<UniversalApplicationMetadataRoute, \"kind\" | \"pattern\">\n  >,\n): string[] {\n  const llmsTxt = agent?.llmsTxt;\n  const ownedByFile = (kind: UniversalApplicationMetadataRoute[\"kind\"]) =>\n    applicationMetadataRoutes.some(\n      (metadata) => metadata.kind === kind && metadata.pattern === \"/\",\n    );\n  return [\n    ...(llmsTxt?.enabled || ownedByFile(\"llms\") ? [\"/llms.txt\"] : []),\n    ...((llmsTxt?.enabled && llmsTxt.full) || ownedByFile(\"llms-full\") ? [\"/llms-full.txt\"] : []),\n    ...(ownedByFile(\"sitemap\") ? [\"/sitemap.xml\"] : []),\n    ...(agent?.crawlers?.enabled || ownedByFile(\"robots\") ? [\"/robots.txt\"] : []),\n  ];\n}\n\n/**\n * Generate virtual entry code that bundles all routes\n * This creates managers at runtime from bundled code\n */\nexport function generateFarmDocsRuntimeConfigExpression(\n  docs: ResolvedFarmConfig[\"docs\"],\n  precompiled = false,\n): string {\n  if (!docs.enabled) return \"null\";\n\n  const baseConfig = {\n    ...docs,\n    contentDir: undefined,\n    ...(precompiled ? { configPath: undefined } : {}),\n    config: undefined,\n  };\n  const nestedConfig = {\n    ...docs.config,\n    contentDir: undefined,\n  };\n\n  if (precompiled) {\n    return JSON.stringify({\n      ...baseConfig,\n      config: nestedConfig,\n    });\n  }\n\n  return `farmDocsBundledContentDir\n  ? {\n      ...${JSON.stringify(baseConfig)},\n      contentDir: farmDocsBundledContentDir,\n      config: {\n        ...${JSON.stringify(nestedConfig)},\n        contentDir: farmDocsBundledContentDir,\n      },\n    }\n  : ${JSON.stringify(docs)}`;\n}\n\n/**\n * Quote a filesystem path for use as an import specifier in generated code.\n * Windows paths contain backslashes, which JavaScript string literals treat\n * as escape sequences (e.g. `\\f` in `E:\\farm`), producing specifiers the\n * bundler cannot resolve. Normalize to forward slashes and JSON-quote.\n */\nexport function toVirtualEntryImportSpecifier(modulePath: string): string {\n  return JSON.stringify(modulePath.replace(/\\\\/g, \"/\"));\n}\n\n/**\n * Runtime source that remounts the native `auth` integration in a built server.\n *\n * `resolveConfig` turns a top-level `auth` config into `integrations.auth`, but\n * the generated production entry never calls `resolveConfig`: it rebuilds its\n * integration map by re-evaluating the raw user config module, where auth only\n * exists as `auth: true`. Without this the auth routes are absent from every\n * production build and each one 404s while dev serves them.\n *\n * The import is literal so the bundler traces `@farm.js/auth` into the server\n * output, and both pieces are empty when auth is disabled so nothing is pulled\n * in for apps that do not use it.\n */\nexport function generateNativeAuthIntegrationSource(auth: ResolvedFarmConfig[\"auth\"] | undefined): {\n  importSource: string;\n  registerSource: string;\n} {\n  if (auth?.enabled !== true) {\n    return { importSource: \"\", registerSource: \"\" };\n  }\n\n  return {\n    importSource: `import { createFarmAuthIntegration as __farmCreateAuthIntegration } from \"@farm.js/auth/internal\";`,\n    // resolveConfig rejects configuring both `auth` and `integrations.auth`,\n    // so this never overwrites a user-supplied integration.\n    registerSource: `configuredIntegrations.auth = __farmCreateAuthIntegration(${JSON.stringify(auth)}, {\n  root: process.cwd(),\n  mode: \"production\",\n});`,\n  };\n}\n\n/**\n * Runtime source that remounts the top-level `mcp` configuration in a built server.\n *\n * Production re-evaluates raw layer and application config modules instead of\n * calling `resolveConfig`, so the internal plugin created during the build is\n * not otherwise present in the runtime plugin list. The literal import keeps\n * the optional MCP package traceable for server and edge bundles while disabled\n * applications carry no import or runtime code.\n */\nexport function generateNativeMCPPluginSource(mcp: ResolvedFarmConfig[\"mcp\"] | undefined): {\n  importSource: string;\n  registerSource: string;\n  pluginSource: string;\n} {\n  if (mcp?.enabled !== true) {\n    return { importSource: \"\", registerSource: \"\", pluginSource: \"\" };\n  }\n\n  return {\n    importSource: `import { createFarmMCPPlugin as __farmCreateMCPPlugin } from \"@farm.js/mcp/internal\";`,\n    registerSource: `function __farmMCPIsPlainObject(value) {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction __farmMergeMCPConfig(base, override) {\n  const output = { ...base };\n  for (const [key, value] of Object.entries(override)) {\n    if (value === undefined) continue;\n    output[key] =\n      __farmMCPIsPlainObject(output[key]) && __farmMCPIsPlainObject(value)\n        ? __farmMergeMCPConfig(output[key], value)\n        : value;\n  }\n  return output;\n}\n\nconst farmNativeMCPConfig = farmRuntimeConfigs.reduce((merged, runtimeConfig) => {\n  const value = runtimeConfig?.mcp;\n  if (value === undefined) return merged;\n  if (value === false) return false;\n  return __farmMergeMCPConfig(merged && merged !== false ? merged : {}, value);\n}, undefined);\nconst farmNativeMCPPlugin =\n  farmNativeMCPConfig && farmNativeMCPConfig.enabled !== false\n    ? __farmCreateMCPPlugin(farmNativeMCPConfig)\n    : null;`,\n    pluginSource: `...(farmNativeMCPPlugin ? [farmNativeMCPPlugin] : []),`,\n  };\n}\n\n/**\n * Runtime source for the production entry's integration request dispatch.\n *\n * `matchLocalIntegrationRequest` stays route-only: it answers \"does this URL\n * belong to an emitted integration route\", which is what configured-rewrite\n * precedence needs. Request dispatch deliberately does not go through it.\n * Integration middleware is not route scoped (it is how `protectedRoutes`\n * guards and provider session refresh are mounted), so gating dispatch on a\n * route match let anonymous requests reach protected pages. Every request is\n * dispatched instead, exactly like the dev server runs the same middleware.\n */\nexport function generateIntegrationRequestRuntimeSource(options: {\n  hasServerRuntimeIntegrations: boolean;\n}): string {\n  return `\nfunction matchLocalIntegrationRequest(request) {\n  ${\n    options.hasServerRuntimeIntegrations\n      ? `return matchIntegrationRoute(serverRuntimeIntegrations, {\n    pathname: new URL(request.url).pathname,\n    method: request.method,\n  });`\n      : \"return null;\"\n  }\n}\n\nasync function handleIntegrationRequest(request) {\n  ${\n    options.hasServerRuntimeIntegrations\n      ? `return dispatchIntegrationRequests(\n    serverRuntimeIntegrations,\n    {\n      config: integrationRuntimeConfig,\n      isDev: false,\n      isProd: true,\n    },\n    request,\n  );`\n      : `return { response: null, setCookies: [] };`\n  }\n}\n\n// Merge Set-Cookie values forwarded by a passthrough integration middleware\n// into the deferred header bag that every downstream response already applies.\nfunction withFarmIntegrationSetCookies(headers, cookies) {\n  if (!cookies || cookies.length === 0) return headers;\n  const merged = new Headers(headers || undefined);\n  for (const cookie of cookies) {\n    merged.append(\"set-cookie\", cookie);\n  }\n  return merged;\n}\n`;\n}\n\nexport function generateConfiguredResponseHeadersRuntimeSource(): string {\n  return `\n// Configured patterns are immutable build output. Reuse the page matcher's\n// fixed-segment preparation, retaining the complete matcher for catch-alls.\nconst preparedHeaderRoutes = configuredHeaderRoutes.map(function(route) {\n  const segments = splitRuntimePath(route.source);\n  return { headers: route.headers, segments, prepared: prepareRuntimePageSegments(segments) };\n});\n\nfunction getConfiguredSetCookieHeaders(headers) {\n  const getSetCookie = headers.getSetCookie;\n  if (typeof getSetCookie === \"function\") return getSetCookie.call(headers);\n  const value = headers.get(\"set-cookie\");\n  return value ? [value] : [];\n}\n\nfunction applyConfiguredResponseHeaders(response, pathname) {\n  if (preparedHeaderRoutes.length === 0) return response;\n  const pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n  let headers;\n  for (const headerRoute of preparedHeaderRoutes) {\n    const matched = headerRoute.prepared\n      ? matchPreparedRuntimePageSegments(headerRoute.prepared, pathnameSegments)\n      : matchRuntimePathSegments(headerRoute.segments, pathnameSegments);\n    if (!matched) continue;\n    for (const header of headerRoute.headers) {\n      const currentHeaders = headers || response.headers;\n      const normalizedKey = header.key.toLowerCase();\n      if (normalizedKey === \"set-cookie\") {\n        if (getConfiguredSetCookieHeaders(currentHeaders).includes(header.value)) continue;\n        if (!headers) headers = new Headers(response.headers);\n        headers.append(\"Set-Cookie\", header.value);\n      } else {\n        const currentValue = currentHeaders.get(header.key);\n        if (currentValue === header.value) continue;\n        if (!headers) headers = new Headers(response.headers);\n        if (normalizedKey === \"link\") {\n          appendFarmLinkHeader(headers, header.value);\n        } else {\n          headers.set(header.key, header.value);\n        }\n      }\n    }\n  }\n\n  if (!headers) return response;\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n`.trim();\n}\n\nfunction parseRouteRenderingDirectiveFromDisk(modulePath: string) {\n  try {\n    const source = readFileSync(modulePath, \"utf8\");\n    const directive = parseRouteRenderingDirective(source);\n    // The runtime only sees module exports, so whether this route reads request\n    // state has to be decided here and ride the registration. Without it the\n    // runtime merge happily resolves ssg for a route the build already demoted\n    // to per-request rendering, and stamps a shared cache-control on it.\n    if (findRequestBoundSourceBlockers(source).length === 0) return directive;\n    return { ...(directive ?? { ssg: false, ppr: false, directive: \"\" }), requestBound: true };\n  } catch {\n    return undefined;\n  }\n}\n\nexport function generatePreloadResponseRuntimeSource(): string {\n  return `\n// Farm builds buffered HTML responses from strings it already holds. Remember\n// that string per body stream so later steps can use it instead of draining and\n// re-encoding the body: the preload budget scans it, and compression compresses\n// it in one call. Header-only rebuilds (middleware and configured headers) pass\n// the same stream through and keep the entry; anything that changes the body\n// (plugins, CSP nonces, clone/tee) creates a new stream and falls back to\n// reading it, so a changed body is never paired with a stale string.\nconst farmBufferedHtml = new WeakMap();\n\nfunction rememberFarmBufferedHtml(response, html) {\n  // Response.text() strips a leading BOM, so a BOM document keeps reading its\n  // body to preserve that behavior.\n  if (typeof html === \"string\" && html.charCodeAt(0) !== 0xfeff && response.body) {\n    farmBufferedHtml.set(response.body, html);\n  }\n  return response;\n}\n\nfunction getFarmOwnedBufferedHtml(response) {\n  const body = response.body;\n  if (!body || response.bodyUsed || body.locked) return undefined;\n  return farmBufferedHtml.get(body);\n}\n\nfunction getFarmBufferedPreloadMarker(html) {\n  // Prove eligibility while Farm still owns the complete document string.\n  // Candidate-bearing or unknown bodies must retain the full parser path.\n  // Response.text() strips a leading UTF-8 BOM; retain that legacy behavior.\n  return typeof html === \"string\" && html.charCodeAt(0) !== 0xfeff && !/\\\\bpreload\\\\b/i.test(html) ? \"none\" : \"1\";\n}\n\nasync function applyFarmPreloadBudget(response, pathname, request) {\n  let headers = response.headers;\n  const linkHeader = headers.get(\"Link\") || \"\";\n  const isHtml = headers.get(\"Content-Type\")?.toLowerCase().includes(\"text/html\");\n  const isStreaming = headers.get(\"x-farm-preload-streaming\") === \"1\";\n  const bufferedMarker = headers.get(\"x-farm-preload-buffered\");\n  const hasNoHtmlPreloads = bufferedMarker === \"none\";\n  const isBuffered = bufferedMarker === \"1\" || hasNoHtmlPreloads;\n  if (!isHtml) {\n    if (!isStreaming && !isBuffered) return response;\n    headers = new Headers(headers);\n    headers.delete(\"x-farm-preload-streaming\");\n    headers.delete(\"x-farm-preload-buffered\");\n    return new Response(response.body, {\n      status: response.status,\n      statusText: response.statusText,\n      headers,\n    });\n  }\n\n  if (isStreaming || !isBuffered || response.body === null) {\n    const managed = manageFarmLinkHeaderPreloads(linkHeader, farmPreloadConfig);\n    reportFarmPreloadWarnings(managed.warnings, managed.warnings.length > 0\n      ? \"route \" + (pathname ?? getFarmRoutePathname(new URL(request.url).pathname))\n      : undefined);\n    // Unknown streams retain their body and ownership when no headers change.\n    // Empty Link values and even unrecognized internal markers still need cleanup.\n    if (!headers.has(\"x-farm-preload-streaming\") &&\n        !headers.has(\"x-farm-preload-buffered\") &&\n        (managed.value || null) === headers.get(\"Link\")) return response;\n    headers = new Headers(headers);\n    headers.delete(\"x-farm-preload-streaming\");\n    headers.delete(\"x-farm-preload-buffered\");\n    if (managed.value) headers.set(\"Link\", managed.value);\n    else headers.delete(\"Link\");\n    return new Response(response.body, {\n      status: response.status,\n      statusText: response.statusText,\n      headers,\n    });\n  }\n\n  // Keep the document/header budget semantics (including unchanged Link\n  // formatting), but do not consume and re-encode a proven preload-free body.\n  headers = new Headers(headers);\n  headers.delete(\"x-farm-preload-streaming\");\n  headers.delete(\"x-farm-preload-buffered\");\n  const ownedHtml = hasNoHtmlPreloads ? undefined : getFarmOwnedBufferedHtml(response);\n  const html = hasNoHtmlPreloads ? \"\" : (ownedHtml ?? await response.text());\n  const managed = manageFarmDocumentPreloads(html, linkHeader, farmPreloadConfig);\n  // A remembered document the budget left unchanged keeps its unread body.\n  const reusesBody = hasNoHtmlPreloads || (ownedHtml !== undefined && managed.html === html);\n  if (ownedHtml !== undefined && !reusesBody) response.body?.cancel().catch(() => {});\n  if (managed.linkHeader) headers.set(\"Link\", managed.linkHeader);\n  else headers.delete(\"Link\");\n  if (managed.html !== html) headers.delete(\"Content-Length\");\n  reportFarmPreloadWarnings(managed.warnings, managed.warnings.length > 0\n    ? \"route \" + (pathname ?? getFarmRoutePathname(new URL(request.url).pathname))\n    : undefined);\n  const output = new Response(reusesBody ? response.body : managed.html, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n  // A rebuilt document is still a complete string Farm holds.\n  return reusesBody ? output : rememberFarmBufferedHtml(output, managed.html);\n}\n`.trim();\n}\n\nfunction generateVirtualEntryCode(\n  apiRoutes: Array<{ path: string; filePath: string; methods: string[]; pluginMethods?: string[] }>,\n  pageRoutes: UniversalPageRoute[],\n  layoutRoutes: Array<{ pattern: string; modulePath: string }>,\n  routeSlots: UniversalRouteSlot[],\n  errorRoutes: UniversalBoundaryRoute[],\n  metadataImageRoutes: UniversalMetadataImageRoute[],\n  applicationMetadataRoutes: UniversalApplicationMetadataRoute[],\n  middlewareRoutes: UniversalMiddlewareRoute[],\n  redirectRoutes: ProgrammaticRedirectRoute[],\n  configuredRewriteRoutes: RewriteConfig[],\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[],\n  openAPIReference: { route: string; html: string; spec: unknown; specRoute: string | null } | null,\n  notFoundPath: string | null,\n  instrumentationPath: string | null,\n  config: ResolvedFarmConfig,\n  farmDocsPrecompiledManifest: FarmDocsCompiledManifest | null,\n  configModulePath: string | null,\n  hasServerRuntimeIntegrations: boolean,\n  hasRuntimeIntegrationConfig: boolean,\n  hasConfiguredRuntimePlugins: boolean,\n  hasServerRuntimePlugins: boolean,\n  preset: string,\n  i18nCatalogs: FarmI18nCatalogs,\n  isolatedClientBoundaryModules: ReadonlySet<string>,\n  hydrationPlanCache: Map<string, ClientModuleHydrationPlan>,\n): string {\n  const hasCompressionRuntime =\n    config.compress && resolveFarmInstrumentationRuntime(preset) === \"nodejs\";\n  // agent.crawlers serves /robots.txt unless a root robots.ts owns it.\n  const servesAgentRobotsTxt =\n    Boolean(config.agent?.crawlers?.enabled) &&\n    !applicationMetadataRoutes.some(\n      (metadata) => metadata.kind === \"robots\" && metadata.pattern === \"/\",\n    );\n  const hasPluginRuntime = hasRuntimeIntegrationConfig || hasServerRuntimePlugins;\n  // Decided when the server starts, from its environment; see createFarmInfraAnalyticsPlugin.\n  const hasInfraAnalyticsRuntime =\n    config.analytics !== false && resolveFarmInstrumentationRuntime(preset) === \"nodejs\";\n  const hasPrecompiledDocs = Boolean(farmDocsPrecompiledManifest);\n  const adapterOwnsDocsRuntime = Boolean(\n    isReactRenderer(config.renderer) &&\n    config.docs?.enabled &&\n    config.docs.adapter?.server &&\n    config.docs.adapter.react,\n  );\n  const hasIsolatedClientGraphRuntime =\n    isReactRenderer(config.renderer) && isolatedClientBoundaryModules.size > 0;\n  const rendererStreamingCapabilities = getFarmRendererStreamingCapabilitiesForRuntime(\n    config.renderer,\n    getFarmPresetRuntime(preset),\n  );\n  const rendererServerImports = isReactRenderer(config.renderer)\n    ? `import * as React from \"react\";\\nimport * as ReactDOMServer from \"react-dom/server\";${\n        hasIsolatedClientGraphRuntime\n          ? '\\nimport { isolateFarmServerPageGraph, wrapFarmIsolatedClientGraph } from \"@farm.js/core/internal/isolated-boundary\";'\n          : \"\"\n      }`\n    : `import React, * as ReactDOMServer from ${JSON.stringify(config.renderer.server)};`;\n  const routeClientGraphServerRuntime = hasIsolatedClientGraphRuntime\n    ? `function wrapFarmRouteClientGraph(element) {\n  return wrapFarmIsolatedClientGraph(React, element);\n}\n\n// A hydrating layout keeps a page that does not hydrate as server HTML, so the page's client\n// components render as their own islands instead of joining the layout's React tree.\nfunction isolateFarmRouteServerPage(element) {\n  return isolateFarmServerPageGraph(React, element);\n}`\n    : `function wrapFarmRouteClientGraph(element) { return element; }\n\nfunction isolateFarmRouteServerPage(element) { return element; }`;\n  const hasGeneratedMetadataImages = metadataImageRoutes.some(\n    (image) => image.sourceType === \"module\",\n  );\n  const hasMiddlewareRuntime =\n    middlewareRoutes.length > 0 || hasFarmMiddlewareConfig(config.middleware);\n  const farmDocsFontAssets = config.docs?.enabled\n    ? toFarmDocsPublicFontAssets(resolveFarmDocsFontAssets(config.root))\n    : [];\n  const integrationProviders = getIntegrationProviders(config.integrations);\n  const renderedIntegrationProviders = integrationProviders.filter(\n    (provider) => provider.component || provider.type === \"clerk\",\n  );\n  if (\n    renderedIntegrationProviders.length > 0 &&\n    !getFarmRendererCapabilities(config.renderer).functionComponents\n  ) {\n    throw new Error(\n      `Integration provider components are not supported by the \"${config.renderer.name}\" renderer.`,\n    );\n  }\n  const providerServerModules = generateFarmIntegrationProviderServerModules(\n    renderedIntegrationProviders,\n    config.root,\n    config.renderer.componentExtensions ?? [],\n  );\n  const resolvedIntegrationProviderFallback = Object.fromEntries(\n    Object.entries(config.integrations).flatMap(([name, integration]) => {\n      const configuredProviders = (integration as { providers?: unknown } | null)?.providers;\n      const providers = Array.isArray(configuredProviders) ? configuredProviders : [];\n      if (providers.some((provider) => typeof provider?.component === \"function\")) {\n        throw new Error(\n          `Integration provider components in production must use an importable component reference, for example component: { module: \"@/components/provider\" }.`,\n        );\n      }\n      return providers.length > 0 ? [[name, { providers }]] : [];\n    }),\n  );\n  const unsupportedIntegrationProvider = renderedIntegrationProviders.find(\n    (provider) => provider.supportsIsolatedHydration !== true,\n  );\n  const isolatedHydrationMode = resolveFarmIsolatedClientHydrationMode(\n    config.experimental?.isolatedClientHydration,\n    {\n      serverComponents: config.experimental?.serverComponents === true,\n      hasUnsupportedIntegrationProvider: Boolean(unsupportedIntegrationProvider),\n    },\n  );\n  const hydrationPlanOptions = getFarmClientHydrationPlanOptions(\n    config.renderer,\n    Boolean(unsupportedIntegrationProvider),\n  );\n  const layoutAppliesToRoute = (layoutPattern: string, routePattern: string) =>\n    layoutPattern === \"/\" ||\n    routePattern === layoutPattern ||\n    routePattern.startsWith(`${layoutPattern}/`);\n  const layoutHydrationPlans = layoutRoutes.map((layout) => ({\n    ...layout,\n    hydration: getCachedClientModuleHydrationPlan(\n      layout.modulePath,\n      config.root,\n      isolatedHydrationMode,\n      hydrationPlanCache,\n      hydrationPlanOptions,\n    ),\n  }));\n  const markdownPagePlan = createMarkdownPageHydrationPlanner(\n    resolveFarmMdxComponentsModulePath(resolveMdxConfig(config.mdx), config.root),\n    config.root,\n    isolatedHydrationMode,\n    hydrationPlanOptions,\n  );\n  const pageHydrationPlans = new Map(\n    pageRoutes.map((route) => [\n      route.modulePath,\n      isFarmMarkdownPageFile(route.modulePath)\n        ? markdownPagePlan()\n        : getCachedClientModuleHydrationPlan(\n            route.modulePath,\n            config.root,\n            isolatedHydrationMode,\n            hydrationPlanCache,\n            hydrationPlanOptions,\n          ),\n    ]),\n  );\n\n  enforceFarmIsolatedHydrationRouteBudget(\n    layoutHydrationPlans.map((layout) => ({\n      pattern: layout.pattern,\n      depth: layout.pattern.split(\"/\").filter(Boolean).length,\n      metadata: layout.hydration,\n    })),\n    pageRoutes.map((route) => ({\n      pattern: route.pattern,\n      depth: route.pattern.split(\"/\").filter(Boolean).length,\n      metadata: pageHydrationPlans.get(route.modulePath)!,\n    })),\n    layoutAppliesToRoute,\n  );\n  const providerServerImports = [\n    providerServerModules.hasClerkProvider\n      ? `import { ClerkProvider as FarmClerkProvider } from \"@clerk/react\";`\n      : \"\",\n    providerServerModules.imports,\n  ]\n    .filter(Boolean)\n    .join(\"\\n\");\n\n  // Generate imports for all API routes\n  const apiImports: string[] = [];\n  const apiRegistrations: string[] = [];\n\n  apiRoutes.forEach((route, index) => {\n    if (!route.filePath) return;\n    const varName = `apiRoute${index}`;\n    apiImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(route.filePath)};`,\n    );\n    apiRegistrations.push(`\n  {\n    path: ${JSON.stringify(route.path)},\n    methods: ${JSON.stringify(route.methods.filter((method) => !route.pluginMethods?.includes(method)))},\n    endpoints: ${varName},\n  }`);\n  });\n\n  // Generate imports for all page routes\n  const pageImports: string[] = [];\n  const pageRegistrations: string[] = [];\n  const hasMarkdownPages = pageRoutes.some((route) => route.source !== undefined);\n  // Order with the shared route-specificity contract, not a local score. An\n  // additive per-segment score is not equivalent to the segment-wise comparison\n  // the route manager and the generated client matcher use, so the two ranked\n  // some patterns differently and the same build could serve one page on first\n  // load and another after a client navigation.\n  const orderedPageRoutes = pageRoutes\n    .map((route, index) => ({ route, index }))\n    .sort((left, right) => {\n      const order = compareRoutePatternSpecificity(left.route.pattern, right.route.pattern);\n      return order || left.index - right.index;\n    })\n    .map(({ route }) => route);\n\n  orderedPageRoutes.forEach((route, index) => {\n    const varName = `pageRoute${index}`;\n    if (isFarmMarkdownPageFile(route.modulePath)) {\n      pageRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(route.pattern)},\n    module: createFarmMarkdownRouteModule({\n      source: ${JSON.stringify(route.source ?? \"\")},\n      filePath: ${JSON.stringify(toBakedMarkdownSourcePath(config.root, route.modulePath))},\n      components: farmMdxComponents,\n      config: farmMdxConfig,\n    }),\n    markdownSource: {\n      source: ${JSON.stringify(route.source ?? \"\")},\n      filePath: ${JSON.stringify(\n        toBakedMarkdownSourcePath(config.root, route.markdownSourcePath ?? route.modulePath),\n      )},\n    },\n  }`);\n      return;\n    }\n\n    pageImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(route.modulePath)};`,\n    );\n    const clientMetadata = pageHydrationPlans.get(route.modulePath)!;\n    // Directives are parsed from source at build time; the runtime only sees\n    // module exports, so the parsed form must ride the registration for\n    // \\\"use ssg; 60\\\" routes to keep their ISR cache headers in production.\n    const renderingDirective = parseRouteRenderingDirectiveFromDisk(route.modulePath);\n    pageRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(route.pattern)},\n    module: ${varName},\n    shouldHydrate: ${JSON.stringify(clientMetadata.shouldHydrate)},\n    islandStrategy: ${JSON.stringify(clientMetadata.islandStrategy)},${\n      renderingDirective ? `\\n    rendering: ${JSON.stringify(renderingDirective)},` : \"\"\n    }\n    ${\n      route.source !== undefined\n        ? `markdownSource: {\n      source: ${JSON.stringify(route.source)},\n      filePath: ${JSON.stringify(toBakedMarkdownSourcePath(config.root, route.markdownSourcePath))},\n    },`\n        : \"\"\n    }\n  }`);\n  });\n\n  // Generate imports for all layouts\n  const layoutImports: string[] = [];\n  const layoutRegistrations: string[] = [];\n\n  layoutHydrationPlans.forEach((layout, index) => {\n    const varName = `layoutRoute${index}`;\n    const clientMetadata = layout.hydration;\n    layoutImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(layout.modulePath)};`,\n    );\n    layoutRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(layout.pattern)},\n    module: ${varName},\n    shouldHydrate: ${JSON.stringify(clientMetadata.shouldHydrate)},\n    islandStrategy: ${JSON.stringify(clientMetadata.islandStrategy)},\n  }`);\n  });\n\n  // Prepare shared slot owners at build time. Root owners already have a\n  // constant-time check. Do not emit caching for empty or unique-owner manifests.\n  const slotOwnerCounts = new Map(routeSlots.map((slot) => [slot.ownerPattern, 0]));\n  for (const slot of routeSlots) {\n    slotOwnerCounts.set(slot.ownerPattern, (slotOwnerCounts.get(slot.ownerPattern) ?? 0) + 1);\n  }\n  const sharedSlotOwners = new Set(\n    [...slotOwnerCounts]\n      .filter(([owner, count]) => owner !== \"/\" && count > 1)\n      .map(([owner]) => owner),\n  );\n\n  const routeSlotImports: string[] = [];\n  const routeSlotRegistrations: string[] = [];\n  routeSlots.forEach((slot, index) => {\n    const varName = `routeSlot${index}`;\n    routeSlotImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(slot.modulePath)};`,\n    );\n    routeSlotRegistrations.push(`\n  {\n    name: ${JSON.stringify(slot.name)},\n    ownerPattern: ${JSON.stringify(slot.ownerPattern)},\n    pattern: ${JSON.stringify(slot.pattern)},\n    containerId: ${JSON.stringify(slot.containerId)},\n    interception: ${JSON.stringify(slot.interception)},\n    fallback: ${JSON.stringify(slot.fallback)},\n    module: ${varName},\n  }`);\n  });\n\n  // Generate imports for route-level error boundaries.\n  const errorImports: string[] = [];\n  const errorRegistrations: string[] = [];\n\n  errorRoutes.forEach((errorRoute, index) => {\n    const varName = `errorRoute${index}`;\n    errorImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(errorRoute.modulePath)};`,\n    );\n    errorRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(errorRoute.pattern)},\n    module: ${varName},\n  }`);\n  });\n\n  const metadataImageImports: string[] = [];\n  const metadataImageRegistrations: string[] = [];\n\n  metadataImageRoutes.forEach((image, index) => {\n    if (image.sourceType === \"module\" && image.modulePath) {\n      const varName = `metadataImageRoute${index}`;\n      metadataImageImports.push(\n        `import * as ${varName} from ${toVirtualEntryImportSpecifier(image.modulePath)};`,\n      );\n      metadataImageRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(image.pattern)},\n    kind: ${JSON.stringify(image.kind)},\n    fileName: ${JSON.stringify(image.fileName)},\n    sourceType: \"module\",\n    module: ${varName},\n  }`);\n      return;\n    }\n\n    metadataImageRegistrations.push(`  ${JSON.stringify(image)}`);\n  });\n\n  const applicationMetadataImports: string[] = [];\n  const applicationMetadataRegistrations: string[] = [];\n  applicationMetadataRoutes.forEach((metadata, index) => {\n    const varName = `applicationMetadataRoute${index}`;\n    applicationMetadataImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(metadata.modulePath)};`,\n    );\n    applicationMetadataRegistrations.push(`\n  {\n    pattern: ${JSON.stringify(metadata.pattern)},\n    kind: ${JSON.stringify(metadata.kind)},\n    outputName: ${JSON.stringify(metadata.outputName)},\n    module: ${varName},\n  }`);\n  });\n\n  // Generate imports for all app middleware files\n  const middlewareImports: string[] = [];\n  const middlewareRegistrations: string[] = [];\n\n  middlewareRoutes.forEach((middlewareRoute, index) => {\n    const varName = `fileMiddleware${index}`;\n    middlewareImports.push(\n      `import * as ${varName} from ${toVirtualEntryImportSpecifier(middlewareRoute.filePath)};`,\n    );\n    middlewareRegistrations.push(`\n  {\n    path: ${JSON.stringify(middlewareRoute.path)},\n    filePath: ${JSON.stringify(middlewareRoute.filePath)},\n    module: ${varName},\n  }`);\n  });\n\n  // Generate import for custom not-found page if exists\n  const notFoundImport = notFoundPath\n    ? `import * as CustomNotFound from ${toVirtualEntryImportSpecifier(notFoundPath)};`\n    : \"\";\n  const apiRouteHelpersImport =\n    apiRoutes.length > 0\n      ? `import { mergePluginAPIRoutes, getAllowedAPIRouteMethods, invokeAPIRouteEndpoint, createStaticAPIRouteMatcherAtBasePath, resolveAPIRouteEndpoint } from \"@farm.js/core/api/runtime\";`\n      : \"\";\n  const productionRuntimeImport = `import {\n  _runWithAfterRequest,\n  _runWithCurrentRequest,\n  _runWithAPIRequestRuntime,\n  _runWithMiddlewareContext,\n  _runWithMiddlewareData,\n  _setDefaultFarmThemeConfig,\n  addMetadataImageReference,\n  addMetadataMarkdownAlternate,\n  appendFarmRedirectQuery,\n  applyFarmBasePath,\n  applyFarmCspNonceToResponse,\n  applyFarmPreviewRobotsTag,\n  applyFarmThemeDocument,\n  appendFarmLinkHeader,\n  applyProductionMiddlewareHeaders,\n  configureFarmCache,\n  configureFarmObservability,\n  cloneFarmRequestWithContext,\n  createDefaultErrorMarkup,\n  createFarmInstrumentationLifecycle,\n  createFarmLayoutSelector,\n  createFarmCacheKey,\n  createFarmMetadataRouteResponse,\n  createFarmAgentRobots,\n  collectFarmLlmsTxtPages,\n  createFarmDefaultLlmsTxt,\n  createFarmLlmsMarkdownReader,\n  renderFarmLlmsFullTxt,\n  createFarmThemeDocumentParts,\n  createFarmLocaleCookie,\n  createFarmProductionLifecycle,\n  createFarmNodeRequestAbortSignal,\n  createProductionMiddlewareRunner,\n  getTheme as getFarmTheme,\n  emitFarmEvent,\n  getFarmDataCache,\n  getFarmLocaleVaryHeaders,\n  getFarmRedirectError,\n  getDefaultErrorStatusText,\n  isFarmNotFoundError,\n  isFarmRedirectError,\n  localizeFarmHref,\n  manageFarmDocumentPreloads,\n  mergeRouteRenderingDirectiveConfig,\n  manageFarmLinkHeaderPreloads,\n  mergeMetadata,\n  matchesFarmIfNoneMatch,\n  normalizeRevalidatePath,\n  reportFarmPreloadWarnings,\n  renderFarmLocaleAlternateLinks,\n  renderMetadataHead,\n  resolveFarmNotFoundMetadata,\n  resolveFarmRouteContext,\n  resolveFarmTrailingSlashRedirect,\n  resolveDefaultErrorStatus,\n  resolveFarmSecurityConfig,\n  resolveFarmInstrumentationRuntime,\n  resolveFarmPreviewDeployment,\n  resolveFarmWebRequestOrigin,\n  runWithFarmRequestSpan,\n  searchParamsToObject,\n  setFarmBasePath,\n  setFarmTrailingSlashPreference,\n  stripFarmBasePath,\n  stripFarmLocaleFromPathname,\n  withFarmRouteContext,\n  createLateNotFoundRecovery,\n  createLateRedirectRecovery,\n} from \"@farm.js/core/internal/production-runtime\";`;\n  const productionSiteTelemetryImport = config.telemetry\n    ? `import { createFarmProductionSiteReporter } from \"@farm.js/core/internal/product-telemetry-runtime\";`\n    : \"\";\n  const metadataImageRuntimeImport = hasGeneratedMetadataImages\n    ? `import { createFarmMetadataImageResponse } from \"@farm.js/core/internal/metadata-image-runtime\";`\n    : \"\";\n  const pluginRuntimeImport = hasPluginRuntime\n    ? `import { PluginManager } from \"@farm.js/core/plugin\";`\n    : \"\";\n  // A server with a plugin runtime gets the plugin (it also correlates MCP tool calls).\n  // Without one, a direct recorder avoids importing the plugin runtime.\n  const infraAnalyticsImport = hasInfraAnalyticsRuntime\n    ? `import { ${hasPluginRuntime ? \"createFarmInfraAnalyticsPlugin\" : \"createFarmInfraAnalyticsRecorder\"} } from \"@farm.js/core/internal/infra-analytics-runtime\";`\n    : \"\";\n  const compressionRuntimeImport = hasCompressionRuntime\n    ? `import { compressFarmResponse${hasPluginRuntime ? \", createCompressionPlugin\" : \"\"} } from \"@farm.js/core/internal/compression-runtime\";`\n    : \"\";\n  const i18nServerImport = config.i18n.enabled\n    ? `import { _runWithFarmI18nRequest, _setDefaultFarmI18nRuntime, createFarmI18nRuntime, getFarmI18nClientSnapshot } from \"@farm.js/core/i18n/server\";`\n    : \"\";\n  const docsHandlerImport = config.docs?.enabled\n    ? hasPrecompiledDocs\n      ? `import { createFarmDocsPrecompiledRuntime } from \"@farm.js/core/internal/docs-precompiled-runtime\";\nconst isFarmDocsAPIRequest = (requestOrPathname) => {\n  const pathname = typeof requestOrPathname === \"string\"\n    ? requestOrPathname\n    : new URL(requestOrPathname.url).pathname;\n  const apiPath = ${JSON.stringify(farmDocsPrecompiledManifest?.apiPath || \"/api/docs\")};\n  return pathname === apiPath || pathname.startsWith(apiPath + \"/\");\n};`\n      : adapterOwnsDocsRuntime\n        ? `import { isFarmDocsAPIRequest } from \"@farm.js/core/docs\";\nimport { createFarmDocsRuntimeHandler as createFarmDocsAdapterRuntimeHandler } from ${JSON.stringify(config.docs.adapter!.server)};\nimport * as FarmDocsAdapterReact from ${JSON.stringify(config.docs.adapter!.react)};`\n        : `import { createFarmDocsAPIHandler, createFarmDocsHandler, isFarmDocsAPIRequest } from \"@farm.js/core/docs\";`\n    : \"\";\n  const docsFontImport =\n    config.docs?.enabled && !hasPrecompiledDocs\n      ? `import { resolveFarmLayoutFonts } from \"@farm.js/core/font\";`\n      : \"\";\n  const docsRuntimeImport =\n    config.docs?.enabled && !hasPrecompiledDocs\n      ? `import { existsSync as farmDocsExistsSync } from \"node:fs\";\nimport { dirname as farmDocsDirname, join as farmDocsJoin } from \"node:path\";\nimport { fileURLToPath as farmDocsFileURLToPath } from \"node:url\";`\n      : \"\";\n  const markdownHandlerImport = config.md?.enabled\n    ? `import { applyMarkdownNegotiationHeaders, createMarkdownMirrorResponse, getFarmMarkdownAlternatePath } from \"@farm.js/core/markdown\";`\n    : \"\";\n  const appMarkdownImport = hasMarkdownPages\n    ? `import { createFarmMarkdownRouteModule, createFarmMarkdownSourceResponse } from \"@farm.js/core/internal/app-markdown-runtime\";`\n    : \"const createFarmMarkdownSourceResponse = null;\";\n  // Always available: agents can request Markdown on any route, so the\n  // Markdown error body is not gated on the app having Markdown page files.\n  // Use the response-only module so TSX apps do not bundle the MDX compiler.\n  const markdownErrorImport = `import { FARM_MARKDOWN_CONTENT_TYPE, createFarmMarkdownErrorBody, farmRequestWantsMarkdown } from \"@farm.js/core/markdown\";`;\n  const mdxComponentsPath =\n    typeof config.mdx?.components === \"string\"\n      ? path.isAbsolute(config.mdx.components)\n        ? config.mdx.components\n        : path.join(config.root, config.mdx.components)\n      : null;\n  const mdxComponentsImport = mdxComponentsPath\n    ? `import * as FarmMdxComponentsModule from ${toVirtualEntryImportSpecifier(mdxComponentsPath)};`\n    : \"\";\n  const layerConfigPaths = (config.layers || [])\n    .map((layer) => layer.configFile)\n    .filter((configFile): configFile is string => Boolean(configFile))\n    .filter((configFile) => configFile !== configModulePath);\n  const layerConfigImports = layerConfigPaths\n    .map(\n      (configFile, index) =>\n        `import * as FarmLayerConfigModule${index} from ${toVirtualEntryImportSpecifier(configFile)};`,\n    )\n    .join(\"\\n\");\n  const layerConfigValues = layerConfigPaths.map(\n    (_configFile, index) =>\n      `(FarmLayerConfigModule${index}.default || FarmLayerConfigModule${index})`,\n  );\n  const integrationRuntimeExports = Array.from(\n    new Set([\n      ...(hasServerRuntimeIntegrations\n        ? [\"dispatchIntegrationRequests\", \"matchIntegrationRoute\"]\n        : []),\n      ...(hasRuntimeIntegrationConfig\n        ? [\"getRegisteredIntegrationAPIManifest\", \"resolveIntegrationPlugins\"]\n        : []),\n    ]),\n  );\n  const integrationRuntimeImport = integrationRuntimeExports.length\n    ? `import { ${integrationRuntimeExports.join(\", \")} } from \"@farm.js/core/integrations\";`\n    : \"\";\n  const instrumentationImport = instrumentationPath\n    ? `import * as FarmInstrumentationModule from ${toVirtualEntryImportSpecifier(instrumentationPath)};`\n    : \"\";\n  const nativeAuth = generateNativeAuthIntegrationSource(config.auth);\n  const nativeMCP = generateNativeMCPPluginSource(config.mcp);\n  const integrationImports = `\n${configModulePath ? `import * as FarmUserConfigModule from ${toVirtualEntryImportSpecifier(configModulePath)};` : \"\"}\n${layerConfigImports}\n${integrationRuntimeImport}\n${nativeAuth.importSource}\n${nativeMCP.importSource}\n`;\n  const imageRuntime = resolveImageRuntime(config, preset);\n  const imageRuntimeImport =\n    imageRuntime === \"none\"\n      ? \"\"\n      : `import { createCloudflareImageTransformer, createFarmImageHandler } from \"@farm.js/core/image/server\";`;\n  const imageNodeRuntimeImport =\n    imageRuntime === \"node\"\n      ? `import { createNodeImageFetcher, createNodeImageUrlValidator, createSharpImageTransformer } from \"@farm.js/core/image/sharp\";`\n      : \"\";\n  const apiHandlerCode =\n    apiRoutes.length > 0\n      ? `\nconst matchBuiltAPIRoute = createStaticAPIRouteMatcherAtBasePath(apiRoutes, farmLocalAPIBasePath);\n\nfunction matchLocalAPIRequest(request) {\n  return matchBuiltAPIRoute(new URL(request.url).pathname);\n}\n\nasync function handleAPIRequest(request) {\n  const url = new URL(request.url);\n  const method = request.method.toUpperCase();\n  const match = matchLocalAPIRequest(request);\n\n  if (!match) {\n    return null;\n  }\n\n  const { route, params } = match;\n  const startedAt = Date.now();\n  emitFarmEvent({ type: \"route.matched\", pathname: url.pathname, route: route.path });\n  emitFarmEvent({\n    type: \"api.request.start\",\n    pathname: url.pathname,\n    route: route.path,\n    method,\n  });\n  const endpoint = resolveAPIRouteEndpoint(route, method);\n  if (!endpoint) {\n    const response = new Response(\n      JSON.stringify({ error: \"Method Not Allowed\" }),\n      {\n        status: 405,\n        headers: {\n          \"Allow\": getAllowedAPIRouteMethods(route).join(\", \"),\n          \"Content-Type\": \"application/json\",\n        },\n      }\n    );\n    emitFarmEvent({\n      type: \"api.request.complete\",\n      pathname: url.pathname,\n      route: route.path,\n      method,\n      status: response.status,\n      durationMs: Date.now() - startedAt,\n    });\n    return response;\n  }\n\n  try {\n    const response = await invokeAPIRouteEndpoint(\n      endpoint,\n      request,\n      params,\n      farmServerConfig.bodySizeLimit,\n    );\n    emitFarmEvent({\n      type: \"api.request.complete\",\n      pathname: url.pathname,\n      route: route.path,\n      method,\n      status: response.status,\n      durationMs: Date.now() - startedAt,\n    });\n    return response;\n  } catch (error) {\n    emitFarmEvent({\n      type: \"api.error\",\n      pathname: url.pathname,\n      route: route.path,\n      method,\n      durationMs: Date.now() - startedAt,\n      error,\n    });\n    console.error(\\`[API Error] \\${url.pathname}:\\`, error);\n    return new Response(\n      JSON.stringify({ error: \"Internal Server Error\" }),\n      { status: 500, headers: { \"Content-Type\": \"application/json\" } }\n    );\n  }\n}\n`\n      : `\nfunction matchLocalAPIRequest(_request) {\n  return null;\n}\n\nasync function handleAPIRequest(request) {\n  return null;\n}\n`;\n\n  return `\n// Farm.js SSR Entry - Generated at build time\n// All routes are bundled here, managers are created at runtime\n\n${apiImports.join(\"\\n\")}\n${pageImports.join(\"\\n\")}\n${layoutImports.join(\"\\n\")}\n${routeSlotImports.join(\"\\n\")}\n${errorImports.join(\"\\n\")}\n${metadataImageImports.join(\"\\n\")}\n${applicationMetadataImports.join(\"\\n\")}\n${middlewareImports.join(\"\\n\")}\n${notFoundImport}\n${apiRouteHelpersImport}\n${productionRuntimeImport}\n${productionSiteTelemetryImport}\n${metadataImageRuntimeImport}\n${pluginRuntimeImport}\n${infraAnalyticsImport}\n${compressionRuntimeImport}\n${i18nServerImport}\n${docsHandlerImport}\n${docsFontImport}\n${docsRuntimeImport}\n${markdownHandlerImport}\n${appMarkdownImport}\n${markdownErrorImport}\n${mdxComponentsImport}\n${integrationImports}\n${providerServerImports}\n${instrumentationImport}\n${imageRuntimeImport}\n${imageNodeRuntimeImport}\nimport { farmFontPreloadHeader } from \"virtual:farm-font-runtime\";\nimport { isFarmRouteActive } from \"@farm.js/core/router\";\n${rendererServerImports}\n\n${routeClientGraphServerRuntime}\n\nconst farmRendererStreamingCapabilities = ${JSON.stringify(rendererStreamingCapabilities)};\nconst farmRendererName = ${JSON.stringify(config.renderer.name)};\nconst farmRendererRuntime = ${JSON.stringify(getFarmPresetRuntime(preset))};\nconst farmRendererRuntimeStreamingCapabilities = ReactDOMServer.capabilities &&\n  ReactDOMServer.capabilities.streaming;\nif (farmRendererRuntimeStreamingCapabilities &&\n    ((farmRendererStreamingCapabilities.node && !farmRendererRuntimeStreamingCapabilities.node) ||\n     (farmRendererStreamingCapabilities.web && !farmRendererRuntimeStreamingCapabilities.web))) {\n  throw new Error(\n    \"Renderer \" + farmRendererName +\n    \" server module streaming capabilities do not satisfy the descriptor for the \" +\n    farmRendererRuntime + \" runtime.\"\n  );\n}\nif (farmRendererStreamingCapabilities.node &&\n    typeof ReactDOMServer.renderToPipeableStream !== \"function\") {\n  throw new Error(\n    \"Renderer \" + farmRendererName + \" advertises Node streaming for the \" +\n    farmRendererRuntime + \" runtime but its server module does not export \" +\n    \"renderToPipeableStream().\"\n  );\n}\nif (farmRendererStreamingCapabilities.web &&\n    typeof ReactDOMServer.renderToReadableStream !== \"function\") {\n  throw new Error(\n    \"Renderer \" + farmRendererName + \" advertises Web streaming for the \" +\n    farmRendererRuntime + \" runtime but its server module does not export \" +\n    \"renderToReadableStream().\"\n  );\n}\n\nconst farmPreloadConfig = ${JSON.stringify(config.performance.preload)};\nconst farmProductionSiteTelemetry = ${\n    config.telemetry\n      ? `createFarmProductionSiteReporter({\n  renderer: ${JSON.stringify(config.renderer.name)},\n  deployTarget: ${JSON.stringify(config.deploy.target || \"custom\")},\n})`\n      : \"null\"\n  };\n\n// Custom 404 page component (if provided)\nconst hasCustomNotFound = ${notFoundPath ? \"true\" : \"false\"};\nconst CustomNotFoundComponent = ${notFoundPath ? \"CustomNotFound.default || CustomNotFound\" : \"null\"};\nconst CustomNotFoundModule = ${notFoundPath ? \"CustomNotFound\" : \"null\"};\nconst farmUserConfig = ${\n    configModulePath ? \"(FarmUserConfigModule.default || FarmUserConfigModule)\" : \"null\"\n  };\nconst farmRuntimeConfigs = [${[...layerConfigValues, \"farmUserConfig\"].join(\", \")}].filter(Boolean);\nconst farmResolvedRuntimeConfig = Object.assign({}, ...farmRuntimeConfigs);\n\nfunction FarmDefault404Page() {\n  return React.createElement(React.Fragment, null,\n    React.createElement(\"style\", null, ${JSON.stringify(DEFAULT_NOT_FOUND_STYLES)}),\n    React.createElement(\"main\", {\n      className: \"farm-default-not-found\",\n      \"aria-labelledby\": \"farm-default-not-found-title\",\n      \"aria-describedby\": \"farm-default-not-found-description\",\n    },\n      React.createElement(\"div\", { className: \"farm-default-not-found__content\" },\n        React.createElement(\"h1\", {\n          id: \"farm-default-not-found-title\",\n          className: \"farm-default-not-found__code\",\n        }, \"404\"),\n        React.createElement(\"p\", {\n          id: \"farm-default-not-found-description\",\n          className: \"farm-default-not-found__description\",\n        }, \"Not found\"),\n        React.createElement(\"a\", {\n          className: \"farm-default-not-found__home\",\n          href: applyFarmBasePath(\"/\", farmResolvedRuntimeConfig.basePath),\n        }, \"GO HOME\")\n      )\n    )\n  );\n}\n\n/** The app's not-found page, or Farm's, without layouts. */\nfunction createFarmNotFoundElement(pathname) {\n  const NotFoundPage = hasCustomNotFound && CustomNotFoundComponent ? CustomNotFoundComponent : FarmDefault404Page;\n  return React.createElement(NotFoundPage, { pathname: pathname });\n}\n${nativeMCP.registerSource}\n// Config middleware from layers is appended in layer order ahead of the\n// project's, the same merge development applies (mergeFarmLayerConfig).\n// Object.assign above would keep only the last config's middleware.\nconst farmMiddlewareConfig = farmRuntimeConfigs.reduce((merged, runtimeConfig) => {\n  const value = runtimeConfig?.middleware;\n  if (value === undefined) return merged;\n  if (merged === undefined) return value;\n  const toList = (entry) => (entry == null ? [] : Array.isArray(entry) ? entry : [entry]);\n  return [...toList(merged), ...toList(value)];\n}, undefined);\nsetFarmBasePath(${JSON.stringify(config.basePath)});\nsetFarmTrailingSlashPreference(${JSON.stringify(config.trailingSlash)});\nconst hasConfiguredRouteContext = typeof farmResolvedRuntimeConfig.context === \"function\";\nconst configuredIntegrations = ${JSON.stringify(resolvedIntegrationProviderFallback)};\nfor (const runtimeConfig of farmRuntimeConfigs) {\n  for (const [name, integration] of Object.entries(runtimeConfig.integrations || {})) {\n    const fallback = configuredIntegrations[name];\n    configuredIntegrations[name] =\n      fallback?.providers &&\n      integration &&\n      typeof integration === \"object\" &&\n      integration.providers === undefined\n        ? { ...integration, providers: fallback.providers }\n        : integration;\n  }\n}\n${nativeAuth.registerSource}\n${providerServerModules.helpers}\nconst farmIntegrationProviderModuleComponents = new Map([\n${providerServerModules.entries}\n]);\n\nfunction wrapWithFarmIntegrationProviders(element) {\n  const providers = Object.values(configuredIntegrations).flatMap(function(integration) {\n    return Array.isArray(integration?.providers) ? integration.providers : [];\n  });\n  let wrapped = element;\n  for (let index = providers.length - 1; index >= 0; index--) {\n    const provider = providers[index];\n    let Component = null;\n    if (typeof provider.component === \"function\") {\n      Component = provider.component;\n    } else if (provider.component?.module) {\n      const componentKey = provider.component.module + \"\\\\0\" + (provider.component.export || \"default\");\n      Component = farmIntegrationProviderModuleComponents.get(componentKey);\n    } else if (provider.type === \"clerk\") {\n      Component = ${providerServerModules.hasClerkProvider ? \"FarmClerkProvider\" : \"null\"};\n    }\n    if (!Component) {\n      if (!provider.component && provider.type !== \"clerk\") continue;\n      throw new Error(\"Integration provider \" + provider.name + \" did not export its configured component.\");\n    }\n    wrapped = React.createElement(Component, provider.props || {}, wrapped);\n  }\n  return wrapped;\n}\nconst serverRuntimeIntegrations = Object.fromEntries(\n  Object.entries(configuredIntegrations).filter(([, integration]) =>\n    integration && typeof integration === \"object\" && integration.serverRuntime !== false\n  ),\n);\nconst integrationRuntimeConfig = Object.assign({}, ...farmRuntimeConfigs, {\n  integrations: configuredIntegrations,\n});\nconst farmInfraAnalytics = ${\n    hasInfraAnalyticsRuntime\n      ? hasPluginRuntime\n        ? \"createFarmInfraAnalyticsPlugin()\"\n        : \"createFarmInfraAnalyticsRecorder()\"\n      : \"null\"\n  };\nconst configuredPlugins = [\n  ${hasCompressionRuntime && hasPluginRuntime ? \"createCompressionPlugin(),\" : \"\"}\n  ${hasRuntimeIntegrationConfig ? \"...resolveIntegrationPlugins(serverRuntimeIntegrations),\" : \"\"}\n  ${nativeMCP.pluginSource}\n  ${\n    hasConfiguredRuntimePlugins\n      ? `...farmRuntimeConfigs.flatMap((runtimeConfig) =>\n    Array.isArray(runtimeConfig.plugins) ? runtimeConfig.plugins : [],\n  ),`\n      : \"\"\n  }\n  ${hasInfraAnalyticsRuntime && hasPluginRuntime ? \"...(farmInfraAnalytics ? [farmInfraAnalytics] : []),\" : \"\"}\n];\nconst farmPluginRuntime = ${\n    hasPluginRuntime\n      ? `configuredPlugins.length > 0\n  ? (() => {\n      const manager = new PluginManager({\n        config: { ...(farmUserConfig || {}), basePath: ${JSON.stringify(config.basePath)} },\n        isDev: false,\n        isProd: true,\n      });\n      manager.addPlugins(configuredPlugins);\n      return manager;\n    })()\n  : null`\n      : \"null\"\n  };\nconst hasFarmPluginHTMLTransforms = configuredPlugins.some(\n  (plugin) => plugin.render?.html || plugin.afterRender || plugin.transformHTML,\n);\nconst farmImageHandler = ${\n    imageRuntime === \"none\"\n      ? \"null\"\n      : imageRuntime === \"cloudflare\"\n        ? `createFarmImageHandler(${JSON.stringify(config.images)}, {\n  transform: createCloudflareImageTransformer(),\n  onError(error) { console.error(\"[Farm Image]\", error); },\n})`\n        : `createFarmImageHandler(${JSON.stringify(config.images)}, {\n  transform: createSharpImageTransformer(),\n  fetchRemote: createNodeImageFetcher(${JSON.stringify(config.images)}),\n  validateRemoteUrl: createNodeImageUrlValidator(${JSON.stringify(config.images)}),\n  onError(error) { console.error(\"[Farm Image]\", error); },\n})`\n  };\nconst farmMarkdownConfig = ${JSON.stringify(config.md)};\nconst farmLlmsTxtConfig = ${JSON.stringify(config.agent?.llmsTxt ?? { enabled: false, include: [], exclude: [] })};\n${servesAgentRobotsTxt ? `const farmAgentCrawlers = ${JSON.stringify(config.agent.crawlers)};` : \"\"}\nconst farmMdxConfig = ${JSON.stringify({\n    ...config.mdx,\n    components: typeof config.mdx?.components === \"string\" ? config.mdx.components : undefined,\n  })};\nconst configuredFarmMdxComponents = farmUserConfig?.mdx?.components;\n${\n  config.agent?.noindexPreviews\n    ? `// agent.noindexPreviews: the runtime environment decides, falling back to the\n// environment this was built in, since Netlify exposes its deploy context only\n// to the build.\nconst farmNoindexPreview = resolveFarmPreviewDeployment(\n  globalThis.process?.env,\n  ${JSON.stringify(isFarmPreviewDeploymentEnvironment(process.env))},\n);`\n    : \"\"\n}\nconst farmMdxComponents = ${\n    mdxComponentsPath\n      ? `(FarmMdxComponentsModule.components || Reflect.get(FarmMdxComponentsModule, \"default\") || {})`\n      : `(configuredFarmMdxComponents && typeof configuredFarmMdxComponents === \"object\" ? configuredFarmMdxComponents : {})`\n  };\nconst farmObservabilityConfig = farmUserConfig?.observability ?? ${JSON.stringify(\n    config.observability ?? false,\n  )};\nconfigureFarmObservability(farmObservabilityConfig);\nconfigureFarmCache(farmResolvedRuntimeConfig.cache);\nconst farmI18nConfig = ${JSON.stringify(config.i18n)};\nconst farmServerConfig = ${JSON.stringify(config.server)};\nconst farmThemeConfig = ${JSON.stringify(config.theme)};\nconst farmSecurityConfig = resolveFarmSecurityConfig(${JSON.stringify(config.security)});\n_setDefaultFarmThemeConfig(farmThemeConfig);\nconst farmInstrumentationLifecycle = createFarmInstrumentationLifecycle(\n  ${instrumentationPath ? \"FarmInstrumentationModule\" : \"null\"},\n  {\n    root:\n      typeof globalThis.process?.cwd === \"function\" ? globalThis.process.cwd() : \".\",\n    mode: \"production\",\n    runtime: resolveFarmInstrumentationRuntime(${JSON.stringify(preset)}),\n  },\n);\nexport const farmProductionLifecycle = createFarmProductionLifecycle({\n  server: farmServerConfig,\n  start: async () => {\n    await farmInstrumentationLifecycle.start();\n    try {\n      await farmPluginRuntime?.startRuntime();\n    } catch (error) {\n      await farmInstrumentationLifecycle.shutdown();\n      throw error;\n    }\n  },\n  close: async (reason) => {\n    try {\n      await farmPluginRuntime?.closeRuntime(reason);${\n        hasInfraAnalyticsRuntime && !hasPluginRuntime\n          ? \"\\n      await farmInfraAnalytics?.close();\"\n          : \"\"\n      }\n    } finally {\n      await farmInstrumentationLifecycle.shutdown();\n    }\n  },\n});\nconst farmI18nRuntime = ${\n    config.i18n.enabled\n      ? `createFarmI18nRuntime(farmI18nConfig, ${JSON.stringify(i18nCatalogs)})`\n      : \"null\"\n  };\n${config.i18n.enabled ? \"_setDefaultFarmI18nRuntime(farmI18nRuntime);\" : \"\"}\nconst farmDocsBundledContentDir = ${\n    config.docs?.enabled && !hasPrecompiledDocs\n      ? `(() => {\n  try {\n    const currentDir = farmDocsDirname(farmDocsFileURLToPath(import.meta.url));\n    const candidates = [\n      farmDocsJoin(currentDir, \"farm-docs-content\"),\n      farmDocsJoin(currentDir, \"..\", \"farm-docs-content\"),\n      farmDocsJoin(currentDir, \"..\", \"..\", \"farm-docs-content\"),\n    ];\n    return candidates.find((candidate) => farmDocsExistsSync(candidate)) || null;\n  } catch {\n    return null;\n  }\n})()`\n      : \"null\"\n  };\nconst farmDocsResolvedConfig = ${generateFarmDocsRuntimeConfigExpression(config.docs, hasPrecompiledDocs)};\nconst farmDocsRuntimeRoot = ${hasPrecompiledDocs ? '\".\"' : `farmDocsBundledContentDir || ${JSON.stringify(config.root)}`};\nglobalThis.__FARM_DOCS_RUNTIME_CONFIG__ = {\n  root: farmDocsRuntimeRoot,\n  srcDir: ${JSON.stringify(config.srcDir)},\n  docs: farmDocsResolvedConfig,\n};\nconst farmDocsPrecompiledRuntime = ${\n    hasPrecompiledDocs\n      ? `createFarmDocsPrecompiledRuntime(${JSON.stringify(farmDocsPrecompiledManifest)})`\n      : \"null\"\n  };\nconst farmDocsHandler = ${\n    config.docs?.enabled\n      ? hasPrecompiledDocs\n        ? \"farmDocsPrecompiledRuntime.handleDocsRequest\"\n        : adapterOwnsDocsRuntime\n          ? `createFarmDocsAdapterRuntimeHandler({\n  ...farmDocsResolvedConfig.config,\n  entry: farmDocsResolvedConfig.config?.entry || String(farmDocsResolvedConfig.entry || \"/docs\").replace(/^\\\\/+|\\\\/+$/g, \"\") || \"docs\",\n  docsPath: farmDocsResolvedConfig.entry,\n  contentDir: farmDocsResolvedConfig.contentDir || farmDocsResolvedConfig.config?.contentDir,\n}, {\n  rootDir: farmDocsRuntimeRoot,\n  clientEntry: \"/__farm_client_js_src__\",\n  stylesheets: [\"/farm-fonts.css\", \"/__farm_client_css_href__\"],\n  resolveLayoutFonts: (pathname) =>\n    resolveFarmLayoutFonts(\n      getApplicableLayouts(getFarmRoutePathname(pathname)).map((layout) => layout.module),\n    ),\n  loadReactModule: async () => FarmDocsAdapterReact,\n})`\n          : `createFarmDocsHandler(farmDocsResolvedConfig, {\n  root: farmDocsRuntimeRoot,\n  srcDir: ${JSON.stringify(config.srcDir)},\n  clientEntry: \"/__farm_client_js_src__\",\n  fontAssets: ${JSON.stringify(farmDocsFontAssets)},\n  resolveLayoutFonts: (pathname) =>\n    resolveFarmLayoutFonts(\n      getApplicableLayouts(getFarmRoutePathname(pathname)).map((layout) => layout.module),\n    ),\n  fontStylesheetHref: \"/farm-fonts.css\",\n  globalStylesheetHref: \"/assets/globals.css\",\n})`\n      : \"null\"\n  };\nconst farmDocsAPIHandler = ${\n    config.docs?.enabled\n      ? hasPrecompiledDocs\n        ? \"farmDocsPrecompiledRuntime.handleAPIRequest\"\n        : adapterOwnsDocsRuntime\n          ? \"null\"\n          : `createFarmDocsAPIHandler({ rootDir: farmDocsRuntimeRoot, srcDir: ${JSON.stringify(config.srcDir)}, docs: farmDocsResolvedConfig })`\n      : \"null\"\n  };\n\n// API routes bundled at build time\nconst apiRoutes = ${apiRoutes.length > 0 ? \"mergePluginAPIRoutes(\" : \"\"}[${apiRegistrations.join(\",\")}\n]${\n    apiRoutes.length > 0\n      ? `, configuredPlugins, ${JSON.stringify(apiRoutes.map(({ path, methods }) => ({ path, methods })))}, { bodySizeLimit: ${JSON.stringify(config.server.bodySizeLimit)} })`\n      : \"\"\n  };\nconst farmLocalAPIBasePath = ${JSON.stringify(resolveFarmAPIServerBasePath(config.api))};\nconst farmOpenAPIReference = ${JSON.stringify(openAPIReference)};\n\nfunction isFarmLocalAPIPathname(pathname) {\n  return farmLocalAPIBasePath !== \"/\" &&\n    (pathname === farmLocalAPIBasePath ||\n      pathname.startsWith(farmLocalAPIBasePath + \"/\"));\n}\n\n// Page routes bundled at build time\nconst pageRoutes = [${pageRegistrations.join(\",\")}\n];\nconst exactPageRoutes = new Map();\nconst patternPageRoutes = [];\nfor (const route of pageRoutes) {\n  if (/[\\\\[\\\\]*:]/.test(route.pattern)) {\n    const segments = splitRuntimePath(route.pattern);\n    patternPageRoutes.push({ route, segments, prepared: prepareRuntimePageSegments(segments) });\n  } else {\n    const exactPath = normalizeRuntimePath(route.pattern);\n    if (!exactPageRoutes.has(exactPath)) exactPageRoutes.set(exactPath, route);\n  }\n}\n\n// Layout routes bundled at build time (sorted by depth, root first)\nconst layoutRoutes = [${layoutRegistrations.join(\",\")}\n];\nconst selectApplicableLayouts = createFarmLayoutSelector(layoutRoutes);\n\nconst routeSlots = [${routeSlotRegistrations.join(\",\")}\n];\n// The slot manifest is immutable. Share the page matcher's preparation without\n// changing descriptors, owner-prefix checks, grouping, or candidate precedence.\nconst preparedRouteSlots = new Map();\nfor (const entry of routeSlots) {\n  if (entry.fallback) continue;\n  const segments = splitRuntimePath(entry.pattern);\n  preparedRouteSlots.set(entry, {\n    segments: segments,\n    prepared: prepareRuntimePageSegments(segments),\n    specificity: routeSlotSpecificity(entry),\n  });\n}\n${sharedSlotOwners.size > 0 ? `const sharedRouteSlotOwners = new Set(${JSON.stringify([...sharedSlotOwners])});` : \"\"}\n\n// Route-level error boundaries bundled at build time.\nconst errorRoutes = [${errorRegistrations.join(\",\")}\n];\n\n// Metadata image routes bundled at build time\nconst metadataImageRoutes = [${metadataImageRegistrations.join(\",\")}\n];\n\n// sitemap.ts, robots.ts, and manifest.ts routes bundled at build time\nconst applicationMetadataRoutes = [${applicationMetadataRegistrations.join(\",\")}\n];\n\n// Redirect routes bundled at build time\nconst redirectRoutes = ${JSON.stringify(redirectRoutes, null, 2)};\n\n// Legacy rewrites() entries resolved at build time for standalone parity.\nconst configuredRewriteRoutes = ${JSON.stringify(configuredRewriteRoutes, null, 2)};\n\n// Legacy headers() entries resolved at build time for standalone parity.\nconst configuredHeaderRoutes = ${JSON.stringify(configuredHeaderRoutes, null, 2)};\n\nfunction getFarmI18nSnapshot() {\n  return ${config.i18n.enabled ? \"getFarmI18nClientSnapshot()\" : \"undefined\"};\n}\n\nfunction getFarmRoutePathname(pathname) {\n  return farmI18nRuntime\n    ? stripFarmLocaleFromPathname(stripFarmBasePath(pathname), farmI18nConfig)\n    : stripFarmBasePath(pathname);\n}\n\nfunction serializeFarmInlineValue(value) {\n  return JSON.stringify(value)\n    .replace(/</g, \"\\\\\\\\u003c\")\n    .replace(/\\\\u2028/g, \"\\\\\\\\u2028\")\n    .replace(/\\\\u2029/g, \"\\\\\\\\u2029\");\n}\n\nfunction renderFarmClientBootstrapScript(canonicalPath, selectedRouteSlots, pageProps) {\n  const integrationManifest = ${\n    hasRuntimeIntegrationConfig ? \"getRegisteredIntegrationAPIManifest()\" : \"{}\"\n  };\n  const serializedRouteSlots = serializeFarmInlineValue(selectedRouteSlots || []);\n  const serializedPageProps = serializeFarmInlineValue(pageProps || {});\n  let source = 'window.__FARM_PROPS__=' + serializedPageProps +\n    ';window.__FARM_INTEGRATION_API_MANIFEST__=' +\n    serializeFarmInlineValue(integrationManifest) +\n    ';window.__FARM_ROUTE_SLOTS__=' + serializedRouteSlots + ';';\n  if (typeof canonicalPath === \"string\" && canonicalPath.startsWith(\"/\")) {\n    const serializedPath = serializeFarmInlineValue(canonicalPath);\n    source += 'if(location.pathname+location.search!==' + serializedPath + '){' +\n      'history.replaceState(Object.assign({},history.state||{},{path:' + serializedPath + '}),\"\",' +\n      serializedPath + ');}';\n  }\n  return '<script id=\"__farm_route_slots_data__\" type=\"application/json\">' +\n    serializedRouteSlots +\n    '</script><script>' + source + '</script>';\n}\n\nfunction renderFarmRendererHydrationScript() {\n  return typeof ReactDOMServer.generateHydrationScript === \"function\"\n    ? ReactDOMServer.generateHydrationScript()\n    : \"\";\n}\n\nfunction escapeFarmHtmlAttribute(value) {\n  return String(value)\n    .replace(/&/g, \"&amp;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\");\n}\n\nasync function renderFarmElement(ReactDOMServer, element) {\n  const streamErrors = [];\n  let encoder;\n  const normalizeChunk = function(chunk) {\n    if (typeof chunk === \"string\") return (encoder ||= new TextEncoder()).encode(chunk);\n    if (chunk instanceof Uint8Array) return chunk;\n    return new Uint8Array(chunk);\n  };\n  const decodeChunks = function(chunks) {\n    const decoder = new TextDecoder();\n    let html = \"\";\n    for (const chunk of chunks) {\n      html += decoder.decode(chunk, { stream: true });\n    }\n    return html + decoder.decode();\n  };\n  const throwStreamError = function() {\n    if (streamErrors.length > 0) throw streamErrors[0];\n  };\n  // redirect()/notFound() reported while React rendered the shell (a\n  // synchronous page under a loading boundary) still decide the response:\n  // nothing has been sent, so stop instead of streaming an empty boundary.\n  const takeNavigationError = function() {\n    return streamErrors.find(function(error) {\n      return isFarmRedirectError(error) || isFarmNotFoundError(error);\n    });\n  };\n\n  if (farmRendererStreamingCapabilities.web &&\n      typeof ReactDOMServer.renderToReadableStream === \"function\") {\n    const stream = await ReactDOMServer.renderToReadableStream(element, {\n      onError(error) {\n        // redirect()/notFound() are control flow, not render failures: the\n        // request handler must still receive them to map the response status,\n        // but they should not produce a misleading SSR failure log.\n        streamErrors.push(error);\n        if (isFarmRedirectError(error) || isFarmNotFoundError(error)) return;\n        console.error(\"[Farm SSR stream]\", error);\n      },\n    });\n    const reader = stream.getReader();\n    const firstResult = await reader.read();\n    if (firstResult.done) {\n      throwStreamError();\n      return { html: \"\", shellHtml: \"\", streamErrors };\n    }\n\n    const firstChunk = normalizeChunk(firstResult.value);\n    let allReady = false;\n    const allReadyPromise = stream.allReady;\n    if (allReadyPromise && typeof allReadyPromise.then === \"function\") {\n      Promise.resolve(allReadyPromise).then(\n        function() {\n          allReady = true;\n        },\n        function() {},\n      );\n      // React resolves allReady in the same turn for a synchronous tree. A\n      // suspended tree remains pending, so its already-produced shell can be\n      // returned without rendering the element a second time.\n      await Promise.resolve();\n    }\n\n    if (allReady) {\n      const chunks = [firstChunk];\n      while (true) {\n        const result = await reader.read();\n        if (result.done) break;\n        chunks.push(normalizeChunk(result.value));\n      }\n      throwStreamError();\n      const html = decodeChunks(chunks);\n      return { html, shellHtml: html, streamErrors };\n    }\n\n    const earlyNavigationError = takeNavigationError();\n    if (earlyNavigationError) {\n      reader.cancel(earlyNavigationError).catch(function() {});\n      throw earlyNavigationError;\n    }\n\n    let replayFirstChunk = true;\n    const replayStream = new ReadableStream({\n      pull(controller) {\n        if (replayFirstChunk) {\n          replayFirstChunk = false;\n          controller.enqueue(firstChunk);\n          return;\n        }\n        return reader.read().then(\n          function(result) {\n            if (result.done) controller.close();\n            else controller.enqueue(normalizeChunk(result.value));\n          },\n          function(error) {\n            controller.error(error);\n          },\n        );\n      },\n      cancel(reason) {\n        return reader.cancel(reason);\n      },\n    });\n    return {\n      stream: replayStream,\n      shellHtml: new TextDecoder().decode(firstChunk),\n      streamErrors,\n    };\n  }\n\n  if (farmRendererStreamingCapabilities.node &&\n      typeof ReactDOMServer.renderToPipeableStream === \"function\") {\n    let pipeableStream;\n    let stream;\n    let streamController;\n    let streamClosed = false;\n    let streamStarted = false;\n    let allReady = false;\n    let decisionState = \"pending\";\n    let settleDecision;\n    let rejectDecision;\n    let settleComplete;\n    let rejectComplete;\n    const chunks = [];\n    const decision = new Promise(function(resolve, reject) {\n      settleDecision = resolve;\n      rejectDecision = reject;\n    });\n    const complete = new Promise(function(resolve, reject) {\n      settleComplete = resolve;\n      rejectComplete = reject;\n    });\n    const fail = function(error) {\n      if (!streamClosed) {\n        streamClosed = true;\n        if (decisionState === \"stream\") streamController.error(error);\n      }\n      if (decisionState === \"complete\") rejectComplete(error);\n      else if (decisionState === \"pending\") rejectDecision(error);\n    };\n    const destination = {\n      write(chunk) {\n        if (streamClosed) return false;\n        const normalized = normalizeChunk(chunk);\n        if (streamStarted) streamController.enqueue(normalized);\n        else chunks.push(normalized);\n        return true;\n      },\n      end() {\n        if (streamClosed) return;\n        streamClosed = true;\n        if (streamStarted) streamController.close();\n        settleComplete();\n      },\n      on() {\n        return destination;\n      },\n      destroy(error) {\n        fail(error || new Error(\"React server render stream was destroyed\"));\n      },\n    };\n    pipeableStream = ReactDOMServer.renderToPipeableStream(element, {\n      onShellReady() {\n        try {\n          pipeableStream.pipe(destination);\n          queueMicrotask(function() {\n            decisionState = allReady ? \"complete\" : \"stream\";\n            // A synchronous render returns buffered HTML. Only allocate the\n            // bridge when streaming, before exposing that decision to callers.\n            if (decisionState === \"stream\") {\n              stream = new ReadableStream({\n                start(controller) {\n                  streamController = controller;\n                },\n                cancel(reason) {\n                  if (pipeableStream && typeof pipeableStream.abort === \"function\") {\n                    pipeableStream.abort(reason);\n                  }\n                },\n              });\n            }\n            settleDecision(decisionState);\n          });\n        } catch (error) {\n          fail(error);\n        }\n      },\n      onAllReady() {\n        allReady = true;\n      },\n      onShellError: fail,\n      onError(error) {\n        // Same control-flow guard as the readable-stream path above.\n        streamErrors.push(error);\n        if (isFarmRedirectError(error) || isFarmNotFoundError(error)) return;\n        console.error(\"[Farm SSR stream]\", error);\n      },\n    });\n\n    if ((await decision) === \"complete\") {\n      await complete;\n      throwStreamError();\n      const html = decodeChunks(chunks);\n      return { html, shellHtml: html, streamErrors };\n    }\n\n    const earlyNavigationError = takeNavigationError();\n    if (earlyNavigationError) {\n      if (typeof pipeableStream.abort === \"function\") pipeableStream.abort(earlyNavigationError);\n      throw earlyNavigationError;\n    }\n\n    streamStarted = true;\n    for (const chunk of chunks) streamController.enqueue(chunk);\n    if (streamClosed) streamController.close();\n    return {\n      stream,\n      shellHtml: chunks.length > 0 ? new TextDecoder().decode(chunks[0]) : \"\",\n      streamErrors,\n    };\n  }\n\n  if (ReactDOMServer.renderToStringWithHead) {\n    const rendered = await ReactDOMServer.renderToStringWithHead(element);\n    return {\n      html: rendered.html,\n      head: rendered.head || \"\",\n      shellHtml: rendered.html,\n      streamErrors,\n    };\n  }\n  const html = await ReactDOMServer.renderToString(element);\n  return { html, head: \"\", shellHtml: html, streamErrors };\n}\n\nasync function renderFarmElementToString(ReactDOMServer, element) {\n  const rendered = await renderFarmElement(ReactDOMServer, element);\n  if (rendered.html !== undefined) return rendered.html;\n  const html = await new Response(rendered.stream).text();\n  if (rendered.streamErrors.length > 0) throw rendered.streamErrors[0];\n  return html;\n}\n\nfunction createFarmDocumentStream(contentStream, prefix, suffix, onComplete) {\n  const encoder = new TextEncoder();\n  const reader = contentStream.getReader();\n  return new ReadableStream({\n    start(controller) {\n      controller.enqueue(encoder.encode(prefix));\n    },\n    async pull(controller) {\n      try {\n        const result = await reader.read();\n        if (result.done) {\n          const tail = typeof suffix === \"function\" ? await suffix() : suffix;\n          controller.enqueue(encoder.encode(tail));\n          if (onComplete) onComplete();\n          controller.close();\n          return;\n        }\n        controller.enqueue(result.value);\n      } catch (error) {\n        controller.error(error);\n      }\n    },\n    cancel(reason) {\n      return reader.cancel(reason);\n    },\n  });\n}\n\nfunction stripFarmDocumentWrappers(markup) {\n  let output = markup.replace(/^\\\\s+/, \"\");\n  const wrapper = /^<div\\\\b[^>]*style=[\"']display\\\\s*:\\\\s*contents[\"'][^>]*>/i;\n  let match;\n  while ((match = wrapper.exec(output))) {\n    output = output.slice(match[0].length).replace(/^\\\\s+/, \"\");\n  }\n  return output;\n}\n\nfunction opensFarmFullDocument(markup) {\n  const inner = stripFarmDocumentWrappers(markup);\n  return /^<!doctype/i.test(inner) || /^<html[\\\\s>]/i.test(inner);\n}\n\nfunction extractFarmFullDocument(markup) {\n  if (!opensFarmFullDocument(markup)) return null;\n  const start = markup.search(/<!doctype|<html[\\\\s>]/i);\n  const lower = markup.toLowerCase();\n  let closeIndex = lower.lastIndexOf(\"</html>\");\n  // Case conversion can expand Unicode. Recover original offsets only then;\n  // ordinary documents retain the existing closing-tag search.\n  if (lower.length !== markup.length) {\n    closeIndex = -1;\n    const closing = /<\\\\/html>/gi;\n    let match;\n    while ((match = closing.exec(markup))) closeIndex = match.index;\n  }\n  if (start < 0 || closeIndex < 0) return null;\n  const closeEnd = closeIndex + \"</html>\".length;\n  let document = markup.slice(start, closeEnd);\n  // Farm's segment wrappers sit outside an app-authored <html>. When React\n  // streams a suspended descendant, it closes those wrappers after </html>\n  // and then emits the reveal payload. Keep that payload inside <body> instead\n  // of discarding it with the wrapper suffix.\n  const streamedTail = markup\n    .slice(closeEnd)\n    .replace(/^(?:\\\\s*<\\\\/div>)+/i, \"\")\n    .trim();\n  if (streamedTail) {\n    document = document.replace(/<\\\\/body>/i, function() {\n      return streamedTail + \"</body>\";\n    });\n  }\n  return document;\n}\n\nfunction ensureFarmDocumentHead(markup) {\n  if (/<head[\\\\s>]/i.test(markup)) return markup;\n  return markup.replace(/<html([^>]*)>/i, function(_match, attributes) {\n    return \"<html\" + attributes + \"><head></head>\";\n  });\n}\n\nfunction ensureFarmDocumentRoot(markup) {\n  if (/\\\\sid=[\"']root[\"']/i.test(markup)) return markup;\n  return markup\n    .replace(/<body\\\\b([^>]*)>/i, function(_match, attributes) {\n      return \"<body\" + attributes + '><div id=\"root\">';\n    })\n    .replace(/<\\\\/body>/i, function() { return \"</div></body>\"; });\n}\n\nfunction createFarmErrorDocument(html, title) {\n  const escapedTitle = escapeFarmHtmlAttribute(title || \"Application Error\");\n  const fullDocument = extractFarmFullDocument(html);\n  const hasFullDocument = fullDocument !== null;\n\n  if (!hasFullDocument) {\n    return '<!DOCTYPE html>\\\\n<html lang=\"en\">\\\\n<head>\\\\n' +\n      '  <meta charset=\"utf-8\">\\\\n' +\n      '  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\\\\n' +\n      '  <link rel=\"icon\" href=\"data:,\">\\\\n' +\n      '  <title>' + escapedTitle + '</title>\\\\n' +\n      '  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\\\\n' +\n      renderFarmRendererHydrationScript() + '\\\\n' +\n      '</head>\\\\n<body>\\\\n' +\n      '  <div id=\"root\">' + html + '</div>\\\\n' +\n      '  ' + renderFarmClientBootstrapScript() + '\\\\n' +\n      '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n' +\n      '</body>\\\\n</html>';\n  }\n\n  let fullHtml = ensureFarmDocumentRoot(ensureFarmDocumentHead(fullDocument));\n  fullHtml = fullHtml\n    .replace(/<head([^>]*)>/i, '<head$1>\\\\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">')\n    // Function replacements: dynamic markup may contain $-sequences ($&, $', $$)\n    // that a string replacement would expand, corrupting the document.\n    .replace(/<\\\\/head>/i, function() { return renderFarmRendererHydrationScript() + '\\\\n</head>'; })\n    .replace(/<head([^>]*)>([\\\\s\\\\S]*?)<\\\\/head>/i, function(match, attrs, headContent) {\n      return headContent.includes(\"<title\")\n        ? match\n        : '<head' + attrs + '>' + headContent + '\\\\n  <title>' + escapedTitle + '</title>\\\\n</head>';\n    })\n    .replace(\n      /<\\\\/body>/i,\n      function() {\n        return '  ' + renderFarmClientBootstrapScript() + '\\\\n' +\n          '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>';\n      },\n    );\n  return fullHtml.trim().startsWith(\"<!DOCTYPE\")\n    ? fullHtml\n    : \"<!DOCTYPE html>\\\\n\" + fullHtml;\n}\n\n// The origin hreflang alternates resolve against when the route sets no\n// metadataBase. Forwarded authority counts only under server.trustProxy, the\n// same rule the development server applies.\nfunction resolveFarmI18nAlternateOrigin(request) {\n  return resolveFarmWebRequestOrigin(request, {\n    trustProxy: farmServerConfig.trustProxy === true,\n  });\n}\n\nfunction renderFarmI18nAlternateLinks(requestPath, snapshot, request, metadata) {\n  if (!snapshot || snapshot.routing === \"none\") return \"\";\n  const url = new URL(requestPath, \"http://farm.local\");\n  const routePathname = stripFarmLocaleFromPathname(url.pathname, snapshot);\n  return renderFarmLocaleAlternateLinks(routePathname, snapshot, {\n    metadataBase: metadata ? metadata.metadataBase : undefined,\n    origin: request ? resolveFarmI18nAlternateOrigin(request) : undefined,\n  });\n}\n\nfunction applyFarmI18nDocument(html, requestPath, snapshot, request, metadata) {\n  if (!snapshot) return html;\n  const locale = escapeFarmHtmlAttribute(snapshot.locale);\n  const direction = escapeFarmHtmlAttribute(snapshot.direction);\n  let nextHtml = html.replace(/<html([^>]*)>/i, function(_match, attributes) {\n    const cleaned = attributes.replace(\n      /\\\\s+(?:lang|dir)=(?:\"[^\"]*\"|'[^']*'|[^\\\\s>]+)/gi,\n      \"\"\n    );\n    return '<html' + cleaned + ' lang=\"' + locale + '\" dir=\"' + direction + '\">';\n  });\n  const runtimeMarkup =\n    renderFarmI18nAlternateLinks(requestPath, snapshot, request, metadata) +\n    '<script>window.__FARM_I18N__ = ' + serializeFarmInlineValue(snapshot) + ';</script>';\n  nextHtml = nextHtml.replace(/<head([^>]*)>/i, function(_match, attributes) {\n    // Function replacement: runtimeMarkup may contain $-sequences ($&, $', $$).\n    return '<head' + attributes + '>' + runtimeMarkup;\n  });\n  return nextHtml;\n}\n\nfunction appendFarmVary(headers, value) {\n  const existing = headers.get(\"Vary\");\n  const values = new Set(\n    (existing ? existing.split(\",\") : []).map(function(entry) { return entry.trim(); }).filter(Boolean)\n  );\n  values.add(value);\n  headers.set(\"Vary\", Array.from(values).join(\", \"));\n}\n\nfunction applyFarmI18nResponse(response, resolution) {\n  if (!farmI18nRuntime || !resolution) return response;\n  const headers = new Headers(response.headers);\n  if (resolution.persist) {\n    headers.append(\"Set-Cookie\", createFarmLocaleCookie(resolution.locale, farmI18nConfig));\n  }\n  const varyHeaders = getFarmLocaleVaryHeaders(farmI18nConfig, resolution);\n  for (const header of varyHeaders) appendFarmVary(headers, header);\n  if (varyHeaders.length > 0) {\n    headers.set(\"Cache-Control\", \"private, no-store\");\n  }\n  return new Response(response.body, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}\n\nfunction hasOnlyValidFarmLocaleCookie(cookieHeader) {\n  if (!farmI18nRuntime || !cookieHeader) return false;\n  const parts = cookieHeader.split(\";\");\n  if (parts.length !== 1) return false;\n\n  const cookie = parts[0].trim();\n  const separator = cookie.indexOf(\"=\");\n  if (separator <= 0) return false;\n\n  let name;\n  let value;\n  try {\n    name = decodeURIComponent(cookie.slice(0, separator).trim());\n    value = decodeURIComponent(cookie.slice(separator + 1).trim());\n  } catch {\n    return false;\n  }\n\n  return (\n    name === farmI18nConfig.cookie.name &&\n    farmI18nConfig.locales.includes(value)\n  );\n}\n\nfunction hasPrivateFarmRequestHeaders(request, farmLocaleResolution) {\n  if (request.headers.get(\"authorization\")) return true;\n  const cookieHeader = request.headers.get(\"cookie\");\n  if (!cookieHeader) return false;\n\n  return !(\n    farmLocaleResolution?.source === \"url\" &&\n    hasOnlyValidFarmLocaleCookie(cookieHeader)\n  );\n}\n\n${generateRuntimePathMatcherSource()}\n\nfunction getMatchingErrorBoundary(pathname) {\n  const pathSegments = splitRuntimePath(pathname);\n  let bestMatch = null;\n\n  for (const errorRoute of errorRoutes) {\n    const patternDepth = splitRuntimePath(errorRoute.pattern).length;\n    if (patternDepth > pathSegments.length) continue;\n    const candidatePath = patternDepth === 0\n      ? \"/\"\n      : \"/\" + pathSegments.slice(0, patternDepth).join(\"/\");\n    const params = matchRuntimePathPattern(errorRoute.pattern, candidatePath);\n    if (params === null) continue;\n\n    if (!bestMatch || patternDepth > bestMatch.depth) {\n      bestMatch = { route: errorRoute, params, depth: patternDepth };\n    }\n  }\n\n  return bestMatch;\n}\n\nfunction getMatchingMetadataImage(pathname, kind) {\n  const pathSegments = splitRuntimePath(pathname);\n  let bestMatch = null;\n\n  for (const image of metadataImageRoutes) {\n    if (image.kind !== kind) continue;\n    const patternDepth = splitRuntimePath(image.pattern).length;\n    if (patternDepth > pathSegments.length) continue;\n\n    const pagePath = patternDepth === 0\n      ? \"/\"\n      : \"/\" + pathSegments.slice(0, patternDepth).join(\"/\");\n    const params = matchRuntimePathPattern(image.pattern, pagePath);\n    if (params === null) continue;\n\n    if (!bestMatch || patternDepth > bestMatch.depth) {\n      bestMatch = { image, params, pagePath, depth: patternDepth };\n    }\n  }\n\n  return bestMatch;\n}\n\nfunction matchMetadataImageRequest(pathname) {\n  const normalizedPath = normalizeRuntimePath(pathname);\n  let kind;\n  let fileName;\n\n  if (normalizedPath === \"/opengraph-image\" || normalizedPath.endsWith(\"/opengraph-image\")) {\n    kind = \"opengraph\";\n    fileName = \"opengraph-image\";\n  } else if (normalizedPath === \"/twitter-image\" || normalizedPath.endsWith(\"/twitter-image\")) {\n    kind = \"twitter\";\n    fileName = \"twitter-image\";\n  } else {\n    return null;\n  }\n\n  const pagePath = normalizedPath.slice(0, -fileName.length - 1) || \"/\";\n  for (const image of metadataImageRoutes) {\n    if (image.kind !== kind) continue;\n    const params = matchRuntimePathPattern(image.pattern, pagePath);\n    if (params !== null) return { image, params, pagePath };\n  }\n\n  return null;\n}\n\nfunction createMetadataImageReference(match, locale) {\n  const image = match.image;\n  const metadata = image.sourceType === \"static\" ? image.staticInfo : image.module;\n  const basePath = match.pagePath === \"/\" ? \"\" : match.pagePath;\n  const version = image.sourceType === \"static\" ? \"?v=\" + image.staticInfo.hash : \"\";\n  const href = basePath + \"/\" + image.fileName + version;\n  const localizedHref = locale ? localizeFarmHref(href, locale, farmI18nConfig) : href;\n\n  return {\n    kind: image.kind,\n    href: applyFarmBasePath(localizedHref),\n    width: metadata?.width ?? metadata?.size?.width,\n    height: metadata?.height ?? metadata?.size?.height,\n    alt: metadata?.alt,\n    contentType: metadata?.contentType,\n  };\n}\n\nfunction decodeMetadataImage(data) {\n  const binary = atob(data);\n  const bytes = new Uint8Array(binary.length);\n  for (let index = 0; index < binary.length; index++) {\n    bytes[index] = binary.charCodeAt(index);\n  }\n  return bytes;\n}\n\nasync function handleMetadataImageRequest(request, routePathname) {\n  const url = new URL(request.url);\n  const match = matchMetadataImageRequest(routePathname || url.pathname);\n  if (!match) return null;\n\n  const method = request.method.toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    return new Response(null, { status: 405, headers: { Allow: \"GET, HEAD\" } });\n  }\n\n  const image = match.image;\n  if (image.sourceType === \"static\") {\n    const etag = '\"' + image.staticInfo.hash + '\"';\n    const isVersioned = url.searchParams.get(\"v\") === image.staticInfo.hash;\n    const headers = new Headers({\n      \"Content-Type\": image.staticInfo.contentType,\n      \"Content-Length\": String(image.staticInfo.byteLength),\n      \"Cache-Control\": isVersioned\n        ? \"public, max-age=31536000, immutable\"\n        : \"public, max-age=0, must-revalidate\",\n      \"ETag\": etag,\n      \"X-Content-Type-Options\": \"nosniff\",\n    });\n\n    if (matchesFarmIfNoneMatch(request.headers.get(\"if-none-match\"), etag)) {\n      return new Response(null, { status: 304, headers });\n    }\n\n    if (!image.bytes) image.bytes = decodeMetadataImage(image.data);\n    return new Response(method === \"HEAD\" ? null : image.bytes, { status: 200, headers });\n  }\n\n  try {\n    const imageModule = image.module;\n    if (!imageModule?.default) {\n      throw new Error(\"Metadata image module does not export a default component or handler\");\n    }\n\n    const searchParams = searchParamsToObject(url.searchParams);\n    const props = {\n      params: match.params,\n      searchParams: Promise.resolve(searchParams),\n      path: match.pagePath,\n    };\n    const value = typeof imageModule.default === \"function\"\n      ? await imageModule.default(props)\n      : imageModule.default;\n\n    ${\n      hasGeneratedMetadataImages\n        ? `return createFarmMetadataImageResponse(value, imageModule, {\n      method,\n      ifNoneMatch: request.headers.get(\"if-none-match\"),\n    });`\n        : 'throw new Error(\"Generated metadata image runtime is unavailable\");'\n    }\n  } catch (error) {\n    console.error(\"Metadata image render failed:\", error);\n    return new Response(\"Internal Server Error\", {\n      status: 500,\n      headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n    });\n  }\n}\n\nfunction matchApplicationMetadataRouteRequest(pathname) {\n  const normalizedPath = normalizeRuntimePath(pathname);\n  for (const metadata of applicationMetadataRoutes) {\n    const suffix = \"/\" + metadata.outputName;\n    if (normalizedPath !== suffix && !normalizedPath.endsWith(suffix)) continue;\n    const routePath = normalizedPath.slice(0, -suffix.length) || \"/\";\n    const params = matchRuntimePathPattern(metadata.pattern, routePath);\n    if (params !== null) return { metadata, params, routePath };\n  }\n  return null;\n}\n\nfunction getMatchingApplicationMetadataRoute(pathname, kind) {\n  const normalizedPath = normalizeRuntimePath(pathname);\n  const pathSegments = splitRuntimePath(normalizedPath);\n  let bestMatch = null;\n\n  for (const metadata of applicationMetadataRoutes) {\n    if (metadata.kind !== kind) continue;\n    const patternDepth = splitRuntimePath(metadata.pattern).length;\n    if (patternDepth > pathSegments.length) continue;\n    const routePath = patternDepth === 0\n      ? \"/\"\n      : \"/\" + pathSegments.slice(0, patternDepth).join(\"/\");\n    const params = matchRuntimePathPattern(metadata.pattern, routePath);\n    if (params === null) continue;\n    if (!bestMatch || patternDepth > bestMatch.depth) {\n      bestMatch = { metadata, params, routePath, depth: patternDepth };\n    }\n  }\n\n  return bestMatch;\n}\n\nfunction createApplicationMetadataHref(match, locale) {\n  const basePath = match.routePath === \"/\" ? \"\" : match.routePath;\n  const href = basePath + \"/\" + match.metadata.outputName;\n  const localizedHref = locale ? localizeFarmHref(href, locale, farmI18nConfig) : href;\n  return applyFarmBasePath(localizedHref);\n}\n\n${\n  servesAgentRobotsTxt\n    ? `// robots.txt from agent.crawlers, built the same way as in development.\nfunction createFarmAgentRobotsResponse(request) {\n  const rootLayout = layoutRoutes.find((layout) => layout.pattern === \"/\");\n  return createFarmMetadataRouteResponse(\n    \"robots\",\n    createFarmAgentRobots({\n      crawlers: farmAgentCrawlers,\n      sitemapPath: ${\n        applicationMetadataRoutes.some(\n          (metadata) => metadata.kind === \"sitemap\" && metadata.pattern === \"/\",\n        )\n          ? JSON.stringify(\"/sitemap.xml\")\n          : \"undefined\"\n      },\n      metadataBase: rootLayout && rootLayout.module && rootLayout.module.metadata\n        ? rootLayout.module.metadata.metadataBase\n        : undefined,\n      basePath: ${JSON.stringify(config.basePath)},\n    }),\n    {},\n    { method: request.method },\n  );\n}\n`\n    : \"\"\n}\n// Static pages and root metadata for llms.txt, built the same way as in development.\nfunction createFarmLlmsTxtContext(request, full) {\n  const origin = new URL(request.url).origin;\n  const pages = collectFarmLlmsTxtPages(\n    pageRoutes.map((route) => ({ pattern: route.pattern, metadata: route.module && route.module.metadata })),\n    {\n      origin,\n      markdown: farmMarkdownConfig,\n      include: farmLlmsTxtConfig.include,\n      exclude: farmLlmsTxtConfig.exclude,\n    },\n  );\n  const rootLayout = layoutRoutes.find((layout) => layout.pattern === \"/\");\n  return {\n    pages,\n    defaults: createFarmDefaultLlmsTxt({\n      origin,\n      pages,\n      config: farmLlmsTxtConfig,\n      rootMetadata: rootLayout && rootLayout.module && rootLayout.module.metadata,\n    }),\n    // llms-full.txt reads each page's .md mirror through this same handler,\n    // with a fresh request so the caller's cookies never shape its content.\n    // HEAD discards the body, so it reads nothing.\n    ...(full\n      ? {\n          markdown: request.method.toUpperCase() === \"HEAD\"\n            ? async () => null\n            : createFarmLlmsMarkdownReader((page) => handleFarmRequest(page)),\n        }\n      : {}),\n  };\n}\n\nasync function handleApplicationMetadataRouteRequest(request, routePathname) {\n  const url = new URL(request.url);\n  const match = matchApplicationMetadataRouteRequest(routePathname || url.pathname);\n  if (!match) return null;\n\n  const method = request.method.toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") {\n    return new Response(null, { status: 405, headers: { Allow: \"GET, HEAD\" } });\n  }\n\n  try {\n    const routeModule = match.metadata.module;\n    if (routeModule?.default === undefined) {\n      throw new Error(\"Metadata route module does not export a default value or handler\");\n    }\n    const isLlmsFull = match.metadata.kind === \"llms-full\";\n    const llmsContext = match.metadata.kind === \"llms\" || isLlmsFull\n      ? createFarmLlmsTxtContext(request, isLlmsFull)\n      : {};\n    const value = typeof routeModule.default === \"function\"\n      ? await routeModule.default({\n          request,\n          params: match.params,\n          searchParams: url.searchParams,\n          path: match.routePath,\n          ...llmsContext,\n        })\n      : routeModule.default;\n    const body = isLlmsFull && !(value instanceof Response)\n      ? await renderFarmLlmsFullTxt(value, { origin: url.origin, readMarkdown: llmsContext.markdown })\n      : value;\n    return createFarmMetadataRouteResponse(match.metadata.kind, body, routeModule, { method });\n  } catch (error) {\n    console.error(\"Metadata route render failed:\", error);\n    return new Response(\"Internal Server Error\", {\n      status: 500,\n      headers: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n    });\n  }\n}\n\n${generateRedirectInterpolationSource()}\n\nfunction matchRedirectRoute(pathname, locale, search) {\n  for (const redirect of redirectRoutes) {\n    const params = matchRuntimePathPattern(redirect.source, pathname);\n    if (!params) continue;\n    const destination = interpolateRedirectDestination(redirect.destination, params);\n    const localizedDestination =\n      locale && destination.startsWith(\"/\") && !destination.startsWith(\"//\")\n        ? localizeFarmHref(destination, locale, farmI18nConfig)\n        : destination;\n    return {\n      destination: appendFarmRedirectQuery(localizedDestination, search),\n      statusCode: redirect.statusCode ?? (redirect.permanent ? 308 : 307),\n    };\n  }\n  return null;\n}\n\nfunction matchRewriteRoute(pathname, locale) {\n  for (const rewrite of configuredRewriteRoutes) {\n    const params = matchRuntimePathPattern(rewrite.source, pathname);\n    if (!params) continue;\n    const destination = interpolateRedirectDestination(rewrite.destination, params);\n    return locale && destination.startsWith(\"/\") && !destination.startsWith(\"//\")\n      ? localizeFarmHref(destination, locale, farmI18nConfig)\n      : destination;\n  }\n  return null;\n}\n\nfunction createRewrittenRequest(request, destination) {\n  const sourceUrl = new URL(request.url);\n  const destinationUrl = new URL(destination, sourceUrl);\n  if (!destinationUrl.search && sourceUrl.search) {\n    destinationUrl.search = sourceUrl.search;\n  }\n  return new Request(destinationUrl, request);\n}\n\n${generateConfiguredResponseHeadersRuntimeSource()}\n\n// App middleware files bundled at build time (sorted by depth, root first)\nconst fileMiddlewareModules = [${middlewareRegistrations.join(\",\")}\n];\n\nconst farmMiddlewareRunner = ${\n    hasMiddlewareRuntime\n      ? `createProductionMiddlewareRunner({\n  config: farmMiddlewareConfig,\n  modules: fileMiddlewareModules,\n  i18n: farmI18nConfig,\n  server: farmServerConfig,\n})`\n      : \"null\"\n  };\n\n${apiHandlerCode}\n\n${generateIntegrationRequestRuntimeSource({ hasServerRuntimeIntegrations })}\n\n/**\n * Match URL to page route pattern\n */\nfunction matchPageRoute(pathname) {\n  const exactRoute = exactPageRoutes.get(normalizeRuntimePath(pathname));\n  if (exactRoute) return { route: exactRoute, params: {} };\n\n  if (patternPageRoutes.length === 0) return null;\n  // The page manifest is immutable. Reuse its pattern parts and decode this\n  // request once, while each match retains its own params and backtracking state.\n  const pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n  for (const { route, segments, prepared } of patternPageRoutes) {\n    const params = prepared\n      ? matchPreparedRuntimePageSegments(prepared, pathnameSegments)\n      : matchRuntimePathSegments(segments, pathnameSegments);\n    if (params !== null) return { route, params };\n  }\n  return null;\n}\n\nfunction matchesRoutePrefix(pathname, pattern) {\n  return pattern === \"/\" ||\n    isFarmRouteActive(pattern, normalizeRuntimePath(pathname), { exact: false });\n}\n\nfunction routeSlotSpecificity(slot) {\n  return slot.pattern.split(\"/\").reduce(function(score, segment) {\n    if (!segment) return score;\n    // Optional catch-alls rank below their parent path (mirrors routeSpecificity).\n    if (segment.startsWith(\"[[...\")) return score - 1;\n    if (segment.startsWith(\"[...\")) return score + 2;\n    if (segment.startsWith(\"[\")) return score + 3;\n    return score + 10;\n  }, 0);\n}\n\nfunction matchRouteSlots(pathname, interceptFrom) {\n  const groups = new Map();${\n    sharedSlotOwners.size > 0\n      ? `\n  // Incoming-owner results belong only to this request. Interception checks\n  // still use their own background pathname and the complete prefix matcher.\n  const ownerMatches = new Map();\n  function matchesSlotOwner(pattern) {\n    if (!sharedRouteSlotOwners.has(pattern)) return matchesRoutePrefix(pathname, pattern);\n    let matched = ownerMatches.get(pattern);\n    if (matched === undefined) {\n      matched = matchesRoutePrefix(pathname, pattern);\n      ownerMatches.set(pattern, matched);\n    }\n    return matched;\n  }`\n      : \"\"\n  }\n  for (const slot of routeSlots) {\n    if (!${sharedSlotOwners.size > 0 ? \"matchesSlotOwner(slot.ownerPattern)\" : \"matchesRoutePrefix(pathname, slot.ownerPattern)\"}) continue;\n    const key = slot.ownerPattern + \":\" + slot.name;\n    const entries = groups.get(key) || [];\n    entries.push(slot);\n    groups.set(key, entries);\n  }\n\n  const normalizedFrom =\n    typeof interceptFrom === \"string\" && interceptFrom.startsWith(\"/\")\n      ? new URL(interceptFrom, \"http://farm.local\").pathname\n      : null;\n  const matches = [];\n  // Leave empty, fallback-only and ineligible requests unparsed.\n  let pathnameSegments;\n\n  for (const entries of groups.values()) {\n    const candidates = entries\n      .filter(function(entry) { return !entry.fallback; })\n      .filter(function(entry) {\n        return !entry.interception ||\n          (normalizedFrom && matchesRoutePrefix(normalizedFrom, entry.ownerPattern));\n      })\n      .map(function(entry) {\n        const slot = preparedRouteSlots.get(entry);\n        if (!pathnameSegments) pathnameSegments = splitRuntimePath(pathname).map(decodeRouteSegment);\n        return {\n          entry: entry,\n          specificity: slot.specificity,\n          params: slot.prepared\n            ? matchPreparedRuntimePageSegments(slot.prepared, pathnameSegments)\n            : matchRuntimePathSegments(slot.segments, pathnameSegments),\n        };\n      })\n      .filter(function(candidate) { return candidate.params !== null; })\n      .sort(function(left, right) {\n        if (left.entry.interception !== right.entry.interception) {\n          return left.entry.interception ? -1 : 1;\n        }\n        return right.specificity - left.specificity;\n      });\n\n    if (candidates[0]) {\n      matches.push({ ...candidates[0].entry, params: candidates[0].params });\n      continue;\n    }\n\n    const fallback = entries.find(function(entry) { return entry.fallback; });\n    if (fallback) matches.push({ ...fallback, params: {} });\n  }\n\n  return matches.sort(function(left, right) {\n    const ownerDepth =\n      left.ownerPattern.split(\"/\").filter(Boolean).length -\n      right.ownerPattern.split(\"/\").filter(Boolean).length;\n    return ownerDepth || left.name.localeCompare(right.name);\n  });\n}\n\nfunction hasLocalRequestRoute(request, routePathname) {\n  const pathname = new URL(request.url).pathname;\n  if (\n    farmOpenAPIReference &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.route)\n  ) {\n    return true;\n  }\n  if (matchLocalAPIRequest(request) || matchLocalIntegrationRequest(request)) {\n    return true;\n  }\n  if (\n    matchPageRoute(routePathname) ||\n    matchMetadataImageRequest(routePathname) ||\n    matchApplicationMetadataRouteRequest(routePathname)\n  ) {\n    return true;\n  }\n  if (${imageRuntime === \"none\" ? \"false\" : `pathname === ${JSON.stringify(config.images.path)}`}) {\n    return true;\n  }\n  ${\n    config.docs?.enabled\n      ? `const docsPath = normalizeRuntimePath(farmDocsResolvedConfig?.entry || \"/docs\");\n  if (\n    isFarmDocsAPIRequest(pathname) ||\n    docsPath === \"/\" ||\n    pathname === docsPath ||\n    pathname.startsWith(docsPath + \"/\")\n  ) {\n    return true;\n  }`\n      : \"\"\n  }\n  return false;\n}\n\nfunction getFarmPluginRequestOptions(request) {\n  const url = new URL(request.url);\n  const pathname = url.pathname;\n  const routePathname = getFarmRoutePathname(pathname);\n  const route = { pathname };\n  if (\n    farmOpenAPIReference &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.route)\n  ) {\n    return {\n      kind: \"docs\",\n      route: { ...route, pattern: normalizeRuntimePath(farmOpenAPIReference.route) },\n    };\n  }\n  const isDocsAPIRequest = ${config.docs?.enabled ? \"isFarmDocsAPIRequest(pathname)\" : \"false\"};\n  const integrationMatch = ${\n    hasServerRuntimeIntegrations\n      ? `matchIntegrationRoute(serverRuntimeIntegrations, {\n    pathname,\n    method: request.method,\n  })`\n      : \"null\"\n  };\n\n  if (integrationMatch) {\n    return {\n      kind: \"integration\",\n      route: {\n        ...route,\n        pattern: integrationMatch.route.path,\n        params: integrationMatch.params,\n      },\n    };\n  }\n\n  const docsPath = normalizeRuntimePath(farmDocsResolvedConfig?.entry || \"/docs\");\n  if (\n    isDocsAPIRequest ||\n    (farmDocsHandler && (pathname === docsPath || pathname.startsWith(docsPath + \"/\")))\n  ) {\n    return { kind: \"docs\", route: { ...route, pattern: docsPath } };\n  }\n\n  const apiMatch = ${apiRoutes.length > 0 ? \"matchLocalAPIRequest(request)\" : \"null\"};\n  if (apiMatch) {\n    return {\n      kind: \"api\",\n      route: { ...route, pattern: apiMatch.route.path, params: apiMatch.params },\n    };\n  }\n\n  const metadataImageMatch = matchMetadataImageRequest(routePathname);\n  if (metadataImageMatch) {\n    return {\n      kind: \"asset\",\n      route: {\n        ...route,\n        pattern: metadataImageMatch.image.pattern,\n        params: metadataImageMatch.params,\n      },\n    };\n  }\n\n  const applicationMetadataMatch = matchApplicationMetadataRouteRequest(routePathname);\n  if (applicationMetadataMatch) {\n    return {\n      kind: \"asset\",\n      route: {\n        ...route,\n        pattern: applicationMetadataMatch.metadata.pattern,\n        params: applicationMetadataMatch.params,\n      },\n    };\n  }\n\n  const pageMatch = matchPageRoute(routePathname);\n  if (pageMatch) {\n    return {\n      kind: \"page\",\n      route: {\n        ...route,\n        pattern: pageMatch.route.pattern,\n        params: pageMatch.params,\n      },\n    };\n  }\n\n  if (isFarmLocalAPIPathname(pathname)) {\n    return { kind: \"api\", route };\n  }\n\n  if (request.method === \"GET\" || request.method === \"HEAD\") {\n    return { kind: \"page\", route };\n  }\n\n  return { kind: \"request\", route };\n}\n\n/**\n * Get applicable layouts for a page path (from root to most specific)\n */\nfunction getApplicableLayouts(pathname) {\n  const applicable = selectApplicableLayouts(pathname);\n  // buildSSRInMemory already emits these immutable descriptors in stable depth\n  // order. Filtering preserves that order, including equal-depth ties.\n  return applicable;\n}\n\n${\n  config.docs?.enabled\n    ? `async function wrapFarmDocsResponseWithLayouts(request, response) {\n  if (request.method === \"HEAD\") return response;\n  if (response.headers.get(\"x-farm-docs-adapter\")) return response;\n\n  const pathname = getFarmRoutePathname(new URL(request.url).pathname);\n  const applicableLayouts = getApplicableLayouts(pathname);\n  if (!applicableLayouts.some((layout) => layout.shouldHydrate === true)) {\n    return response;\n  }\n\n  const source = await response.text();\n  const bodyMatch = source.match(/<body([^>]*)>([\\\\s\\\\S]*?)<\\\\/body>/i);\n  if (!bodyMatch) {\n    return new Response(source, {\n      status: response.status,\n      statusText: response.statusText,\n      headers: response.headers,\n    });\n  }\n\n  const matchedRoute = matchPageRoute(pathname);\n  const params = matchedRoute?.params || {};\n  const hydrationStrategies = applicableLayouts.flatMap((layout) =>\n    layout.shouldHydrate && layout.islandStrategy ? [layout.islandStrategy] : [],\n  );\n  const islandStrategy = hydrationStrategies.every(\n    (strategy) => strategy === hydrationStrategies[0],\n  )\n    ? (hydrationStrategies[0] || \"load\")\n    : \"load\";\n  let wrappedElement = React.createElement(\"div\", {\n    id: \"__farm_page__\",\n    \"data-farm-client\": \"false\",\n    \"data-farm-layout-client\": \"true\",\n    \"data-farm-island\": \"page\",\n    \"data-farm-island-strategy\": islandStrategy,\n    dangerouslySetInnerHTML: { __html: bodyMatch[2] },\n  });\n\n  for (let index = applicableLayouts.length - 1; index >= 0; index--) {\n    const LayoutComponent = applicableLayouts[index].module.default;\n    if (LayoutComponent) {\n      wrappedElement = React.createElement(LayoutComponent, {\n        children: wrappedElement,\n        params,\n      });\n    }\n  }\n\n  const renderedRoot = await renderFarmElement(\n    ReactDOMServer,\n    React.createElement(\n      \"div\",\n      { id: \"root\" },\n      wrapFarmRouteClientGraph(wrapWithFarmIntegrationProviders(wrappedElement)),\n    ),\n  );\n  let rootMarkup = renderedRoot.html;\n  if (rootMarkup === undefined) {\n    rootMarkup = await new Response(renderedRoot.stream).text();\n    if (renderedRoot.streamErrors.length > 0) throw renderedRoot.streamErrors[0];\n  }\n  let html = source.replace(\n    bodyMatch[0],\n    // Function replacement: rendered markup may contain $-sequences ($&, $', $$).\n    function() { return \"<body\" + bodyMatch[1] + \">\" + rootMarkup + \"</body>\"; },\n  );\n  if (renderedRoot.head) {\n    // Renderer-emitted head markup (e.g. <svelte:head>). First <title> wins,\n    // so the prebuilt shell's fallback title yields when the renderer\n    // supplies one; explicit titles are left in place.\n    if (/<title[\\\\s>]/i.test(renderedRoot.head)) {\n      html = html.replace(/<title>Farm\\\\.js App<[/]title>/i, \"\");\n    }\n    html = html.replace(/<[/]head>/i, function() { return renderedRoot.head + \"\\\\n</head>\"; });\n  }\n  if (!html.includes('href=\"/__farm_client_css_href__\"')) {\n    const clientStylesheet = '  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\\\\n';\n    const firstStyleIndex = html.search(/<style(?:\\\\s|>)/i);\n    html =\n      firstStyleIndex >= 0\n        ? html.slice(0, firstStyleIndex) + clientStylesheet + html.slice(firstStyleIndex)\n        : html.replace(/<[/]head>/i, clientStylesheet + \"</head>\");\n  }\n  if (!html.includes('id=\"__farm_route_slots_data__\"')) {\n    html = html.replace(/<[/]body>/i, function() { return renderFarmClientBootstrapScript() + \"\\\\n</body>\"; });\n  }\n  if (!html.includes('src=\"/__farm_client_js_src__\"')) {\n    html = html.replace(\n      /<[/]body>/i,\n      '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>',\n    );\n  }\n  if (!html.includes('window._$HY')) {\n    html = html.replace(/<[/]head>/i, function() { return renderFarmRendererHydrationScript() + \"\\\\n</head>\"; });\n  }\n  const headers = new Headers(response.headers);\n  headers.delete(\"content-length\");\n  headers.delete(\"etag\");\n  return new Response(html, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  });\n}`\n    : \"\"\n}\n\nconst pprShellCache = getFarmDataCache();\nconst experimentalPPREnabled = ${JSON.stringify(config.experimental?.ppr === true)};\n\nfunction resolveRouteRenderingView(route) {\n  // The same merge development uses: baked directive config under the\n  // module's explicit exports. Routes registered without either stay dynamic.\n  return mergeRouteRenderingDirectiveConfig(route && route.rendering, route && route.module, {\n    experimentalPPR: experimentalPPREnabled,\n  });\n}\n\nfunction resolvePPRConfig(route) {\n  if (!experimentalPPREnabled || !route || !route.module) {\n    return { enabled: false };\n  }\n\n  const view = resolveRouteRenderingView(route);\n  return { enabled: view.ppr, revalidate: view.revalidate };\n}\n\nfunction getPPRShellBypassReason(request, middlewareData, middlewareContext) {\n  const method = request.method.toUpperCase();\n  if (method !== \"GET\" && method !== \"HEAD\") return \"method\";\n  if (request.headers.get(\"cookie\")) return \"cookie\";\n  if (request.headers.get(\"authorization\")) return \"authorization\";\n  if (request.headers.get(\"x-farm-intercept-from\")) return \"route-interception\";\n  if (request.headers.get(\"x-farm-ppr-refresh\")) return \"refresh\";\n  if (hasConfiguredRouteContext) return \"route-context\";\n  if (middlewareData?.size) return \"middleware-data\";\n  if (middlewareContext?.size) return \"middleware-context\";\n  return undefined;\n}\n\n// origin is set when the shell carries hreflang alternates (i18n prefix\n// routing), so one host never serves a shell holding another host's URLs.\nfunction getPPRShellCacheKey(url, locale, origin) {\n  const key = [\n    \"ppr\",\n    locale || \"\",\n    normalizeRevalidatePath(url.pathname),\n    url.search,\n  ];\n  return createFarmCacheKey(origin ? key.concat(origin) : key);\n}\n\nfunction getPPRHeaders(status, config) {\n  const headers = {\n    \"X-Farm-PPR\": status,\n  };\n\n  if (status === \"bypass\") {\n    headers[\"Cache-Control\"] = \"private, no-store\";\n    return headers;\n  }\n\n  if (typeof config.revalidate === \"number\" && config.revalidate > 0) {\n    headers[\"Cache-Control\"] = \\`s-maxage=\\${config.revalidate}, stale-while-revalidate\\`;\n  }\n\n  return headers;\n}\n\nfunction getRouteSharedCacheControl(route, pprCanCache) {\n  if (!route || !route.module) {\n    return null;\n  }\n\n  const view = resolveRouteRenderingView(route);\n  if (view.dynamic === \"force-dynamic\") {\n    return null;\n  }\n  if (!view.ssg && !pprCanCache) {\n    return null;\n  }\n\n  const revalidate =\n    typeof view.revalidate === \"number\" && view.revalidate > 0 ? view.revalidate : 60;\n  return \"public, s-maxage=\" + revalidate + \", stale-while-revalidate=300\";\n}\n\nasync function getCachedPPRShell(cacheKey) {\n  const entry = await pprShellCache.getEntryAsync(cacheKey);\n  if (!entry) {\n    return null;\n  }\n\n  return entry.value.html;\n}\n\n/**\n * Main request handler - created at runtime with bundled routes\n */\nasync function handleFarmRequest(request, adapterContext) {\n  // Share only this request's parse. Rewrites and middleware replacements keep\n  // their own URL, while response negotiation retains the original pathname.\n  const requestUrl = new URL(request.url);\n  const response = await ${\n    config.i18n.enabled\n      ? `_runWithFarmI18nRequest(\n    farmI18nRuntime,\n    request,\n    async function(farmLocaleResolution) {\n      if (\n        farmLocaleResolution.redirect &&\n        (request.method === \"GET\" || request.method === \"HEAD\")\n      ) {\n        return applyFarmI18nResponse(\n          new Response(null, {\n            status: 307,\n            headers: { Location: farmLocaleResolution.redirect },\n          }),\n          farmLocaleResolution\n        );\n      }\n      const response = await handleFarmRequestInContext(\n        request,\n        farmLocaleResolution,\n        false,\n        Date.now(),\n        adapterContext,\n        requestUrl,\n      );\n      return applyFarmI18nResponse(response, farmLocaleResolution);\n    },\n    { redirect: !isFarmLocalAPIPathname(requestUrl.pathname) }\n  )`\n      : \"handleFarmRequestInContext(request, null, false, Date.now(), adapterContext, requestUrl)\"\n  };\n  ${\n    config.md?.enabled\n      ? `const pathname = getFarmRoutePathname(requestUrl.pathname);\n  if (matchPageRoute(pathname)) {\n    return applyMarkdownNegotiationHeaders(response, {\n      config: farmMarkdownConfig,\n      pathname,\n    });\n  }`\n      : \"\"\n  }\n  return response;\n}\n\nasync function handleFarmRequestInContext(\n  request,\n  farmLocaleResolution,\n  configuredRewriteApplied = false,\n  requestStartTime = Date.now(),\n  adapterContext,\n  requestUrl = new URL(request.url),\n) {\n  let url = requestUrl;\n  let pathname = url.pathname;\n  let routePathname = getFarmRoutePathname(pathname);\n\n  // Redirects have precedence over local routes. Configured rewrites use\n  // after-files semantics so emitted page, API, integration, docs, image, and\n  // metadata routes keep their normal method/status handling. Internal rewrite\n  // targets re-enter this handler so middleware and request-local state observe\n  // the rewritten URL; external destinations are proxied transparently.\n  if (!configuredRewriteApplied) {\n    const redirectMatch = matchRedirectRoute(\n      routePathname,\n      farmLocaleResolution?.locale,\n      url.search,\n    );\n    if (redirectMatch) {\n      return new Response(\"Redirecting to \" + redirectMatch.destination, {\n        status: redirectMatch.statusCode,\n        headers: { Location: redirectMatch.destination },\n      });\n    }\n\n    if (\n      configuredRewriteRoutes.length > 0 &&\n      !hasLocalRequestRoute(request, routePathname)\n    ) {\n      const rewriteDestination = matchRewriteRoute(\n        routePathname,\n        farmLocaleResolution?.locale,\n      );\n      if (rewriteDestination) {\n        const rewrittenRequest = createRewrittenRequest(request, rewriteDestination);\n        if (new URL(rewrittenRequest.url).origin !== url.origin) {\n          return globalThis.fetch(rewrittenRequest);\n        }\n        return _runWithCurrentRequest(rewrittenRequest, () =>\n          handleFarmRequestInContext(\n            rewrittenRequest,\n            farmLocaleResolution,\n            true,\n            requestStartTime,\n            adapterContext,\n          )\n        );\n      }\n    }\n  }\n\n  if (farmImageHandler && pathname === ${JSON.stringify(config.images.path)}) {\n    const imageResponse = await farmImageHandler(request, {\n      trustedLocalOrigin: adapterContext?.trustedLocalOrigin,\n    });\n    if (imageResponse) {\n      return imageResponse;\n    }\n  }\n\n  ${\n    hasServerRuntimeIntegrations\n      ? `\n  const integrationDispatch = await handleIntegrationRequest(cloneFarmRequestWithContext(request));\n  if (integrationDispatch.response) {\n    return integrationDispatch.response;\n  }\n  // A middleware that refreshed a session and let the request continue handed\n  // its rotated Set-Cookie values back here. They belong on whatever response\n  // the page or API handler produces, so they ride the same deferred-header\n  // channel the file middleware runner already uses.\n  const farmIntegrationSetCookies = integrationDispatch.setCookies;\n  `\n      : \"\"\n  }\n\n  ${\n    hasMiddlewareRuntime\n      ? `\n  const requestBeforeMiddleware = request;\n  const middlewareResult = await farmMiddlewareRunner(request, {\n    clientAddress: adapterContext?.clientAddress,\n  });\n  if (middlewareResult.response) {\n    return middlewareResult.response;\n  }\n  request = middlewareResult.request;\n  const middlewareData = middlewareResult.data;\n  const middlewareContext = middlewareResult.context;\n  const middlewareHeaders = ${\n    hasServerRuntimeIntegrations\n      ? \"withFarmIntegrationSetCookies(middlewareResult.headers, farmIntegrationSetCookies)\"\n      : \"middlewareResult.headers\"\n  };\n  // A Request's url is already serialized, so an unchanged href means middleware\n  // kept the URL and the pre-middleware parse still describes it.\n  if (request.url !== url.href) {\n    url = new URL(request.url);\n    pathname = url.pathname;\n    routePathname = getFarmRoutePathname(pathname);\n  }\n\n  // Middleware may replace the Request when it rewrites a URL. Re-enter the\n  // request store so pages, layouts, and route context observe that rewritten\n  // request instead of the original outer-handler value.\n  const runResolvedRequest = async () => {\n    if (middlewareResult.notFound) return renderFarmNotFoundResponse();\n  `\n      : `\n  const middlewareData = undefined;\n  const middlewareContext = undefined;\n  const middlewareHeaders = ${\n    hasServerRuntimeIntegrations\n      ? \"withFarmIntegrationSetCookies(undefined, farmIntegrationSetCookies)\"\n      : \"undefined\"\n  };\n  `\n  }\n\n  ${\n    config.docs?.enabled\n      ? `\n  // Docs responses are served after app middleware so route guards and\n  // middleware headers apply to the docs engine like any other page content.\n  // An app's own llms.txt, llms-full.txt, sitemap.xml, and robots.txt take\n  // those paths from the docs engine.\n  if (farmDocsHandler${(() => {\n    const owned = getFarmAppOwnedDocsEnginePaths(config.agent, applicationMetadataRoutes);\n    return owned.length\n      ? ` && !${JSON.stringify(owned)}.includes(normalizeRuntimePath(routePathname))`\n      : \"\";\n  })()}) {\n    const docsResponse = await farmDocsHandler(cloneFarmRequestWithContext(request));\n    if (docsResponse) {\n      if (!docsResponse.headers.get(\"content-type\")?.toLowerCase().includes(\"text/html\")) {\n        return applyProductionMiddlewareHeaders(docsResponse, middlewareHeaders);\n      }\n      const wrappedDocsResponse = await wrapFarmDocsResponseWithLayouts(\n        request,\n        docsResponse,\n      );\n      const docsHeaders = new Headers(wrappedDocsResponse.headers);\n      docsHeaders.set(\"x-farm-preload-buffered\", \"1\");\n      return applyProductionMiddlewareHeaders(new Response(wrappedDocsResponse.body, {\n        status: wrappedDocsResponse.status,\n        statusText: wrappedDocsResponse.statusText,\n        headers: docsHeaders,\n      }), middlewareHeaders);\n    }\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    hasMarkdownPages\n      ? `\n  // The raw markdown source of a page route is the page's content in another\n  // representation; middleware guarding the route must run before serving it.\n  const markdownSourceResponse = await createFarmMarkdownSourceResponse?.({\n    request: cloneFarmRequestWithContext(request),\n    config: farmMdxConfig,\n    resolveSource: (targetPathname) => {\n      const match = matchPageRoute(getFarmRoutePathname(targetPathname));\n      return match?.route?.markdownSource || null;\n    },\n  });\n  if (markdownSourceResponse) {\n    return applyProductionMiddlewareHeaders(markdownSourceResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    config.md?.enabled\n      ? `\n  if (farmMarkdownConfig?.enabled) {\n    const markdownResponse = await createMarkdownMirrorResponse({\n      // The mirror helper only reads metadata and creates its own GET request.\n      // Cloning here needlessly tees bodies even when negotiation rejects them.\n      request,\n      // Middleware and configured rewrites have already resolved this URL.\n      requestUrl: url,\n      config: farmMarkdownConfig,\n      routeExists: (targetPathname) =>\n        Boolean(matchPageRoute(getFarmRoutePathname(targetPathname))),\n      renderPage: (targetRequest) => handleFarmRequest(targetRequest, adapterContext),\n    });\n    if (markdownResponse) {\n      return applyProductionMiddlewareHeaders(markdownResponse, middlewareHeaders);\n    }\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    apiRoutes.length > 0\n      ? `\n  const apiResponse = await handleAPIRequest(cloneFarmRequestWithContext(request));\n  if (apiResponse) {\n    return applyProductionMiddlewareHeaders(apiResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n\n  if (\n    farmOpenAPIReference &&\n    farmOpenAPIReference.specRoute &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.specRoute)\n  ) {\n    const method = request.method.toUpperCase();\n    const specResponse = method === \"GET\" || method === \"HEAD\"\n      ? new Response(method === \"HEAD\" ? null : JSON.stringify(farmOpenAPIReference.spec), {\n          status: 200,\n          headers: {\n            \"Content-Type\": \"application/json; charset=utf-8\",\n            \"Cache-Control\": \"public, max-age=0, must-revalidate\",\n            \"X-Content-Type-Options\": \"nosniff\",\n          },\n        })\n      : new Response(\"Method Not Allowed\", {\n          status: 405,\n          headers: {\n            \"Allow\": \"GET, HEAD\",\n            \"Content-Type\": \"text/plain; charset=utf-8\",\n          },\n        });\n    return applyProductionMiddlewareHeaders(specResponse, middlewareHeaders);\n  }\n\n  if (\n    farmOpenAPIReference &&\n    normalizeRuntimePath(pathname) === normalizeRuntimePath(farmOpenAPIReference.route)\n  ) {\n    const method = request.method.toUpperCase();\n    const response = method === \"GET\" || method === \"HEAD\"\n      ? new Response(method === \"HEAD\" ? null : farmOpenAPIReference.html, {\n          status: 200,\n          headers: {\n            \"Content-Type\": \"text/html; charset=utf-8\",\n            \"Cache-Control\": \"public, max-age=0, must-revalidate\",\n            \"X-Content-Type-Options\": \"nosniff\",\n          },\n        })\n      : new Response(\"Method Not Allowed\", {\n          status: 405,\n          headers: {\n            \"Allow\": \"GET, HEAD\",\n            \"Content-Type\": \"text/plain; charset=utf-8\",\n          },\n        });\n    return applyProductionMiddlewareHeaders(response, middlewareHeaders);\n  }\n\n  ${\n    metadataImageRoutes.length > 0\n      ? `\n  const metadataImageResponse = await handleMetadataImageRequest(\n    cloneFarmRequestWithContext(request),\n    routePathname\n  );\n  if (metadataImageResponse) {\n    return applyProductionMiddlewareHeaders(metadataImageResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    applicationMetadataRoutes.length > 0\n      ? `\n  const applicationMetadataResponse = await handleApplicationMetadataRouteRequest(\n    cloneFarmRequestWithContext(request),\n    routePathname\n  );\n  if (applicationMetadataResponse) {\n    return applyProductionMiddlewareHeaders(applicationMetadataResponse, middlewareHeaders);\n  }\n  `\n      : \"\"\n  }\n  ${\n    servesAgentRobotsTxt\n      ? `\n  // agent.crawlers with no robots.ts: serve the generated file.\n  if (normalizeRuntimePath(routePathname) === \"/robots.txt\") {\n    return applyProductionMiddlewareHeaders(\n      createFarmAgentRobotsResponse(request),\n      middlewareHeaders,\n    );\n  }\n  `\n      : \"\"\n  }\n  ${\n    config.agent?.llmsTxt?.enabled\n      ? `\n  // agent.llmsTxt with no llms.ts or llms-full.ts: serve the generated files.\n  const farmGeneratedLlmsKind = normalizeRuntimePath(routePathname) === \"/llms.txt\"\n    ? \"llms\"\n    : ${config.agent?.llmsTxt?.full ? `normalizeRuntimePath(routePathname) === \"/llms-full.txt\" ? \"llms-full\" : ` : \"\"}null;\n  if (farmGeneratedLlmsKind) {\n    const llmsContext = createFarmLlmsTxtContext(request, farmGeneratedLlmsKind === \"llms-full\");\n    const llmsBody = farmGeneratedLlmsKind === \"llms-full\"\n      ? await renderFarmLlmsFullTxt(llmsContext.defaults, {\n          origin: new URL(request.url).origin,\n          readMarkdown: llmsContext.markdown,\n        })\n      : llmsContext.defaults;\n    return applyProductionMiddlewareHeaders(\n      createFarmMetadataRouteResponse(\n        farmGeneratedLlmsKind,\n        llmsBody,\n        { revalidate: farmLlmsTxtConfig.revalidate },\n        { method: request.method },\n      ),\n      middlewareHeaders,\n    );\n  }\n  `\n      : \"\"\n  }\n\n  ${\n    config.docs?.enabled\n      ? `if (farmDocsAPIHandler && isFarmDocsAPIRequest(pathname)) {\n    const docsAPIResponse = await farmDocsAPIHandler(cloneFarmRequestWithContext(request));\n    if (docsAPIResponse) {\n      return applyProductionMiddlewareHeaders(docsAPIResponse, middlewareHeaders);\n    }\n  }`\n      : \"\"\n  }\n\n  // Preserve the explicit JSON 404 for misses below the configured local API path.\n  if (isFarmLocalAPIPathname(pathname)) {\n    return applyProductionMiddlewareHeaders(new Response(\n      JSON.stringify({ error: \"API route not found\", pathname }),\n      { status: 404, headers: { \"Content-Type\": \"application/json\" } }\n    ), middlewareHeaders);\n  }\n\n  // Handle page routes (SSR)\n  emitFarmEvent({ type: \"render.start\", route: pathname, pathname });\n  const matchedRoute = matchPageRoute(routePathname);\n  if (matchedRoute) {\n    const trailingSlashLocation = resolveFarmTrailingSlashRedirect(\n      url,\n      ${JSON.stringify(config.trailingSlash)}\n    );\n    if (trailingSlashLocation) {\n      return applyProductionMiddlewareHeaders(\n        new Response(null, {\n          status: 308,\n          headers: { Location: trailingSlashLocation },\n        }),\n        middlewareHeaders\n      );\n    }\n    const { route, params } = matchedRoute;\n    emitFarmEvent({ type: \"route.matched\", pathname, route: route.pattern, params });\n    \n    try {\n      const pprConfig = resolvePPRConfig(route);\n      const pprBypassReason = pprConfig.enabled\n        ? getPPRShellBypassReason(request, middlewareData, middlewareContext)\n        : undefined;\n      let pprCanCache = pprConfig.enabled && !pprBypassReason;\n      const pprCacheKey = pprCanCache\n        ? getPPRShellCacheKey(\n            url,\n            farmLocaleResolution?.locale,\n            farmLocaleResolution && farmI18nConfig.routing !== \"none\"\n              ? resolveFarmI18nAlternateOrigin(request)\n              : \"\"\n          )\n        : null;\n      if (pprConfig.enabled && pprBypassReason) {\n        emitFarmEvent({ type: \"ppr.shell.bypass\", route: pathname, reason: pprBypassReason });\n        emitFarmEvent({ type: \"cache.bypass\", route: pathname, reason: pprBypassReason });\n        if (pprBypassReason === \"refresh\") {\n          emitFarmEvent({ type: \"ppr.refresh.start\", route: pathname });\n        }\n      }\n      if (pprCacheKey) {\n        const cachedPPRShell = await getCachedPPRShell(pprCacheKey);\n        if (cachedPPRShell) {\n          emitFarmEvent({ type: \"ppr.shell.hit\", route: pathname, key: pprCacheKey });\n          emitFarmEvent({\n            type: \"render.complete\",\n            route: pathname,\n            pathname,\n            status: 200,\n            durationMs: Date.now() - requestStartTime,\n          });\n          return rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(cachedPPRShell, {\n            status: 200,\n            headers: {\n              \"Content-Type\": \"text/html; charset=utf-8\",\n              \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(cachedPPRShell),\n              ...(farmFontPreloadHeader ? { \"Link\": farmFontPreloadHeader } : {}),\n              ...getPPRHeaders(\"hit\", pprConfig),\n            },\n          }), middlewareHeaders), cachedPPRShell);\n        }\n        emitFarmEvent({ type: \"ppr.shell.miss\", route: pathname, key: pprCacheKey });\n      }\n\n      // Get the page component and metadata\n      let PageComponent = route.module.default;\n      let pageStatus = 200;\n      const pageMetadata = route.module.metadata || {};\n      \n      // Get applicable layouts for this page\n      const applicableLayouts = getApplicableLayouts(routePathname);\n      const shouldHydrateLayout = applicableLayouts.some(\n        (layout) => layout.shouldHydrate === true,\n      );\n      const hydrationStrategies = [\n        ...(route.shouldHydrate && route.islandStrategy ? [route.islandStrategy] : []),\n        ...applicableLayouts.flatMap((layout) =>\n          layout.shouldHydrate && layout.islandStrategy ? [layout.islandStrategy] : [],\n        ),\n      ];\n      const hydrationIslandStrategy = hydrationStrategies.every(\n        (strategy) => strategy === hydrationStrategies[0],\n      )\n        ? (hydrationStrategies[0] || \"load\")\n        : \"load\";\n      const selectedRouteSlots = matchRouteSlots(\n        routePathname,\n        request.headers.get(\"x-farm-intercept-from\"),\n      );\n      \n      if (PageComponent) {\n        // Parse search params - make it a resolved Promise for async components\n        const searchParamsObj = searchParamsToObject(url.searchParams);\n        \n        // Render the page component\n        const routeContext = hasConfiguredRouteContext\n          ? await resolveFarmRouteContext(farmResolvedRuntimeConfig, {\n              request,\n              params,\n              search: searchParamsObj,\n              path: pathname,\n            })\n          : undefined;\n        const rawPageProps = withFarmRouteContext(\n          {\n            params,\n            searchParams: Promise.resolve(searchParamsObj),\n            path: pathname,\n            ...(middlewareData?.size ? { middleware: { data: middlewareData } } : {}),\n          },\n          routeContext,\n        );\n        // Generated programmatic route modules consume app context from the\n        // public context prop while source-created modules read the symbol\n        // carrier above. Expose it only while resolving server route data.\n        if (route.module.__farmResolveRouteProps && routeContext !== undefined) {\n          Object.defineProperty(rawPageProps, \"context\", {\n            value: routeContext,\n            enumerable: true,\n            configurable: true,\n          });\n        }\n        let pageProps;\n        try {\n          // Resolve top-level route state before starting the HTTP stream so\n          // redirects, notFound(), and failures keep their real status. Route\n          // data may still contain explicit defer() values for nested Suspense.\n          pageProps = route.module.__farmResolveRouteProps\n            ? await route.module.__farmResolveRouteProps(rawPageProps)\n            : (() => {\n              const routeSchemas = route.module.__farmRouteParsesProps\n                ? {}\n                : route.module.__farmRouteSchemas || {};\n              const parsedParams = routeSchemas.params?.parse\n                ? routeSchemas.params.parse(params)\n                : params;\n              const parsedSearch = routeSchemas.search?.parse\n                ? routeSchemas.search.parse(searchParamsObj)\n                : searchParamsObj;\n              return {\n                ...rawPageProps,\n                params: parsedParams,\n                search: parsedSearch,\n                searchParams: Promise.resolve(parsedSearch),\n              };\n            })();\n          if (\n            route.module.__farmResolveRouteProps &&\n            routeContext !== undefined &&\n            pageProps.context === routeContext\n          ) {\n            const { context: _routeContext, ...renderPageProps } = pageProps;\n            pageProps = renderPageProps;\n          }\n        } catch (routeStateError) {\n          if (isFarmRedirectError(routeStateError)) throw routeStateError;\n\n          const routeComponents = route.module.__farmRouteComponents;\n          const routeStateProps = {\n            ...rawPageProps,\n            search: searchParamsObj,\n            searchParams: Promise.resolve(searchParamsObj),\n            error: routeStateError,\n          };\n          if (isFarmNotFoundError(routeStateError) && routeComponents?.notFound) {\n            pageStatus = 404;\n            PageComponent = routeComponents.notFound;\n            pageProps = routeStateProps;\n          } else if (routeComponents?.error) {\n            pageStatus = 500;\n            PageComponent = routeComponents.error;\n            pageProps = routeStateProps;\n          } else {\n            throw routeStateError;\n          }\n        }\n\n        const renderedRouteSlots = await Promise.all(\n          selectedRouteSlots.map(async function(slot) {\n            const slotContext = hasConfiguredRouteContext\n              ? await resolveFarmRouteContext(farmResolvedRuntimeConfig, {\n                  request,\n                  params: slot.params,\n                  search: searchParamsObj,\n                  path: pathname,\n                })\n              : undefined;\n            const rawSlotProps = withFarmRouteContext(\n              {\n                params: slot.params,\n                searchParams: Promise.resolve(searchParamsObj),\n                path: pathname,\n                ...(middlewareData?.size ? { middleware: { data: middlewareData } } : {}),\n              },\n              slotContext,\n            );\n            if (slot.module.__farmResolveRouteProps && slotContext !== undefined) {\n              Object.defineProperty(rawSlotProps, \"context\", {\n                value: slotContext,\n                enumerable: true,\n                configurable: true,\n              });\n            }\n\n            const slotSchemas = slot.module.__farmRouteParsesProps\n              ? {}\n              : slot.module.__farmRouteSchemas || {};\n            let slotProps = slot.module.__farmResolveRouteProps\n              ? await slot.module.__farmResolveRouteProps(rawSlotProps)\n              : {\n                  ...rawSlotProps,\n                  params: slotSchemas.params?.parse\n                    ? slotSchemas.params.parse(slot.params)\n                    : slot.params,\n                  search: slotSchemas.search?.parse\n                    ? slotSchemas.search.parse(searchParamsObj)\n                    : searchParamsObj,\n                  searchParams: Promise.resolve(\n                    slotSchemas.search?.parse\n                      ? slotSchemas.search.parse(searchParamsObj)\n                      : searchParamsObj,\n                  ),\n                };\n            if (\n              slot.module.__farmResolveRouteProps &&\n              slotContext !== undefined &&\n              slotProps.context === slotContext\n            ) {\n              const { context: _slotContext, ...renderSlotProps } = slotProps;\n              slotProps = renderSlotProps;\n            }\n\n            return { ...slot, props: slotProps };\n          }),\n        );\n        const clientMiddleware = middlewareData?.size\n          ? { data: Object.fromEntries(middlewareData) }\n          : undefined;\n        const clientPageProps = {\n          params: pageProps.params,\n          search: pageProps.search ?? searchParamsObj,\n          searchParams: pageProps.search ?? searchParamsObj,\n          ...(\"data\" in pageProps ? { data: pageProps.data } : {}),\n          ...(pageProps.__farmCanonicalPath\n            ? { __farmCanonicalPath: pageProps.__farmCanonicalPath }\n            : {}),\n          ...(pageProps.__farmRoutePropsResolved\n            ? { __farmRoutePropsResolved: true }\n            : {}),\n          path: pathname,\n          ...(clientMiddleware ? { middleware: clientMiddleware } : {}),\n        };\n        const routeSlotPayload = renderedRouteSlots.map(function(slot) {\n          return {\n            name: slot.name,\n            ownerPattern: slot.ownerPattern,\n            pattern: slot.pattern,\n            containerId: slot.containerId,\n            interception: slot.interception,\n            fallback: slot.fallback,\n            props: {\n              params: slot.props.params,\n              search: slot.props.search || searchParamsObj,\n              searchParams: slot.props.search || searchParamsObj,\n              ...(\"data\" in slot.props ? { data: slot.props.data } : {}),\n              path: pathname,\n              ...(clientMiddleware ? { middleware: clientMiddleware } : {}),\n            },\n          };\n        });\n        \n        const renderPageElement = async () => {\n            // First, render the page content\n            let pageElement;\n\n            // Only genuinely async components are executed directly; source\n            // sniffing is unsound because any sync component whose source\n            // contains \"async\" (e.g. an async event handler) would be called\n            // outside React, breaking hooks and re-running side effects.\n            // Errors, including redirect/notFound controls, propagate to the\n            // outer request handler exactly like sync render errors.\n            if (typeof PageComponent === \"function\" && PageComponent.constructor.name === \"AsyncFunction\") {\n              const result = await PageComponent(pageProps);\n              if (React.isValidElement(result)) {\n                pageElement = result;\n              } else {\n                pageElement = React.createElement(\"div\", null, String(result));\n              }\n            } else {\n              // Sync component - create element directly\n              pageElement = React.createElement(PageComponent, pageProps);\n            }\n\n            if (route.shouldHydrate && !shouldHydrateLayout) {\n              pageElement = wrapFarmRouteClientGraph(pageElement);\n            } else if (shouldHydrateLayout && !route.shouldHydrate) {\n              pageElement = isolateFarmRouteServerPage(pageElement);\n            }\n\n            pageElement = React.createElement(\n              \"div\",\n              {\n                id: \"__farm_page__\",\n                \"data-farm-segment\": \"page\",\n                \"data-farm-client\": route.shouldHydrate ? \"true\" : \"false\",\n                ...(shouldHydrateLayout\n                  ? { \"data-farm-layout-client\": \"true\" }\n                  : {}),\n                \"data-farm-island\": \"page\",\n                \"data-farm-island-strategy\": hydrationIslandStrategy,\n              },\n              pageElement,\n            );\n\n            // Wrap with layouts (from innermost to outermost)\n            // Layouts are sorted by depth (root first), so we process in reverse\n            let wrappedElement = pageElement;\n            for (let i = applicableLayouts.length - 1; i >= 0; i--) {\n              const layout = applicableLayouts[i];\n              const LayoutComponent = layout.module.default;\n              if (LayoutComponent) {\n                const slotProps = {};\n                for (const slot of renderedRouteSlots) {\n                  if (slot.ownerPattern !== layout.pattern) continue;\n                  slotProps[slot.name] = React.createElement(\n                    \"div\",\n                    {\n                      id: slot.containerId,\n                      \"data-farm-route-slot\": slot.name,\n                      \"data-farm-slot-owner\": slot.ownerPattern,\n                    },\n                    wrapFarmRouteClientGraph(\n                      React.createElement(slot.module.default, slot.props),\n                    ),\n                  );\n                }\n                wrappedElement = React.createElement(LayoutComponent, {\n                  children: wrappedElement,\n                  params,\n                  ...slotProps,\n                });\n                wrappedElement = React.createElement(\n                  \"div\",\n                  {\n                    \"data-farm-layout-boundary\": \"true\",\n                    \"data-farm-layout-pattern\": layout.pattern,\n                    style: { display: \"contents\" },\n                  },\n                  wrappedElement,\n                );\n              }\n            }\n\n          if (shouldHydrateLayout) {\n            wrappedElement = wrapFarmRouteClientGraph(wrappedElement);\n          }\n\n          wrappedElement = wrapWithFarmIntegrationProviders(wrappedElement);\n          return renderFarmElement(ReactDOMServer, wrappedElement);\n        };\n        const renderedPage = ${\n          hasMiddlewareRuntime\n            ? `await _runWithMiddlewareData(middlewareData, () =>\n          _runWithMiddlewareContext(middlewareContext, renderPageElement)\n        )`\n            : \"await renderPageElement()\"\n        };\n\n        // A completed document is not a reusable PPR shell: it already contains\n        // the request's resolved Suspense content. Until the production runtime\n        // can persist and resume the partial shell itself, buffer streamed PPR\n        // responses for late status errors but do not cache their dynamic HTML.\n        const shouldCachePPRShell = Boolean(pprCacheKey && !renderedPage.stream);\n        if (!shouldCachePPRShell && pprCacheKey) {\n          pprCanCache = false;\n          emitFarmEvent({\n            type: \"ppr.shell.bypass\",\n            route: pathname,\n            reason: \"suspense-stream\",\n          });\n          emitFarmEvent({ type: \"cache.bypass\", route: pathname, reason: \"suspense-stream\" });\n        }\n        \n        // Collect static and generated metadata from layouts and page.\n        // Later entries override earlier entries, matching the development renderer.\n        let mergedMetadata = {};\n        for (const layout of applicableLayouts) {\n          mergedMetadata = mergeMetadata(mergedMetadata, layout.module.metadata);\n          if (typeof layout.module.generateMetadata === \"function\") {\n            mergedMetadata = mergeMetadata(\n              mergedMetadata,\n              await layout.module.generateMetadata({ params: pageProps.params }),\n            );\n          }\n        }\n        mergedMetadata = mergeMetadata(mergedMetadata, pageMetadata);\n        if (typeof route.module.generateMetadata === \"function\") {\n          mergedMetadata = mergeMetadata(\n            mergedMetadata,\n            await route.module.generateMetadata(pageProps),\n          );\n        }\n\n        if (!mergedMetadata.manifest) {\n          const manifestMatch = getMatchingApplicationMetadataRoute(routePathname, \"manifest\");\n          if (manifestMatch) {\n            mergedMetadata.manifest = createApplicationMetadataHref(\n              manifestMatch,\n              farmLocaleResolution?.locale,\n            );\n          }\n        }\n\n        for (const kind of [\"opengraph\", \"twitter\"]) {\n          const imageMatch = getMatchingMetadataImage(routePathname, kind);\n          if (imageMatch) {\n            mergedMetadata = addMetadataImageReference(\n              mergedMetadata,\n              createMetadataImageReference(imageMatch, farmLocaleResolution?.locale),\n            );\n          }\n        }\n        ${\n          config.md?.enabled\n            ? `\n        // Advertise the Markdown mirror in the head as well as the Link header,\n        // using the public path the .md request will be resolved against.\n        mergedMetadata = addMetadataMarkdownAlternate(\n          mergedMetadata,\n          getFarmMarkdownAlternatePath(farmMarkdownConfig, pathname),\n        );`\n            : \"\"\n        }\n\n        const renderedMetadata = renderMetadataHead(mergedMetadata, { pathname, jsonLd: ${JSON.stringify(config.agent?.jsonLd ?? false)} });\n        const title = renderedMetadata.title;\n        const metaTags = renderedMetadata.tags;\n        const hasFavicon = renderedMetadata.hasFavicon;\n\n        const hasPrivateRequestHeaders = hasPrivateFarmRequestHeaders(\n          request,\n          farmLocaleResolution,\n        );\n        const hasRequestScopedRender = Boolean(\n          pageStatus >= 400 ||\n          request.headers.get(\"x-farm-intercept-from\") ||\n          hasPrivateRequestHeaders ||\n          hasConfiguredRouteContext ||\n          middlewareData?.size ||\n          middlewareContext?.size\n        );\n        const sharedCacheControl = getRouteSharedCacheControl(route, pprCanCache);\n        const responseHeaders = {\n          \"Content-Type\": \"text/html; charset=utf-8\",\n          \"Cache-Control\": renderedPage.stream || hasRequestScopedRender || !sharedCacheControl\n            ? \"private, no-store\"\n            : sharedCacheControl,\n          ...(farmFontPreloadHeader ? { \"Link\": farmFontPreloadHeader } : {}),\n          ...(pprConfig.enabled ? getPPRHeaders(pprCanCache ? \"miss\" : \"bypass\", pprConfig) : {}),\n        };\n        const farmI18nSnapshot = getFarmI18nSnapshot();\n        let html = renderedPage.html;\n        \n        // Check if the layout already rendered a full HTML document\n        const initialHtml = html !== undefined ? html : renderedPage.shellHtml || \"\";\n        const hasFullDocument = opensFarmFullDocument(initialHtml);\n\n        // Stream a suspended body as soon as React's shell is ready. Full-document\n        // layouts, localized documents, and cacheable PPR shells still use the\n        // buffered path because they require whole-document transformation.\n        if (\n          pageStatus === 200 &&\n          renderedPage.stream &&\n          !hasFullDocument &&\n          !farmI18nSnapshot &&\n          !pprCacheKey\n        ) {\n          const farmThemeDocument = createFarmThemeDocumentParts(\n            farmThemeConfig,\n            farmResolvedRuntimeConfig.basePath,\n            getFarmTheme(request)\n          );\n          const streamPrefix = '<!DOCTYPE html>\\\\n<html lang=\"en\">\\\\n<head>\\\\n' +\n            farmThemeDocument.head + '\\\\n' +\n            '  <meta charset=\"utf-8\">\\\\n' +\n            '  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\\\\n' +\n            (hasFavicon ? '' : '  <link rel=\"icon\" href=\"data:,\">\\\\n') +\n            '  <title>' + title + '</title>' + metaTags + '\\\\n' +\n            '  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\\\\n' +\n            '  <link rel=\"modulepreload\" href=\"/__farm_client_js_src__\">\\\\n' +\n            renderFarmRendererHydrationScript() + '\\\\n' +\n            '</head>\\\\n<body>\\\\n  <div id=\"root\">';\n          const streamSuffix = '</div>\\\\n' +\n            '  ' + renderFarmClientBootstrapScript(\n              pageProps.__farmCanonicalPath,\n              routeSlotPayload,\n              clientPageProps\n            ) + '\\\\n' +\n            '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n' +\n            '</body>\\\\n</html>';\n          const themedStreamPrefix = streamPrefix.replace(\n            '<html lang=\"en\">',\n            () => '<html lang=\"en\"' + farmThemeDocument.attributes + '>'\n          );\n          const streamedDocument = createFarmDocumentStream(\n            renderedPage.stream,\n            themedStreamPrefix,\n            async function() {\n              // A redirect()/notFound() after the 200 shell went out can only\n              // be recovered in the document.\n              const lateNavigationError = renderedPage.streamErrors.find(function(error) {\n                return isFarmRedirectError(error) || isFarmNotFoundError(error);\n              });\n              if (!lateNavigationError) return streamSuffix;\n              if (isFarmRedirectError(lateNavigationError)) {\n                return createLateRedirectRecovery(\n                  getFarmRedirectError(lateNavigationError).url\n                ) + streamSuffix;\n              }\n              try {\n                return createLateNotFoundRecovery(\n                  await ReactDOMServer.renderToString(\n                    wrapWithFarmIntegrationProviders(createFarmNotFoundElement(pathname))\n                  )\n                ) + streamSuffix;\n              } catch (error) {\n                // The layouts are already in the shell; a not-found page that\n                // needs their context cannot render alone, so use Farm's.\n                console.warn(\"not-found page could not render outside its layout, using Farm's:\", error);\n                return createLateNotFoundRecovery(\n                  await ReactDOMServer.renderToString(React.createElement(FarmDefault404Page))\n                ) + streamSuffix;\n              }\n            },\n            function() {\n              if (pprBypassReason === \"refresh\") {\n                emitFarmEvent({\n                  type: \"ppr.refresh.complete\",\n                  route: pathname,\n                  durationMs: Date.now() - requestStartTime,\n                });\n              }\n              emitFarmEvent({\n                type: \"render.complete\",\n                route: pathname,\n                pathname,\n                status: pageStatus,\n                durationMs: Date.now() - requestStartTime,\n              });\n            }\n          );\n          return applyProductionMiddlewareHeaders(new Response(streamedDocument, {\n            status: pageStatus,\n            headers: { ...responseHeaders, \"x-farm-preload-streaming\": \"1\" },\n          }), middlewareHeaders);\n        }\n\n        if (html === undefined) {\n          html = await new Response(renderedPage.stream).text();\n          if (renderedPage.streamErrors.length > 0) {\n            throw renderedPage.streamErrors[0];\n          }\n        }\n        \n        const rendererHead = renderedPage.head || \"\";\n        const rendererHasTitle = /<title[\\\\s>]/i.test(rendererHead);\n        // First <title> wins: the fallback framework title yields to a\n        // renderer-emitted one; explicit metadata titles still come first.\n        const suppressDefaultTitle =\n          !renderedMetadata.hasExplicitTitle && rendererHasTitle;\n        let fullHtml;\n        if (hasFullDocument) {\n          // Layout provides full HTML structure - inject CSS and client script\n          html = ensureFarmDocumentRoot(\n            ensureFarmDocumentHead(extractFarmFullDocument(html) || html),\n          );\n          fullHtml = html\n            // Inject CSS link after opening head tag or first meta tag\n            .replace(/<head([^>]*)>/i, '<head$1>\\\\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">')\n            .replace(/<\\\\/head>/i, () => renderFarmRendererHydrationScript() + '\\\\n</head>')\n            // Explicit metadata wins over renderer and layout titles. Without\n            // explicit metadata, a renderer title wins over the layout title.\n            .replace(/<head([^>]*)>([\\\\s\\\\S]*?)<\\\\/head>/i, (match, attrs, headContent) => {\n              const hasAuthoritativeTitle = renderedMetadata.hasExplicitTitle || rendererHasTitle;\n              let nextHeadContent = hasAuthoritativeTitle\n                ? headContent.replace(/<title\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/title>\\\\s*/gi, \"\")\n                : headContent;\n              if (renderedMetadata.hasExplicitTitle) {\n                nextHeadContent += \"\\\\n  <title>\" + title + \"</title>\";\n              }\n              if (metaTags) nextHeadContent += metaTags;\n              // Renderer-emitted head markup (e.g. <svelte:head>). Function\n              // replacement below keeps $-sequences literal.\n              const effectiveRendererHead = renderedMetadata.hasExplicitTitle\n                ? rendererHead.replace(/<title\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/title>\\\\s*/gi, \"\")\n                : rendererHead;\n              if (effectiveRendererHead) nextHeadContent += \"\\\\n  \" + effectiveRendererHead;\n              return nextHeadContent === headContent\n                ? match\n                : \"<head\" + attrs + \">\" + nextHeadContent + \"\\\\n</head>\";\n            })\n            // Inject client script before closing body tag. Function replacement:\n            // serialized page props may contain $-sequences ($&, $', $$) that a\n            // string replacement would expand into surrounding document markup,\n            // corrupting the inline bootstrap script.\n            .replace(\n              /<\\\\/body>/i,\n              () => '  ' + renderFarmClientBootstrapScript(\n                pageProps.__farmCanonicalPath,\n                routeSlotPayload,\n                clientPageProps\n              ) + '\\\\n' +\n                '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>',\n            );\n          \n          // Add DOCTYPE if not present\n          if (!fullHtml.trim().startsWith('<!DOCTYPE')) {\n            fullHtml = '<!DOCTYPE html>\\\\n' + fullHtml;\n          }\n        } else {\n          // No layout with full document - wrap in HTML structure\n          fullHtml = \\`<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n  \\${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  \\${suppressDefaultTitle ? \"\" : \"<title>\" + title + \"</title>\"}\\${metaTags}\\${rendererHead ? \"\\\\n  \" + rendererHead : \"\"}\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\n  \\${renderFarmRendererHydrationScript()}\n</head>\n<body>\n  <div id=\"root\">\\${html}</div>\n  \\${renderFarmClientBootstrapScript(pageProps.__farmCanonicalPath, routeSlotPayload, clientPageProps)}\n  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\n</body>\n</html>\\`;\n        }\n        fullHtml = applyFarmI18nDocument(\n          fullHtml,\n          pathname,\n          farmI18nSnapshot,\n          request,\n          mergedMetadata\n        );\n        fullHtml = applyFarmThemeDocument(\n          fullHtml,\n          farmThemeConfig,\n          farmResolvedRuntimeConfig.basePath,\n          getFarmTheme(request)\n        );\n\n        if (\n          pageStatus === 200 &&\n          shouldCachePPRShell &&\n          pprCacheKey &&\n          request.method.toUpperCase() !== \"HEAD\"\n        ) {\n          await pprShellCache.setAsync(\n            pprCacheKey,\n            { html: fullHtml },\n            {\n              paths: [pathname],\n              tags: [\"ppr\"],\n              revalidate: pprConfig.revalidate ?? false,\n            }\n          );\n          emitFarmEvent({\n            type: \"ppr.shell.cached\",\n            route: pathname,\n            key: pprCacheKey,\n            revalidate: pprConfig.revalidate,\n          });\n        }\n\n        if (pprBypassReason === \"refresh\") {\n          emitFarmEvent({\n            type: \"ppr.refresh.complete\",\n            route: pathname,\n            durationMs: Date.now() - requestStartTime,\n          });\n        }\n\n        emitFarmEvent({\n          type: \"render.complete\",\n          route: pathname,\n          pathname,\n          status: pageStatus,\n          durationMs: Date.now() - requestStartTime,\n        });\n\n        return rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(\n          fullHtml,\n          { \n            status: pageStatus,\n            headers: { ...responseHeaders, \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(fullHtml) }\n          }\n        ), middlewareHeaders), fullHtml);\n      }\n    } catch (error) {\n      if (isFarmRedirectError(error)) {\n        const redirect = getFarmRedirectError(error);\n        const redirectUrl =\n          farmLocaleResolution?.locale &&\n          redirect.url.startsWith(\"/\") &&\n          !redirect.url.startsWith(\"//\")\n            ? localizeFarmHref(\n                redirect.url,\n                farmLocaleResolution.locale,\n                farmI18nConfig\n              )\n            : redirect.url;\n        emitFarmEvent({\n          type: \"route.redirect\",\n          from: pathname,\n          to: redirectUrl,\n          status: redirect.status,\n        });\n        emitFarmEvent({\n          type: \"render.complete\",\n          route: pathname,\n          pathname,\n          status: redirect.status,\n          durationMs: Date.now() - requestStartTime,\n        });\n        return applyProductionMiddlewareHeaders(new Response(null, {\n          status: redirect.status,\n          headers: {\n            Location: redirectUrl,\n          },\n        }), middlewareHeaders);\n      }\n\n      if (isFarmNotFoundError(error)) {\n        return renderFarmNotFoundResponse();\n      }\n\n      emitFarmEvent({ type: \"render.error\", route: pathname, error });\n      console.error(\"SSR Error:\", error);\n      const errorStatus = resolveDefaultErrorStatus(error);\n      const errorStatusText = getDefaultErrorStatusText(errorStatus);\n\n      const errorBoundaryMatch = getMatchingErrorBoundary(routePathname);\n      if (errorBoundaryMatch?.route.module?.default) {\n        try {\n          const searchParamsObj = searchParamsToObject(url.searchParams);\n          const ErrorComponent = errorBoundaryMatch.route.module.default;\n          let errorElement = React.createElement(ErrorComponent, {\n            error,\n            reset: function() {},\n            params,\n            search: searchParamsObj,\n            searchParams: Promise.resolve(searchParamsObj),\n            path: pathname,\n            ...(middlewareData?.size ? { middleware: { data: middlewareData } } : {}),\n          });\n\n          const applicableLayouts = getApplicableLayouts(routePathname);\n          for (let i = applicableLayouts.length - 1; i >= 0; i--) {\n            const LayoutComponent = applicableLayouts[i].module.default;\n            if (LayoutComponent) {\n              errorElement = React.createElement(LayoutComponent, {\n                children: errorElement,\n                params,\n              });\n            }\n          }\n\n          errorElement = wrapWithFarmIntegrationProviders(errorElement);\n\n          const renderErrorElement = () =>\n            renderFarmElementToString(ReactDOMServer, errorElement);\n          const errorHtml = ${\n            hasMiddlewareRuntime\n              ? `await _runWithMiddlewareData(middlewareData, () =>\n            _runWithMiddlewareContext(middlewareContext, renderErrorElement)\n          )`\n              : \"await renderErrorElement()\"\n          };\n          const errorDocument = applyFarmThemeDocument(\n            applyFarmI18nDocument(\n              createFarmErrorDocument(errorHtml, \"Application Error\"),\n              pathname,\n              getFarmI18nSnapshot(),\n              request\n            ),\n            farmThemeConfig,\n            farmResolvedRuntimeConfig.basePath,\n            getFarmTheme(request)\n          );\n          emitFarmEvent({\n            type: \"render.complete\",\n            route: pathname,\n            pathname,\n            status: errorStatus,\n            durationMs: Date.now() - requestStartTime,\n          });\n          return rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(errorDocument, {\n            status: errorStatus,\n            headers: {\n              \"Content-Type\": \"text/html; charset=utf-8\",\n              \"Cache-Control\": \"private, no-store\",\n              \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(errorDocument),\n            },\n          }), middlewareHeaders), errorDocument);\n        } catch (boundaryError) {\n          console.error(\"Route error boundary failed:\", boundaryError);\n        }\n      }\n\n      const fallbackHtml = createDefaultErrorMarkup({\n        statusCode: errorStatus,\n        statusText: errorStatusText,\n        requestPath: pathname,\n        method: request.method,\n        development: false,\n        mode: \"production\",\n      });\n      const fallbackDocument = applyFarmThemeDocument(\n        applyFarmI18nDocument(\n          createFarmErrorDocument(\n            fallbackHtml,\n            errorStatus + \" - \" + errorStatusText\n          ),\n          pathname,\n          getFarmI18nSnapshot(),\n          request\n        ),\n        farmThemeConfig,\n        farmResolvedRuntimeConfig.basePath,\n        getFarmTheme(request)\n      );\n      return rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(\n        fallbackDocument,\n        {\n          status: errorStatus,\n          headers: {\n            \"Content-Type\": \"text/html; charset=utf-8\",\n            \"Cache-Control\": \"private, no-store\",\n            \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(fallbackDocument),\n          },\n        }\n      ), middlewareHeaders), fallbackDocument);\n    }\n  }\n\n  // 404 fallback - render proper HTML page\n  return renderFarmNotFoundResponse();\n\n  // Hoisted: page and middleware notFound() answer with the same page.\n  async function renderFarmNotFoundResponse() {\n  emitFarmEvent({ type: \"route.notFound\", pathname });\n\n  // Agents that navigate in Markdown (a \\`.md\\` URL or \\`Accept: text/markdown\\`)\n  // get a Markdown error body instead of the HTML not-found shell.\n  if (farmRequestWantsMarkdown(pathname, request.headers.get(\"accept\"))) {\n    emitFarmEvent({\n      type: \"render.complete\",\n      route: pathname,\n      pathname,\n      status: 404,\n      durationMs: Date.now() - requestStartTime,\n    });\n    return applyProductionMiddlewareHeaders(new Response(\n      createFarmMarkdownErrorBody(404, pathname, applyFarmBasePath(\"/\", farmResolvedRuntimeConfig.basePath)),\n      {\n        status: 404,\n        headers: {\n          \"Content-Type\": FARM_MARKDOWN_CONTENT_TYPE,\n          \"X-Farm-Markdown-Error\": \"404\",\n          \"Cache-Control\": \"no-store\",\n        },\n      }\n    ), middlewareHeaders);\n  }\n\n  try {\n    // Wrap 404 page with root layout if available\n    let notFoundElement = createFarmNotFoundElement(pathname);\n    const applicableLayouts = getApplicableLayouts(\"/\");\n    \n    // Wrap with layouts (from innermost to outermost)\n    for (let i = applicableLayouts.length - 1; i >= 0; i--) {\n      const layout = applicableLayouts[i];\n      const LayoutComponent = layout.module.default;\n      if (LayoutComponent) {\n        notFoundElement = React.createElement(LayoutComponent, { children: notFoundElement, params: {} });\n      }\n    }\n    notFoundElement = wrapWithFarmIntegrationProviders(notFoundElement);\n    \n    const html = await ReactDOMServer.renderToString(notFoundElement);\n    // The layouts' and the not-found page's metadata, as the development renderer uses it.\n    const notFoundMetadata = renderMetadataHead(\n      await resolveFarmNotFoundMetadata(\n        applicableLayouts.map((layout) => layout.module),\n        hasCustomNotFound ? CustomNotFoundModule : null,\n      ),\n      { pathname },\n    );\n    \n    // Check if layout provides full HTML document\n    const fullDocument = extractFarmFullDocument(html);\n    const hasFullDocument = fullDocument !== null;\n    \n    let fullHtml;\n    if (hasFullDocument) {\n      fullHtml = ensureFarmDocumentRoot(ensureFarmDocumentHead(fullDocument))\n        // The not-found title replaces any title the layout rendered, as metadata does on pages.\n        .replace(/<head([^>]*)>([\\\\s\\\\S]*?)<\\\\/head>/i, (match, attrs, headContent) =>\n          \"<head\" + attrs + \">\" +\n          headContent.replace(/<title\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/title>\\\\s*/gi, \"\") +\n          \"\\\\n  <title>\" + notFoundMetadata.title + \"</title>\" + notFoundMetadata.tags + \"\\\\n</head>\")\n        .replace(/<head([^>]*)>/i, '<head$1>\\\\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">')\n        .replace(/<\\\\/head>/i, () => renderFarmRendererHydrationScript() + '\\\\n</head>')\n        .replace(\n          /<\\\\/body>/i,\n          () => '  ' + renderFarmClientBootstrapScript() + '\\\\n' +\n            '  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\\\\n</body>',\n        );\n      if (!fullHtml.trim().startsWith('<!DOCTYPE')) {\n        fullHtml = '<!DOCTYPE html>\\\\n' + fullHtml;\n      }\n    } else {\n      fullHtml = \\`<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  \\${notFoundMetadata.hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n  <link rel=\"stylesheet\" href=\"/__farm_client_css_href__\">\n  <title>\\${notFoundMetadata.title}</title>\\${notFoundMetadata.tags}\n  \\${renderFarmRendererHydrationScript()}\n</head>\n<body>\n  <div id=\"root\">\\${html}</div>\n  \\${renderFarmClientBootstrapScript()}\n  <script type=\"module\" src=\"/__farm_client_js_src__\"></script>\n</body>\n</html>\\`;\n    }\n    fullHtml = applyFarmI18nDocument(fullHtml, pathname, getFarmI18nSnapshot(), request);\n    fullHtml = applyFarmThemeDocument(\n      fullHtml,\n      farmThemeConfig,\n      farmResolvedRuntimeConfig.basePath,\n      getFarmTheme(request)\n    );\n    \n    emitFarmEvent({\n      type: \"render.complete\",\n      route: pathname,\n      pathname,\n      status: 404,\n      durationMs: Date.now() - requestStartTime,\n    });\n\n    return rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(fullHtml, {\n      status: 404,\n      headers: {\n        \"Content-Type\": \"text/html; charset=utf-8\",\n        \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(fullHtml),\n      }\n    }), middlewareHeaders), fullHtml);\n  } catch (error) {\n    console.error(\"404 render error:\", error);\n    const fallbackDocument = applyFarmThemeDocument(\n      \\`<!DOCTYPE html><html><head><title>404</title></head><body><h1>404 - Page Not Found</h1><p>The page \\${pathname} doesn't exist.</p><a href=\"\\${escapeFarmHtmlAttribute(applyFarmBasePath(\"/\", farmResolvedRuntimeConfig.basePath))}\">Go Home</a></body></html>\\`,\n      farmThemeConfig,\n      farmResolvedRuntimeConfig.basePath,\n      getFarmTheme(request)\n    );\n    return rememberFarmBufferedHtml(applyProductionMiddlewareHeaders(new Response(\n      fallbackDocument,\n      {\n        status: 404,\n        headers: { \"Content-Type\": \"text/html\", \"x-farm-preload-buffered\": getFarmBufferedPreloadMarker(fallbackDocument) },\n      }\n    ), middlewareHeaders), fallbackDocument);\n  }\n  }\n  ${\n    hasMiddlewareRuntime\n      ? `\n  };\n  return request === requestBeforeMiddleware\n    ? runResolvedRequest()\n    : _runWithCurrentRequest(request, runResolvedRequest);\n  `\n      : \"\"\n  }\n}\n\nasync function handleFarmPluginRequest(request, runtimeOptions, adapterContext) {\n  if (!farmPluginRuntime || runtimeOptions.kind !== \"page\") {\n    return handleFarmRequest(request, adapterContext);\n  }\n\n  const pathname = runtimeOptions.route?.pathname || new URL(request.url).pathname;\n  const routePattern = runtimeOptions.route?.pattern || null;\n  const params = runtimeOptions.route?.params || {};\n  const layouts = getApplicableLayouts(getFarmRoutePathname(pathname));\n\n  await farmPluginRuntime.runHookParallel(\"beforeRouteMatch\", {\n    pathname,\n    method: request.method,\n  });\n  await farmPluginRuntime.runHookParallel(\"afterRouteMatch\", {\n    pathname,\n    matched: Boolean(routePattern),\n    routePattern,\n    params,\n    layoutPatterns: layouts.map((layout) => layout.pattern),\n  });\n\n  const renderPayload = {\n    pathname,\n    method: request.method,\n    routePattern,\n    params,\n  };\n  await farmPluginRuntime.runHookParallel(\"beforeRender\", renderPayload);\n\n  const response = await handleFarmRequest(request, adapterContext);\n  if (\n    !hasFarmPluginHTMLTransforms ||\n    !response.headers.get(\"content-type\")?.toLowerCase().includes(\"text/html\")\n  ) {\n    return response;\n  }\n\n  let html = await response.text();\n  html = await farmPluginRuntime.runHookSerial(\"transformHTML\", html);\n  html = await farmPluginRuntime.runHookSerial(\"afterRender\", html, renderPayload);\n\n  const headers = new Headers(response.headers);\n  headers.delete(\"content-length\");\n  headers.delete(\"x-farm-preload-streaming\");\n  headers.set(\"x-farm-preload-buffered\", getFarmBufferedPreloadMarker(html));\n  return rememberFarmBufferedHtml(new Response(html, {\n    status: response.status,\n    statusText: response.statusText,\n    headers,\n  }), html);\n}\n\n${generatePreloadResponseRuntimeSource()}\n\n// Export as Web Standard fetch API\nexport async function fetch(request, context) {\n  ${config.agent?.noindexPreviews ? \"const response = await\" : \"return\"} _runWithAPIRequestRuntime({\n    basePath: farmLocalAPIBasePath,\n    dispatch: async (localRequest) =>\n      (await handleAPIRequest(localRequest)) ?? Response.json({ error: \"Not Found\" }, { status: 404 }),\n  }, () => handleFarmFetch(request, context));${\n    config.agent?.noindexPreviews\n      ? `\n  // Keep every response of a preview deployment out of search indexes.\n  return farmNoindexPreview ? applyFarmPreviewRobotsTag(response) : response;`\n      : \"\"\n  }\n}\n\nasync function handleFarmFetch(request, context) {\n  const healthResponse = await farmProductionLifecycle.handleHealthRequest(request);\n  if (healthResponse) return healthResponse;\n\n  const productionSiteAttestation = farmProductionSiteTelemetry?.handleAttestation(request);\n  if (productionSiteAttestation) return productionSiteAttestation;\n\n  farmProductionSiteTelemetry?.report(\n    request.url,\n    typeof context?.waitUntil === \"function\" ? context.waitUntil.bind(context) : undefined,\n  );\n\n  return farmProductionLifecycle.runRequest(\n    () =>\n      runWithFarmRequestSpan(request, async () => {\n        const runtimeOptions = farmPluginRuntime ? getFarmPluginRequestOptions(request) : null;\n        const prepareResponse = async (runtimeRequest, responsePromise) => {\n          const response = await responsePromise;\n          // Headers need the path eagerly; preload reporting needs it only for\n          // actual warnings. Keep the current plugin request, not a render URL.\n          const routePathname = configuredHeaderRoutes.length > 0\n            ? getFarmRoutePathname(new URL(runtimeRequest.url).pathname)\n            : undefined;\n          return applyFarmPreloadBudget(\n            applyFarmCspNonceToResponse(\n              applyConfiguredResponseHeaders(response, routePathname),\n              farmSecurityConfig,\n            ),\n            routePathname,\n            runtimeRequest,\n          );\n        };\n        const runRequest = () => farmPluginRuntime\n          ? farmPluginRuntime.runRuntimeRequest(\n              request,\n              (runtimeRequest) =>\n                _runWithCurrentRequest(runtimeRequest, () =>\n                  prepareResponse(\n                    runtimeRequest,\n                    handleFarmPluginRequest(runtimeRequest, runtimeOptions, context),\n                  )\n                ),\n              {\n                ...runtimeOptions,\n                waitUntil: typeof context?.waitUntil === \"function\"\n                  ? context.waitUntil.bind(context)\n                  : undefined,\n              },\n            )\n          : ${\n            hasInfraAnalyticsRuntime && !hasPluginRuntime\n              ? `farmInfraAnalytics\n            ? farmInfraAnalytics.record(\n                request,\n                getFarmPluginRequestOptions(request),\n                typeof context?.waitUntil === \"function\" ? context.waitUntil.bind(context) : undefined,\n                () => prepareResponse(request, handleFarmRequest(request, context)),\n              )\n            : `\n              : \"\"\n          }prepareResponse(request, handleFarmRequest(request, context));\n\n        const response = await _runWithCurrentRequest(request, () =>\n          _runWithAfterRequest(request, runRequest, context),\n        );\n        return ${hasCompressionRuntime && !hasPluginRuntime ? \"compressFarmResponse(request, response, getFarmOwnedBufferedHtml(response))\" : \"response\"};\n      }),\n    {\n      onResponseFinished: typeof context?.onResponseFinished === \"function\"\n        ? context.onResponseFinished\n        : undefined,\n    },\n  );\n}\nexport { createFarmNodeRequestAbortSignal };\nexport default { fetch, lifecycle: farmProductionLifecycle };\n  `.trim();\n}\n\n/**\n * Build with Nitro using virtual bundle\n * Routes are now bundled in the SSR entry, so we just need to wrap the handler\n */\nfunction matchesConfiguredRoute(source: string, pathname: string): boolean {\n  const sourceSegments = source.split(\"/\").filter(Boolean);\n  const pathnameSegments = pathname.split(\"/\").filter(Boolean);\n  let pathnameIndex = 0;\n\n  for (const sourceSegment of sourceSegments) {\n    if (sourceSegment === \"*\" || /^:[^/]+\\*$/.test(sourceSegment)) return true;\n\n    const pathnameSegment = pathnameSegments[pathnameIndex];\n    if (/^:[^/]+\\?$/.test(sourceSegment)) {\n      if (pathnameSegment !== undefined) pathnameIndex++;\n      continue;\n    }\n    if (pathnameSegment === undefined) return false;\n    if (!sourceSegment.startsWith(\":\") && sourceSegment !== pathnameSegment) return false;\n    pathnameIndex++;\n  }\n\n  return pathnameIndex === pathnameSegments.length;\n}\n\nfunction getPrerenderRouteHeaders(\n  pathname: string,\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[],\n): Record<string, string> {\n  const headers: Record<string, string> = {\n    \"cache-control\": \"public, max-age=0, must-revalidate\",\n  };\n  for (const route of configuredHeaderRoutes) {\n    if (!matchesConfiguredRoute(route.source, pathname)) continue;\n    for (const header of route.headers) headers[header.key.toLowerCase()] = header.value;\n  }\n  return headers;\n}\n\nfunction escapeRoutePattern(value: string): string {\n  return value.replace(/[|\\\\{}()[\\]^$+?.*]/g, \"\\\\$&\");\n}\n\nfunction middlewarePatternMatches(pattern: string | RegExp, pathname: string): boolean {\n  if (pattern instanceof RegExp) {\n    pattern.lastIndex = 0;\n    return pattern.test(pathname);\n  }\n\n  if (pattern === \"*\" || pattern === \"/(.*)\") return true;\n  if (pattern.endsWith(\"(.*)\")) {\n    const prefix = pattern.slice(0, -4);\n    return pathname === prefix || pathname.startsWith(`${prefix}/`);\n  }\n\n  const segments = pattern.split(\"/\").filter(Boolean);\n  if (segments.length === 0) return pathname === \"/\";\n  const expression = segments\n    .map((segment) => {\n      if (segment === \"**\") return \"(?:/.*)?\";\n      if (segment === \"*\") return \"/[^/]+\";\n      if (\n        /^:[^/]+\\*$/.test(segment) ||\n        /^\\[\\.\\.\\..+\\]$/.test(segment) ||\n        /^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)\n      ) {\n        return \"(?:/.*)?\";\n      }\n      if (/^:[^/]+\\+$/.test(segment)) return \"/.+\";\n      if (/^:[^/]+\\?$/.test(segment)) return \"(?:/[^/]+)?\";\n      if (segment.startsWith(\":\") || /^\\[.+\\]$/.test(segment)) return \"/[^/]+\";\n      return `/${escapeRoutePattern(segment).replace(/\\\\\\*/g, \"[^/]*\")}`;\n    })\n    .join(\"\");\n  return new RegExp(`^${expression}/?$`).test(pathname);\n}\n\nfunction configMiddlewareMayHandlePath(\n  config: ResolvedFarmConfig[\"middleware\"],\n  pathname: string,\n): boolean {\n  if (!hasFarmMiddlewareConfig(config)) return false;\n\n  const entries = (Array.isArray(config) ? config : [config]) as Array<{\n    matcher?: unknown | unknown[];\n    exclude?: Array<string | RegExp>;\n  }>;\n  return entries.some((entry) => {\n    if (entry.exclude?.some((pattern) => middlewarePatternMatches(pattern, pathname))) {\n      return false;\n    }\n\n    if (!entry.matcher) return true;\n    const matchers = Array.isArray(entry.matcher) ? entry.matcher : [entry.matcher];\n    return matchers.some((matcher) => {\n      // A request-aware matcher cannot be proven safe at build time.\n      if (typeof matcher === \"function\") return true;\n      return (\n        (typeof matcher === \"string\" || matcher instanceof RegExp) &&\n        middlewarePatternMatches(matcher, pathname)\n      );\n    });\n  });\n}\n\nfunction appMiddlewareMayHandlePath(\n  middlewareRoutes: readonly UniversalMiddlewareRoute[],\n  pathname: string,\n): boolean {\n  return middlewareRoutes.some((route) => {\n    if (route.path === \"/\") return true;\n    return (\n      middlewarePatternMatches(route.path, pathname) ||\n      middlewarePatternMatches(`${route.path}/**`, pathname)\n    );\n  });\n}\n\n/**\n * Rank a `routeRules` glob (`/blog/**`). This is config-pattern syntax, not file\n * route syntax, and is deliberately separate from the file-route ordering in\n * `compareRoutePatternSpecificity`.\n */\nfunction routePatternSpecificity(pattern: string): number {\n  return pattern\n    .split(\"/\")\n    .filter(Boolean)\n    .reduce((score, segment) => {\n      if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n      if (segment === \"*\" || segment.startsWith(\"[...\") || /:\\w+\\*$/.test(segment)) {\n        return score + 10;\n      }\n      if (/^\\[.+\\]$/.test(segment) || segment.startsWith(\":\")) return score + 50;\n      return score + 100;\n    }, 0);\n}\n\nfunction getEffectiveRouteRule(config: ResolvedFarmConfig, pathname: string) {\n  return Object.entries(config.routeRules)\n    .filter(([pattern]) => middlewarePatternMatches(pattern, pathname))\n    .sort(([left], [right]) => routePatternSpecificity(left) - routePatternSpecificity(right))\n    .reduce<Record<string, unknown>>((resolved, [, rule]) => Object.assign(resolved, rule), {});\n}\n\nfunction getManifestPageEntry(\n  manifest: FarmRouteRuntimeManifest,\n  pathname: string,\n): FarmRouteRuntimeManifestEntry | undefined {\n  return (\n    manifest.routes\n      .filter((entry) => entry.kind === \"page\" && middlewarePatternMatches(entry.pattern, pathname))\n      // Page patterns, so this uses the shared file-route ordering contract too.\n      .sort((left, right) => compareRoutePatternSpecificity(left.pattern, right.pattern))[0]\n  );\n}\n\nfunction getPhysicalPrerenderBypassReason(options: {\n  config: ResolvedFarmConfig;\n  middlewareRoutes: readonly UniversalMiddlewareRoute[];\n  routeRuntimeManifest: FarmRouteRuntimeManifest;\n  redirectSources: readonly string[];\n  rewriteSources: readonly string[];\n  pathname: string;\n}): string | undefined {\n  const {\n    config,\n    middlewareRoutes,\n    routeRuntimeManifest,\n    redirectSources,\n    rewriteSources,\n    pathname,\n  } = options;\n  if (config.i18n.enabled) return \"request-sensitive i18n\";\n  if (redirectSources.some((source) => middlewarePatternMatches(source, pathname))) {\n    return \"redirect\";\n  }\n  if (rewriteSources.some((source) => middlewarePatternMatches(source, pathname))) {\n    return \"rewrite\";\n  }\n  if (appMiddlewareMayHandlePath(middlewareRoutes, pathname)) return \"app middleware\";\n  if (configMiddlewareMayHandlePath(config.middleware, pathname)) return \"configured middleware\";\n  if (hasCustomFarmRouteContext(config)) return \"request context\";\n  if (farmServerRuntimePluginsMayHandlePath(config, pathname)) return \"server runtime plugin\";\n\n  const manifestEntry = getManifestPageEntry(routeRuntimeManifest, pathname);\n  if (manifestEntry?.rendering === \"dynamic\") return \"dynamic runtime manifest\";\n  if (\n    manifestEntry &&\n    (manifestEntry.runtime !== \"auto\" ||\n      Boolean(manifestEntry.regions?.length) ||\n      manifestEntry.maxDuration !== undefined)\n  ) {\n    return \"route runtime controls\";\n  }\n\n  const routeRule = getEffectiveRouteRule(config, pathname);\n  if (routeRule.prerender === false || routeRule.render === \"dynamic\" || routeRule.ssr === true) {\n    return \"dynamic route rule\";\n  }\n  if (\n    (routeRule.swr !== undefined && routeRule.swr !== false) ||\n    (routeRule.isr !== undefined && routeRule.isr !== false)\n  ) {\n    return \"runtime cache route rule\";\n  }\n\n  return undefined;\n}\n\nasync function buildNitroUniversal(\n  config: ResolvedFarmConfig,\n  routeManager: RouteManager,\n  apiRouteManager: APIRouteManager,\n  serverRenderer: ServerRenderer,\n  preset: string,\n  root: string,\n  distDir: string,\n  ssrBundle: OutputBundle,\n  ssrEntryFile: string,\n  clientOutputDir: string,\n  routeRuntimeManifest: FarmRouteRuntimeManifest,\n  configuredHeaderRoutes: UniversalConfiguredHeaderRoute[],\n  nitroBuilderResultPromise: Promise<PromiseSettledResult<FarmNitroBuilder>>,\n  pluginManager?: PluginManager,\n) {\n  // Nitro is only needed while producing the deployment artifact. Keeping the\n  // import lazy prevents this build-only dependency from leaking into an\n  // application's standalone server bundle through @farm.js/core's root entry.\n  const [fs, nitroBuilderResult] = await Promise.all([\n    import(\"fs/promises\"),\n    nitroBuilderResultPromise,\n  ]);\n  if (nitroBuilderResult.status === \"rejected\") throw nitroBuilderResult.reason;\n  const nitroBuilder = nitroBuilderResult.value;\n\n  const isVercel = preset === \"vercel\" || preset === \"vercel-edge\";\n  const isCloudflareWorker = preset === \"cloudflare-module\";\n  const outputDir = resolveDeployOutputPath(root, config.deploy.outputDir);\n  const runtimeServerOutputDir = isVercel\n    ? path.join(outputDir, \"functions\", \"__nitro.func\")\n    : path.join(outputDir, \"server\");\n  const ssrOutputDir = path.join(root, distDir, \"ssr\");\n  const imageRuntime = resolveImageRuntime(config, preset);\n  const hasGeneratedMetadataImages = Array.from(routeManager.getMetadataImages().values()).some(\n    (image) => image.sourceType === \"module\",\n  );\n  const ssrExternalPackages = collectSSRExternalPackages(ssrBundle);\n  const useExternalMetadataImageRuntime = shouldUseExternalMetadataImageRuntime(\n    preset,\n    hasGeneratedMetadataImages || ssrExternalPackages.has(\"@vercel/og\"),\n  );\n  const nitroRollupExternal = (id: string) =>\n    (useExternalMetadataImageRuntime && id === \"@vercel/og\") ||\n    (isNitroRollupExternal(id) && !(isCloudflareWorker && NITRO_REACT_RUNTIME_MODULES.has(id)));\n  const copiedRuntimePackages = new Set([\n    ...(imageRuntime === \"node\" ? [\"sharp\"] : []),\n    ...(useExternalMetadataImageRuntime ? [\"@vercel/og\"] : []),\n  ]);\n  // Nitro normally rebundles the Vite SSR graph so its bare dependencies are\n  // deployable. Skip that duplicate pass only when Farm already knows how to\n  // package every remaining external; otherwise retain Nitro's proven path.\n  const isPrebuiltSSRCandidate =\n    preset === \"node-server\" &&\n    [...ssrExternalPackages].every((packageName) => copiedRuntimePackages.has(packageName));\n\n  logger.info(`📦 Nitro output directory: ${outputDir}`);\n  logger.info(`📦 SSR entry file: ${ssrEntryFile}`);\n  logger.info(`📦 Preset: ${preset}`);\n\n  const ssgCollectionPromise = routeManager.collectSSGPages();\n  const middlewareRoutesPromise = discoverMiddlewareRoutes(getFarmAppDirectories(config));\n  // Resolved config callbacks close over already-loaded arrays, so this does\n  // not re-run user discovery or fetch mutable external configuration.\n  const configuredResponseRoutesPromise = Promise.all([config.redirects(), config.rewrites()]);\n  const farmWorkflows = await prepareFarmWorkflowsForNitro(config);\n  const farmCron = await prepareFarmCronForNitro(config);\n  const [{ ssg: ssgPages }, middlewareRoutes, [configuredRedirects, configuredRewrites]] =\n    await Promise.all([\n      ssgCollectionPromise,\n      middlewareRoutesPromise,\n      configuredResponseRoutesPromise,\n    ]);\n  const redirectSources = [\n    ...routeManager.getRedirects().map((route) => route.source),\n    ...configuredRedirects.map((route: RedirectConfig) => route.source),\n  ];\n  const rewriteSources = configuredRewrites.map((route: RewriteConfig) => route.source);\n  const prerenderRoutes: string[] = [];\n  const skippedPrerenderRoutes: Array<{ pathname: string; reason: string }> = [];\n  for (const page of ssgPages) {\n    // Revalidated pages keep their runtime/CDN stale-while-revalidate\n    // behavior. Emitting them as public files would prevent the server from\n    // ever regenerating them.\n    if (page.revalidate !== undefined) continue;\n    if (prerenderRoutes.includes(page.urlPath)) continue;\n\n    const reason = getPhysicalPrerenderBypassReason({\n      config,\n      middlewareRoutes,\n      routeRuntimeManifest,\n      redirectSources,\n      rewriteSources,\n      pathname: page.urlPath,\n    });\n    if (reason) {\n      skippedPrerenderRoutes.push({ pathname: page.urlPath, reason });\n      continue;\n    }\n    prerenderRoutes.push(page.urlPath);\n  }\n  for (const skipped of skippedPrerenderRoutes) {\n    logger.info(`↪ Keeping SSG route ${skipped.pathname} server-handled (${skipped.reason})`);\n  }\n  if (farmWorkflows.workflows.length > 0) {\n    logger.info(`⏱️  Found ${farmWorkflows.workflows.length} Farm workflow task(s)`);\n  }\n  if (farmCron.jobs.length > 0) {\n    logger.info(`⏱️  Configured ${farmCron.jobs.length} Farm cron route(s)`);\n  }\n  if (preset === \"cloudflare-pages\" && farmCron.jobs.length > 0) {\n    logger.warn(\n      \"Cloudflare Pages does not install Cron Triggers. Use the cloudflare-module preset or an external scheduler with .farm/cron-manifest.json.\",\n    );\n  }\n\n  const scheduledTasks = mergeScheduledTasks(farmWorkflows.scheduledTasks, farmCron.scheduledTasks);\n  const cloudflareCronConfig = createFarmCronCloudflareConfig(farmCron.jobs);\n\n  // The client build has fully settled by now (fonts merged, output\n  // validated), so the stylesheet href baked into server code can carry the\n  // content hash of the bytes browsers will actually receive. Substituting in\n  // memory, before any consumer, covers the disk write below as well as the\n  // prebuilt-SSR copies and prerendering that reuse this bundle directly.\n  const [clientCssHref, clientJsSrc] = await Promise.all([\n    resolveHashedClientCssHref(clientOutputDir),\n    resolveHashedClientJsSrc(clientOutputDir),\n  ]);\n  for (const output of Object.values(ssrBundle)) {\n    if (output.type !== \"chunk\") continue;\n    // split/join rather than replaceAll: the package's lib target predates\n    // ES2021, and a fixed token needs no regex escaping either way.\n    if (output.code.includes(FARM_CLIENT_CSS_HREF_PLACEHOLDER)) {\n      output.code = output.code.split(FARM_CLIENT_CSS_HREF_PLACEHOLDER).join(clientCssHref);\n    }\n    if (output.code.includes(FARM_CLIENT_JS_SRC_PLACEHOLDER)) {\n      output.code = output.code.split(FARM_CLIENT_JS_SRC_PLACEHOLDER).join(clientJsSrc);\n    }\n  }\n\n  // Write SSR bundle to disk\n  await fs.mkdir(ssrOutputDir, { recursive: true });\n\n  for (const [fileName, output] of Object.entries(ssrBundle)) {\n    const filePath = path.join(ssrOutputDir, fileName);\n    // Ensure parent directory exists for nested chunks and emitted assets.\n    await fs.mkdir(path.dirname(filePath), { recursive: true });\n    await fs.writeFile(filePath, output.type === \"chunk\" ? output.code : output.source);\n  }\n\n  // Create the Nitro event handler adapter. Nitro accepts plain event handler\n  // functions, so keep this entry dependency-free for standalone output.\n  const nitroEntryPath = path.join(ssrOutputDir, \"nitro-entry.mjs\");\n\n  const nitroEntryCode = `\n// Farm.js Nitro Entry\n// This file adapts Farm's Web fetch handler to Nitro's event handler contract.\n\nimport { useNitroHooks } from '#nitro/runtime/app'\nimport handler, { farmProductionLifecycle, createFarmNodeRequestAbortSignal } from './${ssrEntryFile}'\n\nexport { farmProductionLifecycle }\n\nlet farmCloseHookRegistered = false\nfunction registerFarmCloseHook() {\n  if (farmCloseHookRegistered) return\n  farmCloseHookRegistered = true\n  useNitroHooks().hook('close', () =>\n    farmProductionLifecycle.close('production-server-closed')\n  )\n}\n\nfunction mergeVaryHeaders(target, source) {\n  const values = new Set(\n    [target.get('Vary'), source]\n      .filter(Boolean)\n      .flatMap((value) => value.split(','))\n      .map((value) => value.trim())\n      .filter(Boolean),\n  )\n\n  if (values.size > 0) target.set('Vary', Array.from(values).join(', '))\n}\n\nfunction createResponseFinishedHook(event) {\n  const nodeResponse = event.node?.res\n  if (!nodeResponse || typeof nodeResponse.once !== 'function') return undefined\n\n  return (callback) => {\n    if (nodeResponse.writableEnded || nodeResponse.writableFinished) {\n      queueMicrotask(callback)\n      return\n    }\n\n    let finished = false\n    const finish = () => {\n      if (finished) return\n      finished = true\n      nodeResponse.off('finish', finish)\n      nodeResponse.off('close', finish)\n      callback()\n    }\n    nodeResponse.once('finish', finish)\n    nodeResponse.once('close', finish)\n  }\n}\n\n// The peer address the server adapter already knows. The Request handed to\n// Farm is rebuilt below and has no socket, so without this a built app cannot\n// tell its visitors apart even though its development server can. Mirrors h3's\n// getRequestIP without the forwarded header, which only trustProxy may honor.\nfunction resolveFarmClientAddress(event) {\n  try {\n    return event.req?.context?.clientAddress || event.req?.ip ||\n      event.node?.req?.socket?.remoteAddress || undefined\n  } catch {\n    return undefined\n  }\n}\n\nfunction resolveTrustedLocalOrigin(event, request) {\n  const socket = event.node?.req?.socket\n  const port = socket?.localPort\n  let address = socket?.localAddress\n  if (!address || !Number.isInteger(port) || port <= 0) return undefined\n  if (address.startsWith('::ffff:')) address = address.slice('::ffff:'.length)\n  const hostname = address.includes(':') ? '[' + address + ']' : address\n  const protocol = socket.encrypted ? 'https:' : 'http:'\n  const requestURL = new URL(request.url)\n  let origin\n  try {\n    origin = new URL(protocol + '//' + hostname + ':' + port).origin\n  } catch {\n    return undefined\n  }\n  if (requestURL.origin === origin) return origin\n\n  const requestPort = Number(requestURL.port || (requestURL.protocol === 'https:' ? 443 : 80))\n  const normalizedRequestHostname =\n    requestURL.hostname.startsWith('[') && requestURL.hostname.endsWith(']')\n      ? requestURL.hostname.slice(1, -1)\n      : requestURL.hostname\n  const isLoopback = (value) =>\n    value === 'localhost' || value === '::1' || /^127(?:[.][0-9]{1,3}){3}$/.test(value)\n  return requestURL.protocol === protocol &&\n    requestPort === port &&\n    isLoopback(address) &&\n    isLoopback(normalizedRequestHostname)\n    ? requestURL.origin\n    : undefined\n}\n\n// Export the event handler for Nitro\nexport default async function farmNitroEventHandler(event) {\n  registerFarmCloseHook()\n  // Some Node adapters abort their Request on normal IncomingMessage close.\n  // Use the same actual disconnect events as Farm's development server.\n  const node = event.node\n  const webRequest = event.req?._request || event.req\n  const request = node?.req && node?.res\n    ? new Request(webRequest, { signal: createFarmNodeRequestAbortSignal(node.req, node.res) })\n    : webRequest\n  const response = await handler.fetch(request, {\n    waitUntil: (promise) => event.waitUntil(promise),\n    onResponseFinished: createResponseFinishedHook(event),\n    trustedLocalOrigin: resolveTrustedLocalOrigin(event, request),\n    clientAddress: resolveFarmClientAddress(event),\n  })\n\n  // Nitro records asset compression negotiation on the event response. Merge\n  // Farm's cache signals there so H3 preserves both sets of Vary values.\n  const farmVary = response.headers.get('Vary')\n  if (farmVary) mergeVaryHeaders(event.res.headers, farmVary)\n  return response\n}\n  `.trim();\n\n  await fs.writeFile(nitroEntryPath, nitroEntryCode);\n  const farmNodeServerEntryPath =\n    preset === \"node-server\" ? path.join(ssrOutputDir, \"farm-node-server-entry.mjs\") : null;\n  if (farmNodeServerEntryPath) {\n    await fs.writeFile(\n      farmNodeServerEntryPath,\n      createFarmNodeServerEntry({\n        nitroEntryFile: path.basename(nitroEntryPath),\n        nodeAdapterModule: resolveNitroRuntimeDependency(root, \"srvx/node\"),\n        server: config.server,\n        websocketAdapterModule: resolveNitroRuntimeDependency(root, \"crossws/adapters/node\"),\n      }),\n    );\n  }\n  const prebuiltSSRPlugin = createExternalSSRBundlePlugin(\n    nitroEntryPath,\n    ssrOutputDir,\n    ssrEntryFile,\n  );\n  const configuredNitroRouteRules = routeRulesToNitroRouteRules(config.routeRules);\n  const prerenderNitroRouteRules = Object.fromEntries(\n    prerenderRoutes.map((route) => {\n      const configuredRule = configuredNitroRouteRules[route] || {};\n      return [\n        route,\n        {\n          ...configuredRule,\n          prerender: true,\n          headers: {\n            ...getPrerenderRouteHeaders(route, configuredHeaderRoutes),\n            ...configuredRule.headers,\n          },\n        },\n      ];\n    }),\n  );\n\n  let nitroConfig: NitroConfig = {\n    preset,\n    ...(farmNodeServerEntryPath ? { entry: farmNodeServerEntryPath } : {}),\n    rootDir: root,\n    serverDir: root,\n    buildDir: path.join(root, distDir, \".nitro\"),\n    alias: resolveNitroInternalRuntimeAliases(root),\n    compatibilityDate: \"2024-12-01\",\n    output: resolveFarmNitroOutputConfig(preset, outputDir),\n    publicAssets: [\n      {\n        dir: clientOutputDir,\n        maxAge: 31536000,\n        baseURL: \"/\",\n      },\n    ],\n    ...(prerenderRoutes.length > 0\n      ? {\n          prerender: {\n            crawlLinks: false,\n            failOnError: true,\n            routes: prerenderRoutes,\n          },\n        }\n      : {}),\n    experimental: {\n      tasks: farmWorkflows.workflows.length > 0 || farmCron.jobs.length > 0,\n    },\n    tasks: {\n      ...farmWorkflows.tasks,\n      ...farmCron.tasks,\n    },\n    scheduledTasks: isVercel ? farmWorkflows.scheduledTasks : scheduledTasks,\n    ...(isCloudflareWorker && cloudflareCronConfig\n      ? {\n          cloudflare: cloudflareCronConfig,\n        }\n      : {}),\n    // Use serverHandlers to define our workflow handler first, then the catch-all handler.\n    handlers: [\n      ...(farmWorkflows.handlerPath\n        ? [\n            {\n              route: `${config.workflows.route}/**`,\n              handler: farmWorkflows.handlerPath,\n            },\n          ]\n        : []),\n      {\n        route: \"/**\",\n        handler: toPosixPath(nitroEntryPath),\n      },\n    ],\n    routeRules: {\n      \"/**\": {\n        prerender: false,\n      },\n      ...configuredNitroRouteRules,\n      // Exact user rules must retain their runtime settings without replacing\n      // the headers and prerender marker generated for a safe physical page.\n      ...prerenderNitroRouteRules,\n    },\n    rollupConfig: {\n      external: nitroRollupExternal,\n      plugins:\n        hasGeneratedMetadataImages && !useExternalMetadataImageRuntime\n          ? [createMetadataImageWasmPlugin()]\n          : [],\n    },\n    // Keep the public Nitro boolean intact for build hooks. Farm replaces\n    // Nitro's minifier only when no custom OXC transform was requested.\n    minify: true,\n    sourcemap: false, // Skip sourcemaps for faster build\n  };\n  const initialSSRRebundleOptions = snapshotSSRRebundleOptions(nitroConfig);\n\n  if (pluginManager) {\n    nitroConfig = await pluginManager.runHookSerial(\"beforeNitroBuild\", nitroConfig);\n  }\n\n  const expectedServerDir = path.join(outputDir, \"server\");\n  const customRollupKeys = Object.keys(nitroConfig.rollupConfig || {}).filter(\n    (key) => key !== \"external\" && key !== \"plugins\",\n  );\n  const hasCustomOxcOptions = Boolean(nitroConfig.oxc && Object.keys(nitroConfig.oxc).length > 0);\n  const hasLateBuildMutationConfig = Boolean(\n    Object.keys(nitroConfig.hooks || {}).length > 0 ||\n    (Array.isArray(nitroConfig.modules) ? nitroConfig.modules.some(Boolean) : nitroConfig.modules),\n  );\n  const hasUnsupportedSSRRebundleOverrides = !isDeepStrictEqual(\n    initialSSRRebundleOptions,\n    snapshotSSRRebundleOptions(nitroConfig),\n  );\n  const requestedBuilder = nitroConfig.builder ?? process.env.NITRO_BUILDER;\n  const canReusePrebuiltSSR =\n    isPrebuiltSSRCandidate &&\n    nitroConfig.preset === \"node-server\" &&\n    (requestedBuilder === undefined ||\n      requestedBuilder === \"rollup\" ||\n      requestedBuilder === \"rolldown\") &&\n    nitroConfig.sourcemap === false &&\n    !hasCustomOxcOptions &&\n    !hasLateBuildMutationConfig &&\n    !hasUnsupportedSSRRebundleOverrides &&\n    nitroConfig.rollupConfig?.external === nitroRollupExternal &&\n    !hasRollupPlugins(nitroConfig.rollupConfig?.plugins) &&\n    customRollupKeys.length === 0 &&\n    path.resolve(nitroConfig.output?.serverDir || \"\") === path.resolve(expectedServerDir) &&\n    Boolean(\n      nitroConfig.handlers?.some(\n        (handler) => path.resolve(handler?.handler || \"\") === nitroEntryPath,\n      ),\n    );\n  const selectRolldownBuilder =\n    canReusePrebuiltSSR && requestedBuilder === undefined && (await canUseRolldownBuilder());\n  if (selectRolldownBuilder) nitroConfig.builder = \"rolldown\";\n  const useRolldownBuilder =\n    canReusePrebuiltSSR && (nitroConfig.builder ?? process.env.NITRO_BUILDER) === \"rolldown\";\n\n  const shouldMinify = nitroConfig.minify !== false;\n  const configuredEsbuildOptions: FarmEsbuildOptions = {};\n  const resolvedEsbuildOptions: FarmEsbuildOptions = {\n    // Function-name helpers are unsafe for provider scripts that serialize a\n    // function with toString(); the helper is outside the emitted script scope.\n    keepNames: !(config.docs?.enabled && config.docs.adapter?.server),\n    legalComments: \"none\",\n  };\n  const prebuiltSSREsbuildOptions =\n    config.docs?.enabled && config.docs.adapter?.server\n      ? resolvedEsbuildOptions\n      : configuredEsbuildOptions;\n  const useFarmEsbuildMinifier =\n    shouldMinify &&\n    nitroConfig.sourcemap === false &&\n    !hasCustomOxcOptions &&\n    !hasLateBuildMutationConfig;\n  const esbuildChunkMinifier = useFarmEsbuildMinifier\n    ? createEsbuildChunkMinifyPlugin(resolvedEsbuildOptions)\n    : null;\n  if (canReusePrebuiltSSR) {\n    const configuredRollupPlugins = nitroConfig.rollupConfig?.plugins;\n    nitroConfig.rollupConfig = {\n      ...nitroConfig.rollupConfig,\n      plugins: [\n        ...(Array.isArray(configuredRollupPlugins)\n          ? configuredRollupPlugins\n          : configuredRollupPlugins\n            ? [configuredRollupPlugins]\n            : []),\n        prebuiltSSRPlugin,\n      ],\n    };\n  }\n\n  nitroConfig.minify = useFarmEsbuildMinifier ? false : shouldMinify;\n\n  // Build with Nitro\n  const nitroInstance = await nitroBuilder.createNitro(nitroConfig);\n  if (config.security.csp && config.security.csp.nonce) {\n    nitroInstance.hooks.hook(\"prerender:generate\", async (route) => {\n      if (!route.contents || !route.contentType?.toLowerCase().includes(\"html\")) return;\n      const staticCsp = await applyFarmCspHashesToHtml(route.contents, config.security);\n      if (!staticCsp) return;\n\n      route.contents = staticCsp.html;\n      const routeRule = nitroInstance.options.routeRules[route.route] || {};\n      const headers = { ...routeRule.headers };\n      for (const key of Object.keys(headers)) {\n        if (key.toLowerCase() === staticCsp.header.key.toLowerCase()) delete headers[key];\n      }\n      headers[staticCsp.header.key] = staticCsp.header.value;\n      nitroInstance.options.routeRules[route.route] = { ...routeRule, headers };\n    });\n    nitroInstance.hooks.hook(\"prerender:done\", () => {\n      // The final adapter build reads both the resolved options and Nitro's\n      // routing index. Refresh the latter after per-page policies are known.\n      nitroInstance.routing.sync();\n    });\n  }\n  if (farmNodeServerEntryPath) {\n    // The custom entry is only for the final long-running Node server. Nitro\n    // derives its prerenderer config from this config, so remove the override\n    // and let the nitro-prerender preset provide appFetch/closePrerenderer.\n    nitroInstance.hooks.hook(\"prerender:config\", (prerendererConfig) => {\n      delete prerendererConfig.entry;\n    });\n  }\n  nitroInstance.hooks.hook(\"prerender:init\", (prerenderer) => {\n    prerenderer.hooks.hook(\"rollup:before\", (_prerenderNitro, rollupConfig) => {\n      // Nitro's virtual modules (storage, tasks, ...) emit bare imports of\n      // Nitro's own runtime dependencies (unstorage, h3, ...). Their virtual\n      // importer is discarded during resolution, so under pnpm's strict\n      // node_modules layout these transitive dependencies cannot be resolved,\n      // and rollup silently leaves them as bare imports in the temporary\n      // prerender server. Importing that server from the output directory\n      // then fails with ERR_MODULE_NOT_FOUND (#403). Retry unresolved bare\n      // ids from Nitro's own package context so they bundle like the rest.\n      const configuredPlugins = rollupConfig.plugins;\n      rollupConfig.plugins = [\n        ...(Array.isArray(configuredPlugins)\n          ? configuredPlugins\n          : configuredPlugins\n            ? [configuredPlugins]\n            : []),\n        createPrerenderRuntimeResolverPlugin(config.root),\n      ];\n    });\n  });\n  await nitroBuilder.prepare(nitroInstance);\n  await nitroBuilder.copyPublicAssets(nitroInstance);\n  if (prerenderRoutes.length > 0 && canReusePrebuiltSSR) {\n    // The prerenderer builds and immediately imports a temporary server before\n    // the final Node adapter exists. Materialize the same prebuilt SSR package\n    // import for that temporary server so it can render the static routes.\n    nitroInstance.hooks.hook(\"prerender:init\", (prerenderer) => {\n      if (useRolldownBuilder) {\n        prerenderer.hooks.hook(\"rollup:before\", (_nitro, rollupConfig) => {\n          const rolldownConfig = rollupConfig as typeof rollupConfig & {\n            inject?: unknown;\n            jsx?: unknown;\n          };\n          delete rolldownConfig.inject;\n          delete rolldownConfig.jsx;\n        });\n      }\n      prerenderer.hooks.hook(\"compiled\", async () => {\n        const prerenderServerDir = path.join(outputDir, \"server\");\n        await copyPrebuiltSSRBundle(\n          ssrBundle,\n          path.join(prerenderServerDir, FARM_SSR_OUTPUT_DIR),\n          {},\n          false,\n          fs,\n        );\n        await registerPrebuiltSSRPackageImport(prerenderServerDir, ssrEntryFile, fs);\n      });\n    });\n  }\n  if (esbuildChunkMinifier || useRolldownBuilder) {\n    // Register after Nitro and user hooks are prepared so the minifier is the\n    // final renderChunk transform, matching Nitro's Terser ordering.\n    nitroInstance.hooks.hook(\"rollup:before\", (_nitro, rollupConfig) => {\n      if (useRolldownBuilder) {\n        // Nitro 3 alpha still emits transform options that this Rolldown API\n        // rejects. The generated native Node adapter contains neither JSX nor\n        // browser-global injections, so omit both without changing its output.\n        const rolldownConfig = rollupConfig as typeof rollupConfig & {\n          inject?: unknown;\n          jsx?: unknown;\n        };\n        delete rolldownConfig.inject;\n        delete rolldownConfig.jsx;\n      }\n      if (esbuildChunkMinifier) {\n        const configuredPlugins = rollupConfig.plugins;\n        rollupConfig.plugins = [\n          ...(Array.isArray(configuredPlugins)\n            ? configuredPlugins\n            : configuredPlugins\n              ? [configuredPlugins]\n              : []),\n          esbuildChunkMinifier,\n        ];\n      }\n    });\n  }\n  if (prerenderRoutes.length > 0) {\n    logger.info(`📄 Pre-rendering ${prerenderRoutes.length} SSG page(s)`);\n    // Nitro's prerender worker copies this environment, so built-in analytics\n    // doesn't report the build's own page requests as traffic.\n    const previousPrerender = process.env[FARM_PRERENDER_ENV];\n    process.env[FARM_PRERENDER_ENV] = \"1\";\n    try {\n      await nitroBuilder.prerender(nitroInstance);\n    } finally {\n      if (previousPrerender === undefined) delete process.env[FARM_PRERENDER_ENV];\n      else process.env[FARM_PRERENDER_ENV] = previousPrerender;\n    }\n  }\n  const sharpRuntimeStagePromise =\n    imageRuntime === \"node\"\n      ? stageSharpRuntime(config, root, distDir, fs)\n      : Promise.resolve<StagedSharpRuntime | null>(null);\n  const [nitroBuildResult, sharpRuntimeStageResult] = await Promise.allSettled([\n    nitroBuilder.build(nitroInstance),\n    sharpRuntimeStagePromise,\n  ]);\n  await nitroInstance.close();\n  if (nitroBuildResult.status === \"rejected\") {\n    if (sharpRuntimeStageResult.status === \"fulfilled\" && sharpRuntimeStageResult.value) {\n      await fs.rm(sharpRuntimeStageResult.value.stageDir, {\n        recursive: true,\n        force: true,\n      });\n    }\n    throw nitroBuildResult.reason;\n  }\n  if (sharpRuntimeStageResult.status === \"rejected\") {\n    throw sharpRuntimeStageResult.reason;\n  }\n  const stagedSharpRuntime =\n    sharpRuntimeStageResult.value ??\n    (imageRuntime === \"node\" ? await stageSharpRuntime(config, root, distDir, fs) : null);\n\n  const runtimeCopyPromise = (async () => {\n    if (stagedSharpRuntime) {\n      await installStagedSharpRuntime(stagedSharpRuntime, runtimeServerOutputDir, fs);\n    }\n    if (useExternalMetadataImageRuntime) {\n      await copyMetadataImageRuntime(root, runtimeServerOutputDir, fs);\n    }\n  })();\n  const copyResults = await Promise.allSettled([\n    canReusePrebuiltSSR\n      ? copyPrebuiltSSRBundle(\n          ssrBundle,\n          path.join(outputDir, \"server\", FARM_SSR_OUTPUT_DIR),\n          prebuiltSSREsbuildOptions,\n          shouldMinify,\n          fs,\n        )\n      : Promise.resolve(),\n    runtimeCopyPromise,\n  ]);\n  const failedCopy = copyResults.find(\n    (result): result is PromiseRejectedResult => result.status === \"rejected\",\n  );\n  if (failedCopy) throw failedCopy.reason;\n\n  if (canReusePrebuiltSSR) {\n    await registerPrebuiltSSRPackageImport(path.join(outputDir, \"server\"), ssrEntryFile, fs);\n    logger.info(\"⚡ Reused Farm's prebuilt SSR bundle for the Node output\");\n  }\n  if (useRolldownBuilder) {\n    logger.info(\"⚡ Built the Node adapter with Rolldown\");\n  }\n\n  if (pluginManager) {\n    await pluginManager.runHookParallel(\"afterNitroBuild\", {\n      root,\n      preset,\n      distDir,\n      outputDir,\n    });\n  }\n\n  // Post-process for Vercel Build Output API v3\n  // Move server/ to functions/__nitro.func/ and update config.json\n  if (isVercel) {\n    await postProcessVercelOutput(root, outputDir, fs, config, farmWorkflows, routeRuntimeManifest);\n  }\n\n  logger.success(`✅ Nitro build completed with preset: ${preset}`);\n}\n\n/**\n * Keep Farm's conventional server/public split only for targets whose\n * post-processing and runtime adapters consume it. Platform presets such as\n * Cloudflare Pages and Netlify define their own output layout (for example\n * `_worker.js` or `.netlify/functions-internal`); supplying these directories\n * here overrides Nitro's preset defaults and produces an undeployable bundle.\n */\nexport function resolveFarmNitroOutputConfig(\n  preset: string,\n  outputDir: string,\n): NonNullable<NitroConfig[\"output\"]> {\n  const isVercel = preset === \"vercel\" || preset === \"vercel-edge\";\n\n  return {\n    dir: outputDir,\n    ...(preset === \"node-server\"\n      ? {\n          serverDir: path.join(outputDir, \"server\"),\n          publicDir: path.join(outputDir, \"public\"),\n        }\n      : isVercel\n        ? {\n            serverDir: path.join(outputDir, \"functions\", \"__nitro.func\"),\n            publicDir: path.join(outputDir, \"static\"),\n          }\n        : {}),\n  };\n}\n\nasync function copyPrebuiltSSRBundle(\n  ssrBundle: OutputBundle,\n  targetDir: string,\n  configuredEsbuildOptions: FarmEsbuildOptions,\n  minify: boolean,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const {\n    include: _include,\n    exclude: _exclude,\n    sourceMap: _sourceMap,\n    loaders: _loaders,\n    ...configuredTransformOptions\n  } = configuredEsbuildOptions;\n  const hasConfiguredTransforms = Object.keys(configuredTransformOptions).some(\n    (option) => option !== \"minify\",\n  );\n  const transformOptions = createEsbuildTransformOptions(\n    configuredEsbuildOptions,\n    minify,\n    \"node18\",\n  );\n  const transform = minify || hasConfiguredTransforms ? (await import(\"esbuild\")).transform : null;\n\n  await fs.rm(targetDir, { recursive: true, force: true });\n  await Promise.all(\n    Object.entries(ssrBundle).map(async ([fileName, output]) => {\n      const targetPath = path.join(targetDir, fileName);\n      await fs.mkdir(path.dirname(targetPath), { recursive: true });\n\n      if (output.type === \"asset\") {\n        await fs.writeFile(targetPath, output.source);\n        return;\n      }\n\n      let code = output.code;\n      if (transform) {\n        const result = await transform(code, {\n          ...transformOptions,\n          sourcefile: fileName,\n        });\n        code = result.code;\n      }\n\n      await fs.writeFile(targetPath, code);\n    }),\n  );\n}\n\nasync function registerPrebuiltSSRPackageImport(\n  serverDir: string,\n  ssrEntryFile: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const packagePath = path.join(serverDir, \"package.json\");\n  const packageJSON = await fs\n    .readFile(packagePath, \"utf8\")\n    .then((contents) => JSON.parse(contents))\n    .catch((error: NodeJS.ErrnoException) => {\n      if (error.code === \"ENOENT\") return { type: \"module\" };\n      throw error;\n    });\n  const existingImports =\n    packageJSON.imports && typeof packageJSON.imports === \"object\" ? packageJSON.imports : {};\n  const outputEntry = `${FARM_SSR_OUTPUT_DIR}/${ssrEntryFile}`.replace(/\\\\/g, \"/\");\n\n  packageJSON.imports = {\n    ...existingImports,\n    [FARM_SSR_PACKAGE_IMPORT]: `./${outputEntry}`,\n  };\n  await fs.mkdir(serverDir, { recursive: true });\n  await fs.writeFile(packagePath, `${JSON.stringify(packageJSON, null, 2)}\\n`);\n}\n\n/**\n * Move a file or directory, falling back to copy-and-remove when rename is\n * not permitted. On Windows, fs.rename fails with EPERM/EACCES when another\n * process (antivirus, indexing, a running dev server) holds a handle on the\n * directory, and with EXDEV across drives; a copy is slower but succeeds.\n */\nexport async function moveVercelOutputPath(\n  src: string,\n  dest: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  try {\n    await fs.rename(src, dest);\n    return;\n  } catch (error) {\n    const code = (error as NodeJS.ErrnoException)?.code;\n    if (code !== \"EPERM\" && code !== \"EACCES\" && code !== \"EXDEV\" && code !== \"ENOTEMPTY\") {\n      throw error;\n    }\n  }\n  await fs.cp(src, dest, { recursive: true, force: true });\n  await fs.rm(src, { recursive: true, force: true });\n}\n\n/**\n * Post-process Vercel output to match Build Output API v3\n * Moves server/ to functions/__nitro.func/ and updates routes\n */\nasync function postProcessVercelOutput(\n  root: string,\n  outputDir: string,\n  fs: typeof import(\"fs/promises\"),\n  config: ResolvedFarmConfig,\n  farmWorkflows: PreparedFarmWorkflows,\n  routeRuntimeManifest: FarmRouteRuntimeManifest,\n) {\n  const serverDir = path.join(outputDir, \"server\");\n  const functionsDir = path.join(outputDir, \"functions\");\n  const nitroFuncDir = path.join(functionsDir, \"__nitro.func\");\n  const staticDir = path.join(outputDir, \"static\");\n  const publicDir = path.join(outputDir, \"public\");\n\n  // Patched Nitro v3 Vercel presets already write the function in its Build\n  // Output API directory. Retain migration support for older preset output.\n  await fs.mkdir(nitroFuncDir, { recursive: true });\n  const serverContents = await fs.readdir(serverDir).catch((error: NodeJS.ErrnoException) => {\n    if (error.code === \"ENOENT\") return [];\n    throw error;\n  });\n  for (const file of serverContents) {\n    await moveVercelOutputPath(path.join(serverDir, file), path.join(nitroFuncDir, file), fs);\n  }\n  if (serverContents.length > 0) await fs.rm(serverDir, { recursive: true, force: true });\n\n  // Rename public to static (Vercel expects static files in static/)\n  try {\n    await moveVercelOutputPath(publicDir, staticDir, fs);\n  } catch (error) {\n    // public might not exist\n    if ((error as NodeJS.ErrnoException)?.code !== \"ENOENT\") throw error;\n  }\n\n  // Add runtime assets before cloning route-specific functions.\n  await copyFarmDocsContentForVercel(config, root, nitroFuncDir, fs);\n  await copyPrismaClientForVercel(root, nitroFuncDir, fs);\n\n  // Update config.json routes to point to the function\n  const configPath = path.join(outputDir, \"config.json\");\n  const configContent = await fs.readFile(configPath, \"utf-8\");\n  const vercelConfig = JSON.parse(configContent);\n\n  const runtimeRoutes = await createFarmVercelRouteRuntimeFunctions(\n    outputDir,\n    routeRuntimeManifest,\n    fs,\n    config.basePath,\n  );\n\n  // Rebuild the routes around Farm's `__nitro` function while preserving the\n  // preset's redirect and header routes (previously discarded). See\n  // buildFarmVercelRoutes for the full merge contract.\n  vercelConfig.routes = buildFarmVercelRoutes({\n    presetRoutes: Array.isArray(vercelConfig.routes) ? vercelConfig.routes : [],\n    runtimeRoutes,\n  });\n\n  const vercelConfigWithWorkflowCrons = applyFarmWorkflowVercelCrons(\n    vercelConfig,\n    farmWorkflows.workflows,\n  );\n  const vercelConfigWithCrons = applyFarmCronVercelCrons(\n    vercelConfigWithWorkflowCrons,\n    config.cron.jobs,\n  );\n\n  await fs.writeFile(configPath, JSON.stringify(vercelConfigWithCrons, null, 2));\n\n  logger.info(\"✅ Post-processed Vercel output for Build Output API v3\");\n}\n\nasync function copyFarmDocsContentForVercel(\n  config: ResolvedFarmConfig,\n  root: string,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n) {\n  const docsContentDir = resolveBuildDocsContentDir(config, root);\n  if (!docsContentDir) return;\n\n  // Nitro v3 emits the SSR entry at the function root. Its docs lookup searches\n  // beside the entry and its ancestors, not the old chunks/nitro directory.\n  const bundledContentDir = path.join(nitroFuncDir, \"farm-docs-content\");\n  const lastModifiedManifest = createFarmDocsLastModifiedManifest(docsContentDir, {\n    fallback: \"now\",\n  });\n  await fs.rm(bundledContentDir, { recursive: true, force: true });\n  await fs.mkdir(path.dirname(bundledContentDir), { recursive: true });\n  await fs.cp(docsContentDir, bundledContentDir, {\n    recursive: true,\n    force: true,\n  });\n  await fs.writeFile(\n    path.join(bundledContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST),\n    `${JSON.stringify(lastModifiedManifest, null, 2)}\\n`,\n  );\n\n  logger.info(`📚 Bundled docs content for Vercel: ${path.relative(root, docsContentDir)}`);\n}\n\ninterface StagedSharpRuntime {\n  stageDir: string;\n  dependencies: Record<string, string>;\n}\n\nasync function stageSharpRuntime(\n  config: ResolvedFarmConfig,\n  root: string,\n  distDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<StagedSharpRuntime> {\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  let sharpRequire = projectRequire;\n  if (!resolvePackageJson(projectRequire, \"sharp\")) {\n    try {\n      // Applications are not required to depend on Sharp directly. Resolve\n      // Farm's optional dependency from the installed framework entry when the\n      // project dependency tree does not expose it.\n      sharpRequire = createRequire(projectRequire.resolve(\"@farm.js/core\"));\n    } catch {\n      // The existing missing-Sharp diagnostic below remains authoritative.\n    }\n  }\n  const copiedPackages = new Map<string, string>();\n  const packageCopies = new Map<string, Promise<void>>();\n  const stageRoot = path.join(root, distDir, \"tmp\");\n  await fs.mkdir(stageRoot, { recursive: true });\n  const stageDir = await fs.mkdtemp(path.join(stageRoot, \"sharp-runtime-\"));\n  const targetNodeModules = path.join(stageDir, \"node_modules\");\n\n  function copyPackage(packageName: string, parentRequire: NodeJS.Require): Promise<void> {\n    const activeCopy = packageCopies.get(packageName);\n    if (activeCopy) return activeCopy;\n\n    const packageCopy = copyPackageOnce(packageName, parentRequire);\n    packageCopies.set(packageName, packageCopy);\n    return packageCopy;\n  }\n\n  async function copyPackageOnce(\n    packageName: string,\n    parentRequire: NodeJS.Require,\n  ): Promise<void> {\n    const packageJsonPath = resolvePackageJson(parentRequire, packageName);\n    if (!packageJsonPath) return;\n    const packageJson = JSON.parse(await fs.readFile(packageJsonPath, \"utf8\"));\n    const packageDir = path.dirname(packageJsonPath);\n    const targetDir = path.join(targetNodeModules, ...packageName.split(\"/\"));\n    copiedPackages.set(packageName, String(packageJson.version || \"*\"));\n\n    await fs.mkdir(path.dirname(targetDir), { recursive: true });\n    const packageRequire = createRequire(packageJsonPath);\n    const dependencies = {\n      ...packageJson.dependencies,\n      ...packageJson.optionalDependencies,\n    };\n    await Promise.all([\n      fs.cp(packageDir, targetDir, {\n        recursive: true,\n        force: true,\n        dereference: true,\n        // Reflinks make native runtime packaging nearly metadata-only on\n        // supporting filesystems and transparently fall back to byte copies.\n        mode: fsConstants.COPYFILE_FICLONE,\n      }),\n      ...Object.keys(dependencies).map((dependency) => copyPackage(dependency, packageRequire)),\n    ]);\n  }\n\n  try {\n    await copyPackage(\"sharp\", sharpRequire);\n    if (!copiedPackages.has(\"sharp\")) {\n      throw new Error(\n        \"Farm image optimization requires sharp. Reinstall dependencies without omitting optional packages.\",\n      );\n    }\n  } catch (error) {\n    await fs.rm(stageDir, { recursive: true, force: true });\n    throw error;\n  }\n\n  return {\n    stageDir,\n    dependencies: Object.fromEntries(\n      [...copiedPackages].sort(([left], [right]) => left.localeCompare(right)),\n    ),\n  };\n}\n\nasync function installStagedSharpRuntime(\n  staged: StagedSharpRuntime,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const stagedNodeModules = path.join(staged.stageDir, \"node_modules\");\n  const targetNodeModules = path.join(nitroFuncDir, \"node_modules\");\n\n  try {\n    await mergeStagedDirectory(stagedNodeModules, targetNodeModules, fs);\n\n    const functionPackage = await readNitroOutputPackage(nitroFuncDir, fs);\n    functionPackage.dependencies = {\n      ...functionPackage.dependencies,\n      ...staged.dependencies,\n    };\n    await writeNitroOutputPackage(nitroFuncDir, functionPackage, fs);\n  } finally {\n    await fs.rm(staged.stageDir, { recursive: true, force: true });\n  }\n\n  logger.info(\n    `🖼️  Bundled Sharp image runtime (${Object.keys(staged.dependencies).length} packages)`,\n  );\n}\n\nasync function mergeStagedDirectory(\n  sourceDir: string,\n  targetDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  await fs.mkdir(targetDir, { recursive: true });\n  const entries = await fs.readdir(sourceDir, { withFileTypes: true });\n\n  await Promise.all(\n    entries.map(async (entry) => {\n      const sourcePath = path.join(sourceDir, entry.name);\n      const targetPath = path.join(targetDir, entry.name);\n\n      try {\n        await fs.rename(sourcePath, targetPath);\n        return;\n      } catch (error) {\n        const code = (error as NodeJS.ErrnoException).code;\n        if (code !== \"EEXIST\" && code !== \"ENOTEMPTY\" && code !== \"EXDEV\") {\n          throw error;\n        }\n      }\n\n      if (entry.isDirectory()) {\n        await mergeStagedDirectory(sourcePath, targetPath, fs);\n        await fs.rm(sourcePath, { recursive: true, force: true });\n        return;\n      }\n\n      await fs.cp(sourcePath, targetPath, {\n        force: true,\n        dereference: true,\n        mode: fsConstants.COPYFILE_FICLONE,\n      });\n      await fs.rm(sourcePath, { force: true });\n    }),\n  );\n}\n\nasync function copyMetadataImageRuntime(\n  root: string,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n  let runtimeRequire = projectRequire;\n  let packageJsonPath = resolvePackageJson(runtimeRequire, \"@vercel/og\");\n\n  if (!packageJsonPath) {\n    try {\n      runtimeRequire = createRequire(projectRequire.resolve(\"@farm.js/core\"));\n      packageJsonPath = resolvePackageJson(runtimeRequire, \"@vercel/og\");\n    } catch {\n      // The missing-runtime diagnostic below remains authoritative.\n    }\n  }\n\n  if (!packageJsonPath) {\n    throw new Error(\n      \"Generated metadata images require @vercel/og. Reinstall @farm.js/core with production dependencies.\",\n    );\n  }\n\n  const packageJson = JSON.parse(await fs.readFile(packageJsonPath, \"utf8\"));\n  const packageDir = path.dirname(packageJsonPath);\n  const targetDir = path.join(nitroFuncDir, \"node_modules\", \"@vercel\", \"og\");\n  await fs.mkdir(path.dirname(targetDir), { recursive: true });\n  await fs.cp(packageDir, targetDir, {\n    recursive: true,\n    force: true,\n    dereference: true,\n    mode: fsConstants.COPYFILE_FICLONE,\n  });\n\n  const functionPackage = await readNitroOutputPackage(nitroFuncDir, fs);\n  functionPackage.dependencies = {\n    ...functionPackage.dependencies,\n    \"@vercel/og\": String(packageJson.version || \"0.11.1\"),\n  };\n  await writeNitroOutputPackage(nitroFuncDir, functionPackage, fs);\n  logger.info(\"🖼️  Bundled generated metadata image runtime\");\n}\n\nasync function readNitroOutputPackage(\n  outputDir: string,\n  fs: typeof import(\"fs/promises\"),\n): Promise<NitroOutputPackage> {\n  const packagePath = path.join(outputDir, \"package.json\");\n  return fs\n    .readFile(packagePath, \"utf8\")\n    .then((contents) => JSON.parse(contents))\n    .catch((error: NodeJS.ErrnoException) => {\n      if (error.code === \"ENOENT\") return {};\n      throw error;\n    });\n}\n\nasync function writeNitroOutputPackage(\n  outputDir: string,\n  packageJson: NitroOutputPackage,\n  fs: typeof import(\"fs/promises\"),\n): Promise<void> {\n  await fs.mkdir(outputDir, { recursive: true });\n  await fs.writeFile(\n    path.join(outputDir, \"package.json\"),\n    `${JSON.stringify(packageJson, null, 2)}\\n`,\n  );\n}\n\nfunction resolvePackageJson(parentRequire: NodeJS.Require, packageName: string): string | null {\n  for (const request of [`${packageName}/package.json`, `${packageName}/package`]) {\n    try {\n      return parentRequire.resolve(request);\n    } catch {\n      // Try the next package metadata export.\n    }\n  }\n\n  // Some modern packages, including Sharp 0.35+, do not export their\n  // package.json. Resolve their entry point and walk back to the package root\n  // so production staging keeps working without requiring a legacy export.\n  try {\n    let directory = path.dirname(parentRequire.resolve(packageName));\n    while (directory !== path.dirname(directory)) {\n      const candidate = path.join(directory, \"package.json\");\n      if (existsSync(candidate)) {\n        try {\n          const manifest = JSON.parse(readFileSync(candidate, \"utf8\")) as { name?: unknown };\n          if (manifest.name === packageName) return candidate;\n        } catch {\n          // Ignore unrelated or malformed metadata while walking upward.\n        }\n      }\n      if (path.basename(directory) === \"node_modules\") break;\n      directory = path.dirname(directory);\n    }\n  } catch {\n    // Keep the existing null result and caller diagnostics when resolution fails.\n  }\n  return null;\n}\n\nasync function copyPrismaClientForVercel(\n  root: string,\n  nitroFuncDir: string,\n  fs: typeof import(\"fs/promises\"),\n) {\n  const projectRequire = createRequire(path.join(root, \"package.json\"));\n\n  let prismaClientDir: string;\n  try {\n    prismaClientDir = path.dirname(projectRequire.resolve(\"@prisma/client/default.js\"));\n  } catch {\n    return;\n  }\n\n  const generatedClientDir = path.join(prismaClientDir, \"..\", \"..\", \".prisma\", \"client\");\n\n  try {\n    await fs.access(generatedClientDir);\n  } catch {\n    return;\n  }\n\n  const targetNodeModules = path.join(nitroFuncDir, \"node_modules\");\n  const targetPrismaScopeDir = path.join(targetNodeModules, \"@prisma\");\n  const targetGeneratedDir = path.join(targetNodeModules, \".prisma\", \"client\");\n  const targetClientDir = path.join(targetPrismaScopeDir, \"client\");\n\n  await fs.mkdir(targetPrismaScopeDir, { recursive: true });\n  await fs.cp(prismaClientDir, targetClientDir, {\n    recursive: true,\n    force: true,\n  });\n  await fs.cp(generatedClientDir, targetGeneratedDir, {\n    recursive: true,\n    force: true,\n  });\n\n  const clientPackagePath = path.join(prismaClientDir, \"package.json\");\n  const [functionPackage, clientPackageContent] = await Promise.all([\n    readNitroOutputPackage(nitroFuncDir, fs),\n    fs.readFile(clientPackagePath, \"utf-8\"),\n  ]);\n  const clientPackage = JSON.parse(clientPackageContent);\n\n  functionPackage.dependencies = {\n    ...functionPackage.dependencies,\n    \"@prisma/client\": clientPackage.version,\n  };\n\n  await writeNitroOutputPackage(nitroFuncDir, functionPackage, fs);\n}\n","import path from \"node:path\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\nimport {\n  createFarmDocsHandler,\n  discoverFarmDocsPages,\n  loadFarmDocsPage,\n  resolveFarmDocsContentDir,\n  toFarmDocsMarkdownPage,\n  type LoadedFarmDocsPage,\n} from \"./handler\";\nimport { createFarmDocsAPIHandler } from \"./api\";\nimport type { FarmDocsPublicFontAsset } from \"./fonts\";\nimport type { FarmDocsCompiledManifest, FarmDocsCompiledResponse } from \"./precompiled-runtime\";\n\nexport const FARM_DOCS_COMPILED_ORIGIN = \"https://farm-docs-build.invalid\";\n\nexport interface CompileFarmDocsManifestOptions {\n  root: string;\n  srcDir: string;\n  clientEntry: string;\n  fontAssets: readonly FarmDocsPublicFontAsset[];\n  fontStylesheetHref?: string;\n  globalStylesheetHref?: string;\n}\n\nfunction normalizePathname(pathname: string): string {\n  if (pathname === \"/\") return pathname;\n  return pathname.replace(/\\/+$/g, \"\") || \"/\";\n}\n\nfunction sanitizeCompiledValue(value: string, absolutePaths: readonly string[]): string {\n  let sanitized = value;\n  for (const absolutePath of absolutePaths) {\n    if (!absolutePath) continue;\n    sanitized = sanitized.split(absolutePath).join(\".\");\n    sanitized = sanitized.split(absolutePath.replace(/\\\\/g, \"/\")).join(\".\");\n    sanitized = sanitized.split(absolutePath.replace(/\\//g, \"\\\\\")).join(\".\");\n  }\n  return sanitized;\n}\n\nasync function compileResponse(\n  response: Response,\n  absolutePaths: readonly string[],\n): Promise<FarmDocsCompiledResponse> {\n  return {\n    status: response.status,\n    statusText: response.statusText,\n    headers: Array.from(response.headers.entries()).map(([key, value]) => [\n      key,\n      sanitizeCompiledValue(value, absolutePaths),\n    ]),\n    body: sanitizeCompiledValue(await response.text(), absolutePaths),\n  };\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n  return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n    ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n    : \"Documentation\";\n}\n\nfunction loadPages(contentDir: string, docs: FarmDocsResolvedConfig): LoadedFarmDocsPage[] {\n  return discoverFarmDocsPages(contentDir, docs)\n    .map((page) => loadFarmDocsPage(contentDir, docs, page.slug))\n    .filter((page): page is LoadedFarmDocsPage => Boolean(page))\n    .sort((a, b) => a.href.localeCompare(b.href));\n}\n\nfunction findSocialImagePath(html: string): string | null {\n  const match =\n    /<meta\\s+property=[\"']og:image[\"']\\s+content=[\"']([^\"']+)[\"']/i.exec(html) ||\n    /<meta\\s+content=[\"']([^\"']+)[\"']\\s+property=[\"']og:image[\"']/i.exec(html);\n  if (!match?.[1]) return null;\n  try {\n    return new URL(match[1], FARM_DOCS_COMPILED_ORIGIN).pathname;\n  } catch {\n    return null;\n  }\n}\n\nasync function addHandlerRoute(\n  routes: Record<string, FarmDocsCompiledResponse>,\n  pathname: string,\n  handler: (request: Request) => Promise<Response | null>,\n  absolutePaths: readonly string[],\n): Promise<Response | null> {\n  const response = await handler(new Request(`${FARM_DOCS_COMPILED_ORIGIN}${pathname}`));\n  if (!response) return null;\n  routes[normalizePathname(pathname)] = await compileResponse(response.clone(), absolutePaths);\n  return response;\n}\n\nexport async function compileFarmDocsManifest(\n  docs: FarmDocsResolvedConfig,\n  options: CompileFarmDocsManifestOptions,\n): Promise<FarmDocsCompiledManifest> {\n  const contentDir = resolveFarmDocsContentDir(docs, options);\n  const pages = loadPages(contentDir, docs);\n  const absolutePaths = [\n    path.resolve(options.root),\n    path.resolve(contentDir),\n    docs.configPath || \"\",\n  ];\n  const handler = createFarmDocsHandler(docs, {\n    root: options.root,\n    srcDir: options.srcDir,\n    clientEntry: options.clientEntry,\n    fontAssets: options.fontAssets,\n    fontStylesheetHref: options.fontStylesheetHref,\n    globalStylesheetHref: options.globalStylesheetHref,\n  });\n  const apiHandler = createFarmDocsAPIHandler({\n    rootDir: options.root,\n    srcDir: options.srcDir,\n    docs,\n  });\n  const routes: Record<string, FarmDocsCompiledResponse> = {};\n  const apiMarkdown: Record<string, FarmDocsCompiledResponse> = {};\n\n  for (const page of pages) {\n    const htmlResponse = await addHandlerRoute(routes, page.href, handler, absolutePaths);\n    const markdownPath = page.href === \"/\" ? \"/.md\" : `${page.href}.md`;\n    await addHandlerRoute(routes, markdownPath, handler, absolutePaths);\n\n    if (htmlResponse) {\n      const socialImagePath = findSocialImagePath(await htmlResponse.text());\n      if (socialImagePath && !routes[normalizePathname(socialImagePath)]) {\n        await addHandlerRoute(routes, socialImagePath, handler, absolutePaths);\n      }\n    }\n\n    const apiResponse = await apiHandler(\n      new Request(\n        `${FARM_DOCS_COMPILED_ORIGIN}/api/docs?format=markdown&path=${encodeURIComponent(page.slug)}`,\n      ),\n    );\n    if (apiResponse) {\n      apiMarkdown[page.slug] = await compileResponse(apiResponse, absolutePaths);\n    }\n  }\n\n  const publicCandidates = [\n    \"/llms.txt\",\n    \"/llms-full.txt\",\n    \"/.well-known/llms.txt\",\n    \"/.well-known/llms-full.txt\",\n    \"/AGENTS.md\",\n    \"/agent.md\",\n    \"/.well-known/AGENTS.md\",\n    \"/SKILL.md\",\n    \"/.well-known/SKILL.md\",\n    \"/.well-known/agent.json\",\n    \"/sitemap.xml\",\n    \"/sitemap.md\",\n    \"/robots.txt\",\n    `${docs.entry.replace(/\\/+$/g, \"\")}/sitemap.md`,\n  ];\n  for (const pathname of publicCandidates) {\n    if (!routes[normalizePathname(pathname)]) {\n      await addHandlerRoute(routes, pathname, handler, absolutePaths);\n    }\n  }\n\n  const staticFormats = [\n    \"config\",\n    \"skill\",\n    \"agents\",\n    \"agent-spec\",\n    \"diagnostics\",\n    \"llms\",\n    \"llms-full\",\n    \"sitemap-md\",\n    \"sitemap-xml\",\n    \"robots\",\n  ];\n  const apiStatic: Record<string, FarmDocsCompiledResponse> = {};\n  for (const format of staticFormats) {\n    const response = await apiHandler(\n      new Request(`${FARM_DOCS_COMPILED_ORIGIN}/api/docs?format=${format}`),\n    );\n    if (response) apiStatic[format] = await compileResponse(response, absolutePaths);\n  }\n\n  const emptyResponse = await apiHandler(new Request(`${FARM_DOCS_COMPILED_ORIGIN}/api/docs`));\n  const postResponse = await apiHandler(\n    new Request(`${FARM_DOCS_COMPILED_ORIGIN}/api/docs`, { method: \"POST\" }),\n  );\n  if (!emptyResponse || !postResponse) {\n    throw new Error(\"Farm docs compiler could not create the built-in API responses.\");\n  }\n\n  const searchConfig = docs.config.search;\n  if (\n    searchConfig &&\n    typeof searchConfig === \"object\" &&\n    \"provider\" in searchConfig &&\n    searchConfig.provider === \"custom\"\n  ) {\n    throw new Error(\n      \"Farm cannot serialize a custom docs search adapter into an edge deployment. \" +\n        'Use the built-in \"simple\" provider, a serializable hosted provider, or a Node target.',\n    );\n  }\n  const searchLimit =\n    searchConfig && typeof searchConfig === \"object\" && \"maxResults\" in searchConfig\n      ? Number((searchConfig as { maxResults?: unknown }).maxResults)\n      : undefined;\n\n  return {\n    protocol: 1,\n    originPlaceholder: FARM_DOCS_COMPILED_ORIGIN,\n    entry: docs.entry,\n    routes,\n    api: {\n      static: apiStatic,\n      markdown: apiMarkdown,\n      empty: await compileResponse(emptyResponse, absolutePaths),\n      post: await compileResponse(postResponse, absolutePaths),\n      search: {\n        pages: pages.map((page) => ({\n          ...toFarmDocsMarkdownPage(page),\n          sourcePath: `farm-docs:${page.slug || \"index\"}`,\n        })),\n        search: searchConfig ?? true,\n        siteTitle: getDocsTitle(docs),\n        ...(Number.isFinite(searchLimit) ? { limit: searchLimit } : {}),\n      },\n    },\n  };\n}\n","import path from \"path\";\nimport type { APIRouteManager } from \"./api/route-manager\";\nimport { resolveFarmAPIServerBasePath, resolveFarmAPIServerRoutePath } from \"./api/server-path\";\nimport type { ResolvedFarmConfig } from \"./config\";\nimport { getFarmPresetRuntime, type FarmPresetRuntime } from \"./deployment\";\nimport {\n  getFarmRouteRuntimeConfig,\n  hasFarmRouteRuntimeControls,\n  mergeFarmRouteRuntimeConfigs,\n  normalizeFarmRouteRuntimeConfig,\n  resolveFarmRouteRuleRuntimeConfig,\n  resolveFarmRouteRuntimeConfig,\n  type FarmRouteRuntimeManifest,\n  type FarmRouteRuntimeManifestEntry,\n} from \"./route-runtime\";\nimport type { RouteManager } from \"./routing/route-manager\";\nimport { resolveRouteRenderingConfigFromFile } from \"./ssg\";\n\nexport const FARM_ROUTE_RUNTIME_MANIFEST = \"route-runtime-manifest.json\";\n\nexport interface FarmRouteRuntimeDeploymentValidation {\n  runtime: FarmPresetRuntime;\n  warnings: string[];\n}\n\nexport async function createFarmRouteRuntimeManifest(options: {\n  config: ResolvedFarmConfig;\n  routeManager: RouteManager;\n  apiRouteManager: APIRouteManager;\n  root?: string;\n}): Promise<FarmRouteRuntimeManifest> {\n  const root = path.resolve(options.root || options.config.root || process.cwd());\n  const routes: FarmRouteRuntimeManifestEntry[] = [];\n\n  for (const [pattern, entry] of options.routeManager.getRoutes()) {\n    const routeModule = await options.routeManager.loadRouteModule(entry.modulePath);\n    const rendering = await resolveRouteRenderingConfigFromFile(routeModule, entry.modulePath);\n    const runtimeConfig = await options.routeManager.resolveRouteRuntimeConfig(pattern);\n\n    routes.push({\n      kind: \"page\",\n      pattern,\n      rendering: rendering.ssg ? \"static\" : \"dynamic\",\n      source: normalizeManifestSource(root, entry.modulePath),\n      ...runtimeConfig,\n    });\n  }\n\n  for (const [pattern, route] of options.apiRouteManager.getRoutes()) {\n    const publicPattern = resolveFarmAPIServerRoutePath(\n      pattern,\n      resolveFarmAPIServerBasePath(options.config.api),\n    );\n    const inherited = resolveFarmRouteRuleRuntimeConfig(publicPattern, options.config.routeRules);\n    const own = normalizeFarmRouteRuntimeConfig(\n      getFarmRouteRuntimeConfig(route),\n      `API route \"${pattern}\"`,\n    );\n\n    routes.push({\n      kind: \"api\",\n      pattern: publicPattern,\n      rendering: \"dynamic\",\n      source: normalizeManifestSource(root, route.filePath),\n      ...resolveFarmRouteRuntimeConfig(\n        mergeFarmRouteRuntimeConfigs(inherited, own),\n        `API route \"${pattern}\"`,\n      ),\n    });\n  }\n\n  for (const entry of options.routeManager.getMetadataRoutes().values()) {\n    const routeModule = await options.routeManager.loadRouteModule(entry.modulePath);\n    const pattern =\n      entry.pattern === \"/\" ? `/${entry.outputName}` : `${entry.pattern}/${entry.outputName}`;\n    const inherited = resolveFarmRouteRuleRuntimeConfig(pattern, options.config.routeRules);\n    const own = normalizeFarmRouteRuntimeConfig(\n      getFarmRouteRuntimeConfig(routeModule),\n      `Metadata route \"${pattern}\"`,\n    );\n\n    routes.push({\n      kind: \"metadata\",\n      pattern,\n      rendering: \"dynamic\",\n      source: normalizeManifestSource(root, entry.modulePath),\n      ...resolveFarmRouteRuntimeConfig(\n        mergeFarmRouteRuntimeConfigs(inherited, own),\n        `Metadata route \"${pattern}\"`,\n      ),\n    });\n  }\n\n  for (const [pattern, rule] of Object.entries(options.config.routeRules)) {\n    if (!hasFarmRouteRuntimeControls(rule)) continue;\n\n    routes.push({\n      kind: \"rule\",\n      pattern,\n      rendering: rule.prerender || rule.render === \"static\" ? \"static\" : \"dynamic\",\n      ...resolveFarmRouteRuntimeConfig(rule, `Route rule \"${pattern}\"`),\n    });\n  }\n\n  return {\n    version: 1,\n    routes,\n  };\n}\n\nexport async function writeFarmRouteRuntimeManifest(\n  directory: string,\n  manifest: FarmRouteRuntimeManifest,\n): Promise<string> {\n  const fs = await import(\"fs/promises\");\n  const manifestPath = path.join(directory, FARM_ROUTE_RUNTIME_MANIFEST);\n  await fs.mkdir(directory, { recursive: true });\n  await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n  return manifestPath;\n}\n\nexport function validateFarmRouteRuntimeDeployment(\n  manifest: FarmRouteRuntimeManifest,\n  preset: string,\n): FarmRouteRuntimeDeploymentValidation {\n  const runtime = getFarmPresetRuntime(preset);\n  const warnings = new Set<string>();\n\n  for (const route of manifest.routes) {\n    if (route.rendering === \"static\") continue;\n\n    if (runtime === \"unknown\" && route.runtime !== \"auto\") {\n      warnings.add(\n        `Preset \"${preset}\" has an unknown runtime, so Farm could not verify routes that explicitly require node or edge.`,\n      );\n    }\n\n    if (runtime !== \"unknown\" && route.runtime !== \"auto\" && route.runtime !== runtime) {\n      throw new Error(\n        `Route \"${route.pattern}\" requires the ${route.runtime} runtime, but preset \"${preset}\" emits ${runtime} functions. Choose a compatible preset or change the route runtime.`,\n      );\n    }\n\n    if (route.regions?.length && preset !== \"vercel\" && preset !== \"vercel-edge\") {\n      warnings.add(\n        `Preset \"${preset}\" does not map per-route regions; Farm kept them in ${FARM_ROUTE_RUNTIME_MANIFEST} for deployment adapters.`,\n      );\n    }\n\n    if (route.maxDuration && preset !== \"vercel\") {\n      warnings.add(\n        `Preset \"${preset}\" does not map per-route maxDuration; Farm kept it in ${FARM_ROUTE_RUNTIME_MANIFEST} for deployment adapters.`,\n      );\n    }\n  }\n\n  return { runtime, warnings: Array.from(warnings) };\n}\n\nfunction normalizeManifestSource(root: string, modulePath: string): string {\n  const queryIndex = modulePath.indexOf(\"?\");\n  const filePath = queryIndex === -1 ? modulePath : modulePath.slice(0, queryIndex);\n  const query = queryIndex === -1 ? \"\" : modulePath.slice(queryIndex);\n  const relativePath = path.isAbsolute(filePath) ? path.relative(root, filePath) : filePath;\n  return `${relativePath.replace(/\\\\/g, \"/\")}${query}`;\n}\n","import path from \"path\";\nimport {\n  createFarmRouteRuntimeKey,\n  type FarmRouteRuntimeManifest,\n  type FarmRouteRuntimeManifestEntry,\n  type ResolvedFarmRouteRuntimeConfig,\n} from \"../route-runtime\";\n\nexport interface FarmVercelRuntimeRoute {\n  src: string;\n  dest: string;\n  headers?: Record<string, string>;\n}\n\ntype FileSystemPromises = typeof import(\"fs/promises\");\n\n/** Materialize one Node function per distinct region/duration policy. */\nexport async function createFarmVercelRouteRuntimeFunctions(\n  outputDir: string,\n  manifest: FarmRouteRuntimeManifest,\n  fs: FileSystemPromises,\n  basePath = \"/\",\n): Promise<FarmVercelRuntimeRoute[]> {\n  const dynamicRoutes = manifest.routes.filter(\n    (route) => route.rendering === \"dynamic\" && route.runtime !== \"edge\",\n  );\n  if (!dynamicRoutes.some(hasVercelFunctionControls)) return [];\n\n  const configuredRoutes = dynamicRoutes\n    .filter((route) => route.kind !== \"rule\" || hasVercelFunctionControls(route))\n    .sort(compareRuntimeRoutes);\n  if (configuredRoutes.length === 0) return [];\n\n  const groups = new Map<\n    string,\n    { config: ResolvedFarmRouteRuntimeConfig; routes: FarmRouteRuntimeManifestEntry[] }\n  >();\n\n  for (const route of configuredRoutes) {\n    const config = {\n      runtime: route.runtime === \"auto\" ? \"node\" : route.runtime,\n      regions: route.regions,\n      maxDuration: route.maxDuration,\n    } satisfies ResolvedFarmRouteRuntimeConfig;\n    const key = createFarmRouteRuntimeKey(config);\n    const group = groups.get(key) || { config, routes: [] };\n    group.routes.push(route);\n    groups.set(key, group);\n  }\n\n  const functionsDir = path.join(outputDir, \"functions\");\n  const baseFunctionDir = path.join(functionsDir, \"__nitro.func\");\n  const destinations = new Map<string, string>();\n  let groupIndex = 0;\n\n  for (const [key, group] of groups) {\n    if (!group.config.regions?.length && !group.config.maxDuration) {\n      destinations.set(key, \"/__nitro\");\n      continue;\n    }\n\n    groupIndex += 1;\n    const functionName = `__farm_runtime_${groupIndex}`;\n    const functionDir = path.join(functionsDir, `${functionName}.func`);\n    await fs.cp(baseFunctionDir, functionDir, { recursive: true, force: true });\n    await configureVercelFunction(functionDir, group.config, fs);\n    destinations.set(key, `/${functionName}`);\n  }\n\n  const routes: FarmVercelRuntimeRoute[] = [];\n  const seenSources = new Set<string>();\n  for (const route of configuredRoutes) {\n    const src = farmRoutePatternToVercelSource(route.pattern, basePath);\n    if (seenSources.has(src)) continue;\n    seenSources.add(src);\n    const key = createFarmRouteRuntimeKey({\n      runtime: route.runtime === \"auto\" ? \"node\" : route.runtime,\n      regions: route.regions,\n      maxDuration: route.maxDuration,\n    });\n    routes.push({\n      src,\n      dest: destinations.get(key) || \"/__nitro\",\n      ...(route.kind === \"api\" || route.pattern.startsWith(\"/api/\")\n        ? {\n            headers: {\n              \"Access-Control-Allow-Origin\": \"*\",\n              \"Access-Control-Allow-Methods\": \"*\",\n              \"Access-Control-Allow-Headers\": \"*\",\n            },\n          }\n        : {}),\n    });\n  }\n\n  return routes;\n}\n\nexport function farmRoutePatternToVercelSource(pattern: string, basePath = \"/\"): string {\n  const normalized = normalizePattern(pattern);\n  const normalizedBasePath = normalizeBasePath(basePath);\n  if (normalized === \"/\") return normalizedBasePath || \"/\";\n\n  let source = \"\";\n  for (const segment of normalized.split(\"/\").filter(Boolean)) {\n    if (segment === \"**\" || /^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)) {\n      source += \"(?:/(.*))?\";\n    } else if (/^\\[\\.\\.\\..+\\]$/.test(segment)) {\n      source += \"/(.+)\";\n    } else if (segment === \"*\" || /^\\[.+\\]$/.test(segment)) {\n      source += \"/([^/]+)\";\n    } else {\n      source += `/${escapeRegExp(segment)}`;\n    }\n  }\n\n  if (!normalizedBasePath) return source || \"/\";\n  return source === \"/\" ? normalizedBasePath : `${normalizedBasePath}${source}`;\n}\n\nasync function configureVercelFunction(\n  functionDir: string,\n  config: ResolvedFarmRouteRuntimeConfig,\n  fs: FileSystemPromises,\n): Promise<void> {\n  const configPath = path.join(functionDir, \".vc-config.json\");\n  const current = JSON.parse(await fs.readFile(configPath, \"utf8\"));\n  const next = {\n    ...current,\n    ...(config.regions?.length ? { regions: config.regions } : {}),\n    ...(config.maxDuration ? { maxDuration: config.maxDuration } : {}),\n  };\n  await fs.writeFile(configPath, `${JSON.stringify(next, null, 2)}\\n`);\n}\n\nfunction hasVercelFunctionControls(route: FarmRouteRuntimeManifestEntry): boolean {\n  return Boolean(route.regions?.length || route.maxDuration);\n}\n\nfunction compareRuntimeRoutes(\n  left: FarmRouteRuntimeManifestEntry,\n  right: FarmRouteRuntimeManifestEntry,\n): number {\n  const kindOrder = { page: 0, api: 0, metadata: 0, rule: 1 };\n  const kindDifference = kindOrder[left.kind] - kindOrder[right.kind];\n  if (kindDifference !== 0) return kindDifference;\n\n  const specificityDifference =\n    getPatternSpecificity(right.pattern) - getPatternSpecificity(left.pattern);\n  return specificityDifference || left.pattern.localeCompare(right.pattern);\n}\n\nfunction getPatternSpecificity(pattern: string): number {\n  return normalizePattern(pattern)\n    .split(\"/\")\n    .filter(Boolean)\n    .reduce((score, segment) => {\n      if (segment === \"**\" || segment.startsWith(\"[[...\")) return score + 1;\n      if (segment === \"*\" || segment.startsWith(\"[...\")) return score + 10;\n      if (/^\\[.+\\]$/.test(segment)) return score + 50;\n      return score + 100;\n    }, 0);\n}\n\nfunction normalizePattern(value: string): string {\n  const trimmed = value.trim();\n  const withSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n  return withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n}\n\nfunction normalizeBasePath(value: string): string {\n  const trimmed = value.trim();\n  if (!trimmed || trimmed === \"/\") return \"\";\n  const withSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n  return withSlash.replace(/\\/+$/g, \"\") || \"/\";\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","export const FARM_IMMUTABLE_ASSET_CACHE_CONTROL = \"public, max-age=31536000, immutable\" as const;\n\nexport interface FarmVercelImmutableAssetRoute {\n  src: string;\n  headers: { \"Cache-Control\": typeof FARM_IMMUTABLE_ASSET_CACHE_CONTROL };\n  continue: true;\n  caseSensitive: true;\n}\n\n/**\n * Apply immutable caching only to Farm/Vite filenames carrying Farm's `-h`\n * content-fingerprint marker. Stable entry filenames and HTML are deliberately\n * excluded because they can change between deployments. The fingerprinted\n * client entry lives at the public root — its relative chunk imports pin it\n * there — so root-level farm-client-h files qualify alongside assets/chunks.\n *\n * Hashed client assets are emitted and served at the root even when a\n * basePath is configured — the client build sets no Vite `base` and Nitro\n * mounts the client output at \"/\" — so the route matches root paths\n * unconditionally.\n */\nexport function createFarmVercelImmutableAssetRoute(): FarmVercelImmutableAssetRoute {\n  const fingerprint = \"-h(?:[a-fA-F0-9]{8}|[a-fA-F0-9]{12}|[a-fA-F0-9]{16})\";\n\n  return {\n    src: `^/(?:(?:assets|chunks)/(?:.+/)*[^/]+|farm-client)${fingerprint}\\\\.(?!(?:[hH][tT][mM][lL]?)$)[^/]+$`,\n    headers: {\n      \"Cache-Control\": FARM_IMMUTABLE_ASSET_CACHE_CONTROL,\n    },\n    continue: true,\n    caseSensitive: true,\n  };\n}\n\nexport function isFarmVercelImmutableAssetPath(pathname: string): boolean {\n  return new RegExp(createFarmVercelImmutableAssetRoute().src).test(pathname);\n}\n\nexport interface FarmVercelRoute {\n  handle?: string;\n  src?: string;\n  dest?: string;\n  status?: number;\n  headers?: Record<string, string>;\n  continue?: boolean;\n  caseSensitive?: boolean;\n}\n\n/**\n * Rebuild the Vercel Build Output `routes` array around Farm's serverless\n * function while preserving the preset-generated source routes.\n *\n * Nitro's Vercel builder emits, before the `filesystem` handler, the redirect\n * and header routes declared through `routeRules` (this is how Farm ships its\n * configured `headers()` and per-prerendered-route cache policy on Vercel), then\n * a blanket immutable public-asset route. Farm previously discarded the whole\n * array, which silently dropped those redirect and header routes on Vercel while\n * they kept working on every other target.\n *\n * We keep the redirect/header source routes, replace the preset's blanket\n * immutable asset route (`continue: true`) with Farm's fingerprint-precise one so\n * stable filenames and HTML are not over-cached, and re-point Farm's runtime,\n * API, and catch-all routes at the `__nitro` function this post-processing\n * creates. Routes after the `filesystem` handler (ISR invocations, observability,\n * the preset's own `/__fallback` catch-all) are intentionally not carried over:\n * Farm keeps ISR routes server-handled, and the preset's catch-all targets a\n * function name Farm does not emit.\n */\nexport function buildFarmVercelRoutes(options: {\n  presetRoutes: FarmVercelRoute[];\n  runtimeRoutes: FarmVercelRoute[];\n}): FarmVercelRoute[] {\n  const { presetRoutes, runtimeRoutes } = options;\n  const filesystemIndex = presetRoutes.findIndex((route) => route.handle === \"filesystem\");\n  const sourceRoutes = filesystemIndex >= 0 ? presetRoutes.slice(0, filesystemIndex) : [];\n  // Drop the preset's blanket immutable public-asset routes (the only\n  // pre-filesystem routes marked `continue: true`); Farm supplies its own\n  // precise immutable route below. Everything else here is a redirect or header\n  // route from routeRules and must be preserved.\n  const preservedSourceRoutes = sourceRoutes.filter((route) => route.continue !== true);\n\n  return [\n    ...preservedSourceRoutes,\n    createFarmVercelImmutableAssetRoute(),\n    { handle: \"filesystem\" },\n    ...runtimeRoutes,\n    {\n      src: \"/(.*)\",\n      dest: \"/__nitro\",\n    },\n  ];\n}\n","import type { ResolvedFarmServerConfig } from \"../server-http\";\n\nexport interface FarmNodeServerEntryOptions {\n  nitroEntryFile: string;\n  nodeAdapterModule: string;\n  server: ResolvedFarmServerConfig;\n  websocketAdapterModule: string;\n}\n\n/** Generate the long-running Node adapter entry while retaining Nitro's routing runtime. */\nexport function createFarmNodeServerEntry(options: FarmNodeServerEntryOptions): string {\n  const serverConfig = JSON.stringify(options.server);\n  const nitroEntryImport = `./${options.nitroEntryFile.replace(/^\\.\\//, \"\")}`;\n\n  return `\nimport \"#nitro/virtual/polyfills\";\nimport { NodeRequest, serve } from ${JSON.stringify(options.nodeAdapterModule)};\nimport wsAdapter from ${JSON.stringify(options.websocketAdapterModule)};\nimport { resolveWebsocketHooks, useNitroApp, useNitroHooks } from \"#nitro/runtime/app\";\nimport { useRuntimeConfig } from \"#nitro/runtime/runtime-config\";\nimport { trapUnhandledErrors } from \"#nitro/runtime/error/hooks\";\nimport { setupCloseHooks } from \"#nitro/runtime/shutdown\";\nimport { startScheduleRunner } from \"#nitro/runtime/task\";\nimport { tracingSrvxPlugins } from \"#nitro/virtual/tracing\";\nimport { farmProductionLifecycle } from ${JSON.stringify(nitroEntryImport)};\n\nconst farmServerConfig = ${serverConfig};\nif (!process.env.NITRO_SHUTDOWN_TIMEOUT) {\n  process.env.NITRO_SHUTDOWN_TIMEOUT = String(farmServerConfig.gracefulShutdownTimeout);\n}\nconst shutdownConfig = {\n  disabled: Boolean(process.env.NITRO_SHUTDOWN_DISABLED),\n  signals: (process.env.NITRO_SHUTDOWN_SIGNALS || \"SIGTERM SIGINT\")\n    .split(\" \")\n    .map((signal) => signal.trim())\n    .filter(Boolean),\n  timeout: Number.parseInt(process.env.NITRO_SHUTDOWN_TIMEOUT || \"\", 10) || 30000,\n  forceExit: !process.env.NITRO_SHUTDOWN_NO_FORCE_EXIT,\n};\n\nconst nitroApp = useNitroApp();\nuseNitroHooks().hook(\"close\", async () => {\n  try {\n    await farmProductionLifecycle.close(\"production-server-closed\");\n  } catch (error) {\n    process.exitCode = 1;\n    throw error;\n  }\n});\n\nlet startupSignal;\nlet resolveStartupSignal;\nconst startupSignalPromise = new Promise((resolve) => {\n  resolveStartupSignal = resolve;\n});\nconst startupSignalListeners = new Map();\nif (!shutdownConfig.disabled) {\n  for (const signal of shutdownConfig.signals) {\n    const listener = (receivedSignal) => {\n      if (!startupSignal) {\n        startupSignal = receivedSignal;\n        resolveStartupSignal(receivedSignal);\n      }\n      farmProductionLifecycle.beginDrain(receivedSignal);\n    };\n    startupSignalListeners.set(signal, listener);\n    process.once(signal, listener);\n  }\n}\n\ntry {\n  await Promise.race([\n    Promise.resolve().then(() => farmProductionLifecycle.start()),\n    startupSignalPromise,\n  ]);\n} catch (error) {\n  await farmProductionLifecycle.close(\"production-start-failed\").catch((closeError) => {\n    console.error(\"[Farm] Runtime cleanup after startup failure failed:\", closeError);\n  });\n  throw error;\n} finally {\n  for (const [signal, listener] of startupSignalListeners) {\n    process.removeListener(signal, listener);\n  }\n}\n\nif (startupSignal) {\n  let startupCloseTimer;\n  const startupCloseCompleted = await Promise.race([\n    Promise.resolve()\n      .then(() => farmProductionLifecycle.close(startupSignal))\n      .then(\n        () => true,\n        (error) => {\n          console.error(\"[Farm] Runtime shutdown during startup failed:\", error);\n          process.exitCode = 1;\n          return true;\n        },\n      ),\n    new Promise((resolve) => {\n      startupCloseTimer = setTimeout(() => resolve(false), farmServerConfig.gracefulShutdownTimeout);\n    }),\n  ]);\n  clearTimeout(startupCloseTimer);\n  if (!startupCloseCompleted) {\n    console.warn(\"[Farm] Runtime startup did not settle before shutdown; forcing cleanup\");\n    let forcedCloseTimer;\n    const forcedCloseCompleted = await Promise.race([\n      Promise.resolve()\n        .then(() => farmProductionLifecycle.forceClose(startupSignal))\n        .then(\n          () => true,\n          (error) => {\n            console.error(\"[Farm] Forced runtime shutdown during startup failed:\", error);\n            process.exitCode = 1;\n            return true;\n          },\n        ),\n      new Promise((resolve) => {\n        forcedCloseTimer = setTimeout(\n          () => resolve(false),\n          farmServerConfig.gracefulShutdownTimeout,\n        );\n      }),\n    ]);\n    clearTimeout(forcedCloseTimer);\n    if (!forcedCloseCompleted) {\n      console.error(\"[Farm] Forced runtime shutdown during startup timed out\");\n      process.exitCode = 1;\n    }\n  }\n  process.exit(process.exitCode || 0);\n}\n\nconst cert = process.env.NITRO_SSL_CERT;\nconst key = process.env.NITRO_SSL_KEY;\nconst configuredPort = Number(process.env.NITRO_PORT || process.env.PORT);\nconst port = Number.isFinite(configuredPort) && configuredPort > 0 ? configuredPort : 3000;\nconst host = process.env.NITRO_HOST || process.env.HOST;\nconst socketPath = process.env.NITRO_UNIX_SOCKET;\nconst server = serve({\n  manual: true,\n  silent: true,\n  gracefulShutdown: false,\n  port,\n  hostname: host,\n  node: socketPath ? { path: socketPath } : undefined,\n  tls: cert && key ? { cert, key } : undefined,\n  fetch: nitroApp.fetch,\n  plugins: [...tracingSrvxPlugins],\n});\nconst nodeServer = server.node?.server;\nif (!nodeServer) throw new Error(\"[Farm] Nitro did not create a Node server\");\n\nnodeServer.headersTimeout = farmServerConfig.headersTimeout;\nnodeServer.requestTimeout = farmServerConfig.requestTimeout;\nnodeServer.keepAliveTimeout = farmServerConfig.keepAliveTimeout;\n\nlet isShuttingDown = false;\nnodeServer.on(\"request\", (_request, response) => {\n  response.once(\"finish\", () => {\n    if (isShuttingDown) nodeServer.closeIdleConnections?.();\n  });\n});\n\nif (import.meta._websocket) {\n  const { handleUpgrade } = wsAdapter({ resolve: resolveWebsocketHooks });\n  nodeServer.on(\"upgrade\", (request, socket, head) => {\n    handleUpgrade(\n      request,\n      socket,\n      head,\n      new NodeRequest({ req: request, upgrade: { socket, head } }),\n    );\n  });\n}\n\nsetupCloseHooks(server);\ntrapUnhandledErrors();\n\nlet shutdownPromise;\nasync function shutdown(signal) {\n  isShuttingDown = true;\n  farmProductionLifecycle.beginDrain(signal);\n\n  const gracefulClose = server.close().then(\n    () => true,\n    (error) => {\n      console.error(\"[Farm] Runtime shutdown failed:\", error);\n      process.exitCode = 1;\n      return true;\n    },\n  );\n  nodeServer.closeIdleConnections?.();\n  let gracefulTimer;\n  const gracefullyClosed = await Promise.race([\n    gracefulClose,\n    new Promise((resolve) => {\n      gracefulTimer = setTimeout(() => resolve(false), shutdownConfig.timeout);\n    }),\n  ]);\n  clearTimeout(gracefulTimer);\n\n  if (!gracefullyClosed) {\n    console.warn(\"[Farm] Graceful shutdown timed out; forcing cleanup\");\n    void server.close(true).catch((error) => {\n      console.error(\"[Farm] Forced server shutdown failed:\", error);\n      process.exitCode = 1;\n    });\n\n    let forceTimer;\n    const forceClosed = await Promise.race([\n      Promise.resolve()\n        .then(() => farmProductionLifecycle.forceClose(\"production-server-closed\"))\n        .then(\n          () => true,\n          (error) => {\n            console.error(\"[Farm] Forced runtime shutdown failed:\", error);\n            process.exitCode = 1;\n            return true;\n          },\n        ),\n      new Promise((resolve) => {\n        forceTimer = setTimeout(() => resolve(false), shutdownConfig.timeout);\n      }),\n    ]);\n    clearTimeout(forceTimer);\n    if (!forceClosed) {\n      console.error(\"[Farm] Forced runtime shutdown timed out\");\n      process.exitCode = 1;\n    }\n  }\n\n  if (shutdownConfig.forceExit) process.exit(process.exitCode || 0);\n}\n\nif (!shutdownConfig.disabled) {\n  for (const signal of shutdownConfig.signals) {\n    process.once(signal, (receivedSignal) => {\n      shutdownPromise ||= shutdown(receivedSignal);\n    });\n  }\n}\n\ntry {\n  await server.serve();\n  const protocol = cert && key ? \"https\" : \"http\";\n  const addressInfo = nodeServer.address();\n  if (typeof addressInfo === \"string\") {\n    console.log(\\`Listening on unix socket \\${addressInfo}\\`);\n  } else if (addressInfo) {\n    const configuredBaseURL = useRuntimeConfig().app.baseURL || \"\";\n    const baseURL = configuredBaseURL.endsWith(\"/\")\n      ? configuredBaseURL.slice(0, -1)\n      : configuredBaseURL;\n    const address = addressInfo.family === \"IPv6\"\n      ? \\`[\\${addressInfo.address}]\\`\n      : addressInfo.address;\n    console.log(\\`Listening on \\${protocol}://\\${address}:\\${addressInfo.port}\\${baseURL}\\`);\n  }\n} catch (error) {\n  console.error(error);\n  process.exitCode = 1;\n  await farmProductionLifecycle.close(\"production-listen-error\").catch((closeError) => {\n    console.error(\"[Farm] Runtime cleanup after listen failure failed:\", closeError);\n  });\n  throw error;\n}\n\nif (import.meta._tasks) {\n  startScheduleRunner({ waitUntil: server.waitUntil });\n}\n\nexport default {};\n  `.trim();\n}\n","import type { FarmProductionViteBuilder } from \"./production-vite\";\n\ntype VitePluginLike = {\n  name?: string;\n  transform?: unknown;\n};\n\ntype VitePluginHook = (...args: any[]) => any;\n\n/**\n * Tailwind 4.1 supports Farm's Node baseline, but its Vite plugin resolves\n * against Farm's Vite 5 compatibility dependency. When that plugin runs in\n * Vite 8 it mistakes the active environment for its own Vite environment and\n * calls an API that Vite 5 does not export. Keep its documented Vite 5 hook\n * path while Farm uses the Rolldown production builder.\n */\nexport function adaptTailwindVitePlugin<T>(pluginOption: T, builder: FarmProductionViteBuilder): T {\n  if (builder !== \"rolldown\") return pluginOption;\n  return adaptPluginOption(pluginOption) as T;\n}\n\nfunction adaptPluginOption(pluginOption: unknown): unknown {\n  if (Array.isArray(pluginOption)) return pluginOption.map(adaptPluginOption);\n  if (!pluginOption || typeof pluginOption !== \"object\") return pluginOption;\n\n  const plugin = pluginOption as VitePluginLike;\n  if (!plugin.name?.startsWith(\"@tailwindcss/vite:generate:\")) return pluginOption;\n\n  if (isVitePluginHook(plugin.transform)) {\n    return {\n      ...plugin,\n      transform: withVite5TransformContext(plugin.transform),\n    };\n  }\n\n  if (\n    plugin.transform &&\n    typeof plugin.transform === \"object\" &&\n    \"handler\" in plugin.transform &&\n    isVitePluginHook(plugin.transform.handler)\n  ) {\n    return {\n      ...plugin,\n      transform: {\n        ...plugin.transform,\n        handler: withVite5TransformContext(plugin.transform.handler),\n      },\n    };\n  }\n\n  return pluginOption;\n}\n\nfunction isVitePluginHook(value: unknown): value is VitePluginHook {\n  return typeof value === \"function\";\n}\n\nfunction withVite5TransformContext<T extends (...args: any[]) => any>(handler: T): T {\n  return function (this: object, ...args: Parameters<T>): ReturnType<T> {\n    const context = new Proxy(this, {\n      get(target, property, receiver) {\n        if (property === \"environment\") return undefined;\n        return Reflect.get(target, property, receiver);\n      },\n    });\n    return handler.apply(context, args);\n  } as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,OAAOA,WAAU;AACjB,SAAS,cAAAC,mBAAkB;;;ACR3B,OAAO,UAAU;AASV,IAAM,mCAAmC;AACzC,IAAM,iCAAiC;AAE9C,eAAe,YACb,YACA,gBACA,YACwB;AACxB,QAAM,KAAK,MAAM,OAAO,aAAa;AACrC,MAAI;AACF,UAAM,QAAQ,MAAM,GAAG,SAAS,UAAU;AAC1C,QAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,UAAM,EAAE,WAAW,IAAI,MAAM,OAAO,QAAa;AACjD,UAAM,OAAO,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,CAAC;AACxE,UAAM,OAAO,WAAW,IAAI;AAC5B,UAAM,GAAG,MAAM,gBAAgB,EAAE,WAAW,KAAK,CAAC;AAClD,UAAM,GAAG,UAAU,KAAK,KAAK,gBAAgB,IAAI,GAAG,KAAK;AACzD,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAlBe;AA+Bf,eAAsB,2BAA2B,iBAA0C;AAC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Je;","names":["path","existsSync","path","path","path","path","path","path","path","path","clone","PluginManager","metadata","buildClient","path","PluginManager","existsSync"]}